Esempio n. 1
0
 public void CreateAsyncServer(string pipeName)
 {
     _pipeName = pipeName;
     StartSettingsApplication();
     CreateAsyncServerBase();
     NLogger.LogDebugToHdd($"Server: Async server created. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
 }
Esempio n. 2
0
        private static TryAsyncPipesAction AsyncPipesAction(CommunicationObject communicationObject)
        {
            try
            {
                switch (communicationObject.ActionType)
                {
                case CommunicationActionType.Reinitialization:
                    break;

                case CommunicationActionType.Restart:
                    break;

                case CommunicationActionType.ShowConfirmationMessage:
                    break;

                case CommunicationActionType.ShowMessage:
                    NLogger.LogDebugToHdd(communicationObject.Data.ToString());
                    break;

                case CommunicationActionType.ShowProgressForm:
                    break;
                }
                return(new TryAsyncPipesAction());
            }
            catch (Exception ex)
            {
                return(new TryAsyncPipesAction(false, ex.Message.ToString()));
            }
        }
Esempio n. 3
0
        private void _asyncClient_MessageRecieved(object sender, CommunicationObject communicationObject = null)
        {
            if (communicationObject.ActionType == CommunicationActionType.MessageRecieved)
            {
                NLogger.LogDebugToHdd($"Client: Answer received. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
                _isMessageRecieved = true;
            }
            else
            {
                if (communicationObject.Tag != null && (bool)(communicationObject.Tag))
                {
                    NLogger.LogDebugToHdd($"Client: Message recieved with sending answer: \"{communicationObject.ActionType.ToString()}\". Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
                    SendAsyncMessage(new CommunicationObject
                    {
                        ActionType = CommunicationActionType.MessageRecieved
                    });
                    NLogger.LogDebugToHdd($"Client: Answer sended. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
                }
                else
                {
                    NLogger.LogDebugToHdd($"Client: Message recieved: \"{communicationObject.ActionType.ToString()}\". Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
                }

                var res = AsyncPipesAction(communicationObject);
                if (!res.IsComplete)
                {
                    NLogger.LogErrorToBaseAndHdd(MainSettings.MainSqlSettings.ComputerId, res.Message);
                }
            }
        }
Esempio n. 4
0
        private void SettingsForm_Load(object sender, EventArgs e)
        {
            try
            {
                txtServerTask.Text           = _serverTaskDefault;
                txtBaseTask.Text             = _baseTaskDefault;
                txtUserTask.Text             = _userTaskDefault;
                txtPasswordTask.Text         = _passwordTaskDefault;
                txtUser1C.Text               = _user1CDefault;
                txtPass1C.Text               = _pass1CDefault;
                tbSelfUpdateFtpServer.Text   = _selfUpdateFtpServerDefault;
                tbSelfUpdateFtpUser.Text     = _selfUpdateFtpUserDefault;
                tbSelfUpdateFtpPassword.Text = _selfUpdateFtpPasswordDefault;

                var loadFromJsonResult = MainSettings.LoadFromJson();

                if (!loadFromJsonResult.IsComplete)
                {
                    return;
                }

                txtServerTask.Text   = MainSettings.JsonSettings.ServerTask;
                txtBaseTask.Text     = MainSettings.JsonSettings.BaseTask;
                txtUserTask.Text     = MainSettings.JsonSettings.UserTask;
                txtPasswordTask.Text = MainSettings.JsonSettings.PasswordTask;
            }
            catch (Exception ex)
            {
                ConnectionToService?.DisposeAsyncClient();
                MessageBox.Show(ex.Message.ToString(), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                NLogger.LogDebugToHdd(ex.Message.ToString());
                Application.Exit();
            }
        }
Esempio n. 5
0
 private static void RestoreCurrentVersionFromBackup()
 {
     try
     {
         if (Directory.Exists(_currentVersionBackupPath))
         {
             foreach (var file in FilesWorks.GetFiles(_currentVersionBackupPath, _searchPatterns, SearchOption.TopDirectoryOnly))
             {
                 try
                 {
                     file.CopyTo(Path.Combine(_currentVersionPath, file.Name));
                 }
                 catch (Exception ex)
                 {
                     NLogger.LogErrorToHdd($"Не критическая ошибка копирования файла из бекапа. Original: {ex.Message}", MainSettings.Constants.MAGIC_UPDATER_RESTART);
                 }
             }
         }
         else
         {
             NLogger.LogErrorToHdd($"Ошибка восстановления текущей версии из бекапа. Бекапа не существует.", MainSettings.Constants.MAGIC_UPDATER_RESTART);
         }
         NLogger.LogDebugToHdd($"Восстановление ткущей версии из бекапа выполнено.", MainSettings.Constants.MAGIC_UPDATER_RESTART);
     }
     catch (Exception ex)
     {
         NLogger.LogErrorToHdd($"Ошибка восстановления текущей версии из бекапа. Original: {ex.Message}", MainSettings.Constants.MAGIC_UPDATER_RESTART);
     }
 }
Esempio n. 6
0
        protected override void OnStop()
        {
#if DEBUG
            workerThread.Abort();
#endif
            StopEntryPoint();

            NLogger.LogDebugToHdd("Служба остановлена", MainSettings.Constants.MAGIC_UPDATER);
        }
Esempio n. 7
0
        protected override void OnStart(string[] args)
        {
#if !DEBUG
            //Точка входа для режима Release
            StartEntryPoint();
#else
            workerThread.Start();
#endif
            NLogger.LogDebugToHdd("Служба запущена", MainSettings.Constants.MAGIC_UPDATER);
        }
Esempio n. 8
0
 private void StopEntryPoint()
 {
     try
     {
         //_muCore?.Dispose();
     }
     catch (Exception ex)
     {
         NLogger.LogDebugToHdd(ex.ToString(), MainSettings.Constants.MAGIC_UPDATER);
     }
 }
Esempio n. 9
0
 private void StartEntryPoint()
 {
     try
     {
         _muCore = new MuCore();
     }
     catch (Exception ex)
     {
         NLogger.LogDebugToHdd(ex.ToString(), MainSettings.Constants.MAGIC_UPDATER);
     }
 }
Esempio n. 10
0
 private void _asyncClient_Disposed(object sender, CommunicationObject communicationObject = null)
 {
     if (!_isManualDispose)
     {
         NLogger.LogDebugToHdd($"Client: Disposed. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
         AsyncConnectBase();
     }
     else
     {
         NLogger.LogDebugToHdd($"Client: Manual dispose. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
     }
 }
Esempio n. 11
0
 private void _pipesAsyncServer_Disposed(object sender, Communications.Common.CommunicationObject communicationObject = null)
 {
     if (!_isManualDispose)
     {
         NLogger.LogDebugToHdd($"Server: Disposed. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
         CreateAsyncServerBase();
     }
     else
     {
         NLogger.LogDebugToHdd($"Server: Manual dispose. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
     }
 }
Esempio n. 12
0
 private TryAsyncPipesAction AsyncPipesAction(CommunicationObject communicationObject)
 {
     try
     {
         NLogger.LogDebugToHdd($"Client: Start action excecute...:\"{communicationObject.ActionType.ToString()}\". Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
         ClientAsyncPipesActionExecute(communicationObject);
         NLogger.LogDebugToHdd($"Client: End action execute: \"{communicationObject.ActionType.ToString()}\". Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
         return(new TryAsyncPipesAction());
     }
     catch (Exception ex)
     {
         return(new TryAsyncPipesAction(false, ex.Message.ToString()));
     }
 }
Esempio n. 13
0
        public void Restart()
        {
            try
            {
                NLogger.LogDebugToHdd($"Установка новой службы {SERVICE_NAME}");
                InstallService(_servicePath, SERVICE_NAME, SERVICE_DISPLAY_NAME);
                NLogger.LogDebugToHdd($"Новая служба {SERVICE_NAME} - установлена и запущена");
                AddMessage($"Новая служба {SERVICE_NAME} - установлена и запущена");

                Thread.Sleep(3000);
                //Меняем режим запуска на отложенный
                Process.Start("sc.exe", $"config {SERVICE_NAME} start= delayed-auto");

                //sc.exe config MagicUpdater start= delayed-auto
            }
            catch (Exception ex)
            {
                NLogger.LogDebugToHdd(ex.ToString());
            }
        }
Esempio n. 14
0
        protected override void ServerAsyncPipesActionExecute(CommunicationObject communicationObject)
        {
            switch (communicationObject.ActionType)
            {
            case CommunicationActionType.Reinitialization:
                break;

            case CommunicationActionType.Restart:
                break;

            case CommunicationActionType.ShowConfirmationMessage:
                break;

            case CommunicationActionType.ShowMessage:
                NLogger.LogDebugToHdd(communicationObject.Data.ToString());
                break;

            case CommunicationActionType.ShowProgressForm:
                break;
            }
        }
Esempio n. 15
0
        private void btnRestartService_Click(object sender, EventArgs e)
        {
            const int RESTART_TIMEOUT = 60000;
            Button    button          = sender as Button;

            button.Enabled = false;
            string buttonText = button.Text;

            button.Text = ".......";

            try
            {
                ServiceController service = new ServiceController(MainSettings.Constants.SERVICE_NAME);
                TimeSpan          timeout = TimeSpan.FromMilliseconds(RESTART_TIMEOUT);
                if (service.Status == ServiceControllerStatus.Running)
                {
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                }

                if (service.Status == ServiceControllerStatus.Stopped)
                {
                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                }
            }
            catch (Exception ex)
            {
                NLogger.LogDebugToHdd(ex.Message.ToString());
                MessageBox.Show(ex.Message.ToString(), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                button.Text    = buttonText;
                button.Enabled = true;
            }
        }
Esempio n. 16
0
 public void LogInstallServiceString(string logStr)
 {
     NLogger.LogDebugToHdd(logStr);
     if (this.InvokeRequired)
     {
         this.Invoke(new MethodInvoker(() =>
         {
             _rtbInstallServiceLog.AppendText($"{logStr}{Environment.NewLine}");
             if (_progressBar1.Value < _progressBar1.Maximum)
             {
                 _progressBar1.Value++;
             }
         }));
     }
     else
     {
         _rtbInstallServiceLog.AppendText($"{logStr}{Environment.NewLine}");
         if (_progressBar1.Value < _progressBar1.Maximum)
         {
             _progressBar1.Value++;
         }
     }
 }
Esempio n. 17
0
 public void LogInstallServiceString(Exception ex)
 {
     NLogger.LogDebugToHdd(ex.ToString());
     if (this.InvokeRequired)
     {
         this.Invoke(new MethodInvoker(() =>
         {
             _rtbInstallServiceLog.AppendText($"{ex.Message}{Environment.NewLine}");
             if (_progressBar1.Value < _progressBar1.Maximum)
             {
                 _progressBar1.Value++;
             }
         }));
     }
     else
     {
         _rtbInstallServiceLog.AppendText($"{ex.Message}{Environment.NewLine}");
         if (_progressBar1.Value < _progressBar1.Maximum)
         {
             _progressBar1.Value++;
         }
     }
 }
Esempio n. 18
0
        private void UninstallerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                if (_IsServiceUninstalling)
                {
                    MessageBox.Show("Выход из мастера установки в процессе удаления службы запрещен.", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    e.Cancel = true;
                    return;
                }

                if (!_isServiceUninstallComplete && MessageBox.Show($"Удаление не завершено!{Environment.NewLine}Вы уверены, что хотите выйти?"
                                                                    , "Подтверждение"
                                                                    , MessageBoxButtons.YesNo
                                                                    , MessageBoxIcon.Question) == DialogResult.No)
                {
                    e.Cancel = true;
                }
                else
                {
                    NLogger.LogDebugToHdd($"Удаление не завершено!{Environment.NewLine}Удаление прервано пользователем.");
                }
            }
        }
Esempio n. 19
0
        private void SettingsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                if (_isServiceInstalling)
                {
                    MessageBox.Show("Выход из мастера установки в процессе установки службы запрещен.", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    e.Cancel = true;
                    return;
                }

                if (MessageBox.Show($"Установка не завершена!{Environment.NewLine}Вы уверены, что хотите прервать установку?"
                                    , "Подтверждение"
                                    , MessageBoxButtons.YesNo
                                    , MessageBoxIcon.Question) == DialogResult.No)
                {
                    e.Cancel = true;
                }
                else
                {
                    NLogger.LogDebugToHdd($"Установка не завершена!{Environment.NewLine}Установка прервана пользователем.");
                }
            }
        }
Esempio n. 20
0
 public void LogString(Exception ex)
 {
     NLogger.LogDebugToHdd(ex.ToString());
     rtbLog.AppendText($"{ex.Message}{Environment.NewLine}");
 }
Esempio n. 21
0
 protected virtual void _asyncClient_Connected(object sender, Communications.Common.CommunicationObject communicationObject = null)
 {
     NLogger.LogDebugToHdd($"Client: Async client connected. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
 }
Esempio n. 22
0
 private static void _pipesAsyncServer_Connected(object sender, Communications.Common.CommunicationObject communicationObject = null)
 {
     NLogger.LogDebugToHdd("client connected");
 }
Esempio n. 23
0
 private void _asyncClient_MessagSended(object sender, CommunicationObject communicationObject = null)
 {
     NLogger.LogDebugToHdd($"Client: Message sended: \"{communicationObject.ActionType.ToString()}\". Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
 }
Esempio n. 24
0
 public void AsyncConnect(string pipeName)
 {
     _pipeName = pipeName;
     AsyncConnectBase();
     NLogger.LogDebugToHdd($"Client: Async client created. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
 }
Esempio n. 25
0
        static void Main(string[] args)
        {
            if (args != null && args.Length > 0)
            {
                try
                {
                    _operationId = Convert.ToInt32(args[0]);
                }
                catch
                {
                    _operationId = 0;
                }

                if (args.Length == 2)
                {
                    try
                    {
                        _action = Convert.ToString(args[1]);
                    }
                    catch
                    {
                        _action = "";
                    }
                }
            }



            // TODO: Add code to start application here
            // Testing --------------
            //string svcPath;
            //string svcName;
            //string svcDispName;
            //path to the service that you want to install
            //const string SERVICE_PATH = @"D:\GitProjects\MagicUpdater\MagicUpdater\bin\Release\MagicUpdater.exe";
            const string SERVICE_PATH               = @"C:\SystemUtils\MagicUpdater\MagicUpdater.exe";
            const string SERVICE_DISPLAY_NAME       = "MagicUpdater";
            const string SERVICE_NAME               = "MagicUpdater";
            const string MAGIC_UPDATER_PATH         = @"C:\SystemUtils\MagicUpdater";
            const string MAGIC_UPDATER_NEW_VER_PATH = @"C:\SystemUtils\MagicUpdaterNewVer";
            const string SETTINGS_FILE_NAME         = "settings.json";

            ServiceInstaller  serviceInstaller = new ServiceInstaller();
            ServiceController service          = new ServiceController(SERVICE_NAME);

            try
            {
                if (string.IsNullOrEmpty(_action))
                {
                    TimeSpan timeout = TimeSpan.FromMilliseconds(30000);

                    Console.WriteLine("Тормозим старую службу...");
                    //Тормозим старую службу
                    try
                    {
                        service.Stop();
                        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                        AddMessage($"Старая служба {SERVICE_NAME} - остановлена");
                        NLogger.LogDebugToHdd($"Старая служба {SERVICE_NAME} - остановлена");
                        Console.WriteLine("Старая служба остановлена");
                    }
                    catch (Exception ex)
                    {
                        AddMessage(ex.Message);
                        NLogger.LogDebugToHdd(ex.Message);
                        Console.WriteLine(ex.Message);
                    }

                    Console.WriteLine("Удаляем старую службу...");
                    //Удаляем старую службу
                    try
                    {
                        serviceInstaller.UnInstallService(SERVICE_NAME);
                        Thread.Sleep(3000);
                        NLogger.LogDebugToHdd($"Старая служба {SERVICE_NAME} - удалена");
                        AddMessage($"Старая служба {SERVICE_NAME} - удалена");

                        Console.WriteLine($"Старая служба {SERVICE_NAME} - удалена");
                    }
                    catch (Exception ex)
                    {
                        AddMessage(ex.Message);
                        NLogger.LogDebugToHdd(ex.Message);
                        Console.WriteLine(ex.Message);
                    }

                    Console.WriteLine("Убиваем все процессы MagicUpdater...");
                    //Убиваем все процессы MagicUpdater
                    Process[] procs = Process.GetProcessesByName(SERVICE_NAME);
                    foreach (var proc in procs)
                    {
                        proc.Kill();
                    }
                    Thread.Sleep(3000);
                    NLogger.LogDebugToHdd($"Все процессы {SERVICE_NAME} - убиты");
                    AddMessage($"Все процессы {SERVICE_NAME} - убиты");
                    Console.WriteLine("Все процессы MagicUpdater завершены");

                    Console.WriteLine("Чистим реестр (автозагрузка MU как приложения в корне run)...");
                    //Чистим реестр (автозагрузка MU как приложения в корне run)
                    #region Чистим реестр
                    string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";
                    using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
                    {
                        if (key == null)
                        {
                            Console.WriteLine($"CurrentUser: Отсутствует путь в реестре {keyName}");
                            NLogger.LogErrorToHdd($"CurrentUser: Отсутствует путь в реестре {keyName}");
                            AddMessage($"CurrentUser: Отсутствует путь в реестре {keyName}");
                        }
                        else
                        {
                            try
                            {
                                key.DeleteValue(SERVICE_NAME);
                                Console.WriteLine($"CurrentUser: Значение реестра - {SERVICE_NAME} удалено");
                                NLogger.LogDebugToHdd($"CurrentUser: Значение реестра - {SERVICE_NAME} удалено");
                                AddMessage($"CurrentUser: Значение реестра - {SERVICE_NAME} удалено");
                            }
                            catch (Exception ex)
                            {
                                NLogger.LogDebugToHdd($"CurrentUser: {ex.Message}");
                                Console.WriteLine($"CurrentUser: {ex.Message}");
                                AddMessage($"CurrentUser: {ex.Message}");
                            }
                        }
                    }

                    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName, true))
                    {
                        if (key == null)
                        {
                            NLogger.LogErrorToHdd($"LocalMachine: Отсутствует путь в реестре {keyName}");
                            AddMessage($"LocalMachine: Отсутствует путь в реестре {keyName}");
                        }
                        else
                        {
                            try
                            {
                                key.DeleteValue(SERVICE_NAME);
                                Console.WriteLine($"LocalMachine: Значение реестра - {SERVICE_NAME} удалено");
                                NLogger.LogDebugToHdd($"LocalMachine: Значение реестра - {SERVICE_NAME} удалено");
                                AddMessage($"LocalMachine: Значение реестра - {SERVICE_NAME} удалено");
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"LocalMachine: {ex.Message}");
                                NLogger.LogDebugToHdd($"LocalMachine: {ex.Message}");
                                AddMessage($"LocalMachine: {ex.Message}");
                            }
                        }
                    }
                    #endregion Чистим реестр

                    Console.WriteLine("Удаляем все из папок MagicUpdater и MagicUpdaterNewVer...");
                    //Удаляем все из папок MagicUpdater и MagicUpdaterNewVer
                    #region Удаляем все из папок MagicUpdater и MagicUpdaterNewVer
                    try
                    {
                        DirectoryInfo di = new DirectoryInfo(MAGIC_UPDATER_PATH);

                        foreach (FileInfo file in di.GetFiles())
                        {
                            if (file.Name.ToUpper() != SETTINGS_FILE_NAME.ToUpper())
                            {
                                file.Delete();
                            }
                        }
                        foreach (DirectoryInfo dir in di.GetDirectories())
                        {
                            dir.Delete(true);
                        }
                        Console.WriteLine($"Путь {MAGIC_UPDATER_PATH} - очищен");
                        NLogger.LogDebugToHdd($"Путь {MAGIC_UPDATER_PATH} - очищен");
                        AddMessage($"Путь {MAGIC_UPDATER_PATH} - очищен");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        NLogger.LogErrorToHdd(ex.ToString());
                        AddMessage(ex.Message);
                    }

                    try
                    {
                        DirectoryInfo di = new DirectoryInfo(MAGIC_UPDATER_NEW_VER_PATH);

                        foreach (FileInfo file in di.GetFiles())
                        {
                            file.Delete();
                        }
                        foreach (DirectoryInfo dir in di.GetDirectories())
                        {
                            dir.Delete(true);
                        }
                        Console.WriteLine($"Путь {MAGIC_UPDATER_NEW_VER_PATH} - очищен");
                        NLogger.LogDebugToHdd($"Путь {MAGIC_UPDATER_NEW_VER_PATH} - очищен");
                        AddMessage($"Путь {MAGIC_UPDATER_NEW_VER_PATH} - очищен");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        NLogger.LogErrorToHdd(ex.ToString());
                        AddMessage(ex.Message);
                    }
                    #endregion Удаляем все из папок MagicUpdater и MagicUpdaterNewVer

                    Thread.Sleep(1000);

                    Console.WriteLine("Скачиваем новую версию...");
                    //Копируем новый MagicUpdater целиком!
                    #region Копируем новый MagicUpdater целиком!
                    using (Ftp ftp = new Ftp())
                    {
                        ftp.Connect("mskftp.sela.ru");                          // or ConnectSSL for SSL
                        ftp.Login("cis_obmen", "cisobmen836");
                        try
                        {
                            Directory.CreateDirectory(MAGIC_UPDATER_PATH);
                            ftp.DownloadFiles("MagicUpdaterTest", MAGIC_UPDATER_PATH, new RemoteSearchOptions("*", true));
                        }
                        finally
                        {
                            if (ftp.Connected)
                            {
                                ftp.Close();
                            }
                        }
                    }
                    Console.WriteLine($"Закачка нового {SERVICE_NAME} - завешена");
                    NLogger.LogDebugToHdd($"Закачка нового {SERVICE_NAME} - завешена");
                    AddMessage($"Закачка нового {SERVICE_NAME} - завешена");
                    #endregion Копируем новый MagicUpdater целиком!

                    //Устанавливаем службу с режимом автозапуска
                    //Запускаем службу
                    Thread.Sleep(3000);

                    Console.WriteLine("Создаем задачу MuInstallService в планировщике для установки службы...");
                    NLogger.LogDebugToHdd("Создаем задачу MuInstallService в планировщике для установки службы...");
                    try
                    {
                        CreateMuInstallServiceSchedule("MuInstallService");
                        Console.WriteLine("Задача MuInstallService создана");
                        NLogger.LogDebugToHdd("Задача MuInstallService создана");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Задача MuInstallService: {ex.Message}");
                        NLogger.LogErrorToHdd($"Задача MuInstallService: {ex.ToString()}");
                    }

                    //string path = System.Reflection.Assembly.GetEntryAssembly().Location;
                    //Process.Start(path, $"{_operationId.ToString()} restart");
                }
                else if (_action == "restart")
                {
                    serviceInstaller.InstallService(SERVICE_PATH, SERVICE_NAME, SERVICE_DISPLAY_NAME);
                    Console.WriteLine($"Новая служба {SERVICE_NAME} - установлена и запущена");
                    NLogger.LogDebugToHdd($"Новая служба {SERVICE_NAME} - установлена и запущена");
                    AddMessage($"Новая служба {SERVICE_NAME} - установлена и запущена");

                    //serviceInstaller.UnInstallService(SERVICE_NAME);

                    SendMessagesToOperation(true);
                    DeleteSchedule("MuInstallService");
                }
                else if (_action == "schedule")
                {
                    CreateMuInstallServiceSchedule("MuInstallService");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                NLogger.LogErrorToHdd(ex.ToString());
                AddMessage(ex.Message);
                SendMessagesToOperation(false);
            }

            //Console.Read();
        }
Esempio n. 26
0
 private static void _asyncClient_Connected(object sender, Communications.Common.CommunicationObject communicationObject = null)
 {
     NLogger.LogDebugToHdd("server connected");
 }
Esempio n. 27
0
        private void UninstallBase()
        {
            TimeSpan timeout = TimeSpan.FromMilliseconds(30000);

            Program.MainForm?.LogInstallServiceString("Тормозим старую службу...");
            //Тормозим старую службу
            try
            {
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                AddMessage($"Старая служба {SERVICE_NAME} - остановлена");
                Program.MainForm?.LogInstallServiceString($"Старая служба {SERVICE_NAME} - остановлена");
                Program.MainForm?.LogInstallServiceString("Старая служба остановлена");
            }
            catch (Exception ex)
            {
                AddMessage(ex.Message);
                Program.MainForm?.LogInstallServiceString(ex);
            }

            Console.WriteLine("Удаляем старую службу...");
            //Удаляем старую службу
            try
            {
                using (ServiceInstaller ServiceInstallerObj = new ServiceInstaller())
                {
                    InstallContext Context = new InstallContext(null, null);
                    ServiceInstallerObj.Context     = Context;
                    ServiceInstallerObj.ServiceName = SERVICE_NAME;
                    ServiceInstallerObj.Uninstall(null);
                }

                Thread.Sleep(3000);

                AddMessage($"Старая служба {SERVICE_NAME} - удалена");
                Program.MainForm?.LogInstallServiceString($"Старая служба {SERVICE_NAME} - удалена");
            }
            catch (Exception ex)
            {
                AddMessage(ex.Message);
                Program.MainForm?.LogInstallServiceString(ex);
            }

            Program.MainForm?.LogInstallServiceString("Убиваем все процессы MagicUpdater...");
            //Убиваем все процессы MagicUpdater
            Process[] procs = Process.GetProcessesByName(SERVICE_NAME);
            foreach (var proc in procs)
            {
                proc.Kill();
            }
            Thread.Sleep(3000);
            AddMessage($"Все процессы {SERVICE_NAME} - убиты");
            Program.MainForm?.LogInstallServiceString("Все процессы MagicUpdater завершены");

            Program.MainForm?.LogInstallServiceString("Чистим реестр (автозагрузка MU как приложения в корне run)...");
            //Чистим реестр (автозагрузка MU как приложения в корне run)
            #region Чистим реестр
            string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
            {
                if (key == null)
                {
                    Program.MainForm?.LogInstallServiceString($"CurrentUser: Отсутствует путь в реестре {keyName}");
                    AddMessage($"CurrentUser: Отсутствует путь в реестре {keyName}");
                }
                else
                {
                    try
                    {
                        key.DeleteValue(SERVICE_NAME);
                        Program.MainForm?.LogInstallServiceString($"CurrentUser: Значение реестра - {SERVICE_NAME} удалено");
                        AddMessage($"CurrentUser: Значение реестра - {SERVICE_NAME} удалено");
                    }
                    catch (Exception ex)
                    {
                        NLogger.LogDebugToHdd($"CurrentUser: {ex.Message}");
                        AddMessage($"CurrentUser: {ex.Message}");
                    }
                }
            }

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName, true))
            {
                if (key == null)
                {
                    NLogger.LogErrorToHdd($"LocalMachine: Отсутствует путь в реестре {keyName}");
                    AddMessage($"LocalMachine: Отсутствует путь в реестре {keyName}");
                }
                else
                {
                    try
                    {
                        key.DeleteValue(SERVICE_NAME);
                        Program.MainForm?.LogInstallServiceString($"LocalMachine: Значение реестра - {SERVICE_NAME} удалено");
                        AddMessage($"LocalMachine: Значение реестра - {SERVICE_NAME} удалено");
                    }
                    catch (Exception ex)
                    {
                        Program.MainForm?.LogInstallServiceString($"LocalMachine: {ex.Message}");
                        AddMessage($"LocalMachine: {ex.Message}");
                    }
                }
            }
            #endregion Чистим реестр

            Program.MainForm?.LogInstallServiceString("Удаляем все из папок MagicUpdater и MagicUpdaterNewVer...");
            //Удаляем все из папок MagicUpdater и MagicUpdaterNewVer
            #region Удаляем все из папок MagicUpdater и MagicUpdaterNewVer
            try
            {
                DirectoryInfo di = new DirectoryInfo(_magicUpdaterPath);

                foreach (FileInfo file in di.GetFiles())
                {
                    if (file.Name.ToUpper() != MainSettings.Constants.SETTINGS_JSON_FILE_NAME.ToUpper())
                    {
                        file.Delete();
                    }
                }
                foreach (DirectoryInfo dir in di.GetDirectories())
                {
                    dir.Delete(true);
                }
                Program.MainForm?.LogInstallServiceString($"Путь {_magicUpdaterPath} - очищен");
                AddMessage($"Путь {_magicUpdaterPath} - очищен");
            }
            catch (Exception ex)
            {
                Program.MainForm?.LogInstallServiceString(ex.Message);
                AddMessage(ex.Message);
            }

            try
            {
                DirectoryInfo di = new DirectoryInfo(MAGIC_UPDATER_NEW_VER_PATH);

                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }
                foreach (DirectoryInfo dir in di.GetDirectories())
                {
                    dir.Delete(true);
                }
                Program.MainForm?.LogInstallServiceString($"Путь {MAGIC_UPDATER_NEW_VER_PATH} - очищен");
                AddMessage($"Путь {MAGIC_UPDATER_NEW_VER_PATH} - очищен");
            }
            catch (Exception ex)
            {
                Program.MainForm?.LogInstallServiceString(ex.Message);
                AddMessage(ex.Message);
            }
            #endregion Удаляем все из папок MagicUpdater и MagicUpdaterNewVer
        }
Esempio n. 28
0
 public void LogString(string logStr)
 {
     NLogger.LogDebugToHdd(logStr);
     rtbLog.AppendText($"{logStr}{Environment.NewLine}");
 }
Esempio n. 29
0
 protected override void Execution(object sender = null, DoWorkEventArgs e = null)
 {
     NLogger.LogDebugToHdd("TestPluginOperation1");
 }
Esempio n. 30
0
 private void _pipesAsyncServer_Connected(object sender, Communications.Common.CommunicationObject communicationObject = null)
 {
     NLogger.LogDebugToHdd($"Server: Client connected. Pipe name: \"{_pipeName}\"", MainSettings.Constants.PIPES_LOGGER_NAME);
 }