Thursday, June 17, 2010

ReSharper live template for Sharepoint utilities

In everyday Sharepoint development we often need to create many console utilities for various maintenance tasks which should be performed on production or staging environments (e.g. install bugfix on living Sharepoint site, trace some information from production site, etc). Before to run program on remote server we test it on our development environment and then copy it to remote server and run it there with different site URL (in most cases there are different URLs on production and dev environment). So we have to write the following code each time we need to create such utility:

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         if (args.Length != 1)
   6:         {
   7:             Console.WriteLine("Usage: exe <site_collection_url>");
   8:             return;
   9:         }
  11:         using (var site = new SPSite(args[0]))
  12:         {
  13:             using (var web = site.OpenWeb())
  14:             {
  15:                 // code goes here
  16:             }
  17:         }
  19:     }
  20: }

It is very annoying. So I created ReSharper live template which slightly simplify this task. Just add the following code to User Template (in Visual Studio menu ReSharper > Live Templates > User Templates > New Template):

   1: if (args.Length != 1)
   2: {
   3:     Console.WriteLine("Usage: exe <site_collection_url>");
   4:     return;
   5: }
   7: using (var site = new SPSite($site$))
   8: {
   9:     using (var web = site.OpenWeb($web$))
  10:     {
  11:     }
  12: }

and specify “Shortcut” for it (e.g. “spsite”). Now you are able to create the above code by typing “spsite”. ReSharper will offer spsite template for you (like it does for “for” or “foreach” templates):


After selecting of “spsite” template ReSharper will add this code for you and it will allow to specify parameters in SPSite() constructor and OpenWeb() method by clicking Enter key (which is more convenient in comparison with VS code snippets):


This is a little automation which slightly simplifies creation of console utilities for Sharepoint.

1 comment:

  1. Nice, thanks for idea. I used it in reSP as nsite/nweb/nsw/rwep tokens: