Thursday, May 28, 2015

Sharepoint 2010 Create a Custome Master Page using Visual Studio

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. You can get his minimal masterpage here: Starter Master Page.

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.




Start of 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.
asp:LabelFirst 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>
div
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 ============================================================ -->
</div>
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.

Inherits

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=1.0.0.0)
  • 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=1.0.0.0, Culture=neutral, PublicKeyToken=f8a88530fbc7b81b

Place this as value from the Inherits attribute.

Result

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:


0 comments:

Post a Comment