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.

Performance Optimising SharePoint Sites – Part 3

In Performance Optimising SharePoint Sites – Part 1 of this series I focussed on some of the first steps you should undertake or consider when embarking on performance optimising your SharePoint site. Performance Optimising SharePoint Sites – Part 2 explored some of the platform-independent techniques available at your disposal while this part of the series will identify some of the SharePoint-specific techniques able to be leveraged.

This is another topic where the information available is quite extensive. In a lot of cases however the information is either spread around or quite targetted so I think there is some value consolidating a lot of these ideas as part of this series.

One aspect of performance optimisation for SharePoint sites I won’t delve heavily into is on the infrastructure and administration side. This isn’t particularly my area of expertise so instead i’ll invite you to read some articles with more appropriate authors including Arpan Shah’s Things to Consider for SharePoint Performance, David Lozzi’s Improving SharePoint’s Performance and Eric Shupps’ 10 steps to optimize SharePoint performance.

Make sure your Objects are Disposed Correctly

It could be considered that this has been done to death and surely no one out there would fall into the trap of incorrectly, or failing to completely, dispose their SharePoint objects – but no performance optimisation article would be complete without at least mentioning it. It’s one of the most serious pitfalls a developer can fall into when developing a SharePoint site. Two main resources exist to steer you clear of this evil; the MSDN articles Disposing Objects for SharePoint 2010 and Best Practices: Using Disposable Windows SharePoint Services Objects for SharePoint 2007 and the SPDisposeCheck tool which can be run over your code to check for potential errors. There really is no excuse to letting these issues slip through the cracks and should definitely form part of your optimisation process.

Perform a Code Review and Ensure Your SharePoint Code is Optimal

Aside from object disposal mentioned above, a number of other code factors exist which can leave your pages rendering in a less than optimal time. A number of blog posts run through a bunch of these including Andreas Grabner’s How to avoid the Top 5 SharePoint Performance Mistakes, Eric Shupps’ SharePoint.Performance: Optimizing Web Parts and Waldek Mastykarz’s Performance of various methods to retrieve one list item. However the best resource i’ve found in regards to writing optimal code is on the MSDN site Developer Best Practices Resource Center – definitely worth your time in parsing through all the information on that site to ensure your code is as optimal as it can be.

Use Caching within your Code

No matter how optimal you eventually make your code, it will still be slower than not having to query the information in the first place. Caching is a great mechanism to allow you to run the query once then retrieve the data from memory on subsequent loads. There’s always a trade off between caching the data for performance and the currency of data – the trick is to find the balance between improving the performance of your site and ensuring the data being displayed is relatively up to date – this could differ on a case by case basis. You can either harness the built-in SharePoint objects which handle the caching for you or cache the objects yourself. Claudio Brotto has a good article on all things caching at SharePoint Internet Sites – Performance Optimization for Data Access which is worth a read.

Make Use of SharePoint’s Built-In Caching Functionality

SharePoint also has other built-in forms of caching that can be harnessed for your site both identified in Claudio’s article above; the Output Cache and the BLOB Cache. There are pitfalls associated with caching and these need to be considered, however caching is one of the most powerful methods of improving the load time of your SharePoint site. For more information on BLOB caching i’d recommend reading Sean McDonough’s Do You Know What’s Going to Happen When You Enable the SharePoint BLOB Cache? – it’s a long but quality post. For Output Caching (and caching in general) have a read of Tobias Zimmergren’s Caching in SharePoint 2010. As a side note particularly for SharePoint 2007 you may need to consider the issues Chris O’Brien identifies in his article Optimization, BLOB caching and HTTP 304s.

Get Rid of those Unnecessary SharePoint JavaScript Files

If your site has been extended to solely be an anonymous internet site then chances are a bunch of JavaScript is being downloaded to the page that will never be used by the end user and you should strongly consider changing that. Microsoft covered this off in SharePoint 2007 in a section (within a larger article) titled Managing Page Payload (Small Is Good). Chris O’Brien covered this off again in SharePoint 2010 in his post Eliminating large JS files to optimize SharePoint 2010 internet sites and Mahmood Hamed extended on that in his article Eliminate large JS files to optimize SharePoint 2010 internet sites: the complete reference.

Consider Warming up your SharePoint Site

Warming up the pages across your SharePoint site is a good idea for two reasons. Firstly, ASP.NET’s Just-In-Time compiler will often cause the first access of a site to be extremely slow compared to usual. Secondly, the caching techniques discussed previously only kick in once a page has been visited for the first time. By running a script or job to warm up the site you can avoid the ‘first hit’ performance lag associated with these issues. There are a number of sources of information regarding this topic but one such article that seems to collate a lot of them is Wahid Saleemi’s Roundup: SharePoint Warm-Up Scripts.

So that about sums it up – my take on a start to finish process on performance optimising a SharePoint site. When approaching this task with limited time and budget it’s important to target the factors you believe will offer the greatest gain for the time required to implement. With any luck the tasks completed will be identifiably successful enough that future projects will be undertaken with performance in mind right from the start.

Performance Optimising SharePoint Sites – Part 2

In Performance Optimising SharePoint Sites – Part 1 of this series I focussed on some of the first steps you should undertake or consider when embarking on performance optimising your SharePoint site. This part of the series will explore some of the platform-independent techniques available at your disposal while Performance Optimising SharePoint Sites – Part 3 will identify some of the SharePoint-specific techniques able to be leveraged.

Before I delve into some of the techniques available I should point out that the information available on this subject is extensive. It may seem a bit redundant even including this section in my series due to the wealth of information available elsewhere however I’ve done so for completeness. Both Google and Yahoo offer terrific sources of information on this subject matter if you’d prefer to go directly to the source – i’ll try to differentiate my contribution by linking to alternate tools and resources.

Minimise HTTP Requests

Reducing the number of HTTP requests on your page is one of the best ways to reduce the load time, particularly for first time visitors. As pointed out on Yahoo’s performance rules page via Tenni Theurer’s Browser Cache Usage – Exposed! 40-60% of daily visitors to your site come in with an empty cache. Every request requires a round trip to the server so it’s easy to see how this component of page optimisation could provide a significant improvement to the overall load time of the page. The majority of techniques that can be used to achieve this will be identified in the following 3 sections.

Optimise your JavaScript

There are a number of ways in which the JavaScript on your site can be performance optimised. Firstly, you should Move Scripts to the Bottom as Steve Sauders explains. This enables progressive rendering and helps to achieve parallel downloads. This should only be done where it doesn’t impact the visual rendering of the page. You should ensure that JavaScript isn’t duplicated within your site – either in various libraries or particularly in terms of referencing the same file multiple times (which can happen if you’ve included the reference in multiple web parts or controls). Your JavaScript should exist in external files rather than inline so that it can be cached and hence not add to the size of the HTML document. You should combine your JavaScript into as few external files as possible to minimise the number of HTTP requests and finally you should minify those external JavaScript files. There are a number of resources available to assist you in automating the minification process, both for Visual Studio described in Dave Ward’s post Automatically minify and combine JavaScript in Visual Studio or if you prefer it with a SharePoint flavour via Waldek Mastykarz’s Minifying JavaScript and CSS files made easy with Mavention SharePoint Assets Minifier.

Optimise your CSS

Similarly to optimising JavaScript, you can perform a number of optimisations to your CSS. Whereas you should load your JavaScript at the bottom of the page to enable progressive rendering, with CSS you should Put Stylesheets at the Top. You should always refactor your CSS similar to how you would your code to ensure it is optimal and doesn’t repeat definitions. Take advantage of the fact you can assign multiple classes to your elements – for instance where appropriate include a base CSS class which has the shared definitions and another which has the unique ones. You should externalise your CSS for the same reasons as you should your JavaScript and combine your CSS into as few external files as appropriate (find the balance between reducing HTTP requests and combining a large amount of CSS which is only used on one or two pages). Finally, you are also able to minify your CSS much in the same fashion as you can your JavaScript.

Optimise your Images

Along with HTTP requests, the size of images is one of the biggest factors in determining page load times. There are 3 major areas of focus when it comes to optimising your images. Firstly, it is important that the images are as optimised as possible to begin with. This means achieving smaller file sizes without reducing the quality of the image itself. A number of tools exist to assist with this highlighted in Jacob Gube’s post 8 Excellent Tools for Optimizing Your Images – the one I’m most familiar with it Yahoo’s Smush.it. Secondly, it’s important to ensure that you’re not relying on the browser to resize your images. It is common to find large images reduced in size by the size of the containing element which is definitely not optimal. Finally, CSS sprites can be used to reduce the number of HTTP requests required to retrieve the images explained via Chris Coyier’s CSS Sprites: What They Are, Why They’re Cool, and How To Use Them. One thing you’ll want to consider is that you may be able to optimise the images for the site initially, but if you have content being added by end users and they upload and reference unoptimised and HTML-resized images to a page you’re at risk of losing the optimised nature of that page. One final thing to note is that if you’re displaying a page with a known transition path you can pre-load the images that will appear on the next screen/page to further optimise that page’s load time using a method such as CSS Ninja’s Even better image preloading with CSS2.

Utilise GZip Compression

GZip compression is another way in which you can reduce the size of the payload coming back from the server to the user accessing your site. The majority of browsers support GZip compression and hence this should not be ignored. For a better explanation of why it is beneficial and what it actually does have a read of Kalid Azad’s How To Optimize Your Site With GZIP Compression. For implementation details with IIS6 see Bill Baer’s HTTP Compression, Internet Information Services 6.0, and SharePoint Products and Technologies or Todd Sharp’s Enabling GZip Encoding On IIS7.

In Performance Optimising SharePoint Sites – Part 3 of this series i’ll identify some of the SharePoint-specific techniques able to be leveraged.

Performance Optimising SharePoint Sites – Part 1

For anyone involved in delivering public facing websites, particularly for an international audience, minimising page load times would have to be something high on the agenda. While this subject is not limited to sites hosted on SharePoint, it is an essential topic for consideration for any SharePoint project. There is somewhat of a misperception that SharePoint is inherently slow and often becomes the primary target of blame when trying to work out why page load times aren’t to an acceptable standard. The simple fact is there are a number of optimisation techniques available to be leveraged to minimise page load times.

These topics are not only relevant to public facing websites – a number of them are applicable to intranets and extranets experiencing performance issues. My personal experience in this field stems from delivering a number of public facing websites to specific performance targets. My initial exposure to optimising SharePoint sites came working with the team at Tourism WA on the famous SharePoint site westernaustralia.com and most recently in the early stages of a site optimisation phase for the Career Centre website.

Ideally site optimisation would be a major consideration at the beginning of any project and planned for accordingly. Realistically due to tight deadlines and more functional concerns it’s often a task carried out in retrospect. Either way performance optimisation for your SharePoint site should be considered a crucial task and one that is always undertaken – this article will approach the topic from a retrospective viewpoint.

