Ejemplo n.º 1
0
        public ActionResult GetUpdateProcessSelected(int templateId)
        {
            UpdateGA update = _context.UpdateGA.Include(x => x.UpdateSteps).Where(x => x.Id == templateId).First();
            var      teste  = SetUpdateProcessSelected(update);

            return(Json(teste, new JsonSerializerSettings()));
        }
Ejemplo n.º 2
0
        /*
         * Type:
         * 1 = Directory
         * 2 = File
         */
        private static String UpdateDeleteFilesBackup(UpdateGA update, FileDelete filedelete, String path, String pathFolder, int folderId, int type)
        {
            Models.GAContext           context   = new Models.GAContext();
            GALibrary.Models.Parameter parameter = context.Parameter.FirstOrDefault();

            String pathBackup          = context.Parameter.First().PathBackup;
            String pathBackupDirectory = "";
            String log     = "";
            String pathZip = "";

            try
            {
                if (!pathBackup.EndsWith("\\"))
                {
                    pathBackup += "\\";
                }
                pathZip     = pathBackup + update.Schedule.GetValueOrDefault().Date.Year.ToString().PadLeft(4, '0') + "\\" + update.Schedule.GetValueOrDefault().Date.Month.ToString().PadLeft(2, '0') + "\\" + update.Id + "\\" + filedelete.Id + "\\";
                pathBackup += update.Schedule.GetValueOrDefault().Date.Year.ToString().PadLeft(4, '0') + "\\" + update.Schedule.GetValueOrDefault().Date.Month.ToString().PadLeft(2, '0') + "\\" + update.Id + "\\Arquivos apagados - " + filedelete.Id + "\\Pasta - " + folderId + "\\";

                pathBackupDirectory = pathBackup.Substring(0, pathBackup.LastIndexOf("\\"));
                if (!pathBackupDirectory.EndsWith("\\"))
                {
                    pathBackupDirectory += "\\";
                }

                if (!System.IO.Directory.Exists(pathBackupDirectory))
                {
                    System.IO.Directory.CreateDirectory(pathBackupDirectory);
                }

                //Delete folder
                if (type == 1)
                {
                    String pathDestination = pathBackupDirectory + path.Replace(pathFolder, "");
                    CopyFolder(new System.IO.DirectoryInfo(path), new System.IO.DirectoryInfo(pathDestination));
                }
                //Delete file
                if (type == 2)
                {
                    String fileName        = path.Substring(path.LastIndexOf("\\") + 1);
                    String fileDestination = pathBackupDirectory + path.Replace(pathFolder, "");
                    String directory       = fileDestination.Substring(0, fileDestination.LastIndexOf("\\"));
                    if (!System.IO.Directory.Exists(directory))
                    {
                        System.IO.Directory.CreateDirectory(directory);
                    }
                    System.IO.File.Copy(path, fileDestination, true);
                }

                GALibrary.GALogs.SaveLogUpdate(update, "FilesDelete", "Backup do arquivo " + path + " para " + pathBackup + " realizado.", 2, parameter);
            }
            catch (Exception error)
            {
                log = error.ToString();
                GALibrary.GALogs.SaveLogUpdate(update, "FilesDelete", "Backup do arquivo " + path + " para " + pathBackup + " não realizado. Erro: " + log, 1, parameter);
            }

            return(log);
        }
