Automating password reset in salesforce - salesforce

I want to automate the password reset in salesforce for 10 specific users everytime. For doing this I have written a Apex class in salesforce. And I want to schedule this class also.But I am new in Apex coding.
Here is the class that I have written:
public class DataTeam_ResetPassword
{
public DataTeam_ResetPassword()
{
List<id> DteamIDs = new List<id>{'005A0000003ja3x'};
for(Id u : DteamIDs)
{
system.setPassword(u,'qweEfetividade_1');
system.setPassword(u,'werwEfetividade_1');
system.setPassword(u,'wetEfetividade_1');
system.setPassword(u,'dsfEfetividade_1');
system.setPassword(u,'bhcvEfetividade_1');
system.setPassword(u,'dhEfetividade_1');
system.setPassword(u,'fjfjEfetividade_1');
system.setPassword(u,'tyEfetividade_1');
system.setPassword(u,'tweEfetividade_1');
system.setPassword(u,'mmEfetividade_1');
system.setPassword(u,'rwrEfetividade_1');
system.setPassword(u,'jkgkEfetividade_1');
system.setPassword(u,'5y4yEfetividade_1');
system.setPassword(u,'kjEfetividade_1');
system.setPassword(u,'asgaghEfetividade_1');
system.setPassword(u,'Efafwrwrw_1');
}
}
}
can any one help me what next should I need to do?

You may be better server by having a common profile for all the required users and then having a specific password policy for that profile. See Set Session Timeout and Password Policies for Individual Profiles
Create an Apex Scheduler and use System.resetPassword(ID userID, Boolean send_user_email).
global class scheduledPasswordReset implements Schedulable {
global void execute(SchedulableContext SC) {
Boolean sendUserEmail = true;
System.resetPassword('005A0000003ja3x', sendUserEmail);
// Repeat for other User Ids to reset.
}
}
Start with something like:
scheduledPasswordReset m = new scheduledPasswordReset();
String sch = '20 30 8 10 2 ?';
String jobID = system.schedule('Reset Password Job', sch, m);
Alter the expression above to run as required.

Related

Is there a way to convert Apex Select Statement to String

I have all the permission sets updated correctly as I i can hardcode a string 'Test' where the select statement is, but when i put in the select statement, My chat bot immediately closes. Could someone take a quick look? I am trying to test that I can take an email address, search the contact object and return the appDecision (Custom Field)
public with Sharing class GetAdmissionStatus {
public class DecisionOutput {
#InvocableVariable( required=true )
public String aDecision;
}
public class DecisionInput {
#InvocableVariable( required=true )
public String applyEmail;
}
#InvocableMethod(label='Get Admission Status')
public static List < DecisionOutput > GetAdmissionStatus( List < DecisionInput > listDecisionInputs ) {
List < DecisionOutput > objOutputs = new List < DecisionOutput >();
DecisionOutput objOutput = new DecisionOutput();
Set < String > strapplyEmails = new Set < String >();
for ( DecisionInput objDecisionInput : listDecisionInputs )
strapplyEmails.add( objDecisionInput.applyEmail );
objOutput.aDecision = [ SELECT AppDecision__c FROM Contact WHERE Email IN: strapplyEmails LIMIT 1].AppDecision__c;
objOutputs.add( objOutput );
return objOutputs;
}
}
Question is unclear. You have a query in [brackets] and you want to see a text version of it? Try with
String q = Database.getQueryLocator([SELECT Id FROM Account LIMIT 5]).getQuery();
System.debug(q);
If you want to cast query results to string this might help
String x = JSON.serializePretty([SELECT Id FROM Account LIMIT 5]);
// you can do JSON.serialize() too
System.debug(x);
If the bot closes there's high chance some exception is thrown. Try to play with the bot with DeveloperConsole open, see if it throws anything.
And did you give the "bot user" permission to use this apex class, contact object and the fields? Search in https://developer.salesforce.com/docs/atlas.en-us.bot_cookbook.meta/bot_cookbook/bot_cookbook_call_apex_action.htm for "permission set"

I sheduled an apex class to run everyday, but nothing happens. Can somebody help me out?

