in c# .Net OAuth Web services salesforce ~ read.

Integrating .Net and Salesforce, part 1: REST API

Note: all the code for this example is found on Github

Welcome to Part 1 of our "Integrating .Net and Salesforce" series. In this series, we'll explore different ways of connecting to Salesforce and accessing your data from a C# application. Salesforce exposes a lot of functionality via REST and SOAP web services (and you can extend it with your own web services), which means that it can be consumed by an application written in pretty much any modern language. Since we're .Net people in this blog, we'll create a client application using our favourite CLR language (hint: it's not VB.Net).

Our application

We're going to create a simple command-line application that will allow us to run SOQL queries and print the results on the console. In an exercise of wild imagination, we're going to name our nifty little app SfQuery.

Authenticating in Salesforce

There's a great variety of options to authenticate to Salesforce, all of which use some form of OAuth flow. We'll try to cover a few of these in a series of blog posts. Stay tuned for more examples!

Today we're going to explore connecting via the REST API using a Connected App. A Connected App is an authentication endpoint inside your Salesforce org. This allows a sys admin to grant different permissions on a per-app basis, and even configure what users have access to what external application.

Step 1: create your connected app

  • Inside salesforce setup, navigate to Build > Create > Apps.
  • In the bottom panel of the page, where it says Connected Apps, click New. This will open a dialog to create a new connected app.
  • In Name, type "SF Query", and supply a mandatory contact email
  • Make sure Enable OAuth settings is ticked.
  • In Callback URL, type in a dummy https URL (something like https://dummy.org). We're not going to need a callback URL as we will use the 'resource owner password' grant. Callback URL is used for other types of OAuth flows that we will explore in a future post.
  • In Selected OAuth scopes, Add "Access and manage your data (api)"
    Create connected app
  • Click Save. We will get a message telling us to wait a few minutes before using the app.
  • Click Continue. The information for our connected app will be displayed. Take note of the Consumer Key, which we'll use in the following steps.
  • Click on the Click to Reveal link next to Consumer Secret. Write down the consumer secret that is displayed, as we'll use it in the following steps.

Step 2: create a new .Net console project

We now have all the information we need to start coding our client app. In VisualStudio, create a new Console project, and add a new class, which we'll call SalesforceClient. This will encapsulate all the steps required to log onto and query our org.

We will be using the new HttpClient class, which is the easiest way to make HTTP callouts. It offers great support for asynchronous calls, but for the purposes of this post, we'll be making the calls synchronous by calling the Result keyword.

We will need a few properties to store the login credentials and the OAuth authentication token:

Step 3: authenticating / logging in

We can now create the Login() method to authenticate onto our connected app. Salesforce requires us to use FormUrlEncodedContent or it will complain of a bad request.

The response to our authentication request will consist of a JSON object containing the authentication token and the instance URL (where to direct all subsequent queries). We store these in the properties created above.

If we test the class we should obtain our authentication token. Ooops, what's this? An error? It looks like a recent Salesforce security upgrade requires TLS 1.1 or 1.2. We need to tell our runtime to add the necessary protocols, with this static constructor:

If we test our method now and we print the response, we obtain a token like this:

Response: {
  "access_token" : "00D20000000lYi7!ARwAQEp4K9Lz0ozt5zjlHu...",
  "instance_url" : "https://emea.salesforce.com",
  "id" : "https://login.salesforce.com/id/00D20000000lYi7EAE/005...",
  "token_type" : "Bearer",
  "issued_at" : "1463411571997",
  "signature" : "TmoeKs2s70SgVNxQSay..."
}

It looks good, so on to the next step!

Step 4: querying data

Now that we're logged in, we can run a user-supplied SOQL query with a few lines of code:

In this case we're returning the whole JSON as a string. We leave the parsing of the result to the calling method.

Step 5: bootstrapping

All we need to do now is supply all the login credentials and the user's query. We've decided to supply all the configuration in the App.Config file, and pass the query as a command-line argument.

Our Program.cs class looks like this:

Our App.config file looks like this:

We can now query our Salesforce instance by running SfQuery "SELECT Name FROM Contact"... how cool is that?

Conclusions

We've seen that calling the REST API from .Net is quite easy, especially with the help of the HttpClient class. The main challenges are around authenticating with Salesforce, the complexities of OAuth and the concept of the connected app.

Using OAuth with the resource owner password grant is maybe the easiest way to obtain an OAuth token without having to create and host an application to receive a callback. However, it has the shortcoming that it requires the resource owner (or in this case, the Salesforce user) to supply his credentials to a third-party app. The user needs to trust that the app will not store or disclose this password. This flow is good for CLI apps that cannot use a browser or for apps that you write yourself; otherwise, it should be avoided. Other flows that we'll see in a next post avoid this by using web redirects to supply the OAuth token.

Useful References: