Esempio n. 1
0
        public static void Start()
        {
            string configurationFilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Quartz.config");

            var configurationFileMap = new ExeConfigurationFileMap {
                ExeConfigFilename = configurationFilepath
            };
            var configuration = ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, ConfigurationUserLevel.None);

            System.Xml.XmlDocument sectionXmlDocument = new System.Xml.XmlDocument();
            sectionXmlDocument.Load(new StringReader(configuration.GetSection("quartz").SectionInformation.GetRawXml()));
            NameValueSectionHandler handler = new NameValueSectionHandler();

            var quartzProperties = (NameValueCollection)handler.Create(null, null, sectionXmlDocument.DocumentElement);

            LogProvider.SetCurrentLogProvider(new Areas.CmsAdmin.Scheduler.EntLibLogProvider());

            var logEntiry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry();

            logEntiry.Title    = "Scheduler Event";
            logEntiry.Severity = System.Diagnostics.TraceEventType.Start;
            logEntiry.Message  = "Restart the scheduler has been completed";
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(logEntiry);

            IUnityContainer unityContainer = new UnityContainer();

            ConfigUnityContainer(unityContainer);
            unityContainer.AddExtension(new QuartzUnityExtension(quartzProperties));
            unityContainer.Resolve <IScheduler>().Start();
        }
Esempio n. 2
0
        static void load()
        {
            if (!File.Exists("settings.xml"))
            {
                Application.Run(new MessageWindow("Not find 'settings.xml'"));
                return;
            }

            XmlDocument doc = new XmlDocument();

            doc.Load("settings.xml");

            XmlNode xNode = doc.GetElementsByTagName("settings").Item(0);

            IConfigurationSectionHandler csh = new NameValueSectionHandler();
            NameValueCollection          nvc = (NameValueCollection)csh.Create(null, null, xNode);

            JAVA_HOME = nvc.Get("JAVA_HOME");
            XMS       = nvc.Get("XMS");
            XMX       = nvc.Get("XMX");

            if (JAVA_HOME == null)
            {
                Application.Run(new MessageWindow("Not find 'JAVA_HOME' in 'settings.xml'"));
                return;
            }
            if (!File.Exists(JAVA_HOME + "javaw.exe"))
            {
                Application.Run(new MessageWindow("Not find javaw.exe in 'JAVA_HOME'"));
                return;
            }
        }
Esempio n. 3
0
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            NameValueSectionHandler baseHandler = new NameValueSectionHandler();
            NameValueCollection     configs     = (NameValueCollection)baseHandler.Create(parent, configContext, section);

            return(configs);
        }
Esempio n. 4
0
        bool IConfigurationProvider.TryGetNameValueCollectionSection(string section, out NameValueCollection collection)
        {
            ConfigurationSection configurationSection = GetSection(section);

            if (configurationSection == null)
            {
                collection = null;
                return(false);
            }

            string xml = configurationSection.SectionInformation.GetRawXml();
            var    sectionXmlDocument = new XmlDocument();

            sectionXmlDocument.LoadXml(xml);
            if (sectionXmlDocument.DocumentElement == null)
            {
                collection = null;
                return(false);
            }

            var handler = new NameValueSectionHandler();

            collection = handler.Create(null, null, sectionXmlDocument.DocumentElement) as NameValueCollection;
            return(collection != null);
        }
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            NameValueSectionHandler handler = new NameValueSectionHandler();
            OrderedHashTable        schemes = new OrderedHashTable();

            NameValueCollection options = (NameValueCollection)
                                          handler.Create(parent, configContext, section);

            if (options != null)
            {
                foreach (string key in options.Keys)
                {
                    Type type = Type.GetType(options[key]);
                    if (type == null)
                    {
                        throw new ConfigurationException(string.Format("Type '{0}' not found", key));
                    }
                    if (!typeof(IAMQCallbackHandler).IsAssignableFrom(type))
                    {
                        throw new ConfigurationException(string.Format("Type '{0}' does not implement IAMQCallbackHandler", key));
                    }

                    schemes.Add(key, type);
                }
            }

            return(schemes);
        }
