Get Total Count of records in CRM. (more than 5000)

For version 9.0 please check the below post


Just sharing a sample code to get the total number of records (e.g. account here)

 IOrganizationService orgService = GetOrganizationService();

 int totalCount = 0;

 QueryExpression query = new QueryExpression("account");
 query.ColumnSet = new ColumnSet();
 query.Distinct = true;
 query.PageInfo = new PagingInfo();
 query.PageInfo.Count = 5000;
 query.PageInfo.PageNumber = 1;
 query.PageInfo.ReturnTotalRecordCount = true;

 EntityCollection entityCollection = orgService.RetrieveMultiple(query);
 totalCount = entityCollection.Entities.Count;

 while (entityCollection.MoreRecords)
 query.PageInfo.PageNumber += 1;
 query.PageInfo.PagingCookie = entityCollection.PagingCookie;
 entityCollection = orgService.RetrieveMultiple(query);
 totalCount = totalCount + entityCollection.Entities.Count;



Hope it helps

Business Process Error while trying to open records in CRM 2015

Hi we were getting the below error while trying to open any record in CRM 2015


Turned out that by mistake one wrong extra step had got registered on RetrieveMultiple

ActivityFeeds.Plugins: ActivityFeeds.Plugins.ActivityClose]

[c824b80a-d392-e511-8114-3863bb356f90: ActivityFeeds.Plugins.ActivityClose: RetrieveMultiple of any Entity]

Removing this step fixed the issue.

Hope it helps.

Fixed – Microsoft Dynamics CRM Reporting Authoring Extension Setup – Setup cannot continue because there is a pending restart required error in CRM 2015


Got the below error while trying to install the Report Authoring Extension for CRM 2015.

To fix the issue, open the log file, check for the registry path and delete it

Hope it helps !

“Duplicate Column Heading Exists” Error while using Templates for Data Import in CRM 2015


We were getting the Duplicate Column Heading Existing while trying to download template for data import for Opportunity Entity.

Through Customizations we changed the Display Name of the fields that were duplicate and it fixed the issue for us.


I had the same issue.  In Settings> Customizations, display the Entities that causes the error.  Sort the fields by display name and scroll through the list until you find two identical display names.  Rename one, save and publish your changes.  You should now be able to download the Import template.

Do check out this awesome article

Hope it helps ..

Sample code to check if User is a member of a team C# CRM 2011/2013/2015

Sharing sample code to check if a user belongs to a team or not

public static bool IsTeamMember(Guid teamID, Guid userID, IOrganizationService service)
QueryExpression query = new QueryExpression("team");
query.ColumnSet = new ColumnSet(true);
query.Criteria.AddCondition(new ConditionExpression("teamid", ConditionOperator.Equal, teamID));
LinkEntity link = query.AddLink("teammembership", "teamid", "teamid");
link.LinkCriteria.AddCondition(new ConditionExpression("systemuserid", ConditionOperator.Equal, userID));
var results = service.RetrieveMultiple(query);

if (results.Entities.Count > 0)
return true;
return false;

Hope it helps.

Sample code to read XML Data from Web Resource in Plugin in CRM 2011/2013/2015

We recently had a requirement to read xml data stored in a particular web resource in plugin.

Sharing the sample code

public static Dictionary<string, string> GetMarketClusterAndMarketSegment(string webresourceName, string buildingTypeValue, IOrganizationService organizationService)
Dictionary<string, string> dictionaryMarket = new Dictionary<string, string>();

// tk_et_oppline_marketingfilterpicklists
// create request to retrieve Webresource
ColumnSet cols = new ColumnSet();
QueryByAttribute requestWebResource = new QueryByAttribute
EntityName = "webresource",
ColumnSet = cols

Entity webResourceEntity = null;
EntityCollection webResourceEntityCollection = organizationService.RetrieveMultiple(requestWebResource);

