{TipsAndTricks} Leverage Powershell to simplify your day to day CRM tasks

I have been using powershell for sometime now for my day to day job in my CRM project. And yes, whenever I use it, I simply love it. Just today another CRM consultant walked up to my desk and saw me running some CRM commands in PowerShell and he was simply amazed about quickly we can do stuffs without actually opening CRM. I showed him al the tricks and later I thought why not post it in my blog so that anybody who still does not know how to use it, can leverage the same. And yes you can do this everything from your desktop only.

So let’s start.

The first step is download the link – https://github.com/seanmcne/Microsoft.Xrm.Data.PowerShell and download the wonderful library which make all this possible. A zip file would be download Microsoft.Xrm.Data.PowerShell-master.zip. Unzip the file, you would see one folder – Microsoft.Xrm.Data.Powershell



Copy this folder and go to the location – c:\users\<username>\My Documents\

Create the folder in MyDocuments in the following hierarchy – WindowsPowerShell –> Modules and within modules paste the copied folder.

Launch Powershell ISE. You can launch just the default Powershell window but ISE will give you intellisense as well.


Once the window loads, type the below line

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser


This line basically allows you to import the Microsoft.Xrm.Data.Powershell.dll which is unsigned. You would get a confirmation box once you execute the above code. Click on ‘Yes’

Once the above command is executed successfully, execute the below line.

Import-Module Microsoft.Xrm.Data.Powershell

Once done you are all set. But first lets see what we can do.

In the window type get-command *crm*  and you could see all the CRM related commands



There are 81 commands to use which will aid you greatly in your day-day tasks. I am not going to show all but I surely enough to make you curious and then out of the curiosity you would explore the rest Smile

First things first. People new to this might get overwhelmed about how to use these commands. No worries, PowerShell has your back here. To get detailed help for any of the commands just type the below line.

get-help Get-CrmOrganizations -detailed



Pretty detailed isn’t it.

Now the first thing you need to do is to connect to CRM organization and for that you would need credentials.

Type in the command window – get-credential. A window will pop-up to take the credential. In the below example I have take the credentials in a variable called $cred so that I can use it for later use.

Enter the credentials specific to the organization you want to connect to



The next step is to connect to the organization using the above credentials. And this what I do.


As you can see from the above screenshot, I just supplied the credentials and the Server Url. Just provide the server url not the entire organization service url. Once I press enter, system connects to CRM and determines I have access to two organizations. I select the first organization

And then my connection is set-up. Don’t worry if you are in online organization. Just like Connect-CrmOnPremDiscovery you have Connect-CrmOnlineDiscovery

Now coming to the interesting part – exploring the crm commands.


What if you have the entitytypecode and need the logical name of a custom entity. No need to open CRM. Just a single line of code in the powershell




How many times we need this? I think lot of times. I have the entitylogicalname but I need the entitytypecode. No worries just one line.




Now here comes the big one. What if you are writing some jscript code and you have a picklist to refer to but as with everyone you cannot remember the picklist text and value (I wonder who can. Must be a genius). Just a couple of lines below and you get it. And yes intellisense is there to help you as you write this code.


Wonderful isn’t it. And did you observe one thing in the above code. It’s not case-sensitive as well unlike C#.

Similar to this, you have Get-CrmGlobalOptionSet  as well to explore the global option sets.



Yes you can query records as well just like you do in query expressions. However you are limited as power of Query Expression goes.


In the above example I just querying for all the accounts whose name begins with Test and then iterating and printing the names of the returned accounts.



Say somebody would walk up to your desk and ask hey man, how many opportunities you have in your system. Say you do not have database access to run a SQL query on. And before you think of other ways, here is the code for you.


Easy isn’t it.



How many click when you export the solution? No need to open CRM even. Here is the one liner code for you.


In the above code, I am exporting a solution named ‘Sitemap’ as Managed solution and saving it in my location – c:\debajit as FromPowershell.zip.


Cool isn’t it. I would not show you all. By this time you have idea already. So start exploring. And yes you have 81 of the cool stuffs to explore. And all this from your desktop without even opening your CRM.


Hope this helps! Till you read one of my blog posts, happy CRMing.