Esempio n. 6
0
        public Object Create(Object parent, object configContext, XmlNode section)
        {
            NameValueCollection settings;

            try
            {
                NameValueSectionHandler baseHandler = new NameValueSectionHandler();
                settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);
            }
            catch
            {
                settings = null;
            }

            if (settings != null)
            {
                dbServiceName                 = ReadSetting(settings, "dbServiceName", "JsonDbOpensocialService");
                allowUnauthenticated          = ReadSetting(settings, "allowUnauthenticated", "true");
                gadgetDebug                   = ReadSetting(settings, "gadgetDebug", "true");
                tokenMaxAge                   = ReadSetting(settings, "tokenMaxAge", "3600");
                gadgetCacheXmlRefreshInterval = ReadSetting(settings, "gadgetCacheXmlRefreshInterval", "300000");
                containerUrlPrefix            = ReadSetting(settings, "containerUrlPrefix", "");
                tokenMasterKey                = ReadSetting(settings, "tokenMasterKey", "INSECURE_DEFAULT_KEY");
                javaPath = ReadSetting(settings, "javaPath", @"c:\program files\java\jdk1.6.0_12\bin\java.exe");
            }

            return(null);
        }
Esempio n. 7
0
        public Object Create(Object parent, object configContext, XmlNode section)
        {
            NameValueCollection settings;

            try
            {
                NameValueSectionHandler baseHandler = new NameValueSectionHandler();
                settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);
            }
            catch
            {
                settings = null;
            }

            if (settings != null)
            {
                language                   = ReadSetting(settings, "language", "en_US");
                web_prefix                 = ReadSetting(settings, "web_prefix", "");
                container                  = ReadSetting(settings, "container", "default");
                ifr_uri                    = ReadSetting(settings, "ifr_uri", "/gadgets/ifr?");
                gadget_server              = ReadSetting(settings, "gadget_server", "http://localhost/");
                st_max_age                 = ReadSetting(settings, "st_max_age", "3600");
                site_root                  = ReadSetting(settings, "site_root", "");
                enable_caching             = string.Compare(bool.TrueString, ReadSetting(settings, "enable_caching", "true")) == 0;
                enable_facebookConnect     = string.Compare(bool.TrueString, ReadSetting(settings, "enable_facebookConnect", "true")) == 0;
                enable_googleFriendConnect = string.Compare(bool.TrueString, ReadSetting(settings, "enable_googleFriendConnect", "true")) == 0;
                fb_api_session_key         = ReadSetting(settings, "fb_api_session_key", "");
                fb_api_session_userid      = long.Parse(ReadSetting(settings, "fb_api_session_userid", ""));
                gfc_key                    = ReadSetting(settings, "gfc_key", "");
            }

            return(null);
        }
        /// <summary>
        /// Gets the handler for a config section
        /// </summary>
        /// <param name="sectionName">Name of the section</param>
        /// <param name="xmlDoc">XML document containing the config</param>
        /// <returns>Handler for a config section</returns>
        private static IConfigurationSectionHandler GetHandler(string sectionName, XmlDocument xmlDoc)
        {
            IConfigurationSectionHandler handler = null;

            handler = new NameValueSectionHandler();
            return(handler);
        }
        /// <summary>
        /// Gets the handler for a config section
        /// </summary>
        /// <param name="sectionName">Name of the handler</param>
        /// <param name="parentHandler">Handler of the parent section</param>
        /// <param name="xmlDoc">XML document containing the config</param>
        /// <returns>Handler for a config section</returns>
        private static object GetAppSettingsFileHandler(string sectionName, IConfigurationSectionHandler parentHandler, XmlDocument xmlDoc)
        {
            object       handler = null;
            XmlNode      node    = xmlDoc.SelectSingleNode("//" + sectionName);
            XmlAttribute att     = (XmlAttribute)node.Attributes.RemoveNamedItem("file");

            if (att == null || att.Value == null || att.Value.Length == 0)
            {
                return(parentHandler.Create(null, null, node));
            }
            else
            {
                string      fileName = att.Value;
                string      dir      = Path.GetDirectoryName(fileName);
                string      fullName = Path.Combine(dir, fileName);
                XmlDocument xmlDoc2  = new XmlDocument();
                xmlDoc2.Load(fullName);

                object parent = parentHandler.Create(null, null, node);
                IConfigurationSectionHandler h = new NameValueSectionHandler();
                handler = h.Create(parent, null, xmlDoc2.DocumentElement);
            }

            return(handler);
        }
