Dynamically loading SharePoint 2010 or 2007 master pages for your legacy layouts

So you have a layouts page you used in your SharePoint 2007 product and you want to use it in SharePoint 2010. The functionality did not change much, however when you open the page it looks ugly and it uses an older SharePoint 2007 master page. What can I do to fix this, so that I have one code base that covers both platforms?

One option is to dynamically change the master page on the PreInit event. Keep the aspx page as it is and do not change the master page entry. In the page class add the snippet below. In this particular example I use reflection to find out the version of SharePoint, but you can use any other method.

protected override void OnPreInit(EventArgs e)
    bool isSP2010 = false;
        Assembly assembly = Assembly.LoadWithPartialName("Microsoft.Sharepoint");
        var assemblyName = assembly.GetName();
        isSP2010 = assemblyName.Version.Major > 13;
    catch (Exception)
        isSP2010 = false;
    if (isSP2010)
        this.Page.MasterPageFile = "/_layouts/applicationv4.master";

Layouts work on both SharePoint 2007 and 2010!


Credit goes also to Dan D. and Ivan P., thanks!


Rick said…
Ummmm.... YOU FREAKIN ROCK! Thank you for posting this.