采用解决方案包自动修改sharepoint站点的web.config参数

每次修改配置sharepoint站点的web.config参数很是繁琐,如果有多个web前段,比如:有3台web端部署做了NLB,每次部署安装的需要部署3台前段。不但麻烦,而且一旦一台少部署了些参数就会出现访问错误。最近想用代码实现自动部署修改,查询了MSDN,原来有SPWebApplication对象。

采用自己的XML文件进行解析,并用在Feature上添加事件接收器。如下图:

image

1、自定义的XML定义如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <!-- 应用程序集 -->
    <compilation>
      <assemblies>
        <add assembly="TCL.EP.WebServices, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3eacd9f89e4e2d7c" />
        <add assembly="TCL.EP.GPortal.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bb2d8d9d97c5e2f1" />
        <add assembly="TCL.EP.SPCommon, Version=1.0.0.0, Culture=neutral, PublicKeyToken=99579db435012b8e" />
        <add assembly="AspNetPager, Version=7.4.3.0, Culture=neutral, PublicKeyToken=fb0a0fe055d40fd4" />
      </assemblies>
    </compilation>
    <!-- 应用程序集 -->
  </system.web>
  <appSettings>
    <add key="DocsiteUrl" value="http://moss:8002" />
    <add key="DocwebUrl" value="" />
  </appSettings>
  <!-- 数据库连接字符串-->
  <connectionStrings>
    <add name="strConn" connectionString="Data Source=.;Initial Catalog=test;Integrated Security=false;User Id=sa;Password=Passw0rd!" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <!-- 数据库连接字符串-->
</configuration>

 

2、事件接收器代码如下:

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;
using System.Xml;
//***************************************************************************************
//编制人:忘忧草
//编制时间:2013-5-24
//编制作用:修改web.config的Feature
//编制单位:XXX
//***************************************************************************************
namespace TCL.EP.WebConfigFeature.Features.Feature_WebConfig
{
    /// <summary>
    /// 此类用于处理在激活、停用、安装、卸载和升级功能的过程中引发的事件。
    /// </summary>
    /// <remarks>
    /// 附加到此类的 GUID 可能会在打包期间使用,不应进行修改。
    /// </remarks>
    [Guid("d754c8e3-81a6-4ea4-8706-43ba92d1ff20")]
    public class Feature_WebConfigEventReceiver : SPFeatureReceiver
    {
        private const string SPWebConfigModificationOwner = "OwnerName";
        #region//事件
        #region// 取消对以下方法的注释,以便处理激活某个功能后引发的事件。
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            string name, xpath, value;
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
            #region ..: appSettings :..
            //解析xml
            //*********************************************************
            //读取XML文件
            XmlDocument doc = new XmlDocument();
            //加载XML文件
            doc.Load("TCL.EP.WebConfig.xml");
            #region//如果不为空
            if (doc != null)
            {
                //**********************************************************
                #region//解析:应用程序集assembly
                XmlNodeList assemblyNodesList = doc.SelectNodes("/configuration/system.web/compilation/assemblies/add");
                //循环
                //
                if (assemblyNodesList.Count > 0)
                {
                    foreach (XmlNode assemblyNode in assemblyNodesList)
                    {
                        //name
                        name = string.Format("add[@assembly='{0}']", assemblyNode.Attributes["assembly"]== null ? string.Empty :
                            assemblyNode.Attributes["assembly"].Value);
                        //xpath
                        xpath = "configuration/system.web/compilation/assemblies";
                        //value
                        value = string.Format("<add assembly='{0}'/>", assemblyNode.Attributes["assembly"] == null ? string.Empty :
                            assemblyNode.Attributes["assembly"].Value);
                        //modify 
                        ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
                    }
                }
                #endregion
                #region//解析:appSettings
                XmlNodeList appSettingNodesList = doc.SelectNodes("/configuration/appSettings/add");
                //foreach
                if (appSettingNodesList.Count > 0)
                {
                    foreach (XmlNode appSettingNode in appSettingNodesList)
                    {
                        //name
                        name = string.Format("add[@key='{0}']", appSettingNode.Attributes["key"] == null ? string.Empty :
                            appSettingNode.Attributes["key"].Value);
                        //xpath
                        xpath = "configuration/appSettings";
                        //value
                        value = string.Format("<add key='{0}' value='{1}' />", appSettingNode.Attributes["key"] == null ? string.Empty :
                            appSettingNode.Attributes["key"].Value, appSettingNode.Attributes["value"] == null ? string.Empty :
                            appSettingNode.Attributes["value"].Value);
                        //
                        ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
                    }
                }
                #endregion
                #region//解析:connectionStrings
                XmlNodeList connNodesList = doc.SelectNodes("/configuration/connectionStrings/add");
                //循环
                if (connNodesList.Count > 0)
                {
                    foreach (XmlNode connNode in connNodesList)
                    {
                        //name
                        name = string.Format("add[@name='{0}']", connNode.Attributes["name"] == null ? string.Empty :
                            connNode.Attributes["name"].Value);
                        //xpath
                        xpath = "configuration/connectionStrings";
                        //value
                        value = string.Format("<add name='{0}' connectionString='{1}' providerName='System.Data.SqlClient' />", connNode.Attributes["name"] == null ? string.Empty :
                            connNode.Attributes["name"].Value, connNode.Attributes["connectionString"] == null ? string.Empty :
                            connNode.Attributes["connectionString"].Value);
                        //modify 
                        ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
                    }
                }
                #endregion
            }
            #endregion
            //   //此处的@后面的值必须与value里的标识对应,不然RemoveAllModifications无法移除
            ////发现name与value要对应,不然不会移除,如key对应key ,name对应name
            //name = "add[@assembly='AspNetPager, Version=7.4.3.0, Culture=neutral, PublicKeyToken=fb0a0fe055d40fd4']";
            //xpath = "configuration/system.web/compilation/assemblies";
            //value = "<add assembly='AspNetPager, Version=7.4.3.0, Culture=neutral, PublicKeyToken=fb0a0fe055d40fd4' />";
            //ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
            //name = "add[@key='TrustedGroup']";
            //xpath = "configuration/appSettings";
            //value = "<add key='TrustedGroup' value='Trusted' />";
            //ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
            //name = "add[@key='KeyName']";
            //xpath = "configuration/appSettings";
            //value = "<add key='KeyName' value='Value' />";
            //ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
            ////增加数据库连接
            //name = "add[@key='KeyName']";
            //xpath = "configuration/appSettings";
            //value = "<add key='KeyName' value='Value' />";
            //ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
 
         
            
