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 = "xxxxxxxxxxx@xxxxxxx.com";
    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