{Utility} FetchXml to SQL converter for Dynamics CRM 2016/ 2015. Enjoy seeing your fetchxml queries getting converted to SQL without using profiler

First of all, I have been able to make this work for CRM 2015/ 2016 on-premise and IFD but does not work with online version. However I am still trying hard to make it work for online version as well. Hopefully I would be able to find a solution very soon.

Now coming to what the tool does.

  1. First of all, it is not a custom logic of string manipulation which is based on the format of FetchXml. So even if the fetch XML format changes in a rollup update, it would still work
  2. It would generate exactly the same SQL that would find if you check in your profiler, for your fetch calls.

Now coming to the requirement

How often does it happen that a view is taking significant amount of time to execute (both personal and system views) and you wish to view what is the SQL query generated behind the scenes. And sometimes you have constructed this fetchxml from advanced find and using it in your plugins and workflows and somehow that is taking a lot of time to execute. You wish if I could have the SQL for it to check what exactly is happening behind the scenes.

And below are the steps that you would normally do to view SQL query

  • Login to the database server (assuming you have access)
  • Launch the profiler
  • Run you view/ custom fetchxml
  • The profiler would generate lot of logs.
  • From the log list, find out the query for you trigger


We have all done it I guess. But you have two problems here

  • Assuming you have access to the database and launch the profiler, still it is a considerable effort to every time start a new session and take out your query from the list of logs  generated.
  • Second and perhaps the most important point here. You can use this tool even if you do not have login to the database server. Are you guessing that you still need to have System Administrator role in Dynamics CRM to use this tool? Well then I have to disappoint you here. Even if you are a sales user but still want to peek what’s going on behind the scenes, it will allow you to do so.

My team was having these repeated complaints about this and I thought why not give a weekend for this. 🙂

Download links

The tools is available for download at – FetchXml to SQL Converter

You would need to go to the Downloads section and download the version as per your CRM version




Once you download and unzip you would find two stuffs

  • Folder containing the executables
  • A managed solution.

I have using the 2016 version and this is what I see after I unzip.



The next step is to import the managed solution. Don’t worry. It is a very simple solution and it won’t even touch any of your existing entities any way.

Once the import is successful, open the executable folder and run the FetchXmlToSql.exe


The first thing it would ask for is your organization type. I have on-premise and hence I select the appropriate choices and it guides me to enter the details.


Once you enter your password and press enter, the system would search for all the organizations you have access to and show you.


I have only one. So I put ‘1’ as input in the console. If you have multiple organizations configured, all would be displayed here.

Once I select the appropriate organization and press enter, I am presented with the below choices


1 – Press 1 if you have any fetchxml saved in a file. Ideally you would use it in case you construct an advanced find query and download the fetchxml. In case you have some custom fetchxml, save it in a file. The moment you press enter, it would ask you to select a file.

2 – Using this option allows you to view the SQL query for your system views configured for an entity

3 – Using this option allows you to view the SQL query for your personal views you created for an entity.


FetchXml Input:

I enter 1 and then press Enter. It asks me to select a FetchXml file. I select a fetchxml that I downloaded from advanced find to view the enabled users for my organization.


After the file is selected, it takes some time to generate your SQL.

When done it will show a message like below screenshot.


The output file is generated in the same location as you executable. When I click open the file, I could see the same SQL being generated like the one you are familiar viewing in advanced find.


Liking it. Well then let’s explore the other options as well.


Saved Views:

I enter 2 this time and then you are prompted to enter the entity schema name. Please note you have to enter the entity logical name of the entity for which you want the system views to be displayed and not the display name. I enter opportunity.


When I press enter, I could see all the views configured in my system for opportunity.


As you can see that it displays all the system views configured for opportunity with a number for each. All you need to do is enter the number corresponding for the view you want to proceed with. I want to view ‘All Open Opportunities’. So I press 39 and then press enter


As it says, it saved to some file. I open the file and this is query generated below.

