SharePoint 2010 custom masterpage with code behind file – Part 1

Part 1 – Deploy a custom masterpage on SharePoint 2010 trough Visual Studio 2010

Introduction

Why the creators of SharePoint made it so hard to have an codebehind file for your master I really don’t get, but gladly there’s a way to do it.

This first part will describe how to deploy your own custom masterpage with Visual Studio. I’m not using SharePoint Designer and I like to code everything myself. With SharePoint 2010 and their masterpage uploading system I cannot easily use my own version-control system like subversion. With this work around it is possible

I will tell the steps I needed to do to get a codebehind file for my SharePoint 2010 masterpage.



Getting started

First of all, you need to get SharePoint 2010 installed and Visual Studio 2010.

Next open Visual Studio 2010 and create a new Project.
I choose the language Visual C# on the left, then selected SharePoint –> 2010 and then create an Empty SharePoint Project.
I named the project: MasterPageWithCodeBehind.


After clicking the OK button, you will be asked how and where you want to deploy it, I choose to Deploy it as a farm solution.

 

Module


Right-click on the SharePoint Project in your Solution Explorer on the right then –> Add –> New Item.


You’ll get a new window where you can choose multiple items. I created a module and called it MasterPageModule.


You’ll see that the module is added to your project with a sample file called Sample.txt. There’s also an Elements.xml file in the module, in this file the other files will be registered. I deleted the Sample.txt in my Solution Explorer and Visual Studio automatically removed it from the Elements.xml file.

The next step I did was copying my custom masterpage into the module. This can be done by copying the file from Windows Explorer en then right-click on your Module in the Solution Explorer. I used the masterpage from Randy Drisgill. You can get his minimal masterpage here: Starter Master Page. His blog with very useful tips is: Randy Drisgill SharePoint Branding and Design

After I paste it into my Module my Elements.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MasterPageModule">
  <File Path="MasterPageModule\_starter.master" Url="MasterPageModule/_starter.master" />
</Module>
</Elements>

In Module this attribute needs to be added: Url="_catalogs/sharepoint".
In File the Url attribute needs to be changed as follows: "_starter.master"
In File also this attribute needs to be added: Type="GhostableInLibrary".
This will make sure that the file will be cached. More info here.


My Element.xml looks like this now:
 

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MasterPageModule" Url="_catalogs/masterpage">
    <File Path="MasterPageModule\_starter.master" Url="_starter.master" Type="GhostableInLibrary"/>
  </Module>
</Elements>


Feature

In this beta of Visual Studio 2010 a feature is automatically created when I added a Module into the solution. If not you have to create a feature yourself, here’s how you do it: (if there’s automatically added a feature you can skip it and move to the next part)

———-
The final step to do is creating a feature that will configure the masterpage.
Right-click on Features in your Solution Explorer and click Add Feature.


Now a new Feature is created, and the properties window of that Feature has popped up. Underneath the Title, Description and Scope there are 2 large fields. On the left you’ll see the created Module, add this to the left and it should look like this:


———–

 

Next I right-clicked on the Feature1 and then –> Add Event Receiver.

A new window will be open with the content of Feature1.EventReceiver.cs.
Uncomment these methods:

  • FeatureActivated
  • FeatureDeactivating

The code underneath will overwrite the MasterPage variables.
When it is deactivated it will restore the values back to a default SharePoint masterpage.

The code:

—————–

// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPWeb currentWeb = (SPWeb)properties.Feature.Parent;

    currentWeb.MasterUrl = "/_catalogs/masterpage/_starter.master";
    currentWeb.CustomMasterUrl = "/_catalogs/masterpage/_starter.master";
    currentWeb.Update();
}

// Uncomment the method below to handle the event raised before a feature is deactivated.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    SPWeb currentWeb = (SPWeb)properties.Feature.Parent;

    currentWeb.MasterUrl = "/_catalogs/masterpage/nightandday.master";
    currentWeb.CustomMasterUrl = "/_catalogs/masterpage/nightandday.master";
    currentWeb.Update();
}

——————-

End of part 1


When this will be deployed, the custom masterpage is loaded instead of the default without uploading/publishing a masterpage trough the web interface, pretty neat huh.

Your SharePoint 2010 site should look something like this now (if you used the same masterpage as I did):

 

This is the first part of how to create a code-behind file and this part is focused on how getting the fundamentals right. The result of following part 1 is a alternative manner to deploy a masterpage.

Here’s Part 2

This entry was posted in Sharepoint 2010. Bookmark the permalink.

9 Responses to SharePoint 2010 custom masterpage with code behind file – Part 1

  1. Ron says:

    Great post!

  2. Unknown says:

    Hi,very nice tutorial. if someone have still trouble with creating and deploying custom masterpage with codebehind, try to look at the following blogpost. it have screenshots and detailed comments.http://sharepoint-charles.blogspot.com/ – <a href="http://sharepoint-charles.blogspot.com/">Sharepoint Custom Master Page</a>

  3. Fred says:

    May be you should dispose your SharePoint objects in the Event Receiver…

  4. Phil says:

    Fred – you should NOT displose of the SharePoint objects in the Event Receiver. The objects within the SPFeatureReceiverProperties are managed by SharePoint and do not need to be disposed, similar to SPContext objects; doing so could cause adverse effects for other processes that rely on these objects.

  5. np says:

    Hi,
    I’ve created a Visual Web Part Project and added the Master page as shown here. While deploying it gives error “Error occurred in deployment step ‘Activate Features’: Unable to cast object of type ‘Microsoft.SharePoint.SPSite’ to type ‘Microsoft.SharePoint.SPWeb’”. Any idea?

    • diederik050 says:

      It has been a long time for me working with SharePoint, but I guess you’re scope is set to a Site instead of Web? When you add a Feature you can select it’s Scope. In this example it’s using Web, I think there’s you problem, good luck!

      • Chetana says:

        how to create an custom master page in sharepoint 2010?? Can anyone tell me?Thankx in advance

  6. Bas says:

    Do you still have to activate the Publishing Feature when Creating a New Site?

    Thanks!

  7. Pingback: SharePoint 2010 Custom Masterpage with code behind file « Jinesh Shah

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s