mo.notono.us

Thursday, January 10, 2008

C#/MOSS: Extension Methods: For Good and For Evil

Let me start with some good news:  C# 3.0/ASP.NET 3.5 works beautifully with SharePoint 2007, thanks to the forward-compatible nature of the .NET framework from version 2.0 onwards.

This compatibility opens up all sorts of avenues, one of them is the use of Extension Methods, replacing trusty old Utility classes.

Extension methods are amazingly simple, yet handy, essentially they allow you to "correct" the behavior of a class that you otherwise have no control over.  This can be used both for Good (adding useful methods to a poorly written API) and for Evil (making C# look like VB).  And of course it can also be used for sheer Anal Retentiveness:

For instance, I am not a fan of the SPListCollection.Add() method, especially the last two overloads.  Among other parameters these overloads take a string featureID(where the string represents a Guid), an integer templateType (where the integer represents a SPListTemplateType enum), and a string docTemplateType (where the string represents an integer).  WTF?  Why aren't these parameters in their native types?

So I created the following method inside a static class:

/// <summary>
/// Creates a list based on the specified title, description, URL, Feature ID, template type, document template type, and options for displaying a link to the list in Quick Launch.
/// </summary>
/// <param name="listCollection">The list collection.</param>
/// <param name="title">The title.</param>
/// <param name="description">The description.</param>
/// <param name="featureId">The feature id.</param>
/// <param name="templateType">The template type.</param>
/// <param name="docTemplateType">The doc template type.</param>
/// <param name="quickLaunchOptions">The quick launch options.</param>
/// <returns>A GUID that identifies the new list.</returns>
public static Guid Add(this SPListCollection listCollection, string title, string description, 
  string url, Guid featureId, SPListTemplateType templateType, int docTemplateType, 
  SPListTemplate.QuickLaunchOptions quickLaunchOptions)
{
  return listCollection.Add(title, description, url, featureId.ToString("B").ToUpper(), 
    (int)templateType, docTemplateType.ToString(), quickLaunchOptions);
}

Itch scratched. The properly typed overload now shows up in intellisense.

Labels: , , , , ,

0 Comments:

Post a Comment

<< Home