• EagerToLearn
  • NEWBIE
  • 25 Points
  • Member since 2009

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 21
    Questions
  • 22
    Replies
I need help on dynamically assigning data to a query result so I can do a DML update. I want to use Batch Apex to overcome the 10k governor limit.  So for example, if I have a table that a user can supply a query of their own that I would never know to code for in advance how can I iterate over the results and detect the actual field type so I can determine how to update that field.  Let's say the query is "SELECT Firstname, Lastname, Email FROM Contact".  
My code would need to dynamically, detected that the two fields are string type and one is email type and dynamically, update the fields with data that I will have predefined based on the field type.  So this code could never hard code in FOR LOOP c.Email = 'some value' because I don't know that they would supply EMAIL in their query, I have to detect that it is email type and the code would have to be able to update the field whether it is actually named email or a custom field named myemail__c with 'some value'.
 
 
Does Salesforce even let you get to that level to be truly dynamic in your code base.  I see some rough examples, that don't seem to get me to what I am describing or I am just not understanding it.
Using the following SF link as reference for DX packaging.  How would I put the URL string in on the PostInstallURL parameter if I want to reference a Visualforce page (call it myvfpage) that is part of the package?  In the unmanaged package gui you can select the VF page with point and click.
Its seem that you have to go around the barn every which way I turn with SF LWC!  I am trying to do a simple condition check but I don't want to check true to a boolean value such as below.  I want to check a data records field value to a hard-coded value in the HTML file.

<template if:true={mydata.data}>

I want to check the value of the of the data to a hardcoded value like...

<template for:each={mydata.data} for:item="d">
     <div key={d.Message__c}>
         <div if:m.Message_Style__c = "Success">
             <strong>{m.Message__c}</strong>
         </div>
     </div>
</template>


I tried...

<div if:true={m.Message_Style__c} = "Success">

and

<div if:true={m.Message_Style__c} == "Success">

and other variations with no luck.

Just seem like there is so much lacking capability to easily do conditional markup in LWC.  I am really new to LWC and not much on javascript or HTML so that could be some of my issue! :)

What I want to do is have the data on a record control the color theme.  So if a user picks from the picklist "Info" it will use the slds-theme_info, or if the record has "Success" selected in the picklist then the data is displayed using the slds-theme_sucess.

Thanks for your help.
I been developing an LWC and it works as expected when I push to a scratch org and tested.  Then I created an unlock packaged and installed but only to discover that the picklist in the custom metadata type object can not be edited to add picklist values. It is set to allow subscriber change but that seems to allow change to other properties of the field and not managing values!

Is there way way to override this lockdown?  Thanks in advance for your help.
Hi,
I know that apex batch query locator is capabile of 50 million rows but what is the limit on a query that I peform while inside my batch apex.  Lets say I have to query a table that has over 10K rows and I need to review that data per batch iteration?  Is the limit 50k or what?

Thanks for your support.
I am trying to dynamically iterate through an account list, for example but I do not want to hard code the field names.  
Lets assume I performed a dynamic query before the code below to get just Name and Prospect fields.
This is what I don't want to do...
List<Account> accList = Database.query(queryString);  //this line is fine but below is not dynamic...
for (Account a : accList) {
   htmlBody += '<td>' + a.Name + '</td>';
   htmlBody += '<td>' + a.Type + '</td></tr>';
}
...

This is what I want to do or something like it...
List<Account> accList = Database.query(queryString);  
for (Account a : accList) {
   for (fld f : fieldsInAccList) {
      htmlBody += '<td>' + a.f + '</td>';
   }
   htmlBody += '</tr>'
}

Bottomline, I am trying to dynamically build an html table and I don't want to hard code anything if I can help it as that would require code changes everytime someone added a new field to the account object, for example.  I am using a custom metadata table to hold a string of field names that I pass into a method that does everything dynamically but the above part!

Thanks for any help you can provide.

Hi,
At a high level, I have two different objects (not related) that I want to pass data from each to a customized service using JSON.  I am currently doing that with a single object but now I need to add a second. I have built what I thought could be a good visual example but keep in mind that I am not using account and contact but the user object and custom metadata setting as the two objects but this should give a concept that hopefully you could help me with a code snippet or something from mine below that could get an example done.
 

