Actions in CRM 2013

One of the most powerful features introduced in CRM 2013 is Actions. It strongly supports the concept of XRM platform. Actions are the Custom messages which can be created for any entity or globally to perform business operations like create/update/Assign etc. (more than what a Workflow can do). Looking first time we get a feeling that it is very similar to Workflow but hold on it’s very different from WF’s or Plugins.

Below are the key points which make it different:
  1. Can be associated with single entity or globally.
  2. Actions support Arguments – Input and Output Arguments.
  3. Can be only called through web service calls – either JavaScript/Plugins/Web through API calls.
  4. Supports Rollback and executes in real time.
  5. Always runs under the context of the calling user.


Arguments are the parameters or the variables which can be used while creating the action. There are two kinds of arguments

 Input Arguments:

These are the parameters which need to be passed during action call. These can be Optional/Mandatory. For Mandatory argument it is necessary to provide some value while calling this action. These input arguments can be used as variables while performing any operation in the action.

Output Arguments:

These are the parameters which can be returned when the action is called. These can be Optional/Mandatory.

To understand in an easy way we can compare actions with a Function/method in normal C# programming which can have parameters and also can return something at the end.

Let’s take a look of the different types of Arguments it supports.



Let me create a simple Action on Enquiry entity which has one Input Argument: ProjectName [string]

To create this we need to navigate to Processes and select Category as Actions. In primary entity I am selecting Enquiry which is custom entity in my case. I have taken one Input Parameter- ProjectName. And in the step I am using this Variable during creating a Project’s record which is again a custom entity.


And here is the snap of the Step which I have configured. Here we can see that I am using this ProjectName as a dynamic value during the Project Creation. Here note that new_EnquiryCreateProject is the name of the Action which should be referred while calling this through API.


Let’s activate this Action and see how we can call this from Plugin or JavaScript.

Calling Actions from Plugins

Now we can call this Action from our Plugin. I have a Plugin which fires on Post Create of Enquiry. There I am calling this Action. I am passing the Input Argument ProjectName as Parameter before calling this Action. Once this is called It creates a new Project record.

// Calling the Action - new_EnquiryCreateProject
OrganizationRequest req = new OrganizationRequest("new_EnquiryCreateProject");
req["ProjectName"] = "This is a test operation for using Actions in CRM 2013 ";
req["Target"] = new EntityReference("new_enquiry", enquiryObj.Id);

//execute the request
OrganizationResponse response = service.Execute(req);

Calling Actions from Javascript

Yes we can call Actions through JavaScript. I have a stage field in the Enquiry entity and on Change of Stage field I want to call this Action. Let us see below how we can use this.

 function CallActionFromJavaScript() {
    var projectName = "Project Created through Action from Javascript";
    var entityId =;
    var entityName = "new_enquiry";
    var requestName = "new_EnquiryCreateProject";
    ExecuteActionCreateProject(projectName, entityId, entityName, requestName);}
function ExecuteActionCreateProject(projectName, entityId, entityName, requestName) {
    // Creating the request XML for calling the Action
    var requestXML = ""
    requestXML += "<s:Envelope xmlns:s=\"\">";
    requestXML += "  <s:Body>";
    requestXML += "    <Execute xmlns=\"\" xmlns:i=\"\">";
    requestXML += "      <request xmlns:a=\"\">";
    requestXML += "        <a:Parameters xmlns:b=\"\">";
    requestXML += "          <a:KeyValuePairOfstringanyType>";
    requestXML += "            <b:key>Target</b:key>";
    requestXML += "            <b:value i:type=\"a:EntityReference\">";
    requestXML += "              <a:Id>" + entityId + "</a:Id>";
    requestXML += "              <a:LogicalName>" + entityName + "</a:LogicalName>";
    requestXML += "              <a:Name i:nil=\"true\" />";
    requestXML += "            </b:value>";
    requestXML += "          </a:KeyValuePairOfstringanyType>";
    requestXML += "          <a:KeyValuePairOfstringanyType>";
    requestXML += "            <b:key>ProjectName</b:key>";
    requestXML += "            <b:value i:type=\"c:string\" xmlns:c=\"\">" + project
Name + "</b:value>";
    requestXML += "          </a:KeyValuePairOfstringanyType>";
    requestXML += "        </a:Parameters>";
    requestXML += "        <a:RequestId i:nil=\"true\" />";
    requestXML += "        <a:RequestName>" + requestName + "</a:RequestName>";
    requestXML += "      </request>";
    requestXML += "    </Execute>";
    requestXML += "  </s:Body>";
    requestXML += "</s:Envelope>";
    var req = new XMLHttpRequest();"POST", GetClientUrl(), false)
    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "
    //Get the Resonse from the CRM Execute method
    //var response = req.responseXML.xml;