Esempio n. 10
0
        public bool GetValue(string section, string key, out string value)
        {
            value = null;

            try
            {
                var configFileMap = new ExeConfigurationFileMap()
                {
                    ExeConfigFilename = Configfile
                };
                var appConfig             = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
                var sectionProduct        = appConfig.GetSection(section);
                var myParamsSectionRawXml = sectionProduct.SectionInformation.GetRawXml();
                var sectionXmlDoc         = new XmlDocument();
                sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml));
                var sectionHandler = new NameValueSectionHandler();
                NameValueCollection sectionHandlerCollection = sectionHandler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;
                value = sectionHandlerCollection[key];
                ConfigurationManager.RefreshSection("//" + section);

                if (value == null)
                {
                    return(false);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 11
0
        private void ParseConfig(string s)
        {
            var h = new NameValueSectionHandler();

            using (var ms = new MemoryStream())
            {
                byte[] bs = Encoding.UTF8.GetBytes(s);
                ms.Write(bs, 0, bs.Length);
                ms.Flush();
                ms.Position = 0;
                var xd = new XmlDocument();
                xd.Load(ms);

                XmlElement node = xd["configuration"];
                if (node == null)
                {
                    throw new SettingException("配置选项没有找到.");
                }

                foreach (XmlNode n in node.ChildNodes)
                {
                    if (n.Name != "configSections")
                    {
                        var l = (NameValueCollection)h.Create(null, null, n);
                        lock (_xmlConfigs)
                        {
                            _xmlConfigs[n.Name] = l;
                        }
                    }
                }
            }
        }
Esempio n. 12
0
        public object Create(object parent, object configContext, XmlNode section)
        {
            WindowFactory.AddSpecializedWindowFactory(new BrowserWindowFactory());

            NameValueSectionHandler sectionHandler = new NameValueSectionHandler();

            return(sectionHandler.Create(parent, configContext, section));
        }
Esempio n. 13
0
        public Object Create(Object parent, object configContext, XmlNode section)
        {
            NameValueCollection settings;

            NameValueSectionHandler baseHandler = new NameValueSectionHandler();

            settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);

            return(settings);
        }
Esempio n. 14
0
        /// <summary>
        /// 实现接口方法
        /// </summary>
        /// <param name="parent"> 父对象。</param>
        /// <param name="configContext">配置上下文对象。</param>
        /// <param name="section">节 XML 节点。</param>
        /// <returns></returns>
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            //表示可通过键或索引访问的关联 String 键和 String 值的集合。
            NameValueCollection configs;

            //提供配置节中的名称/值对配置信息。NameValueSectionHandler 这个类也继承IConfigurationSectionHandler
            NameValueSectionHandler baseHandler = new NameValueSectionHandler();

            configs = (NameValueCollection)baseHandler.Create(parent, configContext, section);
            return(configs);
        }
Esempio n. 15
0
 /// <summary>
 ///     Called from OnApplicationStart to initialize settings from
 ///     the Web.Config file(s).
 ///     <remarks>
 ///         The app domain will restart if settings change, so there is
 ///         no reason to read these values more than once. This funtion
 ///         uses the NameValueSectionHandler base class to generate a
 ///         hashtablefrom the XML, which is then used to store the current
 ///         settings.  Because all settings are read here, we do not actually
 ///         store the generated hashtable object for later retrieval by
 ///         Context.GetConfig. The application should use the accessor
 ///         functions directly.
 ///     </remarks>
 ///     <param name="parent">An object created by processing a section
 ///         with this name in a Config.Web file in a parent directory.
 ///     </param>
 ///     <param name="configContext">The config's context.</param>
 ///     <param name="section">The section to be read.</param>
 ///     <retvalue>
 ///		    <para>
 ///             A ConfigOutput object: which we leave empty because all settings
 ///             are stored at this point.
 ///		    </para>
 ///		    <para>
 ///             null:  if there was an error.
 ///		    </para>
 ///	    </retvalue>
 /// </summary>
 public Object Create(Object parent, object configContext, XmlNode section)
 {
     try
     {
         NameValueSectionHandler baseHandler = new NameValueSectionHandler();
         _settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);
     }
     catch
     {
         _settings = null;
     }
     return(null);
 }
    public object Create(object parent, object configContext, XmlNode section)
    {
        object  result        = parent;
        XmlNode fileAttribute = section.Attributes.RemoveNamedItem("file");

        if (fileAttribute == null && fileAttribute.Value.Length == 0)
        {
            return(new NameValueSectionHandler().Create(result, null, section));
        }
        IConfigErrorInfo configXmlNode = fileAttribute as IConfigErrorInfo;

        if (configXmlNode == null)
        {
            return(null);
        }

        string directory        = Path.GetDirectoryName(configXmlNode.Filename);
        string absoluteFilePath = Path.GetFullPath(directory + fileAttribute.Value);

        if (!File.Exists(absoluteFilePath))
        {
            throw new ConfigurationErrorsException(string.Format("external config file: {0} does not exists", absoluteFilePath));
        }
        var configXmlDocument = new ConfigXmlDocument();

        try
        {
            configXmlDocument.Load(absoluteFilePath);
        }
        catch (XmlException e)
        {
            throw new ConfigurationErrorsException(e.Message, e, absoluteFilePath, e.LineNumber);
        }
        if (section.Name != configXmlDocument.DocumentElement.Name)
        {
            throw new ConfigurationErrorsException(string.Format("Section name '{0}' in app.config does not match section name '{1}' in file '{2}'", section.Name, configXmlDocument.DocumentElement.Name, absoluteFilePath));
        }

        var nodeToDecrypt = configXmlDocument.DocumentElement["EncryptedData"];

        if (nodeToDecrypt == null)
        {
            throw new ConfigurationErrorsException(string.Format("External encrypted file {0} does not contain EncryptedData element", absoluteFilePath));
        }
        var protectionProvider     = new DpapiProtectedConfigurationProvider();
        var decryptedConfigSection = protectionProvider.Decrypt(nodeToDecrypt);

        result = new NameValueSectionHandler().Create(result, null, decryptedConfigSection);

        return(result);
    }
Esempio n. 17
0
        private static NameValueCollection WeChatConfigInitialize()
        {
            string configurationFilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WeChat.config");

            var configurationFileMap = new ExeConfigurationFileMap {
                ExeConfigFilename = configurationFilepath
            };
            var configuration = ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, ConfigurationUserLevel.None);

            System.Xml.XmlDocument sectionXmlDocument = new System.Xml.XmlDocument();
            sectionXmlDocument.Load(new StringReader(configuration.GetSection("wechat").SectionInformation.GetRawXml()));
            NameValueSectionHandler handler = new NameValueSectionHandler();

            return((NameValueCollection)handler.Create(null, null, sectionXmlDocument.DocumentElement));
        }
        /// <summary>
        /// Gets the handler.
        /// </summary>
        /// <param name="sectionName">Name of the section.</param>
        /// <param name="xmlDoc">The XML doc.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        protected static IConfigurationSectionHandler GetHandler(string sectionName, XmlDocument xmlDoc)
        {
            IConfigurationSectionHandler handler = null;

            if (sectionName == APPSETTINGS_SECTION_NAME)
            {
                handler = new NameValueSectionHandler();
                return(handler);
            }

            string[] sections     = sectionName.Split('/');
            string   sectionGroup = string.Empty;
            string   section      = string.Empty;
            string   xPath        = string.Empty;

            //see if we have a section group that we have to go through
            if (sections.Length > 1)
            {
                sectionGroup = sections[0];
                section      = sections[1];

                xPath = string.Format(CONFIG_SECTIONS_PATH + "/" +
                                      CONFIG_SECTIONS_GROUP_PATH + "[@name='" + sectionGroup + "']/" +
                                      CONFIG_SECTION_PATH + "[@name='" + section + "']");
            }
            else
            {
                section = sections[0];

                xPath = string.Format(CONFIG_SECTIONS_PATH + "/" +
                                      CONFIG_SECTION_PATH + "[@name='" + section + "']");
            }

            XmlNode node = xmlDoc.SelectSingleNode(xPath);

            string typeName = node.Attributes["type", ""].Value;

            if (typeName == null || typeName.Length == 0)
            {
                return(handler);
            }

            Type handlerType = Type.GetType(typeName);

            handler = (IConfigurationSectionHandler)Activator.CreateInstance(handlerType);

            return(handler);
        }
