In my previous blog I showed you how you can query any object in Salesforce without having to write all the fields in the object using the Enterprise WSDL. In this post, I'm going to re-write the same method using the Partner WSDL. The method signature will be a little different using the Partner WSDL, the most noticeable one will be that I will not be able to make use of Generic like I did with Enterprise WSDL.
1: public static IEnumerable<sObject> QueryObject(string sObjectName, SforceService binding)
2: {
3: List<sObject> result = new List<sObject>();
4: // Get more information about the object
5: DescribeSObjectResult describeResult = binding.describeSObject(sObjectName);
6: if (describeResult.queryable)
7: {
8: // Get all the sObject's fields in an array
9: IEnumerable<string> fields = describeResult.fields.Select(a => a.name);
10: string query = string.Format("SELECT {0} FROM {1}", string.Join(", ", fields), sObjectName);
11: if (binding != null)
12: {
13: // Send the query to Salesforce
14: QueryResult qResult = binding.query(query);
15: if (qResult.records != null && qResult.records.Length > 0)
16: result.AddRange(qResult.records);
17: // Keep querying until we have all the records
18: while (!qResult.done && !string.IsNullOrEmpty(qResult.queryLocator))
19: {
20: qResult = binding.queryMore(qResult.queryLocator);
21: if (qResult.records != null && qResult.records.Length > 0)
22: result.AddRange(qResult.records);
23: }
24: }
25: }
26: return result;
27: }
Although this make querying Salesforce objects very easy, there is one big drawback; that is the describeSObject will count toward an API calls. This means that every query to Salesforce will have one additional API call. My suggestion is if you are making too many query calls, try to cache the objects fields. This will result in less API call and faster execution since there is one less trip to Salesforce.
Also same
restrictions
to the query length apply here too. Make sure you stay within the 10K characters when building your query string.
Happy Coding
No comments:
Post a Comment