How to connect Salesforce with .NET console application using SOAP API?

This article mainly focusing on the basics about the integration with Salesforce and .NET console application via Salesforce SOAP Api.

So I would prefer to start it form Salesforce. 🙂 . And I think it would be easy if I continuing with Steps so the viewers can go through the steps easily.

Step 1 : Navigating to Enterprise WSDL from Salesforce.

Navigating to strongEnterprise WSDL/strong from Salesforce

You will be able to generate WSDL in Salesforce by Navigating to Setup -> Integrations -> API. Here you will be able to see different APIS which will be generating for different purposes. In order to do this you need to log in as an system administrator or as a user who has the “Modify All Data” permission. You will be able to see below APis.

  • Enterprise WSDL
  • Partner WSDL
  • Apex WSDL
  • Metadata WSDL
  • Tooling WSDL
  • Generate Tooling WSDL
  • Delegated Authentication WSDL
  • Client Certificate
  • Enterprise Package Version Settings
  • Partner Package Version Settings

We are focusing Enterprise WDSL in order to integrate with .NET and you want to know the difference between Enterprise and Partner WSDLs. I will describe other apis in my next posts.

The enterprise WSDL file is a strongly typed and It provides information about your organization's schema, data types, and fields. This WSDL changes if custom fields or custom objects are added to, renamed, or removed from the Salesforce org.

Partner WSDL  is a loosely-typed representation of the Salesforce object model and the partner WSDL can be used to access data within any organization. The nice thing of the partner WSDL is it does not contain metadata about objects and fields. So that objects , fields and schema changes will not affect for the WSDL representation.

We are using enterprise wsdl since we need strong typed representation for the developments because it's easy to use once we are doing the coding. (You can get intellisenses ). So our next step is to generate WSDL.

Step 2 : Generate Enterprise WSDL

You just need to click "Generate Enterprise WSDL" to to generate the wsdl. So you will be able to see xml file which is possible to download by clicking save as in the xml. And also we have another way of doing use wsdl file without saving the xml. For that you just need to copy the url.

Step 3 : Create a console application from Visual studio

Here I'm using visual studio community 2017 version which is free. It's good if you open visual studio as administrator. I will explain why later in this post. And create Console Application and I'm targeting for .Net framework 4.5 as below.

Create a console application from Visual studio

One thing I need to mention here regarding Salesforce disabling TLS 1.0 and Salesforce is requiring an upgrade to TLS 1.1 or higher beginning July 22, 2017, in order to align with industry best practices for security and data integrity.

This is the official announcement from Salesforce regarding SOAP API Version Retirement. https://help.salesforce.com/articleView?id=000221207&type=1

This is the official announcement from Salesforce regarding SOAP API Version Retirement

Since we are using .NET framework 4.5 we need small code modification to support TLS 1.1. If you are using .NET framework 4.6 it will automatically supports for TLS 1.1.

Step 4 : Add Salesforce service reference to the console application

Now we need to upload wsdl file which we generated earlier. For that we need to add the reference to console app. Just right click on Reference and click on Add service reference. Then click on Advanced button in the popup and click on Add Web Reference in the next popup.

sr
refer
 
And our next step would be pasting the WSDL URL which we copied earlier from Salesforce. You can give the local path to the url if you downloaded the wsdl to your local mechine. For this you must open visual studio as administrator. I think the better option would be copying the wsdl enterprise url from Salesforce and pasting here. Once you click on go icon you might ask to login to Salesforce. After that you will be able to see below screen.
WSDL URL which we copied earlier from Salesforce
Give a proper web reference name and click on Add Reference button. (my case I used com.salesforce.enterprise namespace and if you use same namespace you just need to copy the  below code without any modification in order to connect with Salesforce. ). After that there will be adding other related references automatically to the console application project.

Step 5 : Coding in Visual Studio

Below I have added the full integration code block which will retrieve top 10 lead records from Salesforce.