if (webResourceEntityCollection.Entities.Count > 0)
webResourceEntity = webResourceEntityCollection.Entities[0];
byte[] binary = Convert.FromBase64String(webResourceEntity.Attributes["content"].ToString());
string resourceContent = System.Text.Encoding.UTF8.GetString(binary);
string byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (resourceContent.StartsWith(byteOrderMarkUtf8))
resourceContent = resourceContent.Remove(0, byteOrderMarkUtf8.Length);

XDocument xmlDocument = XDocument.Parse(resourceContent);

var marketSegment = from t in xmlDocument.Descendants("ParentField").ElementAt(1).Descendants("ShowOption")
where t.Attribute("value").Value.Equals(buildingTypeValue)
select new
marketSegmentValue = t.Parent.Attribute("value").Value,
marketSegmentLabel = t.Parent.Attribute("label").Value

foreach (var v in marketSegment)
dictionaryMarket.Add("marketsegment", v.marketSegmentValue);
var marketCluster = from t in xmlDocument.Descendants("ParentField").ElementAt(0).Descendants("ShowOption")
where t.Attribute("value").Value.Equals(v.marketSegmentValue)
select new
marketClusterValue = t.Parent.Attribute("value").Value,
marketClusterLabel = t.Parent.Attribute("label").Value

foreach (var m in marketCluster)
dictionaryMarket.Add("marketcluster", m.marketClusterValue);

return dictionaryMarket;

Hope it helps..

“The entity referenced by this process includes a currency value that does not exist in your organization. Select a different currency and try again.” Error in Workflow in CRM.


After importing one of the solution was getting the below error in one of the processes

The solution was to find out the Currency field and set it to the currency that existed in our organization.

Hope it helps..

Query execution time of 60 seconds exceeded the threshold of 10 seconds warning in CRM 2013.

Query execution time of 60 seconds exceeded the threshold of 10 seconds warning in CRM 2013.

We were getting the below warning in one of our test environment

On analyzing figured out that one of the plugin was using retrieve with ColumnSet(true) option i.e. retrieving all the columns of the entity which was not required in this case.

Fetching only the required columns fixed the warning.

The other option could have been indexing or increate the value for LongQueryThersholdInSeconds column in ServerSetingProperties table of MSCRM_Config.

Helpful posts

Hope it helps..


Plugin when a case (incident) is resolved in CRM 2013.


To fire a plugin when an incident is resolved we need to register the plugin in

Close message for the incident entity.

And in the input parameters of the context we need to check for IncidentResolution.

This entity is a special entity that holds the information about the incident record that is being closed.

The sample plugin below gets the actual end attribute value of IncidentResolution and subtracts created on attribute value of Incident to get the duration and updates the duration (custom field) in the case being resolved.

public void Execute(IServiceProvider serviceProvider)
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)

if (context.InputParameters.Contains("IncidentResolution"))
Entity incidentResolution = (Entity)context.InputParameters["IncidentResolution"];
Guid relatedIncidentGuid = ((EntityReference)incidentResolution.Attributes["incidentid"]).Id;
DateTime actualEnd = DateTime.Now;
if (incidentResolution.Contains("actualend"))
actualEnd = (DateTime)incidentResolution.Attributes["actualend"];
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

// Get created on of incident

Entity retrievedIncident = service.Retrieve("incident", relatedIncidentGuid, new ColumnSet(true));
DateTime createdOn = (DateTime)retrievedIncident.Attributes["createdon"];

TimeSpan totalTimeSpent = actualEnd.Subtract(createdOn);

Entity incident = new Entity("incident");
incident.Id = relatedIncidentGuid;
incident.Attributes["new_duration"] = totalTimeSpent.TotalMinutes;


The helpful post








Fixed – CRM Mail Merge button missing in Word 2013.


The way we got it working was to download the following template


From the following location


And place it at the following location


Followed by restarting Word.

The helpful post

Nested Quick Create form in CRM 2015

