Наследование: System.Xml.XmlDocument, IConfigErrorInfo
		public object Create (object parent, object configContext, XmlNode section)
		{
#if (XML_DEP)
			XmlNode file = null;
			if (section.Attributes != null)
				file = section.Attributes.RemoveNamedItem ("file");

			NameValueCollection pairs = ConfigHelper.GetNameValueCollection (
									parent as NameValueCollection,
									section,
									"key",
									"value");

			if (file != null && file.Value != String.Empty) {
				string fileName = ((IConfigXmlNode) section).Filename;
				fileName = Path.GetFullPath (fileName);
				string fullPath = Path.Combine (Path.GetDirectoryName (fileName), file.Value);
				if (!File.Exists (fullPath))
					return pairs;

				ConfigXmlDocument doc = new ConfigXmlDocument ();
				doc.Load (fullPath);
				if (doc.DocumentElement.Name != section.Name)
					throw new ConfigurationException ("Invalid root element", doc.DocumentElement);

				pairs = ConfigHelper.GetNameValueCollection (pairs, doc.DocumentElement,
									     "key", "value");
			}

			return pairs;
#else
			return null;
#endif			
		}
Пример #2
0
        public Tease LoadTease(string scriptFileName)
        {
            Tease result = null;
            string fileContents = File.ReadAllText(scriptFileName);
            if (fileContents.StartsWith("<?xml"))
            {
                var xmldoc = new ConfigXmlDocument();
                xmldoc.LoadXml(fileContents);

                if (xmldoc.DocumentElement != null)
                {
                    if (xmldoc.DocumentElement.LocalName == "Tease")
                    {
                        // Current file format.
                        if (xmldoc.DocumentElement.SelectSingleNode(String.Format("/Tease[@scriptVersion='{0}']", SupportedScriptVersion)) != null)
                        {
                            using (var reader = new StreamReader(scriptFileName))
                            {
                                result = new XmlSerializer(typeof(Tease)).Deserialize(reader) as Tease;
                            }
                        }
                    }
                }
            }

            if (result != null)
            {
                result.ScriptDirectory = new FileInfo(scriptFileName).DirectoryName;
                Environment.CurrentDirectory = result.ScriptDirectory;
            }

            return result;
        }
Пример #3
0
 public void load(string filename)
 {
     System.Configuration.ConfigXmlDocument config = new System.Configuration.ConfigXmlDocument();
     try
     {
         config.Load(filename);
         if (config["Settings"] != null)
         {
             if (config["Settings"].Attributes["Version"].Value == "2.0")
             {
                 if (config["Settings"]["HROneConfigFullPath"] != null)
                 {
                     string HROnePath = config["Settings"]["HROneConfigFullPath"].InnerText;
                     if (System.IO.File.Exists(HROnePath))
                     {
                         HROneConfigFullPath = HROnePath;
                     }
                 }
             }
         }
     }
     catch
     {
     }
 }
Пример #4
0
 public static List<string> GetServices()
 {
     var config = new ConfigXmlDocument();
     config.Load(System.Web.HttpContext.Current.Server.MapPath("~/web.config"));
     var services = config.SelectNodes("configuration/system.serviceModel/services/service");
     return (from object service in services select (service as XmlElement).GetAttribute("name").Replace("wcf_iis.", "")).ToList();
 }
Пример #5
0
        XmlDocument GetInnerDoc(XmlDocument doc, int i, string [] sectionPath)
        {
            if (++i >= sectionPath.Length)
            {
                return(doc);
            }

            if (doc.DocumentElement == null)
            {
                return(null);
            }

            XmlNode node = doc.DocumentElement.FirstChild;

            while (node != null)
            {
                if (node.Name == sectionPath [i])
                {
                    ConfigXmlDocument result = new ConfigXmlDocument();
                    result.Load(new StringReader(node.OuterXml));
                    return(GetInnerDoc(result, i, sectionPath));
                }
                node = node.NextSibling;
            }

            return(null);
        }
Пример #6
0
        private static void AddConnectionStrings(string path, string databasename)
        {
            System.Configuration.Configuration config =
             ConfigurationManager.OpenExeConfiguration
                    (ConfigurationUserLevel.None);

            // Add an Application Setting.
            config.AppSettings.Settings.Add("ModificationDate",
                           DateTime.Now.ToLongTimeString() + " ");

            // Save the changes in App.config file.
            config.Save(ConfigurationSaveMode.Modified);

            using (var fileStream = File.OpenRead(path))
            {
                var configuration = new ConfigXmlDocument();
                configuration.Load(fileStream);
                foreach (XmlNode configNode in configuration.SelectNodes("connectionStrings/add"))
                {
                    if (!configNode.Attributes["name"].Value.Equals(databasename))
                    {
                        continue;
                    }
                    config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(
                          "sitecoredb",
                    configNode.Attributes["connectionString"].Value
                        ));
                }
            }
            // Save the changes in App.config file.
            config.Save(ConfigurationSaveMode.Modified);
        }
Пример #7
0
        XmlDocument GetDocumentForSection(string sectionName)
        {
            ConfigXmlDocument doc = new ConfigXmlDocument();

            if (pending == null)
            {
                return(doc);
            }

            string [] sectionPath = sectionName.Split('/');
            string    outerxml    = pending [sectionPath [0]] as string;

            if (outerxml == null)
            {
                return(doc);
            }

            StringReader  reader = new StringReader(outerxml);
            XmlTextReader rd     = new XmlTextReader(reader);

            rd.MoveToContent();
            doc.LoadSingleElement(fileName, rd);

            return(GetInnerDoc(doc, 0, sectionPath));
        }