Ejemplo n.º 3
0
        public static String UpdateRemoveFiles(UpdateGA update, int fileDeleteId)
        {
            Models.GAContext context = new Models.GAContext();

            Parameter  parameter  = context.Parameter.FirstOrDefault();
            FileDelete filedelete = context.FileDelete.First(x => x.Id == fileDeleteId);
            List <FileDeleteFolder> fileDeleteFolders = context.FileDeleteFolder.Where(x => x.FileDeleteId == fileDeleteId).ToList();
            var    pathToDelete = filedelete.FilesDirectory.Replace("\n", "").Split('\r');
            String log          = "";

            try
            {
                GALibrary.GALogs.SaveLogUpdate(update, "FilesDelete", "Procedimento - " + filedelete.Name, 2, parameter);

                foreach (FileDeleteFolder fileDeleteFolder in fileDeleteFolders)
                {
                    String pathDestination = context.Folder.First(x => x.Id == fileDeleteFolder.FolderId).Path;
                    if (!pathDestination.EndsWith("\\"))
                    {
                        pathDestination += "\\";
                    }
                    for (int i = 0; i < pathToDelete.Length; i++)
                    {
                        if (pathToDelete[i].Trim() == "")
                        {
                            continue;
                        }
                        String path = pathDestination + pathToDelete[i];
                        try
                        {
                            //1 = Directory
                            //2 = File
                            if (System.IO.File.GetAttributes(path).HasFlag(System.IO.FileAttributes.Directory))
                            {
                                UpdateDeleteFilesBackup(update, filedelete, path, pathDestination, fileDeleteFolder.FolderId, 1);
                                System.IO.Directory.Delete(path, true);
                            }
                            else
                            {
                                UpdateDeleteFilesBackup(update, filedelete, path, pathDestination, fileDeleteFolder.FolderId, 2);
                                System.IO.File.Delete(path);
                            }
                        }
                        catch
                        {
                            GALibrary.GALogs.SaveLogUpdate(update, "FileDelete", "Arquivo/Pasta - " + path + " não foi encontrado.", 1, parameter);
                            log += path + " não foi encontrado" + System.Environment.NewLine;
                        }
                    }
                }
            }
            catch (Exception error)
            {
                log = error.ToString();
                GALibrary.GALogs.SaveLogUpdate(update, "FileDelete", "Arquivo/Pasta - " + filedelete.Id + " - " + log, 1, parameter);
            }

            return(log);
        }
Ejemplo n.º 4
0
        private List <SelectListItem> SetUpdateProcessSelected(UpdateGA update)
        {
            List <SelectListItem> items = new List <SelectListItem>();

            foreach (UpdateSteps step in update.UpdateSteps.OrderBy(x => x.Order))
            {
                String type        = "";
                String processName = "";

                switch (step.Type)
                {
                case 1:
                    type        = "Arquivos para apagar";
                    processName = _context.FileDelete.Find(step.ProcessId).Name;
                    break;

                case 2:
                    type        = "Arquivos para copiar";
                    processName = _context.File.Find(step.ProcessId).Name;
                    break;

                case 3:
                    type        = "Comandos";
                    processName = _context.Command.Find(step.ProcessId).Name;
                    break;

                case 4:
                    type        = "Serviço iniciar";
                    processName = _context.Service.Find(step.ProcessId).Name;
                    break;

                case 5:
                    type        = "Serviço parar";
                    processName = _context.Service.Find(step.ProcessId).Name;
                    break;

                case 6:
                    type        = "SQL";
                    processName = _context.SQL.Find(step.ProcessId).Name;
                    break;
                }


                var item = new SelectListItem
                {
                    Value = type + " - " + processName,
                    Text  = step.Type + " - " + step.ProcessId
                };

                items.Add(item);
            }

            return(items);
        }
Ejemplo n.º 5
0
        static void ExecutaUpdateTask(Object stateInfo)
        {
            Models.GAContext context   = new Models.GAContext();
            Parameter        parameter = context.Parameter.FirstOrDefault();

            UpdateGA update = (UpdateGA)stateInfo;

            GALibrary.GALogs.SaveLogUpdate(update, "Start", "Inicio da atualização", 2, parameter);
            UpdateGA updateStatus = Lib.Updates.UpdateApplication(update.Id);

            if (update.AlertUser)
            {
                CallSendMail(updateStatus);
            }
        }
