How to Connect Salesforce API With C#


This article explains how to connect to or integrate with Salesforce with C#. The platform tightly integrates with the Microsoft .NET technologies via the SOAP API that lets you access and manipulate your data and functionality in the cloud. is a cloud computing platform as a service system from that developers use to build multitenant applications hosted on their servers as a service.

Integrating Salesforce with C#

It is easy to connect to or integrate with the Salesforce API with any platform. In this article, we will learn how to invoke the Salesforce API with two types of WSDL. We need to connect to a custom method for developing in developer org. 
  • Enterprise WSDL: This API is for users developing client applications for their organization.
  • Partner WSDL: This API is for partners who are developing client applications for multiple organizations. 
Here is the procedure to connect Salesforce with C#.
Step 1: We need to create a developer account to access any API, custom objects or methods from the org. You can create a developer account from the following link. 
Step 2:  Connect with the org using your credentials. Once you connected with the org, next we will create a method to get the details of the lead object.
To create a method in the class go to Setup (under the user name drop down or beside the help menu top right corner) -> Develop -> Apex Classes -> New.
We need to get the lead details based on email. Hence, create a method as shown in the following screen shot in the apex class. To access other platforms we need to use the global keyword to declare the class and use the webservice keyword for the method.

Step 3:
 Once a method is created in Salesforce, create a new website or project in Visual Studio 2010/2012/2013. Add a web form to display the lead object details. 
Add web form
Step 4: Add control in the newly created webform. The user can enter an email id in the TextBox based on email and other relevant lead details displayed in a different label as shown in the following screenshot.

newly created webform

Step 5 : Next you need to get the URL to the WSDL file, that we'll add to our project in Visual Studio to generate the web service proxy. To get this, expand the Develop section on the left hand side in your salesforce org. Then click on Apex Classes. You can see our created custom method (getLeadInfo). Click on the WSDL link and copy it (it'll be something like*).
WSDL link 
Step 6 : After the getting WSDL link, first we'll need to add a reference to our WSDL from Salesforce to generate the webservice proxy. Right-click on References in the Solution Explorer and select Add Service Reference. Click Advanced (bottom left on dialog box). Then Add Web Reference. Paste the URL from Step 5 above into the URL box and click the green arrow. You'll probably be prompted to login to Salesforce. Once that's done, you should see the WSDL or service method summaries in the window. On the right hand side, under “Web Reference Name”, type LeadService and click Add Reference.
Add Reference

Step 7 :
 After adding Leadservice to your project, you need to do same steps to add a partner WSDL to your project. The Partners WSDL, who wish to get an OAuth consumer Id for authentication, can contact The Partner WSDL can send requests to the enterprise endpoint. Assign the session Id to the SOAP header for subsequent calls.
You need to get the partner URL. To get this, expand the Develop section on the left hand side in your Salesforce org. Then click on API.You can see list if WSDL. Find the Partner WSDL. Click on the Generate Partner WSDL link and copy it (it'll be something like*). You can see same as shown in following screenshot.
screen shot 
Step 8:After adding the webreference of the enterprise and partner WSDL, we will go through the code snippet to authenticate with Salesforce. 

Authenticating and Creating a Session

1. Capture a user name and password: These values can be hardcoded as part of your application's .config files, stored in a database for retrieval, or passed to the API via values collected from the application user. In this example, the username and password are simply hard-coded as string variables within the application. You need to append the password with your security token.
A security token is an automatically generated key that you must add to the end of your password to log into Salesforce from an untrusted network. For example, if your password is mypassword and your security token is XXXXXXXXXX, then you must enter mypasswordXXXXXXXXXX to log in. Security tokens are required whether you log in via the API or a desktop client such as Connect for Outlook, Connect Offline, Connect for Office, Connect for Lotus Notes, or the Data Loader.
For more details refer to the following link:
  1. // User ID   
  2. private string userID = "[email protected]";  
  3. // Password + token  
  4. private string password = "somecomplexpassword";  
2. Once the username and password values are established, they are passed to the API to determine if they are valid. As part of this validation, a binding to the API is established by instantiating a SforceService object. Once the binding is established, the result of the login attempt is returned in the form of a LoginResult object. Best practices also dictate this login attempt be wrapped in a try/catch block to allow for graceful handling of any exceptions that may be thrown as part of the login process
  1. /// <summary>  
  2. /// Authentication and Get Sessioninfo  
  3. /// </summary>  
  4. private void getSessionInfo()  
  5. {  
  6.     // Initilize salesforce partner service  
  7.     PartnerService.SforceService partnerService = new PartnerService.SforceService();  
  8.     PartnerService.LoginResult lr = new PartnerService.LoginResult();  
  10.     // Pass userid and password in login method  
  11.     lr = partnerService.login(userID, password);  
  12.     _sessionId = lr.sessionId;  
  13.     Session["_sessionId"] = lr.sessionId;  
  14.     Session["_serverUrl"] = lr.serverUrl;  
  15.     Session["_nextLoginTime"] = DateTime.Now;  
  16. }  
You can avoid calling the partner WSDL every time if the user is already connected with that session. For this you can make a method that checks whether or not  a connection exists. 
  1. /// <summary>  
  2. /// Check whether session connected or not  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. public bool IsConnected()  
  6. {  
  7.     bool blnResult = false;  
  8.     if (!string.IsNullOrEmpty(_sessionId) & _sessionId != null)  
  9.     {  
  10.         if (DateTime.Now > _nextLoginTime)  
  11.             blnResult = false;  
  12.         else  
  13.             blnResult = true;          
  14.     }  
  15.     else  
  16.         blnResult = false;  
  18.     return blnResult;  
  19. }  
Step 9: Once you get a session id, now you can call your actual method that we created in Step 2. Create an object of the enterprise service proxy class and pass a session id that we have stored in a session object. We wrote this code on a button click event for the lead details based on email id. You can see the code snippet as follows.
  1. /// <summary>  
  2. /// Get Lead details   
  3. /// </summary>  
  4. /// <param name="sender"></param>  
  5. /// <param name="e"></param>  
  6. protected void btnGet_Click(object sender, EventArgs e)  
  7. {  
  8.     // Check if it is already connected than no need to call partner service for get session id  
  9.     if (!IsConnected())  
  10.         getSessionInfo();  
  12.     LeadService.getLeadInfoService leadService = new LeadService.getLeadInfoService();  
  14.     // Pass session id to lead service  
  15.     leadService.SessionHeaderValue = new LeadService.SessionHeader();  
  16.     leadService.SessionHeaderValue.sessionId = _sessionId;  
  18.     LeadService.Lead getLeadInfoResponse = new LeadService.Lead();  
  19.     getLeadInfoResponse = leadService.getLeadAddressByEmail(Convert.ToString(txtEmailVal.Text));  
  20.     this.lblAddressVal.Text = getLeadInfoResponse.Street.ToString();  
  21.     this.lblCityVal.Text = getLeadInfoResponse.City.ToString();  
  22.     this.lblStateVal.Text = getLeadInfoResponse.State.ToString();  
  23.     this.lblZipVal.Text = getLeadInfoResponse.PostalCode.ToString();  
  24. }  
Step 10: Now to build the project. Press F5 to run your project. Enter an email id in the TextBox to get the lead details. You can see the lead details shown in the label in the following screenshot.


This article explains how to integrate Salesforce with C#. We learned about partner and enterprise WSDLs. I hope this helps the developers who want to Integration with Salesforce using C#.
Reference link

Similar Articles