控制台应用程序控制sharepoint web.config

1)App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="webUrl" value="http://dg-caozhenhua:85"/>
  </appSettings>
</configuration>

2)source.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration>
  <appSettings>
    <!-- 报表打印的地址 -->
    <add key="ReoprtUrl" value=" http://dzzw.ynstc.gov.cn:82/ReportPrint/"/>
    <!-- Silerlight下载地址 -->
    <add key="SlUrl" value=" http://dzzw.ynstc.gov.cn:82/SlDown/"/>
    <!--域(Domain),组织单元(Ou),邮箱(Exchange)-->
    <add key="OwaAddress" value="http://dzzw.ynstc.gov.cn:8080/owa/default.aspx"/>
    <add key="Domain" value="ynstc"/>
    <add key="ExpertOu" value="Experts"/>
    <add key="YnstcOu" value="YnstcOu"/>
    <add key="MailDomain" value="@ynst.net.cn"/>
    <add key="DomainAdmin" value="administrator"/>
    <add key="DomainAdminPsd" value="ynst12589kwjg@"/>
    <!-- 上传文件信息配置 fileType 允许上传文件格式 fileMax 单个上传文件大小(KB) fileCount 上传文件个数 fileTotalMax 上传文件总大小限制(KB) -->
    <add key="fileType" value="doc,docx,xls,xlsx"/>
    <add key="fileMax" value="2048"/>
    <add key="fileCount" value="10"/>
    <add key="fileTotalMax" value="20480"/>
    <!--设置可研报告模板-->
    <add key ="projectTemp" value="http://dzzw.ynstc.gov.cn/plat/Documents/自荐报告模板.doc"/>
    <!--设置立项任务书模板-->
    <add key ="PmTemp" value="http://dzzw.ynstc.gov.cn/Documents1/云南省科技计划项目任务书.doc"/>
  </appSettings>
  <!--connectionStrings-->
  <connectionStrings>
    <add name="YnstcAuthMembershipDB" connectionString="SERVER=localhost;DATABASE=YnstcAuthDB; TRUSTED_CONNECTION=true;" />
  </connectionStrings>
  <system.web>
    <!--memberShip-->
    <membership defaultProvider="YnstcAuthMembershipProvider">
      <providers>
        <add name="YnstcAuthMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="YnstcAuthMembershipDB" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="2" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
      </providers>
    </membership>
    <!--roleManager-->
    <roleManager enabled="true" defaultProvider="YnstcAuthRoleProvider">
      <providers>
        <add name="YnstcAuthRoleProvider" connectionStringName="YnstcAuthMembershipDB" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </roleManager>
    <httpModules>
      <!--配置启用会话-->
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      <!--部署 Ajax uploader-->
      <add name="CuteWebUI.UploadModule" type="CuteWebUI.UploadModule,CuteWebUI.AjaxUploader, Version=3.0.0.0, Culture=neutral, PublicKeyToken=bc00d4b0e43ec38d"/>
    </httpModules>
    <pages enableSessionState="true" enableViewState="true" enableViewStateMac="true" validateRequest="false" pageParserFilterType="Microsoft.SharePoint.ApplicationRuntime.SPPageParserFilter, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" asyncTimeout="7"></pages>
  </system.web>
  <SharePoint>
    <SafeMode>
      <!--配置允许页面代码-->
      <PageParserPaths>
        <PageParserPath VirtualPath="/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="True" />
      </PageParserPaths>
    </SafeMode>
    <SafeControls>
      <!--部署 用户控件-->
      <SafeControl Src="~/UserControls/*" IncludeSubFolders="True" Safe="True" AllowRemoteDesigner="True" />
      <!--部署 Ajax-->
      <SafeControl Assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Namespace="System.Web.UI" TypeName="*" Safe="True" AllowRemoteDesigner="True" />
      <!--部署 Ajax uploader-->
      <SafeControl Assembly="CuteWebUI.AjaxUploader, Version=3.0.0.0, Culture=neutral, PublicKeyToken=bc00d4b0e43ec38d" Namespace="CuteWebUI" TypeName="*" />
      <SafeControl Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TypeName="*" />
    </SafeControls>
  </SharePoint>
</configuration>
3)后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Configuration;
using System.IO;

namespace XmlDeliver
{
    class Program
    {
        private static string sourceUrl = "source.xml";//源xml
        private static string webUrl = ConfigurationManager.AppSettings["webUrl"];//获取网站地址
        private static string targetParentUrl = @"C:/Inetpub/wwwroot/wss/VirtualDirectories/" + webUrl.Split(':')[2]+@"/";//目标文件所在的文件夹
        private static string targetFileName=@"web.config";//目标文件名
        private static string targetUrl = targetParentUrl +targetFileName ;//目标xml
        //private static string targetParentUrl = "";
        //private static string targetUrl = "target.xml";//目标xml
        static void Main(string[] args)
        {
            XmlDocument xmlSource = GetSourceXml();
            XmlDocument xmltarget = GetTargetXml();
            //备份目标文件
            Console.WriteLine("开始备份文件......");
            Backup(xmltarget);
            Console.WriteLine("备份文件成功!");

            //设置appSettings
            Console.WriteLine("设置appSettings......");
            AddNodeDistinguishByKey(xmlSource, xmltarget, @"/configuration/appSettings");

            //设置connectionStrings
            Console.WriteLine("设置connectionStrings......");
            AddNodeDistinguishByPath(xmlSource, xmltarget, @"/configuration", "connectionStrings");
            AddNodeDistinguishByKey(xmlSource, xmltarget, @"/configuration/connectionStrings");

            //设置memberShip
            Console.WriteLine("设置memberShip......");
            AddNodeDistinguishByPath(xmlSource, xmltarget, @"/configuration/system.web", "membership");
            AddNodeDistinguishByPath(xmlSource, xmltarget, @"/configuration/system.web/membership", "providers");
            AddNodeDistinguishByKey(xmlSource, xmltarget, @"/configuration/system.web/membership/providers");

            //设置roleManager
            Console.WriteLine("设置roleManager......");
            AddNodeDistinguishByPath(xmlSource, xmltarget, @"/configuration/system.web", "roleManager");
            AddNodeDistinguishByPath(xmlSource, xmltarget, @"/configuration/system.web/roleManager", "providers");
            AddNodeDistinguishByKey(xmlSource, xmltarget, @"/configuration/system.web/roleManager/providers");

            //配置httpModules
            Console.WriteLine("配置httpModules......");
            AddNodeDistinguishByKey(xmlSource, xmltarget, @"/configuration/system.web/httpModules");

            //配置pages
            Console.WriteLine("配置pages......");
            EditNode(xmlSource, xmltarget, @"/configuration/system.web/pages");

            //配置PageParserPaths
            Console.WriteLine("配置PageParserPaths......");
            AddNodeDistinguishByOuterXml(xmlSource, xmltarget, @"/configuration/SharePoint/SafeMode/PageParserPaths", "PageParserPath");

            //配置safeControl
            Console.WriteLine("配置safeControl......");
            AddNodeDistinguishByOuterXml(xmlSource, xmltarget, @"/configuration/SharePoint/SafeControls", "SafeControl");

            xmltarget.Save(targetUrl);
            Console.ReadLine();
        }
        /// <summary>
        /// 备份目标文件
        /// </summary>
        private static void Backup(XmlDocument xmltarget)
        {
            string filePath = targetParentUrl+GetFileName();//获取备份文件路径
            // 如果备份文件存在就删除
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            // 创建备份文件
            using (FileStream fs = File.Create(filePath))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes(xmltarget.InnerXml);
                //将信息添加到备份文件中
                fs.Write(info, 0, info.Length);
            }
        }
        /// <summary>
        /// 生成xml文件名
        /// </summary>
        /// <returns></returns>
        private static string GetFileName()
        {
            string fileName="";
            fileName += "domcool_";
            fileName += targetFileName.Split('.')[0];
            string time = "" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day;
            fileName += time;
            fileName += "." + targetFileName.Split('.')[1];
            return fileName;
        }
        /// <summary>
        /// 根据OuterXml区分添加节点
        /// </summary>
        /// <param name="xmlSource"></param>
        /// <param name="xmltarget"></param>
        /// <param name="xPath"></param>
        private static void AddNodeDistinguishByOuterXml(XmlDocument xmlSource, XmlDocument xmltarget, string xPath, string nodeName)
        {
            XmlElement sourceElement = (XmlElement)xmlSource.SelectSingleNode(xPath);//获取节点(源)
            XmlElement targetElement = (XmlElement)xmltarget.SelectSingleNode(xPath);//获取节点(目标)
            if (sourceElement != null)//节点不存在(源)
            {
                if (sourceElement.ChildNodes.Count != 0)//节点不存在子节点(源)
                {
                    foreach (XmlNode sourceNode in sourceElement.ChildNodes)//遍历节点(源)
                    {
                        if (sourceNode.NodeType == XmlNodeType.Element)//节点类型是元素(源)
                        {
                            bool flag = false;
                            foreach (XmlNode targetNode in targetElement.ChildNodes)//遍历节点(目标)
                            {
                                if (targetNode.NodeType == XmlNodeType.Element)//节点类型是元素(目标)
                                {
                                    if (targetNode.OuterXml == sourceNode.OuterXml)//存在节点(目标)
                                    {
                                        flag = true;
                                        break;
                                    }
                                }
                            }
                            if (flag == false)//不存在节点(目标)
                            {
                                XmlElement element = xmltarget.CreateElement(nodeName);//新建元素节点
                                if (((XmlElement)sourceNode).HasAttributes)//节点存在属性(源)
                                {
                                    foreach (XmlAttribute attribute in ((XmlElement)sourceNode).Attributes)//遍历节点属性(源)
                                    {
                                        element.SetAttribute(attribute.Name, attribute.Value);//添加属性(新建节点)
                                    }
                                }
                                targetElement.AppendChild(element);//添加节点(目标)
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("源xml在路径" + xPath + "下不存在子节点");
                }
            }
            else
            {
                Console.WriteLine("源xml不存在路径:" + xPath);
            }
        }
        /// <summary>
        /// 修改节点
        /// </summary>
        /// <param name="xmlSource"></param>
        /// <param name="xmltarget"></param>
        /// <param name="xPath"></param>
        private static void EditNode(XmlDocument xmlSource, XmlDocument xmltarget, string xPath)
        {
            XmlElement sourceElement = (XmlElement)xmlSource.SelectSingleNode(xPath);//获取节点(源)
            XmlElement targetElement = (XmlElement)xmltarget.SelectSingleNode(xPath);//获取节点(目标)
            if (sourceElement != null)//节点存在(源)
            {
                if (targetElement.HasAttributes)//节点存在属性(目标)
                {
                    targetElement.Attributes.RemoveAll();//去掉节点的属性(目标)
                    foreach (XmlAttribute attribute in sourceElement.Attributes)//遍历节点(源)
                    {
                        targetElement.SetAttribute(attribute.Name, attribute.Value);
                    }
                }
            }
            else
            {
                Console.WriteLine("源xml不存在路径:" + xPath);
            }
        }
       /// <summary>
        /// 根据路径区分添加节点
       /// </summary>
       /// <param name="xmlSource"></param>
       /// <param name="xmltarget"></param>
       /// <param name="xPath"></param>
       /// <param name="nodeName"></param>
        private static void AddNodeDistinguishByPath(XmlDocument xmlSource, XmlDocument xmltarget, string xPath, string nodeName)
        {
            XmlElement targetElement = (XmlElement)xmltarget.SelectSingleNode(xPath);//获取节点(目标)
            XmlNode node=xmltarget.SelectSingleNode(xPath + "/" + nodeName);//获取子节点(目标)
            if (node == null)//节点不存在(目标)
            {
                XmlElement element = xmltarget.CreateElement(nodeName);
                targetElement.AppendChild(element);
            }
        }
        /// <summary>
        /// 根据主键区分添加节点
        /// </summary>
        /// <param name="xmlSource"></param>
        /// <param name="xmltarget"></param>
        /// <param name="xPath"></param>
        private static void AddNodeDistinguishByKey(XmlDocument xmlSource, XmlDocument xmltarget, string xPath)
        {
            XmlElement sourceElement = (XmlElement)xmlSource.SelectSingleNode(xPath);//获取节点(源)
            XmlElement targetElement = (XmlElement)xmltarget.SelectSingleNode(xPath);//获取节点(目标)
            if (sourceElement != null)//节点存在(源)
            {
                if (sourceElement.ChildNodes.Count != 0)//节点存在子节点(源)
                {
                    XmlNodeList childNodes = sourceElement.ChildNodes;//获取子节点(源)
                    foreach (XmlNode childNode in childNodes)//遍历子节点(源)
                    {
                        if (childNode.NodeType == XmlNodeType.Element)//节点的类型是元素(源)
                        {
                            XmlElement childElement = (XmlElement)childNode;
                            XmlElement element = xmltarget.CreateElement(childNode.Name);//新建元素节点
                            if (childElement.HasAttributes)//节点存在属性(源)
                            {
                                foreach (XmlAttribute attribute in childElement.Attributes)//遍历节点属性(源)
                                {
                                    element.SetAttribute(attribute.Name, attribute.Value);//添加属性(目标)
                                }
                            }
                            XmlNode oldChild = GetOldChildByKey(targetElement, element);//根据主键判断是否存在子节点(目标)
                            if (oldChild == null)//不存在节点(目标)
                            {
                                targetElement.AppendChild(element);//添加节点(目标)
                            }
                            else//存在节点(目标)
                            {
                                targetElement.ReplaceChild(element, oldChild);//替换节点(目标)
                            }
                        }
                    }
                    Console.WriteLine("设置成功!");
                }
                else
                {
                    Console.WriteLine("源xml在路径" + xPath + "下不存在子节点");
                }
            }
            else
            {
                Console.WriteLine("源xml不存在路径:" + xPath);
            }
        }
        /// <summary>
        /// 根据主键判断是否存在元素子节点(目标)
        /// 存在返回节点
        /// 不存在返回null
        /// </summary>
        /// <param name="targetElement"></param>
        /// <param name="element"></param>
        /// <returns></returns>
        private static XmlNode GetOldChildByKey(XmlElement targetElement, XmlElement element)
        {
            XmlNode oldChild = null;
            string value = element.Attributes[0].Value;//获取键值(新建)
            foreach (XmlNode childNode in targetElement.ChildNodes)
            {
                string childValue="";
                try
                {
                    childValue = childNode.Attributes[0].Value;//获取键值(目标)
                }
                catch (Exception e)
                { }
                if (childValue == value)//节点存在
                {
                    oldChild = childNode;
                    break;
                }
            }
            return oldChild;
        }
        /// <summary>
        /// 获取源xml
        /// </summary>
        /// <returns></returns>
        private static XmlDocument GetSourceXml()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(sourceUrl);
            return xmlDoc;
        }
        /// <summary>
        /// 获取目标xml
        /// </summary>
        /// <returns></returns>
        private static XmlDocument GetTargetXml()
        {
            XmlDocument xmlDoc=new XmlDocument();
            xmlDoc.Load(targetUrl);
            return xmlDoc;
        }
       
    } 
}

你可能感兴趣的:(控制台应用程序控制sharepoint web.config)