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