Is there a c# wrapper available for the Salesforce REST Api?
Asked Answered
D

6

14

I would like to integrate SalesForce information into a .net MVC application.

The samples on SalesForce website are all SOAP as far as I can see, or alternatively there is a SalesForce ADO.NET data provider.

http://wiki.developerforce.com/page/Web_Services_API#.NET

Thanks.

Decembrist answered 29/2, 2012 at 10:17 Comment(0)
L
10

A .NET tool kit was announced by salesforce.

"The Force.com Toolkit for .NET provides an easy way for .NET developers to interact with the Force.com REST API using a native libraries."

https://github.com/developerforce/Force.com-Toolkit-for-NET/

Lipread answered 11/2, 2014 at 17:38 Comment(0)
T
7

If you're looking for a Salesforce's REST API client library, take a look on SalesforceSharp.

It supports create, update, delete and query records from REST API.

Create

client.Create("Account", 
   new { Name = "name created", Description = "description created" }));

Update

client.Update("Account", "<record id>", 
   new { Description = "description updated" }));

Delete

client.Delete("Account", "<ID">);

Query

var records = client.Query<Account>("SELECT id, name, description FROM Account");

Nowadays it supports username-password authentication flow, but others flows (web server and user-agent) can be created and injected.

Tripalmitin answered 10/9, 2013 at 11:3 Comment(0)
C
3

I was really hoping for something that would parse the WebResponse into classes representing the SF resources returned, and have solid error handling - the tedious stuff :)

This exists - it's called the SOAP API :) Seriously though, if you are doing server-side integration and want typed generated classes and solid error handling, SOAP is your pony.

Clary answered 29/2, 2012 at 22:52 Comment(0)
P
3

I use RestSharp to simplify the calls and de-serialize the objects, but you still have to handle all the Salesforce error codes. It has some OAuth functionality built in as well, but the version I'm using (about 2 months old) doesn't support OAuth 2 very well. It's still a pain, but worth it if you are pulling a lot of data.

Potion answered 6/3, 2012 at 22:48 Comment(2)
Interesting, I will take a look at RestSharp. I was looking at the asp.net web api samples where they extend to access twitter via OAuth2: code.msdn.microsoft.com/Extending-HttpClient-with-8739f267Decembrist
Thanks for the link, I'll definitely check that out. Is that sample for OAuth2 though? I haven't looked at it closely, but I noticed the oauth_ prefix, which is not implemented in the Salesforce OAuth2 service.Potion
B
2

well, not that I know of. Nothing much to it though, depending on whether you want to use it client side or server side you use javascript approach (as documented in restapi) or simply System.Net.WebRequest for server side.

Check Dan's .NET blog

Bills answered 29/2, 2012 at 16:51 Comment(2)
Thanks for the answer. I'll be using it server side to integrate into other systems. I was really hoping for something that would parse the WebResponse into classes representing the SF resources returned, and have solid error handling - the tedious stuff :)Decembrist
if you want strong typing you should go the WSDL way and use web services. REST by itself is an architectural idea rather than a set protocol that could lead to universal code generation, it doesn't even mandate the use of JSON which sf restApi uses and it does not include any standardized metadata that you could parse and create classes. In theory you can use /sobjects/object_name/describe to retrieve the metadata as aprt of development proces, then create classes for it and use JavaScriptSerializer.Deserialize<T>. HOwever, it sounds and really is a pain :)Bills
K
1

Here is sample code using Password workflow. It gets the access token and queries the API:

public static string Login()
{
    string responseJsonString = string.Empty;
    StringBuilder str = new StringBuilder();
    str.AppendFormat("{0}?grant_type=password&client_id={1}&client_secret={2}&username={3}&password={4}"
                     , LoginOAuthUrl, ClientID, ClientSecret, ClientUserName, ClientPassword);
    // Request token
    try
    {
        HttpWebRequest request = WebRequest.Create(str.ToString()) as HttpWebRequest;

        if (request != null)
        {
            request.Method = "POST";
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // Get the "access_token" and "instance_url" from the response.
                    // Convert the JSON response into a token object


                    // Here we get the response as a stream.
                    using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
                    {
                        responseJsonString = responseStream.ReadToEnd();
                        // Deserialize JSON response into an Object.
                        JsonValue value = JsonValue.Parse(responseJsonString);
                        JsonObject responseObject = value as JsonObject;
                        AccessToken = (string)responseObject["access_token"];
                        InstanceUrl = (string)responseObject["instance_url"];
                        return "We have an access token: " + AccessToken + "\n" + "Using instance " + InstanceUrl + "\n\n";
                    }
                }
            }
        }
        return responseJsonString;
    }
    catch (Exception ex)
    {
        throw new Exception(string.Format("Unable to login to salesforce: {0}", str), ex);
    }
}

public static string Query()
{            
    string RequestUrl = InstanceUrl + "/services/data/v28.0/query";
    string queryParam = "q=" + QUERY;
    // Read the REST resources
    string responseJsonString = HttpGet(RequestUrl, queryParam);
    return responseJsonString;
}

public static string HttpGet(string URI, string Parameters)
{
    // Add parameters to the URI
    string requestUri = URI + "?" + Parameters;
    System.Net.WebRequest req = System.Net.WebRequest.Create(requestUri);
    req.Method = "GET";
    req.Headers.Add("Authorization: OAuth " + AccessToken);

    // Do the GET request
    System.Net.WebResponse resp = req.GetResponse();
    if (resp == null) return null;
    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
    return sr.ReadToEnd().Trim();
}
Kerwon answered 28/8, 2013 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.