dfdr 发表于 2015-9-27 09:02:23

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

  每次修改配置sharepoint站点的web.config参数很是繁琐,如果有多个web前段,比如:有3台web端部署做了NLB,每次部署安装的需要部署3台前段。不但麻烦,而且一旦一台少部署了些参数就会出现访问错误。最近想用代码实现自动部署修改,查询了MSDN,原来有SPWebApplication对象。
  采用自己的XML文件进行解析,并用在Feature上添加事件接收器。如下图:

  1、自定义的XML定义如下:
<?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?>
<configuration>
<system.web>
    <!-- 应用程序集 -->
    <compilation>
      <assemblies>
      <add assembly=&quot;TCL.EP.WebServices, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3eacd9f89e4e2d7c&quot; />
      <add assembly=&quot;TCL.EP.GPortal.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bb2d8d9d97c5e2f1&quot; />
      <add assembly=&quot;TCL.EP.SPCommon, Version=1.0.0.0, Culture=neutral, PublicKeyToken=99579db435012b8e&quot; />
      <add assembly=&quot;AspNetPager, Version=7.4.3.0, Culture=neutral, PublicKeyToken=fb0a0fe055d40fd4&quot; />
      </assemblies>
    </compilation>
    <!-- 应用程序集 -->
</system.web>
<appSettings>
    <add key=&quot;DocsiteUrl&quot; value=&quot;http://moss:8002&quot; />
    <add key=&quot;DocwebUrl&quot; value=&quot;&quot; />
</appSettings>
<!-- 数据库连接字符串-->
<connectionStrings>
    <add name=&quot;strConn&quot; connectionString=&quot;Data Source=.;Initial Catalog=test;Integrated Security=false;User Id=sa;Password=Passw0rd!&quot; providerName=&quot;System.Data.SqlClient&quot; />
</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>
   
    public class Feature_WebConfigEventReceiver : SPFeatureReceiver
    {
      private const string SPWebConfigModificationOwner = &quot;OwnerName&quot;;
      #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(&quot;TCL.EP.WebConfig.xml&quot;);
            #region//如果不为空
            if (doc != null)
            {
                //**********************************************************
                #region//解析:应用程序集assembly
                XmlNodeList assemblyNodesList = doc.SelectNodes(&quot;/configuration/system.web/compilation/assemblies/add&quot;);
                //循环
                //
                if (assemblyNodesList.Count > 0)
                {
                  foreach (XmlNode assemblyNode in assemblyNodesList)
                  {
                        //name
                        name = string.Format(&quot;add[@assembly='{0}']&quot;, assemblyNode.Attributes[&quot;assembly&quot;]== null ? string.Empty :
                            assemblyNode.Attributes[&quot;assembly&quot;].Value);
                        //xpath
                        xpath = &quot;configuration/system.web/compilation/assemblies&quot;;
                        //value
                        value = string.Format(&quot;<add assembly='{0}'/>&quot;, assemblyNode.Attributes[&quot;assembly&quot;] == null ? string.Empty :
                            assemblyNode.Attributes[&quot;assembly&quot;].Value);
                        //modify
                        ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
                  }
                }
                #endregion
                #region//解析:appSettings
                XmlNodeList appSettingNodesList = doc.SelectNodes(&quot;/configuration/appSettings/add&quot;);
                //foreach
                if (appSettingNodesList.Count > 0)
                {
                  foreach (XmlNode appSettingNode in appSettingNodesList)
                  {
                        //name
                        name = string.Format(&quot;add[@key='{0}']&quot;, appSettingNode.Attributes[&quot;key&quot;] == null ? string.Empty :
                            appSettingNode.Attributes[&quot;key&quot;].Value);
                        //xpath
                        xpath = &quot;configuration/appSettings&quot;;
                        //value
                        value = string.Format(&quot;<add key='{0}' value='{1}' />&quot;, appSettingNode.Attributes[&quot;key&quot;] == null ? string.Empty :
                            appSettingNode.Attributes[&quot;key&quot;].Value, appSettingNode.Attributes[&quot;value&quot;] == null ? string.Empty :
                            appSettingNode.Attributes[&quot;value&quot;].Value);
                        //
                        ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
                  }
                }
                #endregion
                #region//解析:connectionStrings
                XmlNodeList connNodesList = doc.SelectNodes(&quot;/configuration/connectionStrings/add&quot;);
                //循环
                if (connNodesList.Count > 0)
                {
                  foreach (XmlNode connNode in connNodesList)
                  {
                        //name
                        name = string.Format(&quot;add[@name='{0}']&quot;, connNode.Attributes[&quot;name&quot;] == null ? string.Empty :
                            connNode.Attributes[&quot;name&quot;].Value);
                        //xpath
                        xpath = &quot;configuration/connectionStrings&quot;;
                        //value
                        value = string.Format(&quot;<add name='{0}' connectionString='{1}' providerName='System.Data.SqlClient' />&quot;, connNode.Attributes[&quot;name&quot;] == null ? string.Empty :
                            connNode.Attributes[&quot;name&quot;].Value, connNode.Attributes[&quot;connectionString&quot;] == null ? string.Empty :
                            connNode.Attributes[&quot;connectionString&quot;].Value);
                        //modify
                        ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
                  }
                }
                #endregion
            }
            #endregion
            //   //此处的@后面的值必须与value里的标识对应,不然RemoveAllModifications无法移除
            ////发现name与value要对应,不然不会移除,如key对应key ,name对应name
            //name = &quot;add[@assembly='AspNetPager, Version=7.4.3.0, Culture=neutral, PublicKeyToken=fb0a0fe055d40fd4']&quot;;
            //xpath = &quot;configuration/system.web/compilation/assemblies&quot;;
            //value = &quot;<add assembly='AspNetPager, Version=7.4.3.0, Culture=neutral, PublicKeyToken=fb0a0fe055d40fd4' />&quot;;
            //ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
            //name = &quot;add[@key='TrustedGroup']&quot;;
            //xpath = &quot;configuration/appSettings&quot;;
            //value = &quot;<add key='TrustedGroup' value='Trusted' />&quot;;
            //ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
            //name = &quot;add[@key='KeyName']&quot;;
            //xpath = &quot;configuration/appSettings&quot;;
            //value = &quot;<add key='KeyName' value='Value' />&quot;;
            //ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
            ////增加数据库连接
            //name = &quot;add[@key='KeyName']&quot;;
            //xpath = &quot;configuration/appSettings&quot;;
            //value = &quot;<add key='KeyName' value='Value' />&quot;;
            //ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);

         
            
            ////数据库连接字符串
            //name = &quot;add[@name='strConn']&quot;;
            //xpath = &quot;configuration/connectionStrings&quot;;
            //value = &quot;<add name='strConn' connectionString='Data Source=.;Initial Catalog=test;Integrated Security=false;User Id=sa;Password=Passw0rd!' providerName='System.Data.SqlClient' />&quot;;
            //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=&quot;properties&quot;>属性</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=&quot;webApp&quot;>web app</param>
      /// <param name=&quot;nameModif&quot;>要修改的名字</param>
      /// <param name=&quot;pathModif&quot;>路径</param>
      /// <param name=&quot;valueModif&quot;>值</param>
      /// <param name=&quot;typeModif&quot;>参数类型</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
    }
}
页: [1]
查看完整版本: 采用解决方案包自动修改sharepoint站点的web.config参数