Refreshing a particular profile cache instance

It’s pretty easy to call an operation in Commerce Server 2009 that refreshes the entire profile cache like below:

 var updateCaches = new CommerceUpdate<CommerceEntity>("CommerceCache");updateCaches.SearchCriteria.Model.Properties["Name"] = "ProfileCache";
CommerceResponse updateResponse =  OperationService.ProcessRequest(currentContext, updateCache.ToRequest());

But what if you want to modify a particular instance in the cache, rather than blowing the whole cache away?

There is no out of the box way to do that in Commerce Server,  but its very easy to create a new message that does exactly that.

To start, create a new OperationSequenceComponent that encapsulates the Commerce Core Service functionality that clears a cache instance like below:

 namespace Microsoft.Commerce.Samples.Pipelines
    class ProfileCacheInstance : OperationSequenceComponent
        public override void ExecuteUpdate(CommerceUpdateOperation updateOperation, OperationCacheDictionary operationCache, CommerceUpdateOperationResponse response)

            var modelSearch = (CommerceModelSearch)updateOperation.SearchCriteria;

            var eMail = modelSearch.Model.Properties["email"].ToString();

            // Get the Profiles run-time object.
            ProfileContext ctxt = CommerceContext.Current.ProfileSystem;

            // Get the profile from an eMail variable.
            Profile prof = ctxt.GetProfile("email_address", eMail, "UserObject");

            // Refresh the profile.


Next, you add a reference to this handler in your CommerceConfiguration.config file like this:

 <MessageHandler name="CommerceUpdateOperation_ProfileCacheInstance"        responseType="Microsoft.Commerce.Contracts.Messages.CommerceUpdateOperationResponse,            Microsoft.Commerce.Contracts, Version=, Culture=neutral,PublicKeyToken=31bf3856ad364e35">
          <Component name="ProfileCacheInstance Updater"              type="Microsoft.Commerce.Samples.Pipelines.ProfileCacheInstance,             Microsoft.Commerce.Samples.Pipelines, Version=, Culture=neutral,PublicKeyToken=b23706c1d1011ab9" />

To call this functionality, you can build a CommerceUpdate operation like this one:

 var updateCaches = new CommerceUpdate<CommerceEntity>("ProfileCacheInstance"); 
updateCaches.SearchCriteria.Model.Properties.Add("email", “”);

CommerceResponse updateResponse =  OperationService.ProcessRequest(currentContext, updateCache.ToRequest());

As you can see, it is quite easy to add a new message and a new handler that executes specific business functionality.  Now you have that business functionality in a nice discreet handler that can be reused in many projects.