Summary – This article describes how to send messages from Microsoft CRM 2011 to Microsoft Azure Service Bus Topics and Queues, using CRM SDK 5.08 and Azure SDK 1.6
Configuring Azure Service Bus Queues, Topics and Subscriptions
Azure Account
An Azure account is required to use Service Bus Queues, Topics and Subscriptions. Information is available at https://www.windowsazure.com on creating an account and pricing. Free trial accounts, and special free accounts for MSDN subscribers are also available.
Create a Service Bus Namespace
Once you have created an Azure account, you will need to create a Service Bus Namespace. In the Azure Management Portal select “Service Bus, Access Control and Caching” on the lower left side of the screen, then expand “Services” at the top left, and choose “Service Bus”. Any existing Service Bus Namespaces you have provisioned will be listed in the main window of the portal. Select “New” on the ribbon bar and you will be presented with the pop-up window below:
![CreateServiceBusNameSpace_thumb[3] CreateServiceBusNameSpace_thumb[3]](http://www.lbidotnet.com/resource/Windows-Live-Writer-736fc863794b_1468C-?fileId=16042450)
You need to choose a unique name for your Namespace and then press “Check Availability”, then choose an Azure datacenter to host your Service Bus, and associate it to one of your Azure subscriptions for billing purposes.
Queues, Topics and Subscriptions
In late 2011, Queues, Topics and Subscriptions went live on Windows Azure Service Bus. A Service Bus is a message-oriented middleware pattern that facilitates building loosely-coupled distributed applications. Azure Queues support reliable queuing of messages for later consumption. Azure Topics are an extension of Queues specifically intended to support the publish/subscribe pattern. These queuing and pub/sub support asynchronous de-coupling and load-balancing scenarios in distributed systems.
Queues are First In, First Out durable message containers. Multiple consumers can connect to the same Queue to create a load-balanced “competing consumer” pattern. In general, queued messages are expected to be delivered in the order received, and only once.
Queues support two methods for consumers to read messages. In “ReceiveAndDelete” mode, the message is deleted from the Queue as soon as the consumer reads it. In “PeekLock” mode, the message is hidden from other consumers after being read by the consumer. The consumer must explicitly mark the message “Complete” or “Abandon” within the lock timeout period configured on the connection to the Queue. If the message lock timeout is reached without a “Complete”, or the consumer calls “Abandon” then the message is returned to the Queue. “PeekLock” processing is often called “At Least Once” processing. In systems where it is critical that every message is processed, this is a good pattern to follow because faults in the consumer will re-queue the message for another attempt. It is important when using this pattern that the client have proper compensation processes to handle possible duplicate or out of sequence messages. The “MessageID” property on Service Bus messages can be used to track which messages have been processed in the consumer.
When using “PeekLock” with “competing consumer” it is critical that all messages and consumer processes are idempotent, as one consumer may abandon a message back to the queue while another consumer completes the message after it, and a third consumer later re-attempts the first message after the second has completed.
Topics differ from Queues in that they offer a one to many “publish/subscribe” pattern for the messages. Messages are written to a Topic the same way they are written to Queues. The difference is that Topics are write-only. Subscriptions are setup in Azure through the portal or code, and the Subscription is where the consumer connects to read the messages. Each Subscription represents a unique path for the distribution of messages. Subscriptions can also be set with filters so they only receive a subset of the messages.
Subscriptions support both “ReceiveAndDelete” and “PeekLock” consumers just like Queues, and all the same rules regarding competing consumers apply to each Subscription.
An example of when to use Subscriptions instead of Queues: Suppose you have a CRM installation configured to send messages to a Service Bus Queue each time a change is made to an Account entity, and then a listener application on Azure reads the message and updates a customer portal database in SQL Azure. The Queue model would support scale-out by having multiple consumers reading the messages from the Queue using the competing consumer pattern. Later, you decide that you would also like to post a copy of each message to a data warehouse. Suppose the portal application needs the data to update your website as soon as possible, but the data warehouse only needs an hourly update. You could add an additional Subscription to the Topic receiving the Account entity messages. The new Subscription would receive a durable copy of each message from that point forward that is posted to the the Topic.
Topics must have at least one Subscription. You will receive an error if you post a message to a Topic with no Subscriptions.
Setting Up a New Queue or Topic
To set up a Queue in Azure, click on Service Bus under Services in the portal menu. Expand the drop-down next to your Azure Subscription name and you will see the new Service Bus Namespace that we created above.
![NewSubScriptionInPortal_thumb[3] NewSubScriptionInPortal_thumb[3]](http://www.lbidotnet.com/resource/Windows-Live-Writer-736fc863794b_1468C-?fileId=16042452)
Clicking “New Queue”, on the ribbon, while the Queues list is highlighted will pop-up the Queue configuration window:
![NewQueue_thumb[3] NewQueue_thumb[3]](http://www.lbidotnet.com/resource/Windows-Live-Writer-736fc863794b_1468C-?fileId=16042454)
Clicking “New Topic” on the ribbon will pop-up the Topic configuration window:
![CreateNewTopic_thumb[1] CreateNewTopic_thumb[1]](http://www.lbidotnet.com/resource/Windows-Live-Writer-736fc863794b_1468C-?fileId=16042456)
Note how the options related to reading messages are not on the Topic as it is a write-only object.
As noted above, a Topic must have an active Subscription to receive messages. Click “New Subscription” while the Topic is highlighted to create one:
![CreateSubscription_thumb[1] CreateSubscription_thumb[1]](http://www.lbidotnet.com/resource/Windows-Live-Writer-736fc863794b_1468C-?fileId=16042458)
This is what the portal looks like after creating a Queue, Topic and Subscription:
![PortalAfterQueueAndTopicCreation_thumb[2] PortalAfterQueueAndTopicCreation_thumb[2]](http://www.lbidotnet.com/resource/Windows-Live-Writer-736fc863794b_1468C-?fileId=16042460)
Configuring CRM to Send Messages to an Azure Service Bus Queue
Using the Service Bus Plug-In for Microsoft CRM 2011
Microsoft provides a plug-in for CRM that will send messages to a Service Bus Queue or Topic. Messages sent to Service Bus using the Microsoft provided plug-in use Windows Azure Access Control Service (ACS) for claims-based authentication to the Queue. The configuration requires that the CRM server has a valid publicly signed certificate for ACS to trust the CRM server as an authorized client. There are directions on how to configure the certificate for an on-premise CRM 2011 installation here. For this walk-through, I will use a trial account for CRM 2011 Online available here. CRM Online provides a public certificate that we can use for ACS.
ACS 2.0 and Microsoft CRM 2011
The CRM SDK documentation provides a walkthrough for configuring ACS 1.0 to work with CRM. We created new Queues, in this walkthrough, after the release of ACS 2.0, so ACS 2.0 was chosen automatically as the security model for our Namespace by the Azure Management Portal. This SDK article which describes how to register an Azure-aware plug-in actually also contains the details on how to use the Plug-In registration tool to configure ACS.
Here is a summary of the steps:
- Download and unzip the CRM 2011 SDK.
- Install the correct version of Windows Identity Foundation for your version of Windows.
- Build the Plug-In Registration tool using Visual Studio 2010. The solution file is located at “sdk\tools\pluginregistration\pluginregistrationtool.sln”.
- Run the Plug-in Registration Tool.
- Click “Create New Connection”.
- Open CRM 2011 in your browser.
- Go to Settings->Customizations->Developer Resources this page contains all the CRM Discovery Service URL, Organization Unique Name, and a link to download the certificate you will need to configure ACS.
- In the Plug-In tool, name the connection in the Label field, key in the Discovery URL from CRM, and enter your CRM User Name. (Windows for on-prem or Live ID for Online) then choose connect.
- Double-click on the organization name so that the right side panel of the Tool loads your Organization.
- In the tab for you Organization, click Register->Register New Service Endpoint.
- The key fields here are Solution Namespace = to our Azure Namespace, Path = to the name of our Queue or Topic, and Queue as the Contract Type.
- Click “Save & Configure ACS”. The ACS Configuration window will open.
- Enter the Management Key from your Azure Management Portal. (Click on the NameSpace, then click View for the Default Key. Click Copy to Clipboard in the pop-up window, and then paste the value into the ACS Configuration window of the Plug-in tool.)
- If using CRM Online, click Download Certificate on the Developer Resources page. Then upload the certificate into the ACS Configuration window.
- For CRM Online, the certificate Issuer Name is crm.dynamics.com. Enter your certificate issuer name in to the ACS Configuration window and then click Configure ACS.
- If you have configured it correctly, there will be a log displaying the changes that the Plug-in tool has made to your ACS on Azure. Close the ACS Configuration window.
- Click Save & Verify Authentication on the Service Endpoint Details Window.
- You should see this window indicating that you have successfully authorized CRM to post to the Queue. Click Close.
- Click Save on the Service Endpoint Details window and it will close. You should now see something similar to this in the main window of the Plug-in Tool:
- Click the Service Endpoint so that it is highlighted, then click Register->Register New Step. You will see the Register New Step window.
- CRM uses message types for Create, Update, Delete, etc. To send all Create messages for the Contact entity, Type “Create” in the Message field and “Contact” in the Primary Entity field. Note that the Event Handler is defaulted to our Service Bus.
Confirming that CRM is Sending Messages to Service Bus
CRM uses an Asynchronous task to send messages to Azure Service Bus. It can take up to 10 minutes for a message to post to the Queue depending upon how busy your server is. To confirm that the messages are being sent:
- Open CRM and Navigate to the Contacts list
- Fill in the required fields and click Save and Close.
- Open Setting->System Jobs
If the message was sent you should see something similar to the following:![SystemJobs_thumb[4] SystemJobs_thumb[4]](http://www.lbidotnet.com/resource/Windows-Live-Writer-736fc863794b_1468C-?fileId=16042473)
If the job fails, the notes of the system job object will contain the stack trace.
Once you are comfortable that your messages are flowing correctly, you can go back to the Plug-in Tool, and check the box “Delete Async Operation if Status Code = Successful” this will purge the job from the System Jobs table if successful.
Confirming the Messages are in the Service Bus Queue
From the Management Portal for Azure, you cannot directly see the message data in your Queue, but the Portal will list the length of the Queue in Messages and Bytes.
- Open the Azure Management Portal
- Click on your Queue in the Service Bus Area
- Scroll the Properties Window on the right until you see the Queue Length field
The number listed is the number of Messages in your Queue. If you already had the Portal open when you sent the message from CRM, you may to hit Refresh on the ribbon to get the Queue Length to update.
Reading Messages from the Queue and De-Serializing the CRM Entity
The sample provided in the CRM SDK works in ReadAndDelete mode, but does not seem to work in PeekLock mode.
PeekLock requires the use of the BrokeredMessage object, rather than the Message object used in the CRM SDK sample.
Using the samples provided with the Azure SDK, I have created a listener using PeekLock, but the object returned from the Brokered Message is an XML Stream instead of the expected IExecutionContext.
I’ll provide a sample that is able to de-serialize the XML Stream back to IExecutionContext, and then extract the CRM entity, in my next post.