Friday 25 May 2018

Switch Statement in Salesforce | Salesforce Summer ’18 Release Notes

Simplify Your Code with the Apex Switch Statement

Finally Swtich Statement is available in Salesforce with Summer 18.

Sample Code:-
public class  SwitchExample { 
    public static void testSwitchCase() {
        Integer i = 2;
        switch on i {
            when 1
            when 2
            when else
NOTE:- Please set the Apex code version as 43. 

 (This Image is from Salesforce documentation)

Amit Chaudhary

Thursday 24 May 2018

Callouts from a Visualforce Page | Continuation | Asynchronous callouts from VF page

Most of the time got the requirement to do callout from VF page button. We can do the same with the help of Continuation method. An asynchronous callout is a callout that's made from a Visualforce page for which the response is came back through a callback methodology. An asynchronous callout is additionally referred to as a continuation.

(This Image is from Salesforce documentation)

Apex Class:-

public class AnimalsCallouts {

    // Unique label corresponding to the continuation
    public String requestLabel;
    public String result {get;set;}
    public List<Object> animals {get;set;}
    public AnimalsCallouts(){ 
        animals =new List<Object>();

    public Object  makeGetCallout() {
        Continuation con = new Continuation(40);
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        // Add callout request to continuation
        this.requestLabel = con.addHttpRequest(request);
        // Return the continuation
        return con; 
    public Object processResponse() {  
        HttpResponse response = Continuation.getResponse(this.requestLabel);

        // Set the result variable that is displayed on the Visualforce page
        if (response.getStatusCode() == 200) {
            this.result = response.getBody();
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            animals = (List<Object>) results.get('animals');
        return null;

NOTE:- Dnt forget to add Remote Site Setting for your URL.

Visual Force Page:-
<apex:page controller="AnimalsCallouts">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton action="{!makeGetCallout}" value="GetCall" reRender="detail"/>
            <apex:pageBlockSection id="detail" columns="1">
                 {!result }
                 <apex:pageBlockTable value="{!animals }" var="an">
                     <apex:column value="{!an}" headerValue="Response"/>



If you want to learn about REST API check below post


Amit Chaudhary

Sunday 13 May 2018

REST API with XML and JSON | REST API with XML Payload | REST API with Dynamic Response

Recently i got one requirement to create one REST API which should support JSON and XML both. If we will pass JSON request body then response should come in JSON. But if we will send request body in XML then response should come in XML.

So here is solution :)

Global class REST_API_Helper{     public static blob formatResponse(ResponseBase ResponseBaseObj,String contentType){         String response;         String strContectType = contentType.toUpperCase();         if(strContectType.contains('XML')){             response = serializeRespinseBaseXml(ResponseBaseObj);         }             else {             response = JSON.serialize(ResponseBaseObj);         }         return blob.valueOf(response);     }     /*     *************************************************************************     * @description: This function is used to send the response in XML     * @return: string       *************************************************************************     */      public static string serializeRespinseBaseXml(ResponseBase ResponseBaseObj ){         String responseXML = '';         responseXML  += '<response>';         XmlStreamWriter w = new XmlStreamWriter();         w.writeStartElement(null , 'Message', null );         w.writeCharacters(ResponseBaseObj.Message);         w.writeEndElement();                  w.writeStartElement(null , 'Success', null );         w.writeCharacters(String.valueOf(ResponseBaseObj.Success));         w.writeEndElement();         responseXML += '</response>';         String xmlOutput = '<?xml version="1.0" encoding="UTF-8"?>' + '<Response>' + w.getXmlString()              + '</Response>';         w.close();         return xmlOutput ;     }     global class ResponseBase {         global Boolean Success {get;set;}         global String Message  {get;set;}         global ResponseBase(){                 success = true;                 message = 'Records are updated';         }     } }

global with sharing class RESTAPI_JSON_XML 
    global static void doPost(ContactDetail  Detail) {
        RestResponse standardResp = RestContext.response;
        REST_API_Helper.ResponseBase  CustomeResponse = new REST_API_Helper.ResponseBase(); 
        ContactDetail reqBodyObj = Detail; 

        RestRequest req = RestContext.request;       
        String ContentType = RestContext.request.headers.get('Content-Type') ;
        Contact cont = new Contact();
        cont.FirstName = reqBodyObj.FirstName.trim();   
        cont.LastName  = reqBodyObj.LastName.trim();
        insert cont;
        CustomeResponse.Success = true;
        CustomeResponse.Message = 'Contact Created id =';
        standardResp.statusCode = 200;
        standardResp.responseBody = REST_API_Helper.formatResponse(CustomeResponse,ContentType); 

    global class ContactDetail{
       global string FirstName {get;set;}
       global string LastName  {get;set;}
       public ContactDetail()  {}

Sample JSON Example:-
Method:- Post
URL:- /services/apexrest/api/*/createContact
Request Body
   "Detail": {
                "LastName" :"Chaudhary"

Sample XML Example:-
Method:- Post
URL:- /services/apexrest/api/*/createContact
Request Headers:-
Content-Type: application/xml; charset=UTF-8
Accept: application/xml
Request Body
<?xml version="1.0" encoding="UTF-8"?>

Response :-
<?xml version="1.0" encoding="UTF-8"?><Response><Message>Contact Created id =0039000002SMSFJAA5</Message><Success>true</Success></Response>