Provisioning SharePoint Features – Declaratively or Programmatically?

The question posed is often one which causes much debate. It’s one of those ready-made ‘Friday flame wars’ topics that could easily bait the uninitiated. Right from the outset I want to define some boundaries around this discussion. I’ll be approaching it predominantly from a content type and list definition/instance perspective more so than anything else. Obviously features can be used to provision much more, but those mentioned are some of the most common and often what is being referred to when this question arises.

While i’ve filed this under ‘best practices’ I must admit that I wouldn’t consider it ‘best practice’ as such. More to the point, this is my current personal preference and my reasons behind it. Like most things SharePoint, both standpoints could be argued and in different situations the alternate approach might be the right one.

I consider myself able to judge the merits of both having recently made the switch. For a long time – the majority of my SharePoint career – i’ve been firmly in the declarative camp. I wouldn’t say this was the case for any noble reason – it was the way I learnt it, the way in which it was being implemented where I first worked and hence the way I implemented it myself on numerous projects since. Recently however on a greenfields project I decided that programmatic provisioning would be the way to go. This decision was made for a couple of reasons. I had been burnt by declaratively provisioning list definitions in the past and wanted a first hand experience in programmatic provisioning to be able to make a more personally-educated decision for future endevours.

Before writing this post I decided to read anything I could find out there to get the wider community’s opinion on the subject matter. I’ll endevour to include all links that helped shape this post.

I remembered having a discussion with Jeremy Thake at the Perth SharePoint User Group a long time ago on the reasons why he favoured programmatic provisioning and while I couldn’t completely recall the conversation, knew that there was a resource on the old SharePoint Dev Wiki. Thankfully it still exists on NothingButSharePoint.com and still proves to be one of the most useful resources on the matter. Have a read of SharePoint Declarative (CAML) vs Imperative (Object Model) Provisioning to see some of the collaborative thought on the pro’s and con’s of both approaches.

When approaching SharePoint best practices one of my first stops is always to the patterns & practices SharePoint Guidance where I found buried in the documentation the following quote:

“There are various tradeoffs to consider when you choose whether to create content types declaratively or programmatically. You cannot update a content type that has been created declaratively—all content types must be upgraded programmatically. However, declarative approaches are simple; therefore, they are a better choice if your content types are not expected to evolve or change.”

Also worth a read are the opinions of highly respected SharePoint MVP, MCM and MCA Wictor Wilen in his post Avoiding Xml Based SharePoint Features – Use The API Way. The post is a few years old and it would be interesting to hear an updated opinion but it still strongly advocates the programmatic approach.

Finally a couple of forum postings influenced my view, particularly the comments by Scot Hillier in what is the best practice to deploy a list instance to a sharepoint site and Rob Windsor in Best way to package publishing content types.

My views and experience with the declarative approach

As previously mentioned I’ve been using this approach for a long time. Aside from the fact that this may have been so due to habit, there were factors that lead me to believe it was a fine approach and seeking an alternative was not necessary. As vindicated by the patterns and practices quote above – it can be a simple method of provisioning features. There are examples and documentation aplenty all over the internet and MSDN. Particularly for provisioning lists and content types, applications exist which allow you to essentially reverse engineer the XML required from those that were created/prototyped in SharePoint via the UI (in 2007 there was the Solution Generator and SPSource, in 2010 you can import site templates into Visual Studio and find the relevant files or use the Community Kit for SharePoint).

A lot of the often-mentioned downsides to declarative provisioning never really caused me any issues. There was the ‘inability’ to define lookup fields in lists declaratively (which I never had a problem with using something similar to that described in Peter Holpar’s post Declaratively adding a lookup field to a list schema using the name of the referenced list). There was the dreaded length of the Views component of the schema which was easily rectified using Oskar Austegard’s approach in MOSS: The dreaded schema.xml. Overall, I think I just got used to writing XML and how it all tied together and it never really seemed too difficult.

There was one incident however which started to change my mind a little. It was at a client where I had provisioned reasonably simple custom libraries using the declarative method which ended up behaving oddly. I can’t remember the exact issue but it had something to do with adding (seemingly random – not all) documents and issues with setting the metadata. The issue was not replicable in an identical list created through the UI, yet multiple sets of eyes couldn’t see any issues with the XML. Sure, the problem may have been caused by the definition, but that’s the problem – it’s hard to debug and hard to determine where issues may arise from. It’s also relatively easy to introduce them unknowingly.

I also, in hindsight, remember putting up with a lot of iterations to identify why features weren’t activating correctly or lists weren’t being provisioned correctly, usually all a result of manually typed XML errors. In development there was the constant process of making slight changes to the content types or lists, making sure all traces were removed from SharePoint then reploying and activating. It was a cycle I probably got used to and thought little of, but reflectively it really can be quite painful considering the alternative.

My views and experience with the programmatic approach

Having recently experienced using the programmatic approach to feature provisioning, I’d have to say i’ve been converted and can’t see myself going back. Sure it takes a little longer sometimes, but the level of control you have (checking to see if lists already exist, whether fields already exist, making conditional changes if desired) over everything is such a refreshing change. Everything is in the one location – no need to jump from XML file to XML file, making changes to Elements and Schemas and the like – everything can exist in the one feature receiver class. Whereas previously if you needed some code for things you just couldn’t do in the XML (cleaning up upon removal perhaps?) now it all just lived in the same place and you could easily get a picture of what the feature as a whole achieved.

The option is potentially only a valid one for developers – but at least in my experience it tends to be the developers doing the XML definitions anyway. It is far better to keep them to their strengths within the SharePoint API.

It also seems that the majority of the community seems to be behind the programmatic approach – at least from the readings I did for this post. There are some fairly respected names lending their weight of support to the method and it’s hard to ignore.

So to conclude it’s fair to say that i’m now firmly in the programmatic camp. While my experience using the approach is in its infancy and my opinion may end up changing as I stumble upon potential hurdles – I have had a LOT of experience manipulating SharePoint via the API in various applications, including building up entire sites from the ground up, and have yet to run into as many issues as I had with declaratively provisioned features. One thing that I wished I had the opportunity to view before writing this post is a presentation/debate delivered at the Tulsa SharePoint Interest Group by Corey Roth (declarative) and Kyle Kelin (programmatic). It was a slideless presentation and hence I wasn’t even able to view them, however they have made available their code examples which were used in the presentation which may be worth a look if you’re wanting to compare the two approaches to provisioning features in a SharePoint site. Take a look at Corey’s post Code Samples from our CAML vs API talk at Tulsa SharePoint Interest Group for the solution.

Using Web Part Verbs to Shortcut Web Part Property Configuration

Web part verbs are a pretty useful yet seemingly under-utilised feature of SharePoint web parts. Over my years in SharePoint I’ve seen and created more web parts than I care to remember, yet in that time can never remember seeing one which made use of the handy functionality web part verbs provide. I’m not sure whether it’s through lack of knowledge or lack of necessity, but I thought it would be useful to highlight one scenario where harnessing web part verbs would be valid – a more efficient method of setting web part property configuration.

First though, the obligatory background information. It would be remiss of me to assume that everyone reading this knows what web part verbs are. Most however, including those who think they don’t, probably already do. They’re simply the menu items available when you click the downward arrow in the top right-hand corner of the web part chrome.

Not as many however would know that it is quite easy to get your own items into that menu. This is done by creating custom WebPartVerb objects using one of 3 constructors – one which specifies a client-side function to run in the event the action item is clicked, one which specifies a server-side function to run in the event the action item is clicked and one which specifies both a client-side and server-side function to run – and adding them to a WebPartVerbCollection. You can read about the WebPartVerb class for more information.

Now this opens up a number of possibilities – you can essentially run any code client-side or server-side from these web part verbs, however being in an environment where i’ve worked on so many public facing websites for some time now and the fact that those web parts would rarely if ever expose the web part chrome, this functionality tends to only be available when the page is in edit mode, hence lends itself to configuration actions rather than functional actions.

As such, i’ve decided to slant this post in that direction – showing how web part verbs can be used to simplify the action of configuring a web part’s properties.