select  "opportunity0".sandisk_OpportunityID as "sandisk_opportunityid"
, "opportunity0".sandisk_opportunitytypeName as "sandisk_opportunitytypename"
, "opportunity0".CreatedOn as "createdon"
, "opportunity0".sandisk_OppCloseDateFiscalQuarterName as "sandisk_oppclosedatefiscalquartername"
, "opportunity0".sandisk_RSMName as "sandisk_rsmname"
, "opportunity0".sandisk_OpportunityValue as "sandisk_opportunityvalue"
, "opportunity0".sandisk_regionName as "sandisk_regionname"
, "opportunity0".OpportunityId as "opportunityid"
, "a_ef8066bb4eb040ba856b83c0ae259e29".StageName as "a_ef8066bb4eb040ba856b83c0ae259e29.stagename"  from  FilteredOpportunity as "opportunity0" left outer join FilteredProcessStage as "a_ef8066bb4eb040ba856b83c0ae259e29" on ("opportunity0".StageId  =  "a_ef8066bb4eb040ba856b83c0ae259e29".processstageid) order by  "opportunity0".name asc


Wow. isn’t that easy?


Personal Views:

Follow the same steps as Saved Views. Except you should chose 3 instead of 2 as input.


Now coming to another important part. The above would happen smoothly for a user who is a system administrator. However if you are a normal user, running it simply would throw an error. Don’t worry. I have you guys covered here.

The system administrator needs to open the security role you are having and then go to custom entities and then search for the entity named ‘Target Entity’


Provide access to this entity. And you are done.

The next time you run the same, you could see the the tool in action.


Leave me a comment if this tool really helped you.

If you wish to donate, you could do so at my paypal account debajit.prod@gmail.com. Your comments and support gives me the inspiration to keep me going.

{Azure-CRM Integration Blog Series} Part4– Developing a queue listener to read messages from the queue

This is the final post in the series and if the you are directly in here, I strongly suggest to start from the link – https://debajmecrm.com/2016/05/12/blog-series-complete-in-depth-walkthrough-of-dynamics-crm-plugins-with-azure-service-bus-queues/

So we are almost at the end of our journey and we just have to build a client to read the message we have posted in the queue.

If you remember, in my third post, I have explained that are three sets of permissions for a queue

  • Send – If a client is provided with Send privileges for the queue, the client can post messages to the queue
  • Listen – If a client is provided with Listen privileges for the queue, the client can process incoming messages to the queue.
  • Manage – Manage is like the admin credentials for the queue. If you give manage, send and listen privileges are included by default

Since you are just building a listener here, you should provide only listen privileges to the queue to the client. It is very important to understand this. If you do not understand how the privileges work and simply follow the steps documented in the SDK, you might end up with using the Management credentials of the entire service bus in your code. Believe me I have seen real life examples where the queue listener is constructed with the service bus root credentials. Those are like super-admin credentials and a person gaining access to those credentials can end up modifying the entire service bus configuration and not just the queue.

So let’s see how we can set-up a Access Policy with just the listen privilege.

Go to your service bus  and then open the ‘testqueue’ that we created earlier.

Click on Configure. A screen like below will come up.


Go to ‘Shared Access Policies’ section and type in a new policy name called ListenerClient. Select Listen privilege only. After all, I just need the client to read messages right?


Click on Save at the bottom. Once saved in the ‘Shared Access Key generator’ section, select the ListenerClient Policy. You would see both the primary key and secondary key.


Now we need the connection string for the Queue for the ListenerClient policy. To find the connection string, click on the Dashboard of the queue and then click on View Connection String


Copy the connection string of the Listener client from the pop-up window and store it somewhere. You will need it very soon.



So you are all set. Now I create a console application called QueueListener. 

Using Nuget, install the azure service bus dlls. Also include reference to the Microsoft.Xrm.Sdk dll


Below is the code for reading data from the queue.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.ServiceModel;
using System.Runtime.Serialization;

using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using Microsoft.Xrm.Sdk;

namespace QueueListener
    class Program
        static void Main(string[] args)
            var queueProcesssor = new QueueProcessor();


    internal class QueueProcessor
        private const string QueueName = "TestQueue";
        internal QueueClient _queueClient;

        public QueueProcessor()

        internal void CreateQueueClient()
            _queueClient = QueueClient.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]);

        internal void ProcessMessages()
                var message = _queueClient.Receive();

                if(message != null)
                    var context = message.GetBody<RemoteExecutionContext>();

                    Console.WriteLine("User Id: {0}", context.UserId);
                    Console.WriteLine("Organization Id: {0}", context.OrganizationId);


