30 Jan 2011

We struggle with this issue on my current project. The issue itself is rather trivial: we have a field (actually, the Guid of a field) and we want to know if it is one of SharePoint’s built-in field or if it is a custom field from our application.

Now, as our application runs on MOSS 2007, there are two kind of built-in fields: those of WSS 3.0 and those of MOSS 2007. For WSS 3.0 fields, there is a class named SPBuiltInFieldId that has all the built-in fields’ guids as public fields and the class even has a static method Contains that allows to quickly find out if the field is built-in from WSS 3.0 or not.

For MOSS 2007 fields, there is the Microsoft.SharePoint.Publishing.FieldId class that has all the built-in fields’ Guids as public properties, but unfortunately does not have a “Contains” method.

So how are we going to find out? Obviously, we are not going to compare against all the properties of the FieldId class… No, let’s do this the clean way: make use reflection to build up a Dictionnary with all the Guids then we’ll use that table to check if our field is in it or not!

static IDictionary<Guid, bool> PublishingBuildInFields { get; set; }

static Program()
    Type type = typeof(Microsoft.SharePoint.Publishing.FieldId);
    var propsInfoArray = type.GetProperties(BindingFlags.Static | BindingFlags.Public);

    PublishingBuildInFields = propsInfoArray
        .Select(prop => (Guid)prop.GetValue(null, null))
        .ToDictionary(g => g, g => true);
bool IsSPBuiltInField(SPField field)
    return SPBuiltInFieldId.Contains(field.Id)
        || PublishingBuildInFields.ContainsKey(field.Id);

Now, one interesting detail is that ToDictionary uses immediate execution, so we are sure to execute reflection calls only once, during the static constructor’s execution. This is important, because if we just built a sequence with Select, every time we could access that sequence the reflection code would execute, which is not a good idea in most cases.

Update: follow up here.

blog comments powered by Disqus