Showing posts with label Integration. Show all posts
Showing posts with label Integration. 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!

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]


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........

Friday, July 24, 2015

Implementing Expand/Collpasible Master-detail records in Visualforce page using datatables/Jquery/JS

Hi Everyone ,Recently I got a requirement where i have to display all master record in a vf page where clicking on any master record i want to show it's child records below the selected master record.

I searched many places and many blogs finally i came up with some idea how to implement  and I came to know already available plugins.So I feel it will be helpful if I share the collected information.So,I'm just sharing all those documents.

http://jsfiddle.net/lbriquet/4Rkb3/36/

http://jsfiddle.net/nanoquantumtech/RgKPZ/

https://jquery-datatables-row-grouping.googlecode.com/svn/trunk/customization.html

https://jquery-datatables-row-grouping.googlecode.com/svn/trunk/accordion.html

http://www.codeproject.com/Articles/189621/Creating-an-expandable-master-details-table-jQuery

http://datatables.net/release-datatables/examples/server_side/row_details.html

http://www.telerik.com/forums/expand-row-show-details-when-row-is-selected

http://imomins.blogspot.in/2013/01/creating-expandable-master-details.html

https://imomins.wordpress.com/2013/01/03/creating-an-expandable-master-details-table-jquery-datatables-and-asp-net-mvc-integration-part-iv/

http://www.script-tutorials.com/creating-expandable-tables-with-jexpand/

http://stackoverflow.com/questions/24751034/creating-a-vertically-collapsing-and-expanding-html-table

http://stackoverflow.com/questions/16926752/expand-collapse-table-rows-with-jquery

https://jquery-datatables-row-grouping.googlecode.com/svn/trunk/collapsibleGroups.html

https://jquery-datatables-row-grouping.googlecode.com/svn/trunk/accordion.html

http://salesforce.stackexchange.com/questions/83641/how-to-show-related-contacts-under-account-in-vf-page



Enjoy...........



Thursday, November 21, 2013

Like Operator in SOQL Query

Like Operator:

        Like Operator in SOQL act as a Comparison operator  for String Field Expression.Expression is true if the value in the specified fieldName matches the characters of the text string in the specified value. It provides a mechanism for matching partial text strings and includes support for wildcards.


Notes:

  • The % and _ wildcards are supported for the LIKE operator.
  • The % wildcard matches zero or more characters.
  • The _ wildcard matches exactly one character.
  • The text string in the specified value must be enclosed in single quotes.
  • The LIKE operator is supported for string fields only.
  • The LIKE operator performs a case-insensitive match, unlike the case-sensitive matching in SQL.
  • The LIKE operator in SOQL and SOSL supports escaping of special characters % or _.
  • Do not use the backslash character in a search except to escape a special character.
Special Characters % and _

   %-->Specifies that Zero ,One or more characters 
   _ --> Specifies that only One character.

SOQL Query Examples for Like Operator

Example, the following query matches Appleton, Apple, and Bappl , but not Appl:

   SELECT Id, Name FROM Widget__c WHERE Name LIKE 'appl_%'

Example 1:Withou Using Variable

     1.[Select Id,FirstName form User where FirstName LIKE 'srinivas'];

     2.[Select Id,FirstName form User where FirstName LIKE '%srinivas'];

     3.[Select Id,FirstName form User where FirstName LIKE '%srinivas_'];

Example 2:Like Using Variable need to use (:) bind Variavble

    User object contains FirstName as below Records:
     1. srinivasa
     2. msrinivasa
     3. srinivas

   String firstname ='srinivas';

 User u=  [SELECT Id , FirstName,LastName  FROM User where FirstName LIKE : firstName LIMIT 9];

  This query returns Users record from User object where FirstName of user is srinivas only.
  output: srinivas record only number3

Example 2:Using variable with % and _ wildcard characters
  String firstname ='srinivas';
  String str='%'+firstname +'%';
 User u=  [SELECT Id , FirstName,LastName  FROM User where FirstName LIKE : firstName LIMIT 9];

This query will return Users record from User object where FirstName of User contains srinivas
output:It returns Three Records  1. srinivasa 2. msrinivasa 3. srinivas

                              
                                                         
                               


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/