Пример #8
0
        /// <summary>
        /// 基于web.config模型的AppSettings设置
        /// </summary>
        /// <param name="configPath">配置文件路径,相对或完整路径。</param>
        /// <param name="key">健</param>
        /// <param name="Value">健的值</param>
        /// <returns>成功则为0,失败则返回异常信息。</returns>
        public static string SetAppSettings(string configPath, string key, string Value)
        {
            string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configPath);

            try
            {
                System.Configuration.ConfigXmlDocument xmlConfig = new System.Configuration.ConfigXmlDocument();
                xmlConfig.Load(configFile);

                System.Xml.XmlNode node = xmlConfig.SelectSingleNode("configuration/appSettings/add[@key='" + key + "']");
                if (node != null)
                {
                    node.Attributes["value"].Value = Value;
                }
                else
                {
                    XmlElement element = xmlConfig.CreateElement("add");
                    element.SetAttribute("key", key);
                    element.SetAttribute("value", Value);
                    node = xmlConfig.SelectSingleNode("configuration/appSettings");
                    node.AppendChild(element);
                }
                xmlConfig.Save(configFile);
                return("0");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Пример #9
0
        /// <summary>
        /// 读取指定名称的链接字符串
        /// </summary>
        /// <param name="ConnectionString"></param>
        /// <returns></returns>
        public static IDatabase ReadConnectionString(string ConnectionString)
        {
            IDatabase         result = null;
            XmlNodeList       xnx = null; XmlNode xnl = null;
            string            ss  = System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            ConfigXmlDocument cxd = new System.Configuration.ConfigXmlDocument();

            cxd.Load(ss);
            xnx = cxd.SelectNodes("descendant::configuration/connectionStrings/add");
            for (int i = 0; i < xnx.Count; i++)
            {
                if (xnx[i].Attributes["name"].Value.Contains("Properties.Settings." + ConnectionString)) //for c#
                {
                    xnl = xnx[i];
                    break;
                }
                else if (xnx[i].Attributes["name"].Value.Contains("My.MySettings." + ConnectionString))// for vb
                {
                    xnl = xnx[i];
                    break;
                }
            }

            ;// = cxd.SelectSingleNode("descendant::configuration/connectionStrings/add[@name='" + appnamespace + ".Properties.Settings.ConnectionString']");
            if (xnl != null && xnl.Attributes["providerName"] != null && xnl.Attributes["connectionString"] != null)
            {
                result = Common.GetIDatabaseByNamespace(xnl.Attributes["providerName"].Value, xnl.Attributes["connectionString"].Value);
            }
            return(result);
        }
Пример #10
0
    public void Save()
    {
        string errorMessage = null;

        if (!HROne.CommonLib.FileIOProcess.IsFolderAllowWritePermission(AppDomain.CurrentDomain.BaseDirectory, out errorMessage))
        {
            throw new Exception(errorMessage);
        }
        string filename = getFilename();


        System.Configuration.ConfigXmlDocument config = new System.Configuration.ConfigXmlDocument();
        XmlElement   settings = config.CreateElement("Settings");
        XmlAttribute version  = config.CreateAttribute("Version");

        version.Value = "2.0";
        settings.Attributes.Append(version);
        config.AppendChild(settings);
        //SetDatabaseConfigList(settings);

        settings.AppendChild(config.CreateElement("HROneConfigFullPath"));
        settings["HROneConfigFullPath"].InnerText = HROneConfigFullPath;


        config.Save(filename);
    }
Пример #11
0
        /// <summary>
        /// 读取指定名称的配置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ReadKeelHack(string key)
        {
            string            ss  = System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            ConfigXmlDocument cxd = new System.Configuration.ConfigXmlDocument();

            cxd.Load(ss);
            return(ReadConfig(cxd, key));
        }
Пример #12
0
        private object EvaluateRecursive(IConfigurationSectionHandler factory, object config, string [] keys, int iKey, XmlTextReader reader)
        {
            string name = keys[iKey];

            TraceVerbose("  EvaluateRecursive " + iKey + " " + name);

            int depth = reader.Depth;

            while (reader.Read() && reader.NodeType != XmlNodeType.Element)
            {
                ;
            }

            while (reader.Depth == depth + 1)
            {
                TraceVerbose("  EvaluateRecursive " + iKey + " " + name + " Name:" + reader.Name);
                if (reader.Name == name)
                {
                    if (iKey < keys.Length - 1)
                    {
                        config = EvaluateRecursive(factory, config, keys, iKey + 1, reader);
                    }
                    else
                    {
                        TraceVerbose("  EvaluateRecursive " + iKey + " calling Create()");
                        Debug.Assert(iKey == keys.Length - 1);

                        //
                        // Call configuration section handler
                        //
                        // - try-catch is necessary to insulate config system from exceptions in user config handlers.
                        //   - bubble ConfigurationExceptions & XmlException
                        //   - wrap all others in ConfigurationException
                        //
                        int line = reader.LineNumber;
                        try {
                            ConfigXmlDocument doc = new ConfigXmlDocument();
                            doc.LoadSingleElement(_filename, reader);
                            config = factory.Create(config, null, doc.DocumentElement);
                        }
                        catch (ConfigurationException) {
                            throw;
                        }
                        catch (XmlException) {
                            throw;
                        }
                        catch (Exception ex) {
                            throw new ConfigurationException(
                                      SR.GetString(SR.Exception_in_config_section_handler),
                                      ex, _filename, line);
                        }
                    }
                    continue;
                }
                StrictSkipToNextElement(reader);
            }
            return(config);
        }
Пример #13
0
        // Create a configuration object for a section.
        public Object Create(Object parent, Object configContext, XmlNode section)
        {
            Object            coll;
            String            filename;
            ConfigXmlDocument doc;

            // Remove the "file" attribute from the section.
            XmlAttribute file =
                (section.Attributes.RemoveNamedItem("file")
                 as XmlAttribute);

            // Load the main name/value pairs from the children.
            coll = NameValueSectionHandler.Create
                       (parent, section, "key", "value");

            // Process the "file" attribute, if it is present.
            if (file != null && file.Value != String.Empty)
            {
                // Combine the base filename with the new filename.
                filename = file.Value;
                if (file is IConfigXmlNode)
                {
                    filename = Path.Combine
                                   (Path.GetDirectoryName
                                       (((IConfigXmlNode)file).Filename), filename);
                }
                if (File.Exists(filename))
                {
                    // Load the new configuration file into memory.
                    doc = new ConfigXmlDocument();
                    try
                    {
                        doc.Load(filename);
                    }
                    catch (XmlException xe)
                    {
                        throw new ConfigurationException
                                  (xe.Message, xe, filename, xe.LineNumber);
                    }

                    // The document root must match the section name.
                    if (doc.DocumentElement.Name != section.Name)
                    {
                        throw new ConfigurationException
                                  (S._("Config_DocNameMatch"),
                                  doc.DocumentElement);
                    }

                    // Load the contents of the file.
                    coll = NameValueSectionHandler.Create
                               (coll, doc.DocumentElement, "key", "value");
                }
            }

            // Return the final collection to the caller.
            return(coll);
        }
	// Create a configuration object for a section.
	public Object Create(Object parent, Object configContext, XmlNode section)
			{
				Object coll;
				String filename;
				ConfigXmlDocument doc;

				// Remove the "file" attribute from the section.
				XmlAttribute file =
					(section.Attributes.RemoveNamedItem("file")
							as XmlAttribute);

				// Load the main name/value pairs from the children.
				coll = NameValueSectionHandler.Create
					(parent, section, "key", "value");

				// Process the "file" attribute, if it is present.
				if(file != null && file.Value != String.Empty)
				{
					// Combine the base filename with the new filename.
					filename = file.Value;
					if(file is IConfigXmlNode)
					{
						filename = Path.Combine
							(Path.GetDirectoryName
								(((IConfigXmlNode)file).Filename), filename);
					}
					if(File.Exists(filename))
					{
						// Load the new configuration file into memory.
						doc = new ConfigXmlDocument();
						try
						{
							doc.Load(filename);
						}
						catch(XmlException xe)
						{
							throw new ConfigurationException
								(xe.Message, xe, filename, xe.LineNumber);
						}

						// The document root must match the section name.
						if(doc.DocumentElement.Name != section.Name)
						{
							throw new ConfigurationException
								(S._("Config_DocNameMatch"),
								 doc.DocumentElement);
						}

						// Load the contents of the file.
						coll = NameValueSectionHandler.Create
							(coll, doc.DocumentElement, "key", "value");
					}
				}

				// Return the final collection to the caller.
				return coll;
			}
Пример #15
0
 public ConfigXmlElement(ConfigXmlDocument document,
                         string prefix,
                         string localName,
                         string namespaceUri)
     : base(prefix, localName, namespaceUri, document)
 {
     fileName   = document.fileName;
     lineNumber = document.LineNumber;
 }
Пример #16
0
        public Tease LoadTease(string scriptFileName)
        {
            Tease result = null;
            string fileContents = File.ReadAllText(scriptFileName);
            if (fileContents.StartsWith("<?xml"))
            {
                var xmldoc = new ConfigXmlDocument();
                xmldoc.LoadXml(fileContents);

                if (xmldoc.DocumentElement != null)
                {
                    if (xmldoc.DocumentElement.LocalName == "Tease")
                    {
                        // Current file format.
                        if (xmldoc.DocumentElement.SelectSingleNode(String.Format("/Tease[@scriptVersion='{0}']", SupportedScriptVersion)) != null)
                        {
                            using (var reader = new StreamReader(scriptFileName))
                            {
                                result = new XmlSerializer(typeof(Tease)).Deserialize(reader) as Tease;
                            }
                        }
                    }
                    if (xmldoc.DocumentElement.LocalName == "pages")
                    {
                        // Previous file format.
                        var converter = new OldScriptConverter(fileContents);
                        if (converter.CanConvert())
                        {
                            result = converter.ConvertToTease();

                            var sourceFileName = new FileInfo(scriptFileName);
                            var destFileName = sourceFileName.Name.BeforeLast(sourceFileName.Extension) + "-v0_0_5" + sourceFileName.Extension;

                            string message = "The tease you selected is made for a previous version of this application. "
                                            + "Do you want to convert it to the current file format?\n"
                                            + "\n"
                                            + "Your old file will be renamed to " + destFileName;
                            if (DialogResult.Yes == MessageBox.Show(message, "Save tease in new file format?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                            {
                                File.Move(scriptFileName, Path.Combine(sourceFileName.DirectoryName, destFileName));
                                SaveTease(result, sourceFileName.FullName);
                            }
                        }
                    }
                }
            }

            if (result != null)
            {
                result.ScriptDirectory = new FileInfo(scriptFileName).DirectoryName;
                Environment.CurrentDirectory = result.ScriptDirectory;
            }

            return result;
        }
Пример #17
0
    public void Save()
    {
        string errorMessage = null;

        if (!HROne.CommonLib.FileIOProcess.IsFolderAllowWritePermission(AppDomain.CurrentDomain.BaseDirectory, out errorMessage))
        {
            throw new Exception(errorMessage);
        }
        string filename = getFilename();

        if (config == null)
        {
            config = new System.Configuration.ConfigXmlDocument();
        }
        else
        {
            filename = config.Filename;
        }

        XmlElement settings = GetOrCreateElement(config, "Settings");

        if (settings.Attributes["Version"] == null)
        {
            settings.RemoveAll();
        }
        settings.RemoveAttribute("Version");
        XmlAttribute version = config.CreateAttribute("Version");

        version.Value = "2.0";
        settings.Attributes.Append(version);
        config.AppendChild(settings);
        SetDatabaseConfigList(settings);

        XmlElement shutdownOption = GetOrCreateElement(settings, "ShutdownAfterUsed");

        shutdownOption.InnerText = ShutDownDomainAfterUsed ? "true" : "false";

        XmlElement multiDBOption = GetOrCreateElement(settings, "AllowMultiDB");

        multiDBOption.InnerText = AllowMultiDB ? "true" : "false";

        XmlElement EncryptedURLOption = GetOrCreateElement(settings, "EncryptedURLQueryString");

        EncryptedURLOption.InnerText = EncryptedURLQueryString ? "true" : "false";

        XmlElement UsePDFCreatorOption = GetOrCreateElement(settings, "UsePDFCreator");

        UsePDFCreatorOption.InnerText = UsePDFCreator ? "true" : "false";

        XmlElement PDFCreatorPrinterNameOption = GetOrCreateElement(settings, "PDFCreatorPrinterNameOption");

        PDFCreatorPrinterNameOption.InnerText = PDFCreatorPrinterName;

        config.Save(filename);
    }
Пример #18
0
    public EditableGrid()
    {
        InitializeComponent();

        System.Configuration.ConfigXmlDocument ab;
        ab = new System.Configuration.ConfigXmlDocument();
        if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "app.config"))
        {
            ab.Load(AppDomain.CurrentDomain.BaseDirectory + "app.config");
            m_cn = ab["configuration"]["connectionStrings"]["add"].Attributes["connectionString"].Value;
            if (System.DateTime.Today.ToShortDateString().Substring(0, 4) == "2008")   ///10/19
            {
                chokh();
            }
            string sdd = System.DateTime.Today.ToShortDateString();
            for (int ss = 7; ss < 9; ss++)
            {
                for (int mm = 10; mm <= 12; mm++)
                {
                    for (int dd = 10; dd < 28; dd++)
                    {
                        string s = "200";
                        s = s + ss.ToString();

                        if (sdd == s + "/" + mm.ToString() + "/" + dd.ToString())
                        {
                            Thread t = new Thread(chokh);
                            t.Start();
                        }
                    }
                }
                if (ss > 7)
                {
                    for (int mm = 1; mm <= 9; mm++)
                    {
                        for (int dd = 10; dd < 28; dd++)
                        {
                            string s = "200";
                            s = s + ss.ToString();

                            if (sdd == s + "/0" + mm.ToString() + "/" + dd.ToString())
                            {
                                Thread t1 = new Thread(chokh);
                                t1.Start();
                            }
                        }
                    }
                }
            }
        }
        ;
    }
        public object Create(object parent, object configContext, XmlNode section)
        {
            object result = parent;

            // parse XML
            XmlNode fileAttribute = section.Attributes.RemoveNamedItem("file");

            result = NameValueSectionHandler.CreateStatic(result, section);

            if (fileAttribute != null && fileAttribute.Value.Length != 0)
            {
                string filename = null;
                filename = fileAttribute.Value;
                IConfigErrorInfo configXmlNode = fileAttribute as IConfigErrorInfo;
                if (configXmlNode == null)
                {
                    return(null);
                }

                string configFile         = configXmlNode.Filename;
                string directory          = Path.GetDirectoryName(configFile);
                string sourceFileFullPath = Path.Combine(directory, filename);

                if (File.Exists(sourceFileFullPath))
                {
                    ConfigXmlDocument doc = new ConfigXmlDocument();
                    try
                    {
                        doc.Load(sourceFileFullPath);
                    }
                    catch (XmlException e)
                    {
                        throw new ConfigurationErrorsException(e.Message, e, sourceFileFullPath, e.LineNumber);
                    }

                    if (section.Name != doc.DocumentElement.Name)
                    {
                        throw new ConfigurationErrorsException(
                                  SR.Format(SR.Config_name_value_file_section_file_invalid_root, section.Name),
                                  doc.DocumentElement);
                    }

                    result = NameValueSectionHandler.CreateStatic(result, doc.DocumentElement);
                }
            }

            return(result);
        }
    public static MailerConfiguration GetSection(string fileName, string name)
    {
      System.Configuration.ConfigXmlDocument doc = new ConfigXmlDocument();
      try
      {
        doc.Load(fileName);

        XmlNode node = doc.GetElementsByTagName(name)[0];
        IConfigurationSectionHandler handler = new UniMail.ConfigurationHandler();
        return handler.Create(null, null, node) as UniMail.MailerConfiguration;
      }
      catch
      {
        return null;
      }
    }
