Exemplo n.º 1
0
        public static bool SendEmail(EmailSettings emailSettings, string subject, string body)
        {
            try {
                var emailPassword = SecurityHelpers.DecodeSecret(emailSettings.EmailPassword);

                var client = new SmtpClient(emailSettings.EmailServerAddress, emailSettings.EmailPort)
                {
                    Credentials =
                        new NetworkCredential(emailSettings.EmailUser, emailPassword),
                    EnableSsl = emailSettings.EmailUseSSL
                };

                //Create the email
                var mailMessage = new MailMessage(emailSettings.EmailUser, emailSettings.EmailTo, subject, body);

                //Try to attach the log if specified
                var logFile = Path.Combine(Environment.CurrentDirectory, "logs", "logfile.txt");

                if (File.Exists(logFile))
                {
                    mailMessage.Attachments.Add(new Attachment(logFile));
                }
                else
                {
                    log.Warn("Unable to find log file to attach: " + logFile);
                }

                client.Send(mailMessage);
                return(true);
            }catch (Exception e) {
                log.ErrorException("Could not send email. " + subject, e);
                return(false);
            }
        }
Exemplo n.º 2
0
        private string BuildZipArguments(BackupJob backupJob, string listFile)
        {
            const string archiveType = "7z";

            var arguments = new StringBuilder(100);

            arguments.Append(backupJob.IsFullBackup ? "a" : "u");

            arguments.AppendFormat(" \"{0}\"", backupJob.FullBackupFile.FullName);

            arguments.AppendFormat(" -t{0}", archiveType);
            arguments.AppendFormat(" -mx={0}", backupSettings.CompressionLevel);
            arguments.AppendFormat(" -mhe={0}", backupSettings.EncryptHeaders ? "on" : "off");

            //Is the archive encrypted?
            var archivePassword = SecurityHelpers.DecodeSecret(backupSettings.ArchivePassword);

            if (!string.IsNullOrEmpty(archivePassword))
            {
                arguments.AppendFormat(" -p{0}", archivePassword);
            }

            if (!backupJob.IsFullBackup)
            {
                arguments.Append(" -ms=off");
                arguments.Append(" -u- -up0q3r2x2y2z0w2");
                arguments.AppendFormat("!\"{0}\"", backupJob.IncrementalFile.FullName);
            }

            arguments.AppendFormat(" @{0}", listFile);
            return(arguments.ToString());
        }
Exemplo n.º 3
0
        private static int UpdateOrCreateSettingsFile()
        {
            var configFile     = GetConfigFile();
            var backupSettings = File.Exists(configFile) ? BackupSettings.LoadBackupSettings(configFile) : new BackupSettings();

            var passwordSettingsDialog = new PasswordSettingsDialog();

            if (passwordSettingsDialog.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrWhiteSpace(passwordSettingsDialog.ArchivePassword))
                {
                    backupSettings.ArchivePassword = SecurityHelpers.EncodeSecret(passwordSettingsDialog.ArchivePassword);
                }

                if (!string.IsNullOrWhiteSpace(passwordSettingsDialog.FTPPassword))
                {
                    backupSettings.FTPSettings.FTPPassword = SecurityHelpers.EncodeSecret(passwordSettingsDialog.FTPPassword);
                }

                if (!string.IsNullOrWhiteSpace(passwordSettingsDialog.EmailPassword))
                {
                    backupSettings.EmailSettings.EmailPassword = SecurityHelpers.EncodeSecret(passwordSettingsDialog.EmailPassword);
                }

                //Create a backup of the existing config file
                if (File.Exists(configFile))
                {
                    File.Copy(configFile, configFile + ".bak", true);
                }

                backupSettings.SaveBackupSettings(configFile);
            }
            return(ExitCodeSuccess);
        }
Exemplo n.º 4
0
        private bool TestFullBackupFile(BackupJob backupJob)
        {
            string args            = "t \"" + backupJob.FullBackupFile.FullName + "\"";
            var    archivePassword = SecurityHelpers.DecodeSecret(backupSettings.ArchivePassword);

            if (!string.IsNullOrEmpty(archivePassword))
            {
                args += " -p" + archivePassword;
            }

            var p = new ProcessStartInfo {
                FileName               = backupSettings.SevenZipExecutablePath,
                UseShellExecute        = false,
                Arguments              = args,
                RedirectStandardOutput = true
            };
            var    x      = Process.Start(p);
            string output = x.StandardOutput.ReadToEnd();

            x.WaitForExit(1000 * 60 * 30);
            log.Debug(output);

            return(x.ExitCode == 0);
        }
