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!).

[csharp]
public static class Extensions
{
public static Type DoSomething(this Type type)
{
// let’s get something going!
}
}
[/csharp]

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:

[csharp]
public static class Extensions
{
public static Type DoSomething(this SPList list)
{
// let’s get something going!
}
}
[/csharp]

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.
[csharp]

public static class Extensions
{
public static IEnumerable HarvestLastFive(this SPList typeToTarget)
{
try
{
SPListItemCollection collection = typeToTarget.Items;
var finalCollection = tempCollection.OrderByDescending(x => x[SPBuiltInFieldId.Modified]).Take(5);
return finalCollection;
}
catch (Exception exception)
{

}
return null;
}
}[/csharp]

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:
[csharp]
public static void TestingExtensionMethod()
{
SPList list = SPContext.Current.Web.Lists[“My List”];
var collection = list.HarvestLastFive();
// Do whatever you want!
}[/csharp]

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.

Share

Auto-Implemented Properties and Developing WebParts

Auto-Implemented (or just automatic) properties are one of the new features in C# 3.0 that allow property declaration to be additionally succinct, lessening compulsory code thereby lightening maintenance and increasing readability. Auto-properties make SharePoint code, which tends to be property heavy for personalization features much easier to write, (sure, you can use the “prop” code snippet in VS.NET, however it still will subscribe to the old property structure) read, and maintain.

Firstly, let’s take a basic SharePoint class, OrthodoxWebPartClass in the below, which uses a conventional property declaration with minimal relevant attributes. The class doesn’t do much outside of rendering the text property to the output stream.

[csharp]
public class OrthodoxWebPartClass : WebPart
{
private string _text;

[Personalizable(PersonalizationScope.Shared),  WebBrowsable(true),  WebDisplayName(“Text ToDisplay”), WebDescription(“The Text To Display”)]
public string Text
{
get { return _text; }
set { _text = value; }
}

protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write(_text);
base.RenderContents(writer);
}
}
[/csharp]

Not very interesting. Examining the above, the property takes on the customary declaration structure of:
[csharp]
private string _property;
public string Property
{
get { return _property; }
set { _property = value; }
}
[/csharp]
Outside of the property attributes (for SharePoint interface instruction) this is 5 lines for declaration, a sizable amount to append to an arbitrary class file.

Automatic properties are instead written in the form of:

[csharp]
public string Property { get; set; }
[/csharp]

Taking this construct into our example class file, our WebPart code will take on the form:

[csharp]

public class AutoWebPartClass : WebPart
{
[Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName(“Text To Display”), WebDescription(“The Text To Display”)]
public string Text { get; set; }

protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write(Text);
base.RenderContents(writer);
}
}

[/csharp]

Much trimmer, cleaner code!

Although there is an empty setter and getter, behind the scenes the get_PropertyName and set_PropertyName methods are still being called. The compiler will generate a private field used as the backing store for the property (which is why you can’t use field attributes, but can use property attributes).

What is most important out of the use of auto-properties is the adherence to an ever important OOP concept: encapsulation! There are some things to note however, namely setting a default value and creating read-only properties.

Setting a Default Value for An Auto-Property
Seeing as WebPart properties tend to hold vital configuration values, there should be compensation for assignment of default values. There are two ways for assignment:

Set The Default Value Via Assignment In the Constructor
Set The Default Value Using DefaultValue And The Property Type

In the below, I am demonstrating the assignment of the property within the WebPart constructor:

[csharp]
public class IntializationWebPartClass : WebPart
{
public IntializationWebPartClass()
{
Text = “Text”;
}

[Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName(“Text To Display”), WebDescription(“The Text To Display”)]
public string Text { get; set; }

protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write(Text);
base.RenderContents(writer);
}
}
[/csharp]

Creating a Read-only Automatic Property
Creating a property that is set in the class and will be immutable when used is fairly easy (however a write-only property is obviously not possible). At first glance it might be assumed that simply by removing the set of the property that the property should be read-only, however this will only create a lean on the default value. In order to create a read-property, the private access modifier simply needs to be decorated on the set of the property.

[csharp]

public string Text { get; private set; }

[/csharp]

That’s about all I have for now on automatic properties, because they are after all, just properties. However I hope this should get you going using auto-properties in your SharePoint code! :)

Share

Four Rules for Implicit Types in SharePoint Development

One of the principal code modifications when using C# 3.0 is the introduction of implicit types. Having freshly concluded a sizeable code review for a manufacturing company where they had just completed framework retrofits, I found myself irritated with the prostitution of implicit types. So I thought that I would attempt to wrap some organization around appropriate use.

Implicit types are decorated through the use of the var keyword. The most notable instantiation is on construction of objects, but there are assortments of other tangible circumstances such as cast expressions (both orthodox in addition to safe casting) and orthodox/static method with explicit type arguments.

Implicit types are something to use with vigilance and care, they otherwise lessen inclusive code readability. And while mature and adhered to naming convention standards get over particular issues, there are four key rules to follow (IMHO) when considering implicit types:

1) When you are defining local variables inside methods wherever their type is easily grafted from the context (you can only use the var keyword for local variables anyways), use an implicit type. If you are declaring a SPList object with a descriptive variable name using a hydrated SPWeb, it is acceptable to use an implicit type. The type in that unambiguous circumstance should be unproblematic to grasp from the background.

2) When you are using an anonymous type, use an implicit type since giving it a type is not possible. This is a pretty straightforward case :)

3) If you are building largely named types, something like:

[csharp]

var adambuenz = new ()

[/csharp]

increases readability to not use explicit type declaration. This is ordinary in SharePoint aggregation applications where numerous objects are rolled into complex collections. Often times instantiating the collection for use can lead to large declarations, of which var is a perfect use for stylistic truncation.

4) When using simple loops var can shorten code length and maintain readability. Like if you were doing a foreach (SPList list in SPWeb.Lists) you could implicit type the SPList variable with no loss.

Remember, since a lot of the use of implicit types is bound to the stylistic concerns of the code, established and adhered to coding naming conventions augment readability more than anything that the language will present.

Share