Most would be familiar with the concept of web part properties. When you click the ‘Edit Web Part’ verb shown above, you make visible a tool pane in which you can set a number of web part properties. When creating a web part, you can also define custom properties which will also appear in that tool pane. Without wanting to delve into custom ToolParts or EditorParts generally web part properties are displayed based on their type – for instance a string will appear as a textbox and a boolean as a checkbox. So if I wanted to toggle a switch on my web part to enable one display type over another I would create a custom property as a boolean value and conditionally render the web part based on that value.

This is a pretty common pattern when creating generic reusable web parts and trying to minimise the sprawl of custom web parts. The example i’ll show in this post is a visual web part used for searching. The web part will have two views – a simple view and an advanced view, configurable by the user who places the web part on the page.

When simply using a custom property to achieve this, the user must click the downward arrow in the web part chrome, select Edit Web Part, expand out the relevant category, check the checkbox and click OK. It’s not ridiculously painful in SP2010 but it is a little more frustrating in SP2007. I think everyone would agree that such a simple display toggle would be better served with an option that can be selected directly from the menu which is what web part verbs enable. The example can be seen below.

Search in Simple Mode

Search in Advanced Mode

Toggling Display via the ToolPane

Toggling Display via a Web Part Verb

The code required to get this up and running is fairly simple and requires modifications to 3 files:

WebPart.cs

using Microsoft.SharePoint.WebPartPages;

namespace WebPartVerbsExample.SearchWebPart
{
    [ToolboxItemAttribute(false)]
    public class SearchWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/WebPartVerbsExample/SearchWebPart/SearchWebPartUserControl.ascx";

        [WebBrowsable(true),
        WebDisplayName("Advanced Search"),
        WebDescription("Click to show advanced options for search"),
        Personalizable(PersonalizationScope.Shared),
        Category("Custom Properties"),
        DefaultValue("")]
        public bool IsAdvancedSearch { get; set; }

        protected override void CreateChildControls()
        {
            SearchWebPartUserControl control = (SearchWebPartUserControl)Page.LoadControl(_ascxPath);
            control.IsAdvancedSearch = IsAdvancedSearch;
            Controls.Add(control);
        }

        public override WebPartVerbCollection Verbs
        {
            get
            {
                //server-side verb
                WebPartVerb titleVerb = new WebPartVerb(this.ID + "_searchModeVerb", ToggleSearchMode);
                titleVerb.Text = "Toggle Search Mode";

                // return collection with new verbs
                WebPartVerb[] verbs = new WebPartVerb[] { titleVerb };
                return new WebPartVerbCollection(verbs);
            }
        }

        // event gets executed when the user invokes the server-side verb
        void ToggleSearchMode(object sender, WebPartEventArgs e)
        {

            SPWeb site = SPContext.Current.Web;
            SPFile page = site.GetFile(Context.Request.Url.AbsolutePath);
            SPLimitedWebPartManager wpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
            SearchWebPart webpart = wpm.WebParts[this.ID] as SearchWebPart;

            //Toggle the search mode
            webpart.IsAdvancedSearch = !webpart.IsAdvancedSearch;
            wpm.SaveChanges(webpart);
        }
    }
}

WebPartUserControl.ascx.cs

namespace WebPartVerbsExample.SearchWebPart
{
    public partial class SearchWebPartUserControl : UserControl
    {
        public bool IsAdvancedSearch { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}

WebPartUserControl.ascx

<div>
    <% if (!IsAdvancedSearch) { %>
    <div>Search</div>
    <div>
        <!-- simple search fields -->
    </div>
    <% } else { %>
    <div>Advanced Search</div>
    <div>
        <!-- advanced search fields -->
    </div>
    <% } %>
</div>

So there you have it, a neat little way to leverage web part verbs to shortcut the need to edit the web part’s properties to set a simple configuration toggle. This makes the page editors life far easier and is definitely a more efficient way to handle such a requirement. Before I finish and on a slightly unrelated note, if you’re looking for an even more efficient way to set web part configuration values in SP2010 then check out Wictor Wilen’s post Improve the experience using Modal Dialogs when adding Web Parts in SharePoint 2010.

Follow

Get every new post delivered to your Inbox.