Salesforce Integration with Microsoft.NET using SOAP API
Introduction
Salesforce has set of APIs for
different purposes such as REST API
for accessing objects in Salesforce, SOAP
API for Integrating Salesforce with other applications, Tooling API for building custom
development tools for Salesforce applications, Chatter REST API for accessing Salesforce Chatter feeds and social
data, Bulk API for loading or
deleting large numbers of records in Salesforce, Metadata API for managing customizations in Salesforce and building
tools to manage metadata model, Streaming
API for providing a stream of data reflecting data changes in Salesforce, Apex REST API for building REST API in
Apex, Apex SOAP API for creating custom SOAP Web services in Apex
and finally Data.com API for
Data.com providing 100% complete, high
quality data, updated in real-time in the cloud.
SOAP
API is simple, powerful, and secure application programming interface
to integrating salesforce with Microsoft .NET which allows to manipulate
Salesforce data with more than 20 different calls so, let see how it does with C#.NET.
Salesforce Integration with Microsoft.NET
First, it requires to establish a
bridge in between Salesforce organization and the Microsoft.NET application and
to do so, we must generate the Web Services Description Language (WSDL) file which describes
how the web service can be used. Once
logged into the Salesforce organization, navigate to following route to
generate the WSDL.
Setup à Develop à API à Then choose the appropriate WSDL and generate it
In the API section there
are Enterprise, Partner, Apex, Metadata and Tooling WSDLs and for accessing
standard and custom object records we can either use Enterprise WSDL which is strongly typed and integrates only single
Salesforce organization or Partner WSDL
which is loosely typed and integrates multiple Salesforce organizations.
We may download the preferred
WSDL if we are planning to create the bride as a service reference but since
the description could be changed when creating new objects or adding new fields
to existing objects, it is better to create the bride as a web reference so, we
just need the web address of the generated WSDL which is the browser URL. Let’s
see how we can do this in Visual Studio 2017.
Open the Visual Studio 2017 and follow the following steps.
Project à
Add Service Reference
à Advance à
Add Web Referenceà
Locate the WSDLà Log in to Salesforceà Add Reference
Once you done with the
referencing the web service then we can move to coding part and all the
relevant meta data of the web service is stored in the App.config and Settings.settings which we can change dynamically
at run time, whenever it requires to change the source of the Salesforce
organization.
Now let see how we can connect to
Salesforce with SOAP API in C#.Net.
SforceService sfLoginClient = new SforceService ();
// Connect with Salesforce credentials (You may not need to
provide security token when you specify a login IP range)
LoginResult sfLoginResult
= sfLoginClient.login(USERNAME, PASSWORD+SECURITY_TOKEN);
// Reset the Destination or Endpoint URL
sfLoginClient.Url = sfLoginResult.serverUrl;
// Set the session header
sfLoginClient.SessionHeaderValue = sfLoginResult.sessionId;
You should handle exceptions in
case of unable to authenticate, password expired or any other run time
exceptions and let’s move to query Salesforce records by assuming all is well
up to now.
QueryResult sfQueryResult
= sfLoginClient.query(SOQL_QUERY);
Once you execute the query method
with the correct SOQL, you will get the query result but in Salesforce default
batch size 500 which means you will get only 500 records if you not specified
it. Even though you specified the maximum batch size is 2000 and this is also
not guaranteed. So, let see how we can do this.
You need to write the below code block
before you execute the above-mentioned query method.
sfLoginClient.QueryOptionsValue
= new QueryOptions();
sfLoginClient.QueryOptionsValue.batchSize
= INTEGER_BATCH_SIZE;
sfLoginClient.QueryOptionsValue.batchSizeSpecified
= true;
When you need to move to next
query set, just call the below line of code.
sfQueryResult
= sfLoginClient.queryMore(sfQueryResult.queryLocator);
You can get the returned records
to sObject array but executing the following code line.
Object[]
sfRecords = sfQueryResult .records;
You can use the following code block to loop through
the record set and retrieve the field values and with the same manner you can
set the values for the desired fields.
foreach (sObject record in sfRecords)
{
XmlElement[] elements = record.Any; // Get
the xml which holds the values
for
(int i = 0; i < elements.Length; i++)
{
//elements[i].LocalName à give you the field name
//elements[i].InnerText)à give you the
field value
}
}
Let’s see how we can perform Insert, Update, Upsert
and Delete Salesforce data. Generally, we can create new sObject and perform
Insert, Update or Upsert operations as shown below.
Account acc = new Account();
Acc.Name = “Account Virath”;
SaveResult[] sfCreateResult = sfLoginClient. create(new sObject[] { acc }); // Insert Record
Acc.Id = ID; // Specify the
relevant ID
Acc.Name = “Account Virath Chinthaka”;
SaveResult[] sfUpdateResult = sfLoginClient.update(new sObject[] { acc }); // Update
Record
// Specify the relevant ID if it is an Update, otherwise no need
to set it which will create a new record
Acc.Id = ID;
Acc.Name = “Account Virath Chinthaka Liyanage”;
// For Upsert method. it requires to set the external Id field
UpsertResult[] sfUpsertResult = sfLoginClient. upsert (EXTERNAL_ID, new
sObject[] { acc });
We can check whether the
operation is successful by property: success
in the 0th index of the result array and we can get the error
message as shown below.
if
(!sfUpsertResult [0].success)
{
throw new
Exception(sfUpsertResult [0].errors[0].message);
}
If it sent more than one sObject where
we can send max 200 records per time, then we can loop result array and see
whether all are successful or has errors. Also, we can Insert, Update or Upsert
records dynamically and in that case, we should instantiate new sObject and set
the entity type as shown below.
sObject
sfRecord = new sObject();
sfRecord.type
= ENTITY_TYPE; // Object Type in String. E.g.:- “Account”
Then set the values like shown below.
XmlDocument doc
= new XmlDocument();
// Specify the field name correctly otherwise it will raise an
error while pushing it to Salesforce
XmlElement
newField = doc.CreateElement(FIELD_NAME);
// Specify the field value in String format
newField.InnerText
= FIELD_VALUE;
// If you already have values specified then make sure you
append it
sfRecord.Any =
new XmlElement[] { newField };
We can delete Salesforce records
by specifying the relevant Ids as shown below and that’s it!
DeleteResult[] sfDeleteResult
= sfLoginClient.delete(new String[]
{ ID_1, ID_2, … });
Conclusion
The aim of this blog is to share how we
can connect to Salesforce organization from .NET platform and manipulate Salesforce
data where we can perform select, insert, update and delete operations.
Comments
Post a Comment