The code reads the connection string from configuration file from the Key – Microsoft.ServiceBus.ConnectionString. So add an app settings value like the one below

        <!– Service Bus specific app setings for messaging connections –>
        <add key="Microsoft.ServiceBus.ConnectionString"
            value="<Paste the connection string copied for Listener client earlier>”/>

Just a few lines of code and you are done. And when I run the code, below is the screenshot from debugger.



I hope my series of blogs have not only helped you to show how you can configure dynamics crm with azure but also helped you to understand the inner workings as well.

Leave a comment on how you liked it. Till then happy CRMing

{Azure-CRM Integration Blog Series} Part3 – ACS integration with Dynamics CRM and posting of messages to Queue

This is the third post in the series and if the you are directly in here, I strongly suggest to start from the link – https://debajmecrm.com/2016/05/12/blog-series-complete-in-depth-walkthrough-of-dynamics-crm-plugins-with-azure-service-bus-queues/

Open Plugin Registration Tool and click on Register –> New Service Endpoint

  • Name – Enter a suitable name.
  • Description -  Don’t leave this blank. It is mandatory otherwise you would get object reference error
  • Solution Namespace – This should be same as service bus namespace you created. I put the service bus namespace that we created in the previous step – crmdemo-ns
  • Path – This should be the name of the queue. In my last article, we created queue named ‘testqueue’. So I put testqueue here.
  • Contract – Since we are dealing with queues here, choose PersitentQueue from the list of values.



And you are done! Click on Save and Configure ACS button.

As soon as you click, you get a pop-up screen as shown in the screenshot below.



Management Key –

Open Azure Management Portal –> Service Bus –> Select your service bus –> Connection information (at the bottom of the screen). You should see a screen like below.


Copy the default key and paste in the management key box in plugin registration tool.


Certificate File –

The public certificate file that was used to configure Microsoft Dynamics CRM for integration with Microsoft Azure.

For Microsoft Dynamics CRM Online 2016 Update and Microsoft Dynamics CRM 2016 (on-premises), you can download this certificate file from the server. In the Microsoft Dynamics CRM web application click Settings > Customizations, and then click Developer Resources. Download and save the certificate file using the link provided below Microsoft Azure Service Bus Issuer Certificate.


Issuer Name –

The name of the issuer. This name must be the same name that was used to configure Microsoft Dynamics CRM for Microsoft Azure integration. You can obtain the issuer name from the Developer Resources webpage mentioned in the previous description.



Click “Configure ACS”. The system will create Rulegroups and relying party applications. Once done click on ‘Close’ and then click save on the main plugin registration window. So you have set-up Dynamics CRM to integrate with the queue to send messages. This steps you can even find in the SDK. Nothing new in that. But wouldn’t you like to know what happened inside. Come on – let’s explore it together.

Open Azure Management Portal –> Service Bus –> Select your service bus –> Connection information (at the bottom of the screen). In the pop-window click on ‘Open ACS Management Portal’ at the bottom of the screen.


Once the ACS management portal opens, go to ‘Relying Party applications’. Remember in the first post of this series, I explained that Queue would be set-up to trust the ACS for authentication. This is what CRM plugin registration tool has done. It has create an entry for the Relying Party.


Open the record. You would see a screen like below.


The field “Realm” is the path to the relying party. Any claims issued by ACS for realm would be valid.

In the ‘Authentication Settings’ section, the identity provider is selected as Windows Live Id. This is because Dynamics CRM online is based on the Office 365 credentials.

And then you have Rule Groups. Now these are the rules which dictates how the claims generated from Dynamics CRM identity provider are transformed into ACS token claims which is understood by the relying party. As you can as a part of the configuration process, Dynamics CRM has created a Rule group name ‘Rule group for testqueue’.

Let us open this rule group and check what rules are in there.


