Sonoma Partners Microsoft CRM and Salesforce Blog

Silverlight 5 Async Tasks with Microsoft Dynamics CRM 2011

Have you ever needed to execute several queries in CRM 2011 from Silverlight and perform some task when all the data is retrieved?  If so, you’ll know that this can be a major pain as well as create some ugly code due to asynchronous requests.

With Silverlight 5 you can use the System.Threading.Tasks namespace to simplify your code.  In the following code sample I will use two simple queries, one to retrieve all contacts and one to retrieve all accounts.  I will then utilize Tasks to execute the queries asynchronously and wait until they are both finished in order to perform more logic.  The following code sample uses the SilverlightUtility from the SDK to use the SOAP endpoint which can be found here.

        public void RetrieveData()
            IOrganizationService orgService = SilverlightUtility.GetSoapService();

            QueryExpression accountQuery = new QueryExpression();
            accountQuery.EntityName = "account";
            accountQuery.ColumnSet = new ColumnSet() { AllColumns = true };            

            QueryExpression contactQuery = new QueryExpression();
            contactQuery.EntityName = "contact";
            contactQuery.ColumnSet = new ColumnSet() { AllColumns = true };

            var accountTask = CreateRetrieveMultipleTask(orgService, accountQuery);
            var contactTask = CreateRetrieveMultipleTask(orgService, contactQuery);

            Task.Factory.ContinueWhenAll(new Task[] { accountTask, contactTask },
                completedTasks =>
                    EntityCollection accounts = accountTask.Result;
                    EntityCollection contacts = contactTask.Result;

                    // Perform task

        public Task<EntityCollection> CreateRetrieveMultipleTask(IOrganizationService orgService,                         
            QueryBase query)
                Task.Factory.FromAsync<QueryBase, EntityCollection>(

If you are using Visual Studio 2012 then you can make asynchronous processing even cleaner with the Async Targeting Pack and the 'await' keyword.  More information can be found here.

Topics: Microsoft Dynamics CRM 2011 Microsoft Dynamics CRM Online