Skip to content

Instantly share code, notes, and snippets.

@mkorman
Created May 16, 2016 12:53
Show Gist options
  • Save mkorman/de4f4280ca5f473a2d040bb347aceb8c to your computer and use it in GitHub Desktop.
Save mkorman/de4f4280ca5f473a2d040bb347aceb8c to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace SfQuery
{
public class SalesforceClient
{
private const string LOGIN_ENDPOINT = "https://login.salesforce.com/services/oauth2/token";
private const string API_ENDPOINT = "/services/data/v36.0/";
public string Username { get; set; }
public string Password { get; set; }
public string Token { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string AuthToken { get; set; }
public string InstanceUrl { get; set; }
static SalesforceClient()
{
// SF requires TLS 1.1 or 1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
public void Login()
{
String response;
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{"grant_type", "password"},
{"client_id", ClientId},
{"client_secret", ClientSecret},
{"username", Username},
{"password", Password + Token}
}
);
var message = client.PostAsync(LOGIN_ENDPOINT, content).Result;
response = message.Content.ReadAsStringAsync().Result;
}
Console.WriteLine($"Response: {response}");
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
AuthToken = values["access_token"];
InstanceUrl = values["instance_url"];
}
public string Query (string queryString)
{
using (var client = new HttpClient())
{
string restQuery = InstanceUrl + API_ENDPOINT + "query/?q=" + queryString;
var request = new HttpRequestMessage(HttpMethod.Get, restQuery);
request.Headers.Add("Authorization", "Bearer " + AuthToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Add("X-PrettyPrint", "1");
var response = client.SendAsync(request).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment