SharePoint 2010 custom masterpage with code behind file – Part 2

In part 2 I will tell how I eventually got a code-behind file working on the custom master-page that I deployed trough Visual Studio. To be clear I don’t use SharePoint Designer to customize my master pages so I cannot guarantee that those pages will work.

To completely understand this information I recommend you to read Part 1 first.

The story continues….


Add Reference…

The next thing to do is adding a Reference to the SharePoint 2010 project.
This can be done by right-click on References in the Solution Explorer and then –> Add Reference

A new Window will popup arise that look like this:

As far as I know there 2 References that there need to be added:

  • Microsoft.SharePoint.Publishing
    • First select the Browse tab
    • then go to following directory: C:\Program Files\Microsoft Office Servers\14.0\Bin
    • Select Microsoft.SharePoint.Publishing.dll
    • Press the OK button
  • System.Web
    • Repeat the Add reference step
    • Now select the .NET tab
    • Find the System.Web
    • Select it and press the OK button














Add object(s) for the code-behind file

In this how-to I will add 2 objects that I will manipulate with the code-behind file.

First I added an asp:Label to the masterpage. I put this above the ribbon section so it will be noticed when it works.

<asp:Label ID="Label1" runat="server" Text=""></asp:Label>

I put a simple div around the ribbon so that I can disable the complete ribbon.

<div id="divRibbonContainer" runat="server">
<!-- =====  Begin Ribbon ============================================================ -->

<!-- =====  End Ribbon and other Top Content ============================================================ -->

The id’s of these objects will be needed for the code-behind file.

The code-behind file

To create a code behind file right-click on the Module in the solution, –> Add –> New Item…

In the following window select on the left Code –> Class and I called the file _starter.master.cs, just like a normal code-behind file.

There are some things that need to be added

  • Add using statements of:
    • System.Web;
    • System.Web.UI;
    • System.Web.UI.WebControls;
  • Make the class public and let it inherit from Masterpage
  • Declare protected objects from the masterpage
  • Add a page_load method

If you’ve done all that your class should look something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MasterPageWithCodeBehind.MasterPageModule
    public class _starter : MasterPage
        protected System.Web.UI.HtmlControls.HtmlGenericControl divRibbonContainer;
        protected Label Label1;

        protected void Page_Load(object sender, EventArgs e)
            divRibbonContainer.Visible = false;
            Label1.Text = "Hello World!";


Retrieving Public Key Token/PublicKeyToken

This is a little bit tricky, this token is needed in the next step when we need to apply the Inherits attribute.

  • First build the project
  • Right-click on the SharePoint 2010 project in the Solution Explorer
    • Click –> Open Folder in Windows Explorer
    • Next open: bin
    • Open: Debug
    • Copy the directory path and paste it into a text editor or something like that
    • Next copy the filename of the <Projectname>.dll file en past it behind the path you just pasted in the text editor
    • The result should be something like this:
      D:\administrator\documents\visual studio 2010\Projects\MasterPageWithCodeBehind\MasterPageWithCodeBehind\bin\Debug\MasterPageWithCodeBehind.dll
  • Next go to Start (Windows start menu)
    • Programs/All programs
      • Microsoft Visual Studio 2010
        • Visual Studio Tools
          • Visual Studio Command Prompt (2010)

You’ll get a dos prompt.
Do the following things:

  • Enter the following command: cd\
  • Next copy your complete directory path including the *.dll from your texteditor
  • Type the following:
    – sn.exe –Tp “<paste your directory + filename in here>”
    Don’t forget the quotes around the directory and filename
    It should look something like this:
    sn.exe -Tp "D:\administrator\documents\visual studio 2010\Projects\MasterPageWithCodeBehind\MasterPageWithCodeBehind\bin\Debug\MasterPageWithCodeBehind.dll"

The output should be something like this:

Copy the Public key token.