Could I get this to work where it provides a list of list or something like that and I pass it into the JSON serialized method; as mentioned I do this with a single list of users currently.  Again I just through something below together to give context but it uses accounts and contacts.

Bottomline, I need to pass to JSON serialize two different object records and deserialize them on the service side.  Any help, examples would be appreciated.


public class WrapperMain {
    public static List<AccountWrapper> awList = new List<AccountWrapper>();
    public static List<ContactWrapper> cwList = new List<ContactWrapper>();   
    
    {       
        for (Account a : [SELECT Name FROM Account LIMIT 1]) {
             AccountWrapper aw = new AccountWrapper();
            aw.Name = a.Name;
            awList.add(aw);
        }
        for (Contact c : [SELECT Name FROM Contact LIMIT 1]) {
            ContactWrapper cw = new ContactWrapper();
            cw.Name = c.Name;
            cwList.add(cw);
        }        
        
    }

    private class AccountWrapper {
       public String Name {get; set;}   
    }
    
    private class ContactWrapper {
        public String Name {get; set;}
    }
}

I created an unmanaged package in a sandbox.  I was able to take the link of the unmanaged package that has test.salesforce.com... in it and install that package on two other sandboxes.  However, I tack the /packaging/installPackage.apexp?p0=<id of package> to the end of my domain name path in the URL address bar it starts to load and then I get the following error...

This app can't be installed.
There are problems that prevent this package from being installed.
Mismatching VersionsThe AppExchange Application or component you have selected is not yet available on your instance of salesforce.com. Please check back in a few days to retry the installation. Press the back button of your browser now and bookmark the AppExchange Directory page so that you can find it later.

I uninstalled the previous version that was in the production org thinking that was the issue but after waiting about 20 minutes I still get the error above.

Any ideas what would cause this or what the solution is?

I need to know when the last trigger fires and even better the grand total row count of the records being processed from apex code dynamically.  For example, if I use dataloader to insert 300 records, I know that will be 2 triggers (200 then 100 records).  But when code is processing I need the code to make that termination of 300 records in a variable - then I can do the math to figure out when the last (in this case 2nd trigger) fires.
 

Knowing this allows me to build an email during the last trigger fire, for example.  There are other reasons that this information is usefull as well.

Any ideas?  I tried Trigger.size and trigger.new.size() but they return 200 when there are over two hundred records being processed, for example.

Thanks in advance.

I am having an issue getting a SOQL query to return the proper results when the WHERE clause is using the CreatedDate.  I hear about the UTC/GTM but don't fully understand how to get the proper results.

Today is 7/21 and I have records that show on the standard SF page for Created Date as 7/20/2018 and 7/21/2018; however, when I use in code or the Developer Console I only see CreatedDate values of 7/21/218Tnn:nn:nn.000+0000.
 

If I us the following WHERE clause (...WHERE CreatedDate < 2018-07-21T00:00:00Z) I get no records back but if I change the 21 I do get records back but again they all show as 07/21...

However, when I use the following WHERE clause (WHERE CreatedDate < TODAY) I get records back but they still show as 07/21/2018...

From my code persective I am trying to delete record based on a specific date in the past.and although the requirement is that that specific that it can't be off a bit but this issue is really bothering me that I can't easily delete the records starting on a specific date using a query in apex like below and accurately.

DELETE [ SELECT id  from mytablename__c WHERE CreatedDate < :calculatedDate LIMIT 9999];


Your help is very much appreciated - thank you in advance.

Hi,

ERROR: You have uncommitted work pending. Please commit or rollback before calling out.