I wrote this APEX class and sheduled it to run every day.I don't get an error message, but unfortunately the class doesn't do anything... Can anybody help me out?
global class CustomersDateCheck implements Schedulable {
global void execute(SchedulableContext sc) {
List<Customers__c> CustomerList = [SELECT Id FROM Customers__c];
DateCheck(CustomerList);}
public static void DateCheck(Customers__c[] objects){
for(Customers__c obj: objects){
if(obj.DateField > Date.today()){
continue;}
else{obj.FlowUpdateHelper__c = true;}
}
}
}
you write the Schedulable now you need Schedule it.
run this 3 line of code in developer console then check apex jobs
//will run daily at 13:00
CustomersDateCheck m = new CustomersDateCheck();
String sch = '0 0 13 * * ?';
String jobID = system.schedule('Customers Date Check Job', sch, m);
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
The error means you're trying to access something that you didn't include in the query, in this case the Customers__c.DateField__c , you need to either remove the reference to that, or update your query to include that info

How To Understand #TestClass Apex code with List embedded in Map

I am trying to understand this code ,this seems to be a test class,but i am having hard time to understand the code,i know conceptually how List and Map collection works in Sales force,but this seems to be little difficult to understand,
.In brief to me this seems to test a method which browses a list of CollaborationGroupMember.
For that, CollaborationGroup has been created and code tried to add one User.
can some one please take some time to make me understand the below code line by line?
Thanks in advance
#isTest
public class TestGroupFactory {
public static Map<CollaborationGroup, List<CollaborationGroupMember>> groupWithMember() {
CollaborationGroup groupe = new CollaborationGroup(Name = 'Test1', CollaborationType = 'Public');
insert groupe;
groupe = [SELECT Id, Name FROM CollaborationGroup WHERE Name = 'Test1'];
List<User> users = [SELECT Id, Name, Numero_de_plaque__c, SenderEmail
FROM User
WHERE Name = 'User User'];
List<CollaborationGroupMember> cgms = new List<CollaborationGroupMember>();
for (User u : users) {
CollaborationGroupMember cgm = new CollaborationGroupMember();
cgm.CollaborationGroupId = groupe.Id;
cgm.MemberId = u.Id;
cgms.add(cgm);
}
insert cgms;
return new Map<CollaborationGroup, List<CollaborationGroupMember>>{groupe => cgms};
}
}
It is technically a test class, but it does not perform any tests. Its purpose is to create test data for other test classes that contain test methods. The reason it has the #isTest annotation is so that it is only accessible in test context and does not count against the total test coverage of the organization.
The method shown creates a Chatter Group and adds Users to the group if they have the name "User User".
The code below inserts the Chatter Group and then retrieves it so the Id is available. I don't think the retrieval is necessary in this instance, but I'd have to test it.
CollaborationGroup groupe = new CollaborationGroup(Name = 'Test1', CollaborationType = 'Public');
insert groupe;
groupe = [SELECT Id, Name FROM CollaborationGroup WHERE Name = 'Test1'];
The next section retrieves the Users (presumably created in another test class)
List<User> users = [SELECT Id, Name, Numero_de_plaque__c, SenderEmail
FROM User
WHERE Name = 'User User'];
Then, a list of CollaborationGroupMembers is instantiated. A loop begins that iterates over every User. For each user, a new CollaborationGroupMember is instantiated and added to the list.
List<CollaborationGroupMember> cgms = new List<CollaborationGroupMember>();
for (User u : users) {
CollaborationGroupMember cgm = new CollaborationGroupMember();
cgm.CollaborationGroupId = groupe.Id;
cgm.MemberId = u.Id;
cgms.add(cgm);
}
The group members are inserted
insert cgms;
The group and group members are added to a map and returned
return new Map<CollaborationGroup, List<CollaborationGroupMember>>{groupe => cgms};

Test Class in Salesforce for a Trigger

