Nothing But .Net – Querying Objects with the new Force.com Toolkit for .NET

In this latest post, Sara shows how to query Salesforce objects with the Force.com Toolkit for .Net. She also explains how to make relationship queries, or subqueries.

The second and third posts in this series, focused on the newly available Open Source Force.com Toolkit for .NET. The toolkit allows you to easily interact with the Force.com and Chatter REST API’s using native libraries. In the previous posts, I went over what you needed to know to install the toolkits and authenticate to your org. In this post, I will go over things you need to know to query Salesforce objects with the toolkit.

Creating the ForceClient

When a user successfully logs in using either one of the supported authentication methods, WebServer or Username-Password, they will be returned a valid Instance URL, Access Token, and API Version. In the WebServerOAuthFlow sample application (available on GitHub) these values are then stored in the ViewBag.

Depending on your applications architecture, you could also store these values is in Session variables. Either way, they need to be stored somewhere because all three are needed to instantiate the ForceClient object. The ForceClient object is used to send authorized requests to the server and it can be created with code such as the following:

var client = new ForceClient(instanceUrl, accessToken, apiVersion);

Querying Objects

Once the client has been created, you can query objects using a valid SOQL statement and the QueryAsync method. Just make sure that your query statement only returns the properties you need. At the most basic level, results can be returned with a generic object type. For example, a query to return the name and description of 10 accounts could be performed using the following code:

var results = await client.QueryAsync

This will return results that can then be serialized into JSON and returned to the client, such as how it is done in the WebServerOAuthFlow sample application.

Alternatively, I could use the dynamic keyword to return an object whose operations are resolved only at runtime. I could then loop through the results and access properties, even though I never defined them anywhere, using code such as this:

var accts = await client.QueryAsync("Select ID, Name, Description FROM Account LIMIT 10");
string name = "";
foreach(dynamic acct in accts.records)
{
    string name = acct.Name;
    string description = acct.Description;
}

While the code above will compile successfully, if I accidently mistype one of the property names, I will not discover this error until runtime. Of course, I can avoid this by returning the data as a strongly typed object. The only issue is that I am responsible for declaring the object type. Unlike working with the SOAP API, where I have a WSDL that gives me access to all the Salesforce metadata, I have to define any metadata types I want to return. I can do this by creating a class object to represent the Account such as the following:

public class Account
{
     public string Id { get; set; }
     public string Name { get; set; }
     public string Description { get; set; }
}

My query could also utilize the QueryResult object and if I wanted to return all the accounts the code would look like the following:

QueryResult accts = await client.QueryAsync("Select ID, Name, Description FROM Account");

One of the advantages to using the QueryResult is I can check the value of the nextRecordsUrl field to see if my query returns more than one batch of account records. If it is not null then I would access the remaining records using the QueryContinuationAsync method. To see a full example of what I described above, refer to the SimpleConsole sample application that is available on the GitHub website.

What about Relationship Queries?

Another advantage to using QueryResult is that doing so allows you to access data within relationship queries or subqueries. For example, let’s say I wanted to access contact records along with the Account data. I could do this by first adding a class definition for the Contacts, such as this:

private class Contact
{
    public const String SObjectTypeName = "Contact";
    public String Id { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String title { get; set; }
}

And then change my Account class definition to look like the following:

public class Account
{
     public string Id { get; set; }
     public string Name { get; set; }
     public string Description { get; set; }
     public QueryResult Contacts { get; set; }
}

The code to query account and contact records would then look like this:

QueryResult results = await client.QueryAsync("Select ID, Name, Description, (Select Id, Firstname, lastname, Title FROM Contacts) FROM Account");

The results returned from this query will include all the child contact records for each account. You can then loop through the results (easy peasy) using something like the following:

//First loop through the account results
foreach(Account acc in results.records)
{
     Console.WriteLine("Account name: " + acc.Name);
     //Now loop through the contacts
     foreach(Contact con in acc.Contacts.records)
     {
        Console.WriteLine("Contact name: " + con.FirstName + " " + con.LastName);
     }
}

The Force.com toolkit is a great addition to the set of tools that Salesforce offers to .NET Developers. And the best part is that it is all open source, so we all have a chance to contribute to its development. I encourage anyone working with .NET and Salesforce to check it out and report any issues or suggestions you have to the GitHub website. In the next post for this series, I will go through what you need to know to create, update and delete Salesforce objects using the Force.com Toolkit. Stay Tuned!

Editors Note: This is the fourth post in our blog series Nothing But .Net. Sara Morgan, our resident expert, is an independent Software Developer and long-time .NET programmer who has recently been wooed into the world of Force.com development. She recently filmed her first introductory course covering Visualforce for Lynda.com.

Published
October 21, 2014
Topics:

Leave your comments...

Nothing But .Net – Querying Objects with the new Force.com Toolkit for .NET