Salesforce gives us a limit of 2000 records to fetch from it using REST calls. But sometimes we need to get all the records from Salesforce. In Salesforce, there is a limit of API calls. By default, it gives 15,000 for a sandbox. Making salesforce call, again and again, consumes lots of API calls. One needs to purchase a license to extend this limit. Then why not optimize the code?
ForceClient library (automatically comes with Salesforce.Force NuGet package) provides a method that makes an asynchronous call and does not have the restriction of fetching only 2000 records. It can fetch all the records in one go.
See below code :
public static async Task<List> getallrecords(ForceClient client) { var list = new List(); try { string qry = "select Id from CustomObject"; var results = await client.QueryAsync(qry); var totalSize = results.TotalSize; list.AddRange(results.Records); var nextRecordsUrl = results.NextRecordsUrl; if (!string.IsNullOrEmpty(nextRecordsUrl)) { System.Diagnostics.Debug.WriteLine("next record url."); while (true) { var asynlist = await client.QueryContinuationAsync(nextRecordsUrl); totalSize = asynlist.TotalSize; System.Diagnostics.Debug.WriteLine("Next " + totalSize+ "records."); list.AddRange(asynlist.Records); if (string.IsNullOrEmpty(asynlist.NextRecordsUrl)) break; nextRecordsUrl = asynlist.NextRecordsUrl; } } System.Diagnostics.Debug.WriteLine("total = " + totalSize); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } return list ; }
You can find the more details regarding the ForceClient library methods at the link “https://developer.salesforce.com/blogs/developer-relations/2014/09/nothing-but-dotnet-force-toolkit-dotnet.html”.