Sunday 3 December 2017

Roll up summary functionality through trigger

========================================================================

trigger ContactTrigger on Contact (After insert,After update,After Delete,After Undelete) {
    
    set<id> accIds = new Set<Id>();
    ContactTriggerHelper helper = new ContactTriggerHelper();
    
    if(Trigger.IsAfter && (Trigger.isinsert || Trigger.isUpdate || Trigger.isUndelete )){
        for(Contact con : Trigger.New){
            if(con.AccountId != null){
                accIds.add(con.AccountId);
            }
            
        }
        
    }
    
     if(Trigger.IsAfter && (Trigger.isUpdate || Trigger.isdelete )){
        for(Contact con : Trigger.Old){
            if(con.AccountId != null){
                accIds.add(con.AccountId);
            }
            
        }
        
    }
    
    if(accIds != null) {
        helper.updateAccoutTotals(accIds); 
    }

}

=====================================================================

public class ContactTriggerHelper {
    
    public void updateAccoutTotals(set<id> acIds){        
        
        List<AggregateResult> agrls = [SELECT Accountid accid,Count(Id) cnt,
                                     SUM(Payment__c) sm FROM COntact WHERE Accountid
                                      in :acIds Group By Accountid];
        
        list<Account> lstAccs = new List<Account>();
        
        for(AggregateResult agr : agrls){
            Account acc = new Account();
            acc.Id = String.valueOf(agr.get('accid'));
            acc.Total_Count__c =  Double.valueOf(agr.get('cnt'));
            acc.Total_Payemnts__c = Double.valueOf(agr.get('sm'));
            lstAccs.add(acc);            
        }
        
        update lstAccs;
        
        
    }
}

Friday 13 October 2017

Salesforce Test Class Template

Salesforce Test Class Template :



/*********************************************************************************
Class Name: TestClassTemplate

Purpose:   This is the test class for testing related apex class.

Please maintain only the last 5 history changes/modifications in the audit log

History of Changes:           
--------------------------------------------------------------------------------------------------------------------------
Date                                          Developer                               Comments
--------------------------------------------------------------------------------------------------------------------------
07-Feb-2017                                 Developer Name                         Added new method
********************************************************************************/
@isTest
public class TestClassTemplate {

    /*
* MethodName     : testData
* Description    : Create Testdata in @testSetup, use same data in all testmethods of this class.
*/
    @testsetup
    public static void testData(){
        list<account> lstAccs = new list<account>();
        list<contact> lstCons = new list<contact>();
   
        //Sample test data inserting here:
        for(integer i =0; i<10;i++){
            Account accData = new Account(
                name = 'testAcc'+i,
                Phone = '33333344444',                    // Phone
                Industry = 'Energy',                        // Industry
                Type = 'Prospect',                          // Type
                Match_Billing_Address__c = false,           // Match Billing Address
                Number_of_Contacts__c = 1,                  // Number of Contacts
                Description = 'Smith Enterprises :: null'  // Description
           
            );
            lstAccs.add(accData);
       
        }
        insert lstAccs;
   
        integer i = 0;
        for(account acc : lstAccs){
            Contact con = new Contact(
                lastname = 'testingcons'+i,
                Email = 'varam@gmail.com',               // Email
                Accountid = acc.id,                      // Account Name
                AssistantPhone = '1231234561',           // Asst. Phone
                Title = 'CEO',                           // Title
                Birthdate = system.today(),              // Birthdate       
                MobilePhone = '9874561235'              // Mobile
            );
            i++;       
            lstCons.add(con);
        }
        insert lstCons;
   
    }

    /*
* MethodName     : methodTest
* Description    : testing class methods.
*/

    public static testmethod void methodTest(){
        //Querey TestData
        list<contact> ltConsdata = [select id,firstname,lastname,accountid,account.name from contact];
   
        //Use assert statements
        system.assertEquals(10, ltConsdata.size())
       
            //Use test.startTest() and stopTest() for refreshing governor limits.
            test.startTest();
        classname.method(ltConsdata);
        test.stopTest();
   
    }

}






Friday 30 June 2017

Avoid Recursive Trigger Calls

Description:

Many developers face this issue because of a recursive trigger. For example,
 in an 'after update' trigger, a developer could be performing an update 
operation and this would lead to recursive call, and the error:
"maximum trigger depth exceeded"

Resolution:

In order to avoid the situation of recursive call, make sure your trigger
 is getting executed only one time. To do so, you can create a class with a 
static set<string> variable .

In the trigger, before executing your code keep a check that the string contains
trigger or not.based on that it will execute only once.

Below same code we will add where ever recursion happen.

public with sharing class RecursiveCheck {
    public static Set<String> triggerMonitor = new Set<String>();    
}

trigger ContactTrigger on Contact (after insert) {
    if(trigger.isInsert && !RecursiveCheck.triggerMonitor.contains('NAV_CRM_ContactTrigger')){
        RecursiveCheck.triggerMonitor.add('NAV_CRM_ContactTrigger');
        ====your logic here====
    }  

}


where ever your doing DML in class just need to add below line, it will stop recursion. 

if(updContacts.size() > 0){
 RecursiveCheck.triggerMonitor.add('ContactTrigger'); //Here we need to add trigger name. 
 database.update(updContacts); 
 }



Recursive Triggers

Saturday 27 May 2017

Test class for XML DOM Parser and Testing HTTP Callouts Using Static Resources



Sample respone receiving from external system  to Test :