function GetClientUrl() {
    if (typeof Xrm.Page.context == "object") {
        clientUrl = Xrm.Page.context.getClientUrl();
    var ServicePath = "/XRMServices/2011/Organization.svc/web";
    return clientUrl + ServicePath;

And now the most Amazing part of Actions are that we can consider this as a unique message and can register this through Plugin registration tool and can do Custom Validations if we want to do during the execution time.

Let’s say during the execution of this Action I want to validate something or abort this Operation in certain conditions then we can easily do by registering this as a message which is  a great example of Xrm support in CRM 2013 as now it is not restricted to messages like Create, update, delete etc.

Below it is shown how we can register this through Plugin Registration Tool.


Note: These actions are little bit different from Plugins as return type of the Target is not Entity but it is Entity Reference. During the execution of this Action we can get the Input Arguments and use this for any type of validations.

Below is the sample where I am reading the values of the Target and the Input Argument ProjectName used in the above example.


Here we can clearly see that the context contains only 2 values one is the Parameter and the other one is the Target.

As a developer, introduction to Actions in this CRM 2013 release is really a great improvement from CRM’s perspective which will help us to minimize the coding part and also achieve some complex requirement easily.

Happy Reading!!!!!


, , , , , , , , , ,


Error while publishing entity in CRM 2011

I was getting the below error while  publishing a particular entity as System Admin  in CRM 2011, though was not getting the error for other entities . The error was

The Requested record was not found or you do not have sufficient permissions to view it.”

The details of the error are :

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: role With Id = 3adccc07-6293-4cac-b790-4be053184063 Does Not ExistDetail:
<OrganizationServiceFault xmlns:i=”; xmlns=””&gt;
<ErrorDetails xmlns:d2p1=”; />
<Message>role With Id = 3adccc07-6293-4cac-b790-4be053184063 Does Not Exist</Message>
<InnerFault i:nil=”true” />
<TraceText i:nil=”true” />


The below link helped me to solve the problem which was removing the extra form for this entity, I had 2 forms out of which one I was not using.

Though I do not fully agree on removing the extra form concept just to get rid of this problem,because this may not be the actual Problem but u know when something works for us we take it with both hands……





Leave a comment

Exporting SSRS report to Word giving Error in CRM 2011

Recently in my Project I was getting a error for one of the report when I was trying to export to Word. Having not faced this issue before we started to hunt for the solutions. Then came to know that if the report is having more no of individual controls then while rendering that to word gives issues. To get rid of this you can group the controls in some other control(For Eg. Rectangle).

And here u go  …. your issue fixed ….

Below URL is a handy one  …

, ,

Leave a comment

2012 in Review

The stats helper prepared a 2012 annual report for this blog.

Here’s an excerpt:

4,329 films were submitted to the 2012 Cannes Film Festival. This blog had 18,000 views in 2012. If each view were a film, this blog would power 4 Film Festivals.

Click here to see the complete report.

Leave a comment

By default all fields getting updated issue while using oData(REST) endpoint for Web Resources in Silverlight in CRM 2011

Recently I was facing a typical issue, while updating a couple of fields of a form using REST Endpoint in Silverlight, by default all the fields in the form was getting updated to null. I found this as very strange behavior by using REST in Silverlight.

In seek of answer I found that it was the default feature when you use REST Endpoint in Silverlight in CRM 2011.

The Below URL helped me lot which talks in very detailed manner the actual cause and Resolution.

Happy Reading …

, , , , ,

Leave a comment

Programmer’s …..

Just thought of sharing it …….


Leave a comment

Update Rollup 6 for Microsoft CRM 2011

Hey Guys, Microsoft has released Update Rollup 6 for CRM 2011 with many changes and fixes. You must have Microsoft Dynamics CRM 2011 build 5.0.9688.583 installed to apply this update rollup. You can get the latest Update Rollup 6 from

For the list of new improvements and changes you can go through the below KB article

, , ,


Activity Feed in CRM 2011

Activity Feed is a very interesting features introduced in CRM 2011. But it has not become as famous as it should be and one of the most obvious reasons may be that still it has few Question (?) marks that needs to be answered or solved when it comes to security and usability in an efficient manner.

In my opinion still some of the features can be improved as of now in order to accept this globally. But still what we have is lot to cheer about. Why I am dough ting at this time I will clarify later in this post.

Let see how we can use this and take the most out of it.  You can get the Activity Feed solution from the Dynamic Marketplace in CRM Settings tab or you can just do Google. The CRM 2011 server setup that was released before Nov 2011 does not contain this solution. So you have to download and import it manually. But in all the latest CRM versions that are coming after Nov 2011 have this activity feed solution installed from before whether it is Online or On- Premise.

Let’s understand the common terms associated with this. We can say it can act as a Twitter for the CRM users plus lot of many other functions.


Post is an Entity and whatever you write is saved internally as a record. So every item on your wall is a post. It is yet like another entity. You can create new post through Plugin, workflow etc. You can even trigger anything on different operation performed. We will see how to create a post from workflow to meet our business need.


Wall is nothing but the UI html page what we see where all the posts are visible. Records even can have wall and a tab ‘Record Wall’ can be seen for that record.


Follow and Unfollow are the two options that will be visible for all entities but will be enabled for only those entities for which the activity feed will be configured.

Configuration of Activity Feed

After importing the solution you will find three links in what’s New in the Workplace Area and the other two as shown below

Let’s configure some entities. Click Activity Feed Configuration and create records for the entities which we want to configure. Remember give the schema name of entity and not the display name.

The interesting thing I found that we cannot define Rules for the entities. Because we cannot find any add New Rule or Existing button. However the system creates few rules for the few entities that exist from before like Lead, Opportunity, etc.

We can configure for custom entities also but cannot define rule directly which I found the funniest part. I hope that issue gets solved in the coming versions /updates. At present if we want to define some rules for custom entities than we can do that by configuring with a workflow.

For following a multiple records we can do Advance Find select the records to Follow or UnFollow.

Workflow to create a Rule and Post Automatically for Custom Entity

We will see how we can configure activity feed for a custom entity. This can be done through a workflow.  Let’s take a custom entity called “Investor”. So whenever investor is created by any user then we will post stating that an Investor is created. Let it act as a Notification. Let it as simple as this. Anyways we can do a lot and configure the workflow for our custom logic but here we are going through a sample.

        1. Create a Process of category as “Workflow” and configure for ‘When record is created’ as shown below

          2. Now we will configure the properties.

Here we can see the Dynamic value assigned called “Post URL (Dynamic)“. This option is only visible when we have the latest Update Rollup installed. This is basically used to provide a link to that record. So we can open that record by clicking this. This is a new feature update from Microsoft in CRM 2011. Really this is very helpful while creating email form the workflow. We can directly open the record from the Email.

Anyways configuring this workflow save and Activate this workflow.

Result: Now whenever the Investor record is created automatically a post will be created. We can see this post in the What’s new  in the Workplace Area. Here we have created investor record DTest10.

Note: Yet a lot of things are missing and I think that it needs to be improved a bit more so that it can be accepted widely. Few things that are strange or lack in the current version of the solution are in my opinion are:-

1. We cannot create Rules as per our choice for the entities. Eventually we opt for Workflows to configure. 

As we can see that there is no New Button to add any Rules.

2.  The post lacks security. This means that anybody who can view that post can delete that post which will be deleted from the system. This means that the person that created that post is not the sole owner of that post. Even we cannot set anything from the roles and permission point of view.

3. The system creates rules for some of the predefined entities like lead, contact, opportunity etc. We can’t add the rules to the entities configured and yet there is Grid where it can be added.

So these were my concerns in terms of usability. Hope this gets better in the coming versions or update.

 Happy Reading !!!!!!!

, , , , ,


Retrieve Option Set Selected Text Value in CRM 2011

Retrieve Option Set Selected Text Value  in CRM 2011

In CRM 4.0 it was very easy to get the Picklist Selected Text value. But in CRM 2011 the Picklist has been changed to Option Set and interestingly they have not exposed any Property to get Text value of the selected value.

So now we can get the value only from the Metadata. It’s not huge but simple to implement. Below is the method which returns the Selected Text Value on Passing the Integer Value.

public string GetPickListText(string entityName, string attributeName,int optionSetValue,IOrganizationService service)
    string AttributeName = attributeName;
    string EntityLogicalName = entityName;
RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
    EntityFilters = EntityFilters.All,
    LogicalName = EntityLogicalName
 RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
 Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
 Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
 Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
IList<OptionMetadata> picklistOption = (from o in options.Options
 where o.Value.Value == optionSetValue
 select o).ToList();
string picklistLabel = (picklistOption.First()).Label.UserLocalizedLabel.Label;
 return picklistLabel;

Now by using this we can easily get the selected option set value of any attribute of any record. Now to retrieve the text value we need to pass the value of the option set.

For e.g [How to call] To Get the selected text for Shipping method for a contact record

IOrganizationService service = GetCrmService();//Get the Crm Service 
string textValue=GetPickListText("contact","address1_shippingmethodcode",5,service) ;

I hope this really helps. HAPPY Reading !!!!!


, ,


Filtering records of any entity on top of Role and Permission

Filtering records of any entity on top of Role and Permission

Many times as a developer point of view we get some requirements which are complex in terms of designing and to meet such type of requirement we look to find an alternative solution.

Recently in my project I faced an issue regarding the Security Role for a Specific Type of User(Role). I would like to share the scenario. I had to filer the records of a particular entity dynamically based on a PickList value of that form. I mean in real the problem and the requirement was much more complex but let not focus on that. Let’s see how we can filter the record on top of the role privileges.

To solve my problem I wrote a plugin and registered for a RetrieveMultiple message.

// Obtain the execution context from the service provider.
IPluginExecutionContext context=(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.Mode == 0 && context.Stage == 20 && context.MessageName.Equals("RetrieveMultiple"))
  if (context.InputParameters.Contains("Query"))
     if (context.InputParameters["Query"] is QueryExpression)
         QueryExpression objQueryExpression = (QueryExpression)context.InputParameters["Query"];

       if (objQueryExpression.EntityName == "entityName")
          IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
          service = serviceFactory.CreateOrganizationService(context.UserId);
          ConditionExpression conExpress;
          string role = string.Empty;

          role = getUserRole(context.UserId);//Method to get the role of logged In User
          if (role.Contains("roleName"))
             conExpress = new ConditionExpression()
                AttributeName = "attributeName",
                Operator = ConditionOperator.Equal,
                Values = { "1" }
           // show all for legal , finance, system admin

           conExpress = new ConditionExpression()
             AttributeName = "attributeName",
             Operator = ConditionOperator.In,
             Values = { "1", "2", "3" }

       FilterExpression newFilter = new FilterExpression()
           FilterOperator = LogicalOperator.Or,
           Conditions = { conExpress }


Here I have used the method getUserRole() but not shown in the code. We can get the role easily by using Linq, FetchXml or any other means. Anyways that was not the agenda for this article.

I have tested this plugin & its works fine without any Performance Issue. Below I have shown the registration steps for this plugin.

Note: If you are checking the entityname inside the plugin then its fine you can register the plugin as above otherwise you c an mention the entityname also in the Primary Entity in the above registration  step.

This RetrieveMultiple can be used for multiple purposes for eg for filtering of records in Lookup etc. I hope this really helps.  HAPPY READING !!!!!!!!!!!!!!!!!!

, , , ,

1 Comment

Developer ToolKit in CRM 2011

Developer ToolKit  in CRM 2011

Microsoft has provided the developer toolkit for CRM 2011. But it is unfortunate and sad that lot of people are either not aware or after knowing also do not like to use for their development purpose. But I found it really helpful for development as it can really increase the speed of the development. This tool is integrated with the Visual Studio 2010 to accelerate the development of custom code for Microsoft Dynamics CRM solutions.

This tool comes with the latest CRM SDK version 5.0.7 You can download this from

The Developer Toolkit can be found in the following location in the SDK .sdk\tools\developertoolkit folder. Just run the crmdevelopertools_installer where your Visual Studio is present. Just remember you need VS 2010 with Silverlight 4 for proceeding with this developer toolkit development.

Please follow the below link to get a good picture…. It’s really nice …

Happy Learning ….!!!!!!!!1

, , ,

Leave a comment

oData and JScript in CRM 2011

oData and JScript in CRM 2011

Before going through the usage of oData in CRM 2011 first let us understand what is oData and why it is introduced in CRM 2011.

What is oData ?

oData is also referred as Open Data Protocol. CRM 2011 mainly uses Windows Communication Foundation (WCF) data services framework to provide oData Endpoint which is nothing but a REST based data service. The address for the endpoint is:

http://{OrganizationRootUrl} /XRMServices/2011/OrganizationData.svc

Now What is REST ?

REST(Representational State Transfer) is an style of referring data in which every resource can be referenced by a URL mainly in Microsoft CRM. Here resource is nothing but the entity or record or an image etc. So now in CRM 2011 we can reach to the record collection by the URL (properly defined syntax).  Microsoft has provided some syntax styles  which should be followed to access a resource.

oData uses some data  format for sending and receiving the data. Basically it uses the following two formats.

  1. ATOM: It is an Xml based format mainly used for the RSS feeds.
  2. JSON: JavaScript Object Notation is a text formats which makes very easy for the developers to understand the response what we get. For more info please visit:

For eg: For getting all the contact record set the URL can be like

http://{OrganizationRootUrl} /XRMServices/2011/OrganizationData.svc/ContactSet

We can also select few attributes by using a” select “command.

          http://{OrganizationRootUrl} /XRMServices/2011/OrganizationData.svc/ContactSet?$select=FirstName,LastName

This will give a collection of First Name and Last Name for all the contacts. Lot of other stuffs is also possible like filtering, ordering, paging etc.

Now we will see how we can implement in Jscript in CRM 2011. Below is the sample code for fetching the Contact’s PrimaryEmailId form an Account form. Save the code as some js file and upload as a WebResource(Jscript). Refer this in accounts WebResources and call the function OnLoad() in the OnLoad event of account entity.

function OnLoad() {
    var serverUrl = "http://" + + "/" + Xrm.Page.context.getOrgUniqueName();
    var primarycontact = Xrm.Page.getAttribute("primarycontactid").getValue();
    var primarycontactid = primarycontact[0].id;

 // Creating the Odata Endpoint
    var oDataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    var retrieveReq = new XMLHttpRequest();
    var Odata = oDataPath + "/ContactSet?$select=EMailAddress1&$filter=ContactId eq guid'" + primarycontactid + "'";"GET", Odata, false);
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.onreadystatechange = function () { retrieveReqCallBack(this); };

function retrieveReqCallBack(retrieveReq) {
    if (retrieveReq.readyState == 4 /* complete */) {
        var retrieved = this.parent.JSON.parse(retrieveReq.responseText).d;
        var EmailAddress = retrieved.results[0].EMailAddress1;

Test: Create a contact record and put some email id in the Email field. Save the record. Now create one account record and refer this contact in the primarycontact field.  Now whenever you open a account record that has primarycontact the email id will be alerted.      Note: The name of the attributes in the select and the filter criteria are not the actual attributes names but these are the schemas names for that fields so please be careful while referring to the values.Hope this gives a basic idea of oData in CRM 2011…… Happy Reading !!!!!!!!!!!!!!!!!!!!!!!!!!!!!1

, , , ,




LINQ(Language Integrated Query)to XML is the modern way of dealing with XML data. The Linq to Xml came with the.Net Framework 3.5. Before that we were using XMLDocument which follows the DOM architecture. But with the introduction of LINQ the task has been reduced a lot coding wise for the developers. But for type of operations the whole XML Document has to be loaded in memory.

Today we will look how we canperform certain operation on Xml data using the Linq to XML architecture.

Reading the Xml and Storing in List

Lets create a sample XML which we are going to use read using Linq to XML feature. The below XML is our sample xml lets name it as “Sample.xml”.

    <Employee Id="1">
        <Info Name="aaaaa" Age="24" Sex="Male"></Info>
        <Info Name="bbbbb" Age="25" Sex="Male"></Info>
    <Employee Id="2">
        <Info Name="ccccc" Age="26" Sex="Male"></Info>
        <Info Name="ddddd" Age="27" Sex="Female"></Info>

Lets create a class a define some

property that can hold the xml values. Lets name this class as ReadingXmlWithLinq.cs

public class ReadingXmlWithLinq
            public string Name { get; set; }
            public string Age { get; set; }
            public string Sex { get; set; }

Now let’s see how we can read the Sample.xml file using Linq to Xml concept.

using System;
using System.Linq;
using System.Xml.Linq;

private IList<ReadingXmlWithLinq> GetXMlList()

   XDocument configparentXML = XDocument.Load(xmlPathAddress);
   string node = "Info";
   var configs = (from config in configparentXML.Descendants(node)
   select new ReadingXmlWithLinq
       Name = config.Attribute("Name") != null ? config.Attribute("Name").Value : "",
       Age = config.Attribute("Age") != null ? config.Attribute("Age").Value : datatable,
       Sex = config.Attribute("Sex") != null ? config.Attribute("Sex").Value : "",
   IList<ReadingXmlWithLinq> rules = configs.ToList();
   return rules;

Now this will return a list of four elements. Thus we will get all the four rows values. Thus rules[0].Name will give “aaaaa” and rules[3].Name will give “ddddd” Now what if I need only those info whose Id is 1. That is Node Attribute value Id. So now this looks little  difficult. But if we are using Linq it is quite simple. Lets see

private IList<ReadingXmlWithLinq> GetXMlList()
            XDocument parentXML = XDocument.Load(xmlPathAddress);
            string node = Employee;
            string IdValue = "1";

            var parentconfigs = from config in parentXML.Descendants(node)
                                where (string)config.Attribute("Id") == IdValue
                                select config;
            string childnode = "Info";
            configs = (from config in parentconfigs.Descendants(childnode)
                       select new ReadingXmlWithLinq
                           Name = config.Attribute("Name") != null ? config.Attribute("Name").Value : "",
                           Age = config.Attribute("Age") != null ? config.Attribute("Age").Value : datatable,
                           Sex = config.Attribute("Sex") != null ? config.Attribute("Sex").Value : "",

            IList<ReadingXmlWithLinq> rules = configs.ToList();
            return rules;

Now the above function will return only two values that is Employee ID’s value equal to 1. Thus we can get selective value based on certain criteria or condition. This is pretty simple and easy as compared to the traditional way of handling. 

, , ,

Leave a comment

CRUD Operation (Early Bound Classes) using WCF services in CRM 2011

Working with Early Bound Classes with CRM 2011 WCF Services.

Before starting the development we should see the Services involved

1. IDiscoveryService : The IDiscovery Service is a global service used to determine the Organizations that the system user is a member of, and the endpoint address URL to access the IOrganization service. This is basically used when we have multiple organizations in the same CRM Server and we need to know all the organization and their IOrganization Services URL’s at runtime or  through the code.

For eg: https://{ServerName} /XRMServices/2011/Discovery.svc

2. IOrganizationService : The IOrganization Service is Basically used for accessing the organization data and metadata with the help of the WCF implementation. This is the main service for the operation of all  Create,Update ,Delete,Retrieve  etc.

For eg: https://{ServerName} /XRMServices/2011/Organization.svc

Steps  to be done before Development

  1. Registration of Device using Device Registration Tool Provided in the SDK.


C:\>deviceregistration.exe /operation:Register – Go to the location where the exe is there and then run with the following command.

This will register you device and give Device Username and Device Password. This Device Id Username and Password is basically used while generating  the class which is used for the development though early bound class.

The device Username and password is basically used for the Authentication of the Services (mainly for Claim Based Authentication) which we want to use. The CRM 2011 online supports only claim based authentication so the device username and the password is very important and a necessary component for generating the code{class} for using the Organization Service data and metadata.

Note: The Device Username and the password is not necessary in the other form of Authentication like On- Premise, IFD  etc.

  1. Creating the Class using the CrmSvcUtil.exe Tool  which is again the part of the SDK and can be used for generating the Early bound Class. The syntax for using this tool is given below.

For Eg:

CrmSvcUtil.exe /url:https://{servername}/XRMServices/2011/Organization.svc /out:E:\GeneratedCode.cs /username:USERNAME /password:”********” / deviceid:”11yjcvqjo4ynpdoi5dfyo19yth” /devicepassword:”^Va/oCyeCy~Fbbko0fZ~m;lf”

Note: Please replace the USERNAME with the username with which you logs the CRM for the given URL.

After using this tool a class file will be generated which we need to include in our Project for accessing all the entities and data of the Organization.

Sample Code

  1. First create a class that will contain the configuration details which we can use in our code for creating the proxy class. This class will contain all the details about the Authentication ,the Organization URL information ,Device Credentials, user credentials etc.

So let us create a class called ServerConnection  which also contains a class called Configuration which holds the different  variables like Server Address, Organization Name, Discovery URL, Organization URL , Device Credentials, Credentials etc.

public class ServerConnection
            public class Configuration
                //Declare the variables like Discoveryurl,

Now we will create a method called GetServerConfiguration() for defining the variables.

public virtual Configuration GetServerConfiguration()
            config.ServerAddress = "{ServerAddress}";
            config.DiscoveryUri = new Uri(String.Format("https://{0}/XRMServices/2011/Discovery.svc", config.ServerAddress));
            config.DeviceCredentials = GetDeviceCredentials();// only for CRM Online not required for On-Premise and IFD
            config.Credentials = GetUserLogonCredentials();
            string baseurl ="https://{ServerAddress}/XRMServices/2011/Organization.svc";
            Uri uri = new Uri(baseurl);
            config.OrganizationUri = uri;
            if (configurations == null) configurations = new List<Configuration>();
            return config;

Here we can find that we are using certain methods like GetDeviceCredentials(),GetUserLogonCredentials(), so we are going to define all those methods now.

protected virtual ClientCredentials GetDeviceCredentials()
            ClientCredentials credential = new ClientCredentials();
            credential.UserName.UserName = "11yjcvqjo4ynpdoi5dfyo19yth";//Give the username that you get after registering the device.
            credential.UserName.Password = "^Va/oCyeCy~Fbbko0fZ~m;lf";// Give the Device Password .
            return credential;

Now we will define the GetUserLogonCredential() for getting the User Credentials

protected virtual ClientCredentials GetUserLogonCredentials()
            ClientCredentials credentials = new ClientCredentials(); ;
            String userName;
            String password;
            userName = "{Windows Live ID Username for logging into CRM.}";
            if (string.IsNullOrWhiteSpace(userName))
            return null;
            password = "Windows Live ID Password.";
            credentials.UserName.UserName = userName;
            credentials.UserName.Password = password;
            return credentials;

After our ServerConnection Class is ready tharn we can Proceed for the Application part where we can use this class for creating a proxy class for talking  to the IOrganization Service through code.

Now we will create a class where we can consume this. Lets create a class called ConsumeIorganization.cs

Now first create a Proxy class for establishing a connection to the IOrganization Service and call this method in the page load or any constructor so that before using the classes of the Organization the proxy is properly created.

public void Run(ServerConnection.Configuration serverConfig)
               using (serviceproxy = new OrganizationServiceProxy(serverConfig.OrganizationUr, serverConfig.HomeRealmUri,
               serverConfig.Credentials, serverConfig.DeviceCredentials))
                    serviceproxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                    service = (IOrganizationService)serviceproxy;
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)


Now the next step is to use the class in our project which we have got by the tool [SvcUtil.exe ]. Include the class in our Project and start using to get all the classes of the CRM Organization. By adding this class you can use all the data and metadata in your Project.

So Let’s start using this to consume in our code. In the Below code I have written a method which Creates an Account Record.

public void CreateAccount()
            Account account =new Account();
            account.Name="Sample Account Record Without Service Reference(WCF).";
            accountid = service.Create(account);

Note: Here service is the object which we have defined while creating a Proxy Class. So not forget to Declare in the beginning  of the class. You can declare as follows

IOrganizationService service;

OrganizationServiceProxy serviceproxy;

Both are part of the DLL [using Microsoft.Xrm.Sdk,using Microsoft.Xrm.Sdk.Client]   which is provided in the CRM Sdk .

So Now we are all set to run the. After running the Application you will find that a Account Record will be created in the CRM server.

So Its Easy …………………………..Enjoy………………………..!!!!!!!!!!

, , ,


PreEntityImages and PostEntityImages In CRM 5.0 / 2011 Plugins

PreEntityImages :

It is basically used to capture the data when the form loads. That is the data which is present by default when the form loads.  The syntax for using the PreEntityImages in CRM 2011 is changed as compared to CRM 4.0. Remember the PreEntityImages cannot be registered for “create” operation.

Syntax Used in CRM 2011 :

Suppose you registered the Plugin and added a Image with name “PreImage

Entity preMessageImage;

if (context.PreEntityImages.Contains(“PreImage”) && context.PreEntityImages[“PreImage”] is Entity)


preMessageImage = (Entity)context.PreEntityImages[“PreImage”];

accountnumber = (String)preMessageImage.Attributes[“accountnumber”];


Here Entity is an Class that is available in the Microsoft.Crm.Sdk.dll

PostEntityImages :

The Post Image contains the attributes value which are finally changed. We can capture the changed data before the database operation takes place. And can do any kind of validation based on the changed data. Remember it can only be registered  for update message and cannot be registered on create message.

Syntax Used in CRM 2011 :

Suppose you registered the Plugin and added a Image with name “PostImage

Entity postMessageImage;

if (context.PostEntityImages.Contains(“PostImage”) && context.PostEntityImages[“PostImage”] is Entity)


postMessageImage = (Entity)context.PostEntityImages[“PostImage”];

accountnumber = (String)postMessageImage.Attributes[“accountnumber”];


The PreEntityImages and PostEntityImages are Very useful in Scenarios where we want to compare the data that is changed by the user. Based on the changes the custom operation can be performed.

The below PLugin shows the use of PreEntityImages and PostEntityImages.The plugin creates a contact record when a account record is updated. The plugin uses late binding or Dynamic Entity concept for the creation of the record.

PreEntityImages concept

, , , ,


CRM 2011 Top 10 New Features

There are lot of new features that have been Introduced in CRM 2011. Some of the New Features are :

1. DashBoard

2. Charts

3. Goal Management

4. Connections

5. Auditing

6. Multiple Forms based on Roles.

7.Option  Sets – Global Picklist

8. Solution Packaging

9. Web Resources

10. Processes – Work Flows and Dialogs

Leave a comment

Data Encryption Error in CRM

Recently when we were trying to update the user’s email address in CRM 2015 On Premise version we were getting the below error and we were not able to update even though the user with  which we were updating was having System Administrator and Customizer Security Roles. We were getting the below error

“There are encrypted fields in the organization database, but the data encryption feature isn’t activated. Contact your Microsoft Dynamic CRM system administrator to activate data encryption. To activate, go to Settings > Data Management > Data Encryption. For more information, see”

After analyzing the issue, we figured it out that the error is coming since this environment was newly set up by taking a DB Backup from another CRM instance where data encryption was activated. We updated with the same key from the CRM instance from where we took this backup.

How & Where to copy the Key?

  1. Sign in to Microsoft Dynamics CRM as a user with the system administrator security role.
  2. Go to Settings > Data Management > Data Encryption.
  3. In the Data Encryption dialog box, select Show Encryption Key, in the Current encryption key box select the encryption key, and copy it to the clipboard.

In case your CRM is not configured for HTTPS then follow the below link

, , , ,

Leave a comment

2013 in review

The stats helper monkeys prepared a 2013 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 22,000 times in 2013. If it were a concert at Sydney Opera House, it would take about 8 sold-out performances for that many people to see it.

Click here to see the complete report.

Leave a comment

Programmatically updating stages/process for Business Process Flow in CRM 2013

New release of CRM 2013 allows creating Business Process flows for custom entity as well. It also allows creating multiple processes flows for the same entity.  Different set of users can have different flows based on the business requirement. Even in some scenario’s we may need to shift from one process flow to some other process flow which should be generally done dynamically based on certain conditions.

We can enable Business Process Flows setting during creating custom entity or even we can update this in settings after the entity is created.



Once we enable this 2 fields gets created for this entity.


So when we want to change the current process flow or the current stage we need to update these fields. Unfortunately CRM has not provided any UI to update these fields directly. So we can update this either through JavaScript/plugins using CRM API calls.

Let’s see how to get these values and update accordingly. In my sample I have a Business Process Flow called – “Business Process for Enquiry” with the following stages – “New, Contacted, Confirmed, Visa processed and Close”.


As highlighted above we can enable this flow for distinct/different set of security Roles.

I need to update the stage to CONFIRMED automatically once few fields are updated. To achieve this I wrote the below code in my Plugin.

// Get the Process Id based on the process name
 string procesName = "Business Process for Enquiry";
 var workflow = (from p in orgContext.WorkflowSet
 where p.Name == procesName && p.StateCode == Entities.WorkflowState.Activated
 select p).FirstOrDefault();
 throw new InvalidPluginExecutionException(string.Format("Worflow not found with name {0}",procesName));
 //Get the stage id based on the Stage Name
 string stageName = "CONFIRMED";
 var stage = (from p in orgContext.ProcessStageSet
 where p.StageName==stageName.ToUpper() && p.ProcessId.Id==workflow.WorkflowId
 select p).FirstOrDefault();
 if(stage ==null)
 throw new InvalidPluginExecutionException(string.Format("Stage not found with name {0}", stageName));
//Update the record with the new stage
 Entities.new_enquiry updateEnquiry = new Entities.new_enquiry();
 updateEnquiry.Id = context.PrimaryEntityId;
 updateEnquiry.stageid = stage.ProcessStageId;
 updateEnquiry.processid = workflow.WorkflowId;

And that’s it. It does the job for me


Happy Reading !!!!



, , , , ,

1 Comment

Creating Business Rules in CRM 2013

One of new feature added in new release of CRM 2013 is Business Rule. Though this is not very exciting feature provided by CRM 2013 but obviously this is something which developers can relish as it minimizes the burden of common JavaScript validation. Yes that’s true with the use of Business Rules we can easily perform few simple validation in the form without writing a single line of code.

Wow!!!! It sounds great… Let us have a quick walk through of this new feature and see how we can incorporate this for our requirements.


When a lead source is changed to Partner – I want to make

1. Business Phone and Email as Mandatory Fields

2. Hide the Mobile Phone Field

Now let us create a Business Rule to meet the above requirement.  Business Rules comes as a part of your entity in the solution as shown below.


Go to Business Rules for Lead entity and Create a new one. Here we can notice that we can do the following things

1. Add Conditions

2. Add Actions

3. Provide Description

In this example we have added one condition as if the lead source is Partner. In actions we can see that we are making the Business Phone as Mandatory, Hiding the Mobile Phone field and Making the email as Mandatory.


There are very limited options available for the creating the actions like as shown below.


Once we are done with the creation part we need to save this and activate. Similar to Processes we can activate and deactivate this Rules at any point of time. Also if we have multiple forms then we can also define for which forms these rules should be applied.


One good I liked the most is that there is a Save As Option available so we can create multiple rules in minute and then edit accordingly.

Now we can see the desired result in the lead form(UI)LeadUI

Key points to be noted

1. If there is JavaScript written for same field then it executes before your custom business rules(Java script fires before Business Rules).

2.  It does not supports hiding/Showing  Tabs and Sections.

3.  This is similar to JavaScript so these rules do not trigger when any operation is performed by API calls.

4. Well supported in Mobiles and Ipad.

5. Rules can be applied form wise. So in case of multiple forms you may specify for which forms these rules is applicable for.

, , ,

Leave a comment