Program.cs class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using EnterpriseWSDL.com.salesforce.prasad;
namespace EnterpriseWSDL
{
    class Program
    {
        static void Main(string[] args)
        {
            SforceService SfdcBinding = null;
            LoginResult CurrentLoginResult = null;
            SfdcBinding = new SforceService();
            try
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                CurrentLoginResult = SfdcBinding.login(Constants.USERNAME, Constants.PASSWORD + Constants.TOKEN);
                SfdcBinding.Url = CurrentLoginResult.serverUrl;
                SfdcBinding.SessionHeaderValue = new SessionHeader();
                SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
                QueryResult queryResult = null;
                String SOQL = "";
                SOQL = "select FirstName, LastName, Phone from Lead LIMIT 10";
                queryResult = SfdcBinding.query(SOQL);
                if (queryResult.size > 0)
                {
                    for (int i = 0; i < queryResult.records.Length; i++)
                    {
                        Lead lead = (Lead)queryResult.records[i];
                        string firstName = lead.FirstName;
                        string lastName = lead.LastName;
                        string businessPhone = lead.Phone;
                        Console.WriteLine("First Name " + firstName + ", Last Name " + lastName + ", Phone " + businessPhone);
                    }
                }
                else
                {
                    Console.WriteLine("No records returned.");
                }
            }
            catch (System.Web.Services.Protocols.SoapException e)
            {
                // This is likley to be caused by bad username or password
                SfdcBinding = null;
                Console.WriteLine("SOAP Exception occured " + e.Message.ToString());
            }
            catch (Exception e)
            {
                // This is something else, probably comminication
                SfdcBinding = null;
                Console.WriteLine("Exception occured " + e.Message.ToString());
            }
        }
    }
}

Constants.cs Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnterpriseWSDL {
    public static class Constants {
        public static string USERNAME = "REPLACE WITH YOUR USERNAME";
        public static string PASSWORD = "REPLACE WITH YOUR PASSWORD";
        public static string TOKEN = "REPLACE WITH YOUR SECURITY TOKEN";
    }
}

I have added Constant.cs class in order to keep separate the login information.So you have almost done with the coding. Build the project and run your console app. Probably y get below error while you running the application.

Constant.cs class

The reason for the issue is, Reference.cs file which is automatically generated by Visual Studio has [][] characters. It is a bug and still not fixed. But there's a workaround for this issue. You just need to search [][] in Visual studio and you will be able to find [][] characters in two locations in the Reference.cs file.  Replace [][] with [] and you will resolve the issue. Run the application again.

You have done everything that you need to retrieve lead objects from Salesforce using Enterprise WSDL. 🙂

Here I will explain about the .NET code further.

SforceService SfdcBinding = null;
LoginResult CurrentLoginResult = null;
SfdcBinding = new SforceService();

Integration with Salesforce established by instantiating an SforceService object. Once the binding is established, the result of the login attempt is returned in the form of a LoginResult object.

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

Directly enabling TLS 1.1 and TLS 1.2 in the code

CurrentLoginResult = SfdcBinding.login(Constants.USERNAME, Constants.PASSWORD + Constants.TOKEN);

Login to the system and getting login result object which will contain lots of information about the session and org details.

SfdcBinding.Url = CurrentLoginResult.serverUrl;

Get the binding URL from the WSDL

SfdcBinding.SessionHeaderValue = new SessionHeader();

Setting up the header value for the HTTP request.

SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;

Setting up the session Id in the header from the login result object

QueryResult queryResult = null;

Setting up the object which will hold the retrieved data from Salesforce.

String SOQL = "";
SOQL = "select FirstName, LastName, Phone from Lead LIMIT 10";
queryResult = SfdcBinding.query(SOQL);

Execute the SOQL query and get lead data

if (queryResult.size > 0) {
    for (int i = 0; i < queryResult.records.Length; i++) {
        Lead lead = (Lead)queryResult.records[i];
        string firstName = lead.FirstName;
        string lastName = lead.LastName;
        string businessPhone = lead.Phone;
    Console.WriteLine("First Name " + firstName + ", Last Name " + lastName + ", Phone " + businessPhone)
}

Print the lead data in the console application. Please share your comments and thoughts and if you have any doubts please let me know. Probably my next article would be the partner WSDL. If you need you can find the source code of this project from here https://github.com/prasadruwanpathirana/salesforce-.net-integration-soap-api.git

Popular Salesforce Blogs