In case you want to delete the web part as soon as a feature is deactivated, you can write a feature receiver for the same.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
//Remove the web part from web part gallery
SPSite site = null;
StringBuilder sb = new StringBuilder();
try
{
using (SPWeb web = properties.Feature.Parent as SPWeb)
{
SPList list = web.Lists["Web Part Gallery"];//site.GetCatalog(SPListTemplateType.WebPartCatalog);
for (int i = list.ItemCount - 1; i >= 0; i--)
{
// format name to look like a feature name
string webpartName = list.Items[i].Name;
webpartName = webpartName.Substring(0, webpartName.IndexOf("."));
// delete web parts that have been added
if ((webpartName == "WPChat") || (list.Items[i].DisplayName.Equals("WPChat")))
{
list.Items[i].Delete();
break;
}
}
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
finally
{
if (site != null)
site.Dispose();
}
}
Tuesday, December 28, 2010
Add entries to web.config using wsp
In order to use your solution to add web.config entries follow the below approach-
Step 1: Create feature folder
Step 2: Create Feature.xml file -
Feature Id="113AEEBD-97B0-411a-B118-F6FE6D232C5E"
Title="IMWEBCONFIG"
Description="This feature modifies the Web Application web.config"
Scope="WebApplication"
ReceiverAssembly="Eversheds.InstantMessaging, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=b0c7276684f0a390 "
ReceiverClass="Eversheds.InstantMessaging.FeatureReceiver.ReceiverWebConfig"
xmlns="http://schemas.microsoft.com/sharepoint/"
/Feature
Step 3: Create feature receiver class
SPWebConfigModification webConfigModifications;
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
var oWebApp = properties.Feature.Parent as Microsoft.SharePoint.Administration.SPWebApplication;
try
{
if (!oWebApp.IsAdministrationWebApplication)
{
ModifyWebConfigEntries(oWebApp);
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
}
public void ModifyWebConfigEntries(SPWebApplication oWebApp)
{
#region Http Module Section
webConfigModifications = new SPWebConfigModification();
webConfigModifications.Path = "configuration/system.web/httpModules";
webConfigModifications.Name = "add[@name='CustomHttpModule']";
webConfigModifications.Sequence = 0;
webConfigModifications.Owner = "addCustomModule";
webConfigModifications.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
webConfigModifications.Value = @" ";
oWebApp.WebConfigModifications.Add(webConfigModifications);
#endregion
SPWebService.ContentService.WebApplications[oWebApp.Id].Update();
//Applies the web config settings in all the web application in the farm
SPWebService.ContentService.WebApplications[oWebApp.Id].WebService.ApplyWebConfigModifications();
}
Step 1: Create feature folder
Step 2: Create Feature.xml file -
Feature Id="113AEEBD-97B0-411a-B118-F6FE6D232C5E"
Title="IMWEBCONFIG"
Description="This feature modifies the Web Application web.config"
Scope="WebApplication"
ReceiverAssembly="Eversheds.InstantMessaging, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=b0c7276684f0a390 "
ReceiverClass="Eversheds.InstantMessaging.FeatureReceiver.ReceiverWebConfig"
xmlns="http://schemas.microsoft.com/sharepoint/"
/Feature
Step 3: Create feature receiver class
SPWebConfigModification webConfigModifications;
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
var oWebApp = properties.Feature.Parent as Microsoft.SharePoint.Administration.SPWebApplication;
try
{
if (!oWebApp.IsAdministrationWebApplication)
{
ModifyWebConfigEntries(oWebApp);
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
}
public void ModifyWebConfigEntries(SPWebApplication oWebApp)
{
#region Http Module Section
webConfigModifications = new SPWebConfigModification();
webConfigModifications.Path = "configuration/system.web/httpModules";
webConfigModifications.Name = "add[@name='CustomHttpModule']";
webConfigModifications.Sequence = 0;
webConfigModifications.Owner = "addCustomModule";
webConfigModifications.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
webConfigModifications.Value = @"
oWebApp.WebConfigModifications.Add(webConfigModifications);
#endregion
SPWebService.ContentService.WebApplications[oWebApp.Id].Update();
//Applies the web config settings in all the web application in the farm
SPWebService.ContentService.WebApplications[oWebApp.Id].WebService.ApplyWebConfigModifications();
}
Monday, December 27, 2010
Create list in Feature using list templates
Suppose you have your list templates ready with you. Now you want to deploy the same using a solution. How will you do that using a Feature.
Step 1: Create a Feature folder in your solution
Step 2: Create a folder for your templates say 'ListTemplates' and place all your stp files there.
Step 3: Create a Feature.xml file -
Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="93E56B63-EA76-43b7-9068-162DCFA1FAE4"
Title="IMEVUSERLIST"
Description="Deploy user list for Instant Messaging"
Scope="Web"
Hidden="false"
Version="1.0.0.0"
ReceiverAssembly="Eversheds.InstantMessaging,Version=1.0.0.0,Culture=neutral, PublicKeyToken=b0c7276684f0a390"
ReceiverClass="Eversheds.InstantMessaging.FeatureReceiver.ReceiverEVUserList"
ElementManifests
ElementManifest Location="Elements.xml"/
/ElementManifests
Properties xmlns="http://schemas.microsoft.com/sharepoint/"
!-- Instant Messaging Lists --
Property Key="InstantMessagingLists" Value="EVChatImage,EVConfigInfo,EVUserList"/
/Properties
/Feature
Step 3: Create Elements file
?xml version="1.0" encoding="utf-8" ?
Elements xmlns="http://schemas.microsoft.com/sharepoint/"
/Elements
Step 4: Create feature receiver
namespace Eversheds.InstantMessaging.FeatureReceiver
{
public class ReceiverEVUserList : SPFeatureReceiver
{}
}
Override all events. Below is the code for FeatureActivated
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb parentWeb;
SPSite siteCollection;
if (properties.Feature.Parent is SPWeb)
{
parentWeb = (SPWeb)properties.Feature.Parent;
siteCollection = parentWeb.Site;
}
else if (properties.Feature.Parent is SPSite)
{
parentWeb = ((SPSite)properties.Feature.Parent).RootWeb;
siteCollection = (SPSite)properties.Feature.Parent;
}
else
{
throw new Exception("Unable to retrieve SPWeb - this feature is not Site or Web-scoped.");
}
string directory = properties.Definition.RootDirectory;
try
{
if (!directory.EndsWith("\\"))
directory += "\\";
directory += "ListTemplates";
if (System.IO.Directory.Exists(directory))
{
string[] templates = System.IO.Directory.GetFiles(directory, "*.stp", System.IO.SearchOption.TopDirectoryOnly);
SPDocumentLibrary listTemplates = siteCollection.GetCatalog(SPListTemplateType.ListTemplateCatalog) as SPDocumentLibrary;
UploadTemplates(listTemplates, templates);
// Add lists from the List Template Gallery
parentWeb.AllowUnsafeUpdates = true; //get the list of list templates from the web
SPListTemplateCollection customListTemplates = siteCollection.GetCustomListTemplates(parentWeb); //create the connection library using the uploaded list template
//Get list collection
SPListCollection listCollection = parentWeb.Lists;
//Create List EVConfigInfo------------------------
if (ListExists(listCollection, "EVConfigInfo"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVConfigInfo"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpConfigInfo = customListTemplates["EVConfigInfo"];
parentWeb.Lists.Add("EVConfigInfo", "List for Config Info", stpConfigInfo);
//Create List EVUserList------------------------
if (ListExists(listCollection, "EVUserList"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVUserList"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpUserList = customListTemplates["EVUserList"];
parentWeb.Lists.Add("EVUserList", "List for User Info", stpUserList);
//Create List EVChatImage------------------------
if (ListExists(listCollection, "EVChatImage"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVChatImage"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpChatImage = customListTemplates["EVChatImage"];
parentWeb.Lists.Add("EVChatImage", "List for Chat image", stpChatImage);
parentWeb.Update();
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
}
#region UploadTemplates
///
/// Method to create Sharepoint Lists from template files
///
///
///
private void UploadTemplates(SPDocumentLibrary templateGallery, string[] templateFiles)
{
if (templateGallery != null)
{
foreach (string template in templateFiles)
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(template);
SPQuery query = new SPQuery();
query.Query = string.Format(" " + "{0} ", fileInfo.Name);
SPListItemCollection existingTemplates = templateGallery.GetItems(query);
int[] Ids = new int[existingTemplates.Count];
for (int i = 0; i < existingTemplates.Count; i++)
{
Ids[i] = existingTemplates[i].ID;
}
for (int j = 0; j < Ids.Length; j++)
{
templateGallery.Items.DeleteItemById(Ids[j]);
} byte[] stp = System.IO.File.ReadAllBytes(template);
templateGallery.RootFolder.Files.Add(fileInfo.Name, stp);
}
}
}
#endregion
private static bool ListExists(SPListCollection collection, string title)
{
bool flag = false;
foreach (SPList list in collection)
{
if (list.Title == title)
flag = true;
}
return flag;
}
Step 5: Deploy using wsp builder. The lists will be created
Step 1: Create a Feature folder in your solution
Step 2: Create a folder for your templates say 'ListTemplates' and place all your stp files there.
Step 3: Create a Feature.xml file -
Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="93E56B63-EA76-43b7-9068-162DCFA1FAE4"
Title="IMEVUSERLIST"
Description="Deploy user list for Instant Messaging"
Scope="Web"
Hidden="false"
Version="1.0.0.0"
ReceiverAssembly="Eversheds.InstantMessaging,Version=1.0.0.0,Culture=neutral, PublicKeyToken=b0c7276684f0a390"
ReceiverClass="Eversheds.InstantMessaging.FeatureReceiver.ReceiverEVUserList"
ElementManifests
ElementManifest Location="Elements.xml"/
/ElementManifests
Properties xmlns="http://schemas.microsoft.com/sharepoint/"
!-- Instant Messaging Lists --
Property Key="InstantMessagingLists" Value="EVChatImage,EVConfigInfo,EVUserList"/
/Properties
/Feature
Step 3: Create Elements file
?xml version="1.0" encoding="utf-8" ?
Elements xmlns="http://schemas.microsoft.com/sharepoint/"
/Elements
Step 4: Create feature receiver
namespace Eversheds.InstantMessaging.FeatureReceiver
{
public class ReceiverEVUserList : SPFeatureReceiver
{}
}
Override all events. Below is the code for FeatureActivated
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb parentWeb;
SPSite siteCollection;
if (properties.Feature.Parent is SPWeb)
{
parentWeb = (SPWeb)properties.Feature.Parent;
siteCollection = parentWeb.Site;
}
else if (properties.Feature.Parent is SPSite)
{
parentWeb = ((SPSite)properties.Feature.Parent).RootWeb;
siteCollection = (SPSite)properties.Feature.Parent;
}
else
{
throw new Exception("Unable to retrieve SPWeb - this feature is not Site or Web-scoped.");
}
string directory = properties.Definition.RootDirectory;
try
{
if (!directory.EndsWith("\\"))
directory += "\\";
directory += "ListTemplates";
if (System.IO.Directory.Exists(directory))
{
string[] templates = System.IO.Directory.GetFiles(directory, "*.stp", System.IO.SearchOption.TopDirectoryOnly);
SPDocumentLibrary listTemplates = siteCollection.GetCatalog(SPListTemplateType.ListTemplateCatalog) as SPDocumentLibrary;
UploadTemplates(listTemplates, templates);
// Add lists from the List Template Gallery
parentWeb.AllowUnsafeUpdates = true; //get the list of list templates from the web
SPListTemplateCollection customListTemplates = siteCollection.GetCustomListTemplates(parentWeb); //create the connection library using the uploaded list template
//Get list collection
SPListCollection listCollection = parentWeb.Lists;
//Create List EVConfigInfo------------------------
if (ListExists(listCollection, "EVConfigInfo"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVConfigInfo"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpConfigInfo = customListTemplates["EVConfigInfo"];
parentWeb.Lists.Add("EVConfigInfo", "List for Config Info", stpConfigInfo);
//Create List EVUserList------------------------
if (ListExists(listCollection, "EVUserList"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVUserList"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpUserList = customListTemplates["EVUserList"];
parentWeb.Lists.Add("EVUserList", "List for User Info", stpUserList);
//Create List EVChatImage------------------------
if (ListExists(listCollection, "EVChatImage"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVChatImage"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpChatImage = customListTemplates["EVChatImage"];
parentWeb.Lists.Add("EVChatImage", "List for Chat image", stpChatImage);
parentWeb.Update();
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
}
#region UploadTemplates
///
/// Method to create Sharepoint Lists from template files
///
///
///
private void UploadTemplates(SPDocumentLibrary templateGallery, string[] templateFiles)
{
if (templateGallery != null)
{
foreach (string template in templateFiles)
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(template);
SPQuery query = new SPQuery();
query.Query = string.Format("
SPListItemCollection existingTemplates = templateGallery.GetItems(query);
int[] Ids = new int[existingTemplates.Count];
for (int i = 0; i < existingTemplates.Count; i++)
{
Ids[i] = existingTemplates[i].ID;
}
for (int j = 0; j < Ids.Length; j++)
{
templateGallery.Items.DeleteItemById(Ids[j]);
} byte[] stp = System.IO.File.ReadAllBytes(template);
templateGallery.RootFolder.Files.Add(fileInfo.Name, stp);
}
}
}
#endregion
private static bool ListExists(SPListCollection collection, string title)
{
bool flag = false;
foreach (SPList list in collection)
{
if (list.Title == title)
flag = true;
}
return flag;
}
Step 5: Deploy using wsp builder. The lists will be created
Populate the web part gallery programatically
Suppose you are deploying everything using solutions. You have lots of webparts. How will you populate the web part gallery using your solution. This will allow the user to just add the web part to the page immediately after deploying wsp.
Step1 - Create a Feature.xml file
Feature Id="D34D00B1-EC5C-4da8-8C50-009CB4B8BB42"
Title="IMCHATFEATURE"
Description="This is the chat Webpart"
Version="12.0.0.0"
Hidden="FALSE"
Scope="Web"
DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/"
ElementManifests
ElementManifest Location="elements.xml"/
ElementFile Location="WPChat.webpart" /
/ElementManifests
/Feature
Step 2: Create an Element File
Elements xmlns="http://schemas.microsoft.com/sharepoint/"
Module Name="WebPartPopulation" Url="_catalogs/wp" RootWebOnly="TRUE" List="113"
File Url="WPChat.webpart" Type="GhostableInLibrary"
/File
/Module
/Elements
Step 3: Create a .webpart file for your webpart
webParts
webPart xmlns="http://schemas.microsoft.com/WebPart/v3"
metaData
type name="Eversheds.InstantMessaging.WebParts.WPChat, Eversheds.InstantMessaging, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=b0c7276684f0a390 "/type
importErrorMessage>Can not import WPChat/importErrorMessage
/metaData
data
properties
property name="Title" type="string"WPChat/property
property name="Description" type="string"A web part which allows the user to chat/property
/properties
/data
/webPart
/webParts
Step 4: Lastly create the .cs file for your web part
namespace Eversheds.InstantMessaging.WebParts
{
public class WPChat : System.Web.UI.WebControls.WebParts.WebPart
{}
}
Place all files in step1,2 and 3 in your feature folder. Deploy using wsp builder. The cs file should be outside the 12 hive folder.
Your web part will be available for the user in the gallery.
Step1 - Create a Feature.xml file
Feature Id="D34D00B1-EC5C-4da8-8C50-009CB4B8BB42"
Title="IMCHATFEATURE"
Description="This is the chat Webpart"
Version="12.0.0.0"
Hidden="FALSE"
Scope="Web"
DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/"
ElementManifests
ElementManifest Location="elements.xml"/
ElementFile Location="WPChat.webpart" /
/ElementManifests
/Feature
Step 2: Create an Element File
Elements xmlns="http://schemas.microsoft.com/sharepoint/"
Module Name="WebPartPopulation" Url="_catalogs/wp" RootWebOnly="TRUE" List="113"
File Url="WPChat.webpart" Type="GhostableInLibrary"
/File
/Module
/Elements
Step 3: Create a .webpart file for your webpart
webParts
webPart xmlns="http://schemas.microsoft.com/WebPart/v3"
metaData
type name="Eversheds.InstantMessaging.WebParts.WPChat, Eversheds.InstantMessaging, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=b0c7276684f0a390 "/type
importErrorMessage>Can not import WPChat/importErrorMessage
/metaData
data
properties
property name="Title" type="string"WPChat/property
property name="Description" type="string"A web part which allows the user to chat/property
/properties
/data
/webPart
/webParts
Step 4: Lastly create the .cs file for your web part
namespace Eversheds.InstantMessaging.WebParts
{
public class WPChat : System.Web.UI.WebControls.WebParts.WebPart
{}
}
Place all files in step1,2 and 3 in your feature folder. Deploy using wsp builder. The cs file should be outside the 12 hive folder.
Your web part will be available for the user in the gallery.
Wednesday, October 6, 2010
Commands to deploy WSP
Using Stsadm
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o retractsolution -name "Eversheds.Connect.wsp" -immediate -allcontenturls
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o execadmsvcjobs
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o deletesolution -name "Eversheds.Connect.wsp"
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o execadmsvcjobs
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o addsolution -filename "Eversheds.Connect.wsp"
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o execadmsvcjobs
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o deploysolution -name "Eversheds.Connect.wsp" -immediate -allcontenturls -allowGacDeployment -allowCasPolicies -force
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o execadmsvcjobs
Using WSP builder
wspbuilder.exe -WSPName Eversheds.Connect.wsp -BuildWSP false -deploy true
If there are features involved, add commands to activate feature also in this batch file.
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o retractsolution -name "Eversheds.Connect.wsp" -immediate -allcontenturls
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o execadmsvcjobs
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o deletesolution -name "Eversheds.Connect.wsp"
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o execadmsvcjobs
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o addsolution -filename "Eversheds.Connect.wsp"
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o execadmsvcjobs
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o deploysolution -name "Eversheds.Connect.wsp" -immediate -allcontenturls -allowGacDeployment -allowCasPolicies -force
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe" -o execadmsvcjobs
Using WSP builder
wspbuilder.exe -WSPName Eversheds.Connect.wsp -BuildWSP false -deploy true
If there are features involved, add commands to activate feature also in this batch file.
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.
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.
Subscribe to:
Posts (Atom)