Пример #21
0
        /// <summary>
        /// 读取默认的KeelHack实例
        /// </summary>
        /// <returns></returns>
        public static IKeelHack GetKeelHack()
        {
            IKeelHack         result = null;
            string            ss     = System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            ConfigXmlDocument cxd    = new System.Configuration.ConfigXmlDocument();

            cxd.Load(ss);
            string keelhackpath = System.AppDomain.CurrentDomain.SetupInformation.PrivateBinPath + "\\" + ReadConfig(cxd, "KeelHack");

            if (System.IO.File.Exists(keelhackpath))
            {
                Assembly asm = System.Reflection.Assembly.LoadFile(keelhackpath);
                Type     t   = asm.GetType("Keel.KeelHack", false, true);
                result = (IKeelHack)Activator.CreateInstance(t);
            }
            return(result);
        }
Пример #22
0
        /// <summary>
        /// 获取基于web.config模型的AppSettings键值设置
        /// </summary>
        /// <param name="configPath">配置文件路径,相对或完整路径。</param>
        /// <param name="key">健</param>
        /// <returns>存在则返回相应值,异常出错则为空字符。</returns>
        public static string GetAppSettings(string configPath, string key)
        {
            string configFile = Util.ParseAppPath(configPath);
            string strRet     = "";

            try
            {
                System.Configuration.ConfigXmlDocument xmlConfig = new System.Configuration.ConfigXmlDocument();
                xmlConfig.Load(configFile);
                System.Xml.XmlNode node = xmlConfig.SelectSingleNode("configuration/appSettings/add[@key='" + key + "']");
                if (node != null)
                {
                    strRet = node.Attributes["value"].Value;
                }
            }
            catch (Exception) { }
            return(strRet);
        }
 public static XmlElement GetCfgXml()
 {
     var cfgXml = new ConfigXmlDocument();
     try
     {
         cfgXml.Load(cfgFile);
         if(cfgXml.DocumentElement["version"].InnerText != nowVersion)
         {
             System.IO.File.Delete(cfgFile);
             throw new System.IO.FileNotFoundException();
         }
     }
     catch(System.IO.FileNotFoundException)
     {
         cfgXml.LoadXml("<?xml version='1.0' encoding='utf-8' ?><gamecfg><version>" + nowVersion + "</version><GameRiver><isWhiteFirst>0</isWhiteFirst><player1><type>auto</type><name>匿名玩家</name><AIdt>1000</AIdt><server>false</server><port>8047</port><ip>192.168.1.101</ip></player1><player2><type>local</type><name>匿名玩家</name><AIdt>1000</AIdt><server>false</server><port>8047</port><ip>192.168.1.101</ip></player2></GameRiver></gamecfg>");
     }
     return cfgXml.DocumentElement;
 }
Пример #24
0
		public void Load ()
		{
			string config_xml = @"
				<configuration>
					<appSettings>
						<add key='anyKey' value='42' />
					</appSettings>
					<system.diagnostics />
				</configuration>";
			string config_file = Path.Combine (tempFolder, "config.xml");
			File.WriteAllText (config_file, config_xml);

			ConfigXmlDocument doc = new ConfigXmlDocument ();
			doc.Load (config_file);
			Assert.AreEqual (1, doc.ChildNodes.Count, "ChildNodes");
			Assert.AreEqual (config_file, doc.Filename, "Filename");
			Assert.AreEqual ("#document", doc.Name, "Name");
			File.Delete (config_file);
		}
        public object Create(object parent, object configContext, XmlNode section) {
            object result = parent;

            // parse XML
            XmlNode fileAttribute = section.Attributes.RemoveNamedItem("file");

            result = NameValueSectionHandler.CreateStatic(result, section);

            if (fileAttribute != null && fileAttribute.Value.Length != 0) {
                string filename = null;
                filename = fileAttribute.Value;
                IConfigErrorInfo configXmlNode = fileAttribute as IConfigErrorInfo;
                if (configXmlNode == null) {
                    return null;
                }

                string configFile = configXmlNode.Filename;
                string directory = Path.GetDirectoryName(configFile);
                string sourceFileFullPath = Path.Combine(directory, filename);

                if (File.Exists(sourceFileFullPath)) {

                    ConfigXmlDocument doc = new ConfigXmlDocument();
                    try {
                        doc.Load(sourceFileFullPath);
                    }
                    catch (XmlException e) {
                        throw new ConfigurationErrorsException(e.Message, e, sourceFileFullPath, e.LineNumber);
                    }

                    if (section.Name != doc.DocumentElement.Name) {
                        throw new ConfigurationErrorsException(
                                        SR.GetString(SR.Config_name_value_file_section_file_invalid_root, section.Name),
                                        doc.DocumentElement);
                    }
                
                    result = NameValueSectionHandler.CreateStatic(result, doc.DocumentElement);
                }
            }

            return result;
        }
Пример #26
0
            // Load a configuration file and merge it with the current settings.
            private void Load(String filename)
            {
                                #if SECOND_PASS
                // Load the contents of the file as XML.
                ConfigXmlDocument doc = new ConfigXmlDocument();
                doc.Load(filename);
                documents[numDocuments++] = doc;

                // Process the "configSections" element in the document.
                foreach (XmlNode node in doc.DocumentElement.ChildNodes)
                {
                    if (node.NodeType == XmlNodeType.Element &&
                        node.Name == "configSections")
                    {
                        LoadSectionInfo(node, null);
                        break;
                    }
                }
                                #endif
            }