I have read many posts regarding this issue but my sistuation is not like them!  This is what I have and I am hoping that there is some kind of work-around; otherwise this entire 3 month effort is crapped!
  1. I have  trigger on the user object
  2. It calls a class with the @FUTURE
  3. It performs a REST callout to ALL our associated sandboxes and deactives the user that was deactivated from the client trigger side (prod), #1 above.
  4. On the service side (sandox(s) I deactivate the user(s) and call a Queueable routine to post a log entry on the sandbox(s)  because otherwise, I get the MIX DML error (that was the work-around for that issue if I don't use Queueable.
  5. The service side sends a response back to the client (caller) with the details of what was written to the log on the sandbox(s).
  6. Using the Queueable feature on the client side I attempt to write to its log table but I get the error message in the subject of this post!
I am now having no way to log activity that the client app successfully deactivated a user in sandbox(s) or failed!!!!

Does anyone have a work-around to such a problem?   Appreciate your support.
I have an AfterUpdate user trigger.  The test class is below but I keep getting the following error at the UPDATE line...
System.DmlException: Update failed. First exception on row 0 with id 00560000001A1zeAAC; first error: INSUFFICIENT_ACCESS_OR_READONLY, Cannot insert a user with this profile: []

I have tried without runAS and with runAs and both give the same error!  I need to create an active user then I need to deactive that user which would fire my trigger that is the business requirement.

Any ideas?  I thought I found and Idea that asks to allow updating user records in a test (ones that are created by the test itself).  Is there a way to resolve this issue? Thanks in advance.

@isTest
public class SM_User_Trigger_Test {
    @testSetup static void createUsers() {
        Profile pf= [Select Id from profile where Name='Standard User'];
        List<User> UserList = new List<User>();
        User user = new User();
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User u = new User(firstname = 'Test1', 
                         lastName = 'Tester', 
                         email = 'test1.tester' + '@somecompany' + orgId + '.org', 
                         Username = 'test1.tester' + '@somecompany' + orgId + '.org', 
                         isActive = true,
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        UserList.add(u);
        insert UserList;        
    }    

    static testMethod void testCase1() {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
         User u1 = 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(u1) {
            User User =  [SELECT id, isActive FROM User LIMIT 1];
            System.debug('User: ' + user);
            User.isActive = false;        
            test.startTest();
            Update User;
            test.stopTest();
        }
    }
}
Hi,

I had this code working but realized that it really wasn't bulkifyed because I was passing in a single username!  I changed the caller to pass a list as shown below.  The bold areas are what i changed from a String to a LIST string.  Once I did that I started getting an invalid URI error.  Your help is apprecaited - thanks.

public class SandboxManagerCallout {
    @future(callout=true)
    public static void DeactivateUser(String NamedCredential, List<String> UserNames) {
        // The line below is only here to save time during testing by reactivating users.  
        // This should always be set to FALSE in PRODUCTION.
        Boolean isActive = true; 
        String EndPoint = 'callout:' + NamedCredential + '/services/apexrest/SandboxManagerAPI/' + UserNames + '/' + isActive;        
        HttpRequest req = new HttpRequest();        
        req.setEndpoint(EndPoint);
        req.setMethod('POST');
        Http http = new Http();
        req.setHeader('Content-Type', 'application/json;charset=UTF-8');
        req.setBody('{"UserNames":UserNames, "isActive":isActive}');
        HTTPResponse res = http.send(req);
        System.debug('---Response---');
        System.debug(res.getBody());
    }
}


this is the code on the REST API side but the error I get doesn't even make it to this code but thought to show in case...

@RestResource(urlMapping='/SandboxManagerAPI/*')
global with sharing class SandboxManagerAPI {  
    static Boolean isSandboxValidated = false;
    static Boolean isOrgSandbox = false;

   @HttpPost
    global static void doDeactivate() { 
        Integer USER_NAME = 2;
        Integer IS_ACTIVE = 3; 
        if(!issandbox()) return;
        System.debug('---DeactivateUser.doDeactivate()---');
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        System.debug('req: ' + req.requestURI);
        List<String> Parms = req.requestURI.split('/');
        String UserName = parms[USER_NAME];
        String isActive = parms[IS_ACTIVE];
        //String userName = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);      
        System.debug('Username Passed In: ' + UserName);
        System.debug('isACtive passwed In: ' + isActive);
        User user = [SELECT Id, Username, isActive 
                     FROM User 
                     WHERE userName .............................
.............................

Hi,
I have the coded class below but when I do the http call out using setMethod('GET') or setMethod('POST') the @HTTPPOST (doDeactivate() method) fires, never the @HTTPGET (UserExists()  method). 
 

What am I doing wrong to cause the HTTPGET to never execute in the class?

CALLOUT IN DEBUGGER:
String UserName = 'username_goes_here';
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Sandbox_Management/services/apexrest/User/' + UserName);
req.setMethod('POST');
//req.setMethod('GET');
Http http = new Http();
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
req.setBody('{"UserName":UserName}');
HTTPResponse res = http.send(req);
System.debug('RETURNED TO CALLER');
System.debug(res.getBody());


CLASS:
@RestResource(urlMapping='/User/*')
global with sharing class DeactivateUser {
    
    @HttpGet
    global static Boolean UserExists() {
        final String METHOD_NAME = 'DeactivateUser.UserExists()';
        System.debug('---DeactivateUser.UserExists()---');
        Boolean ret = false;
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String userName = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        System.debug('Username Passed In: ' + userName);
        List<User> userList = [SELECT Id, UserName, isActive 
                               FROM User 
                               WHERE userName = :userName LIMIT 1];
        if (userList.size() > 0) ret = true;        
        return ret;
    }
    
    @HttpPost
    global static String doDeactivate() {
        final String METHOD_NAME = 'DeactivateUser.doDeactivate()';
        System.debug('---' + METHOD_NAME + '---');
        String retVal = METHOD_NAME + ': Unknown Failure!';
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String userName = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        System.debug('Username Passed In: ' + userName);
        User user = [SELECT Id, Username, isActive 
                     FROM User 
                     WHERE userName = :userName LIMIT 1];
        if (user != null) {
            user.isActive = false;
            Try{        
                update user;
                retVal = METHOD_NAME + ': Successfully deactivated user: ' + user.Username;
                return retVal;
            } catch (System.exception e) {
                //Return an error back to the caller
                retVal = METHOD_NAME + ': Error trying to update user: ' + user.Username;
                return retVal;
            }
        } else {
            //Could not find the record so return a message that 
            //informs the caller that the record was not found
            
        }
        return retVal;
    } 
}

I am struggling to find a basic example using Named Credentials, Auth Provider and Connected app that will use two SF developer orgs.  I want to put the https code in the debug window to update a user record's isActive field to false.  I have the aforementioned setup but the code that I have doesn't seem to work as I am getting a 400 error along with the following error:

18:54:22:098 USER_DEBUG [11]|DEBUG|[{"errorCode":"URL_NOT_RESET","message":"Destination URL not reset. The URL returned from login must be set"}]


TRIED THIS IN DEBUG:

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Sandbox_Management/services/data/v40.0/sobjects/User/0056A000001jCnC?_HttpMethod=PATCH');
req.setMethod('POST');
Http http = new Http();
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
req.setBody('{"isActive":false}');
//req.setBody('{"id" : "0056A000001jCnC", "isActive":false}');
HTTPResponse res = http.send(req);
System.debug('SENT');
System.debug(res.getBody());


Thanks for the help.

I have a named credential and finally have the two SF orgs connected with the connected app feature.  Now I want to do a simple update to a user record with a REST call but I get a 400 error.  I am very new to integration and REST and was hoping for some direction....

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Sandbox_Management/services/data/v40.0/sobjects/User/0056A000001jCnC?_HttpMethod=PATCH');
req.setMethod('POST');
Http http = new Http();
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
req.setBody('{"isActive":false}');
req.setBody('{"id" : "0056A000001jCnC", "isActive":false}');
HTTPResponse res = http.send(req);
System.debug('SENT');
System.debug(res.getBody());


GOT THIS BACK:

18:46:56:053 USER_DEBUG [20]|DEBUG|[{"errorCode":"URL_NOT_RESET","message":"Destination URL not reset. The URL returned from login must be set"}]

Hi,  i see mixed answers all over the web regarding what is required for a SOAP Login authentication.  Some answers are Username and password and Security Token while others are saying Username and Password and Organization Id.

I think I am getting it as username and password are the only thing required and security token is optional depending on network ip settings
For communities it would be username and password and Organization id.

Can someon help me understand what is exactly required?
Hi,
I am having issues with a test class that used to work but after making many changes to the VF and Controller and getting those to work, I started getting the following error "class contructor not defined: [ApexPages.StandardController].<Constructor>() at 14 and then I added the following to the controller: 

    public SandboxRefreshUtilPwdChgController() {

    }  
   
Then I now get the list out of bound error.

THIS IS A PORTION OF THE CONTROLLER:
public with sharing class SandboxRefreshUtilPwdChgController {
    
    //list for holding the wrapped users and Integers to be displayed on the page 
    public List<userWrapper> wrappedObjects = new List<userWrapper>();         
    public List<User> userList;    
    public Map<Id, User> compareMap = new Map<Id, User>();
    
    
    // Constructors 1
    public SandboxRefreshUtilPwdChgController() {

    }  
   
    // Constructor 2
    public SandboxRefreshUtilPwdChgController(ApexPages.StandardController ex) {    
        System.debug('constructor');
        List<User> userList = getUsers();
        Integer i = 0; //integer for tracking the row counter value we want to pass back in the wrapper
        for ( user u : userList ) { //start looping through users
            i++; //increment the integer
            userWrapper wrappedObject = new userWrapper(u, i); //wrap the user with the Integer, which calls the userWrapper class below
            wrappedObjects.add(wrappedObject); //add the wrapper object to our list
        }    
    }    

....
....

AND THIS IS THE TEST CLASS:
@isTest
private class SandboxRefreshUtilPwdChgController_Test {
    @testSetup static void setupTestData() {      
        createUserRecords();
    }
    
    private static testMethod void PasswordChangeSucccesTest() {
        List<User> userList = [SELECT id, Email FROM User WHERE CreatedDate = TODAY];
        System.debug('TEST: userList.size(): ' + userList.size());
        
        Test.startTest();
            PageReference pageRef = Page.SandboxRefreshUtilPwdChg;
            Test.setCurrentPage(pageRef);
            SandboxRefreshUtilPwdChgController con = new SandboxRefreshUtilPwdChgController();            //1st error before change
            con.getWrappedObjects()[0].pwd = 'PwT5Srefresh!';          //current error after adding a blank constructor
            con.UpdatePasswords(); 
            System.assertEquals('Yes', con.getWrappedObjects()[0].successfulChange, 'Password Change failed!');
        Test.stopTest();
    }
    


Appreciate your support
Tom
 
I am trying to write a list controller that will get a list of users showing two fields.  The username and a text field as input on the visualforce page.  When I click the "GO" button I want to call a method where I will use the list of users with the value in the text field to do some further work.  Can someone help me with a block code for this and VF page.  I think I need a wrapper class for the text field but I an't see to make sense from other examples as I don't see any were the text field is not a bind to any field on the user object.
Thanks for any help you can provide to get me started.
...I have not done the multiple choice exam yet.  Is that an issue?  Can I do the trailhead requirements first or at least continue for a while and then take the multiple choice exam or will I have to start all over again after I take the multiple choice exam?
I need help on dynamically assigning data to a query result so I can do a DML update. I want to use Batch Apex to overcome the 10k governor limit.  So for example, if I have a table that a user can supply a query of their own that I would never know to code for in advance how can I iterate over the results and detect the actual field type so I can determine how to update that field.  Let's say the query is "SELECT Firstname, Lastname, Email FROM Contact".  
My code would need to dynamically, detected that the two fields are string type and one is email type and dynamically, update the fields with data that I will have predefined based on the field type.  So this code could never hard code in FOR LOOP c.Email = 'some value' because I don't know that they would supply EMAIL in their query, I have to detect that it is email type and the code would have to be able to update the field whether it is actually named email or a custom field named myemail__c with 'some value'.
 
 
Does Salesforce even let you get to that level to be truly dynamic in your code base.  I see some rough examples, that don't seem to get me to what I am describing or I am just not understanding it.
Using the following SF link as reference for DX packaging.  How would I put the URL string in on the PostInstallURL parameter if I want to reference a Visualforce page (call it myvfpage) that is part of the package?  In the unmanaged package gui you can select the VF page with point and click.
Its seem that you have to go around the barn every which way I turn with SF LWC!  I am trying to do a simple condition check but I don't want to check true to a boolean value such as below.  I want to check a data records field value to a hard-coded value in the HTML file.

<template if:true={mydata.data}>

I want to check the value of the of the data to a hardcoded value like...

<template for:each={mydata.data} for:item="d">
     <div key={d.Message__c}>
         <div if:m.Message_Style__c = "Success">
             <strong>{m.Message__c}</strong>
         </div>
     </div>
</template>


I tried...

<div if:true={m.Message_Style__c} = "Success">

and

<div if:true={m.Message_Style__c} == "Success">

and other variations with no luck.

Just seem like there is so much lacking capability to easily do conditional markup in LWC.  I am really new to LWC and not much on javascript or HTML so that could be some of my issue! :)

What I want to do is have the data on a record control the color theme.  So if a user picks from the picklist "Info" it will use the slds-theme_info, or if the record has "Success" selected in the picklist then the data is displayed using the slds-theme_sucess.

Thanks for your help.
I am trying to dynamically iterate through an account list, for example but I do not want to hard code the field names.  
Lets assume I performed a dynamic query before the code below to get just Name and Prospect fields.
This is what I don't want to do...
List<Account> accList = Database.query(queryString);  //this line is fine but below is not dynamic...
for (Account a : accList) {
   htmlBody += '<td>' + a.Name + '</td>';
   htmlBody += '<td>' + a.Type + '</td></tr>';
}
...

This is what I want to do or something like it...
List<Account> accList = Database.query(queryString);  
for (Account a : accList) {
   for (fld f : fieldsInAccList) {
      htmlBody += '<td>' + a.f + '</td>';
   }
   htmlBody += '</tr>'
}

Bottomline, I am trying to dynamically build an html table and I don't want to hard code anything if I can help it as that would require code changes everytime someone added a new field to the account object, for example.  I am using a custom metadata table to hold a string of field names that I pass into a method that does everything dynamically but the above part!

Thanks for any help you can provide.

Hi,
At a high level, I have two different objects (not related) that I want to pass data from each to a customized service using JSON.  I am currently doing that with a single object but now I need to add a second. I have built what I thought could be a good visual example but keep in mind that I am not using account and contact but the user object and custom metadata setting as the two objects but this should give a concept that hopefully you could help me with a code snippet or something from mine below that could get an example done.
 

Could I get this to work where it provides a list of list or something like that and I pass it into the JSON serialized method; as mentioned I do this with a single list of users currently.  Again I just through something below together to give context but it uses accounts and contacts.

Bottomline, I need to pass to JSON serialize two different object records and deserialize them on the service side.  Any help, examples would be appreciated.


public class WrapperMain {
    public static List<AccountWrapper> awList = new List<AccountWrapper>();
    public static List<ContactWrapper> cwList = new List<ContactWrapper>();   
    
    {       
        for (Account a : [SELECT Name FROM Account LIMIT 1]) {
             AccountWrapper aw = new AccountWrapper();
            aw.Name = a.Name;
            awList.add(aw);
        }
        for (Contact c : [SELECT Name FROM Contact LIMIT 1]) {
            ContactWrapper cw = new ContactWrapper();
            cw.Name = c.Name;
            cwList.add(cw);
        }        
        
    }

    private class AccountWrapper {
       public String Name {get; set;}   
    }
    
    private class ContactWrapper {
        public String Name {get; set;}
    }
}

I created an unmanaged package in a sandbox.  I was able to take the link of the unmanaged package that has test.salesforce.com... in it and install that package on two other sandboxes.  However, I tack the /packaging/installPackage.apexp?p0=<id of package> to the end of my domain name path in the URL address bar it starts to load and then I get the following error...

This app can't be installed.
There are problems that prevent this package from being installed.
Mismatching VersionsThe AppExchange Application or component you have selected is not yet available on your instance of salesforce.com. Please check back in a few days to retry the installation. Press the back button of your browser now and bookmark the AppExchange Directory page so that you can find it later.

I uninstalled the previous version that was in the production org thinking that was the issue but after waiting about 20 minutes I still get the error above.

Any ideas what would cause this or what the solution is?

I need to know when the last trigger fires and even better the grand total row count of the records being processed from apex code dynamically.  For example, if I use dataloader to insert 300 records, I know that will be 2 triggers (200 then 100 records).  But when code is processing I need the code to make that termination of 300 records in a variable - then I can do the math to figure out when the last (in this case 2nd trigger) fires.
 

Knowing this allows me to build an email during the last trigger fire, for example.  There are other reasons that this information is usefull as well.

Any ideas?  I tried Trigger.size and trigger.new.size() but they return 200 when there are over two hundred records being processed, for example.

Thanks in advance.

Hi,

ERROR: You have uncommitted work pending. Please commit or rollback before calling out.

I have read many posts regarding this issue but my sistuation is not like them!  This is what I have and I am hoping that there is some kind of work-around; otherwise this entire 3 month effort is crapped!
  1. I have  trigger on the user object
  2. It calls a class with the @FUTURE
  3. It performs a REST callout to ALL our associated sandboxes and deactives the user that was deactivated from the client trigger side (prod), #1 above.
  4. On the service side (sandox(s) I deactivate the user(s) and call a Queueable routine to post a log entry on the sandbox(s)  because otherwise, I get the MIX DML error (that was the work-around for that issue if I don't use Queueable.
  5. The service side sends a response back to the client (caller) with the details of what was written to the log on the sandbox(s).
  6. Using the Queueable feature on the client side I attempt to write to its log table but I get the error message in the subject of this post!
I am now having no way to log activity that the client app successfully deactivated a user in sandbox(s) or failed!!!!

Does anyone have a work-around to such a problem?   Appreciate your support.
I have an AfterUpdate user trigger.  The test class is below but I keep getting the following error at the UPDATE line...
System.DmlException: Update failed. First exception on row 0 with id 00560000001A1zeAAC; first error: INSUFFICIENT_ACCESS_OR_READONLY, Cannot insert a user with this profile: []

I have tried without runAS and with runAs and both give the same error!  I need to create an active user then I need to deactive that user which would fire my trigger that is the business requirement.

Any ideas?  I thought I found and Idea that asks to allow updating user records in a test (ones that are created by the test itself).  Is there a way to resolve this issue? Thanks in advance.

@isTest
public class SM_User_Trigger_Test {
    @testSetup static void createUsers() {
        Profile pf= [Select Id from profile where Name='Standard User'];
        List<User> UserList = new List<User>();
        User user = new User();
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User u = new User(firstname = 'Test1', 
                         lastName = 'Tester', 
                         email = 'test1.tester' + '@somecompany' + orgId + '.org', 
                         Username = 'test1.tester' + '@somecompany' + orgId + '.org', 
                         isActive = true,
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        UserList.add(u);
        insert UserList;        
    }    

    static testMethod void testCase1() {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
         User u1 = 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(u1) {
            User User =  [SELECT id, isActive FROM User LIMIT 1];
            System.debug('User: ' + user);
            User.isActive = false;        
            test.startTest();
            Update User;
            test.stopTest();
        }
    }
}

Hi,
I have the coded class below but when I do the http call out using setMethod('GET') or setMethod('POST') the @HTTPPOST (doDeactivate() method) fires, never the @HTTPGET (UserExists()  method). 
 

What am I doing wrong to cause the HTTPGET to never execute in the class?

CALLOUT IN DEBUGGER:
String UserName = 'username_goes_here';
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Sandbox_Management/services/apexrest/User/' + UserName);
req.setMethod('POST');
//req.setMethod('GET');
Http http = new Http();
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
req.setBody('{"UserName":UserName}');
HTTPResponse res = http.send(req);
System.debug('RETURNED TO CALLER');
System.debug(res.getBody());


CLASS:
@RestResource(urlMapping='/User/*')
global with sharing class DeactivateUser {
    
    @HttpGet
    global static Boolean UserExists() {
        final String METHOD_NAME = 'DeactivateUser.UserExists()';
        System.debug('---DeactivateUser.UserExists()---');
        Boolean ret = false;
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String userName = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        System.debug('Username Passed In: ' + userName);
        List<User> userList = [SELECT Id, UserName, isActive 
                               FROM User 
                               WHERE userName = :userName LIMIT 1];
        if (userList.size() > 0) ret = true;        
        return ret;
    }
    
    @HttpPost
    global static String doDeactivate() {
        final String METHOD_NAME = 'DeactivateUser.doDeactivate()';
        System.debug('---' + METHOD_NAME + '---');
        String retVal = METHOD_NAME + ': Unknown Failure!';
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String userName = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        System.debug('Username Passed In: ' + userName);
        User user = [SELECT Id, Username, isActive 
                     FROM User 
                     WHERE userName = :userName LIMIT 1];
        if (user != null) {
            user.isActive = false;
            Try{        
                update user;
                retVal = METHOD_NAME + ': Successfully deactivated user: ' + user.Username;
                return retVal;
            } catch (System.exception e) {
                //Return an error back to the caller
                retVal = METHOD_NAME + ': Error trying to update user: ' + user.Username;
                return retVal;
            }
        } else {
            //Could not find the record so return a message that 
            //informs the caller that the record was not found
            
        }
        return retVal;
    } 
}

I am struggling to find a basic example using Named Credentials, Auth Provider and Connected app that will use two SF developer orgs.  I want to put the https code in the debug window to update a user record's isActive field to false.  I have the aforementioned setup but the code that I have doesn't seem to work as I am getting a 400 error along with the following error:

18:54:22:098 USER_DEBUG [11]|DEBUG|[{"errorCode":"URL_NOT_RESET","message":"Destination URL not reset. The URL returned from login must be set"}]


TRIED THIS IN DEBUG:

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Sandbox_Management/services/data/v40.0/sobjects/User/0056A000001jCnC?_HttpMethod=PATCH');
req.setMethod('POST');
Http http = new Http();
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
req.setBody('{"isActive":false}');
//req.setBody('{"id" : "0056A000001jCnC", "isActive":false}');
HTTPResponse res = http.send(req);
System.debug('SENT');
System.debug(res.getBody());


Thanks for the help.

I have a named credential and finally have the two SF orgs connected with the connected app feature.  Now I want to do a simple update to a user record with a REST call but I get a 400 error.  I am very new to integration and REST and was hoping for some direction....

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Sandbox_Management/services/data/v40.0/sobjects/User/0056A000001jCnC?_HttpMethod=PATCH');
req.setMethod('POST');
Http http = new Http();
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
req.setBody('{"isActive":false}');
req.setBody('{"id" : "0056A000001jCnC", "isActive":false}');
HTTPResponse res = http.send(req);
System.debug('SENT');
System.debug(res.getBody());


GOT THIS BACK:

18:46:56:053 USER_DEBUG [20]|DEBUG|[{"errorCode":"URL_NOT_RESET","message":"Destination URL not reset. The URL returned from login must be set"}]

Hi,  i see mixed answers all over the web regarding what is required for a SOAP Login authentication.  Some answers are Username and password and Security Token while others are saying Username and Password and Organization Id.

I think I am getting it as username and password are the only thing required and security token is optional depending on network ip settings
For communities it would be username and password and Organization id.

Can someon help me understand what is exactly required?
We have a large SFDC development shop, with several dozen sandboxes.
There is a lot of churn and management around sandbox creation, deletion, maintenance, user access, etc.
We take every opportunity to create automation around these repetitive tasks.

A real impediment to the automation is the fact that we cannot programmatically get a list of sandboxes.
We have a very real need to retrieve the list of active sandboxes through the API (not via graphical user interface).

Example:  a user leaves the company.  We have 45 active sandboxes.  We need to disable the user in each sandbox.
It was easy to automated the process, except for the fact that we cannot get the list of sandboxes.
We have to maintain this list manually in a TXT/CSV file outside of Salesforce.  
Not fun, especially since even the GUI interface does not give a nice way to copy this data out to text or CSV.
(try to copy / paste off the sandbox page, you get an ugly html table needing extensive formatting in your paste target).