Showing posts with label WebServices. Show all posts
Showing posts with label WebServices. Show all posts

Wednesday, August 23, 2017

How to Invoke the REST API from the Visual Force Page in Salesforce

Problem:
We usually making a lot of API calls from Salesforce to External systems to get the some data or to pass the some updates to External Systems.All these calls will be made from the Apex class to External systems. What if you have situation like where you need to make a call to external systems from the visual force page.

Solution:
No need to worry still we have option to make an REST API call from the page directly.How?As we already know that Salesforce has introduced a concept called AJAX ToolKit.This is an frame which will be used to make all the operations from JavaScript similar to APEX. With help of this tool kit you can make an REST API call from the Script in Visual Force Page

Flow Diagram:
 

Sample Source Code:

<apex:page standardController="Account">
<apex:includeScript value="//code.jquery.com/jquery-1.11.1.min.js" />
<script src="../../soap/ajax/40.0/connection.js" type="text/javascript"></script>

<script>
function makeAPICall() 
{
    var weblink = //Your API endpoint 'https://www.yourednpoint/';
 
    $j.ajax({
  url: weblink,
  type: 'GET', // Type POST or GET
  dataType: 'json',
  beforeSend: function(request) {
      // Add All your Headers Here if Any
   request.setRequestHeader('HeaderString','HeaderValue');
   //Sample Headers 
   request.setRequestHeader('Country', 'IND');
   request.setRequestHeader('Currency', 'INR');
  },

  crossDomain: true,
  
  //If Successfully executed 
  success: function(result) {
   
   //Response will be stored in result variable in the form of Object.Please use result variable for processing
    console.log('Response Result'+result); 
    
      //If you want to convert JSResponse Object to JSON response 
    var jsonResp = JSON.stringify(result));

  },
  
  //If any Error
  
  error: function(jqXHR, textStatus, errorThrown) {
   
   // alert('ErrorThrown: ' + errorThrown);
  }
    });
}
</script>
<apex:form>
  call javaScript method from here to make an api call invocation
</apex:form>
</apex:page>

Hope this helps you....Enjoy!
 

Wednesday, August 9, 2017

System.TypeException: Invalid date/time Exception in Salesforce Apex

  • When your assigning a value DateTime field using the String then we will end up with this error.
  • If your receiving your date value as part of JSON response and then assiging to DateTime value you will also end up with same error.
To avoid this issue we can use the below two procedures

Sample Error Code:


if(mapName.KeySet().contains('creation_Time') && string.isNotBlank(string.valueof(mapName.get('creation_Time'))))
{

 if(string.valueof(mapName.get('creation_Time')).contains('T'))
  {
    ObjectInsatnce.creation_Time__c = datetime.valueof(string.valueof(mapName.get('cancellation_time')).replace('T',' '));
  }
else
{
 ObjectInsatnce.Cancellation_Time__c = datetime.valueof(mapName.get('cancellation_time'));
}
}

Rectified Source Code:


if(mapName.KeySet().contains('creation_Time') && string.isNotBlank(string.valueof(mapName.get('creation_Time'))))
{

if(string.valueof(mapName.get('creation_Time')).contains('T'))
{
 ObjectInsatnce.creation_Time__c = datetime.valueof(string.valueof(mapName.get('cancellation_time')).replace('T',' '));
}
else
{
  ObjectInsatnce.Cancellation_Time__c = datetime.valueof((String)mapName.get('cancellation_time'));
}
}
 

Hope this helps you....Enjoy!

Monday, August 7, 2017

Google Service Account Private Key in JSON File

To authenticate the Google Cloud API's we need a Private Key which will be generated by Google for each Service Account Individually . This Private Key can be generated in 2 formats .


  • JSON format
  • PKCS12 format

Sample JSON file with Private Key:


{
 "type": "service_account",
 
 "project_id": "XXXX:api-project-1234",
 
 "private_key_id": "xxxxxx4360517xxxxx",
 
 "private_key": "-----BEGIN PRIVATE KEY-----\+lzqL6szpFDr5M/ow8Fa8X\nKokb6SfT+liJJboTVosoR8C1l1EnYRg+/qwv0w4JPdmLS1sY53k2EFP0EcqVYOYr\nDZx6a+TIVFB
 Xkas2IbyLsN13CCBJ5r1lhpCeP+nrCdi2MddXjTyfAIhGb5/fhTfU\nNoAaodmBuwKBgQDYzKuHLB9S+tjHKca/0fS1DLvo2vxbicDwAlDPrGfDrMHNKZBd\nKDTRJdk8R3FRNHcDHEZI969WyXcNNycM2aNcWy
 jMlCM/15pGylzDZRmP7gM20VFG\nnoNV5Y0TARJYGP2652kVsA2LuiBaA2GPHORSXo4/RvR6B+hQYJdh3GkGUQKBgQCY\nitMHu0ZkbLfze8kEYtnhX20SO5OaNgVtOcVd5RnEkU6W8fjY0ugpINbg+m7ZQh09\
 nS7z8T8DBf0CO2R4izaFZ==\n-----END PRIVATE KEY-----\n",
 
 "client_email": "xxxxxxxxxxxxxx.iam.gserviceaccount.com",
 
 "client_id": "xxxxxx4360517xxxxx",
 
 "auth_uri": "https://accounts.google.com/o/oauth2/auth",
 
 "token_uri": "https://accounts.google.com/o/oauth2/token",
 
 "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
 
 "client_x509_cert_url": "https://www.googleapis.com/xxxxxxxiam.gserviceaccount.com"
}

