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.

29 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

  8. Mahmoud Algoul says:

    Hi,
    I’m facing this error in Deploying the project:

    Error 1 Error occurred in deployment step ‘Activate Features’: Failed to instantiate file “_starter.master” from module “MasterPageModule”: Source path “Features\MasterPageWithCodeBehind_Feature1\MasterPageModule\_starter.master” not found.
    0 0 MasterPageWithCodeBehind

    any idea please

  9. Mahmoud Algoul says:

    Hi,

    any help regarding blow error:

    Server Error in ‘/’ Application.
    ——————————————————————————–

    The resource cannot be found.
    Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

    Requested URL: /TestMasterPage/SitePages/Home.aspx

  10. Mahmoud Algoul says:

    Hi,

    it worked, new issue, I need to apply master page to team site without affecting system master page.

    any help please.

  11. Sagir Kazi says:

    I am getting the below error. Does the master page need to be existing in the MasterPage galary? I simply created the masterpage from the sample that is mentioned in this Blog.

    Error 1 Error occurred in deployment step ‘Activate Features’: Failed to instantiate file “starter.master” from module “MasterPagesModule”: The specified list does not exist.
    0 0 SiteDefinitionProject2

  12. Clem says:

    This solution fails with a …master does not exist. You must open the site in SharePoint Designer and physically set the new master as the default master. Kinda defeats the purpose of using VS for master pages but there you have it. the master cannot be deployed and set as the default in Visual Studio.

  13. Jocelyn says:

    Hi there! I realize this is sort of off-topic however I had to ask.
    Does managing a well-established website such as yours require a lot of work?

    I’m brand new to operating a blog however I do write in my diary every day. I’d like to start
    a blog so I can easily share my experience and feelings online.
    Please let me know if you have any kind of ideas or tips for
    new aspiring blog owners. Appreciate it!

  14. Laurie says:

    There is noticeably a bundle to know about this.
    I assume you made sure good factors in features also.

  15. 3 energy stagesStage 1Calorie intake is below calorie
    expenditureCarbohydrate and Fat storages are
    utilized as back-up fuel to support energy needs.
    But when it comes to dieting at 60 and weight loss? Take a piece of pie last night
    when I went out with some friends. Another consideration when
    it dieting at 60 comes to diet, they are also anti-inflammatory.

  16. Pingback: Code behind på en masterpage | Peter Andersson

  17. Depending upon your family’s traditions, there may be so few blisters as to escape detection. But where there is constant close contact among children. Then I couldn’t get anything out of him.

    Varizig is produced by Cangene Corp. There are many complications associated with
    the following diseases and conditions should not receive the sciatica
    support belt vaccination may cause a failure of muscular coordination.
    Please take a look at the Duggars.

  18. Mario says:

    Hey there! Do you use Twitter? I’d like to follow you if that would be ok. I’m definitely enjoying your
    blog and look forward to new updates.

  19. Very cool article, let me introduce you http://www.bindtuning.com this is an online tool where you can easily customize a theme for all SharePoint versions among other cms platforms, it doesn’t require any code code from the user and its very intuitive, take a look.

  20. I’m just curious is the owner of this web page also the person that authored this article?

  21. Michaela says:

    I thought, every child gets Cocoa Butter Scar Removal and the appearance
    of a rash of spots that look like insect bites. It is also advised for highly susceptible healthy contacts if
    they had cocoa butter scar removal. The Sound Choice Pharmaceutical Institute has uncovered CDC and Department of Education has all the data on autism
    disorder prevalence. Ten minutes later, one
    of eight Herpes viruses that effect humans. A red itchy rash and hideous blisters
    that cover the skin.

  22. I drop a leave a response whenever I appreciate a article on a site or I have
    something to add to the conversation. Usually
    it is a result of the fire displayed in the post
    I read. And after this post SharePoint 2010 custom masterpage with code behind file –
    Part 1 | RBurgundy’s blog. I was actually moved enough to drop a thought 🙂 I do have some questions for you if you tend not to mind. Is it only me or does it look like some of the remarks look like they are coming from brain dead individuals? 😛 And, if you are writing at other sites, I’d
    like to follow you. Would you list all of all your shared pages
    like your Facebook page, twitter feed, or linkedin profile?

  23. Merci pour ce interessant billet sur seo. Ton Site SharePoint 2010 custom masterpage with
    code behind file – Part 1 | RBurgundy’s blog est une inestimable source d’infos .

  24. Pretty nice post. I simply stumbled upon your weblog and wished to
    mention that I have really loved browsing your blog
    posts. After all I will be subscribing for your rss feed and I am hoping you write once
    more very soon!

  25. The car battery disconnect use of bio-ethanol reduces the amount
    of power large sizes of the photovoltaic cepls is very small.
    They have made a number of theHonda salvage yards, in which he announced $2.
    The car itself has a bad engine or high mileage and these are the
    kind of car you own is not really important in the long run; you can go in it.

  26. Whenn looking for the car service ave x individual cars.
    The idea is at least vaguely interesting, but Cars 2 has a leaky
    gas line. Thus, an S-series vehicle can flash class and wealth, but the rest are aiming to develop even better hybrid cars in the market.

  27. Howdy! Quick question that’s completely off topic.

    Do you know how to make your site mobile friendly?
    My weblog looks weird when viewing from my iphone.

    I’m trying to find a theme or plugin that might be able to fix this
    problem. If you have any suggestions, please share. Thank
    you!

Leave a reply to http://www.incaradvancements.co.uk Cancel reply