Part 1 of this series will focus on some of the first steps you should undertake or consider when embarking on performance optimising your SharePoint site. Performance Optimising SharePoint Sites – Part 2 will explore some of the platform-independent techniques available at your disposal while Performance Optimising SharePoint Sites – Part 3 will identify some of the SharePoint-specific techniques able to be leveraged.

Understand the importance of Performance Optimisation

There is a strong correlation between page load times and the success of a website. There is plenty of anecdotal and statistically-backed evidence littered throughout the net to prove this. For a few examples take a look at How Loading Time Affects Your Bottom Line, how Amazon increased revenue for every 100ms of improvement and how ShopZilla increased revenue and page views by reducing load time. Page load times have also been known to influence bounce rates and improve traffic as testified by Google’s Marissa Mayer in Speed Wins. It should be obvious, but with evidence to back it up the likelihood of being granted the time and money to perform optimising tasks should improve.

Establish Benchmarks

In my opinion an important step to undertake before beginning work on optimising a SharePoint website is to establish the performance benchmarks for the site and ideally have a performance target in mind. This works on 2 levels; firstly, having an understanding of the current traffic levels of the site is important. The ultimate goal of performance optimisation is to increase traffic, improve the amount of time spent on the site and if applicable increase conversions. Using a free tool such as Google Analytics may give you the information you need or you can explore a raft of paid options which exist. Secondly you need to capture the current performance of the website. There are a couple of free tools available to do this including Web Page Test and Page Speed Online. With these pieces of information in hand you will be able to accurately determine if the work carried out has had a meaningful influence on both the performance and effectiveness of your site and will increase the likelihood of being able to carry out these tasks in the future.

Know the Tools at your Disposal

There are a number of tools out there that either help identify the areas in which performance optimisation can be implemented, help perform the optimisation tasks themselves or offer somewhat of a shortcut to having to dedicate hours of time on performance optimisation at all. The performance benchmarking tools mentioned above not only rate and measure performance but also offer advice on how your pages can be improved. Tools such as ySlow and Fiddler give you a more granular view of what’s going on as your page loads and with a bit of knowledge lets you target areas for improvement. If you’re hosting your site on SharePoint 2010 then you can make use of the Developer Dashboard to analyse the performance of your page. Products such as Aptimize exist which was famously used on Microsoft’s SharePoint.com to improve performance. Finally, Content Delivery Networks can be leveraged to greatly improve international load times of your site (in my personal experience it was Akamai’s CDN that proved the silver bullet for meeting performance targets on westernaustralia.com).

In Performance Optimising SharePoint Sites – Part 2 of this series i’ll explore some of the platform-independent techniques available at your disposal.

Search Engine Optimisation (SEO) for SharePoint Sites – Part 3

In Search Engine Optimisation (SEO) for SharePoint Sites – Part 1 of this series I looked at the implications content, naming, metadata and structure of your SharePoint site can have on search rankings. Search Engine Optimisation (SEO) for SharePoint Sites – Part 2 focussed more on how content can be manipulated to improve search rankings and other factors that can be leveraged from within SharePoint. This article will take a step outside the SharePoint box into how you can boost rankings and traffic to your SharePoint site using other methods.

Link Back to your Site

Along with creating quality key-phrase rich content to be indexed, having a solid link building strategy is a major factor in terms of search engine optimisation. A link strategy should emphasise quality over quantity. It should be broad and diverse. It’s important to note that value is gained both by linking out to other high-value related sites and especially by having those sites linking back to your page. As far as SharePoint is concerned, this theory is fairly independent of the platform. Due to SharePoint’s nature however and the limitations which exist when optimising a SharePoint site for search engines, the traffic generated by backlinks should be as strongly valued as the SEO benefits gained. You need to think outside of the box when approaching this strategy. Often, having other pages linking back to you is largely out of your control, however other areas are well within it. Ensure your site or pages are listed in all relevant directories. If it makes sense to do so, ensure your location exists in Google Maps and link back to your site from there. Consider creating other content-rich sites such as specific (clean-cut HTML rather than SharePoint) search engine optimised sites or blogs to link back to your site. It’s also important that the phrases used to hyperlink back match that which you are optimising for, similar to the advice given in the section above.

Don’t Ignore Social Media as part of an SEO Strategy

Social Media is another area where you can gain an increase of traffic and some SEO benefits for your SharePoint site, although the concept is removed from the platform. Facebook, Twitter, Linked In – any relevant social media site should be harnessed to both link back to your site and drive traffic to it. The benefits of the latter probably outweigh the former – I’m not entirely sure that any SEO benefit is gained from having your links on these sites. Google+ however could be considered one social media platform that can be harnessed for the purposes of SEO as identified in Christian Del Monte’s post Google+ Plus SEO Benefits- Tips To Make It Work For You.

Create a Specific Mobile Site

Aside from being good practice to cater for the ever-increasing mobile device visitors to your site, it’s been noticed that the results returned from within search engines on mobile devices may be tailored to that device. This seems to be an area of contention – reading Ryan Jones’ article Mobile SEO is a Myth would lead you to believe it’s not important however Bryson Meunier’s How To Best Optimize Your Mobile Site For SEO argues it is worthwhile, and seeing Google is Introducing smartphone Googlebot-Mobile, it’s not something I’d want to discount.

Consider Paid Search Marketing

