Friday, February 20, 2009

Changing master page using feature receiver

Scenario:
This is very common requierment and while doing my class, I was asked about changing the master page from Feature receiver.

Solution:
Assuming you have already uplaoded the newDefault.master to site collection Master Page Gallery, create a Scope=Web level feature receiver that will set the new master page.

Code:

 public override void FeatureActivated(SPFeatureReceiverProperties properties) {
SPWeb web = properties.Feature.Parent as SPWeb;
web.MasterUrl = web.MasterUrl.Substring(0, web.MasterUrl.LastIndexOf('/')+1) + "new.master";
web.CustomMasterUrl = web.CustomMasterUrl.Substring(0,web.CustomMasterUrl.LastIndexOf('/')+1) + "new.master";
web.Update();
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties){
SPWeb web = properties.Feature.Parent as SPWeb;
web.MasterUrl = web.MasterUrl.Substring(0, web.MasterUrl.LastIndexOf('/')+1) + "default.master";
web.CustomMasterUrl = web.CustomMasterUrl.Substring(0,web.CustomMasterUrl.LastIndexOf('/')+1) + "default.master";
web.Update();
}

0 comments: