MS CRM 2011 Integration with Windows Azure

Posted: May 27, 2013 in Azure, CRM 2011

MS CRM 2011 supports integration with Windows Azure, by integrating it we can register plug-in’s and can pass the execution context to the azure solution.

MS Dynamics CRM 2011 has been integrated with the Windows Azure platform by coupling the Microsoft Dynamics CRM event execution pipeline to the Windows Azure Service Bus so effectively during save/update operation we can send processed information to Azure Service Bus. For detailed information look here

MS CRM 2011 can send messages to service bus using 4 different contracts:
1) Queue
2) One-way
3) Two-way

In my blog, i’m going to work with the Two-Way Listener. Two way contract requires an active listener and if there is no active listener on an endpoint, the Microsoft Dynamics CRM post to the service bus fails. A Two way contract can return a string value from the listener to MS CRM 2011.

Here, I’m going to write the Two way listener code in the Azure Worker Role. Worker roles are applications that are developed to run asynchronously and to work on long-running or perpetual tasks independent of user interaction or input. It is similar to a windows service and uses a simple while(true) loop and a sleep statement.

To work with the Windows Azure Worker role, first you need to install the Windows Azure Sdk. Here is the link to download the Sdk.

Once the installation is done, you should get "Windows Azure Cloud Service" in your visual studio.

VS 2010

VS Azure

To create and deploy Worker Role, you should have the Windows Azure account. You can create a free azure trail account here.

First login into your Windows Azure account and create a Service Bus NameSpace. In my sample, my Servie Bus NameSpace is "CrmAzureIntegration"



Once the Service Bus Namespace is created, you should able to see "Default Issuer and Default Key"


Creating a Worker Role

Open Visual Studio 2010, Click on New Project and select "Windows Azure Cloud Service" Click on Ok.


Select Worker Role and give it a Name.


Add the following References to your Worker Role Project:
1) Microsoft.xrm.sdk
2) Microsoft.ServiceBus
3) System.ServiceModel
4) System.Runtime.Serialization

Inherit the "ITwoWayServiceEndpointPlugin" to your Worker Role as shown below.


Add the following code to your worker role. You can also get the code from crm sdk

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Threading;
using Microsoft.ServiceBus;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.Xrm.Sdk;

namespace CrmAzureWorkerRole
    public class WorkerRole : RoleEntryPoint, ITwoWayServiceEndpointPlugin
        public string Execute(RemoteExecutionContext executionContext)
            string returnValue = "Service Call Successful";
            return returnValue;

        public override void Run()
            // This is a sample worker implementation. Replace with your logic.
            Trace.TraceInformation("CrmAzureWorkerRole entry point called", "Information");

            while (true)
                Trace.TraceInformation("Working", "Information");

        public override bool OnStart()
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at

            // Activate the Listener

            return base.OnStart();

        public void ActivateListener()
            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

            // Add service bus namespace
            string serviceNamespace = "crmazureintegration";

            // Add Default issuer name
            string issuerName = "owner";

            // Add Service bus Default Key 
            string issuerKey = "<Add key here>";

            string servicePath = "WorkerRole";

            // Leverage the Azure API to create the correct URI.
            Uri address = ServiceBusEnvironment.CreateServiceUri(

            // Create the shared secret credentials object for the endpoint matching the 
            // Azure access control services issuer 
            var sharedSecretServiceBusCredential = new TransportClientEndpointBehavior()
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey)

            // Using an HTTP binding instead of a SOAP binding for this endpoint.
            WS2007HttpRelayBinding binding = new WS2007HttpRelayBinding();
            binding.Security.Mode = EndToEndSecurityMode.Transport;

            // Create the service host for Azure to post messages to.
            ServiceHost host = new ServiceHost(typeof(WorkerRole));
            host.AddServiceEndpoint(typeof(ITwoWayServiceEndpointPlugin), binding, address);

            // Create the ServiceRegistrySettings behavior for the endpoint.
            var serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);

            // Add the service bus credentials to all endpoints specified in configuration.

            foreach (var endpoint in host.Description.Endpoints)

            // Begin listening for messages posted to Azure.

