As advertised, Salesforce (Force.com or SFDC) is Number one on demand CRM and is currently a very hot technology in IT industry. Through SOAP APIs, Salesforce tightly integrates with various back-end technologies like .NET & JAVA, which lets you, access and manipulates your data and functionality in the Force.com cloud. Behind the scenes, SFDC follow MVC design pattern with Objects, Fields, Relationships comes under Model Layer; Visual Force pages, Page Layouts, Tabs comes under View Layer and Workflows, Apex Classes, Triggers comes under Controller of Model View Controller, Apart from this, just like SQL, offers Salesforce’s official Object Query Language (SOQL) that lets you access anything about any record in your Salesforce database.
We can leverage Force.com SOAP API to integrate the Force.com platform with Microsoft .NET application with ease with below steps:
Step 1: Generate the WSDL
Salesforce automatically generates & maintains the WSDLs. Whatever objects we are creating or already there in Salesforce, it will be automatically available to partner/enterprise WSDL. You need to login to Salesforce & download the appropriate WSDL from navigation path: Setup >> Develop >> API >> Click on ‘Generate’
Step 2: Generate Security Token for API access
In order to access the Salesforce API, we need to provide our login email, password, and the security token. A security token is an automatically-generated key from Salesforce. We can change the Security token via the Salesforce user interface. Changing password automatically sends a new security token to the email address on the user’s Salesforce record or user can do the same using Salesforce interface resetting of security password.
To get the token we need to go to Personal Settings section of the Salesforce platform. Click on the Username on right top corner of the page >> My Settings >> Personal >> Reset My Security Token.
Step 3: Referencing WSDL from .NET application
Add the reference to WSDL file (downloaded in Step#1) to your project in Visual Studio through “Add Service Reference“.
Right click on project and choose ‘Add Service Reference’ option from menu.
You can encounter an error with .Net integration for ListViewRecord and ListViewRecordColumn from Salesforce API.
Unable to generate a temporary class (result=1). error CS0030: Cannot convert type 'Salesforce.Net.Web.SDF.ListViewRecordColumn[]' to 'Salesforce.Net.Web.SDF.ListViewRecordColumn'
To fix this issue we need to go to the dynamically generated file ‘Reference.cs’ file while adding our Web reference to the enterprise WSDL. Open the file and replace all ‘ListViewRecordColumn[][]’ strings to only ‘ListViewRecordColumn[]’.
Step 4: Authenticate and Create Salesforce API Session in .Net
You can now use objects of classes “SforceService” and “LoginResult” to connect to Salesforce API.
string userName = ""; string password = ""; string securityToken = ""; SforceService sfdcBinding = null; LoginResult currentLoginResult = null;
Initialize credantial information containing Username, Password & Security Token.
public BLConnectSF(string UserName, string Password, string SecurityToken) { this.userName = UserName; this.password = Password; this.securityToken = SecurityToken; }
Authenticate & Create connection to Salesforce API.
private void OpenConnection() { GetUserInfoResult result = null; sfdcBinding = HttpContext.Current.Session["SFDC_BINDING"] as SforceService; if (sfdcBinding == null) { ReAuthenticate(); } else { try { //Check if Session is valid result = sfdcBinding.getUserInfo(); } catch (System.Web.Services.Protocols.SoapException ex) { ReAuthenticate(); } catch (Exception ex) { ReAuthenticate(); } } } void ReAuthenticate() { sfdcBinding = new SforceService(); try { currentLoginResult = sfdcBinding.login(userName, password + securityToken); } catch (System.Web.Services.Protocols.SoapException ex) { //Most likely, Bad username/password log.Error(ex.Message); sfdcBinding = null; throw (ex); } catch (Exception ex) { log.Error(ex.Message); //Probably communciation issue sfdcBinding = null; throw (ex); } //Change the binding to the new endpoint sfdcBinding.Url = currentLoginResult.serverUrl; //Create a new session header object and set the session id to that returned by the login sfdcBinding.SessionHeaderValue = new SessionHeader(); sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId; HttpContext.Current.Session["SFDC_BINDING"] = sfdcBinding; }
Step 5: Perform CRUD operations
Once you are able to connect with Salesforce API, you can use three kinds of array-based objects to perfrom all CRUD operations:
- SaveResult – is returned with the insert and update database methods.
- DeleteResult – is returned with the delete database method.
- QueryResult – will hold array of records as results on successful execution of the query string.
Rest is quite straightforward, you just have to right queries in SOQL for SELECT, INSERT, UPDATE & DELETE and play around these Result objects accordingly.
//SELECT RECORDS QueryResult queryResult = sfdcBinding.query("SELECT ContactId, Contact.FirstName, Contact.LastName, Contact.Email FROM CampaignMember WHERE CampaignId = 'ABC'"); if (queryResult.size > 0) { List contacts = new List(); for (int x = 0; x < queryResult.records.Length; x++) { Contact contact = new Contact(); CampaignMember cm = queryResult.records[x] as CampaignMember; contact.Id = cm.Contact.Id; contact.Email = cm.Contact.Email; contact.FirstName = cm.Contact.FirstName; contact.LastName = cm.Contact.LastName; contacts.Add(contact); } } //CREATE RECORDS Contact c = new Contact(); c.Email = Email; c.FirstName = FirstName; c.LastName = LastName; SaveResult[] createResults = sfdcBinding.create(new sObject[] { c }); if (createResults[0].success) { result = createResults[0].id; } else { result = createResults[0].errors[0].message; } //UPDATE RECORDS Contact c = new Contact(); c.Email = Email; c.Id = ContactId; c.FirstName = FirstName; c.LastName = LastName; SaveResult[] updateResults = sfdcBinding.update(new sObject[] { c }); if (updateResults[0].success) { result = updateResults[0].id; } else { result = updateResults[0].errors[0].message; } //DELETE RECORDS Contact c = new Contact(); c.Id = ContactId; SaveResult[] deleteResults = sfdcBinding.delete(new sObject[] { c }); if (deleteResults[0].success) { result = deleteResults[0].id; } else { result = deleteResults[0].errors[0].message; }
Enjoy integrating applications on Salesforce