示例#1
0
        // Gets a database connection object using the connection information that is stored in the configuration file.
        private IDbConnection GetConnectionFromConfigFile()
        {
            IDbConnection connection     = null;
            string        configFileName = Directory.GetCurrentDirectory() + "\\" + App.ApplicationConfig;

            ConfigurationFile configFile;
            string            connectionString;
            string            dataProviderString;

            try
            {
                configFile         = ConfigurationFile.Open(configFileName);
                connectionString   = configFile.Settings["systemSettings"]["ConnectionString"]?.Value;
                dataProviderString = configFile.Settings["systemSettings"]["DataProviderString"]?.Value;

                if ((object)connectionString != null && (object)dataProviderString != null)
                {
                    connection = GetConnection(connectionString, dataProviderString);
                }
            }
            catch
            {
                // Ignore file not found and similar exceptions.
                // Failure to retrieve the node list should not
                // interrupt the setup.
            }

            return(connection);
        }
示例#2
0
文件: Program.cs 项目: lyrain2009/gsf
        public static void Main(string[] args)
        {
            CategorizedSettingsElementCollection systemSettings = ConfigurationFile.Open(GetConfigurationFileName(args)).Settings["systemSettings"];
            string  cachePath = string.Format("{0}{1}ConfigurationCache{1}", FilePath.GetAbsolutePath(""), Path.DirectorySeparatorChar);
            DataSet configuration;

            systemSettings.Add("NodeID", Guid.NewGuid().ToString(), "Unique Node ID");
            systemSettings.Add("ConfigurationType", "Database", "Specifies type of configuration: Database, WebService, BinaryFile or XmlFile");
            systemSettings.Add("ConnectionString", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=IaonHost.mdb", "Configuration database connection string");
            systemSettings.Add("DataProviderString", "AssemblyName={System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089};ConnectionType=System.Data.OleDb.OleDbConnection;AdapterType=System.Data.OleDb.OleDbDataAdapter", "Configuration database ADO.NET data provider assembly type creation string");
            systemSettings.Add("ConfigurationCachePath", cachePath, "Defines the path used to cache serialized configurations");
            systemSettings.Add("CachedConfigurationFile", "SystemConfiguration.xml", "File name for last known good system configuration (only cached for a Database or WebService connection)");
            systemSettings.Add("ConfigurationBackups", 5, "Defines the total number of older backup configurations to maintain.");

            s_nodeID                        = systemSettings["NodeID"].ValueAs <Guid>();
            s_configurationType             = systemSettings["ConfigurationType"].ValueAs <ConfigurationType>();
            s_connectionString              = systemSettings["ConnectionString"].Value;
            s_dataProviderString            = systemSettings["DataProviderString"].Value;
            s_cachedXmlConfigurationFile    = FilePath.AddPathSuffix(cachePath) + systemSettings["CachedConfigurationFile"].Value;
            s_cachedBinaryConfigurationFile = FilePath.AddPathSuffix(cachePath) + FilePath.GetFileNameWithoutExtension(s_cachedXmlConfigurationFile) + ".bin";
            s_configurationBackups          = systemSettings["ConfigurationBackups"].ValueAs(5);

            configuration = GetConfigurationDataSet();
            ExecuteConfigurationCache(configuration);

            Console.WriteLine("Press 'Enter' to exit...");
            Console.ReadLine();
        }
示例#3
0
        private void MainWindow_Load(object sender, EventArgs e)
        {
            Type   sqliteConnectionType  = typeof(System.Data.SQLite.SQLiteConnection);
            Type   sqliteAdapterType     = typeof(System.Data.SQLite.SQLiteDataAdapter);
            string assemblyName          = sqliteConnectionType.Assembly.FullName;
            string memConnectionString   = $"Data Source=:memory:; Version=3; Foreign Keys=True; FailIfMissing=True";
            string memDataProviderString = $"AssemblyName={{{assemblyName}}}; ConnectionType={sqliteConnectionType.FullName}; AdapterType={sqliteAdapterType.FullName}";

            DataProviderLookup["SQLite"] = memDataProviderString;

            ConfigurationFile configurationFile = ConfigurationFile.Current;
            CategorizedSettingsElementCollection applicationSettings = configurationFile.Settings["applicationSettings"];

            DBConnectionString    = applicationSettings["ConnectionString"]?.Value;
            DBDataProviderString  = applicationSettings["DataProviderString"]?.Value;
            SerializedSchema      = applicationSettings["SerializedSchema"]?.Value;
            HostConfigurationFile = applicationSettings["HostConfigurationFile"]?.Value;

            if (!string.IsNullOrEmpty(HostConfigurationFile))
            {
                ConfigurationFile hostConfigurationFile             = ConfigurationFile.Open(HostConfigurationFile);
                CategorizedSettingsElementCollection systemSettings = hostConfigurationFile.Settings["systemSettings"];
                HostConnectionString   = systemSettings["ConnectionString"]?.Value;
                HostDataProviderString = systemSettings["DataProviderString"]?.Value;

                if (string.IsNullOrEmpty(DBConnectionString))
                {
                    DBConnectionString = HostConnectionString;
                }

                if (string.IsNullOrEmpty(DBDataProviderString))
                {
                    DBDataProviderString = HostDataProviderString;
                }
            }

            ConnectionStringTextBox.Text = DBConnectionString;
            DataProviderTextBox.Text     = DBDataProviderString;
            SerializedSchemaTextBox.Text = SerializedSchema;

            MemSchema = new Schema($"{memConnectionString}; DataProviderString={{{memDataProviderString}}}", analyzeNow: false);
            DBSchema  = new Schema();

            try
            {
                UpdateDBSchema();
            }
            catch (Exception ex)
            {
                string message = $"Error opening connection to database: {ex.Message}";
                MessageBox.Show(message, "Database error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                MainTabControl.SelectedTab = ConfigurationTabPage;
            }
        }
        // Attempts to load old connection string parameters
        private void LoadOldConnectionStrings(string configFileName)
        {
            if ((object)m_oldConnectionString != null && (object)m_oldDataProviderString != null)
            {
                return;
            }

            ConfigurationFile                    configFile          = ConfigurationFile.Open(configFileName);
            CategorizedSettingsSection           categorizedSettings = configFile.Settings;
            CategorizedSettingsElementCollection systemSettings      = categorizedSettings["systemSettings"];

            m_oldConnectionString   = systemSettings["ConnectionString"]?.Value;
            m_oldDataProviderString = systemSettings["DataProviderString"]?.Value;
        }
示例#5
0
        private static AdoDataConnection OpenDatabaseConnection()
        {
            // Access openMIC database configuration settings
            string configFileName = FilePath.GetAbsolutePath("openMIC.exe.config");

            if (!File.Exists(configFileName))
            {
                throw new FileNotFoundException($"Failed to open configuration file \"{configFileName}\" - file does not exist.");
            }

            ConfigurationFile                    configFile          = ConfigurationFile.Open(configFileName);
            CategorizedSettingsSection           categorizedSettings = configFile.Settings;
            CategorizedSettingsElementCollection systemSettings      = categorizedSettings["systemSettings"];

            return(new AdoDataConnection(systemSettings["ConnectionString"]?.Value, systemSettings["DataProviderString"]?.Value));
        }
示例#6
0
        static eDNAGrafanaController()
        {
            CategorizedSettingsElementCollection systemSettings = ConfigurationFile.Open("openHistorian.exe.config").Settings["systemSettings"];

            if (!systemSettings["eDNAGrafanaControllerEnabled", true]?.Value.ParseBoolean() ?? true)
            {
                return;
            }

            using (FileBackedDictionary <string, eDNADataSource> FileBackedDataSources = new FileBackedDictionary <string, eDNADataSource>(FileBackedDictionary))
            {
                DataSources = new ConcurrentDictionary <string, eDNADataSource>(FileBackedDataSources);
            }

            string      eDNAMetaData = systemSettings["eDNAMetaData"]?.Value ?? "*.*";
            List <Task> tasks        = new List <Task>();

            foreach (string setting in eDNAMetaData.Split(','))
            {
                string site    = setting.Split('.')[0].ToUpper();
                string service = setting.Split('.')[1].ToUpper();

                if (!DataSources.ContainsKey($"{site}.{service}"))
                {
                    DataSources.AddOrUpdate($"{site}.{service}", new eDNADataSource(site, service));
                }

                tasks.Add(Task.Factory.StartNew(() => RefreshMetaData(site, service)));
            }

            Task.Factory.ContinueWhenAll(tasks.ToArray(), continuationTask =>
            {
                using (FileBackedDictionary <string, eDNADataSource> FileBackedDataSources = new FileBackedDictionary <string, eDNADataSource>(FileBackedDictionary))
                {
                    foreach (KeyValuePair <string, eDNADataSource> kvp in DataSources)
                    {
                        FileBackedDataSources[kvp.Key] = kvp.Value;
                    }
                    FileBackedDataSources.Compact();
                }
            });
        }
        // 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
                string sqliteDatabaseFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SIEGate\\");

                // Make sure path exists

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

                m_sqliteDatabaseFilePathTextBox.Text = Path.Combine(sqliteDatabaseFilePath, migrate ? App.SqliteConfigv2 : App.BaseSqliteConfig);
            }
            catch
            {
                m_sqliteDatabaseFilePathTextBox.Text = migrate ? App.SqliteConfigv2 : App.BaseSqliteConfig;
            }

            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;
                    }
                }
            }
        }
        // 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\nSQL Server database you would like to create.";
                string     oldDatabaseMessage = "Please enter the needed information about\r\nyour existing SQL Server database.";

                ConfigurationFile serviceConfig;
                string            connectionString;
                string            dataProviderString;

                m_state["sqlServerSetup"]                    = m_sqlServerSetup;
                m_sqlServerSetup.HostName                    = m_hostNameTextBox.Text;
                m_sqlServerSetup.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_sqlServerDatabaseInstructionTextBlock.Text = (!existing || migrate) ? newDatabaseMessage : oldDatabaseMessage;
                m_checkBoxIntegratedSecurity.IsChecked       = true;

                // 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:"******"createNewSqlServerUser"))
                {
                    m_state.Add("createNewSqlServerUser", m_createNewUserCheckBox.IsChecked.Value);
                }

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

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

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

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

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

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

                if (!File.Exists(configFile))
                {
                    configFile = FilePath.GetAbsolutePath(App.ManagerConfig);//"openPDCManager.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_sqlServerSetup.DataProviderString.Equals(dataProviderString, StringComparison.InvariantCultureIgnoreCase))
                    {
                        m_sqlServerSetup.ConnectionString            = connectionString;
                        m_hostNameTextBox.Text                       = m_sqlServerSetup.HostName;
                        m_databaseNameTextBox.Text                   = m_sqlServerSetup.DatabaseName;
                        m_adminUserNameTextBox.Text                  = m_sqlServerSetup.UserName;
                        m_adminPasswordTextBox.Password              = m_sqlServerSetup.Password;
                        m_checkBoxIntegratedSecurity.IsChecked       = ((object)m_sqlServerSetup.IntegratedSecurity != null);
                        m_state["encryptSqlServerConnectionStrings"] = serviceConfig.Settings["systemSettings"]["ConnectionString"].Encrypted;
                    }
                }
            }
        }
            /// <summary>
            /// Starts a query that will read data source values, given a set of point IDs and targets, over a time range.
            /// </summary>
            /// <param name="startTime">Start-time for query.</param>
            /// <param name="stopTime">Stop-time for query.</param>
            /// <param name="interval">Interval from Grafana request.</param>
            /// <param name="decimate">Flag that determines if data should be decimated over provided time range.</param>
            /// <param name="targetMap">Set of IDs with associated targets to query.</param>
            /// <returns>Queried data source data in terms of value and time.</returns>
            protected override IEnumerable <DataSourceValue> QueryDataSourceValues(DateTime startTime, DateTime stopTime, string interval, bool decimate, Dictionary <ulong, string> targetMap)
            {
                SnapServer server = GetAdapterInstance(InstanceName)?.Server?.Host;

                if ((object)server == null)
                {
                    yield break;
                }

                using (SnapClient connection = SnapClient.Connect(server))
                    using (ClientDatabaseBase <HistorianKey, HistorianValue> database = connection.GetDatabase <HistorianKey, HistorianValue>(InstanceName))
                    {
                        if ((object)database == null)
                        {
                            yield break;
                        }

                        Resolution resolution = TrendValueAPI.EstimatePlotResolution(InstanceName, startTime, stopTime, targetMap.Keys);
                        SeekFilterBase <HistorianKey> timeFilter;

                        // Set data scan resolution
                        if (!decimate || resolution == Resolution.Full)
                        {
                            timeFilter = TimestampSeekFilter.CreateFromRange <HistorianKey>(startTime, stopTime);
                        }
                        else
                        {
                            TimeSpan             resolutionInterval = resolution.GetInterval();
                            BaselineTimeInterval timeInterval       = BaselineTimeInterval.Second;

                            if (resolutionInterval.Ticks < Ticks.PerMinute)
                            {
                                timeInterval = BaselineTimeInterval.Second;
                            }
                            else if (resolutionInterval.Ticks < Ticks.PerHour)
                            {
                                timeInterval = BaselineTimeInterval.Minute;
                            }
                            else if (resolutionInterval.Ticks == Ticks.PerHour)
                            {
                                timeInterval = BaselineTimeInterval.Hour;
                            }

                            startTime = startTime.BaselinedTimestamp(timeInterval);
                            stopTime  = stopTime.BaselinedTimestamp(timeInterval);

                            int milliseconds = 1;
                            try
                            {
                                ConfigurationFile                    configFile          = ConfigurationFile.Open(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                                CategorizedSettingsSection           categorizedSettings = configFile.Settings;
                                CategorizedSettingsElementCollection systemSettings      = categorizedSettings["systemSettings"];
                                string val = systemSettings["HistoryTolerance"].Value;
                            }
                            catch { } // something went wrong, so just use original default

                            timeFilter = TimestampSeekFilter.CreateFromIntervalData <HistorianKey>(startTime, stopTime, resolutionInterval, new TimeSpan(TimeSpan.TicksPerMillisecond * milliseconds));
                        }

                        // Setup point ID selections
                        MatchFilterBase <HistorianKey, HistorianValue> pointFilter = PointIdMatchFilter.CreateFromList <HistorianKey, HistorianValue>(targetMap.Keys);

                        // Start stream reader for the provided time window and selected points
                        using (TreeStream <HistorianKey, HistorianValue> stream = database.Read(SortedTreeEngineReaderOptions.Default, timeFilter, pointFilter))
                        {
                            HistorianKey   key   = new HistorianKey();
                            HistorianValue value = new HistorianValue();

                            while (stream.Read(key, value))
                            {
                                yield return(new DataSourceValue
                                {
                                    Target = targetMap[key.PointID],
                                    Time = (key.Timestamp - m_baseTicks) / (double)Ticks.PerMillisecond,
                                    Value = value.AsSingle,
                                    Flags = (MeasurementStateFlags)value.Value3
                                });
                            }
                        }
                    }
            }
        // 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:"******"openPDC" + App.DatabaseVersionSuffix : "openPDC";

                // 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;
                    }
                }
            }
        }
        // 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:"******"TSFCloudIO" + App.DatabaseVersionSuffix : "TSFCloudIO";

                // 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;
                    }
                }
            }
        }
