Tag Archives: SFDC

Difference between Remote Action and Action Function in Salesforce

Here are some differences between apex:actionFunction and @RemoteAction.

Remote Action Function:

  • Remote Action is an Apex annotation used to mark a method as being available for javascript remoting.
  • Remote Action can call the apex methods from any apex class.
  • Remote Action allows you to call the method from javascript yourself and retrieve the result as a javascript object for manipulation.
  • Remote Action methods are static and global, hence don’t have access to your current controller variables and methods.
  • Remote Action methods require less bandwidth, and server processing time, because only the data you submit is visible and the view state is not transferred.
  • Remote Action methods have to update the DOM manually using explicit JavaScript.
  • Remote Action methods can return data directly back to the calling JavaScript, but cannot update the page’s view state.

Action Function:

  • Action Function is a Visualforce tag allows you to invoke a controller action from the Visualforce Page asynchronously via AJAX requests.
  • Action Function can call the apex methods only from the class linked to the Visualforce page.
  • Action Function doesn’t let you get retrieve data but you can rerender the page or a specific section of the page to update it with new values from the controller instance.
  • Action Function methods are instance methods, and so can see the entire page state.
    Action Function has to transfer the page view state.
  • Action Function methods automatically update the Visualforce DOM and can refresh part or all of the page, and can provide a standard interface for showing a loading status through apex:actionStatus.
  • Action Function methods can update the page’s view state, but cannot return data directly back to JavaScript (although you can do this with some extra effort using oncomplete).

In general, apex:actionFunction is easier to use and requires less code, while @RemoteAction offers more flexibility. Moreover, @RemoteAction helps in reducing View State size and also provides you near real time transaction.
.

Dynamic Data Creation in Salesforce From Json Data Without Using Wrapper Class

Generally for Json data insertion from external system to Salesforce, we use apex rest class and wrapper class for every object. I had a requirement to insert around 40 SF objects data from the Json data. To accomplish this requirement, I created a dynamic class, where we can insert Json data for N number of objects.

The advantage of this class is don’t need to change anything in class, If our number of object will increase or any field name will change or any field type will change. We need to change only in Custom Settings.

So, here is my article on dynamic data creation in Salesforce from json data without using wrapper class. In this article I’m going to pass Json data of Accounts & Contacts objects.

For external system data I’ve created external Id in both Account & Contact objects.

Account Object External Id Custom Field:
AccountExternalId

Contact Object External Id Custom Field:
ContactExternalId

To save SF object and Json Object information, We need to create a Custom Settings for objects.

Here is the Custom Setting Object (Json Object Mapping):
Json Object Mapping Custom Settings

Custom Setting Object (Json Object Mapping) Fields:
Json Object Mapping Fields

Custom Setting Object (Json Object Mapping) Records For Account & Contact Objects:
Json Object Mapping Records

To save SF field and Json field information, We need to create a Custom Settings for fields.
Here is the Custom Setting Object (JSon Field Mapping):
Json Field Mapping Custom Settings

Custom Setting Object (Json Field Mapping) Fields:
Json Field Mapping Fields

Custom Setting Object (Json Field Mapping) Records For Account & Contact Objects:
Json Field Mapping Records

Sample Json Data of Accounts & Contacts Objects:

{
"Account_List": {
	"Account": [{
		"External_Id": 833993,
		"Account_Name": "John"
	},
	{
		"External_Id": 833994,
		"Account_Name": "Peter"
	}]
},	
"Contact_List": {
    "Contact": [{
		    "External_Id": 100001,
			"Account_External_Id":833993,
			"First_Name":"Biswajeet",
			"Last_Name": "Samal"
		},
		{
			"External_Id": 100002,
			"Account_External_Id":833994,
			"First_Name":"Abhijeet",
			"Last_Name": "Samal"
		}]
	}
}

Dynamic apex rest class:


//URL Mapping
@RestResource(urlMapping='/ApplicationProcess/*')
global with sharing class ApplicationProcess{

    @HttpPost
    global static ApplicationResponseMsg parseApplicationJSON() {

        //Application Response Message
        ApplicationResponseMsg appResponse = new ApplicationResponseMsg();
        
        //Get Custom Settings Field Mapping List
        List<Json_Field_Mapping__c> fieldMappingList = Json_Field_Mapping__c.getall().values();
        
        //Get Custom Settings Object Mapping List
        List<Json_Object_Mapping__c> objectMappingList = Json_Object_Mapping__c.getall().values();
        
        //Sequential Object Mapping List For Data insertion sequence in objects
        List<Json_Object_Mapping__c> sequentialObjectMappingList = new List<Json_Object_Mapping__c>();
        
        //Create Sequential List For Data insertion in objects
        for(Integer i=1; i <= objectMappingList.size(); i++){
            for(Json_Object_Mapping__c jsonObjMapping: objectMappingList){
                if(i == jsonObjMapping.Object_Insertion_Sequence__c){
                    sequentialObjectMappingList.add(jsonObjMapping);
                }
            }
        }
        
        //Savepoint for transaction
        Savepoint sp = Database.setSavepoint();
        try {
        
            RestRequest request = RestContext.request;  
            RestResponse response = RestContext.response;
            String jSONRequestBody = request.requestBody.toString().trim();
            
            //Deserialize the json data
            Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(jSONRequestBody);
            Map<String, Object> formattedResults = new Map<String, Object>();
        
            if(results != null){
                formattedResults = getFormattedJsonDataMap(results);
            }

            //Loop on Sequential Object List
            for (Json_Object_Mapping__c objMap : sequentialObjectMappingList) {
                
                //List For Json Data
                List<Object> JSONDataList = new List<Object>();            
                String jsonObjectListName = (objMap.Json_Object_List_Name__c).toUpperCase();
                Map<String, Object> JSONDataMap = (Map<String, Object>)formattedResults.get(jsonObjectListName);
                Map<String, Object> formattedJSONDataMap = new Map<String, Object>();
                
                if(JSONDataMap  != null){
                    formattedJSONDataMap = getFormattedJsonDataMap(JSONDataMap);
                }
                
                if(formattedJSONDataMap != null){
                    String JSONObjectName = (objMap.Json_Object_Name__c).toUpperCase();
                    JSONDataList = (List<Object>)formattedJSONDataMap.get(JSONObjectName);
                }

                if(JSONDataList != null){
                    if(JSONDataList.Size() > 0){
                    
                        //Get Object wise field map list from custom setting
                        String sfObjectName = (objMap.SF_Object_Name__c).toUpperCase();
                        List<Json_Field_Mapping__c> fieldMapList = getFieldMapJsonSetting(sfObjectName, fieldMappingList);
                
                        //Save data
                        SaveData(JSONDataList, objMap, fieldMapList);
                    }
                }
            }
            appResponse.Status = 'Success';
            appResponse.Message = 'All data are saved successfully';
        }
        catch(Exception e) {
            Database.rollback(sp);
            appResponse.Status = 'Fail';
            appResponse.Message = e.getMessage();
        }
        return appResponse;
    }
    
    //Save Data Method For Save Functionality
    private static void SaveData(List<Object> jsonDataList, Json_Object_Mapping__c objMap, List<Json_Field_Mapping__c> fieldMappingList){
        String objName = objMap.SF_Object_Name__c;
        
        //Make dynamic list of object
        String objListType = 'List<' + objName + '>';
        
        //Cast sobject list to object list
        List<SObject> sobjList = (List<SObject>)Type.forName(objListType).newInstance();
    
        //Main Object External ID field For Upsert
        Schema.SObjectField externalIdField;
        
        for (Object obj : jsonDataList)
        {     
            //Map Json Data
            Map<String, Object> jsonDataMap = (Map<String, Object>)obj;
            
            sObject sObj = Schema.getGlobalDescribe().get(objName).newSObject();

            for (String attributeName : jsonDataMap.keyset())
            {
                for(Integer i=0;i<fieldMappingList.size();i++)
                {
                    Json_Field_Mapping__c fieldMapping = fieldMappingList[i];
                    
                    //Json Data Field Value
                    object jsonValue = jsonDataMap.get(attributeName);
                    
                    if(fieldMapping.Json_Field_Name__c == attributeName){
                    
                        //Save Data For Main Object
                        Boolean isExternalId = fieldMapping.Is_External_Id__c;
                        String sfFieldName = fieldMapping.SF_Field_Name__c;
                        
                        if(!String.isempty(string.valueof(jsonValue)) && !String.isempty(sfFieldName)){
                            
                            //Get Object Description
                            Schema.SObjectType mObjType = Schema.getGlobalDescribe().get(objName);
                            Schema.DescribeSObjectResult ObjDesc = mObjType.getDescribe();
                            
                            //Object Data Mapping
                            sObj = ObjectDataMapping(sObj, jsonValue, objName, fieldMapping);
                            
                            //Check external Id and add the field to external Id variable
                            if(isExternalId){
                                externalIdField = ObjDesc.fields.getMap().get(sfFieldName);
                            }
                        }
                    }
                }
            }
            
            //Add Object List
            if(sObj != null){
                sobjList.add(sObj);
            }
        }
        
        //Upsert Object Data
        if(sobjList != null){
        
            if(sobjList.Size() > 0){
            
                if(objName == 'Account'){
                    Database.Upsert((List<Account>)sobjList, externalIdField, true);
                }
                else if(objName == 'Contact'){
                    Database.Upsert((List<Contact>) sobjList, externalIdField, true);
                }
            }
        }
    }

    //Object Data Mapping
    private static sObject ObjectDataMapping(sObject sObj, object jsonValue, String objName, Json_Field_Mapping__c fieldMapping){

		//Get Field Description
		Schema.SObjectType ObjType = Schema.getGlobalDescribe().get(objName);
		Schema.DescribeSObjectResult ObjDesc = ObjType.getDescribe();
		Schema.DescribeFieldResult fieldDesc = ObjDesc.fields.getMap().get(fieldMapping.SF_Field_Name__c).getDescribe();
			
        //Check Relationship (Lookup or Master Details)
        if(fieldMapping.Is_Relationship__c){

            //Lookup Field Mapping
            sObject sObjLookup = Schema.getGlobalDescribe().get(fieldMapping.Relationship_Object_Name__c).newSObject();
            sObjLookup.put(fieldMapping.Relationship_SF_Field_Name__c, String.valueof(jsonValue));
            sObj.putSObject(fieldDesc.getRelationshipName(), sObjLookup);
        }
        else{
			/*
			//Here You Can check the field type
			if(fieldDesc.getType() == Schema.DisplayType.DATETIME){
				//Do Something
            }
            else if(fieldDesc.getType() == Schema.DisplayType.DATE){
				//Do Something
            }
            else if(fieldDesc.getType() == Schema.DisplayType.INTEGER){
				//Do Something
            }
			*/
            sObj.put(fieldMapping.SF_Field_Name__c,String.valueof(jsonValue));
        }
        return sObj;
    }

    //Get Field Map Json Setting
    private static List<Json_Field_Mapping__c> getFieldMapJsonSetting(string objName, List<Json_Field_Mapping__c> fieldMapJsonList){
        List<Json_Field_Mapping__c> objList = new List<Json_Field_Mapping__c>();
        for(Json_Field_Mapping__c fieldMap:fieldMapJsonList){
            if(fieldMap.SF_Object_Name__c == objName){
                objList.add(fieldMap);
            }
        }
        return objList;
    }
    
    //Get Formatted Json Data Map
    private static Map<String, Object> getFormattedJsonDataMap(Map<String, Object> results){
        Map<String, Object> formattedResult = new Map<String, Object>();
        for(String jsonObjectName: results.keySet()){
            Object jsonData = results.get(jsonObjectName);
            formattedResult.put(jsonObjectName.toUpperCase(), jsonData);
        }
        return formattedResult;
    }
    
    //Inner Class For Application Response Message
    global class ApplicationResponseMsg {
        global String Status ;
        global String message;
    }
}

To test the rest class, here is the snapshot to call the apex rest class from Workbench Rest Explorer.
WorkBench Apex Rest Execute

After successfully execute the rest class with Accounts & Contacts Json data.

Created Account Records:
Account Records

Created Contact Records:
Contact Records

Note: This is the sample class. For better performance and to accomplish your requirement you can modify this class.

How to redirect to the same VF page from the Constructor with parameters in Salesforce?

Sample Code:

Apex Class:

public with sharing class SampleClass{

    public SampleClass(){
    
    }
    public PageReference doRedirect(){
        String param = ApexPages.currentPage().getParameters().get('UserId');
        if(param == null || param == ''){
            String userId = UserInfo.getUserId();
            PageReference pageRef = new PageReference('/apex/TestPage1');
            pageRef.getParameters().put('UserId',userId);
            pageRef.setRedirect(true);
            return pageRef;
        }
        else{
            return null;
        }
    }
}

VF Page:

<apex:page controller="SampleClass" action="{!doRedirect}">
	<h1>Congratulations</h1>
	This is your new Page
</apex:page>

How to redirect to a different VF page from the constructor with parameters in Salesforce?

Sample Code:

Apex Class:

public with sharing class SampleClass{

    public SampleClass(){
    
    }
    public PageReference doRedirect(){
        String userId = UserInfo.getUserId();
        PageReference pageRef = new PageReference('/apex/TestPage2');
        pageRef.getParameters().put('UserId',userId);
        pageRef.setRedirect(true);
        return pageRef;
    }
}

VF Page:

<apex:page controller="SampleClass" action="{!doRedirect}">
	<h1>Congratulations</h1>
	This is your new Page
</apex:page>

Salesforce SSO SAML JIT Handler

For regular standard User creation SAML JIT Handler:

//This class provides logic for inbound just-in-time provisioning of single sign-on users in your Salesforce organization.
global class SSOUserHandler implements Auth.SamlJitHandler {

    //JIT Handler Exception
    private class JitException extends Exception {}

    //Handle User
    private void handleUser(boolean create, User u, Map < String, String > attributes, String federationIdentifier, boolean isStandard) {

        if (create && attributes.containsKey('User.Username')) {
            u.Username = attributes.get('User.Username');
        }
        if (create) {
            if (attributes.containsKey('User.FederationIdentifier')) {
                u.FederationIdentifier = attributes.get('User.FederationIdentifier');
            } else {
                u.FederationIdentifier = federationIdentifier;
            }
        }
        if (attributes.containsKey('User.ProfileId')) {
            String profileId = attributes.get('User.ProfileId');
            Profile p = [SELECT Id FROM Profile WHERE Id =: profileId];
            u.ProfileId = p.Id;
        }
        if (attributes.containsKey('User.UserRoleId')) {
            String userRole = attributes.get('User.UserRoleId');
            UserRole r = [SELECT Id FROM UserRole WHERE Id =: userRole];
            u.UserRoleId = r.Id;
        }
        if (attributes.containsKey('User.Phone')) {
            u.Phone = attributes.get('User.Phone');
        }
        if (attributes.containsKey('User.Email')) {
            u.Email = attributes.get('User.Email');
        }
        if (attributes.containsKey('User.FirstName')) {
            u.FirstName = attributes.get('User.FirstName');
        }
        if (attributes.containsKey('FirstName')) {
            u.FirstName = attributes.get('FirstName');
        }
        if (attributes.containsKey('User.LastName')) {
            u.LastName = attributes.get('User.LastName');
        }
        if (attributes.containsKey('User.Title')) {
            u.Title = attributes.get('User.Title');
        }
        if (attributes.containsKey('User.CompanyName')) {
            u.CompanyName = attributes.get('User.CompanyName');
        }
        if (attributes.containsKey('User.AboutMe')) {
            u.AboutMe = attributes.get('User.AboutMe');
        }
        if (attributes.containsKey('User.Street')) {
            u.Street = attributes.get('User.Street');
        }
        if (attributes.containsKey('User.State')) {
            u.State = attributes.get('User.State');
        }
        if (attributes.containsKey('User.City')) {
            u.City = attributes.get('User.City');
        }
        if (attributes.containsKey('User.Zip')) {
            u.PostalCode = attributes.get('User.Zip');
        }
        if (attributes.containsKey('User.Country')) {
            u.Country = attributes.get('User.Country');
        }
        if (attributes.containsKey('User.CallCenter')) {
            u.CallCenterId = attributes.get('User.CallCenter');
        }
        if (attributes.containsKey('User.Manager')) {
            u.ManagerId = attributes.get('User.Manager');
        }
        if (attributes.containsKey('User.MobilePhone')) {
            u.MobilePhone = attributes.get('User.MobilePhone');
        }
        if (attributes.containsKey('User.DelegatedApproverId')) {
            u.DelegatedApproverId = attributes.get('User.DelegatedApproverId');
        }
        if (attributes.containsKey('User.Department')) {
            u.Department = attributes.get('User.Department');
        }
        if (attributes.containsKey('User.Division')) {
            u.Division = attributes.get('User.Division');
        }
        if (attributes.containsKey('User.EmployeeNumber')) {
            u.EmployeeNumber = attributes.get('User.EmployeeNumber');
        }
        if (attributes.containsKey('User.Extension')) {
            u.Extension = attributes.get('User.Extension');
        }
        if (attributes.containsKey('User.Fax')) {
            u.Fax = attributes.get('User.Fax');
        }
        if (attributes.containsKey('User.CommunityNickname')) {
            u.CommunityNickname = attributes.get('User.CommunityNickname');
        }
        if (attributes.containsKey('User.IsActive')) {
            String IsActiveVal = attributes.get('User.IsActive');
            u.IsActive = '1'.equals(IsActiveVal) || Boolean.valueOf(IsActiveVal);
        }
        if (attributes.containsKey('User.ReceivesAdminInfoEmails')) {
            String ReceivesAdminInfoEmailsVal = attributes.get('User.ReceivesAdminInfoEmails');
            u.ReceivesAdminInfoEmails = '1'.equals(ReceivesAdminInfoEmailsVal) || Boolean.valueOf(ReceivesAdminInfoEmailsVal);
        }
        if (attributes.containsKey('User.ReceivesInfoEmails')) {
            String ReceivesInfoEmailsVal = attributes.get('User.ReceivesInfoEmails');
            u.ReceivesInfoEmails = '1'.equals(ReceivesInfoEmailsVal) || Boolean.valueOf(ReceivesInfoEmailsVal);
        }
        if (attributes.containsKey('User.ForecastEnabled')) {
            String ForecastEnabledVal = attributes.get('User.ForecastEnabled');
            u.ForecastEnabled = '1'.equals(ForecastEnabledVal) || Boolean.valueOf(ForecastEnabledVal);
        }
        String uid = UserInfo.getUserId();
        User currentUser = [SELECT LocaleSidKey, LanguageLocaleKey, TimeZoneSidKey, EmailEncodingKey FROM User WHERE Id =: uid];
        if (attributes.containsKey('User.LocaleSidKey')) {
            u.LocaleSidKey = attributes.get('User.LocaleSidKey');
        } else if (create) {
            u.LocaleSidKey = currentUser.LocaleSidKey;
        }
        if (attributes.containsKey('User.LanguageLocaleKey')) {
            u.LanguageLocaleKey = attributes.get('User.LanguageLocaleKey');
        } else if (create) {
            u.LanguageLocaleKey = currentUser.LanguageLocaleKey;
        }
        if (attributes.containsKey('User.Alias')) {
            u.Alias = attributes.get('User.Alias');
        } else if (create) {
            String alias = '';
            if (u.FirstName == null) {
                alias = u.LastName;
            } else {
                alias = u.FirstName.charAt(0) + u.LastName;
            }
            if (alias.length() > 5) {
                alias = alias.substring(0, 5);
            }
            u.Alias = alias;
        }
        if (attributes.containsKey('User.TimeZoneSidKey')) {
            u.TimeZoneSidKey = attributes.get('User.TimeZoneSidKey');
        } else if (create) {
            u.TimeZoneSidKey = currentUser.TimeZoneSidKey;
        }
        if (attributes.containsKey('User.EmailEncodingKey')) {
            u.EmailEncodingKey = attributes.get('User.EmailEncodingKey');
        } else if (create) {
            u.EmailEncodingKey = currentUser.EmailEncodingKey;
        }

        if (!create) {
            update(u);
        } else {
            Insert u;
        }
    }

    //Handle JIT
    private void handleJit(boolean create, User u, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map < String, String > attributes, String assertion) {
        handleUser(create, u, attributes, federationIdentifier);
    }

    //For New User
    global User createUser(Id samlSsoProviderId, Id communityId, Id portalId,
        String federationIdentifier, Map < String, String > attributes, String assertion) {
        User u = new User();
        handleJit(true, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
        return u;
    }

    //For Existing User
    global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId,
        String federationIdentifier, Map < String, String > attributes, String assertion) {
        User u = [SELECT Id, FirstName, ContactId FROM User WHERE Id =: userId];
        handleJit(false, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
    }
}

For Community User, Account and Contact Creation SAML JIT Handler:

//This class provides logic for inbound just-in-time provisioning of single sign-on users in your Salesforce organization.
global class SSOUserHandler implements Auth.SamlJitHandler {

    //JIT Handler Exception
    private class JitException extends Exception {}

    //Handle User
    private void handleUser(boolean create, User u, Map < String, String > attributes, String federationIdentifier, boolean isStandard) {

        if (create && attributes.containsKey('User.Username')) {
            u.Username = attributes.get('User.Username');
        }
        if (create) {
            if (attributes.containsKey('User.FederationIdentifier')) {
                u.FederationIdentifier = attributes.get('User.FederationIdentifier');
            } else {
                u.FederationIdentifier = federationIdentifier;
            }
        }
        if (attributes.containsKey('User.ProfileId')) {
            String profileId = attributes.get('User.ProfileId');
            Profile p = [SELECT Id FROM Profile WHERE Id =: profileId];
            u.ProfileId = p.Id;
        }
        if (attributes.containsKey('User.UserRoleId')) {
            String userRole = attributes.get('User.UserRoleId');
            UserRole r = [SELECT Id FROM UserRole WHERE Id =: userRole];
            u.UserRoleId = r.Id;
        }
        if (attributes.containsKey('User.Phone')) {
            u.Phone = attributes.get('User.Phone');
        }
        if (attributes.containsKey('User.Email')) {
            u.Email = attributes.get('User.Email');
        }
        if (attributes.containsKey('User.FirstName')) {
            u.FirstName = attributes.get('User.FirstName');
        }
        if (attributes.containsKey('FirstName')) {
            u.FirstName = attributes.get('FirstName');
        }
        if (attributes.containsKey('User.LastName')) {
            u.LastName = attributes.get('User.LastName');
        }
        if (attributes.containsKey('User.Title')) {
            u.Title = attributes.get('User.Title');
        }
        if (attributes.containsKey('User.CompanyName')) {
            u.CompanyName = attributes.get('User.CompanyName');
        }
        if (attributes.containsKey('User.AboutMe')) {
            u.AboutMe = attributes.get('User.AboutMe');
        }
        if (attributes.containsKey('User.Street')) {
            u.Street = attributes.get('User.Street');
        }
        if (attributes.containsKey('User.State')) {
            u.State = attributes.get('User.State');
        }
        if (attributes.containsKey('User.City')) {
            u.City = attributes.get('User.City');
        }
        if (attributes.containsKey('User.Zip')) {
            u.PostalCode = attributes.get('User.Zip');
        }
        if (attributes.containsKey('User.Country')) {
            u.Country = attributes.get('User.Country');
        }
        if (attributes.containsKey('User.CallCenter')) {
            u.CallCenterId = attributes.get('User.CallCenter');
        }
        if (attributes.containsKey('User.Manager')) {
            u.ManagerId = attributes.get('User.Manager');
        }
        if (attributes.containsKey('User.MobilePhone')) {
            u.MobilePhone = attributes.get('User.MobilePhone');
        }
        if (attributes.containsKey('User.DelegatedApproverId')) {
            u.DelegatedApproverId = attributes.get('User.DelegatedApproverId');
        }
        if (attributes.containsKey('User.Department')) {
            u.Department = attributes.get('User.Department');
        }
        if (attributes.containsKey('User.Division')) {
            u.Division = attributes.get('User.Division');
        }
        if (attributes.containsKey('User.EmployeeNumber')) {
            u.EmployeeNumber = attributes.get('User.EmployeeNumber');
        }
        if (attributes.containsKey('User.Extension')) {
            u.Extension = attributes.get('User.Extension');
        }
        if (attributes.containsKey('User.Fax')) {
            u.Fax = attributes.get('User.Fax');
        }
        if (attributes.containsKey('User.CommunityNickname')) {
            u.CommunityNickname = attributes.get('User.CommunityNickname');
        }
        if (attributes.containsKey('User.IsActive')) {
            String IsActiveVal = attributes.get('User.IsActive');
            u.IsActive = '1'.equals(IsActiveVal) || Boolean.valueOf(IsActiveVal);
        }
        if (attributes.containsKey('User.ReceivesAdminInfoEmails')) {
            String ReceivesAdminInfoEmailsVal = attributes.get('User.ReceivesAdminInfoEmails');
            u.ReceivesAdminInfoEmails = '1'.equals(ReceivesAdminInfoEmailsVal) || Boolean.valueOf(ReceivesAdminInfoEmailsVal);
        }
        if (attributes.containsKey('User.ReceivesInfoEmails')) {
            String ReceivesInfoEmailsVal = attributes.get('User.ReceivesInfoEmails');
            u.ReceivesInfoEmails = '1'.equals(ReceivesInfoEmailsVal) || Boolean.valueOf(ReceivesInfoEmailsVal);
        }
        if (attributes.containsKey('User.ForecastEnabled')) {
            String ForecastEnabledVal = attributes.get('User.ForecastEnabled');
            u.ForecastEnabled = '1'.equals(ForecastEnabledVal) || Boolean.valueOf(ForecastEnabledVal);
        }
        String uid = UserInfo.getUserId();
        User currentUser = [SELECT LocaleSidKey, LanguageLocaleKey, TimeZoneSidKey, EmailEncodingKey FROM User WHERE Id =: uid];
        if (attributes.containsKey('User.LocaleSidKey')) {
            u.LocaleSidKey = attributes.get('User.LocaleSidKey');
        } else if (create) {
            u.LocaleSidKey = currentUser.LocaleSidKey;
        }
        if (attributes.containsKey('User.LanguageLocaleKey')) {
            u.LanguageLocaleKey = attributes.get('User.LanguageLocaleKey');
        } else if (create) {
            u.LanguageLocaleKey = currentUser.LanguageLocaleKey;
        }
        if (attributes.containsKey('User.Alias')) {
            u.Alias = attributes.get('User.Alias');
        } else if (create) {
            String alias = '';
            if (u.FirstName == null) {
                alias = u.LastName;
            } else {
                alias = u.FirstName.charAt(0) + u.LastName;
            }
            if (alias.length() > 5) {
                alias = alias.substring(0, 5);
            }
            u.Alias = alias;
        }
        if (attributes.containsKey('User.TimeZoneSidKey')) {
            u.TimeZoneSidKey = attributes.get('User.TimeZoneSidKey');
        } else if (create) {
            u.TimeZoneSidKey = currentUser.TimeZoneSidKey;
        }
        if (attributes.containsKey('User.EmailEncodingKey')) {
            u.EmailEncodingKey = attributes.get('User.EmailEncodingKey');
        } else if (create) {
            u.EmailEncodingKey = currentUser.EmailEncodingKey;
        }

        if (!create) {
            update(u);
        } else {
            Insert u;
        }
    }

    //Handle Contact
    private void handleContact(boolean create, String accountId, User u, Map < String, String > attributes) {

        Contact c;
        boolean newContact = false;

        List < Contact > lstContact = new List < Contact > ();
        Set < String > setEmailIds = new Set < String > ();
        Map < String, Contact > mapContactDetails = new Map < String, Contact > ();
        String communityID = '';
        String invitationId = '';
        String firstName = '';

        lstContact = [SELECT ID, Name, FirstName, Email, Community_Id__c, InvitaionId__c FROM Contact WHERE Community_Id__c != null AND InvitaionId__c != null];

        for (Contact cn: lstContact) {
            setEmailIds.add(cn.Email);
            mapContactDetails.put(cn.Email, cn);
        }

        if (setEmailIds.contains(attributes.get('User.Email'))) {
            communityID = mapContactDetails.get(attributes.get('User.Email')).Community_Id__c;
            invitationId = mapContactDetails.get(attributes.get('User.Email')).InvitaionId__c;
            firstName = mapContactDetails.get(attributes.get('User.Email')).FirstName;
        }

        if (create) {
            if (attributes.containsKey('User.Contact')) {
                String contact = attributes.get('User.Contact');
                c = [SELECT Id, AccountId FROM Contact WHERE Id =: contact];
                u.ContactId = contact;
            } else {
                c = new Contact();
                newContact = true;
            }
        } else {
            if (attributes.containsKey('User.Contact')) {
                String contact = attributes.get('User.Contact');
                c = [SELECT Id, AccountId FROM Contact WHERE Id =: contact];
                if (u.ContactId != c.Id) {
                    throw new JitException('Cannot change User.ContactId');
                }
            } else {
                String contact = u.ContactId;
                c = [SELECT Id, AccountId FROM Contact WHERE Id =: contact];
            }
        }
        if (!newContact && c.AccountId != accountId) {
            throw new JitException('Mismatched account: ' + c.AccountId + ', ' + accountId);
        }

        if (String.isNotBlank(communityID)) {
            c.Community_Id__c = communityID;
            c.IsAddedInPublicGroup__c = true;
        }

        if (String.isNotBlank(invitationId)) {
            c.InvitaionId__c = invitationId;
        }

        if (attributes.containsKey('Contact.Email')) {
            c.Email = attributes.get('Contact.Email');
        }

        if (attributes.containsKey('FirstName')) {
            c.FirstName = attributes.get('FirstName');
        } else if (String.isNotBlank(firstName)) {
            c.FirstName = firstName;
        }
        if (attributes.containsKey('Contact.LastName')) {
            c.LastName = attributes.get('Contact.LastName');
        }
        if (attributes.containsKey('Contact.Phone')) {
            c.Phone = attributes.get('Contact.Phone');
        }
        if (attributes.containsKey('Contact.MailingStreet')) {
            c.MailingStreet = attributes.get('Contact.MailingStreet');
        }
        if (attributes.containsKey('Contact.MailingCity')) {
            c.MailingCity = attributes.get('Contact.MailingCity');
        }
        if (attributes.containsKey('Contact.MailingState')) {
            c.MailingState = attributes.get('Contact.MailingState');
        }
        if (attributes.containsKey('Contact.MailingCountry')) {
            c.MailingCountry = attributes.get('Contact.MailingCountry');
        }
        if (attributes.containsKey('Contact.MailingPostalCode')) {
            c.MailingPostalCode = attributes.get('Contact.MailingPostalCode');
        }
        if (attributes.containsKey('Contact.OtherStreet')) {
            c.OtherStreet = attributes.get('Contact.OtherStreet');
        }
        if (attributes.containsKey('Contact.OtherCity')) {
            c.OtherCity = attributes.get('Contact.OtherCity');
        }
        if (attributes.containsKey('Contact.OtherState')) {
            c.OtherState = attributes.get('Contact.OtherState');
        }
        if (attributes.containsKey('Contact.OtherCountry')) {
            c.OtherCountry = attributes.get('Contact.OtherCountry');
        }
        if (attributes.containsKey('Contact.OtherPostalCode')) {
            c.OtherPostalCode = attributes.get('Contact.OtherPostalCode');
        }
        if (attributes.containsKey('Contact.AssistantPhone')) {
            c.AssistantPhone = attributes.get('Contact.AssistantPhone');
        }
        if (attributes.containsKey('Contact.Department')) {
            c.Department = attributes.get('Contact.Department');
        }
        if (attributes.containsKey('Contact.Description')) {
            c.Description = attributes.get('Contact.Description');
        }
        if (attributes.containsKey('Contact.Fax')) {
            c.Fax = attributes.get('Contact.Fax');
        }
        if (attributes.containsKey('Contact.HomePhone')) {
            c.HomePhone = attributes.get('Contact.HomePhone');
        }
        if (attributes.containsKey('Contact.MobilePhone')) {
            c.MobilePhone = attributes.get('Contact.MobilePhone');
        }
        if (attributes.containsKey('Contact.OtherPhone')) {
            c.OtherPhone = attributes.get('Contact.OtherPhone');
        }
        if (attributes.containsKey('Contact.Title')) {
            c.Title = attributes.get('Contact.Title');
        }
        if (attributes.containsKey('Contact.Salutation')) {
            c.Salutation = attributes.get('Contact.Salutation');
        }
        if (attributes.containsKey('Contact.LeadSource')) {
            c.LeadSource = attributes.get('Contact.LeadSource');
        }
        if (attributes.containsKey('Contact.DoNotCall')) {
            String DoNotCallVal = attributes.get('Contact.DoNotCall');
            c.DoNotCall = '1'.equals(DoNotCallVal) || Boolean.valueOf(DoNotCallVal);
        }
        if (attributes.containsKey('Contact.HasOptedOutOfEmail')) {
            String HasOptedOutOfEmailVal = attributes.get('Contact.HasOptedOutOfEmail');
            c.HasOptedOutOfEmail = '1'.equals(HasOptedOutOfEmailVal) || Boolean.valueOf(HasOptedOutOfEmailVal);
        }
        if (attributes.containsKey('Contact.HasOptedOutOfFax')) {
            String HasOptedOutOfFaxVal = attributes.get('Contact.HasOptedOutOfFax');
            c.HasOptedOutOfFax = '1'.equals(HasOptedOutOfFaxVal) || Boolean.valueOf(HasOptedOutOfFaxVal);
        }
        if (attributes.containsKey('Contact.Owner')) {
            c.OwnerId = attributes.get('Contact.Owner');
        }
        if (attributes.containsKey('Contact.AssistantName')) {
            c.AssistantName = attributes.get('Contact.AssistantName');
        }
        if (attributes.containsKey('Contact.Birthdate')) {
            c.Birthdate = Date.valueOf(attributes.get('Contact.Birthdate'));
        }
        if (newContact) {
            c.AccountId = accountId;
            insert(c);
            u.ContactId = c.Id;
        } else {
            update(c);
        }

        if (setEmailIds.contains(attributes.get('User.Email'))) {
            delete mapContactDetails.get(attributes.get('User.Email'));
        }
    }

    //Handle Account
    private String handleAccount(boolean create, User u, Map < String, String > attributes) {

        Account a;
        boolean newAccount = false;
        if (create) {

            List < Contact > lstContact = new List < Contact > ();
            Set < String > setEmailIds = new Set < String > ();
            Map < String, Contact > mapContactDetails = new Map < String, Contact > ();
            String communityID = '';

            lstContact = [SELECT ID, Name, Email, Community_Id__c, AccountId FROM Contact WHERE Community_Id__c != null];

            for (Contact cn: lstContact) {
                setEmailIds.add(cn.Email);
                mapContactDetails.put(cn.Email, cn);
            }

            if (setEmailIds.contains(attributes.get('User.Email')) && mapContactDetails.get(attributes.get('User.Email')).AccountId != null) {

                a = [SELECT Id FROM Account WHERE Id =: mapContactDetails.get(attributes.get('User.Email')).AccountId];
            } else if (attributes.containsKey('Contact.Account')) {
                String account = attributes.get('Contact.Account');
                a = [SELECT Id FROM Account WHERE Id =: account];
            } else {
                if (attributes.containsKey('User.Contact')) {
                    String contact = attributes.get('User.Contact');
                    Contact c = [SELECT AccountId FROM Contact WHERE Id =: contact];
                    String account = c.AccountId;
                    a = [SELECT Id FROM Account WHERE Id =: account];
                } else {
                    a = new Account();
                    newAccount = true;
                }
            }
        } else {
            if (attributes.containsKey('User.Account')) {
                String account = attributes.get('User.Account');
                a = [SELECT Id FROM Account WHERE Id =: account];
            } else {
                if (attributes.containsKey('User.Contact')) {
                    String contact = attributes.get('User.Contact');
                    Contact c = [SELECT Id, AccountId FROM Contact WHERE Id =: contact];
                    if (u.ContactId != c.Id) {
                        throw new JitException('Cannot change User.ContactId');
                    }
                    String account = c.AccountId;
                    a = [SELECT Id FROM Account WHERE Id =: account];
                } else {
                    throw new JitException('Could not find account');
                }
            }
        }
        if (attributes.containsKey('Account.Name')) {
            a.Name = attributes.get('Account.Name');
        }
        if (attributes.containsKey('Account.AccountNumber')) {
            a.AccountNumber = attributes.get('Account.AccountNumber');
        }
        if (attributes.containsKey('Account.Owner')) {
            a.OwnerId = attributes.get('Account.Owner');
        }
        if (attributes.containsKey('Account.BillingStreet')) {
            a.BillingStreet = attributes.get('Account.BillingStreet');
        }
        if (attributes.containsKey('Account.BillingCity')) {
            a.BillingCity = attributes.get('Account.BillingCity');
        }
        if (attributes.containsKey('Account.BillingState')) {
            a.BillingState = attributes.get('Account.BillingState');
        }
        if (attributes.containsKey('Account.BillingCountry')) {
            a.BillingCountry = attributes.get('Account.BillingCountry');
        }
        if (attributes.containsKey('Account.BillingPostalCode')) {
            a.BillingPostalCode = attributes.get('Account.BillingPostalCode');
        }
        if (attributes.containsKey('Account.AnnualRevenue')) {
            a.AnnualRevenue = Integer.valueOf(attributes.get('Account.AnnualRevenue'));
        }
        if (attributes.containsKey('Account.Description')) {
            a.Description = attributes.get('Account.Description');
        }
        if (attributes.containsKey('Account.Fax')) {
            a.Fax = attributes.get('Account.Fax');
        }
        if (attributes.containsKey('Account.NumberOfEmployees')) {
            a.NumberOfEmployees = Integer.valueOf(attributes.get('Account.NumberOfEmployees'));
        }
        if (attributes.containsKey('Account.Phone')) {
            a.Phone = attributes.get('Account.Phone');
        }
        if (attributes.containsKey('Account.ShippingStreet')) {
            a.ShippingStreet = attributes.get('Account.ShippingStreet');
        }
        if (attributes.containsKey('Account.ShippingCity')) {
            a.ShippingCity = attributes.get('Account.ShippingCity');
        }
        if (attributes.containsKey('Account.ShippingState')) {
            a.ShippingState = attributes.get('Account.ShippingState');
        }
        if (attributes.containsKey('Account.ShippingCountry')) {
            a.ShippingCountry = attributes.get('Account.ShippingCountry');
        }
        if (attributes.containsKey('Account.ShippingPostalCode')) {
            a.ShippingPostalCode = attributes.get('Account.ShippingPostalCode');
        }
        if (attributes.containsKey('Account.Sic')) {
            a.Sic = attributes.get('Account.Sic');
        }
        if (attributes.containsKey('Account.TickerSymbol')) {
            a.TickerSymbol = attributes.get('Account.TickerSymbol');
        }
        if (attributes.containsKey('Account.Website')) {
            a.Website = attributes.get('Account.Website');
        }
        if (attributes.containsKey('Account.Industry')) {
            a.Industry = attributes.get('Account.Industry');
        }
        if (attributes.containsKey('Account.Ownership')) {
            a.Ownership = attributes.get('Account.Ownership');
        }
        if (attributes.containsKey('Account.Rating')) {
            a.Rating = attributes.get('Account.Rating');
        }
        if (newAccount) {
            insert(a);
        } else {
            update(a);
        }
        return a.Id;
    }

    //Handle JIT
    private void handleJit(boolean create, User u, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map < String, String > attributes, String assertion) {
        if (communityId != null || portalId != null) {
            String account = handleAccount(create, u, attributes);
            handleContact(create, account, u, attributes);
            handleUser(create, u, attributes, federationIdentifier, false);
        } else {
            handleUser(create, u, attributes, federationIdentifier, true);
        }
    }

    //For New User
    global User createUser(Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map < String, String > attributes, String assertion) {
        User u = new User();
        handleJit(true, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
        return u;
    }

    //For Existing User
    global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId,
        String federationIdentifier, Map < String, String > attributes, String assertion) {
        User u = [SELECT Id, FirstName, ContactId FROM User WHERE Id =: userId];
        handleJit(false, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
    }
}