Ejemplo n.º 6
0
        //Compacta a pasta do backup
        public static String CompressFolder(UpdateGA update, Parameter parameter)
        {
            String pathBackup = parameter.PathBackup;

            if (!pathBackup.EndsWith("\\"))
            {
                pathBackup += "\\";
            }

            pathBackup += update.Schedule.GetValueOrDefault().Date.Year.ToString().PadLeft(4, '0') + "\\" + update.Schedule.GetValueOrDefault().Date.Month.ToString().PadLeft(2, '0') + "\\" + update.Id + "\\";
            String name = "Backup.zip";

            String pathZip = pathBackup;

            if (!System.IO.Directory.Exists(pathBackup))
            {
                return(null);
            }

            if (System.IO.File.Exists(pathZip + "\\" + name))
            {
                System.IO.File.Delete(pathZip + "\\" + name);
            }

            try
            {
                Guid   guid = Guid.NewGuid();
                String arquivoTemporario = parameter.PathTemp + "\\" + guid + ".zip";
                ZipFile.CreateFromDirectory(pathZip, arquivoTemporario);
                System.IO.File.Copy(arquivoTemporario, pathZip + "backup.zip", true);
                System.IO.File.Delete(arquivoTemporario);

                foreach (String folder in System.IO.Directory.GetDirectories(pathZip))
                {
                    System.IO.Directory.Delete(folder, true);
                }

                GALogs.SaveLog("Compress", "Arquivos compactados com sucesso para o ID - " + update.Id, 2, parameter);
            }
            catch (Exception error)
            {
                GALogs.SaveLog("Compress", "Erro ao compactar arquivos para o update id - " + update.Id + " - " + error, 1, parameter);
                return(error.ToString());
            }
            return(null);
        }
Ejemplo n.º 7
0
        private static String UpdateCopyFilesBackup(UpdateGA update, int fileId, String fileBackup, String pathOrigin, int folderId)
        {
            Models.GAContext           context   = new Models.GAContext();
            GALibrary.Models.Parameter parameter = context.Parameter.FirstOrDefault();

            String pathBackup          = context.Parameter.First().PathBackup;
            File   file                = context.File.First(x => x.Id == fileId);
            String pathBackupDirectory = "";

            try
            {
                if (!pathBackup.EndsWith("\\"))
                {
                    pathBackup += "\\";
                }
                pathBackup += update.Schedule.GetValueOrDefault().Date.Year.ToString().PadLeft(4, '0') + "\\" + update.Schedule.GetValueOrDefault().Date.Month.ToString().PadLeft(2, '0') + "\\" + update.Id + "\\Arquivos copiados - " + file.Id + "\\Pasta - " + folderId + "\\";

                pathBackup += fileBackup.Replace(pathOrigin, "");
                pathBackup  = pathBackup.Replace("\\\\", "\\");
                fileBackup  = "\\" + fileBackup.Replace("\\\\", "\\");

                pathBackupDirectory = pathBackup.Substring(0, pathBackup.LastIndexOf("\\"));
                if (!System.IO.Directory.Exists(pathBackupDirectory))
                {
                    System.IO.Directory.CreateDirectory(pathBackupDirectory);
                }

                if (System.IO.File.Exists(fileBackup))
                {
                    System.IO.File.Copy(fileBackup, pathBackup, true);
                    GALibrary.GALogs.SaveLogUpdate(update, "Files", "Backup do arquivo " + fileBackup + " para " + pathBackup + " realizado.", 2, parameter);
                }
                else
                {
                    GALibrary.GALogs.SaveLogUpdate(update, "Files", "Backup do arquivo " + fileBackup + " não é necessário porque é um arquivo novo.", 2, parameter);
                }
            }
            catch (Exception error)
            {
                return(error.ToString());
            }

            return(null);
        }
