Blog Site

 Error

Web Part Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. You don't have Add and Customize Pages permissions required to perform this action. Correlation ID: a769aa9e-104a-f008-e1ec-df0271a9abd0.
Dec 09
Improving performance of CRM 2016/Dynamics 365 queries in C#

 

Previous version of Dynamics CRM (2011, 2013 and 2015) used to have a class called CachedOrganizationService, that was part of the Microsoft.Xrm.Client.dll Assembly. The new SDK for 2016 and Dynamics 365 doesn't come with that assembly anymore and the connection classes has been moved to the Microsoft.Xrm.Tooling.Connector.dll assembly. However, this class doesn't come with the CachedOrganizationService, if you had an application that used that class and you want to upgrade the code to work with the latest SDK 2016 Dynamics 365 assemblies you will need to manage the caching manually, here is a sample way you can use to improve the queries performance executed by the RetrieveMultiple method of the IOrganizationService interface that is part of the Microsoft.Xrm.Sdk

private MemoryCache _objectCache = null;
public EntityCollection RetrieveMultipleCached(Microsoft.Xrm.Sdk.Query.QueryExpression myQueryExpression)
{
    EntityCollection entityCol = null;
    ObjectCache cache = MemoryCache.Default;
    if (cache.Contains(myQueryExpression.Serialize()))
    {
        entityCol = (EntityCollection)cache[myQueryExpression.Serialize()];
    }
    else
    {
        Microsoft.Xrm.Tooling.Connector.CrmServiceClient conn = new
Microsoft.Xrm.Tooling.Connector.CrmServiceClient(ConfigurationManager.ConnectionStrings["Xrm"].ConnectionString);
        crmService = (IOrganizationService)conn.OrganizationServiceProxy;
        entityCol = crmService.RetrieveMultiple(myQueryExpression);
        cache.Add(myQueryExpression.Serialize(), entityCol, DateTime.Now.AddDays(30));
    }
    return entityCol;
}

You need to be very careful when you use this method as in the case the data changes frequently this way is not recommended, in case you know something changes in the entity data you can invalidate the cache by using a plugin.

To invalidate the cache you will need to manually remove the items as follows

foreach (var element in MemoryCache.Default)
{
MemoryCache.Default.Remove(element.Key);
}

Other recommendations include making the connection object static so you don't need to create the CrmServiceClient on every request.

Enjoy!

 

Comments

comment

comment
 on 1/4/2017 11:45
​​
​​
All Material in this Website is Property of Remoting Coders. ©2003-2017 Remoting Coders. All rights reserved.

John Doe

Chat with us

Jane Smith
12:23 PM

Hi, I wanted to make sure you got the latest product report. Did Roddy get it to you?


Remoting Coders is typing a message...
All of our staff members are not available at the moment, please try again later, or leave your questions here and we'll back to you shortly.