To combine the code-behind file with the masterpage there need to be an attribute added to the masterpage directive.
The following data is needed:

  • Namespace of the class & Type/Class name (these need to be seperated by a dot) (MasterPageWithCodeBehind.MasterPageModule._starter)
  • Strongname/Assembly in my case was this the same as the projectname (MasterPageWithCodeBehind)
  • Version (Version=
  • Culture (Culture=neutral)
  • PublicKeyToken (PublicKeyToken=f8a88530fbc7b81b)In the masterpage navigate to the following:
    <%@ Master language="C#" %>

Add the following Inherits attribute:
<%@ Master language="C#" Inherits="" %>

Now the 5 dots above need to be combined, in my situation it looks like this:
MasterPageWithCodeBehind.MasterPageModule._starter, MasterPageWithCodeBehind, Version=, Culture=neutral, PublicKeyToken=f8a88530fbc7b81b

Place this as value from the Inherits attribute.


Deploy your SharePoint 2010 project and load the default site.
Your ribbon should be gone and a text like Hello World! should be visible.

The left top corner of my SharePoint 2010 looks like this now:

This entry was posted in Geen categorie. Bookmark the permalink.

29 Responses to SharePoint 2010 custom masterpage with code behind file – Part 2

  1. Bobby Habib says:

    Nice :o)

    Thanks for sharing the Knowledge.

  2. Excellent post! Just what I was looking for. By the way, I thought I’d share another tip I think you’d find helpful. It’s an easy way for getting those strongly named keys easier.

    Use this for an x64 machine + Visual Studio 2010.
    \Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\sn.exe

  3. Clyde Lin says:

    I have investigating it for hours! Your post is really helpful.
    Thanks very much on sharing!

  4. w0ut says:

    Use Redgate reflector to get the public key token. It’s free.

  5. Chris says:

    Nice article! Is this any different if your custom master page is in a sandboxed solution?

  6. Marwen says:

    thank you for this post

  7. Thank you, your post is far the best resource to start a customized master page with full control from Visual Studio.


  8. vasu says:

    nice post

  9. Arthur says:

    Yeah, that’s cool, but what about standard SharePoint 2010 Token: ‘$SharePoint.Project.AssemblyFullName$’, which is replaced with full assembly name during packagin?

  10. Many thanks,
    Very useful post

  11. Wilco24 says:

    Thanks, worked correctly.

  12. Simon says:

    Awesome Walkthrough, but i got one problem.

    As soon as i Deploy the solution to my farm and activate the MasterPage with Codebehind it always says:
    Could not load assembly … Make sure its compiled before … .

    Anyone else got this problem??

  13. Pingback: Wait, There’s No Code-Behind File for a SharePoint Master Page? « ElectroVoid

  14. Brian Almeter says:

    Yes, I got the could not load assembly before compiled issue too. Any solution?

  15. Jish Nath says:

    excellent! thanks!

  16. Terrence says:

    hello!,I love your writing very much! share we keep in touch more about
    your article on AOL? I need a specialist on this house to resolve my problem.

    Maybe that is you! Taking a look forward to see you.

  17. What you posted made a lot of sense. But, think on this, suppose you wrote a catchier title?
    I mean, I don’t wish to tell you how to run your website, however what if you added something that makes people want more? I mean SharePoint 2010 custom masterpage with code behind file – Part 2 | RBurgundy’s blog is kinda boring.

    You should glance at Yahoo’s front page and watch how they create news headlines to get people to open the links. You might try adding a video or a related pic or two to get people excited about everything’ve written.

    Just my opinion, it could bring your posts
    a little bit more interesting.

  18. Overall, if you need more storage capacity, then you should
    definitely get yourself a 6th Generation i – Pod Classic.
    four GHz which is why you want to invest
    in a jammer that can tamper this signal.
    Since it is an HD radio, it produces clear treble and bass tones, and has static
    radio reception.

  19. You can definitely see your expertise in the work you write.

    The sector hopes for even more passionate writers such as you who
    aren’t afraid to say how they believe. Always go after your heart.

  20. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each
    time a comment is added I get four e-mails with the same
    comment. Is there any way you can remove people from that service?


  21. Rdert die Entspannung Anwendung und Bedeutung von Silber in der EsoterikSilber ist dem Mond zugeordnet und
    gilt als weiblich, zusammen mit anderen heilsteine lexikonn
    verstrkt Silber deren Wirkung. Dafrika und Westaustralien gefunden.
    Die grten Diamantenvorkommen befinden sich in Russland, Brasilien,?

  22. MV says:


    I’v a prob Guy…

    I follow your instruction and my master page has changed to new one and works on “Homepage” and “add an app” Page But wen i click list pages it Throw an Error:

    The base type ‘Masterpagecode.AppletonMasterPages.NerderySite’ is not allowed for this page. The type Masterpagecode.AppletonMasterPages.NerderySite, Masterpagecode, Version=, Culture=neutral, PublicKeyToken=6ddbfeb342eefbe8 could not be found or it is not registered as safe.

    Would you please help me? I’m working with sp2013

  23. Aw, this was an extremely nice post. Finding the time and actual effort
    to produce a good article… but what can I say… I procrastinate a lot and don’t manage to get anything done.

  24. Sara Williams says:

    Has anyone successfully deployed custom master page (w\ code behind) for Sharepoint Online? I am receiving the error:
    Could not load the assembly ‘[assembly name], Version=, Culture=neutral, PublicKeyToken=7387cf1d3203ff91’. Make sure that it is compiled before accessing the page.

    I’d really appreciate any feedback. I’ve been investigating this for days now with no resolve. I’ve double checked the master directive, and verified fully qualified assembly name, and all appears ok.

    Many Thanks in advance

  25. Thanks for the help. Greatly appreciated

  26. Excellent post. I absolutely love this site. Continue the good work!

  27. using System;
    using System.Runtime.InteropServices;
    using Microsoft.SharePoint;

    namespace Branding101.Features.Main {
    public class MainEventReceiver : SPFeatureReceiver {
    public override void FeatureActivated(
    SPFeatureReceiverProperties properties) {

    // TODO: add activation code here.

    public override void FeatureDeactivating(
    SPFeatureReceiverProperties properties) {

    // TODO: add deactivation code here.

    Now let’s step through what you have to do when the main Feature is activated. First, you must determine the path to Branding101.master in the master page gallery so that you can configure sites to use it as their master page. Note that the path to the master page must be calculated relative to the root of the hosting web application. Next, you must enumerate all the sites in the current site collection and update several properties of each site to use the custom master page and the custom CSS file. The following implementation of the FeatureActivated(SPFeatureReceiverProperties) method updates the required SPWeb properties for each site.

    public override void FeatureActivated(
    SPFeatureReceiverProperties properties) {
    SPSite siteCollection = properties.Feature.Parent as SPSite;
    if (siteCollection != null) {
    SPWeb topLevelSite = siteCollection.RootWeb;

    // Calculate relative path to site from Web Application root.
    string WebAppRelativePath = topLevelSite.ServerRelativeUrl;
    if (!WebAppRelativePath.EndsWith(“/”)) {
    WebAppRelativePath += “/”;

    // Enumerate through each site and apply branding.
    foreach (SPWeb site in siteCollection.AllWebs) {
    site.MasterUrl = WebAppRelativePath +
    site.CustomMasterUrl = WebAppRelativePath +
    site.AlternateCssUrl = WebAppRelativePath +
    site.SiteLogoUrl = WebAppRelativePath +
    site.UIVersion = 4;

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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