Ejemplo n.º 8
0
        static void CallSendMail(UpdateGA update)
        {
            Models.GAContext context = new Models.GAContext();

            //Busca configuração de E-mails e LDAP
            var builder = new ConfigurationBuilder().SetBasePath(System.IO.Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            IConfigurationRoot configuration = builder.Build();

            var emailSettings = new EmailSettings();

            configuration.GetSection("EmailSettings").Bind(emailSettings);

            var ldap = new Ldap();

            configuration.GetSection("Ldap").Bind(ldap);

            //Busca parametros da aplicação
            Parameter parameter = context.Parameter.FirstOrDefault();

            //Envia e-mail
            GALibrary.GAMail.SendMail(null, 1, update, emailSettings, parameter, "", ldap);
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name,Description,ApplicationId,Enable,Schedule,Approved,AprovedDate,Status,Date,User,Demanda,FilesRemoved,Manual,Template,AlertmailId,AlertUser")] UpdateGA updateGA, String[] updateProcessSelected, int updateEnvironmentId, int updateApplicationId, string button, int updateTemplate, int updateEmails, bool updateManual)
        {
            if (id != updateGA.Id)
            {
                return(NotFound());
            }

            try
            {
                int tipo = 0;
                switch (button)
                {
                case "Agendar a atualização":
                    tipo = 1;
                    break;

                case "Salvar como rascunho":
                    tipo = 2;
                    break;

                case "Salvar como template":
                    tipo = 3;
                    break;
                }

                updateGA.Date          = DateTime.Now;
                updateGA.User          = User.Identity.Name;
                updateGA.Enable        = true;
                updateGA.Approved      = false;
                updateGA.Status        = 0;
                updateGA.FilesRemoved  = false;
                updateGA.ApplicationId = updateApplicationId;
                updateGA.AlertmailId   = updateEmails;
                updateGA.Manual        = Convert.ToBoolean(updateManual);


                if ((tipo == 1 || tipo == 3) && !updateManual)
                {
                    if (updateProcessSelected == null || updateProcessSelected.Length == 0)
                    {
                        ModelState.AddModelError("UpdateSteps", "É preciso cadastrar ao menos um processo.");
                    }
                }

                if (tipo == 1)
                {
                    if (updateGA.Schedule < DateTime.Now || updateGA.Schedule == null)
                    {
                        ModelState.AddModelError("Schedule", "A data não pode estar em branco e precisa ser posterior ao horário atual.");
                    }

                    if (updateGA.Demanda == null)
                    {
                        ModelState.AddModelError("Demanda", "É preciso informar o número da demanda.");
                    }
                }

                if (tipo == 2)
                {
                    updateGA.Status = 4;
                }

                if (tipo == 3)
                {
                    updateGA.Template = true;
                }


                if (ModelState.IsValid)
                {
                    _context.UpdateSteps.RemoveRange(_context.UpdateSteps.Where(x => x.UpdateId == updateGA.Id));
                    await _context.SaveChangesAsync();

                    await this.AtualizaSteps(updateProcessSelected, updateGA.Id);

                    _context.Update(updateGA);
                    await _context.SaveChangesAsync();

                    GALibrary.GALogs.SaveLog("Update", "Fim da edicao da atualizacao " + updateGA.Name + " realizada pelo usuario " + User.Identity.Name, 2, _context.Parameter.FirstOrDefault());

                    //Envia e-mail
                    if (tipo == 1 && updateEnvironmentId == 1)
                    {
                        Application application = _context.Application.FirstOrDefault(x => x.Id == updateGA.ApplicationId);
                        Parameter   parameter   = _context.Parameter.FirstOrDefault();
                        String      email       = _context.AlertMail.First(x => x.Id == updateGA.AlertmailId).Email;

                        GALibrary.GAMail.SendMail(email, 2, updateGA, (EmailSettings)emailSettings.Value, parameter, application.Name, (Ldap)ldap.Value);
                    }

                    return(RedirectToAction(nameof(Index)));
                }


                ViewBag.updateApplicationName = _context.Application.First(x => x.Id == updateGA.ApplicationId).Name;
                ViewBag.updateType            = tiposAtualizacoes;
                ViewBag.updateFilesDelete     = new SelectList(String.Empty, "Text", "Value");
                ViewBag.updateFiles           = new SelectList(String.Empty, "Text", "Value");
                ViewBag.updateCommands        = new SelectList(String.Empty, "Text", "Value");
                ViewBag.updateServices        = new SelectList(String.Empty, "Text", "Value");
                ViewBag.updateSQLs            = new SelectList(String.Empty, "Text", "Value");

                ViewBag.updateApplicationId   = new SelectList(_context.Application.Where(x => x.Enable).OrderBy(x => x.Name), "Id", "Name", updateApplicationId);
                ViewBag.updateEnvironmentId   = new SelectList(_context.Environment.Where(x => x.Enable == true).OrderBy(x => x.Name), "Id", "Name", updateEnvironmentId);
                ViewBag.updateProcessSelected = new MultiSelectList(SetUpdateProcessSelected(updateGA), "Text", "Value");

                ViewBag.updateEmails = new SelectList(_context.AlertMail.Where(x => x.Enable).OrderBy(x => x.Name), "Id", "Name", updateGA.AlertmailId);
                ViewBag.updateManual = new SelectList(new[] { new { ID = true, Name = "Sim" }, new { ID = false, Name = "Não" } }, "ID", "Name", updateGA.Manual);

                return(View(updateGA));
            }
            catch (Exception erro)
            {
                GALibrary.GALogs.SaveLog("Update", "Erro ao editar a atualizacao " + updateGA.Name + " pelo usuario " + User.Identity.Name + ": " + erro.ToString(), 1, _context.Parameter.FirstOrDefault());
                return(View("~/Views/Shared/Error.cshtml"));
            }
        }
Ejemplo n.º 10
0
        public static String UpdateSQL(UpdateGA update, int sqlId)
        {
            Models.GAContext           context   = new Models.GAContext();
            GALibrary.Models.Parameter parameter = context.Parameter.FirstOrDefault();

            SQL    sql = context.SQL.First(x => x.Id == sqlId);
            String log = null;

            GALibrary.GALogs.SaveLogUpdate(update, "SQL", "Procedimento - " + sql.Name, 2, parameter);

            //2 = Text
            //1 = File
            if (sql.Type == 2)
            {
                try
                {
                    log = UpdateSQLCommand(sql.SQLScript, sql);
                    GALibrary.GALogs.SaveLogUpdate(update, "SQL", "SQL - " + sql.SQLScript + " - " + log, 2, parameter);
                }
                catch (Exception error)
                {
                    log = error.ToString();
                    GALibrary.GALogs.SaveLogUpdate(update, "SQL", log, 1, parameter);
                    return(log);
                }
            }
            else
            {
                try
                {
                    String pathUpdate = context.Parameter.First().PathUpdate;

                    if (!pathUpdate.EndsWith("\\"))
                    {
                        pathUpdate += "\\" + "SQL" + "\\";
                    }
                    pathUpdate += sql.Date.Year.ToString().PadLeft(4, '0') + "\\" + sql.Date.Month.ToString().PadLeft(2, '0') + "\\" + sql.Id + "\\";


                    //descompactar arquivo

                    try
                    {
                        ZipFile.ExtractToDirectory(pathUpdate + "sql.zip", pathUpdate);
                    }
                    catch (Exception error)
                    {
                        log = error.ToString();
                        GALibrary.GALogs.SaveLogUpdate(update, "SQL", "SQL - Erro ao descompactar arquivo - " + log, 1, parameter);
                    }


                    String[] fileEntries = System.IO.Directory.GetFiles(pathUpdate, "*.sql");
                    Array.Sort(fileEntries);

                    //Busca todos os SQLs do diretório
                    foreach (string fileName in fileEntries)
                    {
                        try
                        {
                            //Busca o encode do arquivo para evitar erros de acentuação
//                            var encode =  GALibrary.GAFiles.GetEncoding(fileName);
                            String sqlScript = System.IO.File.ReadAllText(fileName, CodePagesEncodingProvider.Instance.GetEncoding(1252));

                            System.IO.FileInfo sqlScriptInfo = new System.IO.FileInfo(fileName);

                            log = "Script: " + sqlScript + " - " + UpdateSQLCommand(sqlScript, sql);
                            GALibrary.GALogs.SaveLogUpdate(update, "SQL", "SQL - " + sqlScriptInfo.Name + " - " + log, 2, parameter);
                        }
                        catch (Exception error)
                        {
                            log = error.ToString();
                            GALibrary.GALogs.SaveLogUpdate(update, "SQL", "SQL - " + fileName + " - " + log, 1, parameter);
                            return(log);
                        }
                    }

                    //Apaga arquivos SQL após a atualização e deixa somente o zip
                    System.IO.DirectoryInfo f = new System.IO.DirectoryInfo(pathUpdate);
                    System.IO.FileInfo[]    a = f.GetFiles();
                    for (int i = 0; i < a.Length; i++)
                    {
                        if (a[i].Name.ToUpper().EndsWith(".SQL"))
                        {
                            a[i].Delete();
                        }
                    }
                }
                catch (Exception error)
                {
                    log = error.ToString();
                    GALibrary.GALogs.SaveLogUpdate(update, "SQL", log, 1, parameter);
                    return(log);
                }
            }

            return(log);
        }
Ejemplo n.º 11
0
        public static String UpdateServiceStop(UpdateGA update, ProcedureSchedule procedureschedule, int serviceId)
        {
            Models.GAContext           context   = new Models.GAContext();
            GALibrary.Models.Parameter parameter = context.Parameter.FirstOrDefault();

            Service service = context.Service.First(x => x.Id == serviceId);
            Server  server  = context.Server.Include(x => x.ServerUser).First(x => x.Id == service.ServerId);
            OS      os      = context.OS.First(x => x.Id == server.OSId);

            String result          = "";
            String comandoCompleto = os.AccessCommand;

            comandoCompleto = comandoCompleto.Replace("nomeDoServidor", server.Name);
            comandoCompleto = comandoCompleto.Replace("usuarioDeAcesso", GALibrary.GACrypto.Base64Decode(server.ServerUser.ServerUsername));
            comandoCompleto = comandoCompleto.Replace("senhaDeAcesso", GALibrary.GACrypto.Base64Decode(server.ServerUser.ServerPassword));
            comandoCompleto = comandoCompleto.Replace("comandoParaExecutar", service.CommandStop);

            try
            {
                if (update != null)
                {
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStop", "Procedimento - " + service.Name, 2, parameter);
                }
                else
                {
                    GALibrary.GALogs.SaveLogProcedure(procedureschedule, "ServiceStop - " + service.Name, "Parando servico", 2, parameter);
                }

                System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + comandoCompleto);
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.CreateNoWindow         = true;
                procStartInfo.UseShellExecute        = false;
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();

                result = proc.StandardOutput.ReadToEnd();

                if (update != null)
                {
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStop - " + service.Name, "Retorno: " + result, 2, parameter);
                }
                else
                {
                    GALibrary.GALogs.SaveLogProcedure(procedureschedule, "ServiceStop - " + service.Name, "Retorno: " + result, 2, parameter);
                }
            }
            catch (Exception error)
            {
                if (update != null)
                {
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStop  - " + service.Name, error.ToString(), 1, parameter);
                }
                else
                {
                    GALibrary.GALogs.SaveLogProcedure(procedureschedule, "ServiceStop  - " + service.Name, error.ToString(), 1, parameter);
                }
                return(error.ToString());
            }

            return(result);
        }
Ejemplo n.º 12
0
        public static UpdateGA UpdateApplication(int updateId)
        {
            Models.GAContext context = new Models.GAContext();

            GALibrary.Models.Parameter parameter = context.Parameter.FirstOrDefault();

            var      steps  = context.UpdateSteps.Where(x => x.UpdateId == updateId).ToList().OrderBy(x => x.Order);
            UpdateGA update = context.UpdateGA.First(x => x.Id == updateId);

            //Atualiza status para atualizando (3)
            update.Status = 3;
            context.Entry(update).State = EntityState.Modified;
            context.SaveChanges();

            foreach (UpdateSteps step in steps)
            {
                switch (step.Type)
                {
                case 1:
                    GALibrary.GALogs.SaveLogUpdate(update, "FilesDelete", "Inicio da remocao de arquivos", 2, parameter);
                    UpdateRemoveFiles(update, step.ProcessId);
                    GALibrary.GALogs.SaveLogUpdate(update, "FilesDelete", "Fim da remocao de arquivos", 2, parameter);
                    break;

                case 2:
                    GALibrary.GALogs.SaveLogUpdate(update, "Files", "Inicio da copia de arquivos", 2, parameter);
                    UpdateCopyFiles(update, step.ProcessId);
                    GALibrary.GALogs.SaveLogUpdate(update, "Files", "Fim da copia de arquivos", 2, parameter);
                    break;

                case 3:
                    GALibrary.GALogs.SaveLogUpdate(update, "Command", "Inicio da execucao do comando", 2, parameter);
                    UpdateCommand(update, null, step.ProcessId);
                    GALibrary.GALogs.SaveLogUpdate(update, "Command", "Fim da execucao do comando", 2, parameter);
                    break;

                case 4:
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStart", "Inicio do start de servico", 2, parameter);
                    UpdateServiceStart(update, null, step.ProcessId);
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStart", "Fim do start de servico", 2, parameter);
                    break;

                case 5:
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStop", "Inicio da parada de servico", 2, parameter);
                    UpdateServiceStop(update, null, step.ProcessId);
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStop", "Fim da parada de servico", 2, parameter);
                    break;

                case 6:
                    GALibrary.GALogs.SaveLogUpdate(update, "SQL", "Inicio da execucao SQL", 2, parameter);
                    UpdateSQL(update, step.ProcessId);
                    GALibrary.GALogs.SaveLogUpdate(update, "SQL", "Fim da execucao SQL", 2, parameter);
                    break;
                }
            }

            GALibrary.GAFiles.CompressFolder(update, parameter);


            try
            {
                string log;
                using (System.IO.StreamReader reader = new System.IO.StreamReader(GALibrary.GALogs.GetUpdateLog(update, parameter)))
                {
                    log = reader.ReadToEnd();
                }

                if (log.Contains(" - Error - "))
                {
                    update.Status = 2;
                }
                else
                {
                    update.Status = 1;
                }
            }
            catch (Exception erro) {
                update.Status = 1;
                GALibrary.GALogs.SaveLogUpdate(update, "Status", "Erro ao salvar status: " + erro.ToString(), 1, parameter);
            }

            context.Entry(update).State = EntityState.Modified;
            context.SaveChanges();

            return(update);
        }
Ejemplo n.º 13
0
        public static String UpdateCopyFiles(UpdateGA update, int fileId)
        {
            Models.GAContext context = new Models.GAContext();

            GALibrary.Models.Parameter parameter = context.Parameter.FirstOrDefault();

            File file = context.File.First(x => x.Id == fileId);
            List <FileFolder> filefolders = context.FileFolder.Where(x => x.FileId == fileId).ToList();

            String  logCopy    = "";
            String  pathUpdate = context.Parameter.First().PathUpdate;
            String  pathZip    = "";
            Boolean errorFound = false;

            // this.SaveLogUpdate(update, "Files", "Inicio da cópia de arquivos", 2);

            if (!pathUpdate.EndsWith("\\"))
            {
                pathUpdate += "\\";
            }
            pathUpdate += "Files" + "\\" + file.Date.Year.ToString().PadLeft(4, '0') + "\\" + file.Date.Month.ToString().PadLeft(2, '0') + "\\" + file.Id + "\\";

            pathZip = pathUpdate + "extracted";

            try
            {
                String[] fileZip = System.IO.Directory.GetFiles(pathUpdate);

                //Apaga o conteúdo extraido caso já exista:
                if (System.IO.Directory.Exists(pathZip))
                {
                    System.IO.Directory.Delete(pathZip, true);
                }

                //Somente busca 1 arquivo da pasta, pois o sistema não permite mais que um
                ZipFile.ExtractToDirectory(fileZip[0], pathZip);

                GALibrary.GALogs.SaveLogUpdate(update, "Files", "Procedimento - " + file.Name, 2, parameter);
                GALibrary.GALogs.SaveLogUpdate(update, "Files", "Arquivos descompactados na pasta " + pathZip, 2, parameter);

                //Copia arquivos
                try
                {
                    foreach (FileFolder filefolder in filefolders)
                    {
                        String pathDestination = context.Folder.First(x => x.Id == filefolder.FolderId).Path;
                        if (!pathDestination.EndsWith("\\"))
                        {
                            pathDestination += "\\";
                        }


                        foreach (string dirPath in System.IO.Directory.GetDirectories(pathZip, "*", System.IO.SearchOption.AllDirectories))
                        {
                            System.IO.Directory.CreateDirectory(dirPath.Replace(pathZip, pathDestination));
                        }

                        String[] allFiles = System.IO.Directory.GetFiles(pathZip, "*.*", System.IO.SearchOption.AllDirectories);
                        //Copy all the files & Replaces any files with the same name
                        foreach (string newPath in allFiles)
                        {
                            try
                            {
                                //Faz backup do arquivo
                                logCopy += UpdateCopyFilesBackup(update, fileId, newPath.Replace(pathZip, pathDestination), pathDestination, filefolder.FolderId);
                                if (logCopy != "")
                                {
                                    GALibrary.GALogs.SaveLogUpdate(update, "Files", "Erro ao fazer backup do arquivo " + pathZip + " para " + pathDestination + ": " + logCopy, 1, parameter);
                                    if (System.IO.Directory.Exists(pathZip))
                                    {
                                        System.IO.Directory.Delete(pathZip, true);
                                    }
                                    return(logCopy);
                                }
                                //Só copia se fez backup
                                String caminhoCopia = newPath.Replace(pathZip, pathDestination);
                                System.IO.File.Copy(newPath, newPath.Replace(pathZip, pathDestination), true);
                                GALibrary.GALogs.SaveLogUpdate(update, "Files", "Copiado arquivo " + newPath + " para " + caminhoCopia, 2, parameter);

                                //Salva histórico dos arquivos
                                try
                                {
                                    System.IO.FileInfo fileInfo    = new System.IO.FileInfo(caminhoCopia);
                                    FileHistory        filehistory = new FileHistory();
                                    filehistory.FileName = fileInfo.Name;
                                    filehistory.Folder   = fileInfo.FullName;
                                    filehistory.FileId   = fileId;
                                    filehistory.Size     = fileInfo.Length;
                                    filehistory.Date     = fileInfo.LastWriteTime;
                                    filehistory.UpdateId = update.Id;
                                    context.FileHistory.Add(filehistory);
                                    context.SaveChanges();
                                }
                                catch { }
                            }
                            catch (Exception error)
                            {
                                GALibrary.GALogs.SaveLogUpdate(update, "Files", "Erro ao copiar arquivo " + newPath + " para " + newPath.Replace(pathZip, pathDestination) + ": " + error.ToString(), 1, parameter);
                                logCopy   += error.ToString();
                                errorFound = true;
                            }
                        }
                    }
                }
                catch (Exception error)
                {
                    GALibrary.GALogs.SaveLogUpdate(update, "Files", error.ToString(), 1, parameter);
                    errorFound = true;
                }
            }
            catch (Exception error)
            {
                GALibrary.GALogs.SaveLogUpdate(update, "Files", error.ToString(), 1, parameter);
                errorFound = true;
            }

            //Remove pasta descompactada
            if (System.IO.Directory.Exists(pathZip))
            {
                System.IO.Directory.Delete(pathZip, true);
            }

            if (errorFound)
            {
                GALibrary.GALogs.SaveLogUpdate(update, "Files", logCopy, 1, parameter);
            }

            return(null);
        }