So as we can see, we have four rule groups. If you remember my first post in the series, the first thing that should happen is that when a user from Dynamics CRM posts a message to the Service Bus queue, CRM would validate the credentials and generate an IP token which will be passed to ACS in the next step. The rule which does that in the above screenshot is highlighted. If you see, the claim issuer is ‘crm.dyanmics.com’ which is the service identity that we set up in an earlier blog post in this series.

Unfortunately, ACS management portal does not support claim rules set-up from service identities. It supports claim rules set-up for only identity providers. So if you open this record you would see something like below. You can access this programatically however. If interested please explore it.


But as far we know what is going on here, we are good.

Now comes the other three rules. Before I explain the above rules, we should first know that a queue has three set of permissions ‘Send’, ‘Listen’ and ‘Manage’. For e.g if you have listen permissions, you can just connect to the queue and receive messages from the queue. You cannot however send a message to the queue.

Now coming to the rules, you can see that dynamics crm configuration process has create three separate claims rules for three permissions

  • sampleorgsendrule
  • sampleorglistenrule
  • sampleorgmanagerule

So now you understand why three claim transformation rules are set-up. I have been through many articles but in none I could find it properly explained regarding why these four claim rules. So I decided to pen it down.

Since we would be posting messages to the queue, I think you have already guessed it. We need to check the Send Rule. So let’s explore the ‘sampleorgsendrule’.


As you understand things, it becomes pretty obvious right. The first thing to notice here is the ‘Input claim Issuer’ section. As you can see Access Control service is selected. Remember I explained in the first post. The ACS converts the token from Identity Provider (IP) into claims which are understandable by the Relying party (queue).

However check for the value of the Input claim. It is specified as owner. Here we just want this rule to execute only if the input claims are from Dynamics CRM. For this I will substitute this value with the unique name of my CRM organization which you can find in Settings –> Customizations –> Developer resources.

One very important thing to remember here is for on-premises, you need to specify the Org Unique name. However for online it should be full host name. Since my organization name is sltraining, so for me the value would sltraining.crm.dynamics.com. Below is the screenshot after edit.


And finally the output claim value is set to ‘Send’. So basically ACS takes the name identifier claims and converts it into Send claim which is understood by the queue.

So now we are all set to send a message to this queue.

Open Plugin registration tool one more time. Right click on the service endpoint we created and click on register new step. Enter the below details.


What we are basically doing here is on-post create of an account we are posting the context information to the Queue. Remember to mark it asynchronous. CRM will not allow you to register Synchronous step here.

So all set and done. Let’s just go ahead and create a new account. Once account creation is completed, go to Settings-> System Jobs. If your configuration is correct, you would see that the post to queue is successful.



In my next article and which is the final article in the series, I will explain how to retrieve this message from the queue – https://debajmecrm.com/2016/05/12/azure-crm-integration-blog-series-part4-developing-a-queue-listener-to-read-messages-from-the-queue/

{Azure-CRM Integration Blog Series} Part2 – Azure Queue and Identity Provider Configuration

This post is a continuation of my previous post. If you have not read the previous post, I would strongly suggest to read the same and come back here. Here is the link –


In this article we will understand how to configure a queue where Dynamics CRM can post messages and also configure Dynamics CRM as identity provider.

If you are familiar to Azure, normally it is just a few clicks to create a service bus namespace through the azure management portal. However with CRM, it’s a bit trick. This is because Dynamics CRM will automatically append “-sb” to the service bus namespace to identify the access control services namespace. Unfortunately with the latest version of Azure, an associated access control namespace does not get automatically created when you create a service bus. Don’t worry, you can still do that with Power shell. After all limitations sometimes help us to explore new ways as well.

So if your service bus URL is – xrmsdk-ns.servicebus.windows.net, then while configuring ACS, the plugin registration tool will automatically append “-sb” to service bus namespace and try to search for ACS. In this case it would search ACS with the URL – https://xrmsdk-ns-sb.accesscontrol.windows.net

Unfortunately with the latest version of Azure, an associated access control namespace does not get automatically created when you create a service bus which used to happen previously. Don’t worry, you can still do that with Power shell. After all limitations sometimes help us to explore new ways as well.

