Tuesday, October 5, 2010

Create Custom Master page and Code Behind in Sharepoint

This post explains how to create a master page for sharepoint in your code, how to create its code behind and how to deploy both in sharepoint using feature.

First step is how you make your project. You have to make the exact folder structure. Starting from TEMPLATE/FEATURES/[Name of the Feature].
First I have created a Folder structure - Template/Features/CustomMasterPage/
In that I have another folder - MasterPages. In master pages I have two files - CustomMaster.master and CustomMaster.cs. Outside the MasterPages folder, I have two files - Feature.xml and ProvisionedFiles.xml.

You can create the design of the master page in sharepoint designer for ease and copy the same here. The important line in the design page is the inherits attribute

<%@ Master language="C#" Inherits="Eversheds.Connect.TEMPLATE.FEATURES.MASTERPAGE.EvershedsMasterPage, Eversheds.Connect, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6624dc3946212ada" meta:progid="SharePoint.WebPartPage.Document" %>

You need to specify the complete name in the inherits attribute. For cs you can make any cs file and include that as page behind for the master page.
I needed a code behind for master page to include logging. My master page handles all exception handling for the entire site.

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging;
using System.Diagnostics;
using Eversheds.Connect.Util;
using Microsoft.SharePoint;

namespace Eversheds.Connect.TEMPLATE.FEATURES.MASTERPAGE
{
public class EvershedsMasterPage : System.Web.UI.MasterPage
{
ScriptManager scriptMan = null;
string _eventLogName = Toolkit.GetEventLogName();
string _eventLogSource = Toolkit.GetEventLogSource();
string _onOffInfo = Toolkit.GetOnOffInfo();
string _eventLogListener = Toolkit.GetEventLogListener();
string _rollingFileListener = Toolkit.GetRollingLogListener();

protected void Page_Init(object sender, EventArgs e)
{
this.Page.Error += new EventHandler(Page_Error);
}

protected void Page_Load(object sender, EventArgs e)
{
//EnsureScriptManager();
Page_Error(sender, e);
}

private void EnsureScriptManager()
{
if (ScriptManager.GetCurrent(this.Page) == null)
{
scriptMan = new ScriptManager();
this.Controls.Add(scriptMan);
}
else
{
scriptMan = ScriptManager.GetCurrent(this.Page);
}
scriptMan.EnablePartialRendering = true;
}

///
/// Page Error to write log entries to event log and rolling file log
///

///
///
void Page_Error(object sender, EventArgs e)
{
try
{
string err="";
//Create an event source if it does not exist
if (!EventLog.SourceExists(_eventLogSource))
{
EventLog.CreateEventSource(_eventLogSource, _eventLogName);
}
//Write to Event log trace listener
// var currErrors = HttpContext.Current.AllErrors;
SPContext currentContext;
try
{
//Getting the current context
currentContext = SPContext.Current;
}
catch (InvalidOperationException)
{
currentContext = null;
}
Exception ex = HttpContext.Current.Error;
if ((currentContext != null) && (ex != null))
{
err = "Sharepoint Internal Error" + ex.Message.ToString();

Logger.Write(err, _eventLogListener, 1, 2000, TraceEventType.Error, _eventLogListener);
//Write info only if the variable is set to on in the config file
if ((_onOffInfo == "on") || (_onOffInfo == "On") || (_onOffInfo == "ON"))
{
using (new Tracer("Trace"))
{
//Write to rolling text file
Logger.Write(err, _rollingFileListener, 2, 4000, TraceEventType.Information, _rollingFileListener);
}
}
}
}
catch (Microsoft.SharePoint.WebPartPages.WebPartPageUserException mex)
{
//Write to Event log trace listener
Logger.Write(mex.Message.ToString(), _eventLogListener, 1, 2000, TraceEventType.Error, _eventLogListener);
//Write info only if the variable is set to on in the config file
if ((_onOffInfo == "on") || (_onOffInfo == "On") || (_onOffInfo == "ON"))
{
using (new Tracer("Trace"))
{
//Write to rolling text file
Logger.Write(mex.Message.ToString(), _rollingFileListener, 2, 4000, TraceEventType.Information, _rollingFileListener);
}
}
}

catch (Exception ex)
{
//Write to Event log trace listener
Logger.Write(ex.Message.ToString(), _eventLogListener, 1, 2000, TraceEventType.Error, _eventLogListener);
//Write info only if the variable is set to on in the config file
if ((_onOffInfo == "on") || (_onOffInfo == "On") || (_onOffInfo == "ON"))
{
using (new Tracer("Trace"))
{
//Write to rolling text file
Logger.Write(ex.Message.ToString(), _rollingFileListener, 2, 4000, TraceEventType.Information, _rollingFileListener);
}
}
}
}
}
}

For logger, you need to configure the Microsoft application blocks on the server. You can find out more information about the same on the below link



Next we need a Feature.xml

Feature Id="8C463F26-AE3C-4309-A284-AC095EB351A9"
Title="EvershedsMasterPage"
Description="Eversheds Custom Master page for use"
Version="12.0.0.0"
Scope="Site"
Hidden="FALSE"
DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/"
ElementManifests
ElementManifest Location="ProvisionedFiles.xml"
ElementManifests
Feature

Last in the ProvisionedFiles.xml

Elements xmlns="http://schemas.microsoft.com/sharepoint/"

Module Name="OSGMasterPages" Url="_catalogs/masterpage" Path="MasterPages" RootWebOnly="TRUE"

File Url="EvershedsMasterPage.master" Type="GhostableInLibrary"
Property Name="ContentType" Value="$Resources:cmscore,contenttype_masterpage_name;"
Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/PolarisSample.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/PolarisSample.png"
Property Name="MasterPageDescription" Value="This is sample master page;"
File
Module
Module Name="MasterPagesModule" Url="_catalogs/masterpage" Path="MasterPages" RootWebOnly="TRUE"

File Url="EvershedsMasterPage.master" Type="GhostableInLibrary"
File
Module
Module Name="PublishingLayoutsPreviewImages" Url="_catalogs/masterpage" IncludeFolders="??-??*" Path="" RootWebOnly="TRUE"
File Url="PolarisSample.png" Name="Preview Images/PolarisSample.png" Type="GhostableInLibrary"
File
Module

Elements

Create a wsp and deploy it to the server. After running the deployment script, activate your feature and the master page would be ready for use.

No comments:

Post a Comment