Load() публичный Метод

public Load ( string filename ) : void
filename string
Результат void
		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 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
     {
     }
 }
Пример #3
0
 public void load(string filename)
 {
     try
     {
         config.Load(filename);
         if (config["Settings"] != null)
         {
             if (config["Settings"].Attributes["Version"] == null)
             {
                 DatabaseConfig dbconfig = LoadDatabaseConfig(config["Settings"]);
                 if (dbconfig != null)
                 {
                     MasterDatabaseConfig = dbconfig;
                     //DBType = dbconfig.DBType;
                     //ConnectionString = dbconfig.ConnectionString;
                 }
             }
             else if (config["Settings"].Attributes["Version"].Value == "2.0")
             {
                 XmlNodeList dbConfigXmlList = config["Settings"].GetElementsByTagName("MasterDatabaseConfig");
                 foreach (XmlElement dbConfigXML in dbConfigXmlList)
                 {
                     MasterDatabaseConfig = LoadDatabaseConfig(dbConfigXML);
                 }
             }
         }
     }
     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
        /// <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);
            }
        }
Пример #6
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);
        }
Пример #7
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);
        }
Пример #8
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);
        }
Пример #9
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));
        }
Пример #10
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;
			}
Пример #12
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();
                            }
                        }
                    }
                }
            }
        }
        ;
    }
Пример #13
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);
            }
        }
        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;
      }
    }
Пример #16
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);
        }
Пример #17
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;
 }
Пример #19
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;
        }
Пример #21
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
            }
        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
        }
Пример #23
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));
        }
 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);
 }
Пример #27
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);
            }
        }
        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);
            }
        }
        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);
        }
Пример #33
0
        private static NameValueCollection LoadGlobalSettings()
        {
            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");
                    System.Configuration.NameValueSectionHandler nvsh = new System.Configuration.NameValueSectionHandler();
                    objCol = (NameValueCollection)nvsh.Create(null, null, objDoc.SelectSingleNode("General.Configuration/GlobalSettings"));
                }
                else if (System.IO.File.Exists(General.Environment.Current.GetAppDirectory() + "General.config"))
                {
                    objDoc.Load(General.Environment.Current.GetAppDirectory() + "General.config");
                    System.Configuration.NameValueSectionHandler nvsh = new System.Configuration.NameValueSectionHandler();
                    objCol = (NameValueCollection)nvsh.Create(null, null, objDoc.SelectSingleNode("General.Configuration/GlobalSettings"));
                }
                else
                {
                    objCol = null;
                    //throw new System.IO.FileNotFoundException("General.config could not be loaded");
                }
            }
            catch
            {
                objCol = null;
            }
            return objCol;
        }
        // 
        // 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));
                }
            }
        }
		public void GetFilename2 ()
		{
			XmlNode node;
			string filename;

			string xmlfile = Path.Combine (foldername, "test.xml");
			XmlDocument doc = new XmlDocument ();
			doc.AppendChild (doc.CreateElement ("test"));
			doc.Save (xmlfile);

			node = new XmlDocument ();
			filename = ConfigurationErrorsException.GetFilename (node);
			Assert.IsNull (filename, "#1");

			doc = new XmlDocument ();
			doc.Load (xmlfile);

			node = doc.DocumentElement;
			filename = ConfigurationErrorsException.GetFilename (node);
			Assert.IsNull (filename, "#2");

			doc = new ConfigXmlDocument ();
			doc.Load (xmlfile);

			node = doc.DocumentElement;
			filename = ConfigurationErrorsException.GetFilename (node);
			Assert.AreEqual (xmlfile, filename, "#3");
		}
Пример #36
0
    public void load(string filename)
    {
        MasterDatabaseConfig = null;

        try
        {
            config.Load(filename);
            if (config["Settings"] != null)
            {
                if (config["Settings"].Attributes["Version"] == null)
                {
                    DatabaseConfig dbconfig = LoadDatabaseConfig(config["Settings"]);
                    if (dbconfig != null)
                    {
                        DatabaseConfigList.Add(dbconfig);
                        //DBType = dbconfig.DBType;
                        //ConnectionString = dbconfig.ConnectionString;
                    }
                    if (config["Settings"]["ShutdownAfterUsed"] != null)
                    {
                        string strShutdownAfterUsed = config["Settings"]["ShutdownAfterUsed"].InnerText;
                        if (strShutdownAfterUsed.Equals("Yes", StringComparison.CurrentCultureIgnoreCase) ||
                            strShutdownAfterUsed.Equals("True", StringComparison.CurrentCultureIgnoreCase))
                        {
                            ShutDownDomainAfterUsed = true;
                        }
                        else
                        {
                            ShutDownDomainAfterUsed = false;
                        }
                    }
                }
                else if (config["Settings"].Attributes["Version"].Value == "2.0")
                {
                    XmlNodeList masterDbConfigXmlList = config["Settings"].GetElementsByTagName("MasterDatabaseConfig");
                    foreach (XmlElement dbConfigXML in masterDbConfigXmlList)
                    {
                        MasterDatabaseConfig = LoadDatabaseConfig(dbConfigXML);
                    }

                    if (config["Settings"]["DatabaseEncryptKey"] != null)
                    {
                        databaseEncryptKey = config["Settings"]["DatabaseEncryptKey"].InnerText;
                    }
                    if (config["Settings"]["UsePDFCreator"] != null)
                    {
                        string tmpValue = config["Settings"]["UsePDFCreator"].InnerText;
                        if (tmpValue.Equals("Yes", StringComparison.CurrentCultureIgnoreCase) ||
                            tmpValue.Equals("True", StringComparison.CurrentCultureIgnoreCase))
                        {
                            UsePDFCreator = true;
                        }
                        else
                        {
                            UsePDFCreator = false;
                        }
                    }
                    if (config["Settings"]["PDFCreatorPrinterName"] != null)
                    {
                        PDFCreatorPrinterName = config["Settings"]["PDFCreatorPrinterName"].InnerText;
                    }

                    if (MasterDatabaseConfig == null)
                    {
                        XmlNodeList dbConfigXmlList = config["Settings"].GetElementsByTagName("DatabaseConfig");
                        foreach (XmlElement dbConfigXML in dbConfigXmlList)
                        {
                            DatabaseConfig dbconfig = LoadDatabaseConfig(dbConfigXML);
                            if (dbconfig != null)
                            {
                                DatabaseConfigList.Add(dbconfig);
                                //DBType = dbconfig.DBType;
                                //ConnectionString = dbconfig.ConnectionString;
                            }
                        }
                        if (config["Settings"]["ShutdownAfterUsed"] != null)
                        {
                            string strShutdownAfterUsed = config["Settings"]["ShutdownAfterUsed"].InnerText;
                            if (strShutdownAfterUsed.Equals("Yes", StringComparison.CurrentCultureIgnoreCase) ||
                                strShutdownAfterUsed.Equals("True", StringComparison.CurrentCultureIgnoreCase))
                            {
                                ShutDownDomainAfterUsed = true;
                            }
                            else
                            {
                                ShutDownDomainAfterUsed = false;
                            }
                        }
                        if (config["Settings"]["AllowMultiDB"] != null)
                        {
                            string strAllowMultiDB = config["Settings"]["AllowMultiDB"].InnerText;
                            if (strAllowMultiDB.Equals("Yes", StringComparison.CurrentCultureIgnoreCase) ||
                                strAllowMultiDB.Equals("True", StringComparison.CurrentCultureIgnoreCase))
                            {
                                AllowMultiDB = true;
                            }
                            else
                            {
                                AllowMultiDB = false;
                            }
                        }
                        if (config["Settings"]["GenerateReportAsInbox"] != null)
                        {
                            string tmpValue = config["Settings"]["GenerateReportAsInbox"].InnerText;
                            if (tmpValue.Equals("Yes", StringComparison.CurrentCultureIgnoreCase) ||
                                tmpValue.Equals("True", StringComparison.CurrentCultureIgnoreCase))
                            {
                                GenerateReportAsInbox = true;
                            }
                            else
                            {
                                GenerateReportAsInbox = false;
                            }
                        }
                        if (config["Settings"]["EncryptedURLQueryString"] != null)
                        {
                            string tmpValue = config["Settings"]["EncryptedURLQueryString"].InnerText;
                            if (tmpValue.Equals("Yes", StringComparison.CurrentCultureIgnoreCase) ||
                                tmpValue.Equals("True", StringComparison.CurrentCultureIgnoreCase))
                            {
                                EncryptedURLQueryString = true;
                            }
                            else
                            {
                                EncryptedURLQueryString = false;
                            }
                        }
                        // Start 0000134, Ricky So, 2014-11-21
                        if (config["Settings"]["SkipEncryptionToDB"] != null)
                        {
                            string tmpValue = config["Settings"]["SkipEncryptionToDB"].InnerText;
                            if (tmpValue.Equals("Yes", StringComparison.CurrentCultureIgnoreCase) ||
                                tmpValue.Equals("True", StringComparison.CurrentCultureIgnoreCase))
                            {
                                SkipEncryptionToDB = true;
                            }
                            else
                            {
                                SkipEncryptionToDB = false;
                            }
                        }
                        // End 0000134, Ricky So, 2014-11-21
                    }
                    else
                    {
                        GenerateReportAsInbox   = true;
                        EncryptedURLQueryString = true;
                    }
                }
            }
        }
        catch
        {
        }
    }
		// 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
				}
