On a recent project, I’ve had to refamiliarize myself with the process of creating custom command buttons within Sitecore Content Editor. Some existing commands our team had already defined used convention in which they passed along control to Sitecore.Context.ClientPage.Start. What this does is allow the command to execute asynchronously without locking up the user’s browser. This is especially appropriate if your command is making an external call to a third-party resource or a possibly time-consuming transaction with Sitecore’s databases.
This seemed like such a useful approach that I thought it would be worthwhile to capture it as an abstract class.
I’m employing the template design pattern. The Execute method will stay the same for all derived classes because it’s simply setting up the async mechanism. The Run method is marked abstract requiring the subclass to “fill in the blank” of what the command should actually do. The PrepareArgs method builds the collection that gets passed to the Run method. I’m assuming most implementations will want the ID, language, and version of the item that was active when the command was clicked. Since the method is virtual, it can be overridden to do more or less.
I debated adding a layer to pack/unpack the data passed in the NameValueCollection but I decided against it. I thought it would over-assume what the Run method was going to do and limit the implementations. There’s always the opportunity to create another abstract subclass that does that extra step.
When you find yourself recommending something as a “best practice”, it’s that much easier make it part of your application and not just a recommendation. With this small class, any command called from the Content Editor can have this asynchronous ability without someone having to “reinvent the wheel” each time.