Good day Everybody,
I am attempting to write a test class for a trigger I helped write. The trigger uses a field called trigger_help__c, a formula field derived from adding the opportunity Type and Account ID, and fires before insert if an Opportunity of that type has been created on that account within the last 90 days. Unless the profile is a system admin. Here is my trigger:
trigger leadDuplicatePreventer on opportunity(before insert) {
set<string> settgs = new set<string>();
list<opportunity> opps = [select id,Trigger_Help__c from opportunity WHERE CreatedDate = LAST_N_DAYS:90];
Profile p=[SELECT ID, Name FROM Profile WHERE Id=:userinfo.getProfileId() Limit 1];
for(opportunity opp : opps){
if(opp.Trigger_Help__c != null && p.Name <> 'System Administrator'){
settgs.add(opp.Trigger_Help__c);
}
}
for(opportunity op : trigger.new){
if(settgs.contains(op.Trigger_Help__c)){
op.adderror('An Opportunity of this type already exists on this Account. Please contact a system administrator with questions.');
}
}
}​
I am having trouble writing the test class and I am clueless as always. I have the following written, but I am lost as to what I actually need to be doing:
#isTest
private class TestleadDuplicatePreventer {
#isTest static void TestleadDuplicatePreventerwithOneOpp() {
Account acct = new Account(Name='Test Account');
insert acct;
Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',
StageName='Open Opportunity',
CloseDate=System.today().addMonths(1),
Facility__c='Tacoma WA',
Oppty_Type__c='UCO Service',
AccountID=acct.Id);
insert opp;
Test.startTest();
opp= new Opportunity(Name='Opportunity Test',
StageName='Open Opportunity',
CloseDate=System.today().addMonths(2),
Facility__c='Tacoma WA',
Oppty_Type__c='UCO Service',
Account=[SELECT ID from Account WHERE Account.Name='Test Account']);
try
{
insert opp;
}
catch(Exception duplicate)
{
}
Test.stopTest();
}
}​
Any and all help is appreciated!!
Not sure exactly what your requirements were for your project, you can probably get this done without code doing a rollup sum field that counts the opportunities tied to an account that has the type used in Trigger_Help__c and then put a validation on opportunity that when ISNEW() if Account.Count_Of_Type__c > 0 causes the validation to fire OR on opportunity create a hidden field that is unique that is the concatenation of the account id and the Opportunity type which can be set by workflow or the process builder. Tis would prevent duplicate types from being added for a given account.
But to your original question: In your test I dont see you set the Trigger_Help__c field unless that is set by automation. Also when creating your second opp you dont need to do the query of account you can just use the acct.Id from earlier in the code.
For your catch you need to assert that the e.getMessage() is the message you expect from your add error in the trigger.
You probably also need to do a separate where you runAs(admin_user) where admin_user is a user that you create with the System administrator profile to ensure that you dont get an error when you run as the admin user, along the lines of:
#isTest
private class TestleadDuplicatePreventer {
#isTest static void TestleadDuplicatePreventerwithOneOpp() {
Account acct = new Account(Name='Test Account');
insert acct;
Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',
StageName='Open Opportunity',
CloseDate=System.today().addMonths(1),
Facility__c='Tacoma WA',
Oppty_Type__c='UCO Service',
AccountID=acct.Id);
insert opp;
Test.startTest();
opp= new Opportunity(Name='Opportunity Test',
StageName='Open Opportunity',
CloseDate=System.today().addMonths(2),
Facility__c='Tacoma WA',
Oppty_Type__c='UCO Service',
AccountId=acct.Id);
try
{
insert opp;
}
catch(Exception duplicate)
{
System.assertEquals('An Opportunity of this type already exists on this Account. Please contact a system administrator with questions.', duplicate.getMessage())
}
//this should probably be in a separate test method
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
User u2 = new User(Alias = 'newUser', Email='newuser#testorg.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='newuser#testorg.com');
System.runAs(u2) {
insert opp;
}
Test.stopTest();
}
}​

[RuntimeException: No EntityManager bound to this thread. Try to annotate your action method with #play.db.jpa.Transactional]

this is the problem once i try to save data into db with sql statement insert.
my function is this:
public void save(){
JPA.em().persist(this);
}
and
public static Result registered() {
Form<User> requestform = form(User.class).bindFromRequest();
if(requestform.hasErrors()){
return badRequest("<p>fehlerhafte eingabe!</p>").as("text/html");
} else {
User user = requestform.get();
String fullname = user.fullname;
String email = user.email;
String password = user.password;
String username = user.username;
new User(username, password, fullname, email).save();
}
return redirect(controllers.routes.Application.index());
}
thanks for help
It is just like the debugging message says, you do not have an entity manager bound to your methods because they are not marked as transactions.
#play.db.jpa.Transactional
public static Result registered() {
Also, if you are using EBean, you could just extend Model for your User class, which comes with many handy built in functions for database use, see documentation here: http://www.playframework.org/documentation/2.0.1/JavaEbean

Resources