6/18/2015 8:16:03 PM

The following code will connect to a Salesforce instance and allow you to execute a report and return the results. This code is remarkably simply yet took a while to put together. I blame Salesforce for having very shitty sparse documentation. Hopefully though this will help somebody from hours/days of frustration.

This code was run under .NET 4.5. It is using the following Nuget packages:

Requires you to create a Salesforce Connected App (https://help.salesforce.com/apex/HTViewHelpDoc?id=connected_app_create.htm)

  • Create the App (In Salesforce -> Setup -> Create -> Apps -> Connected Apps (scroll down) -> New
  • New Connected App must have "Enable OAuth Settings" checked.
  • Callback Url must be set (I set mine to http://localhost/).
  • You must copy the Apps Consumer Key and Consumer Secret
  • YOU MUST ENABLE THE APP FOR THE USER/PROFILE THAT IS BEING USED TO ACCESS THE REPORT

*Included 2 versions of UsernamePasswordAsync. I believe the commented out section is relevant to an older API.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.IO; namespace Console1 { class _Startup { static void Main(string[] args) { string message = ""; try { var task = Reports_Get_Async(); task.Wait(); } catch (Exception ex) { if (ex.InnerException != null) { message += Environment.NewLine + ex.InnerException.Message; } } Console.WriteLine("Results: "); Console.WriteLine(message); Console.WriteLine("Continue?"); var name = Console.ReadLine(); } public static async Task Reports_Get_Async() { string username = "myemail@example.com"; string password = "myPassword"; string usertoken = "xxxxxxxxxxxxxxxxxxxxxx"; string consumerKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; string consumerSecret = "111111111111111111111"; var isSandbox = false; var url = "https://login.salesforce.com/services/oauth2/token"; if (isSandbox) { url = "https://test.salesforce.com/services/oauth2/token"; } var authClient = new Salesforce.Common.AuthenticationClient(); authClient.ApiVersion = "v34.0"; //await authClient.UsernamePasswordAsync(sfdcConsumerKey, sfdcConsumerSecret, username, password + token, ".net-api-client", url); await authClient.UsernamePasswordAsync(consumerKey, consumerSecret, username, password + usertoken, url); var reportId = "XXXXXXXXXX4CoJc"; //Salesforce Id for the report I need string reportUrl = "/services/data/" + authClient.ApiVersion + "/analytics/reports/" + reportId + "?includeDetails=true"; //using the Nuget RestSharp package (http://restsharp.org/) var restClient = new RestSharp.RestClient(authClient.InstanceUrl); var restRequest = new RestSharp.RestRequest(reportUrl, RestSharp.Method.GET); restRequest.AddHeader("Authorization", "Bearer " + authClient.AccessToken); var restResponse = restClient.Execute(restRequest); var reportData = restResponse.Content; // raw content as json string } } }