            ////数据库连接字符串
            //name = "add[@name='strConn']";
            //xpath = "configuration/connectionStrings";
            //value = "<add name='strConn' connectionString='Data Source=.;Initial Catalog=test;Integrated Security=false;User Id=sa;Password=Passw0rd!' providerName='System.Data.SqlClient' />";
            //ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
            #endregion
            try
            {
                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
            catch (Exception ex)
            {
                RemoveAllModifications(properties);
                throw ex;
            }
        }
        #endregion
        #region// 取消对以下方法的注释,以便处理在停用某个功能前引发的事件。
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            RemoveAllModifications(properties);
            try
            {
                SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
                eventLog.Source = SPWebConfigModificationOwner;
                eventLog.WriteEntry(ex.Message);
                throw ex;
            }
        }
        #endregion
        // 取消对以下方法的注释,以便处理在安装某个功能后引发的事件。
        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}
        // 取消对以下方法的注释,以便处理在卸载某个功能前引发的事件。
        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}
        // 取消对以下方法的注释,以便处理在升级某个功能时引发的事件。
        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
        #endregion
        #region//方法
        #region//移走web.config
        /// <summary>
        /// 移走web.config
        /// </summary>
        /// <param name="properties">属性</param>
        private void RemoveAllModifications(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
            List<SPWebConfigModification> modificationsToRemove = new List<SPWebConfigModification>();
            foreach (SPWebConfigModification modification in webApp.WebConfigModifications)
                if (modification.Owner == SPWebConfigModificationOwner)
                    modificationsToRemove.Add(modification);
            foreach (SPWebConfigModification modification in modificationsToRemove)
                webApp.WebConfigModifications.Remove(modification);
            webApp.Update();
        }
        #endregion
        #region//修改web.config
        /// <summary>
        /// 修改web.config
        /// </summary>
        /// <param name="webApp">web app</param>
        /// <param name="nameModif">要修改的名字</param>
        /// <param name="pathModif">路径</param>
        /// <param name="valueModif">值</param>
        /// <param name="typeModif">参数类型</param>
        private void ModifyWebConfig(SPWebApplication webApp, String nameModif, String pathModif, String valueModif, SPWebConfigModification.SPWebConfigModificationType typeModif)
        {
            SPWebConfigModification modification = new SPWebConfigModification(nameModif, pathModif);
            modification.Value = valueModif;
            modification.Sequence = 0;
            modification.Type = typeModif;
            modification.Owner = SPWebConfigModificationOwner;
            try
            {
                webApp.WebConfigModifications.Add(modification);
                webApp.Update();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
                eventLog.Source = SPWebConfigModificationOwner;
                eventLog.WriteEntry(ex.Message);
                throw ex;
            }
        }
        #endregion
        #endregion
    }
}
posted @ 2013-06-03 18:08  love007  阅读(584)  评论(1编辑  收藏  举报