kamagra how much to take

Writing Extension Methods for SharePoint

Extension methods are a formidable programming construct that augment implementation abstraction and modularize segments of code, lending itself well for filling gaps that may be present in a closed API, such as the one that SharePoint provides. Often times there may be a particular method that is desirable on a particular type, however the options for providing it are not available in the shipped API due to sealing and other modifies. Using Extension methods, it is possible to bypass this limitation while maintaining a clean implementation that can avoid deep inheritance tree references.

Extension methods are increasingly important when working with SharePoint code because a majority of objects that would normally mandate customizations of behavior, for example on SPList types, is decorated with a sealed access modified thereby negating possible inheritance. This is most noticeable when you are working with mock objects, which outside of certain frameworks (i.e. TypeMock) require an unsealed class and a default constructor.

As opposed to providing the method definition within the class, an extension method is simply defined by an association and contained in a separate static class supported by partial class constructs (i.e. it must exist in a namespace in the current scope). The method itself is invoked using instance method syntax, allowing some level familiarity in the code constructs. While the method is static, it can be called only on instances as defined in the parameters. In essence, an extension method will allow injection of a method into another class, so it is declared as if it is part of it.

In order to decrease method ambiguity due to extensions methods being defined only by the method name, it is important to take into account the appropriate naming convention (in fact, if the signature is the same the extension will be ignored!). Furthermore, the SharePoint types that will be extended are of course subject to the revisions of the API as released by MSFT. Therefore, when the API changes, there may not be the desired level of backwards compatibility.

The syntax for an extension method is very simple (it is important to note that while VB.NET requires the Extension attribute to be defined, C# does not. However in C# we are forced to create a copy of the object / return value so it evens it out!).

  1. public static class Extensions
  2. {
  3. public static Type DoSomething(this Type type)
  4. {
  5. // let's get something going!
  6. }
  7. }

You can see that in the static Extensions class the DoSomething method has its sole parameter decorated with the this keyword modifier, to indicate the type to which this method will extend. So, for example when writing extension methods to extend the SPList class (without any supplementary parameters), our class would like this:

  1. public static class Extensions
  2. {
  3. public static Type DoSomething(this SPList list)
  4. {
  5. // let's get something going!
  6. }
  7. }

But that isn’t doing much, so let’s take a more pragmatic example.

In the below, I am assuming that within an application, on SPList objects, I am going to be frequently reordering the current instance SPListItem collection into a descending order by the modified date, and then retrieving the last 5 items.

In the HarvestLastFive, it is noticeable that I am firstly specifying the type to target by using the this keyword with the SPList type. Following, I am building a SPListItemCollection of the SPList.Items, which then uses the LINQ OrderByDescending method in combination with the SPBuiltInFieldId.Modified property to handle the ordering. Lastly, Take returns the first 5 items out of the modified collection. If you just wanted the reordering (a variety of extensions I use daily use such LINQ collection modifiers for enhanced manipulation support) you would just take out the Take statement.

  1. public static class Extensions
  2. {
  3. public static IEnumerable<SPListItem> HarvestLastFive(this SPList typeToTarget)
  4. {
  5. try
  6. {
  7. SPListItemCollection collection = typeToTarget.Items;
  8. var finalCollection = tempCollection.OrderByDescending(x => x[SPBuiltInFieldId.Modified]).Take(5);
  9. return finalCollection;
  10. }
  11. catch (Exception exception)
  12. {
  14. }
  15. return null;
  16. }
  17. }

You can see in the members of the Extensions class, that the HarvestLastFive method has a different icon (little down arrow) which specifies it as an extension method.

Using the method in a class is analgous to other methods available on that type. For example, the HarvestLastFive method takes on the form:

  1. public static void TestingExtensionMethod()
  2. {
  3. SPList list = SPContext.Current.Web.Lists["My List"];
  4. var collection = list.HarvestLastFive();
  5. // Do whatever you want!
  6. }

Within Visual Studio, this method is noted as an extension method on the ToolTip with the prefix (extension).

This should give you enough to get going on extension methods. I will be posting some of my common extension methods that I use with SharePoint shortly, as this was meant to be an introduction.


No Comments


  1. SharePoint Shelter » Blog Archive » Remember When Using SPUtility.FormatDate To UTC (Extension Method) - [...] This post is also because people said they required a more reusable extension method (than here) example that tapped …
  2. WSS 3.0 & MOSS: Recopilatorio de enlaces interesantes (XXII)! « Pasión por la tecnología… - [...] Interesante artículo de Adam Buenz sobre como construir métodos de extensión para SharePoint. [...]
  3. iSea (only for iPod and iTouch users) - [...] Taking this a step for further and using the technique that Adam Buenz blogged about at Writing Extension Methods …
  4. SPList has no default URL Property - Nadine's Posts - developers.de - [...] Method is to extend the SPList object by writing Extensions Methods. This is described here, many thanks to Adam …

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>