http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <UpdateCustomerHeaderInfoResponse xmlns="http://tempuri.org/xyz.customerdetails">
         <UpdateCustomerHeaderInfoResult>
<InsertResult>False</InsertResult>
<CustomerNumber>123456789</CustomerNumber>
</UpdateCustomerHeaderInfoResult>
      </UpdateCustomerHeaderInfoResponse>
   </soap:Body>

</soap:Envelope>


First we need to save above response in static resources and then we need call in test class.


More Info : check below URL to test above response.


https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_static.htm



Friday 7 April 2017

How to Test Salesforce REST API

                   How to Test Salesforce REST API

To Test Salesforce Rest API First we need to create Connected App in Salesforce.Once we created Connected App it will generate consumer or client id and consumer secret.



After that we need to create Access-token using below steps.

1.grant_type=password&client_id=YourClientId&client_secret=YourClientSecret&username=YourUserName&password=YourPassword+securitytoken

EX:
client_id =  3MVG9ZL0ppGP5UrB.7GK_luxRT7StxC8dM37EZzuyrj0LMr_TaiMZatpDKASHUikAvgczZCo1ONfmzhV5LER1

client_secret = 1328342625760846904

username =  username

password=YourPassword+securitytoken

Content-Type : application/x-www-form-urlencoded

To make HTTP Requests we are using https://www.hurl.it/  or SOAP UI tool.


Here we will get response like below format:

{"access_token": "00D28000001xtTR!AQkAQO.ZKKI4ccUpsQLzm.RpgI4HxLuMU8vqrpmpku_DEc3_aHMs9ar60o_l2HR9Vc2cF3IbFS8jC5UDD38h3CmXvBX6ue42","instance_url": "https://ap2.salesforce.com","id": "https://login.salesforce.com/id/00D28000001xtTREAY/00528000005dGo3AAE","token_type": "Bearer","issued_at": "1491551856783","signature": "RxPY7+SXQEyaIzTW3B5c1N/0C3ciwhojKNbULX9Xawo="}

Now we will test Rest WS using above access token.

Sample RestClass:
@RestResource(urlmapping = '/showAccounts/*')
global class RestExample {
   
    @HttpGet
    global static list<account> getAccounts(){
        list<account> lstAccounts = new list<account>();
        RestRequest request = RestContext.request;
        system.debug('request >>>' + request);
        string accName = request.params.get('name');
        system.debug('==accName==='+accName);
        lstAccounts = [select id,name,phone from account where name =: accName];       
        system.debug('===result==='+lstAccounts);
        return lstAccounts;
    }
   
}



Using Below Extensions also we can test REST WSs.

Advanced REST client - Chrome Web Store

Postman - Chrome Web Store


Tuesday 4 April 2017

Sample Comments for classes and methods.

Class Comments:
/*********************************************************************************
Class Name: SampleClass

Purpose:    1. This is the class for creating data.

Please maintain only the last 5 history changes/modifications in the audit log

History of Changes:                
--------------------------------------------------------------------------------------------------------------------------
Date                                          Developer                               Comments
--------------------------------------------------------------------------------------------------------------------------
07-Feb-2017                         Developer Name           Added new method
********************************************************************************/
public class SampleClass{

Method Comments:
/*
 * MethodName : sampleMethod
 * Description    : searching all accounts data based on name.
 */

public static void sampleMethod(){

               

}
}

Saturday 28 January 2017

How to disable/enable all validation rules for data loading in Salesforce

How to disable/enable all validation rules for data loading in Salesforce:



1) click Setup, then on the left side, click Develop/Custom Settings.
2) click New and create your settings as hierarchy/public

3) now create a custom field of type Checkbox: click New, select Checkbox, click Next, type the name of the field as “Disable Validation Rules”, default to Unchecked, click Next, then click Save.
4) in the Custom Setting Definition/Your App Settings screen, click Manage to start configuring the setting you just created.
5) click the New button above “Default Organization Level Value”, leave the checkbox “Disable Validation Rules” unchecked and then click Save.

6) click “Back to List”, click the New button at the bottom, select Profile or User then choose the user id or profile that will perform the data loading, then click “Disable Validation Rules” and click Save.
7) now edit the validation rule appending the expression (highlighted below)
&& NOT( $Setup.Your_App_Settings__c.Disable_Validation_Rules__c )
8 ) click Save
9) now the validation rule will only apply if the setting checkbox
Disable Validation Rules is unchecked for your profile/user
10) you can now load data freely and then, later, re-enable all
validation rules for your profile/user by changing the custom
setting.
11) you can use this way of implementing Custom Settings on
triggers too, just use the syntax below:
  • Your_App_Settings__c s = Your_App_Settings__c.getInstance( UserInfo.getUserID() );
  • if( s.Disable_Validation_Rules__c ) return;

Examples : 

In Trigger : 

trigger AccountTriggerHandler on Account (before insert,before update,after update) {
    Application__c bypassTrigger= Application__c.getInstance( UserInfo.getUserID() );
    if(!bypassTrigger.DisableValidations__c){
        if(trigger.isbefore && trigger.isinsert){
            for(account acc : trigger.new){
                if(acc.phone == null){
                    acc.phone.addError('phone no required');
                }
            }
        }
        
    }
    
}

Validation :

ISBLANK( Phone ) && NOT( Setup.Application__c.DisableValidations__c )


Complete Salesforce CPQ training Free videos

Salesforcestart:: We are excited to announce that our YouTube channel, Salesforcestart, is your one-stop-shop for all things Salesforce CPQ!...