public void DoubleLoadMachineConfigTest()
 {
     ConfigurationFile machineConfig = new ConfigurationFile();
     machineConfig.Load(ConfigurationBuilder.MachineConfigurationFile);
     ConfigurationFile machineConfig2 = new ConfigurationFile(machineConfig);
     machineConfig2.Load(ConfigurationBuilder.MachineConfigurationFile);
 }
Example #2
0
        public ConfigurationPage(IWorkingEnvironment environment)
            : base(Guid)
        {
            Verify.Argument.IsNotNull(environment, "environment");

            _environment = environment;

            InitializeComponent();

            _lstSystemConfig.Style = GitterApplication.DefaultStyle;
            _lstUserConfig.Style = GitterApplication.DefaultStyle;

            _pageUser.Text = Resources.StrCurrentUser;
            _pageSystem.Text = Resources.StrSystem;

            _btnAddUserParameter.Text = Resources.StrAddParameter;
            _btnAddSystemParameter.Text = Resources.StrAddParameter;

            var gitAccessor = environment.RepositoryProviders
                                         .OfType<IGitRepositoryProvider>()
                                         .First()
                                         .GitAccessor;

            _userCfg	= ConfigurationFile.OpenCurrentUserFile(gitAccessor);
            _systemCfg	= ConfigurationFile.OpenSystemFile(gitAccessor);
            _lstUserConfig.LoadData(_userCfg);
            _lstSystemConfig.LoadData(_systemCfg);
        }
Example #3
0
		public static ITestingFramework GetFramework(ConfigurationFile configuration)
		{
			if (configuration.TestingFramework.To<string>().ToLower() == "xunit")
				return new XUnitTestingFramework();

			return new MsTestTestingFramework();
		}
 public void AppendSectionNoFileLoadedTest()
 {
     ConfigurationFile file = new ConfigurationFile();
     XmlDocument doc = new XmlDocument();
     XmlNode node = doc.CreateElement("tempElement");
     file.AppendSection("name", "MyType", node);
 }
Example #5
0
        private void btnLoadConfigFile_Click(object sender, EventArgs e)
        {
            Fwk.Configuration.Common.Key wKey;
            Fwk.Configuration.Common.Groups wGroups;
            Fwk.Configuration.Common.Group wGroup;
            wGroups = new Fwk.Configuration.Common.Groups();
            ConfigurationFile wConfigurationFile = new ConfigurationFile();
            wConfigurationFile.CurrentVersion = "1.1";
            wConfigurationFile.Encrypted = false;
        


            wGroup = new Fwk.Configuration.Common.Group();
            wGroup.Name = "G1";
            wKey = new Fwk.Configuration.Common.Key();
            wKey.Name = "K1";
            wKey.Value.Text= "aaaaaaaaaaaaaaaaa";

            wGroup.Keys.Add(wKey);

            wKey = new Fwk.Configuration.Common.Key();
            wKey.Name = "K2";
            wKey.Value.Text = "cccccccccccccccccccccccccccccccccc";
            wGroup.Keys.Add(wKey);


            wGroups.Add(wGroup);



           

            wGroup = new Fwk.Configuration.Common.Group();
            wGroup.Name = "G2";
            wKey = new Fwk.Configuration.Common.Key();
            wKey.Name = "K1";
            wKey.Value.Text = "aaaaaaaaaaaaaaaaa";

            wGroup.Keys.Add(wKey);

            wKey = new Fwk.Configuration.Common.Key();
            wKey.Name = "K2";
            wKey.Value.Text = "cccccccccccccccccccccccccccccccccc";
            wGroup.Keys.Add(wKey);


            wGroups.Add(wGroup);
            wConfigurationFile.Groups = wGroups;

            xmlConfitFile.Text = wConfigurationFile.GetXml();
            xmlConfitFile.ForeColor = Color.Green;
        }
Example #6
0
 public void Clear()
 {
     if(_repository != null)
     {
         DetachFromRepository();
         _repository = null;
     }
     if(_configurationFile != null)
     {
         DetachFromConfigFile();
         _configurationFile = null;
     }
 }
        private void Createcfg(string FilePath)
        {
            try
            {
                ConfigurationFile cfg = new ConfigurationFile();
                cfg.INSTANCEID = TxtINSTANCEID.Text;
                cfg.ACTION = TxtACTION.Text;
                cfg.HELP = CBHELP.Checked;
                cfg.INDICATEPROGRESS = CBINDICATEPROGRESS.Checked;
                cfg.QUIET = CBQUIET.Checked;
                cfg.QUIETSIMPLE = CBQUIETSIMPLE.Checked;
                cfg.X86 = CBX86.Checked;
                cfg.MEDIASOURCE = TxtMEDIASOURCE.Text;
                cfg.ERRORREPORTING = CBERRORREPORTING.Checked;
                cfg.INSTANCEDIR = TxtINSTANCEDIR.Text;
                cfg.SQMREPORTING = CBSQMREPORTING.Checked;
                cfg.INSTANCENAME = TxtINSTANCENAME.Text;
                cfg.AGTSVCACCOUNT = TxtAGTSVCACCOUNT.Text;
                cfg.AGTSVCSTARTUPTYPE = CBAGTSVCSTARTUPTYPE.Text;
                cfg.ISSVCSTARTUPTYPE = CBISSVCSTARTUPTYPE.Text;
                cfg.ISSVCACCOUNT = TxtISSVCACCOUNT.Text;
                cfg.ASSVCSTARTUPTYPE = CBASSVCSTARTUPTYPE.Text;
                cfg.ASCOLLATION = TxtASCOLLATION.Text;
                cfg.ASDATADIR = TxtASDATADIR.Text;
                cfg.ASLOGDIR = TxtASLOGDIR.Text;
                cfg.ASBACKUPDIR = TxtASBACKUPDIR.Text;
                cfg.ASTEMPDIR = TxtASTEMPDIR.Text;
                cfg.ASCONFIGDIR = TxtASCONFIGDIR.Text;
                cfg.ASPROVIDERMSOLAP = TxtASPROVIDERMSOLAP.Text;
                cfg.SQLSVCSTARTUPTYPE = CBSQLSVCSTARTUPTYPE.Text;
                cfg.FILESTREAMLEVEL = TxtFILESTREAMLEVEL.Text;
                cfg.ENABLERANU = CBENABLERANU.Checked;
                cfg.SQLCOLLATION = TxtSQLCOLLATION.Text;
                cfg.SQLSVCACCOUNT = TxtSQLSVCACCOUNT.Text;
                cfg.SQLSYSADMINACCOUNTS = TxtSQLSYSADMINACCOUNTS.Text;
                cfg.SECURITYMODE = TxtSECURITYMODE.Text;
                cfg.ADDCURRENTUSERASSQLADMIN = CBADDCURRENTUSERASSQLADMIN.Checked;
                cfg.TCPENABLED = TxtTCPENABLED.Text;
                cfg.NPENABLED = TxtNPENABLED.Text;
                cfg.BROWSERSVCSTARTUPTYPE = CBBROWSERSVCSTARTUPTYPE.Text;
                cfg.RSSVCACCOUNT = TxtRSSVCACCOUNT.Text;
                cfg.RSSVCSTARTUPTYPE = CBRSSVCSTARTUPTYPE.Text;
                cfg.RSINSTALLMODE = TxtRSINSTALLMODE.Text;

                cfg.CreateConfigFile(FilePath);
            }
            catch (Exception ex)
            { throw ex; }
        }
Example #8
0
 public void WriteConfigurationXML(ConfigurationFile aCF, string aPath)
 {
     List<CFCategories> lCats = aCF.Categories;
     int lAmountCats = lCats.Count();
     List<XElement> lXMLCats = new List<XElement>();
     int lCount = 0;
     foreach (CFCategories lCat in lCats)
     {
         lCount++;
         lXMLCats.Add(new XElement("d"+lCount, 
             new XAttribute("Name", lCat.name),
             new XAttribute("Colour", lCat.colour),
             new XAttribute("Command", lCat.command)
             ));
     }
     XElement lConfigFile = new XElement("Setup", 
         new XAttribute("POSID", aCF.POSID),
         new XAttribute("departments", lAmountCats.ToString()),
         new XAttribute("DebugEnabled", "true")
         );
     foreach (XElement lXMLElement in lXMLCats)
     {
         lConfigFile.Add(lXMLElement);
     }
     if (aPath != null)
     {
         try
         {
             lConfigFile.Save(aPath);
         }
         catch (SystemException ex)
         {
             NotificationWindow lNotify = new NotificationWindow("System Error", "The system encountered an error whilst processing the configuration file. The error is: \r\n"
                 + ex.Message.ToString(), "OKOnly");
             lNotify.ShowDialog();
             AppErr.Log(ex.Message.ToString(), false);
             Environment.Exit(0);
         }
     }
     else
     {
         NotificationWindow lNotify = new NotificationWindow("System Error", "Failure writing to configuration file.\r\n\r\nSystem will now exit."
                 , "OKOnly");
         lNotify.ShowDialog();
         AppErr.Log("Path was not set for XML configuration file. System failure", false);
         Environment.Exit(0);
     }
 }
Example #9
0
 /// <summary>
 /// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值
 /// </summary>
 /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
 /// <param name="key">要删除的子节点Key值</param>
 /// <returns>返回成功与否布尔值</returns>
 public static bool DeleteByKey(ConfigurationFile configurationFile, string key)
 {
     bool isSuccess = false;
     string filename = string.Empty;
     if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
     {
         filename = System.Windows.Forms.Application.ExecutablePath + ".config";
     }
     else
     {
         filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
     }
     XmlDocument doc = new XmlDocument();
     doc.Load(filename); //加载配置文件
     XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点
     ////得到[appSettings]节点中关于Key的子节点
     XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
     if (element != null)
     {
         //存在则删除子节点
         element.ParentNode.RemoveChild(element);
     }
     else
     {
         //不存在
     }
     try
     {
         //保存至配置文件(方式一)
         using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
         {
             xmlwriter.Formatting = Formatting.Indented;
             doc.WriteTo(xmlwriter);
             xmlwriter.Flush();
         }
         isSuccess = true;
     }
     catch (Exception ex)
     {
         isSuccess = false;
     }
     return isSuccess;
 }
Example #10
0
 public void LoadData(Repository repository)
 {
     if(_configurationFile != null)
     {
         DetachFromConfigFile();
         _configurationFile = null;
     }
     if(_repository != repository)
     {
         if(_repository != null)
         {
             DetachFromRepository();
         }
         _repository = repository;
         if(_repository != null)
         {
             AttachToRepository();
         }
     }
 }
Example #11
0
 public RabbitMqCollector()
 {
     _configurationFile = ConfigurationService.Instance.ReadConfigurationFile();
     _isEnabled         = _configurationFile.RabbitMq != null &&
                          (_configurationFile.RabbitMq.Fields?.Any() ?? false);
 }
