YUCEL MORAN

YUCEL MORAN


Salesforce and Mulesoft experience

Yucel
Author

Share


Subscribe to YUCEL MORAN


Subscribe to our email newsletter to receive article notifications and regular updates. We don't spam and your email won't be shared with third-parties.

Tags


YUCEL MORAN

Consuming standard / custom REST Salesforce service with C#

YucelYucel

REST services from Salesforce are the easiest way to integrate with any system, gives you the flexibility to use any kind of programming language and allows you to be under a standard way to integrate and move data.

In this case I want to show an easy way to consume standard or custom REST API endpoints using C#. I know this might be super easy task , but either way, I wan to leave a working sample, and explain a few steps to achieve it.

  1. In your Salesforce instance ( Sandbox or Production ), create a connected application  (Clic on the gear on the top right of your page [if you are in lightning experience] > Platform Tools > Apps > App Manager and clic New Connected App button )

2. In the new screen, you should provide the next information:

3. Save the configuration, then you should have access to the Consumer Key and Consumer Secret information.

4. In my Visual Studio solution, I have a simple class that makes almost everything and depending of the flow and type of objects you need you should be able to create new POJO's and make the serialization/deserialization for those.

5. Get Access Token. In order to authorize your application, the first step would be to Authorize your application using the "https://test.salesforce.com/services/oauth2/token" endpoint. We will use this code for that (Replace the values of CLIENT_ID, SECRET,SALESFORCENAME,PASSWOORDTOKEN with your credentials.):

This code basically returns an access token that you can use in order to consume the next endpoint. The response from the service is serialized on a SalesforceAuthentication POJO that looks like this.

using System;
namespace SalesforceRESTServerConsumer
{
    public class SalesforceAuthentication
    {
        public string access_token { get; set; }
        public string instance_url { get; set; }
        public string id { get; set; }
        public string token_type { get; set; }
        public string issued_at { get; set; }
        public string signature { get; set; }
    }
}

The Main method calls this function on this way:

public static void Main(string[] args)
        {

            SalesforceAuthentication salesforce_auth = getSalesforceAccessToken();

            Console.WriteLine("1. Consuming getSalesforceAccessToken()");
            Console.WriteLine("Access Token:"+salesforce_auth.access_token);
            Console.WriteLine("2. Consuming consumeSalesforceService()");
            requestHTTPcClient(salesforce_auth.access_token);


            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

        }
public static SalesforceAuthentication getSalesforceAccessToken(){
            SalesforceAuthentication authenticationObj = null;
            try
            {
                var request = (HttpWebRequest)WebRequest.Create("https://test.salesforce.com/services/oauth2/token");

                var postData = "grant_type=password";
                postData += "&client_id=CLIENTID";
                postData += "&client_secret=SECRET";
                postData += "&username=SALESFORCENAME";
                postData += "&password=PASSWOORDTOKEN";

                var data = Encoding.ASCII.GetBytes(postData);

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                var response = (HttpWebResponse)request.GetResponse();

                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                authenticationObj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<SalesforceAuthentication>(responseString);

                Console.WriteLine("Response: " + responseString);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error response: " + ex.Message);
            }




            return authenticationObj;
        }

Finally the POST call against a custom Salesforce REST endpoint

public static String consumeSalesforceService(String accessToken){
            

            String res = "";
            string authToken = "Bearer" + " " + accessToken;

            try
            {
                var myUri = new Uri("https://cs21.salesforce.com/services/apexrest/RestServiceTiket/insertaSolicitud");
                var myWebRequest = WebRequest.Create(myUri);
                var myHttpWebRequest = (HttpWebRequest)myWebRequest;
                myHttpWebRequest.PreAuthenticate = true;
                myHttpWebRequest.Headers.Add("Authorization", authToken);
                myHttpWebRequest.Accept = "application/json";
                myHttpWebRequest.Method = "POST";

              
                    
                Solicitud sol = new Solicitud();
                sol.nombre = "pruebaFF_1";
                sol.numeroTiket = "ABC1232H8";
                sol.datosOrigen = null;
                sol.datosDestino = null;

                ExternalRequest httpcall = new ExternalRequest();
                httpcall.request = sol;

                using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
                {               
                    string json = Newtonsoft.Json.JsonConvert.SerializeObject(httpcall);
                    Console.WriteLine("JSON: " + json);

                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();

                }

                var httpResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                Console.WriteLine("JSON: " + httpResponse);
                var responseString = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
                res = responseString;

            }
            catch(Exception ex){
                Console.WriteLine(ex.Message);
            }

           
            return res;
        }

Basically we use the access token and put it as part of the Authorization header, the call is authenticated and we're able to push the data and get a response from that.

You can pull the code from this GitHub Repository.

This is just a simple demonstration of how to make it work and it can be extended as you want,.

Yucel
Author

Yucel

View Comments