Nested Quick Create form in CRM 2015

In CRM 2013,

If we click on Create button for Quick Create a record

Say for e.g. Contact record

And want to create a new Account record to be associated to it

We need to click on “Look Up More Records” and then “New”

This opens up the default Contact form


However in CRM 2015,

We have a New Button

It will open the Quick Create Form for the account record instead of the default form as in the case of CRM 2013.

On creating and saving the account record, it will close the Account record and populate the lookup in Contact record

The pain of missing “Else If” condition in Business Rules in CRM 2013.

Let us take a simple example

There is a field say “Test Field” and 2 option set fields.

OptionSet1 è A1, A2, A3, A4

OptionSet2èB1, B2, B3, B4

Now the logic that we have to implement is

Show “Test Field” when

OptionSet1 = A1 and OptionSet2= B1


OptionSet1 = A2 and OptionSet2= B2


Field should be hidden

Logic in JavaScript

If (optionset1 == A1 && optionset2== B1)

Show field “Test Field”

Else if (optionset1 == A2 && optionset2== B2)

Show field “Test Field”


Hide field “Test Field”

Logic in Business Rule

To implement the same in business we need write 6 business rules.

  1. If OptionSet1 = A1 and OptionSet2= B1 è Show “Test Field”
  2. If OptionSet1 = A2 and OptionSet2= B2 è Show “Test Field”
  3. If OptionSet1 != A1, A2 è Hide “Test Field”
  4. If OptionSet1 2= B1, B2 è Hide “Test Field”
  5. If OptionSet1 = A1 and OptionSet2= B2 è Show “Test Field”
  6. If OptionSet1 = A2 and OptionSet2= B1 è Show “Test Field”

Well the good news is that we now have “Else If” condition in CRM 2015.


JavaScript runtime error: Unable to get property ‘get_code’ of undefined or null reference in CRM

We can get the ‘get_code’ error if we are using Assign Step in Action/Workflow and the value is null for the field selected.

Here we need to use If condition to check if the value exist for that particular field before using Assign Step.

Sample code: Using jqGrid in ASP.NET page to show CRM data

Sample code: Using jqGrid in ASP.NET page to show CRM data

Just sharing a simple ASP.NET page that uses jqGrid to show contact records in CRM and allows user to search.

Here is the code (remove .doc)

Hope it helps ..

Get current user language in JavaScript in CRM 2011/ CRM 2013/ CRM 2015

Field Level Security in CRM 2015

Now supported for System (OOB) Attributes.

Contact’s “Job Title” attribute in CRM 2011

Contact’s “Job Title” attribute in CRM 2015

Can be enabled for email data type attribute

In CRM 2011

In CRM 2015


Address field are also supported.

Hierarchical Security Modelling (Manager Hierarchy) in CRM 2015

Hierarchical Security is a new security feature introduced in CRM.

It could be either

Manager Hierarchy or Custom Position Hierarchy based.

To enable it we need to go to

Settings à Security

Let us enable Hierarchy Modelling and set the Hierarchy Depth as 2.

With depth we can specify up to what level the user can have read access to the records. Here the user will have write, update, append, append to access to those records only which are accessible to his direct report.


Let us say we have 3 users in our system.

  • User A, Manager A and CEO.
  • CEO is manager of Manager A and Manager A is manager of User A in our system.
  • CEO à manager à Manager A à manager à User A
  • User A is sales person and creates a contact record.
  • Now in our configuration we have set depth as 2 which means.
  • CEO user will have Write access to record that are accessible to Manager A and Read Access to those records accessible to User A.
  • CEO opens a record created by User A. ( it is read only for him)

  • Manager A opens the same record (He can edit it)

  • Now Manager A creates a new contact record. This record will be editable for CEO as he is the manager of Manager A

Hierarchical Security Model works in conjunction with all the other existing security models.


Fixed – Unhandled Exception: Microsoft.Crm.CrmException: Cannot create a lookup without the required parameters in CRM 2013


Got this error in one of the steps in the Action. It was updating one of the lookup field using Update step.

The issue was that the lookup field was not in the form. Adding that particular field in the form back resolved the issue.

Hope this helps..



JavaScript Reference for Microsoft Dynamics CRM 2011 / 2013


Here’s a quick reference guide covering Microsoft CRM syntax for common jscript requirements.

Most of the examples are provided as functions that you can easily test in the OnLoad event of the Account form to see a working example.  These are not production hardened but they’ll help you with the CRM syntax.

(updated: 30 July 2012)


  1.   Get the GUID value of a Lookup field
  2.   Get the Text value of a Lookup field
  3.   Get the value of a Text field
  4.   Get the database value of an Option Set field
  5.   Get the text value of an Option Set field
  6.   Get the database value of a Bit field
  7.   Get the value of a Date field
  8.   Get the day, month and year parts from a Date field
  9.   Set the value of a String field
  10. Set the value of an Option Set (pick list)…

View original post 1,401 more words

Using CreateMultiEntityAssociation method of CRMServiceClient for 1: n records.


CreateMultiEntityAssociation method of CrmServiceclient can be used for associating 1 : n records i.e. if we have one contact record that we want to associate with multiple opportunity record ( 1-n) then we can use that method. This way we wont have to update each individual record.

Sample Code

Uri organizationUri = new Uri("http://server/crmrog/XRMServices/2011/Organization.svc");
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultCredentials;
OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);

CrmServiceClient crmServiceClient = new CrmServiceClient(orgProxy);
List<Guid> lstOpportunityGuid = new List<Guid>();
lstOpportunityGuid.Add(new Guid("9DDCE989-0738-E411-9878-00155D56FF56"));
lstOpportunityGuid.Add(new Guid("019E1598-0738-E411-9878-00155D56FF56"));
lstOpportunityGuid.Add(new Guid("EA393A91-0738-E411-9878-00155D56FF56"));
crmServiceClient.CreateMultiEntityAssociation("contact", new Guid("CF1FC3C0-0738-E411-9878-00155D56FF56"), "opportunity", lstOpportunityGuid, "opportunity_customer_contacts");

Hope it helps ..

Business Rules in CRM 2013

Just writing down few key points regarding the Business Rules in CRM 2013.

  • Business Rules run on client side so any custom server side code or data import will bypass it.
  • Business Rule can be created for a specific form or all the forms of the entity.





  • Business Rules execute offline and also for tablet client.
  • If else conditions are not supported.
  • Rule are created for a single entity.
  • No support for or conditions.
  • If there is custom JavaScript and two business rules written on same condition, the custom JavaScript will run first, followed by the order in which the business rules have been activated.



Calling a Windows Authenticated WCF Service in a Plugin in CRM


Suppose we need to call the service created here in our plugin

As plugin don’t have configuration file, we need to specify binding information in Code.

The sample code to call the WCF Service by passing Network Credentials

private static void CallWCFService()
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

// Specify the endpointAddress
EndpointAddress endpointAddress = new EndpointAddress(new Uri("http://servername:port/Service1.svc"));

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(binding, endpointAddress);
if (client.ChannelFactory.Credentials != null)
client.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password", "domain");
if (client.ClientCredentials != null)
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;

Hope it helps ..



Invalid CRMReference Target: The entity Customer doesn’t exist.


Was writing a custom workflow activity on incident entity and in which we wanted the Customer Lookup Value. And based on type of Customer i.e. either contact or account there was some logic to be executed.

So declared an input parameter or type Customer

However while registering the workflow I got the below error

The way to handle this is,

Get the guid of the record from the context and then retrieve the value of customer id attribute.

On retrieval check if the EntityReference is of type account or contact and then proceed accordingly


Hope it helps ..

Microsoft Fakes and LINQ (Custom Workflow Activity) in CRM


Just sharing a sample code to test a custom workflow activity using Microsoft Fakes.

The custom workflow activity uses LINQ.

The custom workflow activity code

public sealed class MyCustomWorkflowActivity : CodeActivity
#region Public Properties

[Input("Stage Name")]
public InArgument<string> StageName { get; set; }


#region Methods

/// <summary>
/// Executes the workflow activity.
/// </summary>
/// <param name="executionContext">
/// The execution context.
/// </param>
protected override void Execute(CodeActivityContext executionContext)
// Create the tracing service
var tracingService = executionContext.GetExtension<ITracingService>();

// Create the context
var context = executionContext.GetExtension<IWorkflowContext>();

var serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();

IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

using (var xrmServiceContext = new XrmServiceContext(service))
// get the business process workflow id
var workflow = (from w in xrmServiceContext.WorkflowSet
where w.Name == "Business Process Workflow Name"
select new Workflow { WorkflowId = w.WorkflowId }).FirstOrDefault();

if (workflow != null)
// get the stage name from the context's input parameter
var stageName = this.StageName.Get<string>(executionContext);
var stage = (from s in xrmServiceContext.ProcessStageSet
where s.StageName == stageName && s.ProcessId.Id == workflow.WorkflowId
select new ProcessStage { ProcessStageId = s.ProcessStageId }).FirstOrDefault();

if (stage != null)
// update the sales state in the case record to which the above business process flow is associated
var incident = new Incident
Id = context.PrimaryEntityId,
StageId = stage.ProcessStageId
catch (FaultException<OrganizationServiceFault> e)
tracingService.Trace("Exception: {0}", e.ToString());


Unit Test Code

public void UnitTestCustomWorkflowActivity()

var workflowUserId = Guid.NewGuid();
var workflowCorrelationId = Guid.NewGuid();
var workflowInitiatingUserId = Guid.NewGuid();

var service = new Microsoft.Xrm.Sdk.Fakes.StubIOrganizationService();

var workflowContext = new Microsoft.Xrm.Sdk.Workflow.Fakes.StubIWorkflowContext();
workflowContext.UserIdGet = () =>
return workflowUserId;
workflowContext.CorrelationIdGet = () =>
return workflowCorrelationId;
workflowContext.InitiatingUserIdGet = () =>
return workflowInitiatingUserId;

// ITracingService
var tracingService = new Microsoft.Xrm.Sdk.Fakes.StubITracingService();
tracingService.TraceStringObjectArray = (f, o) =>
Debug.WriteLine(f, o);

// IOrganizationServiceFactory
var factory = new Microsoft.Xrm.Sdk.Fakes.StubIOrganizationServiceFactory();
factory.CreateOrganizationServiceNullableOfGuid = id =>
return service;

SetBpfStage target = new SetBpfStage();

var wfEntity = new Workflow();
wfEntity.Id = Guid.NewGuid();
wfEntity["name"] = "abcabcabc";
var wfEntity1 = new Workflow();
wfEntity1.Id = Guid.NewGuid();
wfEntity1["name"] = "abcabcabc";

var processStageEntity = new ProcessStage();
processStageEntity.Id = Guid.NewGuid();
processStageEntity["name"] = "abcabcabc";
service.ExecuteOrganizationRequest = r =>
RetrieveMultipleResponse response = null;
if (((Microsoft.Xrm.Sdk.Query.QueryExpression)((RetrieveMultipleRequest)r).Query).EntityName
== "workflow")
List<Entity> entities = new List<Entity> { wfEntity };

response = new RetrieveMultipleResponse
Results =
new ParameterCollection
new EntityCollection

return response;

if (((Microsoft.Xrm.Sdk.Query.QueryExpression)((RetrieveMultipleRequest)r).Query).EntityName
== "processstage")

List<Entity> entities = new List<Entity> { processStageEntity };

