Пример #1
0
        //Log Level
        //    1 - only errors
        //    2 - all

        public static void SaveLog(String step, String message, int logLevel, Models.Parameter parameter)
        {
            String logFolder        = parameter.PathLog;
            int    logLevelDatabase = parameter.LogLevelApplication;
            String logName          = "";
            String logLevelName     = "Message";

            if (logLevel == 1)
            {
                logLevelName = "Error";
            }

            DateTime today = DateTime.Now;

            logName = "GA-" + today.Year.ToString().PadLeft(4, '0') + "-" + today.Month.ToString().PadLeft(2, '0') + "-" + today.Day.ToString().PadLeft(2, '0') + ".log";

            try
            {
                if (!logFolder.EndsWith("\\"))
                {
                    logFolder += "\\";
                }
                Directory.CreateDirectory(logFolder);

                if (logLevel <= logLevelDatabase)
                {
                    System.IO.File.AppendAllText(logFolder + logName, DateTime.Now.ToString() + " - " + logLevelName + " - " + step + " - " + message + System.Environment.NewLine);
                }
            }

            catch (Exception error)
            {
                System.IO.File.AppendAllText("c:\\temp\\" + logName, DateTime.Now.ToString() + " - " + logLevelName + " - " + step + " - Erro ao abrir o arquivo de log: " + error.ToString() + System.Environment.NewLine);
            }
        }
Пример #2
0
        public static void DeleteFiles(int id, DateTime idDate, int type, Models.Parameter parameter)
        {
            String folderUpdate = parameter.PathUpdate;
            String updateType;

            if (type == 1)
            {
                updateType = "SQL";
            }
            else
            {
                updateType = "Files";
            }


            if (!folderUpdate.EndsWith("\\"))
            {
                folderUpdate += "\\";
            }
            folderUpdate += updateType + "\\" + idDate.Year.ToString().PadLeft(4, '0') + "\\" + idDate.Month.ToString().PadLeft(2, '0') + "\\" + id;

            if (Directory.Exists(folderUpdate))
            {
                Directory.Delete(folderUpdate, true);
            }
        }
Пример #3
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);
        }
Пример #4
0
        public static System.IO.Stream GetUpdateLog(Models.UpdateGA update, Models.Parameter parameter)
        {
            String path = parameter.PathLog;

            if (!path.EndsWith("\\"))
            {
                path += "\\";
            }
            path += "Updates\\" + "GA-Update" + "-" + update.Schedule.GetValueOrDefault().Year.ToString().PadLeft(4, '0') + "-" + update.Schedule.GetValueOrDefault().Month.ToString().PadLeft(2, '0') + "-" + update.Schedule.GetValueOrDefault().Day.ToString().PadLeft(2, '0') + "-" + update.Name + "-" + update.Id + ".log";
            return(new System.IO.FileStream(path, System.IO.FileMode.Open));
        }
Пример #5
0
        /*
         * private static Boolean AprovaAtualizacaoComRDM(UpdateGA update)
         * {
         *
         *  var builder = new ConfigurationBuilder().SetBasePath(System.IO.Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
         *  IConfigurationRoot configuration = builder.Build();
         *
         *
         *  var traceGP = new Models.TraceGP();
         *  configuration.GetSection("TraceGP").Bind(traceGP);
         *
         *  String stringConnection = traceGP.TraceGPConexao;
         *  String select = traceGP.TraceGPSelect;
         *
         *
         *  OracleConnection conn;
         *  OracleCommand cmd = null;
         *  conn = new OracleConnection(stringConnection);
         *
         *  conn.Open();
         *  cmd = new OracleCommand(select, conn);
         *  cmd.Parameters.Clear();
         *  cmd.Parameters.Add(":RDM", update.RDM);
         *
         *  OracleDataReader reader = cmd.ExecuteReader();
         *  reader.Read();
         *
         *  if (!reader.HasRows)
         *  {
         *      return false;
         *  }
         *
         *  int resultado = Convert.ToInt16(reader.GetValue(0).ToString());
         *
         *  conn.Close();
         *
         *  if (resultado == 87 || resultado == 60 || resultado == 76 || resultado == 33)
         *  {
         *      return true;
         *  }
         *
         *
         *  return false;
         * }*/


        public static void ExecuteProcedure(ProcedureSchedule procedureSchedule)
        {
            Models.GAContext context = new Models.GAContext();

            GALibrary.Models.Parameter parameter = context.Parameter.FirstOrDefault();
            var steps = context.ProcedureSteps.Where(x => x.ProcedureID == procedureSchedule.ProcedureID).ToList().OrderBy(x => x.Order);

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

            try
            {
                foreach (ProcedureSteps step in steps)
                {
                    switch (step.Type)
                    {
                    case 3:
                        GALibrary.GALogs.SaveLogProcedure(procedureSchedule, "Command", "Inicio da execucao do comando", 2, parameter);
                        UpdateCommand(null, procedureSchedule, step.ProcessId);
                        GALibrary.GALogs.SaveLogProcedure(procedureSchedule, "Command", "Fim da execucao do comando", 2, parameter);
                        break;

                    case 4:
                        GALibrary.GALogs.SaveLogProcedure(procedureSchedule, "ServiceStart", "Inicio do start de serviço", 2, parameter);
                        UpdateServiceStart(null, procedureSchedule, step.ProcessId);
                        GALibrary.GALogs.SaveLogProcedure(procedureSchedule, "ServiceStart", "Fim do start de serviço", 2, parameter);
                        break;

                    case 5:
                        GALibrary.GALogs.SaveLogProcedure(procedureSchedule, "ServiceStop", "Inicio da parada de serviço", 2, parameter);
                        UpdateServiceStop(null, procedureSchedule, step.ProcessId);
                        GALibrary.GALogs.SaveLogProcedure(procedureSchedule, "ServiceStop", "Fim da parada de serviço", 2, parameter);
                        break;
                    }
                }

                procedureSchedule.Status = 1;
                context.Entry(procedureSchedule).State = EntityState.Modified;
                context.SaveChanges();
            }

            catch
            {
                procedureSchedule.Status = 2;
                context.Entry(procedureSchedule).State = EntityState.Modified;
                context.SaveChanges();
            }
        }