Esempio n. 19
0
        public Object Create(Object parent, object configContext, XmlNode section)
        {
            NameValueCollection settings;

            try
            {
                NameValueSectionHandler baseHandler = new NameValueSectionHandler();
                settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);
            }
            catch (Exception exc)
            {
                Common.LogWriter.Instance.WriteEventLogEntry(exc);
                settings = null;
            }

            return(settings);
        }
Esempio n. 20
0
        public static void Start()
        {
            EngineContext.Initialize(false);
            var container = ServiceContainer.Current;

            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType <FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            //验证流
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
            UnityValidatorActivatorFactory validatorFactory = new UnityValidatorActivatorFactory(ServiceContainer.Current);

            ModelValidatorProviders.Providers.Insert(0, new FluentValidationModelValidatorProvider(validatorFactory));


            //企业库【异常/日志】
            var entLibConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs", "EntLibConfig.config");
            var configSouce      = new FileConfigurationSource(entLibConfigPath);
            ExceptionPolicyFactory exceptionPolicyFactory = new ExceptionPolicyFactory(configSouce);

            ExceptionPolicy.SetExceptionManager(exceptionPolicyFactory.CreateManager());

            LogWriterFactory logWriterFactory = new LogWriterFactory(configSouce);

            Logger.SetLogWriter(logWriterFactory.Create());

            //计划任务

            string configurationFilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs", "quartz.config");
            var    configurationFileMap  = new ExeConfigurationFileMap {
                ExeConfigFilename = configurationFilepath
            };
            var configuration = ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, ConfigurationUserLevel.None);

            System.Xml.XmlDocument sectionXmlDocument = new System.Xml.XmlDocument();

            sectionXmlDocument.Load(new StringReader(configuration.GetSection("quartz").SectionInformation.GetRawXml()));

            NameValueSectionHandler handler = new NameValueSectionHandler();

            NameValueCollection props = handler.Create(null, null, sectionXmlDocument.DocumentElement) as NameValueCollection;

            ServiceContainer.Current.AddExtension(new QuartzUnityExtension(props));
            EngineContext.Current.Resolve <ISchedulerProvider>("Quartz").Start();
        }
Esempio n. 21
0
        public static void load()
        {
            _message.Clear();

            var doc = new XmlDocument();

            doc.Load(DIR + "\\localization\\" + RConfig.Instance.Localization);

            XmlNode xNode = doc.GetElementsByTagName("localization").Item(0);
            IConfigurationSectionHandler csh = new NameValueSectionHandler();
            var nvc = (NameValueCollection)csh.Create(null, null, xNode);

            String[] msg = Enum.GetNames(typeof(Word));

            foreach (String st in msg)
            {
                _message.Add(st, get(nvc, st));
            }
        }
Esempio n. 22
0
        public void Test1()
        {
            var h = new NameValueSectionHandler();
            string s = ResourceHelper.ReadToEnd(this.GetType(), "UnitTest.config.xml");
            using (var ms = new MemoryStream())
            {
                byte[] bs = Encoding.UTF8.GetBytes(s);
                ms.Write(bs, 0, bs.Length);
                ms.Flush();
                ms.Position = 0;
                var xd = new XmlDocument();
                xd.Load(ms);

                var config = xd["configuration"];
                Assert.IsNotNull(config);
                var l = (NameValueCollection)h.Create(null, null, config.ChildNodes[1]);
                Assert.AreEqual("@ConsoleMessage | Leafing.UnitTest.SqlRecorder, Leafing.UnitTest", l["SqlLogRecorder"]);
                Assert.AreEqual("@Access : @~test.mdb", l["1.DataBase"]);
            }
        }
