Salesforce API in C#

17.12.2019
|
0 Comments
||
|

Introduction to Salesforce API in C#

We can use salesforce API to connect or send data to salesforce from C#. The API accepts certain parameters and returns the result. We need not create an extra code in it.

In this example, we are going to upload a file data from C# in the salesforce Document object. For this, we are going to use the salesforce document API.

/services/data/v39.0/sobjects/Document

We need to know the salesforce access token and instance URL to connect it to and use the API.

The code in c#:

Uri address = new Uri(sftoken.instance_url + "/services/data/v39.0/sobjects/Document"); 
string result = "";
 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
 using (var client = new HttpClient())
 {
      client.Timeout = new TimeSpan(1, 0, 0);
      client.BaseAddress = address;
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Authorization = new  AuthenticationHeaderValue("Bearer", sftoken.access_token);

         var data = "{\"Name\": \"DocName.jpg\",\"FolderId\": \"YOUR FOLDER ID\",\"Body\":\"Encoded file data\"}";
                     
          StringContent content = new StringContent(data, Encoding.UTF8,                                                                                                      "application/json");
          Task taskResponse = client.PostAsync("", content);
           taskResponse.Wait();
            HttpResponseMessage response = taskResponse.Result;

            if (response.IsSuccessStatusCode)
             {
                   Task taskread = response.Content.ReadAsStringAsync();
                    taskread.Wait();
                    result = taskread.Result;
             }

The result which we will receive will be of the following format:

{
  "id": "string",
  "errors": [
    "string"
  ],
  "success": "boolean"
}

Here id will be the id of the document created.

Leave a Reply

Your email address will not be published. Required fields are marked *

Share on:
Share this...
Share on Facebook
Facebook
Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin
Website security
Contact Us