This is another debatable topic. It depends more so on the site in question and it’s purpose. It really only makes sense to use for a commercial site in my opinion. If your site is selling something and you can target a paid advertisement it is likely to be clicked. If you’re peddling information and you show up as a paid advertisement you’re unlikely to get the same response. For the benefits of paid search marketing have a read of the Top 10 Reasons to Use Paid Search Marketing by Vinny Labarbera. It may not have a lot to do with SEO, but its a method which can be leveraged to drive visitors to your site, especially if the site is new and not appearing in many organic search results.

Ensure you Submit your Site to ALL Main Search Engines

It should go without saying, yet a number of sites will only target the large search engines such as Google, Bing and Yahoo and forget about the others. A quick search for Search Engine Market Share at the time this article was written showed that search engines other than these big 3 had 12.2% of the market share. Granted the majority of that is a Chinese based search engine which would leave less than 1% market share but with over 2.2 billion internet users worldwide, you’d be discounting over 20 million potential visitors to your site. The logic may be flawed, but personally I think it’s not worth the risk – submit your site where ever a potential visitor may see it.

Use all the Tools at your Disposal

There are a tonne of free tools and sources of information available on the web to assist in optimising your site for search rankings. One such tool is the IIS SEO toolkit. Other resources include the infinite number of SEO specialisation sites and blogs available free of charge to garner a wealth of information from. By keeping track of the changes and trends in search engine optimisation you’ll always be one step ahead of the competition.

Monitor how Visitors are Reaching your Site

It’s important that SEO is not considered a one-time event. It should be an ever-evolving function of your site and needs to change with the times. One way to identify what works and what doesn’t is to use analytics on your site to determine how users are finding your site, where they’re coming from, what search terms they’re using and how they end up navigating around your site. The more information you have at your disposal to influence the direction of your SEO campaign the more likely it will be a success.

Returning Visitors are just as Important as New Ones

The final point I wish to make in this ‘outside the box’ look into SEO for SharePoint is a simple one. It’s one thing being able to attract visitors to your site in the first place, but of little worth if they fail to stay on the site or ever return to it. The user experience of the site is just as important as the quality of the SEO or campaign that drew them there in the first place and should not be lost in the quest for search ranking supremecy.

Search Engine Optimisation (SEO) for SharePoint Sites – Part 2

In Search Engine Optimisation (SEO) for SharePoint Sites – Part 1 of this series I looked at the implications content, naming, metadata and structure of your SharePoint site can have on search rankings. This part of the series will focus more on how content can be manipulated to improve search rankings and other factors that can be leveraged from within SharePoint. Finally, Search Engine Optimisation (SEO) for SharePoint Sites – Part 3 will take a step outside the SharePoint box into how you can boost rankings and traffic to your SharePoint site using other methods.

Optimise the Load Time of your Pages

This one works on a couple of levels. Firstly, there is some benefit in terms of SEO for faster loading pages. Take a read of Geoff Kenyon’s article Site Speed – Are You Fast? Does it Matter for SEO?. The reality however is that it isn’t a huge factor. More importantly though is that the time it takes to load your pages has a huge impact on bounce rates and visitors wanting to return to your site, and for that reason it is a critical task to undertake. SharePoint, especially MOSS 2007, doesn’t have the fastest load times therefore anything you can do to reduce the load time of your pages is paramount. I intend on writing a post on this in the future so i’ll leave it at that for now, but it’s definitely something to keep in mind when creating your site.

Maximise your Content to Markup Ratio

There’s a number of articles available discussing the importance (or lack thereof) of maximising your content to markup ratio. Whether you believe it’s a factor or not is largely irrelevant – there are a number of benefits to gain from minimising the amount of markup on a page for both performance and structural reasons. It’s also important to ensure the text content appears as high on the page as possible and this can be affected by manipulating the markup structure of the page. SharePoint is notoriously bad in this regard. Improvements were made from MOSS 2007 to SharePoint 2010 but it’s still not perfectly clean HTML. There are things you can do to improve the situation – using controls instead of webparts in MOSS will minimise the number of tables used on the page. Control Adapters can be used to manipulate the HTML rendered by controls. You can ensure your Master Pages and Page Layouts structure content higher on the page and adjust their location using custom CSS. Often a lot of effort is required when focussing on this SEO technique so unless it’s of critical importance sometimes it’s best to do whatever you can and just live with the rest.

Optimise your Images and Anchor tags

Images and anchor tags are 2 elements within the page content that can be slightly adjusted to provide an extra SEO boost. Images provide the benefit of also being indexed in the Google Images search engine which can provide extra traffic. ALT text is essential when optimising an image. It should be short, sharp, relevant and if possible keyword-rich. File names can also provide some extra juice and should be similar to the ALT text and hyphen-delimited. The Title attribute is unlikely to hold much weight but it can’t hurt and should match the ALT text. Anchor tags are another which can make use of the Title attribute. The other important aspect of anchor tags, particularly intra-site linking which you have control over, is to ensure the text which is hyperlinked is descriptive and keyword rich – preferably matching the key phrase that the page is optimising. In terms of SharePoint there are 2 features you can utilise to reap the rewards – the ALT text field for images and the Tooltip field for hyperlinks. If you want to utilise the Title of an image you’ll need to delve into the code-behind which may not be worth the effort.

Use 301 redirects over 302

As I mentioned in my post 301 vs 302 Redirects in SharePoint there are a number of reasons why 301 redirects are preferred to 302 from an SEO perspective. Rather than going over everything again I’d encourgage you to read through that post and the associated links to understand the benefits and potential solutions around it. It’s significant in a SharePoint context because when accessing a site by its URL directly rather than the specific page URL, a 302 redirect is used to take you to the Welcome Page. The Redirect Page layout in SharePoint also uses 302 redirects.

Don’t Destroy Old Content

No matter how old a page, article or news item is, it still has the ability to appear in the search results and drive people to your site. In fact, the age of a site often has a positive affect on its ranking. Why would anyone want to simply discard all the effort that went into optimising the page in the first place because it was deemed somewhat out of date? Archives are a great and suitable alternative which maintain the content online and hence the rankings of the page. SharePoint makes this quite easy to do – simply filter a Content Query Web Part to return all out of date pages on an ‘Archive’ page and you’re set. The process can either be automated by scheduling an end date for the page, or by manually configuring a custom column of the page. You could also move it into an ‘Archived’ sub-site, however if this option is chosen, keep in mind the redirect that will be required and the fact that will be a 302 redirect by default.

Avoid Flash and Silverlight if you can

It’s common knowledge that using Flash or Silverlight on a website in place of indexable content is a search ranking destroyer. Flash has made SEO improvements to the format but this is still only limited. With HTML5, CSS3 and jQuery taking off and able to achieve a lot of the rich interactive functionality provided by Flash and Silverlight, you’d have to question the use of it on your search engine optimised site. This goes for SharePoint as much as any other platform – leveraging the jQuery library in SharePoint in particular is easy to do and leaves the site more SEO friendly than a Flash or Silverlight equivalent.

Create an XML Sitemap Automatically

I’m not sold on the benefits of XML Sitemaps to be perfectly honest. I tend to agree with an article written by Matt McGee titled XML Sitemaps: The Most Overrated SEO Tactic Ever in that all an XML Sitemap is really doing is masking and potentially even causing problems. There are many more however that argue the opposite, such as Bruce Clay’s XML Sitemaps in SEO – Part 1. If you’re going to go down the XML Sitemap path, and i’m not going to categorically say it’s something you shouldn’t do, I’d suggest that you ensure that it is constructed automatically so it is completely up to date. In SharePoint one way this can be achieved is via Waldek’s Imtech XML Sitemap or Mavention XML Sitemap for 2010.

Include a Robots.txt File

Having a Robots.txt file for your site is not so much about improving the rankings of pages in your site but more about ensuring pages you don’t want appearing in search results aren’t indexed. For more information about Robots.txt have a read of Robots.txt: All you need to know. This is particularly important for SharePoint because often there are a number of pages you simply wouldn’t want indexed – list views and the like – which can sometimes end up being crawled. I’d definitely suggest including this file for your SharePoint site as part of your overall SEO strategy.

Structure your Content with Heading Tags

Using header tags (H1 through to H6) to structure content is another tool at your disposal to infer importance on particular terms and phrases. Header tags are easily applied in SharePoint via the content editor so its important to stress 2 main concepts. Firstly – use them only for the keywords or phrases. Too often heading tags are used unnecessarily throughout the page or on sub-headings which really convey no SEO benefit to the page. Secondly – use them for the keywords and phrases rather than styling DIVs or SPANs to achieve the same visual effect – it’s the tag which is recognised, not the size of the text on the page. You can have the desired visual effect on the page by using heading tags where appropriate and styling other text with CSS if the term or phrase is not a targeted keyword for the page.

Externalise your JavaScript

This one ties in to maximising your content to markup ratio – the less text on the page with no SEO benefit the better. There are also performance trade-offs however – you don’t want to be creating a bunch of extra page requests to pull down each individual JS file that contains your page’s code. There are also development implications – sometimes it’s easier to code the relevant JavaScript directly within a control rather than having to find it and work on it seperately. Ultimately it comes down to what is more important to you. In a SharePoint context i’d recommend using one file to hold all JavaScript functions that will need to be called from various pages, reference it via the SharePoint:ScriptLink control and make the call to the function from within your control. This minimises the amount of JavaScript text on the page and minimises the page requests.

Add ‘Strength’ to Keywords

This one I think would be extremely minor if it has any influence at all – but I guess you never want to miss an opportunity so it’s something worth discussing. Take a read of Traian Neacsu’s article Bold or Strong Tag and SEO – Complete HTML Reference Guide for SEO for more information on the topic. The main take away is that styling via CSS won’t have any affect, while bolding keywords with the STRONG element may be recognised. It’s something worth considering anyway.

In Search Engine Optimisation (SEO) for SharePoint Sites – Part 3 of this series I’ll take a step outside the SharePoint box into how you can boost the rankings and traffic to your SharePoint site using other methods.

Search Engine Optimisation (SEO) for SharePoint Sites – Part 1

Search Engine Optimisation is a topic that i’ve always had a keen interest in. One of my first if not fleeting jobs fresh out of University was at an SEO company, albiet in a sales-based role. It still gave me an insight into something considered somewhere between an exact science and black magic and immediately peaked my interest. Since then i’ve read numerous articles on the subject, provided advice to friends, worked on projects both as the lead consultant and as the implementer for SEO consulting agencies’ recommendations. Not all have been for SharePoint sites, however the concepts applied are often not SharePoint specific. The information available on the web is extensive – it surprises me how SEO companies even manage to exist when the information is so freely available.

When deciding how to differentiate this article from the masses i’ve leant towards applying the concepts with a SharePoint flavour. I by no means claim to be an expert on the subject – merely a keen follower. I won’t claim that everything on here is correct. I may suggest something that has no positive effect on your search rankings whatsoever. In general though, i’ve noticed that applying the majority of these techniques have had a positive affect to the rankings of the sites, so there must be some truth to them.

Part 1 of this series will focus on what you can do in regards to the content, naming, metadata and structure of your SharePoint site. Search Engine Optimisation (SEO) for SharePoint Sites – Part 2 will delve a little deeper into how content can be manipulated to improve search rankings and other factors that can be leveraged from within SharePoint. Finally, Search Engine Optimisation (SEO) for SharePoint Sites – Part 3 will take a step outside the SharePoint box into how you can boost rankings and traffic to your SharePoint site using other methods.

Before I get started I just want to clarify one thing. This article series doesn’t touch on perhaps one of the most important factors in regards to search engine optimisation for a site – the initial research required before any of these steps are even considered. One must know the keywords and phrases that are going to be targeted before they actually can be, and this should be carefully deduced via research into the types of natural language searches your target audience are doing and the competition those terms and phrases have to optimise against. It’s something that definitely needs consideration before you start. But for now, on to the implementation.

Content is King

I love this saying. I’ve heard and read it hundreds of times. It’s a great way to describe how content is key to attracting and keeping visitors returning to your site. It’s also spawned a bunch of posts playing devils advocate such as Derek Halpern’s The ‘Content is King’ Myth Debunked. In a purely SEO sense however, the saying rings true. Content is the most critical element to improving site rankings. The more quality content that exists on the site, the more pages that will rank highly for different search terms and phrases. This isn’t exactly tailored towards SharePoint, however it is too critical to leave out. Content should be keyword and phrase rich – especially in the first and last paragraphs. Each page on your site should target something different – it is easier to optimise for one specific phrase rather than multiples which just leaves you with conflicting goals and spreads the optimisation power too thin. Take a look at the Infographic / Why Content for SEO? and read the links by Google engineer Matt Cutts and Bing’s Duane Forrester if you’re left with any doubt.

Page Titles are Important

Not only are page titles valuable from an SEO perspective, but they’re also what’s used when identifying the pages within the search engines and therefore serve a dual purpose. Not only is it important to use keyword-rich titles, but they need to be visually engaging to invite the user to want to click the link. From a strictly SEO perspective, page titles should begin and perhaps end with a key phrase, and be 6-12 words long. From a visual sense they should attract attention and interest and be no more than 67 characters to prevent Google chopping them short. Page titles should be unique and relevant to both the page content and phrase being targetted. SharePoint already contains the Title column for pages – your master page should contain a ContentPlaceHolder for the title and each page layout should render the page’s title via the SharePointWebControls:FieldValue control. It’s important to ensure the titles are set with optimisation in mind.

Set Page Description and Keywords Metadata

The general consensus is that meta keywords no longer play a part in SEO. Whether the meta description does or not seems to be debated – most sources suggest it is important, however Jill Whalen argues they may not affect your page’s ranking in The Meta Description Tag. My opinion on both is that it can’t hurt. Description is also important for other reasons – it is often the call out text used in either search results or other situations including extended site links or social media links such as when you type a link into facebook. It therefore, like the title, not only needs to be keyword or phrase rich but inviting and attracting to the target audience. The strategy i’d use here is to use the Description page column for both the meta description and keywords and use the same technique identified above for the page title (take note that the internal name of the Description column is actually Comments). It appears Office 365 makes this even easier via Add keyword meta tags to pages to improve search and it is believed SharePoint vNext will do the same. A little side note for the metadata specified above – it should be well structured in the head element of the page and appear towards the top of the page – before any other metadata, script or CSS references.

Name your Pages Appropriately

Page names are another way you can add weight to your page for a given search term or phrase. The important take-away from a SharePoint perspective here is to not rely on the default. The page name is generally auto-populated depending on the Title entered and essentially concatenates the words together. Some authors will modify this title, but do so either by using CamelCase or underscores to seperate the individual words. Neither are ideal from an SEO perspective. Search engines read both as one big word, however read hyphens as a sentence, thus it is important to name your pages accordingly. This can either be done manually or by using a feature developed by Waldek Mastykarz highlighted on Optimize Publishing Pages for search engines using the Imtech SharePoint SEO Slugs Feature.

Directory Structure and Naming Deserves Attention

Directory structure can assist as an optimisation tool. Take a look at Stoney deGeyter’s How to Create a Directory Structure Search Engines Rock To. In my opinion, having a solid structure driven by information architecture requirements is more important than the potential SEO benefits that could be gained – however if it’s possible to consider both then it’s worth doing. One thing to keep in mind is that the further down the chain a page is, the less weighting it will have in a search sense and the harder it will be to find. Keeping SharePoint in mind, there are 2 things to consider here. Firstly, it’s too easy to just spawn multiple sub-site chains when trying to seperate content – this may be done for no logical structural reasons, rather to seperate lists or functionality into different sub-sites – this should be avoided. The other issue from a SharePoint perspective is the frustrating ‘Pages’ directory. This obviously serves no SEO benefit, it in fact acts as a hinderance. There are potential ways around this – Waldek’s Semantic URL’s in MOSS 2007 is one of them, others involve virtual directories and redirects, URL-rewriting components or HTTP handlers. Waldek also has a solution for IIS7 in his Friendly URLs for SharePoint post however it is unsupported and only works in particular scenarios. To be honest, I don’t really like any of the options and for now would just cop the hit. I’m hopeful that SharePoint vNext makes this easier to get around, perhaps leveraging off the URL Routing in ASP.NET 4 functionality. It is believed that SharePoint vNext will provide some form of friendly URLs which would be a welcomed addition.

Your Domain Name Counts

Domain names are an essential component of optimising a site. Often these are forgotten due to the desire of a lot of companies or organisations to use their brand name as their domain name. Unfortunately, this isn’t hugely desirable when trying to optimise a site. It’s no coincidence that when you search for a number of search terms, many of the top results will have included it in their domain name. Many would assume that it’s a trade off, either use the brand name or choose a search-optimised domain name, however as Ian McNeice identifies in his book Step by Step SEO: Search Engine Optimisation for SharePoint Internet Sites (a read I highly recommend) this doesn’t need to be the case. This isn’t entirely in my realm of expertise so I won’t try and explain in detail how to achieve it, but SharePoint does provide Alternate Access Mappings to handle that side of multiple addresses so that would play a part in the process. Another little-considered factor in choosing a domain name for SEO purposes is the domain extension. It’s widely believed that the main domain extensions such as .com, .net etc carry more weight. I also believe however that if you are targetting a particular country for your audience then you’re better off using the domain extension for that country, for example .com.au for Australia.

In Search Engine Optimisation (SEO) for SharePoint Sites – Part 2 of this series I’ll delve a little deeper into how content can be manipulated to improve search rankings and other factors that can be leveraged from within SharePoint.

Anti-aliased fonts, Rounded Corners in IE and the Implications for SharePoint

That’s one mouthful of a title. I’ve lately been revisiting the Career Centre website and thought this one would be worthy of a post. It works on two fronts; firstly as an introduction to a couple of useful libraries which can add that extra bit of flavour to your websites and secondly as a warning or solution to a strange issue they cause in SharePoint. I haven’t tested them in SP2010 as yet so for now I can only describe the issue as I’ve seen it, in MOSS 2007.

Anti-aliased fonts

One of my pet hates when creating public facing sites from image files provided by a design company has always been fonts. It has always seemed a case of having to revert to an uglier looking font on the page or using an image sliced from the design. The problem is to do with the anti-aliasing effect image software such as Photoshop applies to the fonts in the image which isn’t replicated when using the font in a web browser. The image below outlines the difference.

Another limitation of browser-based fonts is being limited to that which is installed on the client machine. It’s all good and well defining your font to be a custom masterpiece and viewing it on your own desktop, however your regular punter who encounters your site will not witness the same experience.

Enter Cufon – a font generator and JavaScript rendering engine which will allow you to display the text within the browser how it was meant to be seen. Below is an example of the navigation on the Career Centre site; before and after Cufon.

The code to achieve this effect is pretty easy, something along the lines of:

<script type="text/javascript" src="cufon-yui.js"></script>
<script type="text/javascript" src="my.font.js"></script>

<script type="text/javascript">
    Cufon.replace('h1');
    Cufon.replace('.class');
    Cufon.replace('#id');
    Cufon.now();
</script>

I’m undecided if I really like the concept. I’m more of a purist and not sure if I like the performance hit and reliance on JavaScript – however you can’t argue with the results. Visually, it’s impressive.

Rounded corners in IE

Another feature which is harnessed across the Career Centre website is rounded corners driven by CSS. Previously if this had needed to be achieved I would have expected to have to use rounded corner images or an image background. These days with the advancement in browsers it can largely be achieved via CSS.

The newer versions of the major browsers all implement the border-radius tag to achieve this. Note however that IE9 needs the following meta tag to be included:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

Older versions of FireFox, Chrome, Safari and Opera used proprietary prefixes like the ones below to achieve the same effect.

-moz-border-radius: 9px;
-webkit-border-radius: 9px;
-o-border-radius: 9px;

As usual however, older versions of IE fail to play nicely. This is where PIE comes in to play. PIE stands for Progressive Internet Explorer and assists in implementing CSS3 features for older versions of IE. There is a JavaScript version, however the version used for the Career Centre is an .htc file and CSS definitions which look like that represented below:

behavior: url(/_layouts/myfolder/PIE.htc);

This is another feature that i’m yet to be sold on – again there is an obvious trade-off between performance and visual excellence. To read a little further on this topic check out Jamy Golden’s post on IE and rounded corners.

Implications for SharePoint

So where does SharePoint come into this you ask? I’ve recently been investigating an issue related to a popup message that comes up every time you click into the editing zones in IE – “One or more URLs were not valid and have been reformatted. Review the links before leaving this page.” as seen below.

It was even more strange considering there was no content in the editing zone. My first cynical instinct was to blame the new foreign features that had been introduced to the site and ironically enough that was precisely the case. Turns out that if I removed the offending JavaScript calls to Cufon and behavior attributes in the CSS file, the message wouldn’t appear.

So is the choice a visually impressive public facing website or an interrupted editing experience? Not exactly. The trick here is to make use of SharePoint’s EditModePanel control.

<PublishingWebControls:EditModePanel runat="server" PageDisplayMode="Edit">
</PublishingWebControls:EditModePanel>

By enclosing the offending JavaScript calls in the EditModePanel and seperating the behavior attributes into a seperate CSS file and referencing that in the control, you can manage to get the best of both worlds.

One last thing that needs to be considered regarding SharePoint and these features is that if you’re using

<meta http-equiv="X-UA-Compatible" content="IE=edge">

as pointed out earlier and want to edit content in IE8 standards mode, it’s quite possible you might run into problems – we did anyway. You can read a little bit about it via Randy Drisgill’s post Problems with IE8 Standards Mode, SharePoint Menus, and DocTypes. The solution here made use of the EditModePanel as well and went something along the lines of:

