/// <summary>
        ///
        /// </summary>
        private void InitializeServiceComponents()
        {
            try
            {
                InitializeEventLog();
            }
            catch { }

            try
            {
                InitializePaths();

                if (!System.IO.File.Exists(this.guiExePath))
                {
                    EventLog.WriteEntry("Main application assembly file is missing.\n\n" +
                                        "Application must be properly installed in order to access required assembly information and paths.",
                                        EventLogEntryType.Error, SVC_INIT_EVENT_ID);
                    return;
                }

                if (!System.IO.File.Exists(this.thisSvcExePath))
                {
                    EventLog.WriteEntry("Service assembly file is missing.\n\n" +
                                        "Application must be properly installed in order to access required assembly information and paths.",
                                        EventLogEntryType.Error, SVC_INIT_EVENT_ID);
                    return;
                }

                try
                {
                    MattimonAgentLibrary.Tools.ProjectAssemblyAtrributes thisSvcAssemAttr =
                        new MattimonAgentLibrary.Tools.ProjectAssemblyAtrributes(
                            this.thisSvcExePath);


                    String message = "";
                    message = String.Format(

                        "{0}->InitializeServiceComponents\n\n" +
                        "Application path: {1}\n" +
                        "Service path: {2}\n" +
                        "Service path (Win32_Services->PathName): {3}\n\n" +
                        "MattimonAgentApplication.exe assembly information:\n\n" +
                        "Title: {4}\n" +
                        "Company: {5}\n" +
                        "Product: {6}\n" +
                        "Version: {7}\n\n" +
                        "CommonAppData directory: {8}",

                        ServiceName,
                        this.guiExePath,
                        this.thisSvcExePath,
                        MattimonAgentLibrary.Tools.MyServiceController.GetWin32ServicePathName(ServiceName),
                        this.thisSvcAssemAttr.AssemblyTitle,
                        this.thisSvcAssemAttr.AssemblyCompany,
                        this.thisSvcAssemAttr.AssemblyProduct,
                        this.thisSvcAssemAttr.GetAssemblyVersion(),
                        MattimonAgentLibrary.Static.Constants.CommonAppData
                        );


                    /// Initialize the local database
                    SQLiteClientDatabase = new SQLiteClientDatabase(

                        MattimonAgentLibrary.Static.Constants.CommonAppData,

                        MattimonAgentLibrary.Tools.RegistryTools.GetPublisherByDisplayName(
                            MattimonAgentLibrary.Static.MattimonRegistrySubkeyNames.DisplayName),

                        MattimonAgentLibrary.Static.MattimonRegistrySubkeyNames.DisplayName,

                        MattimonAgentLibrary.Static.Constants.LocalDatabaseName
                        );

                    long   deviceId     = SQLiteClientDatabase.GetDeviceId();
                    long   deviceTypeId = SQLiteClientDatabase.GetDeviceTypeId();
                    long   userId       = SQLiteClientDatabase.GetUserId();
                    long   companyId    = SQLiteClientDatabase.GetCompanyId();
                    double interval     = SQLiteClientDatabase.GetReportingInterval();

                    string agentId = SQLiteClientDatabase.GetAgentId();

                    // Set global variables
                    this.fetchedDeviceId     = deviceId;
                    this.fetchedDeviceTypeId = deviceTypeId;
                    this.fetchedUserId       = userId;
                    this.fetchedCompanyId    = companyId;
                    this.fetchedInterval     = interval;

                    this.fetchedAgentId = agentId;


                    // Prepare the rest request
                    this.deviceRequests =
                        new MattimonAgentLibrary.Rest.DeviceRequests();

                    // Get the device Options
                    MattimonAgentLibrary.Models.DeviceOptions deviceOptions =
                        RequestDeviceOptions(deviceId, userId, companyId);
                    /// NOTE: each time the user changes related options, the service needs to be stopped and restarted
                    /// in order for the options to take effect.
                    /// [Void if CheckOnlineOptions is called in every timer-elapsed event!]


                    this.fetchedUseAgent = deviceOptions.UseAgent;
                    this.fetchedSqlMonit = deviceOptions.MonitorSql ? 1 : 0;


                    message += String.Format(
                        "User authentication keys:\n\n" +
                        "User ID: {0}\n" +
                        "Company ID: {1}\n" +
                        "Device ID: {2}\n\n" +

                        "Device Options:\n\n" +
                        "Reporting interval (local): every {3} minute(s)\n" +
                        "Reporting inteval (server): every {4} minute(s)\n" +
                        "(Reporting interval on local and server must be identical)\n" +
                        "Email notifications: {5}",
                        userId,
                        companyId,
                        deviceId,
                        MattimonAgentLibrary.Tools.TimeSpanUtil.ConvertMillisecondsToMinutes(interval),
                        MattimonAgentLibrary.Tools.TimeSpanUtil.ConvertMillisecondsToMinutes(deviceOptions.ReportingInterval),
                        (deviceOptions.NotificationEmails ? "Enabled" : "Disabled")
                        );

                    EventLog.WriteEntry(message, EventLogEntryType.Information, SVC_INIT_EVENT_ID);

                    /// Finally, initialize the timers
                    Timer = new System.Timers.Timer
                    {
                        Interval = interval
                    };
                    Timer.Elapsed += Timer_Elapsed;
                    Timer.Start();

                    /// And the Timer that handles the update for our updater service
                    TimerUpd = new System.Timers.Timer
                    {
                        Interval = 1000 * 60 * 1
                    };
                    TimerUpd.Elapsed += TimerUpd_Elapsed;
                    TimerUpd.Start();
                }
                catch (Exception ex)
                {
                    EventLog.WriteEntry(ex.Message + "\n\n" + ex.ToString(),
                                        EventLogEntryType.Error, SVC_INIT_EVENT_ID);
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(ex.Message + "\n\n" + ex.ToString(),
                                    EventLogEntryType.Error, SVC_INIT_EVENT_ID);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string GetAgentID()
        {
            SQLiteClientDatabase db = GetLocalDatabase();

            return(db.GetAgentId());
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private long GetCompanyID()
        {
            SQLiteClientDatabase db = GetLocalDatabase();

            return(db.GetCompanyId());
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private long GetUserID()
        {
            SQLiteClientDatabase db = GetLocalDatabase();

            return(db.GetUserId());
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="instances"></param>
        private void DeleteSqlServerInstance(ServerInstance[] instances)
        {
            string svcPath = string.Empty, svcName = string.Empty;

            FormBackgroundWorker deleteInstances = new FormBackgroundWorker(this,

                                                                            new DoWorkEventHandler((s, e) => {
                SQLServerRequests requests = new SQLServerRequests();

                DeviceServerObjects dso = new DeviceServerObjects();

                dso.DeviceID = GetDeviceID();

                dso.Instances = instances;

                try
                {
                    svcPath = Path.Combine(RegistryTools.GetInstallLocationByDisplayName(

                                               MattimonAgentLibrary.Static.MattimonRegistrySubkeyNames.DisplayName),

                                           "MattimonSQLServerService.exe");

                    if (!File.Exists(svcPath))
                    {
                        throw new IOException("Could not locate the service file: " + svcPath + ".\n" +

                                              "Re-installing the application might fix this issue.");
                    }
                }

                catch (IOException ioe) { throw ioe; }

                catch (Exception ex) { throw ex; }

                svcName = new ProjectAssemblyAtrributes(svcPath).AssemblyTitle;

                SQLiteClientDatabase db = GetLocalDatabase();

                foreach (ServerInstance si in dso.Instances)
                {
                    string insname = si.InstanceName.ToLower().Equals("mssqlserver") ? "" : si.InstanceName;

                    db.DeleteConnectionStringEntry(si.ServerName, insname);
                }



                e.Result = requests.PostDeviceServerObjects(dso, DeviceServerObjectAction.delete);
            }), "Deleting Instance(s)");

            deleteInstances.RunWorkerCompletedEventHandler = new RunWorkerCompletedEventHandler((s, e) => {
                if (e.Error != null)
                {
                    GUI.BitscoreForms.BitscoreMessageBox.Show(this, "An error occurred while attempting to delete SQL Server instances.\n\n" +
                                                              "Error details:\n" + Tools.ExceptionHelper.GetFormatedExceptionMessage(e.Error),
                                                              "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (e.Result != null && e.Result is DeviceServerObjects dso)
                {
                    if (dso.Exception != null || dso.HttpRequestException != null)
                    {
                        if (dso.Exception != null)
                        {
                            GUI.BitscoreForms.BitscoreMessageBox.Show(this, "An server-side error occurred.\n\n" +
                                                                      "Error details:\n" + Tools.ExceptionHelper.GetFormatedExceptionMessage(dso.Exception),
                                                                      "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        if (dso.HttpRequestException != null)
                        {
                            GUI.BitscoreForms.BitscoreMessageBox.Show(this, "An server-side error occurred.\n\n" +
                                                                      "Error details:\n" + Tools.ExceptionHelper.GetFormatedExceptionMessage(dso.HttpRequestException),
                                                                      "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        return;
                    }

                    BtnSqlSrv_Refresh_Click(btn_sqlsrv_refresh, EventArgs.Empty);


                    GUI.BitscoreForms.BitscoreMessageBox.Show(this, "Instance(s) have been deleted.",
                                                              Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            });
            deleteInstances.DoWork();
        }
        private void InitializeServiceComponents()
        {
            try
            {
                InitializeEventLog();
            }
            catch { }

            try
            {
                InitializePaths();



                if (!System.IO.File.Exists(this.guiExePath))
                {
                    EventLog.WriteEntry("Main application assembly file is missing.\n\n" +
                                        "Application must be properly installed in order to access required assembly information and paths.",
                                        EventLogEntryType.Error, SVC_INIT_EVENT_ID);
                    return;
                }

                if (!System.IO.File.Exists(this.thisSvcExePath))
                {
                    EventLog.WriteEntry("Service assembly file is missing.\n\n" +
                                        "Application must be properly installed in order to access required assembly information and paths.",
                                        EventLogEntryType.Error, SVC_INIT_EVENT_ID);
                    return;
                }

                MattimonAgentLibrary.Tools.ProjectAssemblyAtrributes thisSvcAssemAttr =
                    new MattimonAgentLibrary.Tools.ProjectAssemblyAtrributes(
                        this.thisSvcExePath);


                String message = "";
                message = String.Format(

                    "{0}->InitializeServiceComponents\n\n" +
                    "Application path: {1}\n" +
                    "Service path: {2}\n" +
                    "Service path (Win32_Services->PathName): {3}\n\n" +
                    "MattimonAgentApplication.exe assembly information:\n\n" +
                    "Title: {4}\n" +
                    "Company: {5}\n" +
                    "Product: {6}\n" +
                    "Version: {7}\n\n" +
                    "CommonAppData directory: {8}",

                    ServiceName,
                    this.guiExePath,
                    this.thisSvcExePath,
                    MattimonAgentLibrary.Tools.MyServiceController.GetWin32ServicePathName(ServiceName),
                    this.thisSvcAssemAttr.AssemblyTitle,
                    this.thisSvcAssemAttr.AssemblyCompany,
                    this.thisSvcAssemAttr.AssemblyProduct,
                    this.thisSvcAssemAttr.GetAssemblyVersion(),
                    MattimonAgentLibrary.Static.Constants.CommonAppData
                    );


                /// Initialize the local database
                SQLiteClientDatabase = new SQLiteClientDatabase(

                    MattimonAgentLibrary.Static.Constants.CommonAppData,

                    MattimonAgentLibrary.Tools.RegistryTools.GetPublisherByDisplayName(
                        MattimonAgentLibrary.Static.MattimonRegistrySubkeyNames.DisplayName),

                    MattimonAgentLibrary.Static.MattimonRegistrySubkeyNames.DisplayName,

                    MattimonAgentLibrary.Static.Constants.LocalDatabaseName
                    );

                long   deviceId     = SQLiteClientDatabase.GetDeviceId();
                long   deviceTypeId = SQLiteClientDatabase.GetDeviceTypeId();
                long   userId       = SQLiteClientDatabase.GetUserId();
                long   companyId    = SQLiteClientDatabase.GetCompanyId();
                double interval     = SQLiteClientDatabase.GetReportingInterval();

                string agentId = SQLiteClientDatabase.GetAgentId();

                // Set global variables
                this.fetchedDeviceId     = deviceId;
                this.fetchedDeviceTypeId = deviceTypeId;
                this.fetchedUserId       = userId;
                this.fetchedCompanyId    = companyId;
                this.fetchedInterval     = interval;

                this.fetchedAgentId = agentId;


                // Prepare the rest request
                this.deviceRequests =
                    new MattimonAgentLibrary.Rest.DeviceRequests();


                try
                {
                    // Prepare the EventLongEntryListeners
                    // WARNING: The listener posts any event log entry that occurs.
                    // Service intervals do NOT apply in this case --- just a friendly reminder.
                    EventLogEntryListener = new EventLogEntryListener(
                        EventLogEntryListener_EntryWritten,
                        "Application", "Security", "System")
                    {
                        DebugLog = EventLog
                    };

                    // EDITED: The following statement has been removed from OnStart()
                    if (this.EventLogEntryListener != null)
                    {
                        this.EventLogEntryListener.StartListening();
                    }
                    // END EDITED;
                }
                catch (Exception ex)
                {
                    message += "\nError while initializing EventLogsEntryListeners.\n\n" + ex.Message + "\n\n" + ex.ToString() + "\n";
                }

                // Get the device Options
                MattimonAgentLibrary.Models.DeviceOptions deviceOptions =
                    RequestDeviceOptions(deviceId, userId, companyId);

                this.fetchedUseAgent       = deviceOptions.UseAgent;
                this.fetchedMonitorEvtLogs = deviceOptions.MonitorEventLog;

                message += String.Format(
                    "User authentication keys:\n\n" +
                    "User ID: {0}\n" +
                    "Company ID: {1}\n" +
                    "Device ID: {2}\n\n" +

                    "Device Options:\n\n" +
                    "Reporting interval (local): every {3} minute(s)\n" +
                    "Reporting inteval (server): every {4} minute(s)\n" +
                    "(Reporting interval on local and server must be identical)\n" +
                    "Email notifications: {5}",
                    userId,
                    companyId,
                    deviceId,
                    MattimonAgentLibrary.Tools.TimeSpanUtil.ConvertMillisecondsToMinutes(interval),
                    MattimonAgentLibrary.Tools.TimeSpanUtil.ConvertMillisecondsToMinutes(deviceOptions.ReportingInterval),
                    (deviceOptions.NotificationEmails ? "Enabled" : "Disabled")
                    );

                EventLog.WriteEntry(message, EventLogEntryType.Information, SVC_INIT_EVENT_ID);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(ex.Message + "\n\n" + ex.ToString(),
                                    EventLogEntryType.Error, SVC_INIT_EVENT_ID);
            }
        }