Download Azure Powershell from the below link.



Once downloaded open Powershell. First type Add-AzureAccount. This will ask to enter you to login to your azure account



Once logged in, you could see your subscription details



Next Type -New-AzureSbNamespace -name crmdemo-ns -CreateACSNamespace 1

Remember here, –createacsnamespace is the flag which creates an associated ACS namespace along with the service bus. With –name we are setting up the service bus namespace. It will prompt for NamespaceType. Enter messaging in the prompt. It will take some time to get the stuffs created.



Once done, you would get all your service bus details.


Now open Azure Service management portal. Go to Service Bus. You should be able to see the newly created service bus namespace.


Open the namespace and then go to Queues and create a new Queue by clicking in the ‘New’ icon in the bottom left corner of the screen. I have named is testqueue


And you are done setting up the queue.

Now in the previous post, I have explained that the whenever something needs to be posted to the queue, Dynamics CRM would be verifying the incoming credentials and provide an IP token. So dynamics crm is our identity provider here. So let’s set up our CRM as identity provider.

Open Azure Management Portal –> Service Bus –> Select your service bus –> Connection information (at the bottom of the screen). You should see a screen like below.


Click on ‘Open ACS Management Portal’.

In the ACS management portal, click on the ‘Service Identities’ under ‘Service Settings’ section. We are configuration Dynamics CRM as Service Identity and not Identity Provider. In Microsoft Azure Active Directory Access Control (also known as Access Control Service or ACS), a service identity is a credential that is registered with an Access Control namespace and is intended for use by autonomous applications or clients. To know more you can visit this link – https://msdn.microsoft.com/en-us/library/gg185945.aspx

Click on Add to add a new Service Identity.

In the name field enter the issuer name. To get the issuer name go to Settings –> Customizations-> Developer resources. And copy the value from the issuer section.


Click on ‘Download Certificate’.

In the “Credential Settings” section select X.509 certificate and then upload the downloaded certificate file.


Click on save and you are done. So we have successfully set-up the queue and also Dynamics CRM as identity provider.

The next step is to configure your Dynamics CRM with Azure from the plugin registration tool which is explained in the next article – https://debajmecrm.com/2016/05/12/azure-crm-integration-blog-series-part3-acs-integration-with-dynamics-crm-and-posting-of-messages-to-queue/

{Azure-CRM Integration Blog Series} Part1 – Understand the basics

You might be thinking, we already have so many wonderful blog articles which explains how to do this. I agree. But in most of the cases, not the whole steps from the start to finish is mentioned to make it work in real life. In some cases, it is neatly depicted what you should do but why are you doing the same is missing. After all knowing the why part of it with the how part is something we always desire and helps us to design better solutions going forward.

So if you have not tried this, I hope that after reading this post you would understand things better than before. On the other hand if you have configured and the integration works for you as well but you are not sure about how it works, I would suggest you read this. If you have very good idea of what Azure Service bus is and how does ACS authenticates with service identity, unfortunately there is nothing new for you guys here. Smile

So let’s start. Let us split out the components and understand what role they play in this integration.

First is Azure Service Bus. For a quick understanding just think of it is a broker which passes messages between two components. You can compare this to postal services. You want to send a message to someone residing in some other part. You use the postal services. It takes the message from you and delivers it to the appropriate receiver. How does the postal service identify the receiver? Well you have mentioned the address right in the message envelope.

Comparing to the above, Dynamics CRM is the sender and a Queue configured in Azure service bus is the receiver. All you need to do is configure your service bus to collect the message from CRM and deliver it to the queue. And like the postal service, you would indeed need to provide the address of the queue to the service for it to deliver the message correctly.

So the whole thing works like this. A user of Dynamics CRM will post information to the Queue hosted in azure service bus. The service bus would need to authenticate CRM User against the queue. Any Dynamics CRM user who posts information to the queue and those claims should be understood by the Queue. Now since these are two separate applications, the claims generated from one might not be understood by the other as they might not speak the same language.

So now what. Here in comes the concept of Access Control Sevice in Azure Bus Services. The queue will be set-up to trust the Access Control service and any claims generated from the  ACS would be accepted by the queue as a valid token and it would allow those messages to be sent to the queue.

