Skip to main content

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.
1st Step : Navigating to Enterprise WSDL from Salesforce.
wsdl
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.
vs1
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
5
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.srservice_ref webreAnd 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.3Give 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.4
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 inmormation about the session and org details.
SfdcBinding.Url = CurrentLoginResult.serverUrl;
Get the binding url from the wdsl
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.
Thank you very much,
Prasad

Comments

Popular posts from this blog

Exploring the Marvels of Salesforce Marketing Cloud: Unleashing the Power of Marketing Automations

Salesforce Marketing Cloud is a comprehensive marketing automation platform offered by Salesforce, a leading customer relationship management (CRM) company. It is designed to help businesses manage and optimize their marketing efforts across various channels and touchpoints. The platform enables organizations to create, execute, and analyze marketing campaigns to engage with their target audiences more effectively and drive better results. Key features and capabilities of Salesforce Marketing Cloud include: Email Marketing: Users can create and send personalized email campaigns to segmented audiences, track email performance metrics, and automate email workflows to nurture leads and build customer relationships. Journey Builder: This tool allows marketers to design and automate customer journeys across multiple channels such as email, mobile, social media, and advertising. It helps create personalized experiences based on customer behavior and interactions. Social Media Marketing: Sale

Salesforce Metadata API

In this post I'm going the cover basics in the Metadata API and how it can connect with a .net console application. Then after I will show you how to create a custom object and create fields by using the metadata api from the console app. What is Salesforce Metadata API There are many things can be done from the metadata api. you can create Objects,Fields,Validation,Workflows, Profiles, Reports for a particular client organization just by running the piece of code so that you need not do all the customization settings manually which will consume time if you have to do that several times for different clients for the same configuration settings. You can also take the backup of your organization customization settings just by fetching the metadata WSDL from your Salesforce org. You can read, create, update, delete following components in a Salesforce organization. Custom Objects/Fields. Visualforce pages. Page Layouts. Validation rules. Apex. Workflows. Approval processe

Salesforce REST API

This post describe about the salesforce rest api and using salesforce rest api . Salesforce implements the OAuth to authenticate soap and rest calls with the client. So I will describe with the simple steps, how to create salesforce app that expose outside to authenticate and call rest methods. First you need to create a salesforce developer account if you don't have an developer account or sandbox account. If you don't have an developer account go with the following link and create an account. It's free.   https://developer.salesforce.com/signup . Once you create the developer account go to https://login.salesforce.com/ and login with your credentials.     Navigate to setup and type app and you will be able to find Apps section and click the link. So now you will be able to find Connected Apps section and click New. What we doing here is creating a connected app and that app will exposing to outside to authenticate and call rest api calls. So you can insert C