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.
            prof.Refresh();

        }
    }
} 

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=1.0.0.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35">
        <OperationSequence>
          <Component name="ProfileCacheInstance Updater"              type="Microsoft.Commerce.Samples.Pipelines.ProfileCacheInstance,             Microsoft.Commerce.Samples.Pipelines, Version=1.0.0.0, Culture=neutral,PublicKeyToken=b23706c1d1011ab9" />
        </OperationSequence>
      </MessageHandler>

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", “foo@foo.com”);

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.