Esempio n. 1
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                // Set current principal and attempt host service connection
                CommonFunctions.CurrentPrincipal            = SecurityPrincipal;
                CommonFunctions.ServiceConnectionRefreshed += CommonFunctions_ServiceConnectionRefreshed;
                Program.HostNodeID.SetAsCurrentNodeID();
            }
            catch (Exception ex)
            {
                ShowUpdateMessage($"ERROR: Failed to initialize service connection: {ex.Message}");
                m_log.Publish(MessageLevel.Error, "Initialize Service Connection", exception: ex);
            }

            try
            {
                Text += " - " + SecurityPrincipal.Identity.Provider.UserData.LoginID;

                m_database = Program.GetDatabaseConnection();

                if (m_database is null)
                {
                    throw new InvalidOperationException("Failed to connect to database.");
                }

                MeasurementKey.EstablishDefaultCache(m_database.Connection, m_database.AdapterType);

                // Load current settings registering a symbolic reference to this form instance for use by default value expressions
                m_settings = new Settings(new Dictionary <string, object> {
                    { "Form", this }
                }.RegisterSymbols());

                // Restore last window size/location
                this.RestoreLayout();

                LoadDataSource();

                InitializeDataGrid(dataGridViewInputMeasurements);
                InitializeDataGrid(dataGridViewOutputMeasurements);

                InitializeDataSubscriber();
                LoadAdapters(false);

                SetBottomPanelWidths();

                m_formLoaded = true;
            }
            catch (Exception ex)
            {
                ShowUpdateMessage($"ERROR: Failed during load: {ex.Message}");
                m_log.Publish(MessageLevel.Error, "FormLoad", exception: ex);

            #if DEBUG
                throw;
            #endif
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Creates an instance of <see cref="App"/> class.
        /// </summary>
        public App()
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

            m_errorLogger                          = new ErrorLogger();
            m_defaultErrorText                     = m_errorLogger.ErrorTextMethod;
            m_errorLogger.ErrorTextMethod          = ErrorText;
            m_errorLogger.ExitOnUnhandledException = false;
            m_errorLogger.HandleUnhandledException = true;
            m_errorLogger.LogToEmail               = false;
            m_errorLogger.LogToEventLog            = true;
            m_errorLogger.LogToFile                = true;
            m_errorLogger.LogToScreenshot          = true;
            m_errorLogger.LogToUI                  = true;
            m_errorLogger.Initialize();

            m_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);
                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(string.Format("{0} cannot connect to database: {1}", m_title, ex.Message), ex), true);
            }
            finally
            {
                if (database != null)
                {
                    database.Dispose();
                }
            }

            IsolatedStorageManager.WriteToIsolatedStorage("MirrorMode", false);
        }
Esempio n. 3
0
        /// <summary>
        /// Creates an instance of <see cref="App"/> class.
        /// </summary>
        public App()
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

            m_errorLogger                          = new ErrorLogger();
            m_defaultErrorText                     = m_errorLogger.ErrorTextMethod;
            m_errorLogger.ErrorTextMethod          = ErrorText;
            m_errorLogger.ExitOnUnhandledException = false;
            m_errorLogger.HandleUnhandledException = true;
            m_errorLogger.LogToEmail               = false;
            m_errorLogger.LogToEventLog            = true;
            m_errorLogger.LogToFile                = true;
            m_errorLogger.LogToScreenshot          = true;
            m_errorLogger.LogToUI                  = true;
            m_errorLogger.Initialize();

            m_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;

                    if (!string.IsNullOrEmpty(elevateSetting))
                    {
                        elevateProcess = elevateSetting.ParseBoolean();
                    }
                    else
                    {
                        elevateProcess = database.IsSqlite;
                    }

                    if (elevateProcess && !Environment.CommandLine.Contains("-elevated"))
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo();
                        startInfo.FileName        = Environment.GetCommandLineArgs()[0];
                        startInfo.Arguments       = string.Join(" ", Environment.GetCommandLineArgs().Skip(1)) + " -elevated";
                        startInfo.UseShellExecute = true;
                        startInfo.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(string.Format("{0} cannot connect to database: {1}", m_title, ex.Message), ex), true);
            }
            finally
            {
                if (database != null)
                {
                    database.Dispose();
                }
            }

            IsolatedStorageManager.WriteToIsolatedStorage("MirrorMode", false);
        }
Esempio n. 4
0
        /// <summary>
        /// Creates an instance of <see cref="App"/> class.
        /// </summary>
        public App()
        {
            bool mirrorMode = true;

            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

            m_errorLogger                          = new ErrorLogger();
            m_defaultErrorText                     = m_errorLogger.ErrorTextMethod;
            m_errorLogger.ErrorTextMethod          = ErrorText;
            m_errorLogger.ExitOnUnhandledException = false;
            m_errorLogger.HandleUnhandledException = true;
            m_errorLogger.LogToEmail               = false;
            m_errorLogger.LogToEventLog            = true;
            m_errorLogger.LogToFile                = true;
            m_errorLogger.LogToScreenshot          = true;
            m_errorLogger.LogToUI                  = true;
            m_errorLogger.Initialize();

            m_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);
                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(string.Format("{0} cannot connect to database: {1}", m_title, ex.Message), ex), true);
            }
            finally
            {
                if (database != null)
                {
                    database.Dispose();
                }
            }

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

                if ((object)mirrorModeSetting != 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(string.Format("{0} cannot access mirror mode setting in configuration file - defaulting to true: {1}", m_title, ex.Message), ex));
            }

            IsolatedStorageManager.WriteToIsolatedStorage("MirrorMode", mirrorMode);
        }
Esempio n. 5
0
        /// <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);
        }