Browsing posts in: ASP.NET

How to avoid content being cached when using a CrmDataContext

Lately I’ve been working on a project that uses CRM and has a Silverlight app connected to it via a RIA Service. This RIA Service itself uses Microsoft.Xrm.Client.Data.Services.CrmDataContext to access the CRM’s data and it’s wrapped in a DomainService in order to make things easier.

Thing is we’re migrating a part of the app into an ASP.NET app, while reusing the RIA Service’s code by cloning the DomainService. So far so good, because besides making the proper changes to the app’s code, which may seem non-trivial some times, the DomainService works.

The problem is we have and use a lot of child windows wrapped into iframes that connect themselves to CRM. So, for example, if an iframed child window updates a contact details, the parent window will not be aware of the changes…unless you make an AJAX request when the child window is closed and refresh the client’s data; or that’s what you may think, but it doesn’t work, because the Domain Services objects are different in each window and the parent’s Context has content being cached. In Silverlight there’s no problem, because both child and parent windows share the same Context, that’s not possible in ASP.NET without being a mess.

The solution

Remove the cache, right? Well, no, one does not simply remove the cache, nor kill the Batman; it’s undocumented, but there’s a way. 2, actually:

Clearing the cache for a single entity type

 public void ClearCache(string entityName)
{
    var format = "adxdependency:crm:entity:{0}";
    var dep = string.Format(format, entityName).ToLower();
    var cache = CacheManager.GetBaseCache();
    cache.Remove(dep);
}

Or:

CacheManager.GetBaseCache().Remove(string.Format("adxdependency:crm:entity:{0}", entityName));

Clearing the cache for every single entity

BaseCache baseCache = CacheManager.GetBaseCache();
foreach (string x in from x in baseCache
        where x.Key.Contains("adxdependency:crm:entity:")
        select x.Key)
    baseCache.Remove(x);

Or, with an extension method:

public static void Clear(this Cache x)
{
    List<string> cacheKeys = new List<string>();
    IDictionaryEnumerator cacheEnum = x.GetEnumerator();
    while (cacheEnum.MoveNext())
    {
        cacheKeys.Add(cacheEnum.Key.ToString());
    }
    foreach (string cacheKey in cacheKeys)
    {
        x.Remove(cacheKey);
    }
}