Now we need to create a plug-in to call the Execute method which will initiate posting the execution context to the service bus.

Add the following References to your Plug-in:
1) Microsoft.xrm.sdk
2) System.Runtime.Serialization

You can get the following plug-in code from the crm sdk.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;

namespace CrmAzurePlugin
    public class CrmAzureIntegration : IPlugin
        private Guid serviceEndpointId;
        Entity entity = null;

        public CrmAzureIntegration(string config)
			if (String.IsNullOrEmpty(config) || !Guid.TryParse(config, out serviceEndpointId))
				throw new InvalidPluginExecutionException("Service endpoint ID should be passed as config.");

        public void Execute(IServiceProvider serviceProvider)
            // Retrieve the execution context.
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                // Obtain the target business entity from the input parameters.
                entity = (Entity)context.InputParameters["Target"];

            // Extract the Organization Service
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            // Extract the tracing service.
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            if (tracingService == null)
                throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");

            IServiceEndpointNotificationService cloudService = (IServiceEndpointNotificationService)serviceProvider.GetService(typeof(IServiceEndpointNotificationService));
            if (cloudService == null)
                throw new InvalidPluginExecutionException("Failed to retrieve the service bus service.");

                tracingService.Trace("Posting the execution context.");
                string response = cloudService.Execute(new EntityReference("serviceendpoint", serviceEndpointId), context);
                if (!String.IsNullOrEmpty(response))
                    // Update response back to the record
                    UpdateResponse(response, (Guid)entity.Attributes["crm_integrationid"], service);
            catch (Exception e)
                tracingService.Trace("Exception: {0}", e.ToString());
        public void UpdateResponse(string response, Guid recordId, IOrganizationService service)
            Entity integrationEntity = new Entity("crm_integration");
            integrationEntity["crm_response"] = response;
            integrationEntity.Id = recordId;


In the above code, once i get the response i’m going to update the crm record with the response string.

Now open your Plug-in Registration tool and Register the Service Endpoint as shown below :

Click on Register New Service EndPoint.


Add Name, Service Bus Namespace, Path, Select Contract as Two Way and click "Save and Configure ACS"


Add Service Bus Default key in Management Key


Download the certificate and Issuer Name from CRM. Login into crm, navigate to Settings and click on customizations, select Developer Resources

Once everything is added, Click on Configure ACS and finally click on Save and Verify Authentication.

Now you need to register the plugin and pass the service endpoint id from the unsecure configurtaion. In my case i’ve added the plugin on create of entity record.


You can get the service endpoint id once you Register the Service Endpoint as shown below:


Now we can go ahead and test the application. First we need to Activate the listener, so Run the worker role and set the breakpoint at "Execute" method.


Once the listener is active, go to crm and create the entity record to trigger the Execute method.


Once u save the record, Execute method in Worker role gets triggered and sends back the "Service Call Successful" string to crm and updates the record in "Response" attribute as shown below.



Deploy Worker Role to Azure Cloud Service

Right Click on your Azure Project and select Package and Click "Package" button as shown below


Now open your Windows Azure account, click on "Cloud Services" and select New. Add the URL name and click on "Create Cloud Service"


Once your cloud service is created, Click on "Configure" and select "Upload A New Production Deployment"

Add the Deployment Name and select the Package and Configuration files which you have published earlier and click Ok.


It takes few minutes to create your service and start running.

Once everything is finished and if your cloud service is running perfectly, that means now your listener is activated and you can go head and create your entity record in crm to trigger your service.

Happy coding 🙂

  1. harry singh says:

    cool blog ,nice post in very detail .

  2. harry singh says:

    cool blog ,nice post in very detail .

    Dynamics CRM Developers

  3. Maurine says:

    Hi to every body, it’s my first pay a quick visit of this web site; this webpage carries awesome and in fact good
    data in favor of readers.

  4. BlueIce says:

    Thanks for the best post

  5. Subhash Mahato says:

    help full. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s