Esempio n. 23
0
        public void Test1()
        {
            var    h = new NameValueSectionHandler();
            string s = ResourceHelper.ReadToEnd(this.GetType(), "UnitTest.config.xml");

            using (var ms = new MemoryStream())
            {
                byte[] bs = Encoding.UTF8.GetBytes(s);
                ms.Write(bs, 0, bs.Length);
                ms.Flush();
                ms.Position = 0;
                var xd = new XmlDocument();
                xd.Load(ms);

                var config = xd["configuration"];
                Assert.IsNotNull(config);
                var l = (NameValueCollection)h.Create(null, null, config.ChildNodes[1]);
                Assert.AreEqual("@ConsoleMessage | Leafing.UnitTest.SqlRecorder, Leafing.UnitTest", l["SqlLogRecorder"]);
                Assert.AreEqual("@Access : @~test.mdb", l["1.DataBase"]);
            }
        }
Esempio n. 24
0
            public object Create(object parent, object configContext, XmlNode section)
            {
                NameValueCollection settings;

                try
                {
                    NameValueSectionHandler baseHandler = new NameValueSectionHandler();
                    settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);
                }
                catch
                {
                    settings = null;
                }

                if (settings != null)
                {
                    m_connectionString = AppConfig.ReadSetting(settings, "ConnectionString", String.Empty);
                    m_userCount        = Convert.ToInt32(AppConfig.ReadSetting(settings, "UserCount", "0"));
                }

                return(settings);
            }
Esempio n. 25
0
        private static void LoadAppSettings()
        {
            // Load the document

            XmlDocument configDoc = new XmlDocument();

            configDoc.Load(ConfigFileName);
            // Get the node settings
            XmlNode node = configDoc.SelectSingleNode("/configuration/appSettings");
            //XmlNode nodeRuntime = configDoc.SelectSingleNode("/configuration/runtime");
            //XmlNode nodeAssemblybinding = nodeRuntime.FirstChild;
            //XmlNode nodeProbing = nodeAssemblybinding.FirstChild;
            //XmlAttribute oAtt = configDoc.CreateAttribute("privatePath");
            //oAtt.Value = "lib;bin\\Debug\\lib" ;
            //nodeProbing.Attributes.Append(oAtt);


            // Get reference to the NameValueCollection holding the parsed values
            NameValueSectionHandler handler = new NameValueSectionHandler();

            _appSettingsCollection = (NameValueCollection)handler.Create(null, null, node);
        }
Esempio n. 26
0
        public bool GetChildren(string section, out string[] allKeys)
        {
            allKeys = null;
            var sectionHandler = new NameValueSectionHandler();

            try
            {
                var configFileMap = new ExeConfigurationFileMap()
                {
                    ExeConfigFilename = Configfile
                };

                var appConfig             = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
                var sectionProduct        = appConfig.GetSection(section);
                var myParamsSectionRawXml = sectionProduct.SectionInformation.GetRawXml();
                var sectionXmlDoc         = new XmlDocument();
                sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml));

                if (sectionXmlDoc.DocumentElement != null)
                {
                    NameValueCollection sectionHandlerCollection = sectionHandler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;
                    allKeys = sectionHandlerCollection.AllKeys;
                }

                if (allKeys == null)
                {
                    return(false);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// 创建新的配置处理程序并将其添加到节处理程序集合中。
        /// </summary>
        /// <param name="parent">对应父配置节中的配置设置。</param>
        /// <param name="configContext">配置节处理程序为其计算配置值的虚拟路径。通常,该参数是保留参数,并为空引用(Visual Basic 中为 Nothing)。 </param>
        /// <param name="section">包含要处理的配置信息的 XmlNode。提供对配置节 XML 内容的直接访问。</param>
        /// <returns>一个 NameValueCollection。</returns>
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            NameValueSectionHandler handler = new NameValueSectionHandler();

            return(handler.Create(parent, configContext, section));
        }
