代码改变世界

使用Visual Studio进行SharePoint母板页的部署

2012-01-31 22:26  雪中风筝  阅读(330)  评论(0编辑  收藏  举报
SharePoint开发人员怎么进行母板页的定制?或许你还在通过备份v4.master然后通过修改原有的母版页来达到自己的效果?那么如何将这个母版页应用到生产环境中去呢?
下面介绍一种通过Feature来控制使用不同的母板页的示例:
首先准备一个通过Feature来控制的母版页,这里我们使用Starter Master母版页,可以通过http://startermasterpages.codeplex.com/里获取到Starter Master。
建立一个空的Visual Studio的项目,添加一个Module,起名为CustomMasterPage,删除自带的sample.txt文件。然后将要使用的master文件复制到Module中,这个时候Element.xml
文件中会自动添加这个母板页的引用。这个时候我们需要修改Elements.xml
指定母版页的部署位置,如何部署母版页到库中,可以参考MSDN的这篇文章:http://msdn.microsoft.com/en-us/library/ms441170(office.14).aspx
我的Elements.xml文件修改完成以后如下:
 
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="CustemMasterPage" List="116" Url="_catalogs/masterpage">
<File Path="CustemMasterPage\_starter_publishing.master" Url="_starter_publishing.master" Type="GhostableInLibrary" IgnoreIfAlreadyExists="FALSE" />
</Module>
</Elements>

母板页的模块现在完成了。这个时候我们打算通过一个事件接收器来自动完成母板页的切换,右键点击Feature选择添加事件接收器,这个时候会自动生成事件cs文件,这个文件中的方法都是注释掉的,

我们取消FeatureActivated这个事件和FeatureDeactivating这个事件的注释

第一个事件是在激活某个弄能后激发的事件,第二个事件是在取消激活的功能之前发生的事件。

我们要在这两个事件中来完成母版页的切换。也就是要达到这样的效果,当激活Feature的时候,使用我们自定义的母版页,而取消Feature的激活以后,就使用默认的母版页。

 

这个时候我们在FeatureActivated这个事件中添加以下代码:

 

1        SPWeb currentWeb = (SPWeb)properties.Feature.Parent;
2
3
4 Uri masterUri = new Uri(currentWeb.Url+"/_catalogs/masterpage/_starter_publishing.master");
5
6 currentWeb.MasterUrl = masterUri.AbsolutePath;
7 currentWeb.CustomMasterUrl = masterUri.AbsolutePath;
8 currentWeb.Update();

 

在FeatureDeactivating事件中添加以下代码:
 
1        SPWeb currentWeb = (SPWeb)properties.Feature.Parent;
2
3 Uri masterUri = new Uri(currentWeb.Url + "/_catalogs/masterpage/v4.master");
4 currentWeb.MasterUrl = masterUri.AbsolutePath;
5 currentWeb.CustomMasterUrl = masterUri.AbsolutePath;
6 currentWeb.Update();
这个时候大功就告成了,我们部署激活这个Feature,这个时候我们的主页就可以看到自定义的母版页,如果取消Feature,就使用默认的v4.master.