Nov 10

salesforce To Salesforce Integration Through Apex

    public class salesforceToSalesforceIntegrationThroughApex {

        public void integrateS2S()
        {
            final String LOGIN_DOMAIN = 'login'; //other options: test, prerellogin.pre
            final String USERNAME  = 'user name';
            final String PASSWORD  = 'user password';
        
            String SERVER_URL;
            String SESSION_ID;

            // How to generate Consumer Key and Consumer Secret Code? 

            //Goto Setup > Build > Apps>Connected Apps>New> Enter required data alog with API (Enable OAuth Settings)
            String Consumer_Key = '3MVG9Y6d_Btp4xp7HI0OKNu0NNZ7CbuDa8ISx.u_E6f4e3Q.4MBRzkD3Mi3lzUCwlC3OgO5g5oT.I7xVYt1aB';
            String Consumer_Secret = '766475509074793020';
            
            HttpRequest request = new HttpRequest();
            request.setEndpoint('https://login.salesforce.com'+'/services/oauth2/token');
            request.setMethod('POST');
            request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
            request.setHeader('SOAPAction', '""');
            String reqbody = 'grant_type=password&client_id='+Consumer_Key+'&client_secret='+Consumer_Secret+'&username='+USERNAME+'&password='+PASSWORD;          
            request.setBody(reqbody);
            
            Http hp = new Http();
            HttpResponse response = hp.send(request);
            System.debug('response.getbody()'+response.getStatusCode());
            
            JSONParser parser = JSON.createParser(response.getbody());
            
            OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(response.getbody(), OAuth2.class);         
                if(objAuthenticationInfo.access_token!=null)
                {  
                    SERVER_URL=objAuthenticationInfo.instance_url;
                    SESSION_ID = objAuthenticationInfo.access_token;
                }
            final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
            theUrl.getParameters().put('q','select id,name from Account limit 10');
            request = new HttpRequest();
            request.setEndpoint(theUrl.getUrl());
            request.setMethod('GET');
            request.setHeader('Authorization', 'OAuth ' + SESSION_ID);
            String body = (new Http()).send(request).getBody();
            System.debug('Accounts in JSON format: ' + body);
            JSONParser parser2 = JSON.createParser(body);
                do{
                    parser2.nextToken();
                }while(parser2.hasCurrentToken() && !'records'.equals(parser2.getCurrentName()));
                    parser2.nextToken();
                    final List<Account> accounts = (List<Account>) parser2.readValueAs(List<Account>.class);
                    System.debug('Accounts as native list: ' + accounts);                    
        }

    }

Feb 03

Salesforce Apex enum Example

crate a class season,month,MyExample bellow like this
public enum Season {
WINTER,SPRING,SUMMER,FALL
}

public enum Month {
JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC
}

public class MyExample {
public List seasonMonths(Season s)
{

List listMonths = new List();

if(s==season.WINTER)
{
listMonths.add(Month.DEC);
listMonths.add(Month.JAN);
listMonths.add(Month.FEB);

}
else if(s==season.SPRING)
{
listMonths.add(Month.MAR);
listMonths.add(Month.APR);
listMonths.add(Month.MAY);

}
else if(s==season.SUMMER)
{
listMonths.add(Month.JUN);
listMonths.add(Month.JUL);
listMonths.add(Month.AUG);
}
else if(s==season.FALL)
{
listMonths.add(Month.SEP);
listMonths.add(Month.OCT);
listMonths.add(Month.NOV);
}

return listMonths;
}
/*
Steps to execute this code

System.debug(Season.WINTER);
MyExample obj = new MyExample();
System.debug(obj.seasonMonths(Season.WINTER));
*/
}

Jan 21

SOQL Select all fields (Select * from )

public class ApexSelectQueries {
//SOQL will not support direct select * from syntax, so we need to retrive all field names first then we should construct a select statment with the fields.
//This method generates a SOQL select statement equal to select * from object.
//if your object is Account then your fieldMap should be return type of this statment schema.SObjectType.Account.fields.getMap();
//The return type of this method is string i.e select field1,field2,… from yourObject.
public String selectAll(Map fieldMap,String yourObject)
{
Map fldObjMap = fieldMap;
List fldObjMapValues = fldObjMap.values();
String theQuery=”;
for(Schema.SObjectField sObjField : fldObjMapValues)
{
String theName = sObjField.getDescribe().getName();
theQuery += theName+’,';
}
if(theQuery.lastIndexOf(‘,’)!=-1)
{
theQuery = theQuery.removeEnd(‘,’);
}
theQuery = ‘SELECT ‘+theQuery+’ From ‘+yourObject;
return theQuery.trim();
}
}

Oct 21

APEX String Example for to tokenize CSV String to individual Strings.

To learn in-depth Salesforce join in our trainings!       #(+91) 8978397610  mail:  cloud_murali@yahoo.in

Problem Statement: 

         A String contains comma separated values, it is required to split this string into sub strings 
 
Solution:
—————————————————————————————————————————-
String csvString='test,ravi,praveen,ramu,pavan,Raghu,Kamal,Reddy,Sravan,muni,murali';
System.debug('Given String : '+csvString);
List<String> listTokenStrings= csvString.split(',',csvString.countMatches(',')+1);
System.debug('Number of tokenized words in the given String '+listTokenStrings.size());
Integer count = 1;
for(String strToken:listTokenStrings)
{
    System.debug('Word_'+(count++)+' : '+strToken);
}
—————————————————————————————————————————-

Other Uses

   Instead of comma (,) it can be any delimiter like (,.;:' etc) for all things the same example will work.

  It is very common use case to work with comma separated values. In that scenario this example will work very effectively.