The mechanism is very well explained in the below screenshot.


IP –  Identity Provider. Here Dynamics CRM is identity provider.

ACS – The Access Control Service of Azure Service Bus

RP – Relying party which trusts the ACS. For our example it is the Queue.

Client – The user of Dynamics CRM who is trying to post message to the queue.


The mechanism is explained in the following steps.

  • A user in Dynamics CRM tries to send a message to the queue.
  • Since the queue does not get a valid ACS token, it redirects the user to the ACS
  • The ACS in turn redirects the user to the Identity Provider which in our case is Dynamics CRM
  • Dynamics CRM verifies that the request is generated from a valid user and generates a IP token (identity provider token).
  • The user sends the IP token claims to the ACS
  • ACS does the hard job of converting claims from IP token to appropriate claims understood by the Queue and sends an ACS token to the user.
  • Now since the Queue trusts token generated from ACS, it will allow the message into the queue.

Hope now things are getting cleared up. And since we now understand the basics, once we do the steps, we know why are we doing this apart from how to do it.

So let us check all the steps we need to do for this. I have broken this down in a series of blog post otherwise a single post would be pretty lengthy.

The next article explains on how to set-up the queue and also configure dynamics CRM as identity provider – https://debajmecrm.com/2016/05/12/part-2-complete-in-depth-walkthrough-of-dynamics-crm-plugins-with-azure-service-bus-queues/

{Knowhow} Get count of Attachments for Email in Dynamics CRM without code

Recently we had a requirement from our customer to show the number of attachments for each email in a view. The number needs to be reflected whenever the user refreshes the view.

Simple requirement right? And what is coming to your mind? Plugins? Workflows?

Well if you are thinking of the Plugins and workflows, I am sure you are not alone. In fact the first thing that came to my mind was the same. But we are in CRM 2016 right? And is there no other way to achieve this?

I brainstormed for sometime and then came up with the below solution. Believe me it is a simple solution without any code and I am pretty sure you would like it. No it is not rollup field. It is using the calculated field feature of Dynamics CRM.

Let us first look at the email entity in CRM. A quick glance at the email entity and you could see there is field already in the email entity called ‘Attachment Count’. Wow! Can’t we use this field. Unfortunately the answer is ‘No’. If you open this field, it is a non-editable field and it won’t appear in your view and advanced find as well. Nor you can use it in roll-up fields or calculated fields editor. Sad isn’t it.




I was pretty sure that this field could give us the count of attachments for an email. But how to get around the limitation. Well you have CRM 2016 after all which is just awesome. All we consultants need to do is to explore it a bit to make it work for all situations Smile

To start with I created a solution with the email entity in it. And then I created a dummy field called ‘Attachment Count Dummy’. Don’t worry I am just creating a dummy field here. I will delete it later when done. As of now just make sure you make the field as ‘whole number’ type.



Great. So we are done with our first step. Now we create our real field to store the attachments. I name it the same ‘Attachment Count’ of type whole number. But this I make it a calculated field.


I set it to be equal to ‘Attachment count dummy’ field. You may be asking why not set this field to the OOB attachmentcount field. Because as I mentioned before, the OOB attachmentcount field cannot be used in calculated field editor.


Save and close the editor. Include this calculated field in whichever views you want.

All set and done. Now comes the real trick. Publish everything and export the solution. Once the solution is exported, unzip it and you would see the contents. It should have a Formulas folder where CRM stores all the calculated field formulas.



Open the folder and then open the formula of the ‘Attachment Count’ calculated field .xaml file in a xml editor of your choice. Replace the dummy field name with the name ‘attachmentcount’.  Note this is the most important step.







Save and close the file. Now zip the contents of the solution back and import the solution again in your CRM environment. Once the publish is completed, open advanced find and then check for the views


I open my email, attach one more attachment and as soon as I refresh the view, I could see the count being incremented.



Are we missing something here? Yes. You remember we created an extra dummy field. Go ahead and delete it. It won’t do any harm if you delete it. But you would be left with an unnecessary field.

Wonderful isn’t it? I hope you liked the idea.