The one which resides between BEGIN PRIVATE KEY and END PRIVATE KEY is called Private Key.

For more information please refer this link.

Hope this helps you....Enjoy!
  


Friday, August 4, 2017

Parse the JSON Response in Salesforce Apex -Part 2

In this post I'm going to explain how to create a wrapper class in apex to parse the JSON response which having multiple key value pairs only.

JSON String:


{
    "AccID1" : {
        "contacts" : {
            "0055be4ce5802020100" : "CREATED",
            "0055be4ce5802020100" : "Open"
        },
  "cs" : {
            "f0055be4ce5802020100" : "CREATED",
            "09055be4ce5802020100" : "Completed"
        }
    },
    "AccID2" : {
        "contacts" : {
            "0055be4ce5802020100" : "SUCCESSFUL"
        }
    },
    "AccID3" : {
        "contacts" : {
            "0055be4ce5801020100" : "CREATED"
        },
        "cs" : {
            "f0055be4ce5802030100" : "Open",
            "f0055be4ce5802030100" : "Re-Open",
            "f0055be4ce5802030100" : "Closed"
        }
    },
 "AccID4" : {
        "contacts" : {
            "0055be4ce5801020100" : "Initiated"
        }
       
    }
}

Apex Class:

//Wrapper Class For Parsering 
public class ParsingTest
{
  public ParsingTest()
  {
        String jsonString='Pass your JSON String Here';
 Map<string,ContactsCSWrapper> apiRespone = new Map<string,ContactsCSWrapper>();
 apiRespone = (Map<string,ContactsCSWrapper>)System.JSON.deserialize(jsonString,Map<string,ContactsCSWrapper>.class);
 System.debug('apiRespone..'+apiRespone.keySet()); //Outputs AccID1,AccID2,AccID3,AccID4
  }
  
  public class ContactsCSWrapper 
 {
  public map<string, string> cs { get; set; }
  public map<string, string> contacts { get; set; }
 }
}


Hope this helps you....Enjoy!

Parse the JSON Response in Salesforce Apex -Part 1

In this post I'm going to explain how to create a Wrapper class to Parse the JSON Response in Apex which contains key and value pair in JSON.

JSON String:

{
 "status": "SUCCESS",
 "errors": [],
 "data": {
  "oldCaseStatus": "Case_CANCELLATION_success",
  "newCaseStatus": "Case_CANCELLATION_success",
  "NewCaseNumber": "3732gy12"
         }
}

Apex Class:

public class ParsingTest
{
  public ParsingTest()
  {
      String json='{"status":"SUCCESS","errors":[],"data":{"oldCaseStatus":"Case_CANCELLATION_success","newCaseStatus":"Case_CANCELLATION_success","NewCaseNumber":"3732gy12"}}';
      ParsingWrapper apiRespone = new ParsingWrapper();
      
      apiRespone = (ParsingWrapper)System.JSON.deserialize(json,ParsingWrapper.class);
      System.debug('apiRespone..'+apiRespone);
  }

 //Wrapper Class For Parsering 

  public class ParsingWrapper
  {
   public String status{get;set;}
   public Map<String,String> data{get;set;}
   public Cls_errors[] errors;
  }

  public class Cls_errors
  {

  }
}


Hope this helps you....Enjoy!

Saturday, January 23, 2016

Rest API Errors in Salesforce



Below are the some of the errors we will receive while doing REST API integration

1.|FATAL_ERROR|System.JSONException: Can not deserialize SObject out of START_ARRAY token at [line:1, column:1]

2{"errorCode":"APEX_ERROR","message":"System.JSONException: Unexpected character ('C' (code 67)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]\n\n(System Code)\line 28, column 1"}

3.Malformed JSON: Expected '[' at the beginning of List/Set

4.Unexpected character ('C' (code 67)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]


Friday, January 8, 2016

Custom Metadata Loader in Salesforce