Esempio n. 28
0
        public static async Task <bool> Connect()
        {
            if (File.Exists(Path.Combine(App.ExePath, "mqtt.config")))
            {
                var configMap = new ExeConfigurationFileMap
                {
                    ExeConfigFilename = Path.Combine(App.ExePath, "mqtt.config")
                };

                var config =
                    ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

                var myParamsSection = config.GetSection("mqtt");

                var myParamsSectionRawXml = myParamsSection.SectionInformation.GetRawXml();
                var sectionXmlDoc         = new XmlDocument();
                sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml));
                var handler = new NameValueSectionHandler();

                var appSection =
                    handler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;

                mqttURI      = appSection["mqttURI"];
                mqttUser     = appSection["mqttUser"];
                mqttPassword = appSection["mqttPassword"];
                mqttPort     = Convert.ToInt32(appSection["mqttPort"]);
                mqttSecure   = appSection["mqttSecure"] == "True";

                if (string.IsNullOrEmpty(mqttURI))
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }

            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(ClientId)
                                 .WithCredentials(mqttUser, mqttPassword)
                                 .WithTcpServer(mqttURI, mqttPort)
                                 .WithCleanSession();

            var options = mqttSecure
              ? messageBuilder
                          .WithTls()
                          .Build()
              : messageBuilder
                          .Build();

            try
            {
                var result = await mqttClient.ConnectAsync(options, CancellationToken.None);

                if (result.ResultCode != MqttClientConnectResultCode.Success)
                {
                    App.Log.Error($"MQTT CONNECT FAILED: {result.ResultCode} {result.ReasonString}");
                }

                return(result.ResultCode == MqttClientConnectResultCode.Success);
            }
            catch (Exception ex)
            {
                // ignore this exception
                App.Log.Error($"MQTT CONNECT FAILED", ex);
            }

            return(false);
        }
Esempio n. 29
0
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            var settings = new NameValueSectionHandler();

            return(settings.Create(parent, configContext, section) as NameValueCollection ?? new NameValueCollection());
        }
        /// <summary>
        /// Creates a NameValueCollection of the keys and values in the
        /// configuration section
        /// </summary>
        /// <param name="parent">The parent configuration section as a namevaluecollection</param>
        /// <param name="configContext">For webconfig only, this is the context of the configuration</param>
        /// <param name="section">The xmlnode representing the config section</param>
        /// <returns>A name value collection with hte values in the config file, or the referenced
        /// user specific settings file.</returns>
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            string fileName;
            string fileDirectory;

            XmlNode             fileNameNode;
            NameValueCollection currentSettings;

            //get parent settings merged with local settings
            NameValueSectionHandler helperHandler = new NameValueSectionHandler();

            currentSettings = (NameValueCollection)parent;

            //if there was no parent, then create a new collection
            if (currentSettings == null)
            {
                currentSettings = new NameValueCollection();
            }

            try{
                MapNodeToCollection(section, ref currentSettings);


                //get file name if there is one
                fileNameNode = section.Attributes.RemoveNamedItem("file");

                //as long as there is a file, process it
                if (fileNameNode != null && fileNameNode.Value.Length > 0)
                {
                    fileName = fileNameNode.Value;

                    fileDirectory = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

                    //fileDirectory = Path.GetDirectoryName("web.config");

                    fileName = Path.Combine(fileDirectory, fileName);

                    if (File.Exists(fileName))
                    {
                        ConfigXmlDocument doc = new ConfigXmlDocument();

                        //load the file
                        try
                        {
                            doc.Load(fileName);
                        }
                        catch (XmlException xex)
                        {
                            throw new ConfigurationException(xex.Message, xex, fileName, xex.LineNumber);
                        }

                        //make sure the section name in the file matches the
                        //one in the config file
                        if (!section.Name.Equals(doc.DocumentElement.Name))
                        {
                            throw new ConfigurationException("Document root element in the file must match the section name in the original configuration file.", section);
                        }

                        //merge the current settings with the ones from the file
                        MapNodeToCollection(doc.DocumentElement, ref currentSettings);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ConfigurationException("Error in config file", ex);
            }

            return(currentSettings);
        }
Esempio n. 31
0
        private void ParseConfig(string s)
        {
            var h = new NameValueSectionHandler();
            using (var ms = new MemoryStream())
            {
                byte[] bs = Encoding.UTF8.GetBytes(s);
                ms.Write(bs, 0, bs.Length);
                ms.Flush();
                ms.Position = 0;
                var xd = new XmlDocument();
                xd.Load(ms);

                XmlElement node  = xd["configuration"];
                if (node == null)
                {
                    throw new SettingException("configuration section not found.");
                }

                foreach (XmlNode n in node.ChildNodes)
                {
                    if (n.Name != "configSections")
                    {
                        var l = (NameValueCollection)h.Create(null, null, n);
                        lock (_xmlConfigs)
                        {
                            _xmlConfigs[n.Name] = l;
                        }
                    }
                }
            }
        }