Example #12
0
        // Initializes the state keys to their default values.
        private void InitializeState()
        {
            if (m_state != null)
            {
                const string NewDatabaseMessage = "Please enter the needed information about the\r\nMySQL database you would like to create.";
                const string OldDatabaseMessage = "Please enter the needed information about\r\nyour existing MySQL database.";

                bool       existing          = Convert.ToBoolean(m_state["existing"]);
                bool       migrate           = existing && Convert.ToBoolean(m_state["updateConfiguration"]);
                Visibility newUserVisibility = (existing && !migrate) ? Visibility.Collapsed : Visibility.Visible;

                ConfigurationFile serviceConfig;
                string            connectionString;
                string            dataProviderString;

                m_state["mySqlSetup"]                    = m_mySqlSetup;
                m_mySqlSetup.HostName                    = m_hostNameTextBox.Text;
                m_mySqlSetup.DatabaseName                = m_databaseNameTextBox.Text;
                m_createNewUserCheckBox.Visibility       = newUserVisibility;
                m_newUserNameLabel.Visibility            = newUserVisibility;
                m_newUserPasswordLabel.Visibility        = newUserVisibility;
                m_newUserNameTextBox.Visibility          = newUserVisibility;
                m_newUserPasswordTextBox.Visibility      = newUserVisibility;
                m_mySqlDatabaseInstructionTextBlock.Text = (!existing || migrate) ? NewDatabaseMessage : OldDatabaseMessage;

                // If connecting to existing database, user name and password need not be admin user:
                if (existing && !migrate)
                {
                    m_userNameLabel.Content = "User name:";
                    m_passwordLabel.Content = "Password:"******"Admin user name:";
                    m_passwordLabel.Content = "Admin password:"******"createNewMySqlUser"))
                {
                    m_state.Add("createNewMySqlUser", m_createNewUserCheckBox.IsChecked.Value);
                }

                if (!m_state.ContainsKey("newMySqlUserName"))
                {
                    m_state.Add("newMySqlUserName", m_newUserNameTextBox.Text);
                }

                if (!m_state.ContainsKey("newMySqlUserPassword"))
                {
                    m_state.Add("newMySqlUserPassword", m_newUserPasswordTextBox.Password);
                }

                if (!m_state.ContainsKey("encryptMySqlConnectionStrings"))
                {
                    m_state.Add("encryptMySqlConnectionStrings", false);
                }

                m_databaseNameTextBox.Text = migrate ? "openHistorian" + App.DatabaseVersionSuffix : "openHistorian";

                // When using an existing database as-is, read existing connection settings out of the configuration file
                string configFile = FilePath.GetAbsolutePath(App.ApplicationConfig); //"openHistorian.exe.config"

                if (!File.Exists(configFile))
                {
                    configFile = FilePath.GetAbsolutePath(App.ManagerConfig); //"openHistorianManager.exe.config"
                }
                if (existing && !migrate && File.Exists(configFile))
                {
                    serviceConfig      = ConfigurationFile.Open(configFile);
                    connectionString   = serviceConfig.Settings["systemSettings"]["ConnectionString"]?.Value;
                    dataProviderString = serviceConfig.Settings["systemSettings"]["DataProviderString"]?.Value;

                    if (!string.IsNullOrEmpty(connectionString) && m_mySqlSetup.DataProviderString.Equals(dataProviderString, StringComparison.InvariantCultureIgnoreCase))
                    {
                        m_mySqlSetup.ConnectionString            = connectionString;
                        m_hostNameTextBox.Text                   = m_mySqlSetup.HostName;
                        m_databaseNameTextBox.Text               = m_mySqlSetup.DatabaseName;
                        m_adminUserNameTextBox.Text              = m_mySqlSetup.UserName;
                        m_adminPasswordTextBox.Password          = m_mySqlSetup.Password;
                        m_state["encryptMySqlConnectionStrings"] = serviceConfig.Settings["systemSettings"]["ConnectionString"].Encrypted;
                    }
                }
            }
        }
Example #13
0
 public Driver(ConfigurationFile configFile)
 {
     this.configFile = configFile;
     Init();
 }
Example #14
0
 protected NodeBase(ConfigurationFile configurationFile)
 {
     ConfigurationFile = configurationFile;
 }
Example #15
0
        /// <summary>
        /// Creates a new <see cref="IaonSession"/>.
        /// </summary>
        public IaonSession()
        {
            ConfigurationFile configFile = ConfigurationFile.Current;

            // Initialize system settings
            CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"];

            systemSettings.Add("NodeID", Guid.NewGuid().ToString(), "Unique Node ID");
            m_nodeID = systemSettings["NodeID"].ValueAs <Guid>();

            // Initialize threshold settings
            CategorizedSettingsElementCollection thresholdSettings = configFile.Settings["thresholdSettings"];

            thresholdSettings.Add("MeasurementWarningThreshold", "100000", "Number of unarchived measurements allowed in any output adapter queue before displaying a warning message");
            thresholdSettings.Add("MeasurementDumpingThreshold", "500000", "Number of unarchived measurements allowed in any output adapter queue before taking evasive action and dumping data");
            thresholdSettings.Add("DefaultSampleSizeWarningThreshold", "10", "Default number of unpublished samples (in seconds) allowed in any action adapter queue before displaying a warning message");

            m_measurementWarningThreshold       = thresholdSettings["MeasurementWarningThreshold"].ValueAsInt32();
            m_measurementDumpingThreshold       = thresholdSettings["MeasurementDumpingThreshold"].ValueAsInt32();
            m_defaultSampleSizeWarningThreshold = thresholdSettings["DefaultSampleSizeWarningThreshold"].ValueAsInt32();

            using (Logger.AppendStackMessages("HostAdapter", "IaonSession"))
            {
                // Create a new set of routing tables
                switch (OptimizationOptions.DefaultRoutingMethod)
                {
                case OptimizationOptions.RoutingMethod.HighLatencyLowCpu:
                    m_routingTables = new RoutingTables(new RouteMappingHighLatencyLowCpu());
                    break;

                default:
                    m_routingTables = new RoutingTables();
                    break;
                }
            }
            m_routingTables.StatusMessage    += m_routingTables_StatusMessage;
            m_routingTables.ProcessException += m_routingTables_ProcessException;

            // Create a collection to manage all input, action and output adapter collections as a unit
            m_allAdapters = new AllAdaptersCollection();

            // Attach to common adapter events
            m_allAdapters.StatusMessage               += StatusMessageHandler;
            m_allAdapters.ProcessException            += ProcessExceptionHandler;
            m_allAdapters.InputMeasurementKeysUpdated += InputMeasurementKeysUpdatedHandler;
            m_allAdapters.OutputMeasurementsUpdated   += OutputMeasurementsUpdatedHandler;
            m_allAdapters.ConfigurationChanged        += ConfigurationChangedHandler;
            m_allAdapters.Disposed += DisposedHandler;

            // Create filter adapters collection
            m_filterAdapters = new FilterAdapterCollection();

            // Create input adapters collection
            m_inputAdapters = new InputAdapterCollection();
            m_inputAdapters.NewMeasurements    += NewMeasurementsHandler;
            m_inputAdapters.ProcessingComplete += ProcessingCompleteHandler;

            // Create action adapters collection
            m_actionAdapters = new ActionAdapterCollection();
            m_actionAdapters.NewMeasurements        += NewMeasurementsHandler;
            m_actionAdapters.UnpublishedSamples     += UnpublishedSamplesHandler;
            m_actionAdapters.RequestTemporalSupport += RequestTemporalSupportHandler;

            // Create output adapters collection
            m_outputAdapters = new OutputAdapterCollection();
            m_outputAdapters.UnprocessedMeasurements += UnprocessedMeasurementsHandler;

            // Associate adapter collections with routing tables
            m_routingTables.InputAdapters  = m_inputAdapters;
            m_routingTables.ActionAdapters = m_actionAdapters;
            m_routingTables.OutputAdapters = m_outputAdapters;

            // We group these adapters such that they are initialized in the following order: output, filter, input, action.
            // This is done so that the archival capabilities will be setup before we start receiving input and the input
            // data will be flowing before any actions get established for the input - at least generally.
            m_allAdapters.Add(m_outputAdapters);
            m_allAdapters.Add(m_filterAdapters);
            m_allAdapters.Add(m_inputAdapters);
            m_allAdapters.Add(m_actionAdapters);

            m_requestTemporalSupportLock = new object();
        }