In my previous posts I have explained what is Custom MetaData Types and how to Create Custom Metadata Types in Salesforce. Once everything is set up next task is to create records in those custom metadata types.If it 10 to 15 records we can create manually but there are some situations where you need to load more number of records let take an example loading the country names and their respective country codes.

To do this there is no specific tools like Data loader and Import wizard in salesforce to upload Custom Metadata type records.To achieve this we have an other option called Custom Metadata Loader.

Custom Metadata Loader

  • Custom metadata loader is a tool for creating custom metadata records from a csv file. 
  • This Custom Metadata Loader is a custom application which build on top of the salesforce with the help of Metadata API to support bulk uploads.
  • Create custom metadata types in your Salesforce org using Metadata API and then use custom metadata loader to bulk load the records.
  • It supports up to 200 records upload with a single call.


In my next post I will post How to set up and how to upload the records with this tool in salesforce. 

Keep watching the site for more updates enjoy......!

Sunday, November 22, 2015

Generating Access Token for Connected App using CURL

When you have designed a REST API using apex, to provide the authentication to the requester we will be creating a Connected App in salesforce .In this post we will being learning how to create a Connected App and how to get the AcccessToken using the CURL.

Creating the Connected App 

1.Goto Setup--> Create --> App--> click on Connected Apps (as shown as below)




























2. Fill all the manadtory fields(Connected App Name,Contact Email) as heigligted as below image


























3. For authentication purpose we are using here OAuth .So,click on Enable OAuth Settings checkbox 

    i) Fill the CallBack URL with below values based on instance
       
         Prod or Developer Edition =  https://login.salesforce.com/services/oauth2/callback
         For Sandboxes                   =  https://test.salesforce.com/services/oauth2/callback

  ii)In Selected OAuth Scopes section move Full access(full) value from Available OAuth Scopes to Selected OAuth Scopes (Plz refer the below image for more info)




























4.Click on Save and your connected app would populate with Consumer Key and Consumer Secret as heightened in the below image


























Getting the Access Token using the CURL


Testing RESTful webservices on Windows can be done outside of the browser using an open source command tool called cURL.

1.you can download the CURL from the below link based on your operating systems.
     a)  CURL download link
     b)  For Windows 32 bit (safer choice)
     c)  For Window 64 bit

2. For windows download Zip file from the above mention links (b and c).

3. Extract the zip file copy the curl.exe file and paste in the c:\windows\system32

4. Installation of CURL is finished.

5. To test the installation execute the command as given in image























Syntax to get the Access Token 

1.Open command promt and execute the below command

 curl --form client_id=<Your client id/Consumer Key>  --form client_secret=<Your Secret ID/Consumer Secret> --form grant_type=password --form username=<Your User Name>  --form password=<Your Password+SecurityToken> -k https://<Your Domain/Instance Name>.salesforce.com/services/oauth2/token

Example

curl --form client_id=3MVG9Y6d_Btp4xp7.7cBQRNzmybjPJDdJ8B1jneA51uSo_o_5Vwkz --form client_secret=596012939950 --form grant_type=password --form username=test@gmail.com --form password=ilovecodeYlM4IQZjX1TiDAW -k https://cs10.salesforce.com/services/oauth2/token

If command is successfully executed you will receive below response with Access Token

{"access_token":"00D90000000ewis!AQ0A81cE1b4zMyVTJ0lEuk7vxny4WDtUAuEQC1MqOgp6UpIWQT6.F8CQOc4u5b15.y6",
  "instance_url":"https://cs10.salesforce.com",
  "id":"https://login.salesforce.com/id/00D90077777ewisEAA/005900111100jjJ7AAI",
  "token_type":"Bearer",
  "issued_at":"1448333666867",
  "signature":"3vjbiglhrQRMA3KqCiabcBqnoqs4TNdmzyQDlV/M1Aw="}


Thanks for visiting...Enjoy........

Thursday, October 24, 2013

Working with Custom SOAP and REST Services in .NET Applications

           The Force.com platform gives developers a multitude of choices for accessing data. The SOAP API and REST API provide complete access to standard and custom Force.com objects. However, the need often arises to extend built-in functionality in order to support unique business requirements. Fortunately for Force.com developers, it's simple to create powerful, custom services that can be consumed in any platform.
This article explains how developers can build custom Force.com SOAP and REST services and consume them in .NET applications.

         For More information please Click Here.

Friday, September 27, 2013

Most Important OnLine Tool for Coding and Decoding(i.e.,For Conversion)

Coder's Tool Box:

