Tuesday, May 4, 2010

Several extension methods to retrieve SPList from SPWeb safely

Often we need to retrieve SPList instance from SPWeb by title or server relative URL. We can do it using the following code:

   1: // get list by title
   2: var list = web.Lists[listTitle];
   3: // or by URL
   4: var list = web.GetList(listUrl);

But the problem is that if list not found these methods have different behaviors: indexer SPWeb.Lists[…] throws System.ArgumentException (“Value does not fall within the expected range”) and SPWeb.GetList(…) method throws System.IO.FileNotFoundException (“The system cannot find the file specified. (Exception from HRESULT: 0x80070002)”). So in order to handle such errors we need to add try/catch with different catch blocks in our code. This is not very convenient.

In order to simplify error handling and make it similar for both cases I wrote 2 simple extension methods for SPWeb class:

   1: public static class SPWebExtensions
   2: {
   3:     public static SPList GetListByTitleSafely(this SPWeb web, string listTitle)
   4:     {
   5:         if (web == null)
   6:         {
   7:             throw new ArgumentNullException("web");
   8:         }
   9:  
  10:         return web.Lists.Cast<SPList>().FirstOrDefault(l =>
  11:             string.Equals(l.Title, listTitle,
  12:                 StringComparison.InvariantCultureIgnoreCase));
  13:     }
  14:  
  15:     public static SPList GetListByUrlSafely(this SPWeb web, string listUrl)
  16:     {
  17:         if (web == null)
  18:         {
  19:             throw new ArgumentNullException("web");
  20:         }
  21:  
  22:         try
  23:         {
  24:             return web.GetList(listUrl);
  25:         }
  26:         catch (FileNotFoundException)
  27:         {
  28:             return null;
  29:         }
  30:     }
  31: }

Instead of throwing exceptions these methods will return null. So you don’t need to add try/catch every time you retrieve list from SPWeb – you just need to check it on null after it was safely retrieved:

   1: var list = web.GetListByTitleSafely(listTitle);
   2: if (list == null)
   3: {
   4:     // handle list not found
   5: }

And if you will decide to retrieve list by URL instead of title you will not need to change your error handling logic – it will remain the same.

No comments:

Post a Comment