Integrating salesforce SOAP API using C# .NET

Salesforce can be integrated with any .NET based application through the salesforce SOAP API. This article will show how to connect to salesforce and consume data within ASP.NET application hosted outside Salesforce.com.
Before we begin, there are a set of prerequisites that you need to get done in order to interact with salesforce API using the C# .NET.

  • Username and Password (salesforce logins)
  • SOAP API (WSDL file)
  • Security Token

Username and Password

You don’t need to use live company data and risk making a mess of things. You can register for a developer license in case you don’t have a user name and password at https://developer.salesforce.com/signup

SOAP API (WSDL file)

To get WSDL SOAP API, need to login salesforce and click “Set up” on right top Corner. Then go Develop > API and right click on “Generate Enterprise WSDL” under Enterprise WSDL (as we using “Enterprise WSDL” web service) and click on “Save Link as….” (Chrome browser) to save (enterprise.wsdl) file to somewhere in your computer.

SalesforceSOAPAPI

Security Token

My Setting > Personal > Reset My Security Token

SaleforceSecurityToken

.NET Application

Let’s start exploring the SOAP API functionality by creating a sample .Net application and connect into Salesforce. Here are the steps that can be taken to setup the Enterprise WSDL:

Create new ASP.NET Empty Web Site
Adding a Web Service Reference to website

Right click on Website root (Solution Exploere) and select “Add Service Reference”.

addsalesforcesoapapi
Click “Advanced..”
12
Click “Add Web Reference…”

123
In Add Web Reference dialog type path of saved “enterprise.wsdl” file in URL: and click “Enter” then change Web reference name to “SFDC” then click “Add Reference” (As show in below image).

1234
Now Salesforce SOAP API added into our website

12345

Now that the base website is created and a reference setup to the Enterprise WSDL, we can transition to writing code that calls the API.

The first step is to have Salesforce authenticate us as a user. Once the authentication with Salesforce is successful, additional authentication information, such as the Session ID and URL will be returned. This information is needed for subsequent API calls. The Session ID can be cached in your application for periods less than the timeout period. Go to “Setup > Security Controls > Session Settings” to see what your timeout is. For this sample, caching was omitted to keep things simple. Here is example code showing how to authenticate against Salesforce

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SFDC;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string userName = "[email protected]";
        string password = "xxxxxx";
        string securityToken = "xxxxxxxxxxxxxxx";
 
        SforceService sfdcBinding = null;
        LoginResult currentLoginResult = null;
        sfdcBinding = new SforceService();
        try
        {
            currentLoginResult = sfdcBinding.login(userName, password+securityToken);
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
            // This is likley to be caused by bad username or password
            sfdcBinding = null;
            throw (ex);
        }
        catch (Exception ex)
        {
            // This is something else, probably comminication
            sfdcBinding = null;
            throw (ex);
        }
 
 
        //Change the binding to the new endpoint
        sfdcBinding.Url = currentLoginResult.serverUrl;
 
        //Create a new session header object and set the session id to that returned by the login
        sfdcBinding.SessionHeaderValue = new SessionHeader();
        sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;
 
    }
}

That’s it! You have just successfully logged in to the salesforce API and created a valid session to conduct further operations on the salesforce. The sfdcBinding variable now contains the end point URL where further web service interactions will take place, as well as the session. The following code will use this to create, retrieve, update and delete data of product from .NET.

INSERT Product

Product2 insertProduct = new Product2();
        insertProduct.IsActive = true;
        insertProduct.IsActiveSpecified = true;
        insertProduct.Name = "Test Product";
        insertProduct.ProductCode = "Test";
 
        Response.Write("Name:" + insertProduct.Name);
        Response.Write("<br/>ProductCode:" + insertProduct.ProductCode);
 
        SaveResult[] createResults = sfdcBinding.create(new sObject[] { insertProduct });
      
        if (createResults[0].success)
        {
           string id = createResults[0].id;
            Response.Write("<br/>ID:" + id);
            Response.Write("<br/>INSERT Product Successfully!!!");           
        }
        else
        {
            string result = createResults[0].errors[0].message;
            Response.Write("<br/>ERROR:" + result);
        }

Query Products

        QueryResult queryResult = null;
        String SOQL = "";
        string productid = "";   
        SOQL = "select Id from Product2 where ProductCode = 'Test'";
        queryResult = sfdcBinding.query(SOQL);
 
        if (queryResult.size > 0)
        {
            //put some code in here to handle the records being returned
            int i = 0;
            Product2 readProduct = (Product2)queryResult.records[i];
            string productName = readProduct.Name;           
            productid = readProduct.Id; // save id show we can use in update and delete product
            Response.Write("Product Found!!<br/>");
            Response.Write("Name:" + readProduct.Name);
            Response.Write("<br/>ProductCode:" + readProduct.ProductCode);
            Response.Write("<br/>ID:" + readProduct.Id);           
        }
        else
        {
            //put some code in here to handle no records being returned
            string message = "No records returned.";
            Response.Write("<br/>" + message);
        }

UPDATE Product

        Product2 updateProduct = new Product2();
        updateProduct.Id = productid;
        updateProduct.Name = "Test Product 2";
 
        SaveResult[] updatedResults = sfdcBinding.update(new sObject[] { updateProduct });
 	
        if (updatedResults[0].success)
        {
            string id = updatedResults[0].id;
            Response.Write("<br/>ID:" + id); 
            Response.Write("Name:<br/>" + updateProduct.Name);          
            Response.Write("<br/>UPDATE Product Successfully!!!");
        }
        else
        { 
           string result = updatedResults[0].errors[0].message;
            Response.Write("<br/>ERROR:" + result);
        }

Delete Product

       DeleteResult[] deleteResults = sfdcBinding.delete(new string[] { productid });
 
        if (deleteResults[0].success)
        {
           string id = deleteResults[0].id;
           Response.Write("<br/>ID:" + id); 
            Response.Write("<br/>DELETE Product Successfully!!!");
        }
        else
        {
            string result = deleteResults[0].errors[0].message;
            Response.Write("<br/>ERROR:" + result);
        }

More info on SOAP API data model and method
https://www.salesforce.com/us/developer/docs/api/index_Left.htm#CSHID=sforce_api_calls_upsert.htm|StartTopic=Content%2Fsforce_api_calls_upsert.htm|SkinName=webhelp

Download Code
[wpdm_file id=6]

Thanks

Integrating salesforce Using the DeveloperForce Toolkit for .NET

Salesforce can be integrated with any .NET based application through the salesforce DeveloperForce Toolkits for .NET. This article will show how to connect to salesforce and manipulate data within ASP.NET application hosted outside Salesforce.com.

Salesforce SOAP base API

Salesforce can be integrated through the salesforce SOAP API (http://www.ashishblog.com/integrating-salesforce-soap-api-using-c-net/)

[ad#post]
Before we begin, there are a set of prerequisites that you need to get done in order to interact with salesforce using the DeveloperForce Toolkits for .NET.

Username and Password (salesforce logins)
Security Token
ConsumerKey and ConsumerSecret
DeveloperForce Toolkits for .NET

Username and Password

You don’t need to use live company data and risk making a mess of things. You can register for a developer license in case you don’t have a user name and password at https://developer.salesforce.com/signup
Security Token:
My Setting > Personal > Reset My Security Token

SaleforceSecurityToken

ConsumerKey and ConsumerSecret

The Consumer Key and Consumer Secret are available on the Connected App Details page.
Setup > Create > Apps > Connected Apps > New

connectedapps

Now fill Basic Information and API (Enable OAuth Setting) then Click ”SAVE

Salesforce ConsumerKey and ConsumerSecret

Salesforce Consumer Key Token page

DeveloperForce Toolkits for .NET

This Toolkit is open source and available on GitHub (https://github.com/developerforce/Force.com-Toolkit-for-NET). The easiest way to get this toolkit is to use the NuGet packages.

Install-Package DeveloperForce.Common
Install-Package DeveloperForce.Force

.NET Web Application

Let’s start exploring the DeveloperForce Toolkits for .NET functionality by creating a sample .Net web application.

Create new Project and select ASP.NET Empty Web Application in Visual Studio

To add DeveloperForce Toolkits for .NET, open up NuGet packages dialog and search “DeveloperForce”.

Saleforce_DeveloerForce.Force

Install “DeveloperForce.Force” as show in above image and “DeveloperForce.Common” will automatically install in our website as well.

Saleforce_DeveloerForce.Force_NuGet

Now that the base web Application is created and a reference setup to salesforce, we can transition to writing code that calls Salesforce data.

Here is example code showing how to authenticate using DeveloperForce Toolkits for .NET
[ad#post]

using System;
using System.Linq;
using System.Text;
using Salesforce.Common;
using Salesforce.Force; 
using System.Dynamic;
 
namespace AB_SalesForce_NET_Toolkits
{ 
public partial class Default : System.Web.UI.Page
{
    private static readonly string SecurityToken = "xxxxxxxxxxxxxxxxxxxxxxxx";
    private static readonly string ConsumerKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    private static readonly string ConsumerSecret = "xxxxxxxxxxxxxxxxxxx";
    private static readonly string Username = "[email protected]";
    private static readonly string Password = "xxxxxxxxxxxxx";
    private static readonly string IsSandboxUser = "false";

    protected async void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            var auth = new AuthenticationClient();
 
             // Authenticate with Salesforce              
                sb.Append("Authenticating with Salesforce");
                var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                    ? "https://test.salesforce.com/services/oauth2/token"
                    : "https://login.salesforce.com/services/oauth2/token";

                await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password + SecurityToken, ".net-api-client", url);
                sb.Append("<br/>"); sb.Append("Connected to Salesforce");

                var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);     
 
        }
        catch (Exception ex)
        {
            sb.Append("<br/>"); sb.Append(ex.Message);
                sb.Append("<br/>"); sb.Append(ex.StackTrace);

                var innerException = ex.InnerException;
                while (innerException != null)
                {
                    sb.Append("<br/>"); sb.Append(innerException.Message);
                    sb.Append("<br/>"); sb.Append(innerException.StackTrace);

                    innerException = innerException.InnerException;
                }
        } 
            Response.Write(sb.ToString());
    } 
}
}