The Coder’s Toolbox contains all the little tools you never know where to find.
  • Time conversion – convert between Unix timestamp, ISO8601 and RFC 2822 formats
  • String conversion – encode/decode Base64-encoding; escape XML, URL's and ECMAScript; translate to UTF-8
  • Number conversion – convert between decimal, hexadecimal, octal and binary numbers
  • Network – calculate netmasks, broadcast addresses and do DNS lookups
  • Bandwidth – calculate the duration of file transfer
  • XPath debugger – test your XPath expressions
For more information please visit the below link

http://coderstoolbox.net/string/#!encoding=base64&action=encode&charset=iso_8859_1

Monday, September 23, 2013

XML NameSpaces in SalesForce

XML NameSpaces:
An XML namespace is a collection of names identified by a URI reference and used in XML documents to uniquely identify element types and attribute names. Names in XML namespaces may appear as qualified names, which contain a single colon, separating the name into a namespace prefix and a local part. The prefix, which is mapped to a URI reference, selects a namespace. The combination of the universally managed URI namespace and the document's own namespace produces identifiers that are universally unique.
The following XML element has a namespace of http://my.name.space and a prefix of myprefix.
<sampleElement xmlns:myprefix="http://my.name.space" />
  In the following example, the XML element has two attributes:
  • The first attribute has a key of dimension; the value is 2.
  • The second attribute has a key namespace of http://ns1; the value namespace is http://ns2; the key is foo; the value is bar.
<square dimension="2" ns1:foo="ns2:bar" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2" />

 For more information regarding XML Namespaces Please visit the below link
 http://www.xmlmaster.org/en/article/d01/c10/

Friday, September 20, 2013

Document Class in Salesforce

Document Class:


Use the Document class to process XML content. One common application is to use it to create the body of a request for HttpRequest or to parse a response accessed by HttpResponse.


Methods

The Document class has the following methods:
NameArgumentsReturn TypeDescription
createRootElementString name
String namespace
String prefix
Dom.XmlNodeCreates the top-level root element for a document.
The name argument can't have a null value.
If the namespace argument has a non-null value and the prefix argument is null, the namespace is set as the default namespace.
If the prefix argument is nullSalesforce automatically assigns a prefix for the element. The format of the automatic prefix is nsi, where i is a number.
If the prefix argument is '', the namespace is set as the default namespace.
For more information about namespaces, see XML Namespaces.
Calling this method more than once on a document generates an error as a document can have only one root element.
getRootElementDom.XmlNodeReturns the top-level root element node in the document. If this method returns null, the root element has not been created yet.
loadString xmlVoidParse the XML representation of the document specified in the xml argument and load it into a document. For example:
Dom.Document doc = new Dom.Document();
doc.load(xml);
toXmlStringStringReturns the XML representation of the document as a String.



Example:

For the purposes of the sample below, assume that the url argument passed into the parseResponseDom method returns this XML response:

<address>
    <name>Kirk Stevens</name>
    <street1>808 State St</street1>
    <street2>Apt. 2</street2>
    <city>Palookaville</city>
    <state>PA</state>
    <country>USA</country>
</address>

The following example illustrates how to use DOM classes to parse the XML response returned in the body of a GET request:
public class DomDocument {
 
    // Pass in the URL for the request
    // For the purposes of this sample,assume that the URL
    // returns the XML shown above in the response body
    public void parseResponseDom(String url){
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        // url that returns the XML in the response body
        req.setEndpoint(url);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        Dom.Document doc = res.getBodyDocument();
        
        //Retrieve the root element for this document.
        Dom.XMLNode address = doc.getRootElement();
        //getChildElement() method is present in XML Node Class
        String name = address.getChildElement('name', null).getText();
        String state = address.getChildElement('state', null).getText();
        // print out specific elements
        System.debug('Name: ' + name);
        System.debug('State: ' + state);
        
        // Alternatively, loop through the child elements.
        // This prints out all the elements of the address
        for(Dom.XMLNode child : address.getChildElements()) {
           System.debug(child.getText());
        }
    }
}
XML NameSpaces:
An XML namespace is a collection of names identified by a URI reference and used in XML documents to uniquely identify element types and attribute names. Names in XML namespaces may appear as qualified names, which contain a single colon, separating the name into a namespace prefix and a local part. The prefix, which is mapped to a URI reference, selects a namespace. The combination of the universally managed URI namespace and the document's own namespace produces identifiers that are universally unique.
The following XML element has a namespace of http://my.name.space and a prefix of myprefix.
<sampleElement xmlns:myprefix="http://my.name.space" />
  In the following example, the XML element has two attributes:
  • The first attribute has a key of dimension; the value is 2.
  • The second attribute has a key namespace of http://ns1; the value namespace is http://ns2; the key is foo; the value is bar.
<square dimension="2" ns1:foo="ns2:bar" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2" />

 For more information regarding XML Namespaces Please visit the below link
 http://www.xmlmaster.org/en/article/d01/c10/