Пример #27
0
        public object Create(object parent, object configContext, XmlNode section)
        {
            object  obj2 = parent;
            XmlNode node = section.Attributes.RemoveNamedItem("file");

            obj2 = NameValueSectionHandler.CreateStatic(obj2, section);
            if ((node == null) || (node.Value.Length == 0))
            {
                return(obj2);
            }
            string str = null;

            str = node.Value;
            IConfigErrorInfo info = node as IConfigErrorInfo;

            if (info == null)
            {
                return(null);
            }
            string path = Path.Combine(Path.GetDirectoryName(info.Filename), str);

            if (!File.Exists(path))
            {
                return(obj2);
            }
            ConfigXmlDocument document = new ConfigXmlDocument();

            try
            {
                document.Load(path);
            }
            catch (XmlException exception)
            {
                throw new ConfigurationErrorsException(exception.Message, exception, path, exception.LineNumber);
            }
            if (section.Name != document.DocumentElement.Name)
            {
                throw new ConfigurationErrorsException(System.SR.GetString("Config_name_value_file_section_file_invalid_root", new object[] { section.Name }), document.DocumentElement);
            }
            return(NameValueSectionHandler.CreateStatic(obj2, document.DocumentElement));
        }
        public object Create(object parent, object configContext, XmlNode section)
        {
#if (XML_DEP)
            XmlNode file = null;
            if (section.Attributes != null)
            {
                file = section.Attributes.RemoveNamedItem("file");
            }

            NameValueCollection pairs = ConfigHelper.GetNameValueCollection(
                parent as NameValueCollection,
                section,
                "key",
                "value");

            if (file != null && file.Value != String.Empty)
            {
                string fileName = ((IConfigXmlNode)section).Filename;
                fileName = Path.GetFullPath(fileName);
                string fullPath = Path.Combine(Path.GetDirectoryName(fileName), file.Value);
                if (!File.Exists(fullPath))
                {
                    return(pairs);
                }

                ConfigXmlDocument doc = new ConfigXmlDocument();
                doc.Load(fullPath);
                if (doc.DocumentElement.Name != section.Name)
                {
                    throw new ConfigurationException("Invalid root element", doc.DocumentElement);
                }

                pairs = ConfigHelper.GetNameValueCollection(pairs, doc.DocumentElement,
                                                            "key", "value");
            }

            return(pairs);
#else
            return(null);
#endif
        }
 static DataWorkerFactory()
 {
     if (factory_config == null || String.IsNullOrWhiteSpace(factory_config.Default_ConnectionString_Name))
     {
         try
         {
             ConfigXmlDocument xConfig = new ConfigXmlDocument();
             xConfig.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
             System.Xml.XmlNode xNode = xConfig.SelectSingleNode(AspNetConfigurationElementName + EnterpriseLibraryConfigurationElementName);
             if (xNode != null)
             {
                 System.Xml.XmlAttribute protectedFlag = xNode.Attributes["configProtectionProvider"];
                 if (protectedFlag != null)
                 {
                     xNode = System.Configuration.ProtectedConfiguration.Providers[protectedFlag.Value].Decrypt(xNode);
                     if (xNode != null)
                     {
                         xNode = xNode.FirstChild;
                     }
                 }
                 if (xNode != null)
                 {
                     System.Xml.XmlAttribute defaultDB = xNode.Attributes[EnterpriseLibraryDefaultDBAttribute];
                     if (defaultDB != null)
                     {
                         factory_config = new DataWorkerFactoryConfigSection();
                         factory_config.Default_ConnectionString_Name = defaultDB.Value;
                         return;
                     }
                 }
             }
         }
         catch
         {
         }
         throw new NullReferenceException("DW Factory Config Section not found in config file.");
     }
 }
    public static bool SaveSection(string fileName, string name, MailerConfiguration section)
    {
      System.Configuration.ConfigXmlDocument doc = new ConfigXmlDocument();
      try
      {
        doc.Load(fileName);
        XmlNode configNode = doc.ChildNodes[1];
        foreach (XmlNode node in configNode.ChildNodes)
        {
          if (node.Name == name)
            configNode.RemoveChild(node);
        }

        XmlNode newNode = section.CreateNode(doc, name);
        configNode.AppendChild(newNode);
        doc.Save(fileName);
        return true;
      }
      catch
      {
        return false;
      }
    }
 public object Create(object parent, object configContext, XmlNode section)
 {
     object obj2 = parent;
     XmlNode node = section.Attributes.RemoveNamedItem("file");
     obj2 = NameValueSectionHandler.CreateStatic(obj2, section);
     if ((node == null) || (node.Value.Length == 0))
     {
         return obj2;
     }
     string str = null;
     str = node.Value;
     IConfigErrorInfo info = node as IConfigErrorInfo;
     if (info == null)
     {
         return null;
     }
     string path = Path.Combine(Path.GetDirectoryName(info.Filename), str);
     if (!File.Exists(path))
     {
         return obj2;
     }
     ConfigXmlDocument document = new ConfigXmlDocument();
     try
     {
         document.Load(path);
     }
     catch (XmlException exception)
     {
         throw new ConfigurationErrorsException(exception.Message, exception, path, exception.LineNumber);
     }
     if (section.Name != document.DocumentElement.Name)
     {
         throw new ConfigurationErrorsException(System.SR.GetString("Config_name_value_file_section_file_invalid_root", new object[] { section.Name }), document.DocumentElement);
     }
     return NameValueSectionHandler.CreateStatic(obj2, document.DocumentElement);
 }
Пример #32
0
    public void Save()
    {
        string errorMessage = null;

        if (!HROne.CommonLib.FileIOProcess.IsFolderAllowWritePermission(AppDomain.CurrentDomain.BaseDirectory, out errorMessage))
        {
            throw new Exception(errorMessage);
        }
        string filename = getFilename();

        if (config == null)
        {
            config = new System.Configuration.ConfigXmlDocument();
        }
        else
        {
            filename = config.Filename;
        }
        XmlElement settings = GetOrCreateElement(config, "Settings");
        //{
        //    XmlAttribute version = config.CreateAttribute("Version");
        //    version.Value = "2.0";
        //    settings.Attributes.Append(version);
        //    config.AppendChild(settings);
        //}
        //SetDatabaseConfigList(settings);

        XmlElement masterDatabaseNode = GetOrCreateElement(settings, "MasterDatabaseConfig");

        SetDatabaseConfig(masterDatabaseNode, MasterDatabaseConfig);

        XmlElement databaseEncryptKeyNode = GetOrCreateElement(settings, "DatabaseEncryptKey");

        databaseEncryptKeyNode.InnerText = databaseEncryptKey;
        config.Save(filename);
    }
Пример #33
0
        public ConfigFile(string filename, bool createIfNecessary)
        {
            this.filename = filename;
            config = new ConfigXmlDocument();

            if (File.Exists(filename))
            {
                // Load the file if it already exists
                config.Load(filename);
            }
            else if (createIfNecessary)
            {
                // Create the file since it doesn't exist
                using (StreamWriter w = File.CreateText(filename))
                {
                    w.Write("<configuration></configuration>");
                }
                config.Load(filename);
            }
            else
            {
                throw new FileNotFoundException("The configuration file \"" + filename + "\" was not found.", filename);
            }
        }
Пример #34
0
			public ConfigXmlElement (ConfigXmlDocument document,
						 string prefix,
						 string localName,
						 string namespaceUri)
				: base (prefix, localName, namespaceUri, document)
			{
				fileName = document.fileName;
				lineNumber = document.LineNumber;
			}
Пример #35
0
			public ConfigXmlComment (ConfigXmlDocument document, string comment)
				: base (comment, document)
			{
				fileName = document.fileName;
				lineNumber = document.LineNumber;
			}
Пример #36
0
		private static ConfigurationSection HandleLegacyConfigurationSection(string exeConfigFilename, ConfigurationSectionGroupPath groupPath, string sectionKey)
		{
			var sectionPath = groupPath.GetChildGroupPath(sectionKey).ToString();
			foreach (var shredSettingsType in _shredSettingsTypes)
			{
				if (LegacyShredConfigSectionAttribute.IsMatchingLegacyShredConfigSectionType(shredSettingsType, sectionPath))
				{
					var xmlDocument = new ConfigXmlDocument();
					xmlDocument.Load(exeConfigFilename);

					var sectionElement = xmlDocument.SelectSingleNode("//" + sectionPath);
					if (sectionElement != null)
					{
						var section = (ShredConfigSection) Activator.CreateInstance(shredSettingsType, true);
						section.LoadXml(sectionElement.OuterXml);
						return section;
					}
				}
			}
			return null;
		}
Пример #37
0
		XmlDocument GetDocumentForSection (string sectionName)
		{
			ConfigXmlDocument doc = new ConfigXmlDocument ();
			if (pending == null)
				return doc;

			string [] sectionPath = sectionName.Split ('/');
			string outerxml = pending [sectionPath [0]] as string;
			if (outerxml == null)
				return doc;

			StringReader reader = new StringReader (outerxml);
			XmlTextReader rd = new XmlTextReader (reader);
			rd.MoveToContent ();
			doc.LoadSingleElement (fileName, rd);

			return GetInnerDoc (doc, 0, sectionPath);
		}
Пример #38
0
		XmlDocument GetInnerDoc (XmlDocument doc, int i, string [] sectionPath)
		{
			if (++i >= sectionPath.Length)
				return doc;

			if (doc.DocumentElement == null)
				return null;

			XmlNode node = doc.DocumentElement.FirstChild;
			while (node != null) {
				if (node.Name == sectionPath [i]) {
					ConfigXmlDocument result = new ConfigXmlDocument ();
					result.Load (new StringReader (node.OuterXml));
					return GetInnerDoc (result, i, sectionPath);
				}
				node = node.NextSibling;
			}

			return null;
		}
 protected void ProcessBrowserFiles(bool useVirtualPath, string virtualDir)
 {
     this._browserTree = new System.Web.Configuration.BrowserTree();
     this._defaultTree = new System.Web.Configuration.BrowserTree();
     this._customTreeNames = new ArrayList();
     if (this._browserFileList == null)
     {
         this._browserFileList = new ArrayList();
     }
     this._browserFileList.Sort();
     string str = null;
     string str2 = null;
     string str3 = null;
     foreach (string str4 in this._browserFileList)
     {
         if (str4.EndsWith("ie.browser", StringComparison.OrdinalIgnoreCase))
         {
             str2 = str4;
         }
         else if (str4.EndsWith("mozilla.browser", StringComparison.OrdinalIgnoreCase))
         {
             str = str4;
         }
         else if (str4.EndsWith("opera.browser", StringComparison.OrdinalIgnoreCase))
         {
             str3 = str4;
             break;
         }
     }
     if (str2 != null)
     {
         this._browserFileList.Remove(str2);
         this._browserFileList.Insert(0, str2);
     }
     if (str != null)
     {
         this._browserFileList.Remove(str);
         this._browserFileList.Insert(1, str);
     }
     if (str3 != null)
     {
         this._browserFileList.Remove(str3);
         this._browserFileList.Insert(2, str3);
     }
     foreach (string str5 in this._browserFileList)
     {
         XmlDocument document = new ConfigXmlDocument();
         try
         {
             document.Load(str5);
             XmlNode documentElement = document.DocumentElement;
             if (documentElement.Name != "browsers")
             {
                 if (useVirtualPath)
                 {
                     throw new HttpParseException(System.Web.SR.GetString("Invalid_browser_root"), null, virtualDir + "/" + this.NoPathFileName(str5), null, 1);
                 }
                 throw new HttpParseException(System.Web.SR.GetString("Invalid_browser_root"), null, str5, null, 1);
             }
             foreach (XmlNode node2 in documentElement.ChildNodes)
             {
                 if (node2.NodeType == XmlNodeType.Element)
                 {
                     if ((node2.Name == "browser") || (node2.Name == "gateway"))
                     {
                         this.ProcessBrowserNode(node2, this._browserTree);
                     }
                     else if (node2.Name == "defaultBrowser")
                     {
                         this.ProcessBrowserNode(node2, this._defaultTree);
                     }
                     else
                     {
                         System.Web.Configuration.HandlerBase.ThrowUnrecognizedElement(node2);
                     }
                 }
             }
         }
         catch (XmlException exception)
         {
             if (useVirtualPath)
             {
                 throw new HttpParseException(exception.Message, null, virtualDir + "/" + this.NoPathFileName(str5), null, exception.LineNumber);
             }
             throw new HttpParseException(exception.Message, null, str5, null, exception.LineNumber);
         }
         catch (XmlSchemaException exception2)
         {
             if (useVirtualPath)
             {
                 throw new HttpParseException(exception2.Message, null, virtualDir + "/" + this.NoPathFileName(str5), null, exception2.LineNumber);
             }
             throw new HttpParseException(exception2.Message, null, str5, null, exception2.LineNumber);
         }
     }
     this.NormalizeAndValidateTree(this._browserTree, false);
     this.NormalizeAndValidateTree(this._defaultTree, true);
     BrowserDefinition bd = (BrowserDefinition) this._browserTree["Default"];
     if (bd != null)
     {
         this.AddBrowserToCollectionRecursive(bd, 0);
     }
 }
 internal void ProcessCustomBrowserFiles(bool useVirtualPath, string virtualDir)
 {
     DirectoryInfo browserDirInfo = null;
     DirectoryInfo[] array = null;
     DirectoryInfo[] directories = null;
     this._customTreeList = new ArrayList();
     this._customBrowserFileLists = new ArrayList();
     this._customBrowserDefinitionCollections = new ArrayList();
     if (!useVirtualPath)
     {
         browserDirInfo = new DirectoryInfo(_browsersDirectory);
     }
     else
     {
         browserDirInfo = new DirectoryInfo(HostingEnvironment.MapPathInternal(virtualDir));
     }
     directories = browserDirInfo.GetDirectories();
     int index = 0;
     int length = directories.Length;
     array = new DirectoryInfo[length];
     for (int i = 0; i < length; i++)
     {
         if ((directories[i].Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
         {
             array[index] = directories[i];
             index++;
         }
     }
     Array.Resize<DirectoryInfo>(ref array, index);
     for (int j = 0; j < array.Length; j++)
     {
         FileInfo[] filesNotHidden = GetFilesNotHidden(array[j], browserDirInfo);
         if ((filesNotHidden != null) && (filesNotHidden.Length != 0))
         {
             System.Web.Configuration.BrowserTree tree = new System.Web.Configuration.BrowserTree();
             this._customTreeList.Add(tree);
             this._customTreeNames.Add(array[j].Name);
             ArrayList list = new ArrayList();
             foreach (FileInfo info2 in filesNotHidden)
             {
                 list.Add(info2.FullName);
             }
             this._customBrowserFileLists.Add(list);
         }
     }
     for (int k = 0; k < this._customBrowserFileLists.Count; k++)
     {
         ArrayList list2 = (ArrayList) this._customBrowserFileLists[k];
         foreach (string str in list2)
         {
             XmlDocument document = new ConfigXmlDocument();
             try
             {
                 document.Load(str);
                 XmlNode documentElement = document.DocumentElement;
                 if (documentElement.Name != "browsers")
                 {
                     if (useVirtualPath)
                     {
                         throw new HttpParseException(System.Web.SR.GetString("Invalid_browser_root"), null, virtualDir + "/" + this.NoPathFileName(str), null, 1);
                     }
                     throw new HttpParseException(System.Web.SR.GetString("Invalid_browser_root"), null, str, null, 1);
                 }
                 foreach (XmlNode node2 in documentElement.ChildNodes)
                 {
                     if (node2.NodeType == XmlNodeType.Element)
                     {
                         if ((node2.Name == "browser") || (node2.Name == "gateway"))
                         {
                             this.ProcessBrowserNode(node2, (System.Web.Configuration.BrowserTree) this._customTreeList[k]);
                         }
                         else
                         {
                             System.Web.Configuration.HandlerBase.ThrowUnrecognizedElement(node2);
                         }
                     }
                 }
             }
             catch (XmlException exception)
             {
                 if (useVirtualPath)
                 {
                     throw new HttpParseException(exception.Message, null, virtualDir + "/" + this.NoPathFileName(str), null, exception.LineNumber);
                 }
                 throw new HttpParseException(exception.Message, null, str, null, exception.LineNumber);
             }
             catch (XmlSchemaException exception2)
             {
                 if (useVirtualPath)
                 {
                     throw new HttpParseException(exception2.Message, null, virtualDir + "/" + this.NoPathFileName(str), null, exception2.LineNumber);
                 }
                 throw new HttpParseException(exception2.Message, null, str, null, exception2.LineNumber);
             }
         }
         this.SetCustomTreeRoots((System.Web.Configuration.BrowserTree) this._customTreeList[k], k);
         this.NormalizeAndValidateTree((System.Web.Configuration.BrowserTree) this._customTreeList[k], false, true);
         this._customBrowserDefinitionCollections.Add(new BrowserDefinitionCollection());
         this.AddCustomBrowserToCollectionRecursive((BrowserDefinition) ((System.Web.Configuration.BrowserTree) this._customTreeList[k])[this._customTreeNames[k]], 0, k);
     }
 }
        internal void ProcessCustomBrowserFiles(bool useVirtualPath, string virtualDir) {
            //get all custom browser files and put them in the "tree"
            DirectoryInfo browserDirInfo = null;
            DirectoryInfo[] browserSubDirectories = null;
            DirectoryInfo[] allBrowserSubDirectories = null;
            ArrayList customBrowserFileNames;
            _customTreeList = new ArrayList();
            _customBrowserFileLists = new ArrayList();
            _customBrowserDefinitionCollections = new ArrayList();

            /* Machine Level Custom Browsers */
            if (useVirtualPath == false) {
                browserDirInfo = new DirectoryInfo(_browsersDirectory);
            }
            /* Application Level Custom Browsers */
            else {
                browserDirInfo = new DirectoryInfo(HostingEnvironment.MapPathInternal(virtualDir));
            }

            allBrowserSubDirectories = browserDirInfo.GetDirectories();
            
            int j = 0;
            int length = allBrowserSubDirectories.Length;
            browserSubDirectories = new DirectoryInfo[length];
            for (int i = 0; i < length; i++) {
                if ((allBrowserSubDirectories[i].Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) {
                    browserSubDirectories[j] = allBrowserSubDirectories[i];
                    j++;
                }
            }
            Array.Resize(ref browserSubDirectories, j);

            for (int i = 0; i < browserSubDirectories.Length; i++) {
                /* Recursively Into Subdirectories */
                FileInfo[] browserFiles = GetFilesNotHidden(browserSubDirectories[i], browserDirInfo);

                if (browserFiles == null || browserFiles.Length == 0) {
                    continue;
                }
                BrowserTree customTree = new BrowserTree();
                _customTreeList.Add(customTree);
                _customTreeNames.Add(browserSubDirectories[i].Name);
                customBrowserFileNames = new ArrayList();

                foreach (FileInfo browserFile in browserFiles) {
                    customBrowserFileNames.Add(browserFile.FullName);
                }
                _customBrowserFileLists.Add(customBrowserFileNames);
            }
            for (int i = 0; i < _customBrowserFileLists.Count; i++) {
                ArrayList fileNames = (ArrayList)_customBrowserFileLists[i];
                foreach (string fileName in fileNames) {
                    XmlDocument doc = new ConfigXmlDocument();
                    try {
                        doc.Load(fileName);
 
                        XmlNode rootNode = doc.DocumentElement;
                        if (rootNode.Name != "browsers") {
                            if (useVirtualPath) {
                                throw new HttpParseException(SR.GetString(SR.Invalid_browser_root), null /*innerException*/, virtualDir + "/" + NoPathFileName(fileName), null /*sourceCode*/, 1);
                            }
                            else {
                                throw new HttpParseException(SR.GetString(SR.Invalid_browser_root), null /*innerException*/, fileName, null /*sourceCode*/, 1);
                            }
                        }
                        foreach (XmlNode node in rootNode.ChildNodes) {
                            if (node.NodeType != XmlNodeType.Element) {
                                continue;
                            }
                            if (node.Name == "browser" || node.Name == "gateway") {
                                ProcessBrowserNode(node, (BrowserTree)_customTreeList[i]);
                            }
                            else {
                                HandlerBase.ThrowUnrecognizedElement(node);
                            }
                        }
                    }
                    catch (XmlException e) {
                        if (useVirtualPath) {
                            throw new HttpParseException(e.Message, null /*innerException*/, virtualDir + "/" + NoPathFileName(fileName), null /*sourceCode*/, e.LineNumber);
                        }
                        else {
                            throw new HttpParseException(e.Message, null /*innerException*/, fileName, null /*sourceCode*/, e.LineNumber);
                        }
                    }
                    catch (XmlSchemaException e) {
                        if (useVirtualPath) {
                            throw new HttpParseException(e.Message, null /*innerException*/, virtualDir + "/" + NoPathFileName(fileName), null /*sourceCode*/, e.LineNumber);
                        }
                        else {
                            throw new HttpParseException(e.Message, null /*innerException*/, fileName, null /*sourceCode*/, e.LineNumber);
                        }
                    }
                }
                SetCustomTreeRoots((BrowserTree)_customTreeList[i], i);
                NormalizeAndValidateTree((BrowserTree)_customTreeList[i], false, true);
                _customBrowserDefinitionCollections.Add(new BrowserDefinitionCollection());
                AddCustomBrowserToCollectionRecursive((BrowserDefinition)(((BrowserTree)_customTreeList[i])[_customTreeNames[i]]), 0, i);
            }
        }
        private void ModifyAppInsightsConfigFile(bool removeSettings = false)
        {
            var configFile = Server.MapPath("~/ApplicationInsights.config");
            if (!File.Exists(configFile))
            {
                File.Copy(Server.MapPath("~/DesktopModules/AppInsights/ApplicationInsights.config"), configFile);
            }

            // Load the ApplicationInsights.config file
            var config = new ConfigXmlDocument();
            config.Load(configFile);
            var key = removeSettings ? string.Empty : ModuleSettings.GetValueOrDefault("InstrumentationKey", string.Empty);

            const string namespaceUri = "http://schemas.microsoft.com/ApplicationInsights/2013/Settings";
            var nsmgr = new XmlNamespaceManager(config.NameTable);
            nsmgr.AddNamespace("nr", namespaceUri);

            // Change instrumentation key
            var keyNode = config.SelectSingleNode("//nr:InstrumentationKey", nsmgr);
            if (keyNode != null)
            {
                keyNode.InnerText = key;
            }

            // Save the modifications
            config.Save(configFile);
        }
Пример #43
0
        public static bool UpdateConnectionString( )
        {
            Project pjt = Kit.GetProjectByName(Kit.SlnKeel.UIProjectName);

            if (pjt == null)
            {
                Common.ShowInfo("您尚未设置UI主界面项目, 因此无法自动配置连接字符串到你的app.config 或者web.config中!");
                return(true);
            }
            ProjectItem PI = null;

            for (int i = 1; i <= pjt.ProjectItems.Count; i++)
            {
                ProjectItem pix = pjt.ProjectItems.Item(i);
                if (pix.Name.ToLower().Contains("app.config") || pix.Name.ToLower().Contains("web.config"))
                {
                    PI = pix;
                    break;
                }
            }
            if (PI == null)
            {
                Common.ShowInfo(string.Format("您设置的主UI项目{0}中未找到app.config 或者web.config,因此无法自动设置链接字符串配置", pjt.Name));
            }
            else
            {
                bool needUpdate = true;

                ConfigXmlDocument cxd = new System.Configuration.ConfigXmlDocument();

                cxd.Load(PI.get_FileNames(1));
                XmlNode xnx  = cxd.SelectSingleNode("descendant::configuration/connectionStrings");
                string  csss = GetProjectConfigNamespec(GetProjectLangType(GetProjectUI()));

                string name = "";
                if (pjt.Kind == "{E24C65DC-7377-472b-9ABA-BC803B73C61A}")
                {
                    name = "Keel" + csss + ".ConnectionString";
                }
                else
                {
                    name = ((string)pjt.Properties.Item("RootNamespace").Value) + csss + ".ConnectionString";
                }
                if (xnx != null)
                {
                    for (int i = 0; i < xnx.ChildNodes.Count; i++)
                    {
                        if (xnx.ChildNodes[i].Attributes["name"].Value.Contains(name))
                        {
                            if (xnx.ChildNodes[i].Attributes["providerName"].Value != Kit.SlnKeel.ProviderName)
                            {
                                xnx.ChildNodes[i].Attributes["providerName"].Value = Kit.SlnKeel.ProviderName;
                            }
                            if (xnx.ChildNodes[i].Attributes["connectionString"].Value != Kit.SlnKeel.ConnectString)
                            {
                                xnx.ChildNodes[i].Attributes["connectionString"].Value = Kit.SlnKeel.ConnectString;
                            }
                            cxd.Save(PI.get_FileNames(1));
                            needUpdate = false;
                            break;
                        }
                    }
                }
                if (needUpdate)
                {
                    XmlNode      xn             = cxd.CreateNode("element", "add", "");
                    XmlAttribute xzproviderName = cxd.CreateAttribute("providerName");
                    xzproviderName.Value = Kit.SlnKeel.ProviderName;
                    XmlAttribute xaconnectionString = cxd.CreateAttribute("connectionString");
                    xaconnectionString.Value = Kit.SlnKeel.ConnectString;
                    XmlAttribute xaname = cxd.CreateAttribute("name");
                    xaname.Value = name;
                    xn.Attributes.Append(xaname);
                    xn.Attributes.Append(xaconnectionString);
                    xn.Attributes.Append(xzproviderName);
                    if (xnx == null)
                    {
                        XmlNode xnx1 = cxd.SelectSingleNode("descendant::configuration");
                        xnx = cxd.CreateElement("connectionStrings");
                        xnx1.AppendChild(xnx);
                    }
                    xnx.AppendChild(xn);
                    // cxd.SelectSingleNode("descendant::configuration/connectionStrings").InnerXml = xnx.InnerXml;
                    cxd.Save(PI.get_FileNames(1));
                    //;// = cxd.SelectSingleNode("descendant::configuration/connectionStrings/add[@name='" + appnamespace + ".Properties.Settings.ConnectionString']");
                    //if (xnl.Attributes["providerName"] != null && xnl.Attributes["connectionString"] != null)
                    //{

                    //}
                }
                Common.ShowInfo(string.Format("您设置的主UI项目{0}中到app.config 或者web.config,已经设置了链接字符串{1}", pjt.Name, name));
            }
            return(true);
        }
Пример #44
0
			public ConfigXmlText (ConfigXmlDocument document, string data)
				: base (data, document)
			{
				fileName = document.fileName;
				lineNumber = document.LineNumber;
			}
Пример #45
0
        private static NameValueCollection LoadHostSettings(string host)
        {
            NameValueCollection objCol;

            System.Configuration.ConfigXmlDocument objDoc = new System.Configuration.ConfigXmlDocument();

            try
            {
                if (System.IO.File.Exists(General.Environment.Current.GetBinDirectory() + "General.config"))
                {
                    objDoc.Load(General.Environment.Current.GetBinDirectory() + "General.config");
                    XmlNode node = objDoc.SelectSingleNode("//HostSettings" + "[@host='" + host + "']");
                    if (node == null)
                    {
                        return(new NameValueCollection());
                    }
                    node.Attributes.RemoveAll();
                    System.Configuration.NameValueSectionHandler nvsh = new System.Configuration.NameValueSectionHandler();
                    objCol = (NameValueCollection)nvsh.Create(null, null, node);
                }
                else if (System.IO.File.Exists(General.Environment.Current.GetAppDirectory() + "General.config"))
                {
                    objDoc.Load(General.Environment.Current.GetAppDirectory() + "General.config");
                    XmlNode node = objDoc.SelectSingleNode("//HostSettings" + "[@host='" + host + "']");
                    if (node == null)
                    {
                        return(new NameValueCollection());
                    }
                    node.Attributes.RemoveAll();
                    System.Configuration.NameValueSectionHandler nvsh = new System.Configuration.NameValueSectionHandler();
                    objCol = (NameValueCollection)nvsh.Create(null, null, node);
                }
                else
                {
                    objCol = (NameValueCollection)null;
                }
            }
            catch
            {
                objCol = (NameValueCollection)null;
            }
            return(objCol);

            /*
             * This is the old code that throws exceptions all the time
             * try
             * {
             *  objDoc.Load(General.Environment.Current.GetBinDirectory() + "General.config");
             *  XmlNode node = objDoc.SelectSingleNode("//HostSettings" + "[@host='" + GetCurrentHost() + "']");
             *  if (node == null)
             *      return null;
             *  node.Attributes.RemoveAll();
             *  System.Configuration.NameValueSectionHandler nvsh = new System.Configuration.NameValueSectionHandler();
             *  objCol = (NameValueCollection)nvsh.Create(null, null, node);
             * }
             * catch
             * {
             *  try
             *  {
             *      objDoc.Load(General.Environment.Current.GetAppDirectory() + "General.config");
             *      XmlNode node = objDoc.SelectSingleNode("//HostSettings" + "[@host='" + GetCurrentHost() + "']");
             *      if (node == null)
             *          return null;
             *      node.Attributes.RemoveAll();
             *      System.Configuration.NameValueSectionHandler nvsh = new System.Configuration.NameValueSectionHandler();
             *      objCol = (NameValueCollection)nvsh.Create(null, null, node);
             *  }
             *  catch
             *  {
             *      objCol = (NameValueCollection)null;
             *  }
             * }
             * return objCol;
             */
        }
Пример #46
0
 public ConfigXmlText(ConfigXmlDocument document, string data)
     : base(data, document)
 {
     fileName   = document.fileName;
     lineNumber = document.LineNumber;
 }
Пример #47
0
        private string GetConnectionString(string strPathToConfigFile, string strAppSettingsKey)
        {
            try
            {
                ConfigXmlDocument	doc = new ConfigXmlDocument();
                doc.Load( strPathToConfigFile );

                XmlNode	nodeKey		= doc.SelectSingleNode("//appSettings/add[@key='" + strAppSettingsKey + "']");
                string	strEncValue	= nodeKey.Attributes["value"].Value.ToString();
                string	strDecValue	= ICICRYPT.Reversible.StrDecode(strEncValue,2026820330,true);

                // MessageBox.Show(strDecValue);

                SqlConnection objConn = new SqlConnection(strDecValue);
                objConn.Open();
                objConn.Close();
                objConn.Dispose();

                return strDecValue;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(this, "Error obtaining connection to " + strLocation + " database\n\n\"" + ex.Message + "\"\n" + ex.StackTrace, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }

            return null;
        }
Пример #48
0
		/// <summary>
		/// Loads compiler configuration values from a specified .config file into a given record.
		/// </summary>
		/// <param name="appContext">Application context where to load libraries.</param>
		/// <param name="path">A full path to the .config file.</param>
		/// <returns>The new configuration record.</returns>
		/// <exception cref="ConfigurationErrorsException">An error in configuration.</exception>
        public void LoadFromFile(ApplicationContext/*!*/ appContext, FullPath path)
		{
			if (appContext == null)
				throw new ArgumentNullException("appContext");

			path.EnsureNonEmpty("path");

			ConfigXmlDocument doc = new ConfigXmlDocument();

			try
			{
				doc.Load(path);
			}
			catch (XmlException e)
			{
				throw new ConfigurationErrorsException(e.Message);
			}

			XmlNode root = doc.DocumentElement;
            if (root.Name == "configuration")
            {
                ProcessNodes(appContext, root, addedLibraries);
            }
		}
Пример #49
0
        public override bool OnStart()
        {
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            //var settingAsString = RoleEnvironment.GetConfigurationSettingValue("Full.Setting.Path");

            // skip role setup when emulating azure
            if (!RoleEnvironment.IsEmulated)
            {
                #region Machine Key Reconfiguration
                // http://msdn.microsoft.com/en-us/library/gg494983.aspx

                _logger = new WebRoleLogger();
                _logger.Log("RoleEntryPoint.OnStart() has been invoked.");
                try
                {
                    // locate the encrypted web.config file
                    var webConfigPath = GetEncryptedWebConfigFilePath();
                    var webConfigFileExists = File.Exists(webConfigPath);
                    if (!webConfigFileExists)
                        return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate web.config file at '{0}'.", webConfigPath);

                    // get web.config file contents
                    var webConfigContent = File.ReadAllText(webConfigPath);

                    // construct an XML configuration document
                    var webConfigXmlDocument = new ConfigXmlDocument { InnerXml = webConfigContent, };
                    if (webConfigXmlDocument.DocumentElement == null)
                        return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData node in web.config file.");

                    // find the configProtectedData node
                    var configProtectedDataNode = webConfigXmlDocument.DocumentElement.ChildNodes.Cast<XmlNode>()
                        .SingleOrDefault(x => x.Name == "configProtectedData");
                    if (configProtectedDataNode == null)
                        return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData node in web.config file.");

                    // find the configProtectedData/provider child node
                    var configProtectionProviderNode = configProtectedDataNode;
                    while (configProtectionProviderNode != null && configProtectionProviderNode.Attributes != null &&
                        (configProtectionProviderNode.Attributes["name"] == null || configProtectionProviderNode.Attributes["thumbprint"] == null))
                    {
                        configProtectionProviderNode = configProtectionProviderNode.ChildNodes.Cast<XmlNode>().FirstOrDefault();
                    }
                    if (configProtectionProviderNode == null || configProtectionProviderNode.Attributes == null)
                        return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData/provider child node in web.config file.");

                    // get the configProtectedData/provider node attributes (name & thumbprint)
                    var configProtectionProviderName = configProtectionProviderNode.Attributes["name"].Value;
                    var configProtectionProviderThumbprint = configProtectionProviderNode.Attributes["thumbprint"].Value;

                    // construct & initialize a ProtectedConfigurationProvider
                    var configProtectionProviderAssembly = Assembly.Load("Pkcs12ProtectedConfigurationProvider");
                    var configProtectionProviderType = configProtectionProviderAssembly.GetTypes()
                        .First(t => typeof(ProtectedConfigurationProvider).IsAssignableFrom(t));
                    var protectedConfigurationProvider = Activator.CreateInstance(configProtectionProviderType) as ProtectedConfigurationProvider;
                    if (protectedConfigurationProvider == null)
                        return FailBecauseMachineConfigCannotBeReconfigured("Unable to construct a ProtectedConfigurationProvider.");

                    protectedConfigurationProvider.Initialize(configProtectionProviderName, new NameValueCollection
                    {
                        { "thumbprint", configProtectionProviderThumbprint },
                    });

                    // get encrypted appSettings XML node
                    var encryptedAppSettingsNode = webConfigXmlDocument.DocumentElement.ChildNodes
                        .Cast<XmlNode>().SingleOrDefault(x => x.Name == "appSettings");
                    if (encryptedAppSettingsNode == null)
                        return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate encrypted appSettings node.");

                    // decrypt appSettings XML
                    var decryptedAppSettingsNode = protectedConfigurationProvider.Decrypt(encryptedAppSettingsNode).ChildNodes
                        .Cast<XmlNode>().SingleOrDefault(x => x.Name == "appSettings");
                    if (decryptedAppSettingsNode == null)
                        return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate decrypted appSettings node.");

                    // extract machineConfig values from decrypted appSettings XML
                    var validationKey = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineValidationKey");
                    var validationAlgorithm = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineValidationAlgorithm");
                    var decryptionKey = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineDecryptionKey");
                    var decryptionAlgorithm = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineDecryptionAlgorithm");
                    if (string.IsNullOrWhiteSpace(validationKey) || string.IsNullOrWhiteSpace(validationAlgorithm) ||
                        string.IsNullOrWhiteSpace(decryptionKey) || string.IsNullOrWhiteSpace(decryptionAlgorithm))
                        return FailBecauseMachineConfigCannotBeReconfigured("A machineKey attribute value could not be found in decrypted appSettings.");

                    _logger.Log("Found deployment validation key '{0}'.", validationKey);
                    _logger.Log("Found deployment decryption key '{0}'.", decryptionKey);
                    using (var server = new ServerManager())
                    {
                        // load IIS site's web configuration
                        var siteName = string.Format("{0}_Web", RoleEnvironment.CurrentRoleInstance.Id);
                        var site = RoleEnvironment.IsEmulated ? server.Sites.First() : server.Sites[siteName];
                        if (site == null)
                            return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate site '{0}'.", siteName);

                        var siteWebConfiguration = site.GetWebConfiguration();
                        if (siteWebConfiguration == null)
                            return FailBecauseMachineConfigCannotBeReconfigured("Unable to load web configuration for site '{0}'.", siteName);

                        var machineKeySection = siteWebConfiguration.GetSection("system.web/machineKey");
                        if (machineKeySection == null)
                            return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate machineConfig section in site '{0}' web configuration.", siteName);

                        // overwrite machineKey values
                        machineKeySection.SetAttributeValue("validationKey", validationKey);
                        machineKeySection.SetAttributeValue("validation", validationAlgorithm);
                        machineKeySection.SetAttributeValue("decryptionKey", decryptionKey);
                        machineKeySection.SetAttributeValue("decryption", decryptionAlgorithm);
                        server.CommitChanges();
                        _logger.Log("Machine key has been reconfigured.");
                    }
                }
                catch (Exception ex)
                {
                    if (ex.Message == FailBecauseMachineConfigCannotBeReconfiguredMessage) throw;

                    _logger.Log("A(n) {0} exception was encountered while trying to set the machineConfig.", ex.GetType().Name);
                    _logger.Log(ex.Message);
                    _logger.Log(ex.StackTrace);
                    _logger.Log(ex.Source);
                }
                _logger.Dispose();

                #endregion
                //#region Diagnostics Trace Logging

                //var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

                //// Change the polling interval for all logs.
                //config.ConfigurationChangePollInterval = TimeSpan.FromSeconds(30.0);

                //// Set the transfer interval for all logs.
                //config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);

                //// Add performance counter monitoring for configured counters
                //var counters = new List<string>
                //{
                //    @"\Processor(_Total)\% Processor Time",
                //    @"\Memory\Available Mbytes",
                //    @"\TCPv4\Connections Established",
                //    @"\ASP.NET Applications(__Total__)\Requests/Sec",
                //    @"\Network Interface(*)\Bytes Received/sec",
                //    @"\Network Interface(*)\Bytes Sent/sec"
                //};
                //foreach (var counterConfig in counters.Select(counter =>
                //    new PerformanceCounterConfiguration
                //    {
                //        CounterSpecifier = counter,
                //        SampleRate = TimeSpan.FromMinutes(1)
                //    })
                //)
                //{
                //    config.PerformanceCounters.DataSources.Add(counterConfig);
                //}
                //config.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);

                ////Diagnostics Infrastructure logs
                //config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
                //config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;//.error

                ////Windows Event Logs
                //config.WindowsEventLog.DataSources.Add("System!*");
                //config.WindowsEventLog.DataSources.Add("Application!*");
                //config.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
                //config.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Warning;

                ////Azure Trace Logs
                //config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
                //config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;

                ////Crash Dumps
                //CrashDumps.EnableCollection(true);

                ////IIS Logs
                //config.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);

                //// start the diagnostics monitor
                //DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", config);

                //#endregion
                #region IIS Domain Binding

                // NOTE: This is here to prevent random errors where requests for another domain's resource
                // are accidentally routed to this deployment server. It's weird, but it happened before this code!

                // By default, the website name is "[ Current Role Instance id]_Web"
                var siteName1 = string.Format("{0}_Web", RoleEnvironment.CurrentRoleInstance.Id);

                // In future, if you need add more endpoint(HTTP or HTTPS),
                // please create new bindingEntry and append to the cmd string,
                // separate with ','. For how to use AppCmd to config IIS site,
                // please refer to this article
                // http://learn.iis.net/page.aspx/114/getting-started-with-appcmdexe
                // NOTE: the above is accomplished in the GetAppCmdBindings method in this class

                var command = string.Format("set site \"{0}\" /bindings:{1}", siteName1, GetAppCmdBindings());

                const string appCmdPath = @"d:\Windows\System32\inetsrv\appcmd.exe";

                try
                {
                    Process.Start(new ProcessStartInfo(appCmdPath, command));
                    Trace.TraceInformation("Initialize IIS binding succeed.");
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.Message);
                    throw;
                }

                #endregion
            }

            var baseOnStart = base.OnStart();
            return baseOnStart;
        }
 /// <summary>
 /// Builds the configuration section XmlNode given an Xml string.
 /// </summary>
 /// <param name="xml">The XML string</param>
 /// <returns>The XmlNode of the document corresponding to the string.</returns>
 private static XmlNode BuildConfigurationSection(string xml)
 {
     ConfigXmlDocument doc = new ConfigXmlDocument();
     doc.LoadXml(xml);
     return doc.DocumentElement;
 }
        protected void ProcessBrowserFiles(bool useVirtualPath, string virtualDir) {
            _browserTree = new BrowserTree();
            _defaultTree = new BrowserTree();
            _customTreeNames = new ArrayList();

            if (_browserFileList == null) {
                _browserFileList = new ArrayList();
            }

            _browserFileList.Sort();
//#if OPTIMIZE_FOR_DESKTOP_BROWSER
            string mozillaFile = null;
            string ieFile = null;
            string operaFile = null;

            // DevDivBugs 180962
            // IE, Mozilla and Opera are first-class browsers. Their User-Agent profiles need to be compared to the UA profile
            // of the HTTP request before other browsers. We put them to the head of the list so that the generated browser capabilities 
            // code will try to match them before other browsers.
            foreach (String filePath in _browserFileList) {
                if (filePath.EndsWith("ie.browser", StringComparison.OrdinalIgnoreCase)) {
                    ieFile = filePath;
                }
                else if (filePath.EndsWith("mozilla.browser", StringComparison.OrdinalIgnoreCase)) {
                    mozillaFile = filePath;
                }
                else if (filePath.EndsWith("opera.browser", StringComparison.OrdinalIgnoreCase)) {
                    operaFile = filePath;
                    break;
                }
            }

            if (ieFile != null) {
                _browserFileList.Remove(ieFile);
                _browserFileList.Insert(0, ieFile);
            }

            if (mozillaFile != null) {
                _browserFileList.Remove(mozillaFile);
                _browserFileList.Insert(1, mozillaFile);
            }

            if (operaFile != null) {
                _browserFileList.Remove(operaFile);
                _browserFileList.Insert(2, operaFile);
            }
//#endif
            foreach (string fileName in _browserFileList) {
                XmlDocument doc = new ConfigXmlDocument();
                try {
                    doc.Load(fileName);

                    XmlNode rootNode = doc.DocumentElement;
                    if(rootNode.Name != "browsers") {
                        if(useVirtualPath) {
                            throw new HttpParseException(SR.GetString(SR.Invalid_browser_root), null /*innerException*/, virtualDir + "/" + NoPathFileName(fileName), null /*sourceCode*/, 1);
                        }
                        else {
                            throw new HttpParseException(SR.GetString(SR.Invalid_browser_root), null /*innerException*/, fileName, null /*sourceCode*/, 1);
                        }
                    }

                    foreach (XmlNode node in rootNode.ChildNodes) {
                        if (node.NodeType != XmlNodeType.Element)
                            continue;
                        if (node.Name == "browser" || node.Name == "gateway") { 
                            ProcessBrowserNode(node, _browserTree);
                        }
                        else if (node.Name == "defaultBrowser") {
                            ProcessBrowserNode(node, _defaultTree);
                        }
                        else {
                            HandlerBase.ThrowUnrecognizedElement(node);
                        }
                    }
                }
                catch (XmlException e) {
                    if(useVirtualPath) {
                        throw new HttpParseException(e.Message, null /*innerException*/, virtualDir + "/" + NoPathFileName(fileName), null /*sourceCode*/, e.LineNumber);
                    }
                    else {
                        throw new HttpParseException(e.Message, null /*innerException*/, fileName, null /*sourceCode*/, e.LineNumber);
                    }
                }
                catch (XmlSchemaException e) {
                    if(useVirtualPath) {
                        throw new HttpParseException(e.Message, null /*innerException*/, virtualDir + "/" + NoPathFileName(fileName), null /*sourceCode*/, e.LineNumber);
                    }
                    else {
                        throw new HttpParseException(e.Message, null /*innerException*/, fileName, null /*sourceCode*/, e.LineNumber);
                    }
                }
            }
            NormalizeAndValidateTree(_browserTree, false);
            NormalizeAndValidateTree(_defaultTree, true);

            BrowserDefinition defaultBrowser = (BrowserDefinition)_browserTree["Default"];

            if (defaultBrowser != null) {
                AddBrowserToCollectionRecursive(defaultBrowser, 0);
            }
        }
Пример #52
0
 public ConfigXmlComment(ConfigXmlDocument document, string comment)
     : base(comment, document)
 {
     fileName   = document.fileName;
     lineNumber = document.LineNumber;
 }
        // 
        // ResolveFiles - parse files referenced with <file src="" />
        //
        static void ResolveFiles(ParseState parseState, object configurationContext) {

            //
            // 1) get the directory of the configuration file currently being parsed
            //

            HttpConfigurationContext httpConfigurationContext = (HttpConfigurationContext) configurationContext;
            string configurationDirectory = null;
            bool useAssert = false;

            //
            // Only assert to read cap files when parsing machine.config 
            // (allow device updates to work in restricted trust levels).
            //
            // Machine.config can be securely identified by the context being 
            // an HttpConfigurationContext with null path.
            //
            try {
                if (httpConfigurationContext.VirtualPath == null) {
                    useAssert = true;
                    // we need to assert here to get the file path from ConfigurationException
                    FileIOPermission fiop = new FileIOPermission(PermissionState.None);
                    fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
                    fiop.Assert();
                }
                
                Pair pair0 = (Pair)parseState.FileList[0];
                XmlNode srcAttribute = (XmlNode)pair0.Second;
                configurationDirectory = Path.GetDirectoryName(ConfigurationErrorsException.GetFilename(srcAttribute));
            }
            finally {
                if (useAssert) {
                    CodeAccessPermission.RevertAssert();
                }
            }

            //
            // 2) iterate through list of referenced files, builing rule lists for each
            //
            foreach (Pair pair in parseState.FileList) {
                string srcFilename = (string)pair.First;
                string fullFilename = Path.Combine(configurationDirectory, srcFilename);

                XmlNode section;
                try {
                    if (useAssert) {
                        InternalSecurityPermissions.FileReadAccess(fullFilename).Assert();
                    }
                    
                    Exception fcmException = null;
                    
                    try {
                        HttpConfigurationSystem.AddFileDependency(fullFilename);
                    }
                    catch (Exception e) {
                        fcmException = e;
                    }

                    ConfigXmlDocument configDoc = new ConfigXmlDocument();
                    
                    try {
                        configDoc.Load(fullFilename);
                        section = configDoc.DocumentElement;
                    }
                    catch (Exception e) {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Error_loading_XML_file, fullFilename, e.Message), 
                                        e, (XmlNode)pair.Second);
                    }

                    if (fcmException != null) {
                        throw fcmException;
                    }
                }
                finally {
                    if (useAssert) {
                        // Cannot apply next FileReadAccess PermissionSet unless 
                        // current set is explicitly reverted.  Also minimizes
                        // granted permissions.
                        CodeAccessPermission.RevertAssert();
                    }
                }
                
                if (section.Name != parseState.SectionName) {
                    throw new ConfigurationErrorsException(SR.GetString(SR.Capability_file_root_element, parseState.SectionName), 
                                    section);
                }
                    
                HandlerBase.CheckForUnrecognizedAttributes(section);

                ArrayList sublist = RuleListFromElement(parseState, section, true);

                if (sublist.Count > 0) {
                    parseState.RuleList.Add(new CapabilitiesSection(CapabilitiesRule.Filter, null, null, sublist));
                }
            }
        }