Example #16
0
 /// <summary>
 /// 删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值
 /// </summary>
 /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
 /// <param name="name">要删除的子节点name值</param>
 /// <returns>返回成功与否布尔值</returns>
 public static bool DeleteByName(ConfigurationFile configurationFile, string name)
 {
     bool isSuccess = false;
     string filename = string.Empty;
     if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
     {
         filename = System.Windows.Forms.Application.ExecutablePath + ".config";
     }
     else
     {
         filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
     }
     XmlDocument doc = new XmlDocument();
     doc.Load(filename); //加载配置文件
     XmlNode node = doc.SelectSingleNode("//connectionStrings");   //得到[connectionStrings]节点
     ////得到[connectionStrings]节点中关于Name的子节点
     XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
     if (element != null)
     {
         //存在则删除子节点
         node.RemoveChild(element);
     }
     else
     {
         //不存在
     }
     try
     {
         //保存至配置文件(方式二)
         doc.Save(filename);
         isSuccess = true;
     }
     catch (Exception ex)
     {
         isSuccess = false;
     }
     return isSuccess;
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sourceConfigurationFile"></param>
 /// <param name="provider"></param>
 public static void Import(ConfigurationFile sourceConfigurationFile,ConfigProviderElement provider)
 {
     ConfigurationManager.Import(sourceConfigurationFile, provider);
 }
 public ConfigurationSerializer(ConfigurationFile file, string filename)
 {
     this.ConfigFile    = file;
     this.Filename      = filename;
     this._instanceLock = new object();
 }
Example #19
0
        /// <summary>
        /// Loads the information stored in the editors configuration file.
        /// </summary>
        private void LoadConfiguration()
        {
            try
            {
                SerializableData serializer = new SerializableData();
                configurationFile = (ConfigurationFile)serializer.Load(ConfigurationFilePath,
                    typeof(ConfigurationFile));

                if (Directory.Exists(toolkitInstallPath))
                {
                    CheckToolkitInstall(configurationFile.ToolkitPath);
                }
                else
                {
                    if (CheckToolkitInstall(toolkitInstallPath))
                    {
                        configurationFile.ToolkitPath = toolkitInstallPath;
                    }
                    else
                    {
                        ShowToolkitPathDialog();
                    }
                }
                if (configurationFile.ProjectFolder != null)
                {
                    if (Directory.Exists(configurationFile.ProjectFolder))
                    {
                        if (Directory.Exists(configurationFile.ProjectFolder + @"prg"))
                        {
                            projectPath = configurationFile.ProjectFolder + @"prg";
                        }
                        else
                        {
                            projectPath = configurationFile.ProjectFolder;
                        }

                        projectTitle = configurationFile.ProjectName;
                    }
                    else
                    {
                        throw new DirectoryNotFoundException();
                    }

                    projectLoaded = true;
                    this.Text = configurationFile.ProjectName + " - " + programVersion;
                }
            }
            catch (DirectoryNotFoundException)
            {
                string error = "The project folder " + configurationFile.ProjectFolder + " could not be found.";
                MessageBox.Show(error, "Project Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                File.Delete(ConfigurationFilePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ExecutablePath, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #20
0
        private void ServiceHelper_ServiceStarting(object sender, EventArgs <string[]> e)
        {
            ShutdownHandler.Initialize();

            // Define a run-time log
            m_runTimeLog                   = new RunTimeLog();
            m_runTimeLog.FileName          = "RunTimeLog.txt";
            m_runTimeLog.ProcessException += ProcessExceptionHandler;
            m_runTimeLog.Initialize();

            // Create a handler for unobserved task exceptions
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            // Make sure default service settings exist
            ConfigurationFile configFile = ConfigurationFile.Current;

            string servicePath    = FilePath.GetAbsolutePath("");
            string defaultLogPath = string.Format("{0}{1}Logs{1}", servicePath, Path.DirectorySeparatorChar);

            //string defaultNetworkModelPath = string.Format("{0}{1}/NetworkModel.xml", servicePath, Path.DirectorySeparatorChar);

            // Initialize algorithm processing framework - this will define default system settings
            try
            {
                AlgorithmHostingEnvironment.Initialize();
            }
            catch (Exception ex)
            {
                HandleException(new InvalidOperationException($"Exception while creating framework for algorithm hosting environment: {ex.Message}", ex));
            }

            CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"];

            // Makes sure exepected system settings are defined in the configuration file
            systemSettings.Add("LogPath", defaultLogPath, "Defines the path used to archive log files");
            systemSettings.Add("MaxLogFiles", DefaultMaxLogFiles, "Defines the maximum number of log files to keep");
            systemSettings.Add("AllowRemoteRestart", DefaultAllowRemoteRestart, "Controls ability to remotely restart the host service.");
            systemSettings.Add("AllowServiceMonitors", DefaultAllowServiceMonitors, "Controls ability to auto-load IServiceMonitor implementations.");
            systemSettings.Add("DefaultCulture", DefaultCulture, "Default culture to use for language, country/region and calendar formats.");
            systemSettings.Add("InputMapping", SystemSettings.InputMapping, "Mnput mapping used by algorithm for incoming data.");
            systemSettings.Add("OutputMapping", SystemSettings.OutputMapping, "Mapping used by algorithm for outgoing data.");
            systemSettings.Add("ConnectionString", SystemSettings.ConnectionString, "Connection string used by algorithm to connect to openECA data source.");
            systemSettings.Add("FramesPerSecond", SystemSettings.FramesPerSecond, "Data rate, in frames per second, expected by algorithm.");
            systemSettings.Add("LagTime", SystemSettings.LagTime, "Maximum past-time deviation tolerance, in seconds (can be sub-second), that the algorithm will tolerate.");
            systemSettings.Add("LeadTime", SystemSettings.LeadTime, "Maximum future-time deviation tolerance, in seconds (can be sub-second), that the algorithm will tolerate.");
            systemSettings.Add("NetworkModelAbsolutePath", "NetworkModel.xml", "The full path, including the file name, of the LSE network model XML file.");
            systemSettings.Add("PhaseConfiguration", "PositiveSequence", "Either 'PositiveSequence' or 'ThreePhase'");
            systemSettings.Add("OverridePhaseConfiguration", true, "A flag that specifies whether to use the phase configuration in the model or in the system settings.");


            // Attempt to set default culture
            try
            {
                string defaultCulture = systemSettings["DefaultCulture"].ValueAs(DefaultCulture);
                CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.CreateSpecificCulture(defaultCulture);   // Defaults for date formatting, etc.
                CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture(defaultCulture);   // Culture for resource strings, etc.
            }
            catch (Exception ex)
            {
                HandleException(new InvalidOperationException($"Failed to set default culture due to exception, defaulting to \"{CultureInfo.CurrentCulture.Name.ToNonNullNorEmptyString("Undetermined")}\": {ex.Message}", ex));
            }

            // Retrieve application log path as defined in the config file
            string logPath = FilePath.GetAbsolutePath(systemSettings["LogPath"].Value);

            // Make sure log directory exists
            try
            {
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }
            }
            catch (Exception ex)
            {
                // Attempt to default back to common log file path
                if (!Directory.Exists(defaultLogPath))
                {
                    try
                    {
                        Directory.CreateDirectory(defaultLogPath);
                    }
                    catch
                    {
                        defaultLogPath = servicePath;
                    }
                }

                HandleException(new InvalidOperationException($"Failed to create logging directory \"{logPath}\" due to exception, defaulting to \"{defaultLogPath}\": {ex.Message}", ex));
                logPath = defaultLogPath;
            }

            int maxLogFiles = systemSettings["MaxLogFiles"].ValueAs(DefaultMaxLogFiles);

            try
            {
                Logger.FileWriter.SetPath(logPath);
                Logger.FileWriter.SetLoggingFileCount(maxLogFiles);
            }
            catch (Exception ex)
            {
                HandleException(new InvalidOperationException($"Failed to set logging path \"{logPath}\" or max file count \"{maxLogFiles}\" due to exception: {ex.Message}"));
            }

            try
            {
                Directory.SetCurrentDirectory(servicePath);
            }
            catch (Exception ex)
            {
                HandleException(new InvalidOperationException($"Failed to set current directory to execution path \"{servicePath}\" due to exception: {ex.Message}"));
            }

            // Initialize system settings as defined in configuration file
            m_allowRemoteRestart            = systemSettings["AllowRemoteRestart"].ValueAs(DefaultAllowRemoteRestart);
            m_allowServiceMonitors          = systemSettings["AllowServiceMonitors"].ValueAs(DefaultAllowServiceMonitors);
            SystemSettings.InputMapping     = systemSettings["InputMapping"].ValueAs(SystemSettings.InputMapping);
            SystemSettings.OutputMapping    = systemSettings["OutputMapping"].ValueAs(SystemSettings.OutputMapping);
            SystemSettings.ConnectionString = systemSettings["ConnectionString"].ValueAs(SystemSettings.ConnectionString);
            SystemSettings.FramesPerSecond  = systemSettings["FramesPerSecond"].ValueAs(SystemSettings.FramesPerSecond);
            SystemSettings.LagTime          = systemSettings["LagTime"].ValueAs(SystemSettings.LagTime);
            SystemSettings.LeadTime         = systemSettings["LeadTime"].ValueAs(SystemSettings.LeadTime);
        }
Example #21
0
    void Start()
    {
        config  = gameObject.GetComponent <ConfigurationFile>();
        dialogs = config.cutscenesDialog;
        sprites = config.cutscenesSprite;

        SoundManager.instance.PlayerMusic("Cutscene");
        gameObjectOnScene = GameObject.Find("SceneInfos");
        scenesInfos       = gameObjectOnScene.GetComponent <ScenesInfos>();

        while (dialogs [i, 0] != scenesInfos.currentScene)
        {
            i++;
        }
        i++;
        FinnColor        = new Color(51.0f / 255.0f, 0.0f / 255.0f, 255.0f / 255.0f);
        WhitePawnColor   = new Color(1.0f, 1.0f, 1.0f);
        BlackPawnColor   = new Color(0.0f, 0.0f, 0.0f);
        BlackBishopColor = new Color(0.0f, 0.0f, 0.0f);
        BlackRookColor   = new Color(0.0f, 0.0f, 0.0f);
        BlackKnightColor = new Color(0.0f, 0.0f, 0.0f);
        if (dialogs [i, 0] == "Finn")
        {
            textName.color = FinnColor;
        }
        else if (dialogs [i, 0] == "WhitePawn")
        {
            textName.color = WhitePawnColor;
        }
        else if (dialogs[i, 0] == "BlackPawn")
        {
            textName.color = BlackPawnColor;
        }
        else if (dialogs[i, 0] == "BlackBishop")
        {
            textName.color = BlackBishopColor;
        }
        else if (dialogs[i, 0] == "BlackRook")
        {
            textName.color = BlackRookColor;
        }
        else if (dialogs[i, 0] == "BlackKnight")
        {
            textName.color = BlackKnightColor;
        }
        if (dialogs [i, 0] == "")
        {
            textDialog.color = new Color(1.0f, 1.0f, 1.0f);
        }
        textName.text   = dialogs[i, 0];
        textDialog.text = dialogs[i, 1];

        while (sprites [j, 0] != scenesInfos.currentScene)
        {
            j++;
        }
        if (scenesInfos.currentScene == "Intro" || scenesInfos.currentScene == "Intro_2")
        {
            bubble         = gameObject.GetComponent <Image> ();
            bubble.enabled = false;
        }
        sprite            = Resources.Load <Sprite> ("Backgrounds/" + sprites[j, 3]);
        background.sprite = sprite;
        sprite            = Resources.Load <Sprite> ("Sprites/CutScenes/" + sprites[j, 1]);
        leftSprite.sprite = sprite;
        if (sprites [j, 1] == "Finn")
        {
            leftSpriteSize.sizeDelta        = new Vector2(294, 634);
            leftSpriteSize.anchoredPosition = new Vector3(115, -99, 0);
        }
        else if (sprites [j, 1] == "WhitePawn")
        {
            leftSpriteSize.sizeDelta        = new Vector2(168, 274);
            leftSpriteSize.anchoredPosition = new Vector3(115, 150, 0);
        }
        else if (sprites [j, 1] == "BlackPawn")
        {
            leftSpriteSize.sizeDelta        = new Vector2(347, 347);
            leftSpriteSize.anchoredPosition = new Vector3(115, 100, 0);
        }
        else if (sprites [j, 1] == "BlackBishop")
        {
            leftSpriteSize.sizeDelta        = new Vector2(234, 369);
            leftSpriteSize.anchoredPosition = new Vector3(115, 100, 0);
        }
        else if (sprites [j, 1] == "BlackRook")
        {
            leftSpriteSize.sizeDelta        = new Vector2(319, 404);
            leftSpriteSize.anchoredPosition = new Vector3(115, 100, 0);
        }
        else if (sprites [j, 1] == "BlackKnight")
        {
            leftSpriteSize.sizeDelta        = new Vector2(498, 369);
            leftSpriteSize.anchoredPosition = new Vector3(115, 100, 0);
        }
        sprite             = Resources.Load <Sprite>("Sprites/CutScenes/" + sprites[j, 2]);
        rightSprite.sprite = sprite;
        if (sprites [j, 2] == "Finn")
        {
            rightSpriteSize.sizeDelta        = new Vector2(294, 634);
            rightSpriteSize.anchoredPosition = new Vector3(-115, -99, 0);
        }
        else if (sprites [j, 2] == "WhitePawn")
        {
            rightSpriteSize.sizeDelta        = new Vector2(168, 274);
            rightSpriteSize.anchoredPosition = new Vector3(-115, 150, 0);
        }
        else if (sprites [j, 2] == "BlackPawn")
        {
            rightSpriteSize.sizeDelta        = new Vector2(347, 347);
            rightSpriteSize.anchoredPosition = new Vector3(-115, 100, 0);
        }
        else if (sprites [j, 2] == "BlackBishop")
        {
            rightSpriteSize.sizeDelta        = new Vector2(234, 369);
            rightSpriteSize.anchoredPosition = new Vector3(-115, 100, 0);
        }
        else if (sprites [j, 2] == "BlackRook")
        {
            rightSpriteSize.sizeDelta        = new Vector2(319, 404);
            rightSpriteSize.anchoredPosition = new Vector3(-115, 100, 0);
        }
        else if (sprites [j, 2] == "BlackKnight")
        {
            rightSpriteSize.sizeDelta        = new Vector2(498, 369);
            rightSpriteSize.anchoredPosition = new Vector3(-115, 100, 0);
        }
    }
Example #22
0
        public IDictionary <string, string> to_token_dictionary()
        {
            var tokens = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            tokens["AfterMigrationFolderName"] = AfterMigrationFolderName.to_string();
            tokens["AlterDatabaseFolderName"]  = AlterDatabaseFolderName.to_string();
            tokens["Baseline"] = Baseline.to_string();
            tokens["BeforeMigrationFolderName"]  = BeforeMigrationFolderName.to_string();
            tokens["CommandTimeout"]             = CommandTimeout.to_string();
            tokens["CommandTimeoutAdmin"]        = CommandTimeoutAdmin.to_string();
            tokens["ConfigurationFile"]          = ConfigurationFile.to_string();
            tokens["ConnectionString"]           = ConnectionString.to_string();
            tokens["ConnectionStringAdmin"]      = ConnectionStringAdmin.to_string();
            tokens["CreateDatabaseCustomScript"] = CreateDatabaseCustomScript.to_string();
            tokens["DatabaseName"]             = DatabaseName.to_string();
            tokens["DatabaseType"]             = DatabaseType.to_string();
            tokens["Debug"]                    = Debug.to_string();
            tokens["DisableOutput"]            = DisableOutput.to_string();
            tokens["DisableTokenReplacement"]  = DisableTokenReplacement.to_string();
            tokens["DoNotAlterDatabase"]       = DoNotAlterDatabase.to_string();
            tokens["DoNotCreateDatabase"]      = DoNotCreateDatabase.to_string();
            tokens["DoNotStoreScriptsRunText"] = DoNotStoreScriptsRunText.to_string();
            tokens["DownFolderName"]           = DownFolderName.to_string();
            tokens["Drop"]                                     = Drop.to_string();
            tokens["DryRun"]                                   = DryRun.to_string();
            tokens["EnvironmentName"]                          = string.Join(",", EnvironmentNames);
            tokens["EnvironmentNames"]                         = string.Join(",", EnvironmentNames);
            tokens["FunctionsFolderName"]                      = FunctionsFolderName.to_string();
            tokens["IndexesFolderName"]                        = IndexesFolderName.to_string();
            tokens["Initialize"]                               = Initialize.to_string();
            tokens["OutputPath"]                               = OutputPath.to_string();
            tokens["PermissionsFolderName"]                    = PermissionsFolderName.to_string();
            tokens["RecoveryMode"]                             = RecoveryMode.to_string();
            tokens["RepositoryPath"]                           = RepositoryPath.to_string();
            tokens["Restore"]                                  = Restore.to_string();
            tokens["RestoreCustomOptions"]                     = RestoreCustomOptions.to_string();
            tokens["RestoreFromPath"]                          = RestoreFromPath.to_string();
            tokens["RestoreTimeout"]                           = RestoreTimeout.to_string();
            tokens["RunAfterCreateDatabaseFolderName"]         = RunAfterCreateDatabaseFolderName.to_string();
            tokens["RunAfterOtherAnyTimeScriptsFolderName"]    = RunAfterOtherAnyTimeScriptsFolderName.to_string();
            tokens["RunAllAnyTimeScripts"]                     = RunAllAnyTimeScripts.to_string();
            tokens["RunBeforeUpFolderName"]                    = RunBeforeUpFolderName.to_string();
            tokens["RunFirstAfterUpFolderName"]                = RunFirstAfterUpFolderName.to_string();
            tokens["SchemaName"]                               = SchemaName.to_string();
            tokens["ScriptsRunErrorsTableName"]                = ScriptsRunErrorsTableName.to_string();
            tokens["ScriptsRunTableName"]                      = ScriptsRunTableName.to_string();
            tokens["SearchAllSubdirectoriesInsteadOfTraverse"] = SearchAllSubdirectoriesInsteadOfTraverse.to_string();
            tokens["ServerName"]                               = ServerName.to_string();
            tokens["Silent"]                                   = Silent.to_string();
            tokens["SprocsFolderName"]                         = SprocsFolderName.to_string();
            tokens["SqlFilesDirectory"]                        = SqlFilesDirectory.to_string();
            tokens["TriggersFolderName"]                       = TriggersFolderName.to_string();
            tokens["UpFolderName"]                             = UpFolderName.to_string();
            tokens["Version"]                                  = Version.to_string();
            tokens["VersionFile"]                              = VersionFile.to_string();
            tokens["VersionTableName"]                         = VersionTableName.to_string();
            tokens["VersionXPath"]                             = VersionXPath.to_string();
            tokens["ViewsFolderName"]                          = ViewsFolderName.to_string();
            tokens["WarnAndIgnoreOnOneTimeScriptChanges"]      = WarnAndIgnoreOnOneTimeScriptChanges.to_string();
            tokens["WarnOnOneTimeScriptChanges"]               = WarnOnOneTimeScriptChanges.to_string();
            tokens["WithTransaction"]                          = WithTransaction.to_string();

            if (UserTokens != null)
            {
                foreach (var t in UserTokens)
                {
                    tokens[t.Key] = t.Value;
                }
            }

            return(tokens);
        }
Example #23
0
 public static ConfigurationFile GetInstance()
 {
     return(_configFile ?? (_configFile = new ConfigurationFile()));
 }
 public HomeController(IOptions <ConfigurationFile> config)
 {
     _config = config.Value;
 }
Example #25
0
    /// <summary>
    /// 对[appSettings]节点依据Key值读取到Value值,返回字符串
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="key">要读取的Key值</param>
    /// <returns>返回Value值的字符串</returns>
    public static string ReadValueByKey(ConfigurationFile configurationFile, string key)
    {
        string value = string.Empty;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }

        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件
        XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点
        ////得到[appSettings]节点中关于Key的子节点
        XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
        if (element != null)
        {
            value = element.GetAttribute("value");
        }
        return value;
    }
Example #26
0
        private void btnExport_Click(object sender, EventArgs e)
        {
            SqlConnection wConn = null;
            SqlCommand wCmd = null;
            string wXmlText = string.Empty;
            ConfigurationFile wConfigFile = null;
            StringBuilder wBuilder = null;
            System.IO.FileInfo wFInfo = null;

            try
            {
                progressBar1.Value = 0;

                wConn = CreateConnection();
                if (wConn == null || !XmlValidationRequired())
                    return;

                progressBar1.Increment(2);

                //Obtengo los datos del xml
                wFInfo = new System.IO.FileInfo(txtXml.Text);
                wXmlText = Fwk.HelperFunctions.FileFunctions.OpenTextFile(txtXml.Text);
                wConfigFile = new ConfigurationFile();
                wConfigFile = ConfigurationFile.GetFromXml<ConfigurationFile>(wXmlText);
                if (wConfigFile.Groups == null)
                {
                    MessageBox.Show("No hay datos para migrar", "Exportar", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                progressBar1.Increment(48);

                //wBuilder = new StringBuilder();
                //foreach (Group wGrp in wConfigFile.Groups)
                //{
                //    foreach (Fwk.Configuration.Common.Key wKey in wGrp.Keys)
                //    {
                //        wBuilder.Append("INSERT INTO [dbo].[fwk_ConfigManager]([ConfigurationFileName],[group],[key],[encrypted],[value])VALUES(");
                //        wBuilder.Append(string.Concat("'", wFInfo.Name, "', "));
                //        wBuilder.Append(string.Concat("'", wGrp.Name, "', "));
                //        wBuilder.Append(string.Concat("'", wKey.Name, "', "));
                //        wBuilder.Append(string.Concat(Convert.ToInt32(wKey.Encrypted), ", "));
                //        wBuilder.Append(string.Concat("'", wKey.Value.ToString().Replace("'", string.Empty), "'"));
                //        wBuilder.Append(")");
                //        wBuilder.AppendLine();
                //    }
                //}

                progressBar1.Increment(40);
                ConfigProviderElement tempProvider = new ConfigProviderElement();
                tempProvider.BaseConfigFile = wFInfo.Name;
                tempProvider.ConfigProviderType = ConfigProviderType.sqldatabase;
                tempProvider.SourceInfo = wConn.ConnectionString;
                tempProvider.SourceInfoIsConnectionString = true;
                //Fwk.Configuration.ConfigurationManager.ConfigProvider.AddNewProvider(tempProvider);

                Fwk.Configuration.ConfigurationManager_CRUD.Import(wConfigFile,tempProvider);
                //wConn.Open();
                //wCmd = new SqlCommand(wBuilder.ToString(), wConn) { CommandType = CommandType.Text };
                //wCmd.ExecuteNonQuery();

                progressBar1.Increment(10);

                MessageBox.Show("Exportación terminada exitosamente", "Exportar", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (wConn != null && wConn.State == ConnectionState.Open)
                    wConn.Close();
            }
        }
Example #27
0
 /// <summary>
 /// 更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值
 /// </summary>
 /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
 /// <param name="name">子节点name值</param>
 /// <param name="connectionString">子节点connectionString值</param>
 /// <param name="providerName">子节点providerName值</param>
 /// <returns>返回成功与否布尔值</returns>
 public static bool UpdateOrCreateConnectionString(ConfigurationFile configurationFile, string name, string connectionString, string providerName)
 {
     bool isSuccess = false;
     string filename = string.Empty;
     if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
     {
         filename = System.Windows.Forms.Application.ExecutablePath + ".config";
     }
     else
     {
         filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
     }
     XmlDocument doc = new XmlDocument();
     doc.Load(filename); //加载配置文件
     XmlNode node = doc.SelectSingleNode("//connectionStrings");   //得到[connectionStrings]节点
     try
     {
         ////得到[connectionStrings]节点中关于Name的子节点
         XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
         if (element != null)
         {
             //存在则更新子节点
             element.SetAttribute("connectionString", connectionString);
             element.SetAttribute("providerName", providerName);
         }
         else
         {
             //不存在则新增子节点
             XmlElement subElement = doc.CreateElement("add");
             subElement.SetAttribute("name", name);
             subElement.SetAttribute("connectionString", connectionString);
             subElement.SetAttribute("providerName", providerName);
             node.AppendChild(subElement);
         }
         //保存至配置文件(方式二)
         doc.Save(filename);
         isSuccess = true;
     }
     catch (Exception ex)
     {
         isSuccess = false;
         throw ex;
     }
     return isSuccess;
 }
Example #28
0
 public static IConfigurationSerializer GetSerializer(ConfigurationFile file)
 {
     return(config[file]);
 }
Example #29
0
 public string GetConfigurationValue(ConfigurationFile eConfigFile, string xpathquery)
 {
     return searcher.GetConfigurationValue(eConfigFile, xpathquery);
 }
 protected PubSubViewModelBase(ConfigurationFile configurationFile)
 {
     ConfigurationFile = configurationFile;
     CloudContext      = new CloudContext(ConfigurationFile.BaseUrl);
 }
Example #31
0
 public static ConfigurationFile GetInstance(string name)
 {
     if (Instance == null)
         return (Instance = new CsdefFile(name));
     return Instance;
 }
Example #32
0
        /// <summary>
        /// Initializes the web page.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            ConfigurationFile config = ConfigurationFile.Current;
            CategorizedSettingsElementCollection settings = config.Settings[SettingsCategory];
            CategorizedSettingsElement           setting;

            // Setup company logo.
            setting = settings["CompanyLogo"];

            if ((object)setting != null)
            {
                LogoImage.ImageUrl = setting.Value;
            }
            else
            {
                LogoImage.ImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(SecurityPortal), EmbeddedCompanyLogo);
            }

            // Setup company link.
            setting = settings["CompanyLink"];

            if ((object)setting != null)
            {
                LogoLink.NavigateUrl = setting.Value;
            }
            else
            {
                LogoLink.NavigateUrl = DefaultCompanyLink;
            }

            // Setup help link.
            setting = settings["HelpPage"];

            if ((object)setting != null)
            {
                HelpLink.NavigateUrl = setting.Value;
            }
            else
            {
                HelpLink.NavigateUrl = Page.ClientScript.GetWebResourceUrl(typeof(SecurityPortal), EmbeddedHelpFile);
            }

            // Setup footer information.
            setting = settings["FooterText"];

            if ((object)setting != null)
            {
                FooterLabel.Text = setting.Value;
            }
            else
            {
                FooterLabel.Text = DefaultFooterText;
            }

            HelpImage.ImageUrl            = Page.ClientScript.GetWebResourceUrl(typeof(SecurityPortal), EmbeddedHelpImage);
            WarningImage.ImageUrl         = Page.ClientScript.GetWebResourceUrl(typeof(SecurityPortal), EmbeddedWarningImage);
            StyleSheet.Attributes["href"] = Page.ClientScript.GetWebResourceUrl(typeof(SecurityPortal), EmbeddedStyleSheet);

            if (Request[StatusCodeRequestKey] == AccessDeniedStatusCode)
            {
                // Show access denied.
                Page.Title = StaticPageTitle + " :: Access Denied";
                AccessDeniedPanel.Visible = true;
                ContentPlaceHolder.Controls.Add(AccessDeniedPanel);
            }
            else if (Request[StatusCodeRequestKey] == PasswordChangeStatusCode)
            {
                // Show change password.
                Page.Title = StaticPageTitle + " :: Change Password";
                ChangePasswordPanel.Visible = true;
                ContentPlaceHolder.Controls.Add(ChangePasswordPanel);

                // Setup UI.
                ChangeButton.SetSubmitOnce();
                ChangePasswordPanel.DefaultButton = ChangeButton.ID;

                if (!Page.IsPostBack)
                {
                    ChangePasswordUsername.Text = GetSavedUsername();

                    if (string.IsNullOrEmpty(ChangePasswordUsername.Text))
                    {
                        ChangePasswordUsername.Focus();
                    }
                    else
                    {
                        ChangePasswordOldPassword.Focus();
                    }
                }
            }
            else if (Request[StatusCodeRequestKey] == PasswordResetStatusCode)
            {
                // Show reset password.
                Page.Title = StaticPageTitle + " :: Reset Password";

                if ((object)ViewState[UsernameKey] == null)
                {
                    // Check for reset support.
                    ResetPasswordCheckPanel.Visible = true;
                    ContentPlaceHolder.Controls.Add(ResetPasswordCheckPanel);

                    // Setup UI.
                    ResetCheckButton.SetSubmitOnce();
                    ResetPasswordUsername.Focus();
                    ResetPasswordCheckPanel.DefaultButton = ResetCheckButton.ID;
                }
                else
                {
                    // Perform password reset.
                    ResetPasswordFinalPanel.Visible = true;
                    ContentPlaceHolder.Controls.Add(ResetPasswordFinalPanel);

                    // Setup UI.
                    ResetFinalButton.SetSubmitOnce();
                    ResetPasswordSecurityAnswer.Focus();
                    ResetPasswordFinalPanel.DefaultButton = ResetFinalButton.ID;
                    ResetPasswordSecurityQuestion.Text    = ViewState["SecurityQuestion"].ToString();
                    MessageLabel.Text = string.Empty;
                }
            }
            else if (Request[StatusCodeRequestKey] == UnauthorizedStatusCode || (object)CurrentProvider == null || !User.Identity.IsAuthenticated)
            {
                // Show login.
                Page.Title         = StaticPageTitle + " :: Login";
                LoginPanel.Visible = true;
                ContentPlaceHolder.Controls.Add(LoginPanel);

                // Setup UI.
                LoginButton.SetSubmitOnce();
                LoginPanel.DefaultButton   = LoginButton.ID;
                ForgotPassword.NavigateUrl = GetRedirectUrl(PasswordResetStatusCode);
                ChangePassword.NavigateUrl = GetRedirectUrl(PasswordChangeStatusCode);

                if (!Page.IsPostBack)
                {
                    LoginUsername.Text = GetSavedUsername();

                    if (string.IsNullOrEmpty(LoginUsername.Text))
                    {
                        LoginUsername.Focus();
                    }
                    else
                    {
                        LoginPassword.Focus();
                        RememberUsername.Checked = true;
                    }
                }
            }
            else
            {
                // Show my account.
                Page.Title             = StaticPageTitle + " :: My Account";
                MyAccountPanel.Visible = true;
                ContentPlaceHolder.Controls.Clear();
                ContentPlaceHolder.Controls.Add(MyAccountPanel);

                // Setup UI.
                UpdateButton.SetSubmitOnce();
                MyAccountPanel.DefaultButton = UpdateButton.ID;

                if (!Page.IsPostBack)
                {
                    ISecurityProvider provider = CurrentProvider;
                    ShowUserData(provider);

                    // The UpdateData() method was never implemented in
                    // any security provider so it has been removed
                    //if (!provider.CanUpdateData)
                    //{
                    //    AccountUserFirstName.Enabled = false;
                    //    AccountUserLastName.Enabled = false;
                    //    AccountUserEmailAddress.Enabled = false;
                    //    AccountUserPhoneNumber.Enabled = false;
                    //    AccountUserSecurityAnswer.Enabled = false;
                    //    UpdateButton.Enabled = false;
                    //}
                }
            }
        }
        // Initialize the state keys to their default values.
        private void InitializeState()
        {
            if (m_state != null)
            {
                bool       existing           = Convert.ToBoolean(m_state["existing"]);
                bool       migrate            = existing && Convert.ToBoolean(m_state["updateConfiguration"]);
                Visibility newUserVisibility  = (existing && !migrate) ? Visibility.Collapsed : Visibility.Visible;
                string     newDatabaseMessage = "Please enter the needed information about the\r\nOracle database you would like to create.";
                string     oldDatabaseMessage = "Please enter the needed information about\r\nyour existing Oracle database.";

                ConfigurationFile serviceConfig;
                string            connectionString;
                string            dataProviderString;

                m_state["oracleSetup"]        = m_oracleSetup;
                m_oracleSetup.TnsName         = m_tnsNameTextBox.Text;
                m_oracleSetup.AdminUserName   = m_adminUserNameTextBox.Text;
                m_oracleSetup.AdminPassword   = m_adminPasswordTextBox.Password;
                m_oracleSetup.CreateNewSchema = m_createNewSchemaCheckBox.IsChecked.HasValue && m_createNewSchemaCheckBox.IsChecked.Value;

                m_createNewSchemaCheckBox.Visibility      = newUserVisibility;
                m_schemaUserNameLabel.Visibility          = newUserVisibility;
                m_schemaUserPasswordLabel.Visibility      = newUserVisibility;
                m_schemaUserNameTextBox.Visibility        = newUserVisibility;
                m_schemaUserPasswordTextBox.Visibility    = newUserVisibility;
                m_oracleDatabaseInstructionTextBlock.Text = (!existing || migrate) ? newDatabaseMessage : oldDatabaseMessage;

                // If connecting to existing database, user name and password need not be admin user:
                if (existing && !migrate)
                {
                    m_userNameLabel.Content      = "User name:";
                    m_passwordLabel.Content      = "Password:"******"Admin user name:";
                    m_passwordLabel.Content      = "Admin password:"******"openHistorian" + App.DatabaseVersionSuffix : "openHistorian";

                // When using an existing database as-is, read existing connection settings out of the configuration file
                string configFile = FilePath.GetAbsolutePath(App.ApplicationConfig);

                if (!File.Exists(configFile))
                {
                    configFile = FilePath.GetAbsolutePath(App.ManagerConfig);
                }

                if (existing && !migrate && File.Exists(configFile))
                {
                    serviceConfig      = ConfigurationFile.Open(configFile);
                    connectionString   = serviceConfig.Settings["systemSettings"]["ConnectionString"]?.Value;
                    dataProviderString = serviceConfig.Settings["systemSettings"]["DataProviderString"]?.Value;

                    if (!string.IsNullOrEmpty(connectionString) && m_oracleSetup.DataProviderString.Equals(dataProviderString, StringComparison.InvariantCultureIgnoreCase))
                    {
                        m_oracleSetup.ConnectionString        = connectionString;
                        m_tnsNameTextBox.Text                 = m_oracleSetup.TnsName;
                        m_adminUserNameTextBox.Text           = m_oracleSetup.SchemaUserName;
                        m_adminPasswordTextBox.Password       = m_oracleSetup.SchemaPassword;
                        m_oracleSetup.EncryptConnectionString = serviceConfig.Settings["systemSettings"]["ConnectionString"].Encrypted;
                    }
                }
            }
        }
        /// <summary>
        /// Creates an instance of <see cref="App"/> class.
        /// </summary>
        public App()
        {
            string systemName = null;

            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            Application.Current.SessionEnding += Application_SessionEnding;

            try
            {
                string getElementValue(XElement[] elements, string name)
                {
                    XElement element = elements.Elements("add").FirstOrDefault(elem =>
                                                                               elem.Attributes("name").Any(nameAttribute =>
                                                                                                           string.Compare(nameAttribute.Value, name, StringComparison.OrdinalIgnoreCase) == 0));

                    return(element?.Attributes("value").FirstOrDefault()?.Value);
                }

                string configPath = FilePath.GetAbsolutePath(ConfigurationFile.Current.Configuration.FilePath.Replace("Manager", ""));

                if (File.Exists(configPath))
                {
                    XDocument  hostConfig     = XDocument.Load(configPath);
                    XElement[] systemSettings = hostConfig.Descendants(SystemSettings).ToArray();

                    // Get system name from host service config
                    systemName = getElementValue(systemSettings, "SystemName");

                    // Validate manager database connection as compared to host service
                    string hostConnectionString   = getElementValue(systemSettings, "ConnectionString");
                    string hostDataProviderString = getElementValue(systemSettings, "DataProviderString");
                    string hostNodeID             = getElementValue(systemSettings, "NodeID");

                    ConfigurationFile config = ConfigurationFile.Current;
                    CategorizedSettingsElementCollection configSettings = config.Settings[SystemSettings];

                    configSettings.Add("KeepCustomConnection", "false", "Determines if manager should keep custom database connection setting separate from host service.");

                    if (!configSettings["KeepCustomConnection"].Value.ParseBoolean())
                    {
                        MethodInfo getRawValueMethod = typeof(CategorizedSettingsElement).GetMethod("GetRawValue", BindingFlags.Instance | BindingFlags.NonPublic);

                        string getRawValue(CategorizedSettingsElement element)
                        {
                            if (getRawValueMethod is null)
                            {
                                return(element.Value);
                            }

                            return(getRawValueMethod.Invoke(element, Array.Empty <object>()) as string);
                        }

                        // Get value from connection string that is still encrypted for proper comparison
                        string connectionString   = getRawValue(configSettings["ConnectionString"]);
                        string dataProviderString = configSettings["DataProviderString"].Value;
                        string nodeID             = configSettings["NodeID"].Value;

                        if (!hostConnectionString.Equals(connectionString, StringComparison.OrdinalIgnoreCase) ||
                            !hostDataProviderString.Equals(dataProviderString, StringComparison.OrdinalIgnoreCase) ||
                            !hostNodeID.Equals(nodeID, StringComparison.OrdinalIgnoreCase))
                        {
                            bool mismatchHandled = false;

                            if (Environment.CommandLine.Contains("-elevated") && Environment.CommandLine.Contains("-connection"))
                            {
                                if (Environment.CommandLine.Contains("-connectionFix"))
                                {
                                    configSettings["ConnectionString"].Value   = hostConnectionString;
                                    configSettings["DataProviderString"].Value = hostDataProviderString;
                                    configSettings["NodeID"].Value             = hostNodeID;
                                    config.Save();
                                    mismatchHandled = true;
                                }
                                else if (Environment.CommandLine.Contains("-connectionKeep"))
                                {
                                    configSettings["KeepCustomConnection"].Value = "true";
                                    config.Save();
                                    mismatchHandled = true;
                                }
                            }

                            if (!mismatchHandled)
                            {
                                bool   correctMismatch   = System.Windows.Forms.MessageBox.Show(new NativeWindow(), "Manager database connection does not match host service. Do you want to correct this?", "Database Mismatch", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;
                                string elevatedOperation = correctMismatch ? "-connectionFix" : "-connectionKeep";

                                ProcessStartInfo startInfo = new ProcessStartInfo
                                {
                                    FileName        = Environment.GetCommandLineArgs()[0],
                                    Arguments       = $"{string.Join(" ", Environment.GetCommandLineArgs().Skip(1))} -elevated {elevatedOperation}",
                                    UseShellExecute = true,
                                    Verb            = "runas"
                                };

                                using (Process.Start(startInfo)) { }
                                Environment.Exit(0);
                            }
                        }
                    }
                }
            }
            catch
            {
                // If this fails, it's not a huge deal
            }

            m_errorLogger = new ErrorLogger
            {
                ErrorTextMethod          = ErrorText,
                ExitOnUnhandledException = false,
                HandleUnhandledException = true,
                LogToEmail      = false,
                LogToEventLog   = true,
                LogToFile       = true,
                LogToScreenshot = true,
                LogToUI         = true
            };

            m_errorLogger.Initialize();

            m_defaultErrorText = m_errorLogger.ErrorTextMethod;

            Title = AssemblyInfo.EntryAssembly.Title;

            // Add system name to title
            if (!string.IsNullOrWhiteSpace(systemName))
            {
                Title = $"{Title} [{systemName.Trim()}]";
            }

            // Setup default cache for measurement keys and associated Guid based signal ID's
            AdoDataConnection database = null;

            try
            {
                database = new AdoDataConnection(SystemSettings);

                if (!Environment.CommandLine.Contains("-elevated"))
                {
                    ConfigurationFile configurationFile = ConfigurationFile.Current;
                    CategorizedSettingsElementCollection systemSettings = configurationFile.Settings[SystemSettings];
                    string elevateSetting = systemSettings["ElevateProcess"]?.Value;

                    bool elevateProcess = !string.IsNullOrEmpty(elevateSetting) ? elevateSetting.ParseBoolean() : database.IsSqlite;

                    if (elevateProcess)
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo
                        {
                            FileName        = Environment.GetCommandLineArgs()[0],
                            Arguments       = $"{string.Join(" ", Environment.GetCommandLineArgs().Skip(1))} -elevated",
                            UseShellExecute = true,
                            Verb            = "runas"
                        };

                        using (Process.Start(startInfo)) { }
                        Environment.Exit(0);
                    }
                }

                MeasurementKey.EstablishDefaultCache(database.Connection, database.AdapterType);
            }
            catch (Exception ex)
            {
                // First attempt to display a modal dialog will fail to block this
                // thread -- modal dialog displayed by the error logger will block now
                MessageBox.Show(ex.Message);

                // Log and display error, then exit application - manager must connect to database to continue
                m_errorLogger.Log(new InvalidOperationException($"{Title} cannot connect to database: {ex.Message}", ex), true);
            }
            finally
            {
                database?.Dispose();
            }

            bool mirrorMode = true;

            try
            {
                CategorizedSettingsElementCollection systemSettings    = ConfigurationFile.Current.Settings["systemSettings"];
                CategorizedSettingsElement           mirrorModeSetting = systemSettings["MirrorMode"];

                if (!(mirrorModeSetting is null))
                {
                    mirrorMode = mirrorModeSetting.ValueAsBoolean();
                }
            }
            catch (Exception ex)
            {
                // First attempt to display a modal dialog will fail to block this
                // thread -- modal dialog displayed by the error logger will block now
                MessageBox.Show(ex.Message);

                // Log and display error, but continue on - if manager fails to load MirrorMode from the config file, it can just fall back on the default
                m_errorLogger.Log(new InvalidOperationException($"{Title} cannot access mirror mode setting in configuration file - defaulting to true: {ex.Message}", ex));
            }

            IsolatedStorageManager.WriteToIsolatedStorage("MirrorMode", mirrorMode);
        }
Example #35
0
        // Initialize the state keys to their default values.
        private void InitializeState()
        {
            if (m_state != null)
            {
                bool       existing           = Convert.ToBoolean(m_state["existing"]);
                bool       migrate            = existing && Convert.ToBoolean(m_state["updateConfiguration"]);
                Visibility newUserVisibility  = (existing && !migrate) ? Visibility.Collapsed : Visibility.Visible;
                string     newDatabaseMessage = "Please enter the needed information about the\r\nOracle database you would like to create.";
                string     oldDatabaseMessage = "Please enter the needed information about\r\nyour existing Oracle database.";

                ConfigurationFile serviceConfig;
                string            connectionString;
                string            dataProviderString;

                m_state["postgresSetup"]      = m_postgresSetup;
                m_postgresSetup.HostName      = m_hostNameTextBox.Text;
                m_postgresSetup.Port          = m_portTextBox.Text;
                m_postgresSetup.DatabaseName  = m_databaseTextBox.Text;
                m_postgresSetup.AdminUserName = m_adminUserNameTextBox.Text;
                m_postgresSetup.AdminPassword = m_adminPasswordTextBox.SecurePassword;

                m_roleNameLabel.Visibility                  = newUserVisibility;
                m_rolePasswordLabel.Visibility              = newUserVisibility;
                m_roleNameTextBox.Visibility                = newUserVisibility;
                m_rolePasswordTextBox.Visibility            = newUserVisibility;
                m_postgresDatabaseInstructionTextBlock.Text = (!existing || migrate) ? newDatabaseMessage : oldDatabaseMessage;

                // If connecting to existing database, user name and password need to be admin user:
                if (existing && !migrate)
                {
                    m_userNameLabel.Content      = "User name:";
                    m_passwordLabel.Content      = "Password:"******"Admin user name:";
                    m_passwordLabel.Content      = "Admin password:"******"substationSBG" + App.DatabaseVersionSuffix : "substationSBG";

                // When using an existing database as-is, read existing connection settings out of the configuration file
                string configFile = FilePath.GetAbsolutePath(App.ApplicationConfig);

                if (!File.Exists(configFile))
                {
                    configFile = FilePath.GetAbsolutePath(App.ManagerConfig);
                }

                if (existing && !migrate && File.Exists(configFile))
                {
                    serviceConfig      = ConfigurationFile.Open(configFile);
                    connectionString   = serviceConfig.Settings["systemSettings"]["ConnectionString"]?.Value;
                    dataProviderString = serviceConfig.Settings["systemSettings"]["DataProviderString"]?.Value;

                    if (!string.IsNullOrEmpty(connectionString) && PostgresSetup.DataProviderString.Equals(dataProviderString, StringComparison.OrdinalIgnoreCase))
                    {
                        m_postgresSetup.ConnectionString = connectionString;
                        m_hostNameTextBox.Text           = m_postgresSetup.HostName;
                        m_portTextBox.Text                      = m_postgresSetup.Port;
                        m_databaseTextBox.Text                  = m_postgresSetup.DatabaseName;
                        m_adminUserNameTextBox.Text             = m_postgresSetup.RoleName;
                        m_adminPasswordTextBox.Password         = m_postgresSetup.RolePassword?.ToUnsecureString();
                        m_postgresSetup.EncryptConnectionString = serviceConfig.Settings["systemSettings"]["ConnectionString"].Encrypted;
                    }
                }
            }
        }
Example #36
0
        /// <summary>
        /// Creates an instance of <see cref="App"/> class.
        /// </summary>
        public App()
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

            m_errorLogger = new ErrorLogger
            {
                ErrorTextMethod          = ErrorText,
                ExitOnUnhandledException = false,
                HandleUnhandledException = true,
                LogToEmail      = false,
                LogToEventLog   = true,
                LogToFile       = true,
                LogToScreenshot = true,
                LogToUI         = true
            };

            m_errorLogger.Initialize();

            m_defaultErrorText = m_errorLogger.ErrorTextMethod;

            Title = AssemblyInfo.EntryAssembly.Title;

            // Setup default cache for measurement keys and associated Guid based signal ID's
            AdoDataConnection database = null;

            try
            {
                database = new AdoDataConnection(CommonFunctions.DefaultSettingsCategory);

                if (!Environment.CommandLine.Contains("-elevated"))
                {
                    ConfigurationFile configurationFile = ConfigurationFile.Current;
                    CategorizedSettingsElementCollection systemSettings = configurationFile.Settings["SystemSettings"];
                    string elevateSetting = systemSettings["ElevateProcess"]?.Value;

                    bool elevateProcess = !string.IsNullOrEmpty(elevateSetting) ? elevateSetting.ParseBoolean() : database.IsSqlite;

                    if (elevateProcess)
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo
                        {
                            FileName        = Environment.GetCommandLineArgs()[0],
                            Arguments       = string.Join(" ", Environment.GetCommandLineArgs().Skip(1)) + " -elevated",
                            UseShellExecute = true,
                            Verb            = "runas"
                        };

                        using (Process.Start(startInfo)) { }
                        Environment.Exit(0);
                    }
                }

                MeasurementKey.EstablishDefaultCache(database.Connection, database.AdapterType);
            }
            catch (Exception ex)
            {
                // First attempt to display a modal dialog will fail to block this
                // thread -- modal dialog displayed by the error logger will block now
                MessageBox.Show(ex.Message);

                // Log and display error, then exit application - manager must connect to database to continue
                m_errorLogger.Log(new InvalidOperationException($"{Title} cannot connect to database: {ex.Message}", ex), true);
            }
            finally
            {
                database?.Dispose();
            }

            IsolatedStorageManager.WriteToIsolatedStorage("MirrorMode", false);
        }
Example #37
0
 public Driver()
 {
     // added for testability purposes, should not be instansiated outside of test framework
     this.configFile = new ConfigurationFile(new XmlDocument());
     Init();
 }
Example #38
0
        private async Task WriteResponse(HttpServerRequest request, StreamSocket socket)
        {
            var relativeUrlLower = request.Url.ToLowerInvariant();
            var outputStream     = socket.OutputStream;

            //Get javascript files
            if (relativeUrlLower.StartsWith("/javascript"))
            {
                await HttpServerResponse.WriteResponseFile(ToFolderPath(request.Url), HttpContentType.JavaScript, outputStream);
            }
            //Get css style files
            else if (relativeUrlLower.StartsWith("/styles"))
            {
                await HttpServerResponse.WriteResponseFile(ToFolderPath(request.Url), HttpContentType.Css, outputStream);
            }
            //Get video setting
            else if (relativeUrlLower.StartsWith("/videosetting"))
            {
                HttpServerResponse.WriteResponseJson(ConfigurationFile.VideoSetting.Stringify(), outputStream);
            }
            //Get supported video settings
            else if (relativeUrlLower.StartsWith("/supportedvideosettings"))
            {
                HttpServerResponse.WriteResponseJson(ConfigurationFile.VideoSettingsSupported.Stringify(), outputStream);
            }
            //Set video settings
            else if (relativeUrlLower.StartsWith("/savevideosetting"))
            {
                await _camera.Stop();

                var videoSetting = new VideoSetting
                {
                    VideoSubtype    = VideoSubtypeHelper.Get(request.Body["VideoSubtype"].GetString()),
                    VideoResolution = (VideoResolution)request.Body["VideoResolution"].GetNumber(),
                    VideoQuality    = request.Body["VideoQuality"].GetNumber(),
                    UsedThreads     = (int)request.Body["UsedThreads"].GetNumber()
                };

                await ConfigurationFile.Write(videoSetting);

                await _camera.Initialize(videoSetting);

                _camera.Start();

                HttpServerResponse.WriteResponseOk(outputStream);
            }
            //Get current camera frame
            else if (relativeUrlLower.StartsWith("/videoframe"))
            {
                if (_camera.Frame != null)
                {
                    var webSocket = new WebSocket(socket, request, _camera);
                    await webSocket.Start();
                }
                else
                {
                    HttpServerResponse.WriteResponseError("Not camera fram available. Maybe there is an error or camera is not started.", outputStream);
                }
            }
            //Get index.html page
            else
            {
                await HttpServerResponse.WriteResponseFile(@"\Html\Index.html", HttpContentType.Html, outputStream);
            }
        }
Example #39
0
        public S3CommanderFile ResolvePath(string path)
        {
            S3CommanderFile file = null;

            if (path == null)
            {
                return(file);
            }

            var parts = path.TrimEnd('\\').Split('\\');
            var depth = parts.Length - 1;

            //root
            if (depth <= 0)
            {
                return(this);
            }

            //parent directory
            if (parts[depth] == "..")
            {
                return(file);
            }

            var accountName = parts[1];
            var bucketName  = 2 <= depth ? parts[2] : null;

            //accounts
            if (depth == 1)
            {
                if (RS.Settings.Equals(accountName, StringComparison.CurrentCultureIgnoreCase))
                {
                    file = new ConfigurationFile();
                }
                else if (RS.NewAccount.Equals(accountName, StringComparison.CurrentCultureIgnoreCase))
                {
                    file = new NewAccount(accountManager);
                }
                else
                {
                    file = new Account(accountManager, accountName);
                }
            }
            //buckets
            else if (depth == 2)
            {
                if (RS.NewBucket.Equals(bucketName, StringComparison.CurrentCultureIgnoreCase))
                {
                    file = new NewBucket();
                }
                else
                {
                    file = new Bucket(bucketName);
                }
            }
            //amazon s3 folder or file
            else
            {
                file = new Entry(bucketName, string.Join("/", parts, 3, depth - 2));
            }

            file.Initialize(Context, s3ServiceProvider.GetS3Service(accountName));
            return(file);
        }
 /// <inheritdoc />
 public Task DeleteEmptyDirectory(ConfigurationFile directory, CancellationToken cancellationToken) => apiClient.Delete(Routes.Configuration, directory, instance.Id, cancellationToken);
Example #41
0
 /// <summary>
 /// 对[connectionStrings]节点依据name值读取到connectionString值,返回字符串
 /// </summary>
 /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
 /// <param name="name">要读取的name值</param>
 /// <returns>返回connectionString值的字符串</returns>
 public static string ReadConnectionStringByName(ConfigurationFile configurationFile, string name)
 {
     string connectionString = string.Empty;
     string filename = string.Empty;
     if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
     {
         filename = System.Windows.Forms.Application.ExecutablePath + ".config";
     }
     else
     {
         filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
     }
     XmlDocument doc = new XmlDocument();
     doc.Load(filename); //加载配置文件
     XmlNode node = doc.SelectSingleNode("//connectionStrings");   //得到[appSettings]节点
     ////得到[connectionString]节点中关于name的子节点
     XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
     if (element != null)
     {
         connectionString = element.GetAttribute("connectionString");
     }
     return connectionString;
 }
 /// <inheritdoc />
 public Task <ConfigurationFile> CreateDirectory(ConfigurationFile directory, CancellationToken cancellationToken) => apiClient.Create <ConfigurationFile, ConfigurationFile>(Routes.Configuration, directory, instance.Id, cancellationToken);
Example #43
0
 /// <summary>
 /// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
 /// </summary>
 /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
 /// <param name="key">子节点Key值</param>
 /// <param name="value">子节点value值</param>
 /// <returns>返回成功与否布尔值</returns>
 public static bool UpdateOrCreateAppSetting(ConfigurationFile configurationFile, string key, string value)
 {
     bool isSuccess = false;
     string filename = string.Empty;
     if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
     {
         filename = System.Windows.Forms.Application.ExecutablePath + ".config";
     }
     else
     {
         filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
     }
     XmlDocument doc = new XmlDocument();
     doc.Load(filename); //加载配置文件
     XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点
     try
     {
         ////得到[appSettings]节点中关于Key的子节点
         XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
         if (element != null)
         {
             //存在则更新子节点Value
             element.SetAttribute("value", value);
         }
         else
         {
             //不存在则新增子节点
             XmlElement subElement = doc.CreateElement("add");
             subElement.SetAttribute("key", key);
             subElement.SetAttribute("value", value);
             node.AppendChild(subElement);
         }
         //保存至配置文件(方式一)
         using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
         {
             xmlwriter.Formatting = Formatting.Indented;
             doc.WriteTo(xmlwriter);
             xmlwriter.Flush();
         }
         isSuccess = true;
     }
     catch (Exception ex)
     {
         isSuccess = false;
         throw ex;
     }
     return isSuccess;
 }
 /// <inheritdoc />
 public Task <ConfigurationFile> Write(ConfigurationFile file, CancellationToken cancellationToken) => apiClient.Update <ConfigurationFile, ConfigurationFile>(Routes.Configuration, file ?? throw new ArgumentNullException(nameof(file)), instance.Id, cancellationToken);
Example #45
0
 public ElasticSearchCollector()
 {
     _configurationFile = ConfigurationService.Instance.ReadConfigurationFile();
     _isEnabled         = _configurationFile.ElasticSearch != null &&
                          (_configurationFile.ElasticSearch.Fields?.Any() ?? false);
 }
Example #46
0
 internal static void Import(ConfigProviderElement provider, ConfigurationFile sourceConfigurationFile)
 {
     foreach (Group wGrp in sourceConfigurationFile.Groups)
     {
         foreach (Fwk.Configuration.Common.Key wKey in wGrp.Keys)
         {
             if (ExistProperty(wGrp.Name, wKey.Name, provider))
             {
                 ChangeProperty(provider,wGrp.Name,wKey,wKey.Name);
             }
             else
             {
             AddProperty(provider, wKey, wGrp.Name);
             }
             
         }
     }
 }
Example #47
0
 public XmlNodeList GetConfigurationData(ConfigurationFile eConfigFile, string xpathquery)
 {
     return searcher.GetConfigurationData(eConfigFile, xpathquery);
 }
Example #48
0
        private void btnExport_Click(object sender, EventArgs e)
        {
            SqlConnection wConn = null;
            string wXmlText = string.Empty;
            ConfigurationFile wConfigFile = null;
            
            System.IO.FileInfo wFInfo = null;

            try
            {
                progressBar1.Value = 0;

                wConn = CreateConnection();
                if (wConn == null || !XmlValidationRequired())
                    return;

                progressBar1.Increment(2);

                //Obtengo los datos del xml
                wFInfo = new System.IO.FileInfo(txtXml.Text);
                wXmlText = Fwk.HelperFunctions.FileFunctions.OpenTextFile(txtXml.Text);
                wConfigFile = new ConfigurationFile();
                wConfigFile = ConfigurationFile.GetFromXml<ConfigurationFile>(wXmlText);
                if (wConfigFile.Groups == null)
                {
                    MessageBox.Show("No hay datos para migrar", "Exportar", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                progressBar1.Increment(48);

              
                progressBar1.Increment(40);
                ConfigProviderElement tempProvider = new ConfigProviderElement();
                tempProvider.BaseConfigFile = txtConfigFileName.Text;
                tempProvider.ConfigProviderType = ConfigProviderType.sqldatabase;
                tempProvider.SourceInfo = wConn.ConnectionString;
                tempProvider.SourceInfoIsConnectionString = true;
           

                Fwk.Configuration.ConfigurationManager_CRUD.Import(wConfigFile,tempProvider);
           

                progressBar1.Increment(10);

                MessageBox.Show("Exportación terminada exitosamente", "Exportar", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (wConn != null && wConn.State == ConnectionState.Open)
                    wConn.Close();
            }
        }
Example #49
0
 public XmlDocument GetConfigurationXml(ConfigurationFile eConfigFile)
 {
     return searcher.GetConfigurationXml(eConfigFile);
 }
Example #50
0
 public void LoadData(ConfigurationFile configurationFile)
 {
     if(_repository != null)
     {
         DetachFromRepository();
         _repository = null;
     }
     if(_configurationFile != configurationFile)
     {
         if(_configurationFile != null)
         {
             DetachFromConfigFile();
         }
         _configurationFile = configurationFile;
         if(_configurationFile != null)
         {
             AttachToConfigurationFile();
         }
     }
 }
        /// <summary>
        /// Obtiene un String con el contenido del archivo xml de configuracion. 
        /// Si este metodo es accedido desde el servicio web extrae la informacion de estado del archivo:
        /// Encrypt
        /// TTL
        /// ForceUpdate
        /// CurrentVersion
        /// BaseConfigFile
        /// Cacheable
        /// </summary>
        /// <param name="provider">Proveedor de configuración.</param>
        /// <Author>Marcelo Oviedo</Author>
        static ConfigurationFile SetConfigurationFile(ConfigProviderElement provider)
        {
            ConfigurationFile wConfigurationFile = new ConfigurationFile();


            string wFullFileName;
            if (System.IO.File.Exists(provider.BaseConfigFile))
            {
                wFullFileName = provider.BaseConfigFile;
            }
            else
            {
                //Application.StartupPath
                wFullFileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), provider.BaseConfigFile);
            }

            if (!System.IO.File.Exists(wFullFileName))
            {
                TechnicalException te = new TechnicalException(string.Concat("El archivo de artchivo de configuración ", provider.BaseConfigFile, " no existe. ", Environment.NewLine, "Revisar en el archivo .config de la aplicacion la configuración del proveedor [", provider.Name, "]"));
                te.ErrorId = "8011";
                Fwk.Exceptions.ExceptionHelper.SetTechnicalException(te, typeof(LocalFileConfigurationManager));
                throw te;

            }

            wConfigurationFile = ConfigurationFile.GetFromXml<ConfigurationFile>(Fwk.HelperFunctions.FileFunctions.OpenTextFile(wFullFileName));



            wConfigurationFile.FileName = wFullFileName;

            if (wConfigurationFile != null)
            {
                wConfigurationFile.TTL = wConfigurationFile.TTL;
                wConfigurationFile.Encrypted = wConfigurationFile.Encrypted;
                wConfigurationFile.ForceUpdate = wConfigurationFile.ForceUpdate;
                wConfigurationFile.CurrentVersion = wConfigurationFile.CurrentVersion;
                wConfigurationFile.ProviderName = provider.Name;

            }

            return wConfigurationFile;

        }
Example #52
0
        public static void Main(string[] args)
        {
            {
                // Quickest way to use Syllabore's name generator
                // without specifying any configuration. This instance
                // will default to using StandaloneSyllableProvider for
                // name generator and will not use any NameValidator to
                // improve output.
                var g = new NameGenerator();

                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(g.Next());
                }
            }
            {
                // Normally the constructor takes a SyllableProvider
                // and NameValidator. There are "Standalone" classes
                // available for quick and dirty use. It is recommended
                // you create your own by using ISyllableProvider/INameValidator
                // or inheriting from ConfigurableSyllableProvider/ConfigurableNameValidator.

                var provider  = new DefaultSyllableProvider();
                var validator = new NameValidator()
                                .DoNotAllowPattern(@"[j|p|q|w]$")             // Invalidate these awkward endings
                                .DoNotAllowPattern(@"(\w)\1\1")               // Invalidate any sequence of 3 or more identical letters
                                .DoNotAllowPattern(@"([^aeiouAEIOU])\1\1\1"); // Invalidate any sequence of 4 or more consonants

                var g = new NameGenerator(provider, validator);

                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(g.Next());
                }
            }
            {
                // You can choose to build name generators programmatically.
                var g = new NameGenerator()
                        .UsingProvider(x => x
                                       .WithLeadingConsonants("str")
                                       .WithVowels("ae"))
                        .LimitSyllableCount(3);

                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(g.Next());
                }

                Console.WriteLine();
            }

            {
                // Creating variations of a single name
                var g = new NameGenerator().UsingMutator(new VowelMutator());

                for (int i = 0; i < 3; i++)
                {
                    var name = g.NextName();
                    Console.WriteLine(name);

                    for (int j = 0; j < 4; j++)
                    {
                        var variation = g.Mutate(name);
                        Console.WriteLine(variation);
                    }
                }
            }

            {
                Console.WriteLine();
                var g = new NameGenerator()
                        .UsingProvider(p => p
                                       .WithVowels("aeoy")
                                       .WithLeadingConsonants("vstlr")
                                       .WithTrailingConsonants("zrt")
                                       .WithVowelSequences("ey", "ay", "oy"))
                        .UsingMutator(m => m
                                      .WithMutation(x => x.ReplaceSyllable(0, "Gran"))
                                      .WithMutation(x => x.ReplaceSyllable(0, "Bri"))
                                      .WithMutation(x => x.InsertSyllable(0, "Deu").AppendSyllable("gard").WithWeight(2))
                                      .WithMutation(x => x.When(-2, "[aeoyAEOY]$").ReplaceSyllable(-1, "opolis"))
                                      .WithMutation(x => x.When(-2, "[^aeoyAEOY]$").ReplaceSyllable(-1, "polis"))
                                      .WithMutationCount(1))
                        .UsingValidator(v => v
                                        .DoNotAllowPattern(
                                            @".{12,}",
                                            @"(\w)\1\1",             // Prevents any letter from occuring three times in a row
                                            @".*([y|Y]).*([y|Y]).*", // Prevents double y
                                            @".*([z|Z]).*([z|Z]).*", // Prevents double z
                                            @"(zs)",                 // Prevents "zs"
                                            @"(y[v|t])"))            // Prevents "yv" and "yt"
                        .LimitMutationChance(0.99)
                        .LimitSyllableCount(2, 4);

                ConfigurationFile.Save(g, "city-name-generator.txt");
                var g2 = ConfigurationFile.Load("city-name-generator.txt");

                for (int i = 0; i < 50; i++)
                {
                    var name = g.NextName();
                    Console.WriteLine(name);
                }

                Console.WriteLine();
            }
            {
                var provider = new SyllableProvider();
                provider.WithVowels("a", "e", "o", "y");
                provider.WithLeadingConsonants("v", "s", "t", "l", "r");
                provider.WithTrailingConsonants("z", "r", "t");
                provider.WithVowelSequences("ey", "ay", "oy");
                provider.DisallowLeadingConsonantSequences();
                provider.DisallowTrailingConsonantSequences();

                var shifter = new VowelMutator("a", "e", "o", "y");

                var validator = new NameValidator();
                validator.DoNotAllowPattern(@"(\w)\1\1");
                validator.DoNotAllowPattern(@"([^aeoyAEOY])\1");
                validator.DoNotAllowPattern(@".*([y|Y]).*([y|Y]).*");
                validator.DoNotAllowPattern(@".*([z|Z]).*([z|Z]).*");
                validator.DoNotAllowPattern(@"(zs)");
                validator.DoNotAllowPattern(@"(y[v|t])");

                var g = new NameGenerator(provider, shifter, validator);
                g.LimitSyllableCount(2, 3);
            }
            {
                var name    = new Name("syl", "la", "bore");
                var mutator = new NameMutator()
                              .Join(new DefaultNameMutator())
                              .Join(new VowelMutator());

                for (int i = 0; i < 20; i++)
                {
                    Console.WriteLine(mutator.Mutate(name));
                }
            }
        }
Example #53
0
        /// <summary>
        /// Busca en la base de datos el archivo de configuracion
        /// </summary>
        /// <param name="pFileName">Nombre de archivo.</param>
        /// <param name="provider">provider</param>
        /// <Author>Marcelo Oviedo</Author>
        static ConfigurationFile GetFromDatabase(string pFileName, ConfigProviderElement provider)
        {

            ConfigurationFile wConfigurationFile = new ConfigurationFile();
            wConfigurationFile.Groups = new Groups();
            string groupAuxiliar = string.Empty;
            Group g = null;
            Key k = null;
            wConfigurationFile.FileName = pFileName;

            try
            {
                using (FwkDatacontext dc = new FwkDatacontext(GetCnnString(provider)))
                {

                    IEnumerable<fwk_ConfigManager> fwk_ConfigManagerList = from s in dc.fwk_ConfigManagers
                                                                             where s.ConfigurationFileName.Equals(pFileName)

                                                                             select s;

                    foreach (fwk_ConfigManager fwk_Config in fwk_ConfigManagerList.OrderBy(p => p.group))
                    {
                        if (!groupAuxiliar.Equals(fwk_Config.group))
                        {
                            groupAuxiliar = Convert.ToString(fwk_Config.group);
                            g = new Group();
                            g.Name = groupAuxiliar;
                            wConfigurationFile.Groups.Add(g);
                        }

                        k = new Key();
                        k.Encrypted = fwk_Config.encrypted;
                        k.Name = fwk_Config.key;
                        k.Value.Text = fwk_Config.value;

                        g.Keys.Add(k);
                    }

                }
            }
            catch (Exception ex)
            {
                TechnicalException te = new TechnicalException("Problemas con Fwk.Configuration al realizar operaciones con la base de datos \r\n", ex);
                ExceptionHelper.SetTechnicalException<DatabaseConfigManager>(te);
                te.ErrorId = "8200";
                throw te;
            }

            return wConfigurationFile;
        }
 public SubscriberManager(ConfigurationFile configurationFile) : base(configurationFile)
 {
 }
Example #55
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sourceConfigurationFile"></param>
 /// <param name="provider"></param>
 public static void Import(ConfigurationFile sourceConfigurationFile, ConfigProviderElement provider)
 {
     
     if (provider == null) return;
     switch (provider.ConfigProviderType)
     {
         case ConfigProviderType.local:
             {
                 throw new NotImplementedException("Funcionalidad de exportacion no impolementada");
             }
         case ConfigProviderType.sqldatabase:
             {
                 DatabaseConfigManager.Import(provider, sourceConfigurationFile); break;
             }
         case ConfigProviderType.servicewrapper:
             {
                 throw new NotImplementedException("Funcionalidad de exportacion no impolementada");
             }
     }
    
 }
        /// <summary>
        /// Loads the config.
        /// </summary>
        private void LoadConfig()
        {
            try
            {
                var filePath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                filePath = System.IO.Path.Combine(filePath, Globals.ConfigFile);
                this.configuationSettings = new ConfigurationFile(filePath);

                if (this.configuationSettings.FormState == "Maximized")
                {
                    this.WindowState = WindowState.Maximized;
                }
                else if (this.configuationSettings.FormState == "Minimized")
                {
                    WindowState = WindowState.Minimized;
                }
                else
                {
                    WindowState = WindowState.Normal;
                }

                this.Left = this.configuationSettings.FormLeft;
                this.Top = this.configuationSettings.FormTop;
                this.Width = this.configuationSettings.FormWidth;
                this.Height = this.configuationSettings.FormHeight;

                this.ApplyMruSettings();
            }
            catch (System.Exception exp)
            {
                MessageBox.Show(
                    this,
                    (string)this.Resources["ConfigErrorLoadingMessage"] + exp.Message,
                    (string)this.Resources["ConfigurationErrorHeading"],
                    MessageBoxButton.OK,
                    MessageBoxImage.Exclamation);
            }
        }
Example #57
0
 /// <inheritdoc />
 public Task <ConfigurationFile> Write(ConfigurationFile file, CancellationToken cancellationToken) => apiClient.Update <ConfigurationFile, ConfigurationFile>(Routes.Configuration, file, instance.Id, cancellationToken);
        public ConfigurationFile Read(string inputFile)
        {
            try
            {
                string content = File.ReadAllText(inputFile);

                ConfigurationFile result = JsonConvert.DeserializeObject <ConfigurationFile>(content);

                string relativePath = Path.GetDirectoryName(inputFile) ?? "";
                //Set classLocation & resourceLocation if they are not set into the json file
                result.ClassLocation    = result.ClassLocation == null ? DefaultConfiguration.ClassLocation : PathHelper.Normalize(Path.Combine(relativePath, result.ClassLocation));
                result.ResourceLocation = result.ResourceLocation == null ? DefaultConfiguration.ResourceLocation : PathHelper.Normalize(Path.Combine(relativePath, result.ResourceLocation));
                if (string.IsNullOrWhiteSpace(result.GeneratedNamespace))
                {
                    result.GeneratedNamespace = DefaultConfiguration.GeneratedNamespace;
                }
                if (string.IsNullOrWhiteSpace(result.DefaultTemplateSelector))
                {
                    result.DefaultTemplateSelector = DefaultConfiguration.TemplateSelector;
                }
                if (string.IsNullOrWhiteSpace(result.DefaultTemplateSelectorField))
                {
                    result.DefaultTemplateSelectorField = DefaultConfiguration.TemplateSelectorField;
                }
                if (string.IsNullOrWhiteSpace(result.DefaultAdapter))
                {
                    result.DefaultAdapter = DefaultConfiguration.Adapter;
                }
                if (string.IsNullOrWhiteSpace(result.DefaultAdapterField))
                {
                    result.DefaultAdapterField = DefaultConfiguration.AdapterField;
                }
                if (!result.CaseSensitivity.HasValue)
                {
                    result.CaseSensitivity = DefaultConfiguration.CaseSensitivity;
                }

                //Add all default aliases if they have not been overriden
                Dictionary <string, string> aliases = result.Aliases.ToDictionary(x => x.Alias, x => x.FullClassName);
                foreach (AliasDescription alias in DefaultConfiguration.Aliases.Where(alias => !aliases.ContainsKey(alias.Alias)))
                {
                    result.Aliases.Add(alias);
                }

                //Add all default namespaces
                foreach (string name in DefaultConfiguration.Namespaces.Where(name => !result.Namespaces.Contains(name)))
                {
                    result.Namespaces.Add(name);
                }
                if (!result.Namespaces.Contains(result.GeneratedNamespace))
                {
                    result.Namespaces.Add(result.GeneratedNamespace);
                }
                result.Namespaces.Sort();


                List <string> resourceFiles = result.GlobalResourceFiles.Select(x => PathHelper.Normalize(Path.Combine(relativePath, x))).ToList();
                result.GlobalResourceFiles.Clear();
                result.GlobalResourceFiles.AddRange(resourceFiles);

                //Process files to complete with full path
                foreach (FileBindingDescription fileBinding in result.FileDescriptions)
                {
                    if (string.IsNullOrWhiteSpace(fileBinding.Activity.OutputFile))
                    {
                        // generate auto name for activity file
                        fileBinding.Activity.OutputFile = string.Format("{0}.{1}.cs", fileBinding.Activity.NamespaceName, fileBinding.Activity.ClassName);
                    }

                    if (string.IsNullOrWhiteSpace(fileBinding.View.OutputFile))
                    {
                        // generate auto name for view file
                        fileBinding.View.OutputFile = string.Format("{0}.axml", Path.GetFileNameWithoutExtension(fileBinding.View.InputFile));
                    }

                    // add full path as prefix to all file
                    fileBinding.Activity.OutputFile = PathHelper.Normalize(Path.Combine(result.ClassLocation, fileBinding.Activity.OutputFile));
                    fileBinding.View.OutputFile     = PathHelper.Normalize(Path.Combine(result.ResourceLocation, fileBinding.View.OutputFile));
                    fileBinding.View.InputFile      = PathHelper.Normalize(Path.Combine(relativePath, fileBinding.View.InputFile));
                }

                return(result);
            }
            catch (Exception)
            {
                BindingPreprocess.Logger.LogError("Cannot read input configuration file {0}", inputFile);
                throw;
            }
        }
Example #59
0
 public static IConfigurationSerializer GetSerializer(ConfigurationFile file)
 {
     return config[file];
 }
Example #60
0
        // Initializes the state keys to their default values.
        private void InitializeState()
        {
            bool   existing           = Convert.ToBoolean(m_state["existing"]);
            bool   migrate            = existing && Convert.ToBoolean(m_state["updateConfiguration"]);
            string newDatabaseMessage = "Please select the location in which to save the new database file.";
            string oldDatabaseMessage = "Please select the location of your existing database file.";

            ConfigurationFile serviceConfig;
            string            connectionString;
            string            dataProviderString;

            Dictionary <string, string> settings;
            string setting;

            m_sqliteDatabaseInstructionTextBlock.Text = (!existing || migrate) ? newDatabaseMessage : oldDatabaseMessage;

            try
            {
                // Set a default path for SQLite database that will allow non-restrictive read/write access
                // *** For the openMIC, we default this to ConfigurationCache folder so that DFS replication can be simple ***
                string sqliteDatabaseFilePath = string.Format("{0}{1}ConfigurationCache{1}", FilePath.GetAbsolutePath(""), Path.DirectorySeparatorChar);

                //string sqliteDatabaseFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "openMIC\\");

                // Make sure path exists

                if (!Directory.Exists(sqliteDatabaseFilePath))
                {
                    Directory.CreateDirectory(sqliteDatabaseFilePath);
                }

                m_sqliteDatabaseFilePathTextBox.Text = Path.Combine(sqliteDatabaseFilePath, migrate ? App.SqliteConfigv2 : App.BaseSqliteConfig); //"openMIC" + App.DatabaseVersionSuffix + ".db" : "openMIC.db");
            }
            catch
            {
                m_sqliteDatabaseFilePathTextBox.Text = migrate ? App.SqliteConfigv2 : App.BaseSqliteConfig; //"openMIC" + App.DatabaseVersionSuffix + ".db" : "openMIC.db";
            }

            if (!m_state.ContainsKey("sqliteDatabaseFilePath"))
            {
                m_state.Add("sqliteDatabaseFilePath", m_sqliteDatabaseFilePathTextBox.Text);
            }

            // When using an existing database as-is, read existing connection settings out of the configuration file
            string configFile = FilePath.GetAbsolutePath(App.ApplicationConfig);

            if (!File.Exists(configFile))
            {
                configFile = FilePath.GetAbsolutePath(App.ManagerConfig);
            }

            if (existing && !migrate && File.Exists(configFile))
            {
                serviceConfig      = ConfigurationFile.Open(configFile);
                connectionString   = serviceConfig.Settings["systemSettings"]["ConnectionString"]?.Value;
                dataProviderString = serviceConfig.Settings["systemSettings"]["DataProviderString"]?.Value;

                if (!string.IsNullOrEmpty(connectionString) && DataProviderString.Equals(dataProviderString, StringComparison.InvariantCultureIgnoreCase))
                {
                    settings = connectionString.ParseKeyValuePairs();

                    if (settings.TryGetValue("Data Source", out setting) && File.Exists(setting))
                    {
                        m_sqliteDatabaseFilePathTextBox.Text = setting;
                    }
                }
            }
        }