response = new RetrieveMultipleResponse
Results =
new ParameterCollection
new EntityCollection

return response;

return response;

service.UpdateEntity = (p) =>

var invoker = new WorkflowInvoker(target);
invoker.Extensions.Add<ITracingService>(() => tracingService);
invoker.Extensions.Add<IWorkflowContext>(() => workflowContext);
invoker.Extensions.Add<IOrganizationServiceFactory>(() => factory);

var inputs = new Dictionary<string, object>
{ "StageName", "New" }


Hope it helps..

Using LINQ in CRM 2013

There are few ways we can make use of LINQ to write queries against CRM.

Using the early bound entity classes along with the generated service context

Use the CrmSvcUtil tool to generated the early bound entity classes and service context

CrmSvcUtil.exe /url:http://<serverName>/<organizationName>/XRMServices/2011/Organization.svc

/out:<outputFilename>.cs /username:<username> /password:<password> /domain:<domainName>

/namespace:<outputNamespace> /serviceContextName:<serviceContextName>


Uri organizationUri = new Uri("http://server/orgname/XRMServices/2011/Organization.svc");
 Uri homeRealmUri = null;</pre>
<pre> ClientCredentials credentials = new ClientCredentials();
 credentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password", "domain");
 OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
 IOrganizationService _service = (IOrganizationService)orgProxy; 
 var xrmServiceContext = new XrmServiceContext(_service);
 // get all contact record that has first name as Hugh
 var lstContact = (from c in xrmServiceContext.ContactSet
 where c.FirstName == "Hugh"
 select c).ToList();
 foreach(var contact in lstContact)

Using Early bound entity classes and OrganizationServiceContext

Suppose we have the early bound entity classes but haven’t generated the service context. In this case we can use OrganizationServiceContext


var xrmServiceContext = new OrganizationServiceContext(_service);

var lstContact = (from c in xrmServiceContext.CreateQuery<Contact>()
 where c.FirstName == "Hugh"
 select c).ToList();

foreach (var contact in lstContact)

Using Late bound and OrganizationServiceContext

Suppose we are not generating the early bound classes and using late binding



  var xrmServiceContext = new OrganizationServiceContext(_service);

 var lstContact = (from c in xrmServiceContext.CreateQuery("contact")
 where c["firstname"] == "Hugh"
 select c).ToList();

 foreach (var contact in lstContact)

Hope it helps..


“the specified type is not a known entity type” error while using early bound entity classes in CRM 2013


We were writing a custom workflow activity that was using LINQ (early bound).

Here we had used ILMerge to merge the early bound assemblies with the workflow assembly.

The solution was to place the following attribute in the AssemblyInfo.cs of the workflow assembly (same goes for Plugin Assembly)

[assembly: Microsoft.Xrm.Sdk.Client.ProxyTypesAssemblyAttribute()]


The helpful thread

Hope it helps..



OptionSetId cannot be changed. EnumAttributeInfo.AttributeDescription.OptionSetId(089e077e-6055-446a-ad6e-326f0bee7c9c) != c0864f8b-2c13-e411-93ed-000d3a800961

We got this error while importing the solution. This issue is caused by having an optionset with same name but different guid.

The solution is to identify the field and delete it from the org where we are importing.

select name from optionsetview where optionsetid = ‘c0864f8b-2c13-e411-93ed-000d3a800961’ (the 2nd guid)

The helpful post


Fix: Invalid ‘where’ condition. An entity member is invoking an invalid property or method while using LINQ in CRM 2013.


We were writing a LINQ query to get the contract record information by passing in the lawyer name. The lawyer is a lookup in the contract record.

So we were using contract.lawyerid.Name field of lookup in our where condition.

However we got the below error while doing so..


It seems like the LINQ Implementation for CRM doesn’t correctly interpret the lookup field’s name if we are using it in the where clause.

The solution was to do a join between the entities and then use the where condition against the lawyer entity username field itself.

Hope it helps..