<PublishingWebControls:EditModePanel runat="server" PageDisplayMode="Display">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
</PublishingWebControls:EditModePanel>
<PublishingWebControls:EditModePanel runat="server" PageDisplayMode="Edit">
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
</PublishingWebControls:EditModePanel>

Custom Error Pages in SharePoint

As I alluded to in my post Exception Handling in SharePoint, providing custom error pages is an integral step in an overall exception handling strategy. This is particularly important for public facing internet sites to portray a consistent brand for the site in any situation, however is also relevant for intra or extranet portals to provide a more user-friendly experience and to reduce confusion in the event of an error. In similar fashion to my post on Error Logging in SharePoint, the information already available on this topic is extensive so the need for me to blog the specifics is negligible. This post will however join the link between my 2 previous posts mentioned above by outlining the best resources available in this area for both SharePoint 2007 and 2010.

In the ASP.NET world this topic would barely rate a mention. Handling this matter is essentially as simple as ensuring the <customErrors> mode=”” attribute is set to “On” and the defaultRedirect=”” attribute is set to a valid error page. We can’t use this method in SharePoint however as SharePoint has its own error handling infrastructure which overrides this functionality.

What we do have are different ways in which we can achieve this functionality in both versions of the product. When we talk of error pages in a SharePoint context we can group them into two categories for the purpose of identifying ways in which they can be addressed; 404 Page Not Found error pages and any others (which can include but are not limited to 401 Access Denied errors, 500 HTTP Status errors and the like).

404 Page Not Found

Microsoft has a knowledge base article How to point to a custom 404 error Web page in SharePoint which covers both versions of SharePoint. One thing to note here however is that it’s not necessary to create a console application to carry out the command in SharePoint 2007 – you can also use a powershell command to achieve the same thing noted in Ian Morrish’s post Using PowerShell to set a custom SharePoint Error Page.

Another thing to note is that this method requires the specified file to be valid HTML larger than 512 bytes in size. The size limitation is to ensure friendly HTTP error messages are not triggered in the client. I’ve also seen minorly-invalid HTML rendering as text in the browser so this is another thing to look out for. One more gotchya was identified by Andreas Glaser in SharePoint and custom 404 Page Not Found and UTF-8 issue with Firefox which is worth consideration.

One downside to the method presented above is that you are limited to static HTML pages deployed to the _layouts/1033 directory (or which ever LCID is appropriate for your site). This results in branding elements needing to be implemented in the static HTML and ensures maintenance of the page is more complicated than it should be. The main advice here is to implement a redirect on that error page to a standard SharePoint page along the lines identified by Jingmei Li in How to create your own custom 404 error page and handle redirect in SharePoint 2007 (MOSS)?.

There is another line of thought however, predominantly outlined by Waldek Mastykarz in his posts Accessible 404 (PageNotFound) in Microsoft Office SharePoint Server 2007 and SharePoint 2010 ‘Page not found (404)’ page the way it should be. This advocates using an HTTP Module to redirect the user to a page managed in SharePoint. If you’re going to go down this path focus on the second article and pay attention to Andrew Greaves’ comment.

While I like Waldek’s approach and appreciate its thoroughness in its flexibility for working in all scenarios and its technical correctness, for most purposes using the other method would suffice (particularly in controlled internal environments).

Other Error Pages

While the handling of 404 errors is quite similar in both SharePoint 2007 and 2010, the same cannot be said for other errors. SharePoint 2010 excels in this area providing an easy to use method of assigning these custom error pages at the web application level. Todd Carter provides a post titled An Expected Error Has Occurred which is well worth a read and while the code snippets are identical, Ram Prasad Meenavalli’s post Mapping Custom Error Pages for SharePoint 2010 Site is a good extension to it. Mike’s post SharePoint 2010 Custom Error Messages for Public Facing Deployments is a quality post particularly in terms of 401 authentication errors and is worth a look as well.

Implementing custom error pages for SharePoint 2007 however is not so simple. There seems to be 3 camps of thought; firstly there is the HTTP Module method similar to that used with the 404’s outlined above. While its a little difficult to read and follow, this method is documented in Ketaanh Shah’s post MOSS / Sharepoint 2007 Custom Error Page and Access denied Page. Another option is using a control adapter as per Aapo Talvensaari’s post Custom Error Page Adapter although i’d be a little wary implementing the functionality in this manner. My favourite option is Jeremy Jameson’s Error Handling in MOSS 2007 Applications which advocates hooking into the Error event from a custom master page – nice and clean, however it’s only really appropriate for errors that occur once the page has been accessed – i’m guessing it wouldn’t be suitable to handle errors such as a 401 authentication error.

In the interests of completeness there was one other form of configuring custom error pages I came across on Heath Anderson’s Implementing SharePoint 2010 Custom Error Pages. It is relevant to IIS7 and claims to work in SharePoint 2010 (whether it would work on an WSS instance installed on IIS7 i’m not sure). It definitely looks like a reasonably nice and clean option to consider, however it requires modifications to the web.config file even after configuring via the IIS UI and thus would not be the perfect option in my opinion.

So as you can see there are a bunch of ways in which you can implement custom error pages for your SharePoint site no matter which version of the product you are using. All methods vary in terms of their difficulty, suitability and correctness however the main takeaway is to ensure that you do use one of the methods and ensure that your users have the most user-friendly experience if they counter an error on your site.