protected override void ActExecution()
        {
            const string EXTENSION_1C_PROCESSING = ".epf";

            //Чтобы можно было вводить имена файлов с расширением и без
            _name = $"{_name.Replace(EXTENSION_1C_PROCESSING, "")}{EXTENSION_1C_PROCESSING}";

            var res = FtpWorks.DownloadFileFromFtp(MainSettings.Constants.PluginOperationDllDirectoryPath, MainSettings.GlobalSettings.TempFilesFtpPath, _name);

            if (!res.IsComplete)
            {
                throw new Exception(res.Message);
            }

            string fileFullPath = Path.Combine(MainSettings.Constants.PluginOperationDllDirectoryPath, _name);

            if (!File.Exists(fileFullPath))
            {
                throw new Exception($"Файл не существует:{Environment.NewLine}{fileFullPath}");
            }

            var act = new StartWithParameter1C(operationId, Parameters1C.CmdParams1C.ExecProcessing(fileFullPath));

            act.ActRun();

            if (!act.NewProc.HasExited)
            {
                act.NewProc.WaitForExit(60000 * _timeoutMin);
            }

            if (!act.NewProc.HasExited)
            {
                act.NewProc.Kill();
            }
        }
Exemplo n.º 2
0
        protected override void Execution(object sender = null, DoWorkEventArgs e = null)
        {
            #region Качаем wget
            if (File.Exists(_localWgetPath))
            {
                File.Delete(_localWgetPath);
            }

            FtpWorks.DownloadFileFromFtp(Path.GetDirectoryName(_localWgetPath)
                                         , MainSettings.LocalSqlSettings.SelfUpdateFtpServer
                                         , MainSettings.LocalSqlSettings.SelfUpdateFtpUser
                                         , MainSettings.LocalSqlSettings.SelfUpdateFtpPassword
                                         , _ftpHelpFilesPath
                                         , WGET_EXE);

            if (!File.Exists(_localWgetPath))
            {
                AddErrorMessage($"Не найден файл {_localWgetPath}");
                return;
            }
            #endregion

            if (Attributes.IsForceCreatePath)
            {
                if (!Directory.Exists(Attributes.LocalPath))
                {
                    Directory.CreateDirectory(Attributes.LocalPath);
                }
            }

            if (Attributes.IsOverwrite)
            {
                if (File.Exists(Path.Combine(Attributes.LocalPath, Attributes.FileName)))
                {
                    File.Delete(Path.Combine(Attributes.LocalPath, Attributes.FileName));
                }
            }

            Process process = Process.Start($"{_localWgetPath}", $" -c -nc ftp://{Attributes.FtpLogin}:{Attributes.FtpPassword}@{Attributes.FtpServer}/{Attributes.FtpPath}/{Attributes.FileName} -P \"{Attributes.LocalPath}\"");

            if (Attributes.IsWaitForDownload)
            {
                process.WaitForExit();

                if (File.Exists(Path.Combine(Attributes.LocalPath, Attributes.FileName)))
                {
                    AddCompleteMessage($"Файл {Path.Combine(Attributes.LocalPath, Attributes.FileName)} скачан успешно");
                }
                else
                {
                    AddErrorMessage($"Ошибка закачки файла. Файл на клиенте не обнаружен {Path.Combine(Attributes.LocalPath, Attributes.FileName)}");
                    return;
                }

                if (Attributes.IsExecuteAfterDownload)
                {
                    AddCompleteMessage($"Запуск файла {Path.Combine(Attributes.LocalPath, Attributes.FileName)}");

                    try
                    {
                        ExecuteApplication(Path.Combine(Attributes.LocalPath, Attributes.FileName)
                                           , Attributes.StartupParameters
                                           , Attributes.IsWaitForFileFinishExcecute);

                        if (!Attributes.IsWaitForFileFinishExcecute)
                        {
                            AddCompleteMessage($"Файл {Path.Combine(Attributes.LocalPath, Attributes.FileName)} - запущен успешно");
                        }
                        else
                        {
                            AddCompleteMessage($"Файл {Path.Combine(Attributes.LocalPath, Attributes.FileName)} - запущен успешно и его выполнение завершено");
                        }
                    }
                    catch (Exception ex)
                    {
                        AddErrorMessage($"Ошибка выполнения файла {Path.Combine(Attributes.LocalPath, Attributes.FileName)}. Original: {ex.ToString()}");
                    }
                }
            }
            else
            {
                AddCompleteMessage($"Закачка файла {Path.Combine(Attributes.LocalPath, Attributes.FileName)} начата.");
            }
        }
        protected override void ActExecution()
        {
            this._logText = new StringBuilder();
            const string SETUP_FILE_NAME       = @"apache-couchdb-2.0.0.1.msi";
            const string DEFAULT_INI_FILE_NAME = "default.ini";
            const string INI_DESTINATION_PATH_WITHOUT_DRIVE = @"CouchDB\etc";
            const string DIRECTORY_NAME = "CouchDB";
            const string FTP_HOST       = @"mskftp.sela.ru";
            const string LOGIN          = "******";
            const string PASSWORD       = "******";
            const int    SERVICE_RESTART_TIMEOUT_MILLISECONDS = 10000;
            const string COUCH_DB_SERVICE_NAME = "Apache CouchDB";

            const string ADMIN_LOGIN    = "******";
            const string ADMIN_PASSWORD = "******";
            const string MARK_FILENAME  = @"C:\SystemUtils\CouchDB_Marker";

            if (File.Exists(MARK_FILENAME))
            {
                Log($"Marker file was: {MARK_FILENAME} was found.");
                SendReportToDB($"{this._logText.ToString()}{Environment.NewLine}CouchDB was already installed on this computer.", true);
                return;
            }

            Log($"Download from FTP {SETUP_FILE_NAME}");

            var setupFileFullPath  = Path.Combine(Path.GetTempPath(), SETUP_FILE_NAME); //Очистить
            var defaultIniFullPath = Path.Combine(Path.GetTempPath(), DEFAULT_INI_FILE_NAME);

            try
            {
                FtpWorks.DownloadFileFromFtp(Path.GetTempPath(), FTP_HOST, LOGIN, PASSWORD, "Couch", SETUP_FILE_NAME);
                FtpWorks.DownloadFileFromFtp(Path.GetTempPath(), FTP_HOST, LOGIN, PASSWORD, "Couch", DEFAULT_INI_FILE_NAME);
                //using (Ftp client = new Ftp())
                //            {
                //                client.Connect(FTP_HOST);
                //                client.Login(LOGIN, PASSWORD);
                //                client.Download(Path.Combine("Couch", SETUP_FILE_NAME), setupFileFullPath);
                //                client.Download(Path.Combine("Couch", DEFAULT_INI_FILE_NAME), defaultIniFullPath);
                //                client.Close();
                //            }
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка загрузки файлов по FTP:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}");
                return;
            }

            Log($"Download complete");

            Log($"Lauching {SETUP_FILE_NAME}...");
            try
            {
                var setupResult = ExecuteApplication(setupFileFullPath, " /passive"); // (/quiet) /passive - для автоматической установки с показом полосы прогресса
                Log($"Setup was completed with code {setupResult}");
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка инсталлятора:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}");
                return;
            }

            Log("Check drive letter...");
            var    allDrives     = DriveInfo.GetDrives();
            string currentLetter = "";

            foreach (var drive in allDrives)
            {
                Log(drive.Name);
                if (Directory.Exists(Path.Combine(drive.Name, DIRECTORY_NAME)))
                {
                    Log($"{drive.Name} - current drive");
                    currentLetter = drive.Name;
                    break;
                }
            }
            var iniDestinationFullPath = Path.Combine(currentLetter, INI_DESTINATION_PATH_WITHOUT_DRIVE);

            if (!Directory.Exists(iniDestinationFullPath))
            {
                Log($"Path {iniDestinationFullPath} wasn't found.");
                SendReportToDB($"{"Лог: "}{this._logText.ToString()}");
                return;
            }

            try
            {
                Log("Backup current ini-file...");
                var iniFileFullName = Path.Combine(iniDestinationFullPath, DEFAULT_INI_FILE_NAME);
                var iniFileBackUp   = $"{iniFileFullName}_backup";
                if (File.Exists(iniFileBackUp))
                {
                    System.IO.File.Delete(iniFileBackUp);
                }
                File.Move(iniFileFullName, iniFileBackUp);

                Log("Copy ini-file...");

                File.Copy(defaultIniFullPath, iniFileFullName, true);
                if (!File.Exists(iniFileFullName))
                {
                    Log($"Error! {iniFileFullName} nor found.");
                    SendReportToDB($"{"Лог: "}{this._logText.ToString()}");
                    return;
                }
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка при замене ini-файла:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}");
                return;
            }

            var request = new Requests();

            try
            {
                Log("Add new bases");

                request.SendPut(@"http://*****:*****@"http://127.0.0.1:5984/_replicator", new byte[0]);
                request.SendPut(@"http://127.0.0.1:5984/_global_changes", new byte[0]);
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка при создании баз:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}");
                return;
            }

            Log("Restart service");
            this.RestartService(COUCH_DB_SERVICE_NAME, SERVICE_RESTART_TIMEOUT_MILLISECONDS);

            try
            {
                Log("Add Admin"); // adm 123
                var localIninFulFileName = Path.Combine(iniDestinationFullPath, "local.ini");
                var localIniFile         = File.ReadAllLines(localIninFulFileName);
                for (int i = 0; i < localIniFile.Length; i++)
                {
                    if (localIniFile[i] == ";admin = mysecretpassword")
                    {
                        localIniFile[i] = "adm = -pbkdf2-4ba62a224fb986d7a08926f131eab71ce8b0ce22,7e5241170e58517b739181ce79ae82f0,10";
                    }
                }
                File.WriteAllLines(localIninFulFileName, localIniFile);
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка при добавлении администратора:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}");
                return;
            }

            Log("Restart service");
            RestartService(COUCH_DB_SERVICE_NAME, SERVICE_RESTART_TIMEOUT_MILLISECONDS);

            try
            {
                var json     = "{\"_id\": \"replicationtocenter\",\"source\":  \"http://*****:*****@retailcenter.sela.ru:5984/dk_0_remote\",\"target\":  \"http://*****:*****@localhost:5984/dk_0_remote\", \"continuous\":true, \"create_target\": true}";
                var response = request.SendPost("http://localhost:5984/_replicator", json, ADMIN_LOGIN, ADMIN_PASSWORD);
                Log($"Результат POST-запроса: {Environment.NewLine}{response}");
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка при выполнении POST-запроса:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}");
                return;
            }

            try
            {
                // Чистим временные файлы
                File.Delete(setupFileFullPath);
                File.Delete(defaultIniFullPath);
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка при очистке временных файлов:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}");
                return;
            }

            // Добавляем создание маркера успешной установки
            try
            {
                if (!File.Exists(MARK_FILENAME))
                {
                    File.WriteAllLines(MARK_FILENAME, new string[0]);
                    Log("Success-marker file was added.");
                }
                else
                {
                    Log("Success-marker file already exists.");
                }
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка при создании маркера успешной установки:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}");
                return;
            }

            SendReportToDB($"{this._logText.ToString()}{Environment.NewLine}CouchDB setup was successfully completed.", true);
        }
        protected override void ActExecution()
        {
            const string BAT_FILE_NAME          = @"commands.bat";
            const string CURL_EXE_FILE_NAME     = @"curl.exe";
            const string CURL_CRT_EXE_FILE_NAME = @"ca-bundle.crt";

            const string DIRECTORY_NAME        = "Curl";
            const string FTP_HOST              = @"mskftp.sela.ru";
            const string LOGIN                 = "******";
            const string PASSWORD              = "******";
            const string DESTINATION_DIRECTORY = @"C:\SystemUtils\Curl";

            this._logText = new StringBuilder();
            Log($"Download from FTP {CURL_EXE_FILE_NAME}");

            if (!Directory.Exists(DESTINATION_DIRECTORY))
            {
                Directory.CreateDirectory(DESTINATION_DIRECTORY);
                Log($"Directory {DESTINATION_DIRECTORY} was created");
            }

            var batFileFullPath = Path.Combine(DESTINATION_DIRECTORY, BAT_FILE_NAME);
            var curlFullPath    = Path.Combine(DESTINATION_DIRECTORY, CURL_EXE_FILE_NAME);
            var curlCrtFullPath = Path.Combine(DESTINATION_DIRECTORY, CURL_CRT_EXE_FILE_NAME);


            try
            {
                FtpWorks.DownloadFileFromFtp(DESTINATION_DIRECTORY, FTP_HOST, LOGIN, PASSWORD, DIRECTORY_NAME, BAT_FILE_NAME);
                FtpWorks.DownloadFileFromFtp(DESTINATION_DIRECTORY, FTP_HOST, LOGIN, PASSWORD, DIRECTORY_NAME, CURL_EXE_FILE_NAME);
                FtpWorks.DownloadFileFromFtp(DESTINATION_DIRECTORY, FTP_HOST, LOGIN, PASSWORD, DIRECTORY_NAME, CURL_CRT_EXE_FILE_NAME);
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка загрузки файлов по FTP:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}");
                return;
            }


            Log($"Executing command...");
            var executionResult = new List <string>();

            try
            {
                //this._command = @"http://localhost:5984/dk_0_remote";
                executionResult = ExecuteApplicationWithResult(curlFullPath, this._command);
                //var executionResult = ExecuteApplication(batFileFullPath, "");
                Log($"Executing completed, code {executionResult}");
            }
            catch (Exception ex)
            {
                SendReportToDB($"Ошибка выполнения команды:{Environment.NewLine}{ex.ToString()}{Environment.NewLine}{"Лог: "}{this._logText.ToString()}{Environment.NewLine}Console text: {string.Join(Environment.NewLine, executionResult.ToArray())}");
                return;
            }

            //this._parameterName = "doc_count";
            var resultText = string.Empty;

            if (string.IsNullOrEmpty(this._parameterName))
            {
                resultText = $"{this._logText.ToString()}{Environment.NewLine}CouchDB COMMAND was successfully completed.{Environment.NewLine}{string.Join(Environment.NewLine, executionResult.ToArray())}";
            }
            else
            {
                dynamic model = (dynamic)(NewtonJson.GetModelFromJson(string.Join(Environment.NewLine, executionResult.ToArray())));
                resultText = (string)((Newtonsoft.Json.Linq.JObject)model).GetValue(this._parameterName);
            }

            Result = resultText;
        }