示例#12
0
        private void CheckEngineStatus()
        {
            string            configurationPath = Path.Combine("FileWatcher", "openXDAFileWatcherConsole.exe.config");
            string            absolutePath      = FilePath.GetAbsolutePath(configurationPath);
            ConfigurationFile configurationFile = ConfigurationFile.Open(absolutePath);
            CategorizedSettingsElementCollection remotingClientSettings = configurationFile.Settings["remotingClient"];

            string connectionString   = remotingClientSettings["ConnectionString"]?.Value ?? "Server=localhost:9999";
            string integratedSecurity = remotingClientSettings["IntegratedSecurity"]?.Value ?? "True";

            using (ClientHelper helper = new ClientHelper())
                using (TcpClient remotingClient = new TcpClient())
                {
                    string           engineStatus = "";
                    ManualResetEvent waitHandle   = new ManualResetEvent(false);

                    remotingClient.ConnectionString   = connectionString;
                    remotingClient.IntegratedSecurity = integratedSecurity.ParseBoolean();
                    remotingClient.PayloadAware       = true;

                    helper.StatusMessageFilter    = "FILTER -Exclude Message \"\"";
                    helper.RemotingClient         = remotingClient;
                    helper.AuthenticationFailure += (sender, args) => waitHandle.Set();

                    helper.AuthenticationSuccess += (sender, args) =>
                    {
                        EventHandler <EventArgs <UpdateType, string> > handler = null;

                        handler = (obj, e) =>
                        {
                            helper.ReceivedServiceUpdate -= handler;
                            engineStatus = e.Argument2;
                            waitHandle.Set();
                        };

                        helper.ReceivedServiceUpdate += handler;
                        helper.SendRequest("EngineStatus");
                    };

                    helper.ReceivedServiceResponse += (sender, args) =>
                    {
                        engineStatus = args.Argument.Message;
                        waitHandle.Set();
                    };

                    helper.Connect();
                    waitHandle.WaitOne();

                    if (string.IsNullOrEmpty(engineStatus))
                    {
                        return;
                    }

                    bool isEnumerating = engineStatus
                                         .Split('\r', '\n')
                                         .Where(line => line.Trim().StartsWith("Is Enumerating: "))
                                         .Select(line => line.Split(':')[1].Trim())
                                         .Select(value => value.ParseBoolean())
                                         .DefaultIfEmpty(false)
                                         .First();

                    if (!isEnumerating)
                    {
                        m_enumeratingCount = 0;
                    }
                    else if (engineStatus != m_engineStatus)
                    {
                        m_enumeratingCount = 1;
                    }
                    else
                    {
                        m_enumeratingCount++;
                    }

                    if (m_enumeratingCount >= 3)
                    {
                        RestartFileWatcher();
                        m_enumeratingCount = 0;
                    }

                    m_engineStatus = engineStatus;
                }
        }
