Sunday 23 February 2014

Integration with Salesforce using REST API

REST API provides a powerful, convenient, and simple Web services API for interacting with Force.com.
Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and Web 2.0 projects

A Lot of people ask about how can we integrate external system with Salesforce without using any ETL tool. Here is the example in which I am going to show you how can we insert Account in salesforce by using .NET windows form application.

First, we need to create connected app that uses OAuth protocol to verify both the Salesforce user and the external application.

Follow these steps to create a connected app:
From Setup, click Create | Apps.
In the Connected Apps section, click New.


When you’ve finished entering the information, click Save to save your new app.If you’re using OAuth, saving your app gives you two new values the app uses to communicate with Salesforce:

Consumer Key: A value used by the consumer to identify itself to Salesforce. Referred to as client_id in OAuth 2.0.
Consumer Secret: A secret used by the consumer to establish ownership of the consumer key. Referred to as client_secret in OAuth 2.0

We can Authenticate the user via one of several different OAuth 2.0 authentication flows. In this example we are using Username-password flow, where the application has direct access to user credentials.

User Interface of the application from which we are inserting Account record.




Code Snippet.
 using System;  
 using System.Collections;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Data;  
 using System.Drawing;  
 using System.Linq;  
 using System.Text;  
 using System.Windows.Forms;  
 using System.Web.Script.Serialization;  
 using Newtonsoft.Json;  
 using Newtonsoft;  
 using System.Net;  
 using System.Web;  
 using System.IO;  
 using System.Configuration;  
 using System.Collections.ObjectModel;  
 using System.Dynamic;  
 namespace SalesforceREST  
 {  
   public partial class MainForm : Form  
   {  
     // Consumer Key from SFDC account  
     private string clientID = "YOUR CLIENT ID";  
     // Consumer Secret from SFDC account  
     private string clientSecret = "YOUR CLIENT SECRET";  
     // Redirect URL configured in SFDC account  
     private string redirectURL = "resttest:callback";  
     private string sfUserName = "SFDC USERNAME";  
     private string sfPassword ="SFDC PASSWORD";  
     private string sfSecurityToken = "SFDC SECURITY TOKEN";  
     private TokenResponse token;   
     public MainForm()  
     {  
       InitializeComponent();  
     }  
     private void MainForm_Load(object sender, EventArgs e)  
     {    
       // Build authorization URI  
       var authURI = new StringBuilder();  
       authURI.Append("https://test.salesforce.com/services/oauth2/authorize?");  
       authURI.Append("response_type=code");  
       authURI.Append("&client_id=" + clientID);  
       authURI.Append("&redirect_uri=" + redirectURL);  
     }  
     private void GetToken()  
     {    
       // Create the message used to request a token  
       string URI = "https://test.salesforce.com/services/oauth2/token";  
       StringBuilder body = new StringBuilder();  
       body.Append("grant_type=password&");  
       body.Append("client_id=" + clientID + "&");  
       body.Append("client_secret=" + clientSecret + "&");  
       body.Append("username=" + sfUserName + "&");  
       body.Append("password=" + sfPassword + sfSecurityToken);  
       string result = HttpPost(URI, body.ToString());  
       // Convert the JSON response into a token object  
       JavaScriptSerializer ser = new JavaScriptSerializer();  
       token = ser.Deserialize<TokenResponse>(result);  
       var uri = token.instance_url + "/services/data/v20.0/sobjects/Account/";  
       var acct = new sfdcAccount();  
       acct.Name = AccountName.Text;  
       acct.Type = AccountType.Text;  
       acct.AnnualRevenue = AnnualRevenue.Text;  
       acct.Fax = Fax.Text;  
       acct.Phone = Phone.Text;  
       var serr = new JavaScriptSerializer();  
       var bodyy = serr.Serialize(acct);  
       var reeq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);  
       reeq.Headers.Add("Authorization: OAuth " + token.access_token);  
       reeq.ContentType = "application/json";  
       reeq.Method = "POST";  
       byte[] data = System.Text.Encoding.ASCII.GetBytes(bodyy);  
       reeq.ContentLength = bodyy.Length;  
       var oss = reeq.GetRequestStream();  
       oss.Write(data, 0, data.Length);  
       oss.Close();  
       WebResponse resp;  
       try  
       {  
         resp = reeq.GetResponse();  
       }  
       catch (WebException ex)  
       {  
         resp = ex.Response;  
       }  
       string test;  
       if (resp == null) test = null;  
       System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());  
       test = sr.ReadToEnd().Trim();   
       // Read the REST resources  
       string s = HttpGet(token.instance_url + @"/services/data/v20.0/", "");  
       UIResults.Text = s;  
       UIResults.Text = result;  
       UIResults.Text = test;  
     }  
     public string HttpPost(string URI, string Parameters)  
     {  
       System.Net.WebRequest req = System.Net.WebRequest.Create(URI);  
       req.ContentType = "application/x-www-form-urlencoded";  
       req.Method = "POST";  
       // Add parameters to post  
       byte[] data = System.Text.Encoding.ASCII.GetBytes(Parameters);  
       req.ContentLength = data.Length;  
       System.IO.Stream os = req.GetRequestStream();  
       os.Write(data, 0, data.Length);  
       os.Close();  
       // Do the post and get the response.  
       System.Net.WebResponse resp = req.GetResponse();  
       if (resp == null) return null;  
       System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());  
       return sr.ReadToEnd().Trim();  
     }  
     public string HttpGet(string URI, string Parameters)  
     {  
       System.Net.WebRequest req = System.Net.WebRequest.Create(URI);  
       req.Method = "GET";  
       req.Headers.Add("Authorization: OAuth " + token.access_token );  
       System.Net.WebResponse resp = req.GetResponse();  
       if (resp == null) return null;  
       System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());  
       return sr.ReadToEnd().Trim();  
     }  
     private void InsertAccountBtn_Click(object sender, EventArgs e)  
     {  
       GetToken();  
       clearall();  
     }  
     public void clearall()   
     {  
       AccountName.Text = "";  
       AccountType.Text = "";  
       AnnualRevenue.Text = "";  
       Fax.Text = "";  
       Phone.Text = "";  
     }  
   }  
   public class TokenResponse  
   {  
     public string id { get; set; }  
     public string issued_at { get; set; }  
     public string refresh_token { get; set; }  
     public string instance_url { get; set; }  
     public string signature { get; set; }  
     public string access_token { get; set; }  
   }  
   public class sfdcAccount  
   {  
     public string Name { get; set; }  
     public string Type { get; set; }  
     public string AnnualRevenue { get; set; }  
     public string Phone { get; set; }  
     public string Fax { get; set; }  
   }  
 }  

The record is successfully created in Salesforce. You can verify the ids from above error log and URL.


Feel free to post questions and suggestions. Cheers !  

3 comments:

  1. plz let me know that how did u take sfSecurityToken

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Hii Wahib, i got sfSecurity token and application is also working fine....
      Could you plzz give an idea about how to retrieve this inserted data from salesforce to our application..
      Iam new to salesforce...plz revert back...
      Thanks in advance..

      Delete