Пример #38
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;
		}
		public void GetLineNumber2 ()
		{
			XmlNode node;
			int line;

			string xmlfile = Path.Combine (foldername, "test.xml");
			XmlDocument doc = new XmlDocument ();
			doc.AppendChild (doc.CreateElement ("test"));
			doc.Save (xmlfile);

			node = new XmlDocument ();
			line = ConfigurationErrorsException.GetLineNumber (node);
			Assert.AreEqual (0, line, "#1");

			doc = new XmlDocument ();
			doc.Load (xmlfile);

			node = doc.DocumentElement;
			line = ConfigurationErrorsException.GetLineNumber (node);
			Assert.AreEqual (0, line, "#2");

			doc = new ConfigXmlDocument ();
			doc.Load (xmlfile);

			node = doc.DocumentElement;
			line = ConfigurationErrorsException.GetLineNumber (node);
			Assert.AreEqual (1, line, "#3");
		}
Пример #40
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);
        }
Пример #41
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);
            }
		}
Пример #42
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;
            */
        }
Пример #43
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;
             */
        }
Пример #44
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;
        }
Пример #45
0
 public void Configure(string configFilePath)
 {
     string keyAttriuteName = "key", valueAttributeName = "value";
     Check.IsNotEmpty(configFilePath, "configFilePath");
     configFilePath=Util.GetFullPath(configFilePath);
     if (!File.Exists(configFilePath))
     {
         throw new FileNotFoundException(String.Format(AppCommon.File_Not_Found, configFilePath));
     }
     ConfigXmlDocument document1 = new ConfigXmlDocument();
     try
     {
         document1.Load(configFilePath);
     }
     catch (XmlException exception1)
     {
         throw new ConfigurationErrorsException(exception1.Message, exception1, configFilePath, exception1.LineNumber);
     }
     XmlNode section = document1.DocumentElement;
     _locker.EnterWriteLock();
     try
     {
         _readonlyCollection = new ReadOnlyNameValueCollection(StringComparer.OrdinalIgnoreCase);
         HandlerBase.CheckForUnrecognizedAttributes(section);
         foreach (XmlNode node1 in section.ChildNodes)
         {
             if (!HandlerBase.IsIgnorableAlsoCheckForNonElement(node1))
             {
                 if (node1.Name == "add")
                 {
                     string text1 = HandlerBase.RemoveRequiredAttribute(node1, keyAttriuteName);
                     string text2 = HandlerBase.RemoveRequiredAttribute(node1, valueAttributeName, true);
                     HandlerBase.CheckForUnrecognizedAttributes(node1);
                     _readonlyCollection[text1] = text2;
                 }
                 else
                 {
                     if (node1.Name == "remove")
                     {
                         string text3 = HandlerBase.RemoveRequiredAttribute(node1, keyAttriuteName);
                         HandlerBase.CheckForUnrecognizedAttributes(node1);
                         _readonlyCollection.Remove(text3);
                         continue;
                     }
                     if (node1.Name.Equals("clear"))
                     {
                         HandlerBase.CheckForUnrecognizedAttributes(node1);
                         _readonlyCollection.Clear();
                         continue;
                     }
                     HandlerBase.ThrowUnrecognizedElement(node1);
                 }
             }
         }
         _readonlyCollection.SetReadOnly();
     }
     finally
     {
         _locker.ExitWriteLock();
     }
     FileWatchHandler fileWatchHandler = new FileWatchHandler(this, new FileInfo(configFilePath));
     fileWatchHandler.StartWatching();
 }
		public void Constructor6 ()
		{
			string msg;
			Exception inner;
			XmlNode node;
			ConfigurationErrorsException cee;

			string xmlfile = Path.Combine (foldername, "test.xml");
			XmlDocument doc = new XmlDocument ();
			doc.AppendChild (doc.CreateElement ("test"));
			doc.Save (xmlfile);

			msg = "MSG";
			inner = new Exception ();
			node = new XmlDocument ();
			cee = new ConfigurationErrorsException (msg, inner, node);
			Assert.AreSame (msg, cee.BareMessage, "#A1");
			Assert.IsNotNull (cee.Data, "#A2");
			Assert.AreEqual (0, cee.Data.Count, "#A3");
			Assert.IsNull (cee.Filename, "#A4");
			Assert.AreSame (inner, cee.InnerException, "#A5");
			Assert.AreEqual (0, cee.Line, "#A6");
			Assert.AreSame (msg, cee.Message, "#A7");

			doc = new XmlDocument ();
			doc.Load (xmlfile);

			msg = null;
			inner = null;
			node = doc.DocumentElement;
			cee = new ConfigurationErrorsException (msg, inner, node);
			Assert.AreEqual (new ConfigurationErrorsException ().Message, cee.BareMessage, "#B1");
			Assert.IsNotNull (cee.Data, "#B2");
			Assert.AreEqual (0, cee.Data.Count, "#B3");
			Assert.IsNull (cee.Filename, "#B4");
			Assert.AreSame (inner, cee.InnerException, "#B5");
			Assert.AreEqual (0, cee.Line, "#B6");
			Assert.AreEqual (cee.BareMessage, cee.Message, "#B7");

			doc = new ConfigXmlDocument ();
			doc.Load (xmlfile);

			msg = null;
			inner = null;
			node = doc.DocumentElement;
			cee = new ConfigurationErrorsException (msg, inner, node);
			Assert.AreEqual (new ConfigurationErrorsException ().Message, cee.BareMessage, "#C1");
			Assert.IsNotNull (cee.Data, "#C2");
			Assert.AreEqual (0, cee.Data.Count, "#C3");
			Assert.AreEqual (xmlfile, cee.Filename, "#C4");
			Assert.AreSame (inner, cee.InnerException, "#C5");
			Assert.AreEqual (1, cee.Line, "#C6");
			Assert.AreEqual (cee.BareMessage + " (" + xmlfile + " line 1)", cee.Message, "#C7");

			msg = null;
			inner = null;
			node = null;
			cee = new ConfigurationErrorsException (msg, inner, node);
			Assert.AreEqual (new ConfigurationErrorsException ().Message, cee.BareMessage, "#D1");
			Assert.IsNotNull (cee.Data, "#D2");
			Assert.AreEqual (0, cee.Data.Count, "#D3");
			Assert.IsNull (cee.Filename, "#D4");
			Assert.AreSame (inner, cee.InnerException, "#D5");
			Assert.AreEqual (0, cee.Line, "#D6");
			Assert.AreEqual (cee.BareMessage, cee.Message, "#D7");
		}