示例#13
0
        /// <summary>
        /// Read historian data from server.
        /// </summary>
        /// <param name="server">The server to use for the query.</param>
        /// <param name="instanceName">Name of the archive to be queried.</param>
        /// <param name="startTime">Start time of query.</param>
        /// <param name="stopTime">Stop time of query.</param>
        /// <param name="measurementIDs">Measurement IDs to query - or <c>null</c> for all available points.</param>
        /// <param name="resolution">Resolution for data query.</param>
        /// <param name="seriesLimit">Maximum number of points per series.</param>
        /// <param name="forceLimit">Flag that determines if series limit should be strictly enforced.</param>
        /// <param name="cancellationToken">Cancellation token for query.</param>
        /// <returns>Enumeration of <see cref="TrendValue"/> instances read for time range.</returns>
        public static IEnumerable <TrendValue> GetHistorianData(SnapServer server, string instanceName, DateTime startTime, DateTime stopTime, ulong[] measurementIDs, Resolution resolution, int seriesLimit, bool forceLimit, ICancellationToken cancellationToken = null)
        {
            if ((object)cancellationToken == null)
            {
                cancellationToken = new CancellationToken();
            }

            if ((object)server == null)
            {
                yield break;
            }

            // Setting series limit to zero requests full resolution data, which overrides provided parameter
            if (seriesLimit < 1)
            {
                resolution = Resolution.Full;
            }

            TimeSpan resolutionInterval = resolution.GetInterval();
            SeekFilterBase <HistorianKey> timeFilter;
            MatchFilterBase <HistorianKey, HistorianValue> pointFilter = null;
            HistorianKey   key   = new HistorianKey();
            HistorianValue value = new HistorianValue();

            // Set data scan resolution
            if (resolution == Resolution.Full)
            {
                timeFilter = TimestampSeekFilter.CreateFromRange <HistorianKey>(startTime, stopTime);
            }
            else
            {
                BaselineTimeInterval interval = BaselineTimeInterval.Second;

                if (resolutionInterval.Ticks < Ticks.PerMinute)
                {
                    interval = BaselineTimeInterval.Second;
                }
                else if (resolutionInterval.Ticks < Ticks.PerHour)
                {
                    interval = BaselineTimeInterval.Minute;
                }
                else if (resolutionInterval.Ticks == Ticks.PerHour)
                {
                    interval = BaselineTimeInterval.Hour;
                }

                startTime = startTime.BaselinedTimestamp(interval);
                stopTime  = stopTime.BaselinedTimestamp(interval);

                int milliseconds = 1;
                try
                {
                    ConfigurationFile                    configFile          = ConfigurationFile.Open(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                    CategorizedSettingsSection           categorizedSettings = configFile.Settings;
                    CategorizedSettingsElementCollection systemSettings      = categorizedSettings["systemSettings"];
                    string val = systemSettings["HistoryTolerance"].Value;
                }
                catch { } // something went wrong, so just use original default

                timeFilter = TimestampSeekFilter.CreateFromIntervalData <HistorianKey>(startTime, stopTime, resolutionInterval, new TimeSpan(TimeSpan.TicksPerMillisecond * milliseconds));
            }

            Dictionary <ulong, DataRow> metadata = null;
            LocalOutputAdapter          historianAdapter;

            using (SnapClient connection = SnapClient.Connect(server))
                using (ClientDatabaseBase <HistorianKey, HistorianValue> database = connection.GetDatabase <HistorianKey, HistorianValue>(instanceName))
                {
                    if ((object)database == null)
                    {
                        yield break;
                    }

                    if (LocalOutputAdapter.Instances.TryGetValue(database.Info?.DatabaseName ?? DefaultInstanceName, out historianAdapter))
                    {
                        metadata = historianAdapter?.Measurements;
                    }

                    if ((object)metadata == null)
                    {
                        yield break;
                    }

                    // Setup point ID selections
                    if ((object)measurementIDs != null)
                    {
                        pointFilter = PointIdMatchFilter.CreateFromList <HistorianKey, HistorianValue>(measurementIDs);
                    }
                    else
                    {
                        measurementIDs = metadata.Keys.ToArray();
                    }

                    // Start stream reader for the provided time window and selected points
                    Dictionary <ulong, long>  pointCounts = new Dictionary <ulong, long>(measurementIDs.Length);
                    Dictionary <ulong, long>  intervals   = new Dictionary <ulong, long>(measurementIDs.Length);
                    Dictionary <ulong, ulong> lastTimes   = new Dictionary <ulong, ulong>(measurementIDs.Length);
                    double  range = (stopTime - startTime).TotalSeconds;
                    ulong   pointID, timestamp, resolutionSpan = (ulong)resolutionInterval.Ticks, baseTicks = (ulong)UnixTimeTag.BaseTicks.Value;
                    long    pointCount;
                    DataRow row;

                    if (resolutionSpan <= 1UL)
                    {
                        resolutionSpan = Ticks.PerSecond;
                    }

                    if (seriesLimit < 1)
                    {
                        seriesLimit = 1;
                    }

                    // Estimate total measurement counts per point so decimation intervals for each series can be calculated
                    foreach (ulong measurementID in measurementIDs)
                    {
                        if (resolution == Resolution.Full)
                        {
                            pointCounts[measurementID] = metadata.TryGetValue(measurementID, out row) ? (long)(int.Parse(row["FramesPerSecond"].ToString()) * range) : 2;
                        }
                        else
                        {
                            pointCounts[measurementID] = (long)(range / resolutionInterval.TotalSeconds.NotZero(1.0D));
                        }
                    }

                    foreach (ulong measurementID in pointCounts.Keys)
                    {
                        intervals[measurementID] = (pointCounts[measurementID] / seriesLimit).NotZero(1L);
                    }

                    using (TreeStream <HistorianKey, HistorianValue> stream = database.Read(SortedTreeEngineReaderOptions.Default, timeFilter, pointFilter))
                    {
                        while (stream.Read(key, value) && !cancellationToken.IsCancelled)
                        {
                            pointID    = key.PointID;
                            timestamp  = key.Timestamp;
                            pointCount = pointCounts[pointID];

                            if (pointCount++ % intervals[pointID] == 0 || (!forceLimit && timestamp - lastTimes.GetOrAdd(pointID, 0UL) > resolutionSpan))
                            {
                                yield return new TrendValue
                                       {
                                           ID        = (long)pointID,
                                           Timestamp = (timestamp - baseTicks) / (double)Ticks.PerMillisecond,
                                           Value     = value.AsSingle
                                       }
                            }
                            ;

                            pointCounts[pointID] = pointCount;
                            lastTimes[pointID]   = timestamp;
                        }
                    }
                }
        }
    }
示例#14
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 LinearStateEstimator, 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), "LinearStateEstimator\\");

                // Make sure path exists

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

                m_sqliteDatabaseFilePathTextBox.Text = Path.Combine(sqliteDatabaseFilePath, migrate ? "LinearStateEstimator" + App.DatabaseVersionSuffix + ".db" : "LinearStateEstimator.db");
            }
            catch
            {
                m_sqliteDatabaseFilePathTextBox.Text = migrate ? "LinearStateEstimator" + App.DatabaseVersionSuffix + ".db" : "LinearStateEstimator.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("LinearStateEstimator.exe.config");

            if (!File.Exists(configFile))
            {
                configFile = FilePath.GetAbsolutePath("LinearStateEstimatorManager.exe.config");
            }

            if (existing && !migrate)
            {
                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;
                    }
                }
            }
        }