That’s it! You have just successfully logged in to the salesforce and create ForceClient to conduct further operations on the salesforce. The following code will use this to create, retrieve, update and delete data of product from .NET.

Product Class:

public class Product2
    {
        public const String SObjectTypeName = "Product2"; 
        public String Id { get; set; }
        public String Name { get; set; }
        public String ProductCode { get; set; }
        public String Description { get; set; }
        public bool? IsActive { get; set; }
    }

More information on Salesforce object https://www.salesforce.com/us/developer/docs/api/index_Left.htm#CSHID=sforce_api_objects_product2.htm|StartTopic=Content%2Fsforce_api_objects_product2.htm|SkinName=webhelp

INSERT Product

Product2 insertProduct = new Product2();
insertProduct.IsActive = true;
insertProduct.Name = "Test Product x";
insertProduct.Description = "Test Product x";
insertProduct.ProductCode = "Testx"; 
insertProduct.Id = await client.CreateAsync(Product2.SObjectTypeName, insertProduct);
if (insertProduct.Id == null)
{
    sb.Append("<br/>"); sb.Append("Failed to create product record.");
 }
 else
 {
    sb.Append("<br/>Insert Product Successfully!!!");
 }

You can also use the dynamic ExpandoObject to build up an object.

  dynamic c = new ExpandoObject();
c.IsActive = true;
c.Name = "Test Product x";
c.Description = "Test Product x";
c.ProductCode = "Testx";
c.Id = await client.CreateAsync("Product2", insertProduct);

Query Products

var readProducts = await client.QueryAsync<Product2>("SELECT ID, Name,Description,ProductCode,IsActive FROM Product2 where ProductCode='Testx'");
  if (readProducts.totalSize > 0)
  {
      Product2 readProduct = readProducts.records[0];
      productid = readProduct.Id; // save id show we can use in update and delete product
      sb.Append("Product Found!!<br/>");
      sb.Append("Name:" + readProduct.Name);
      sb.Append("<br/>ProductCode:" + readProduct.ProductCode);
      sb.Append("<br/>ID:" + readProduct.Id);
   }
   else
   {
      //put some code in here to handle no records being returned
       string message = "No records returned.";
       sb.Append("<br/>" + message);
   }

UPDATE Product

var success = await client.UpdateAsync(Product2.SObjectTypeName, productid, new { Name = "Test Product 1" });
 if (!success)
 {
     sb.Append("<br/>"); sb.Append("Failed to update product!");
 }
 else
 {
     sb.Append("<br/>UPDATE Product Successfully!!!");
 }

Delete Product

success = await client.DeleteAsync(Product2.SObjectTypeName, productid);
  if (!success)
  {
      sb.Append("<br/>"); sb.Append("Failed to delete the product by ID!");   
   }
   else
   {
       sb.Append("<br/>DELETE Product Successfully!!!");
   }

[ad#post]

Error:

If you see below screen of death

error

Then Add Async =”True” on Design page.

error_Solution

Download Code:

[wpdm_file id=7]

Thanks