Пример #6
0
        public static String CompressSQLFiles(int id, String step, Models.Parameter parameter)
        {
            String   folder     = parameter.PathUpdate;
            String   folderTemp = parameter.PathTemp;
            DateTime today      = DateTime.Now;

            try
            {
                if (!Directory.Exists(folderTemp))
                {
                    Directory.CreateDirectory(folderTemp);
                }

                if (!folder.EndsWith("\\"))
                {
                    folder += "\\";
                }
                folder += "SQL\\" + today.Year.ToString().PadLeft(4, '0') + "\\" + today.Month.ToString().PadLeft(2, '0') + "\\" + id + "\\";


                DirectoryInfo f = new DirectoryInfo(folder);
                FileInfo[]    a = f.GetFiles();

                Guid guid = Guid.NewGuid();

                String arquivoTemporario = folderTemp + "\\" + guid + ".zip";
                ZipFile.CreateFromDirectory(folder, arquivoTemporario);
                File.Copy(arquivoTemporario, folder + "sql.zip", true);
                File.Delete(arquivoTemporario);

                for (int i = 0; i < a.Length; i++)
                {
                    if (a[i].Name.ToUpper().EndsWith(".SQL"))
                    {
                        a[i].Delete();
                    }
                }


                GALibrary.GALogs.SaveLog(step, "Arquivos compactados com sucesso para o ID - " + id, 2, parameter);
            }
            catch (Exception error)
            {
                GALibrary.GALogs.SaveLog(step, "Erro ao compactar arquivos para o ID - " + id + " - " + error, 1, parameter);
                return(error.ToString());
            }
            return(null);
        }
Пример #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);
        }
Пример #8
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);
        }
Пример #9
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);
        }
Пример #10
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);
        }
Пример #11
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);
        }
Пример #12
0
        public static String SaveLogUpdate(Models.UpdateGA update, String process, String message, int logLevel, Models.Parameter parameter)
        {
            String logFolder        = parameter.PathLog;
            int    logLevelDatabase = parameter.LogLevelUpdate;
            String logName          = "";
            String logLevelName     = "Message";

            if (logLevel == 1)
            {
                logLevelName = "Error";
            }

            DateTime today = DateTime.Now;

            logName = "GA-Update-" + update.Schedule.GetValueOrDefault().Year.ToString().PadLeft(4, '0') + "-" + update.Schedule.GetValueOrDefault().Month.ToString().PadLeft(2, '0') + "-" + update.Schedule.GetValueOrDefault().Day.ToString().PadLeft(2, '0') + "-" + update.Name + "-" + update.Id + ".log";

            try
            {
                if (!logFolder.EndsWith("\\"))
                {
                    logFolder += "\\";
                }
                logFolder += "Updates\\";
                System.IO.Directory.CreateDirectory(logFolder);

                if (logLevel <= logLevelDatabase)
                {
                    System.IO.File.AppendAllText(logFolder + logName, DateTime.Now.ToString() + " - " + logLevelName + " - " + process + " - " + message + System.Environment.NewLine);
                }
            }

            catch (Exception error)
            {
                return(error.ToString());
            }

            return(null);
        }