Ads

Sunday, 14 July 2013

Change master page as per logged in user group

we will discuss how you can change the master page for your site according to some logic like you can change the master page for a logged in user or simply can switch the application.master page to your custom master page for all applictaion pages.
I achive written a Step-by-step sample code to switch mater page according to logged in user's group.

The Steps to Create a Custom httpModule for Changing master page for a logged in user are :
1. Create a new Class Library project in Visual Studio name it as CustomhttpModule
2. Add the below code in your class file.
using System;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
namespace SwitchMasterPage{
public class CustomHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
{
// register handler for PreInit event
page.PreInit += new EventHandler(page_PreInit);
}
}
void page_PreInit(object sender, EventArgs e)
{
Page page = sender as Page;
if (page != null)
{
SPSite site = SPContext.Current.Site;
using (SPWeb web = site.OpenWeb())
{
if (web.CurrentUser != null)
{
SPGroupCollection userGroups = web.CurrentUser.Groups; // Check all the groups user belong to
foreach (SPGroup group in userGroups)
{
if (group.Name.Contains(“OurCustomgroupName”)
// Switch the master page.
page.MasterPageFile = “/_catalogs/masterpage/MyCustom.master”;
}}}
}}
public void Dispose() { /* empty implementation */ }
}
}
it’s important to remember that an HttpModule cannot be deployed in a WSS farm for an individual site collection. Instead, an HttpModule must be configured as an all-or-nothing proposition at the Web application level.
3. Now, sign the project and build it.
4. Drag and Drop the signed assembly in GAC.
5. Next, we need to register this CustomhttpModule in our SharePoint webconfig. To do this add the below under <httpModules> tag in your web app’s web.config fie.
<add name=”CustomHttpModule” type=”SwitchMasterPage.CustomHttpModule,  SwitchMasterPage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7ebdb1031dfc1e406?/>
And you are Done!

No comments:

Post a Comment

Ads