Force.com offers an industry-leading set of web service APIs that developers can use to interact with their cloud applications. The Microsoft .NET framework is widely used to build custom applications, and it also forms the foundational layer of Microsoft products such as Microsoft SharePoint. Developers have many reasons to integrate their .NET applications with Force.com data and business logic. This article walks through the techniques and best practices for consuming Force.com SOAP and REST services in .NET 4.5 applications.
Developers can access to a wide range of integration points exposed by the Force.com platform. These includes:
While this article focuses on using the out-of-the-box SOAP and REST APIs, all of these APIs – including custom Apex SOAP and Apex REST APIs – give .NET developers ample ways to interact with the Force.com platform.
Microsoft offers a range of technologies for creating and consuming web services. These include:
In general, Microsoft recommends using WCF for calling and creating SOAP services, the ASP.NET Web API for creating RESTful services, and the HTTPClient for calling web endpoints.
To start off with, consume the Force.com SOAP API from within Visual Studio 2012. One of the benefits of SOAP web services is that they have a WSDL that can be used to generate strongly-typed proxy objects. It works best to download a copy of the Force.com WSDL (instead of pointing to the online version), so navigate to the API page and save a copy of the Enterprise WSDL to your local hard drive.
After the WSDL file is saved locally, create a Visual Studio 2012 project and add a new Service Reference to the project by right-clicking the project and selecting Add Service Reference. Point to the Enterprise WSDL on your local hard drive and notice that the full set of Force.com operations are available. In this example, the service reference is named SfdcReference. This name is used throughout the project to refer to the objects included in the Enterprise API proxy.
Notice that after the service reference is added, a new entry is added to the project’s configuration file. The endpoint XML node holds the “ABCs” (address, binding, and contract) of the WCF proxy used to call the Force.com service. The web service address included in the Enterprise API points to https://login.salesforce.com/services/Soap/c/<version>. When the developer calls the login operation, they get back the web service URL to use for all the subsequent API operations.
This project’s WCF service reference can be used over and over again in the .NET project and gives the developer a strongly-typed set of objects to work with.
Consumers of the Enterprise API must authenticate themselves before accessing the data and functionality in Force.com. Once a security token is acquired, it is included in all subsequent API calls. The security token is associated with a single Force.com user account and all the access permissions associated with that account. For example, if a Force.com user is allowed to view Account records but cannot create them, then the same permission policy will apply if that user attempts to call the “create” API operation against the Account object. To read more about Force.com and the API security model, see the article entitled Security and the API in the Force.com developer documentation.
Also, don’t forget to make sure that the user record you plan to use with the Force.com API is actually enabled for API access. The Force.com user should be associated with a Profile that has API Enabled selected.
In the Visual Studio project, add the necessary using statement (with alias) to reference the Enterprise API types.
Next, add the necessary code to invoke the Force.com Login operation using the user name, password, and security token of the API-enabled user account. In the code below, notice that the developer is not exposed to the raw HTTP communication with Force.com when using the WCF proxy components. Consider wrapping the call to the Login operation in a try-catch block to capture any exceptions that are thrown by the login attempt.
Assuming that the login operation succeeds, the resulting payload contains both the session ID and the API service endpoint URL. Note that the session expires after two hours of inactivity (by default), and every time the API is called, the session inactivity timer is reset to 0.
With a valid session in hand, it’s time to interact with Force.com records through the API. Queries are executed in Force.com using the Salesforce Object Query Language (SOQL). This language bears a striking resemblance to traditional SQL queries and should be easy for developers to pick up. The results of the Query operation are stored in a QueryResult object and developers have access to a cursor reference (for large result sets), the returned records, and a size property that contains the count of records returned from the query.
In the code below, notice that the SessionHeader object is created and loaded with the session ID acquired from the Login operation. When using the WCF proxy object (instead of the legacy ASP.NET XML Web Services proxy object), there are many more parameters included in the Query operation. They are all useful, but the only required parameter is the SOQL query string.
The records property in the QueryResult object contains an array of base SObjects. Since the SOQL query calls for Account objects to be returned, the results can be cast to the Account type for easier access to object properties. In the case below, the results are cast using the IEnumerable.Cast<TResult> method, which doesn’t actually cast the object until it’s accessed by the enumerator.
Refer to SOAP Headers for more information about the SOAP headers used in this section's code samples.
At this point, you’ve successfully issued a secure query against Force.com using WCF proxy objects. What if you know exactly which record(s) you want returned? You can issue a SOQL query that returns a single record or records, or, a better option is to use the Retrieve operation. This applies to records that are all of the same Force.com object type and the developer has control over which object fields to return.
In the code below, notice that the Retrieve operation takes in an array of record IDs. This operation returns an array of SObjects that can be cast do the corresponding object type for easier access.
Querying Force.com is useful, but the Enterprise API supports much more than that. The Enterprise API supports a full set of operations, including query, retrieve, search, create, upsert, update, merge, delete, and much more. This next example walks through the steps to create a new record via the Enterprise API.
The Enterprise API provides us with strongly-typed objects for every out-of-the-box and custom object in your Force.com organization. The Create operation inserts objects (of different types, if you so desire) into the Force.com database. Below, see that an instance of the Account type is instantiated and populated with values. Be aware that an extra Boolean field is generated for each non-string field and if you do not set this value to "true,” then the corresponding field value won’t be sent to Force.com. For example, the Account object below has a field called AnnualReview that is of .NET data type “double.” Therefore, there is an additional field added to the strongly-typed Account object named AnnualReviewSpecified. For each non-string field that is set in an object, this additional field must be set as well or it won’t be included in the outbound SOAP message.
The result of the Create operation is stored in an array of SaveResult objects which contain the newly minted ID value for record, and success or failure indicators.
That’s all there is to it! You’ve now created a record in Force.com using the Enterprise API. The strong object typing makes development simpler, but comes at a cost. If the Force.com objects change in any way (e.g. new or deleted object fields, altered data types), then the Enterprise WSDL must get refreshed and your code might have to change. If you need more flexibility and adaptability to change, consider the Partner API.
The Partner API, as its name suggests, is primarily targeted at Force.com partners who build applications to be consumed by many organizations. They cannot afford to tightly couple to any one organization’s schema and need a more dynamic model to work with. The Partner API relies on a set of name-value pairs that are more forgiving and adaptable to change. The WSDL for the Partner API is downloaded from the same place as the Enterprise WSDL, and only needs to be referenced a single time by the consuming application. Notice below that when you add a Service Reference to the Partner WSDL, you can see the same set of API operations as what exists in the Enterprise WSDL.
After adding a WCF Service Reference to the Partner WSDL within your .NET project, notice that the corresponding application configuration file receives a new endpoint node that has the same URL address, but a different contract.
When calling the Partner API, your code will initially look very similar to the code for calling the Enterprise API. There are still strongly typed objects for interacting with the service endpoint, but the only difference is that none of the Force.com data objects are available. The developer works only with the base sObject type instead of concrete types like Account or Contact. Before jumping into the code that queries the Force.com database through the Partner API, add the necessary using statement (with alias) to the code.
The code below uses the same SOQL query as with the example above, but the code itself diverges from the Enterprise API example once the results of the query are returned. Instead of an sObject that can be cast to a strongly typed Force.com data object, the Partner API returns an sObject with an array of XmlElements that contain the object’s data. To access the object data, you can choose to use either of the two methods demonstrated below. Notice that the “acctName” variable is populated by pulling the XmlElement at the first index array. However, this is a bit brittle as it will break if the query is rewritten and the fields come back in a different order. An alternate approach uses LINQ to grab the XmlElement with a “name” attribute matching the Force.com field name. This approach has no dependency on field ordering and is a bit easier to read.
Refer to SOAP Headers for more information about the SOAP headers used in this section's code samples.
You have now successfully queried Force.com using the more flexible Partner API. As you saw, accessing object properties isn’t as straightforward as when you use the strongly-typed Enterprise API, but the Partner API makes it easier to build applications that can span organizations and tolerate change.
Much like the Enterprise API, the Partner API supports all the various CRUD (create-read-update-delete) operations on an object. In the code below, a new Account record is created in the Force.com database. There are a number of key things to be aware of when calling this API operation from .NET code. First, notice that you must create an array of XmlElements to hold all of the field values. An XmlElement object cannot be explicitly instantiated via the “new” keyword, and must be created from an underlying XmlDocument object. Note that you can choose to use the LINQ-friendly XElement class to build up the array of fields, but then you’d be responsible for converting that array to the XmlElement type in order to be compatible with the WCF proxy objects.
Once the array of XElements is populated with each desired Force.com field, the array is attached to the “Any” property of the sObject that is sent across the wire to Force.com. Observe that the Create operation accepts a wide range of optional parameters that control how the system behaves when accepting and processing the new record. Finally, like with the Enterprise API, the results of the operation are loaded into a SaveResult object array that can then be inspected to determine whether the operation succeeded or failed.
Now you’ve added a new record to your Force.com organization through the Partner API.
The Force.com SOAP APIs are a great choice when you have a development environment like Visual Studio that can consume a WSDL and provide a strongly-typed set of classes to work with. SOAP is also a good fit for relatively static Force.com organizations that don’t undergo a lot of changes to object definitions. You also saw that the WCF proxy for the Force.com SOAP APIs has operations that accept a wide range of (optional) headers that give you expansive control over the behavior of the system.
However, there are also great reasons to embrace the Force.com REST API, even when using Microsoft .NET and Visual Studio. REST is friendlier to mobile clients because of its lightweight message size and choice of either XML or JSON for data format. RESTful services also don’t enforce schemas that have to be updated every time the Force.com data model changes.
Next up, let’s look at how to consume the Force.com REST API from a .NET client application.
Much like the SOAP APIs offered by Force.com, the REST API requires users to be authenticated before accessing the data or functionality within the Force.com organization. While it is possible to reuse the SOAP-based authentication token for REST service calls, a better option is to embrace one of the OAuth 2.0 authentication flows. In the scenario below, you will use the username-password OAuth authentication flow to pass credentials to Force.com and acquire a valid session token.
Before writing any code, the first thing to do is establish Remote Access for the client application. This permits the client application to use OAuth for user authentication. Access these settings on the Force.com management portal by visiting Setup –> Develop –> Remote Access. Create a new entry by providing a unique application name, contact email, and a callback URL. Be aware that the callback URL is for browser-based scenarios where the application user is redirected after the authentication succeeds. In this case, the callback URL value is not used.
With the remote access configured, you’re now ready to authenticate with the REST endpoint. These examples use the new HttpClient class found in the .NET Framework 4.5. As mentioned at the beginning of this article, the HttpClient class provides operations for invoking web APIs. These operations run asynchronously so you have the chance to take advantage of the new Async and Await keywords present in .NET 4.5.
First, create variables to hold the various values needed to authenticate to the service. In reality, it makes the most sense to retrieve these values from a (secure) repository and NOT hardcode them into your client application. In order to authenticate against the OAuth endpoint, you need five values: Consumer Key and Consumer Secret (both from the Remote Access entry), and the Force.com username, password, and security token. Next, the message to the OAuth endpoint must be URL encoded and include the grant_type (Force.com password + Force.com security token), client_id (Consumer Key), client_secret (Consumer Secret), username (Force.com username), and password (Force.com password).
If the credentials are valid, the OAuth endpoint returns a JSON payload containing the issue date, instance URL, signature, and access token. In the code below, notice that you save off the instance URL and token for later use.
You have now authenticated a .NET client application against the REST endpoint. The resulting security token will be used next as you query and create objects in the Force.com database through the REST API.
The REST API offers a variety of ways to query the Force.com database. You can use the URL to pull back all records for a specific object, execute an SOQL query, perform searches, or retrieve a single record by ID. In each case, you can choose whether Force.com should return that data in XML or JSON format. In the example below, you will perform an SOQL query similar to the queries that were executed with the SOAP API above.
First, define a new HttpClient object. Next, author the SOQL query. Notice below that there are examples of other queries that can be executed against the REST API. To have control over the outbound headers, instantiate an HttpRequestMessage, set the HTTP operation to GET, add the URL with the SOQL query, and add the OAuth token to the “Authorization” header. Next, choose the data format of the records returned from Force.com. Both “application/xml” and “application/json” are valid values. Finally, call the SendAsync operation and process for the response.
The HttpClient is a useful library for interacting with REST services and saves the user from all the stream interactions that were necessary when working with the HttpWebRequest object in the past.
Next, create a new Account record through the REST API. First, create a new HttpClient object. Next, define the payload of the new Account. The REST API accepts either XML or JSON payloads. JSON payloads are formulated by creating name-value pairs of each field that you want added to the Force.com object. If you want to send an XML message, start with a node called “root” and create elements that match the name of the Force.com object fields.
Create an HttpRequestMessage and set the HTTP method to POST. This is the HTTP verb used when creating new Force.com records. Next, craft the URL so that it points to the object type of the new record. In this case, “/sobjects/Account.” Once again add the OAuth token to the header so that the request can be authorized. Call the SendAsync operation and see that the response string contains the ID of the newly created record.
Congratulations! You just queried and created records in Force.com via the REST API.
The Force.com family of APIs provide comprehensive access to all the business logic and data in a Force.com application. The SOAP and REST APIs give developers a powerful interface for real-time integration with Force.com. Visual Studio and .NET make it easy to consume web services from any provider. In this article we saw how to reference the SOAP API, establish a secure session, query records, and create records using both the strongly-typed Enterprise API and the flexible Partner API. For mobile clients or applications that don’t need the capabilities or heft of SOAP services, the Force.com REST API is a great choice. We saw how developers can quickly and easily authenticate to the OAuth endpoint, query Force.com records, and create brand new ones.
Newer versions of the .NET framework offer capabilities like LINQ, REST support, and asynchronous programming, but even if you’re using an older version of .NET, you can still readily consume all the SOAP and REST Force.com APIs.
Richard Seroter is a product manager for cloud computing provider Tier 3, a Microsoft MVP, Pluralsight trainer, speaker, and author of multiple books on application integration strategies. Richard maintains a regularly updated blog on topics of architecture and solution design and can be found on Twitter as @rseroter.