예제 #1
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 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);
        }
예제 #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);
        }
예제 #4
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;
                        }
                    }
                }
            }
        }
예제 #5
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;
            }
        }
        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);
        }
예제 #7
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);
        }
예제 #8
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);
            }
        }
예제 #9
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();
        }
예제 #10
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);
        }
예제 #11
0
        public object Create(object parent, object configContext, XmlNode section)
        {
            WindowFactory.AddSpecializedWindowFactory(new BrowserWindowFactory());

            NameValueSectionHandler sectionHandler = new NameValueSectionHandler();

            return(sectionHandler.Create(parent, configContext, section));
        }
예제 #12
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);
        }
예제 #13
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);
        }
예제 #14
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);
 }
예제 #15
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));
        }
예제 #16
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);
        }
예제 #17
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();
        }
예제 #18
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));
            }
        }
예제 #19
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"]);
            }
        }
예제 #20
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"]);
            }
        }
예제 #21
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);
        }
예제 #22
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);
            }
예제 #23
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);
            }
        }
예제 #24
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));
        }
예제 #25
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());
        }
예제 #26
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;
                        }
                    }
                }
            }
        }
예제 #27
0
파일: Mqtt.cs 프로젝트: mhwlng/fiphwinfo
        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);
        }