Welcome to ForceIO blog. I’m hoping that this will be the first of many blogs to come. In my blogs I will try to focus on development of Salesforce.com solutions using Microsoft .NET (C#). I may deviate from time to time, but I will try to mostly keep it relevant.
Did you ever wish that you could just query all your Salesforce Object fields without writing the name of all the fields in the query one by one? SQL give you ability to query all the fields as such:
SELECT * FROM EntityName
But this is simply not possible when querying Salesforce Objects. To get around this minor setback, I’ve created a utility method that queries any force object with all its fields.
1: public static IEnumerable<T> QueryObject<T>(SforceService binding) where T : sObject
2: {
3: List<T> result = new List<T>();
4: Type sObjectType = typeof(T);
5: IEnumerable<string> sObjectProperties = sObjectType.GetProperties().Where(a =>
6: /* Property must be accessible */
7: a.CanRead &&
8: /* Property cannot have base type of sObject to avoid querying related objects */
9: a.PropertyType.BaseType != typeof(sObject) &&
10: /* Ignoring the properties that are of type QueryResult */
11: a.PropertyType != typeof(QueryResult) &&
12: /* Let's make sure we don't query fieldsToNull property */
13: a.Name != "fieldsToNull" &&
14: /* We want to also ignore all boolean related fields that end with "Specified" */
15: !(a.PropertyType == typeof(bool) && a.Name.EndsWith("Specified"))
16: ).OrderBy(a => a.Name).Select(a => a.Name);
17: // Format the query string
18: string query = string.Format("SELECT {0} FROM {1}",
19: string.Join(", ", sObjectProperties), sObjectType.Name);
20: if (binding != null)
21: {
22: // Send the query to Salesforce
23: QueryResult qResult = binding.query(query);
24: if (qResult.records != null && qResult.records.Length > 0)
25: result.AddRange(qResult.records.Cast<T>());
26: // Keep querying until we have all the records
27: while (!qResult.done && !string.IsNullOrEmpty(qResult.queryLocator))
28: {
29: qResult = binding.queryMore(qResult.queryLocator);
30: if (qResult.records != null && qResult.records.Length > 0)
31: result.AddRange(qResult.records.Cast<T>());
32: }
33: }
34: return result;
35: }
Now you can query any Salesforce Object as such:
1: IEnumerable<Account> accounts = QueryObject<Account>(binding);
Of course the world is not black and white, and you don’t always want to retrieve all the records in an Object. I’m sure you can be creative enough to modify the method to suite your need. Just keep in mind that Salesforce limits you to 10K characters for your query string, so if you have way too many fields on your object with very long names, this method will not works.
In my next blog post, I will rewrite the above method so that it works with the Partner WSDL.
Happy Coding
No comments:
Post a Comment