Exemplo n.º 5
0
        private void SyncFTPBackups()
        {
            var ftpSettings = backupSettings.FTPSettings;

            log.Info("Starting FTP: {0}", ftpSettings.FTPServerAddress);

            var ftpPassword = SecurityHelpers.DecodeSecret(ftpSettings.FTPPassword);

            var ftpClient = new FTPClient(ftpSettings.FTPServerAddress, ftpSettings.FTPUser, ftpPassword, port: ftpSettings.FTPPort, useSSL: ftpSettings.FTPUseSSL,
                                          attempts: ftpSettings.RetryAttempts, attemptWaitSeconds: ftpSettings.RetryDelaySeconds);

            var localBackupDirectory = new DirectoryInfo(backupSettings.LocalBackupFolder);
            var localBackupFiles     = new List <FileInfo>();

            localBackupFiles.AddRange(localBackupDirectory.GetFiles("I-*.7z"));
            localBackupFiles.AddRange(localBackupDirectory.GetFiles("F-*.7z"));

            var list = ftpClient.GetList();

            if (list == null)
            {
                throw new ApplicationException("Could not retrieve list from FTP site.");
            }

            var remoteBackupFileNames = list.Where(rbf =>
                                                   rbf.EndsWith(".7z", StringComparison.OrdinalIgnoreCase) &&
                                                   (rbf.StartsWith("I-", StringComparison.OrdinalIgnoreCase) || rbf.StartsWith("F-", StringComparison.OrdinalIgnoreCase))
                                                   ).ToList();

            foreach (string remoteBackupFileName in remoteBackupFileNames)
            {
                bool existsLocal = localBackupFiles.Exists(lbf => string.Equals(lbf.Name, remoteBackupFileName, StringComparison.OrdinalIgnoreCase));
                if (!existsLocal)
                {
                    log.Info("Deleting remote: {0}", remoteBackupFileName);
                    if (!ftpClient.DeleteFile(remoteBackupFileName))
                    {
                        throw new ApplicationException("Delete failed. " + ftpClient.LastStatusDescription);
                    }
                }
            }

            foreach (var localBackupFile in localBackupFiles)
            {
                string remoteFileName = remoteBackupFileNames.Find(rbfn => string.Equals(rbfn, localBackupFile.Name, StringComparison.OrdinalIgnoreCase));
                bool   shouldUpload   = false;

                if (string.IsNullOrEmpty(remoteFileName))
                {
                    shouldUpload = true;
                    log.Info("File: {0} ({1}) does not exist on FTP site. Starting upload.", localBackupFile.Name, StaticHelpers.FormatFileSize(localBackupFile.Length));
                }
                else
                {
                    //Check the sizes
                    if (ftpSettings.FTPVerifySizes)
                    {
                        long?ftpFileSize = ftpClient.GetFileSize(remoteFileName);
                        shouldUpload = localBackupFile.Length != ftpFileSize;
                        if (shouldUpload)
                        {
                            log.Warn("File: {0} ({1}) size DOES NOT match file size on FTP site ({2}).", localBackupFile.Name, StaticHelpers.FormatFileSize(localBackupFile.Length),
                                     StaticHelpers.FormatFileSize(ftpFileSize));
                        }
                        else
                        {
                            log.Info("File: {0} ({1}) size matches file size on FTP site ({2}).", localBackupFile.Name, StaticHelpers.FormatFileSize(localBackupFile.Length),
                                     StaticHelpers.FormatFileSize(ftpFileSize));
                        }
                    }
                }

                if (shouldUpload)
                {
                    Stopwatch sw = Stopwatch.StartNew();
                    if (!ftpClient.UploadFile(localBackupFile))
                    {
                        throw new ApplicationException("Upload failed. " + ftpClient.LastStatusDescription);
                    }
                    sw.Stop();
                    double bytesSec = localBackupFile.Length / sw.Elapsed.TotalSeconds;
                    log.Info("Upload of:{0} ({1}) completed in:{2} ({3} / second)", localBackupFile.Name, StaticHelpers.FormatFileSize(localBackupFile.Length), sw.Elapsed,
                             StaticHelpers.FormatFileSize(bytesSec));
                }
            }
        }