Beispiel #1
0
        public void SetUp()
        {
            _tempDir = new DirectoryInfo(@"C:\Temp\Gu.Persist");
            _setting = new BackupSettings(true, _tempDir, ".bak", BackupSettings.DefaultTimeStampFormat, false, 1, Int32.MaxValue);
            _file    = _tempDir.CreateFileInfoInDirectory("Meh.cfg");
            _backup  = _tempDir.CreateFileInfoInDirectory("Meh.bak");

            _backup1 = _tempDir.CreateFileInfoInDirectory(string.Format("Meh{0}.bak", new DateTime(2015, 06, 13, 21, 38, 00).ToString(BackupSettings.DefaultTimeStampFormat, CultureInfo.InvariantCulture)));
            _backup2 = _tempDir.CreateFileInfoInDirectory(string.Format("Meh{0}.bak", new DateTime(2015, 06, 13, 21, 37, 00).ToString(BackupSettings.DefaultTimeStampFormat, CultureInfo.InvariantCulture)));
            _backup3 = _tempDir.CreateFileInfoInDirectory(string.Format("Meh{0}.bak", new DateTime(2015, 06, 12, 21, 38, 00).ToString(BackupSettings.DefaultTimeStampFormat, CultureInfo.InvariantCulture)));
            _backup4 = _tempDir.CreateFileInfoInDirectory(string.Format("Meh{0}.bak", new DateTime(2015, 06, 11, 21, 38, 00).ToString(BackupSettings.DefaultTimeStampFormat, CultureInfo.InvariantCulture)));
            _backup5 = _tempDir.CreateFileInfoInDirectory(string.Format("Meh{0}.bak", new DateTime(2015, 06, 10, 21, 38, 00).ToString(BackupSettings.DefaultTimeStampFormat, CultureInfo.InvariantCulture)));

            _otherBackup        = _tempDir.CreateFileInfoInDirectory(string.Format("Other{0}.bak", new DateTime(2015, 06, 13, 21, 38, 00).ToString(BackupSettings.DefaultTimeStampFormat, CultureInfo.InvariantCulture)));
            _softDelete         = _tempDir.CreateFileInfoInDirectory(string.Format("Meh{0}.bak.delete", new DateTime(2015, 06, 10, 21, 38, 00).ToString(BackupSettings.DefaultTimeStampFormat, CultureInfo.InvariantCulture)));
            _timestampedBackups = new FileInfo[]
            {
                _backup1,
                _backup2,
                _backup3,
                _backup4,
                _backup5
            };
            _file.Delete();
            _backup.Delete();
            foreach (var backup in _timestampedBackups)
            {
                backup.Delete();
            }

            _otherBackup.Delete();
            _otherBackup.VoidCreate();
            _softDelete.VoidCreate();
            _backuper = new Backuper(_setting);
        }
Beispiel #2
0
        public override string Query()
        {
            LogOptions.GetLogger().Info("Starting to run mysqldump of database");
            var settings   = BackupSettings.GetInstance();
            var executable = settings.Executable;
            var arguments  = $"-u {settings.User} -p{settings.Password} {settings.Database}";

            LogOptions.GetLogger().Info("Starting dump {executable} {arguments}", executable, arguments);
            try
            {
                var processStartInfo = new ProcessStartInfo
                {
                    FileName               = executable,
                    Arguments              = arguments,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                    CreateNoWindow         = true,
                    UseShellExecute        = false
                };
                var p = Process.Start(processStartInfo);
                var standardOutput = p?.StandardOutput.ReadToEnd();
                p?.WaitForExit();
                return(standardOutput);
            }
            catch (Exception e)
            {
                LogOptions.GetLogger().Fatal(e, "Exception in dump mysql database {message}", e.Message);
                return(string.Empty);
            }
        }
Beispiel #3
0
        public BackupTests()
        {
            Directory = new DirectoryInfo(@"C:\Temp\Gu.Settings\" + GetType().Name);
            Directory.CreateIfNotExists();

            Setting = new BackupSettings(Directory, true, BackupSettings.DefaultExtension, BackupSettings.DefaultTimeStampFormat, false, 2, 3);

            File       = Directory.CreateFileInfoInDirectory("Meh.cfg");
            SoftDelete = File.WithAppendedExtension(FileHelper.SoftDeleteExtension);
            Backup     = Directory.CreateFileInfoInDirectory("Meh.bak");

            BackupOneMinuteOld = Backup.WithTimeStamp(DateTime.Now.AddMinutes(-1), Setting);
            BackupOneHourOld   = Backup.WithTimeStamp(DateTime.Now.AddHours(-1), Setting);
            BackupOneDayOld    = Backup.WithTimeStamp(DateTime.Now.AddDays(-1), Setting);
            BackupOneMonthOld  = Backup.WithTimeStamp(DateTime.Now.AddMonths(-1), Setting);
            BackupOneYearOld   = Backup.WithTimeStamp(DateTime.Now.AddYears(-1), Setting);

            OtherBackup = Directory.CreateFileInfoInDirectory("Other.bak").WithTimeStamp(DateTime.Now.AddHours(1), Setting);

            TimestampedBackups = new[]
            {
                BackupOneMinuteOld,
                BackupOneHourOld,
                BackupOneDayOld,
                BackupOneMonthOld,
                BackupOneYearOld
            };
        }
Beispiel #4
0
        private static bool CopyFileForBackup(BackupSettings config, String sDst, String item, Logger log)
        {
            SafeNativeMethods.CopyFileFlags dwCopyFlags = 0;
            if (config.IgnoreEncryption)
            {
                dwCopyFlags = SafeNativeMethods.CopyFileFlags.COPY_FILE_ALLOW_DECRYPTED_DESTINATION;
            }

            bool pbCancel = false;

            SafeNativeMethods.CopyProgressRoutine cb = new SafeNativeMethods.CopyProgressRoutine(callback);

            StartTimeCopy = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

            //CopyFileEx
            //https://msdn.microsoft.com/en-us/library/windows/desktop/aa363852%28v=vs.85%29.aspx
            log("Starting copying...");
            bool bOK = SafeNativeMethods.CopyFileEx(item, sDst, cb, IntPtr.Zero, ref pbCancel, dwCopyFlags);

            if (!bOK)
            {
                log("Failed to copy file: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
            }
            return(bOK);
        }
Beispiel #5
0
        private /*async*/ void startAsyncWork()
        {
            Console.WriteLine("DoWork Starting");
            //await Task.Run(() =>
            Task t = Task.Factory.StartNew(() =>
            {
                int iError            = 0;
                BackupSettings config = BackupSettingsDao.loadSettings();

                BackupTool.setFileLabel(this.lblFilename);
                BackupTool.setProgressBar(this.pbCopyProgress);
                BackupTool.setTotalProgressBar(this.pbTotalProgress);
                BackupTool.setMegaByesPerSecondLabel(this.lblMegaBytesPerSecond);

                if (config != null && config.LastRun == null)
                {
                    startCountdown(config, LogToScreen);
                    iError = BackupTool.tryBackup(config, LogToScreen);
                }
                else if (config != null && config.LastRun.AddDays(config.Interval) <= DateTime.Now)
                {
                    startCountdown(config, LogToScreen);
                    iError = BackupTool.tryBackup(config, LogToScreen);
                }

                if (iError == 0)
                {
                    Application.Exit();
                }
                else
                {
                    BackupTool.CanExit = true;  //allow manual closing
                }
            });
        }
        /// <summary>
        /// Deletes any target files that are not listed in the source array.
        /// </summary>
        private void DeleteSourceFilesFromTarget(IEnumerable <string> sourceFiles, DirectoryInfo targetDirInfo)
        {
            // Get names only as lowercase for comparison
            string[] sourceFileNames = sourceFiles.Select(f => Path.GetFileName(f).ToLower()).ToArray();

            // Get full paths to target (maintain case, UNIX names can be case sensitive.)
            string[] targetFiles = Directory.EnumerateFiles(targetDirInfo.FullName, "*.*", SearchOption.TopDirectoryOnly).ToArray();

            // Need to check for files that exist in target but not in source
            foreach (string file in targetFiles)
            {
                // Compare names as lowercase
                string nameOnly = Path.GetFileName(file).ToLower();

                // Only name will match, full paths are from different locations
                bool remove = !sourceFileNames.Contains(nameOnly);

                // Remove if ext is now excluded
                remove |= BackupSettings.IsFileTypeExcluded(file);

                // Remove if hidden options changed
                remove |= BackupSettings.IgnoreHiddenFiles && (File.GetAttributes(file) & FileAttributes.Hidden) > 0;

                if (remove)
                {
                    // Delete using full path
                    DeleteFile(file);
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Saves the current settings from the form to disk
        /// </summary>
        /// <returns>true, if save action was successful</returns>
        private bool saveSettings()
        {
            //preserve hidden flags
            //BackupSettings config = BackupSettingsDao.loadSettings();
            if (config == null)
            {
                config = new BackupSettings();
            }
            config.DestinationPath  = txtDestination.Text;
            config.Interval         = (int)numInterval.Value;
            config.BackupProgram    = txtBackupExe.Text;
            config.BackupPrefix     = txtPrefix.Text;
            config.BackupSuffix     = txtSuffix.Text;
            config.PostBackupCmd    = txtPostBackupCmd.Text;
            config.BackupAll        = cbxBackupAll.Checked;
            config.CountdownSeconds = (int)numCountdown.Value;
            if (String.IsNullOrEmpty(txtLastBackup.Text))
            {
                config.LastRun = DateTime.MinValue;
            }

            config.Items.Clear();
            for (int i = 0; i < lvStores.Items.Count; i++)
            {
                if (lvStores.Items[i].Checked)
                {
                    config.Items.Add(lvStores.Items[i].Text);
                }
            }
            return(BackupSettingsDao.saveSettings(config));
        }
        public DatabaseBackupService(DatabaseRepository database, IConfiguration configuration)
        {
            this.database = database;

            settings = new BackupSettings();
            configuration.Bind("BackupSettings", settings);
        }
Beispiel #9
0
        public BackupTests()
        {
            this.Directory = new DirectoryInfo(@"C:\Temp\Gu.Persist\" + this.GetType().Name);
            this.Directory.CreateIfNotExists();

            this.File       = this.Directory.CreateFileInfoInDirectory("Meh.cfg");
            this.SoftDelete = this.File.WithAppendedExtension(FileHelper.SoftDeleteExtension);
            this.Backup     = this.Directory.CreateFileInfoInDirectory("Meh.bak");
            var settings = new BackupSettings(this.Directory.FullName, BackupSettings.DefaultExtension, BackupSettings.DefaultTimeStampFormat, 3, 3);

            this.BackupOneMinuteOld = this.Backup.WithTimeStamp(DateTime.Now.AddMinutes(-1), settings);
            this.BackupOneHourOld   = this.Backup.WithTimeStamp(DateTime.Now.AddHours(-1), settings);
            this.BackupOneDayOld    = this.Backup.WithTimeStamp(DateTime.Now.AddDays(-1), settings);
            this.BackupOneMonthOld  = this.Backup.WithTimeStamp(DateTime.Now.AddMonths(-1), settings);
            this.BackupOneYearOld   = this.Backup.WithTimeStamp(DateTime.Now.AddYears(-1), settings);

            this.OtherBackup = this.Directory.CreateFileInfoInDirectory("Other.bak").WithTimeStamp(DateTime.Now.AddHours(1), settings);

            this.TimestampedBackups = new[]
            {
                this.BackupOneMinuteOld,
                this.BackupOneHourOld,
                this.BackupOneDayOld,
                this.BackupOneMonthOld,
                this.BackupOneYearOld
            };
        }
Beispiel #10
0
        public void GetTimeStamp(string fileName)
        {
            var file      = new FileInfo(fileName);
            var setting   = new BackupSettings(true, file.Directory, ".bak", BackupSettings.DefaultTimeStampFormat, false, 1, Int32.MaxValue);
            var timeStamp = BackupFile.GetTimeStamp(file, setting);

            Assert.AreEqual(new DateTime(2015, 06, 13, 17, 05, 15), timeStamp);
        }
Beispiel #11
0
        public void CreateForNoTimestamp(string fileName, string expected)
        {
            var file    = new FileInfo(fileName);
            var setting = new BackupSettings(true, file.Directory, ".bak", null, false, 1, Int32.MaxValue);
            var backup  = BackupFile.CreateFor(file, setting);

            Assert.AreEqual(expected, backup.FullName);
        }
Beispiel #12
0
 /// <summary>
 /// Creates a backuper for the given settings.
 /// </summary>
 /// <remarks>
 /// If <paramref name="setting"/> is null a <see cref="NullBackuper"/> is returned.
 /// </remarks>
 /// <param name="setting">The setting to use for backups.</param>
 /// <returns></returns>
 public static IBackuper Create(BackupSettings setting)
 {
     if (setting != null)
     {
         return(new Backuper(setting));
     }
     return(NullBackuper.Default);
 }
        private static JsonRepository CreateJsonRepository()
        {
            var jsonSerializerSettings = JsonRepositorySettings.DefaultJsonSettings;
            var backupSettings         = new BackupSettings(Directories.DefaultBackup, 10, 2);
            var jsonRepositorySettings = new JsonRepositorySettings(jsonSerializerSettings, true, true, backupSettings);

            return(new JsonRepository(jsonRepositorySettings));
        }
 public async Task <IActionResult> BackupSave(BackupSettings settings)
 {
     if (ModelState.IsValid)
     {
         await _settingsService.UpdateBackupSettings(settings);
     }
     return(RedirectToAction("Backup", "Home"));
 }
Beispiel #15
0
        public void CreateFor(string expected)
        {
            this.File.CreatePlaceHolder();
            var backupSettings = new BackupSettings(this.Directory.FullName, BackupSettings.DefaultExtension, BackupSettings.DefaultTimeStampFormat, 1, 1);
            var backup         = BackupFile.CreateFor(this.File, backupSettings);

            StringAssert.IsMatch(expected, backup.FullName);
        }
Beispiel #16
0
        public void CreateForNoTimestamp(string expected)
        {
            this.File.CreatePlaceHolder();
            var setting = new BackupSettings(this.File.DirectoryName, BackupSettings.DefaultExtension, null, 1, int.MaxValue);
            var backup  = BackupFile.CreateFor(this.File, setting);

            Assert.AreEqual(expected, backup.FullName);
        }
        public void CreateForNoTimestamp(string expected)
        {
            File.VoidCreate();
            var setting = new BackupSettings(File.Directory, true, BackupSettings.DefaultExtension, null, false, 1, Int32.MaxValue);
            var backup  = BackupFile.CreateFor(File, setting);

            Assert.AreEqual(expected, backup.FullName);
        }
Beispiel #18
0
        public void GetTimeStamp(string fileName)
        {
            var file      = new FileInfo(fileName);
            var setting   = new BackupSettings(this.Directory.FullName, BackupSettings.DefaultExtension, BackupSettings.DefaultTimeStampFormat, 1, int.MaxValue);
            var timeStamp = file.GetTimeStamp(setting);

            Assert.AreEqual(new DateTime(2015, 06, 13, 17, 05, 15), timeStamp);
        }
Beispiel #19
0
 protected override void OnExecuting()
 {
     foreach (var extraPath in BackupSettings.GetInstance().CopyBackupsTo)
     {
         var destinationPath = Path.Combine(extraPath, _subPath);
         CopyFile(destinationPath);
     }
 }
Beispiel #20
0
 /// <summary> Initializes a new instance of the <see cref="RepositorySettings"/> class. </summary>
 public RepositorySettings(
     string directory,
     bool isTrackingDirty,
     BackupSettings backupSettings,
     string extension     = ".cfg",
     string tempExtension = ".tmp")
     : base(directory, isTrackingDirty, backupSettings, extension, tempExtension)
 {
 }
Beispiel #21
0
        public void RoundtripBackupSettingsWithNullTimestampFormat()
        {
            var backupSettings = new BackupSettings(BackupDir.FullName, ".abc", null, 2, 3);
            var json           = JsonConvert.SerializeObject(backupSettings);
            var roundtripped   = JsonConvert.DeserializeObject <BackupSettings>(json);

            AssertProperties(backupSettings, roundtripped);
            Assert.IsTrue(JsonEqualsComparer <BackupSettings> .Default.Equals(backupSettings, roundtripped));
        }
Beispiel #22
0
        public static void CreateForNoTimestamp()
        {
            var file = CreateFile();

            file.CreateFileOnDisk();
            var setting = new BackupSettings(file.DirectoryName, BackupSettings.DefaultExtension, null, 1, int.MaxValue);
            var backup  = BackupFile.CreateFor(file, setting);

            StringAssert.IsMatch(@"BackupFileTests\\CreateForNoTimestamp\.bak", backup.FullName);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DataRepositorySettings"/> class.
 /// </summary>
 public DataRepositorySettings(
     string directory,
     bool isTrackingDirty,
     bool saveNullDeletesFile,
     BackupSettings backupSettings,
     string extension     = ".cfg",
     string tempExtension = ".tmp")
     : base(directory, isTrackingDirty, saveNullDeletesFile, backupSettings, extension, tempExtension)
 {
 }
        public void RoundtripRepositorySettingsWithRepo()
        {
            var backupSettings = new BackupSettings(new DirectoryInfo(@"C:\Temp\Gu.Settings\" + GetType().Name + @"\Backup"));
            var directory      = new DirectoryInfo(@"C:\Temp\Gu.Settings\" + GetType().Name);
            var settings       = new XmlRepositorySettings(directory, true, true, backupSettings, ".cfg", ".tmp");
            var repository     = new XmlRepository(settings);

            repository.Save(settings);
            var repositorySettings = repository.Read <XmlRepositorySettings>();
        }
Beispiel #25
0
        public static void CreateFor()
        {
            var file = CreateFile();

            file.CreateFileOnDisk();
            var backupSettings = new BackupSettings(Directory.FullName, BackupSettings.DefaultExtension, BackupSettings.DefaultTimeStampFormat, 1, 1);
            var backup         = BackupFile.CreateFor(file, backupSettings);

            StringAssert.IsMatch(@"BackupFileTests\\CreateFor\.\d\d\d\d_\d\d_\d\d_\d\d_\d\d_\d\d\.bak", backup.FullName);
        }
        // zapisanie do pliku przesłanej konfiguracji
        public void SaveConfiguration(BackupConfigurationData backupConf, CallBackDel callBack)
        {
            BackupSettings settings;

            // jeżeli plik nie istnieje to jest tworzony i zapisywane są do niego dane
            if (!fileHasAnyData())
            {
                try
                {
                    using (var fs = new FileStream(xmlFilePath, FileMode.Open))
                    {
                        settings      = new BackupSettings();
                        backupConf.Id = randomIntGuid();
                        settings.ConfigurationList.Add(backupConf);
                        xs.Serialize(fs, settings);
                    }

                    callBack(new CallBackModel {
                        Success = true, Message = "Konfiguracja została zapisana !"
                    });
                }
                catch (Exception ex)
                {
                    LogInfo.LogErrorWrite("Nie udało się zapisać konfiguracji backup'u do pustego pliku", ex);
                    callBack(new CallBackModel {
                        Success = false
                    });
                }
            }
            else // jeżeli plik istnieje to dane są 'dokładane' na koniec
            {
                try
                {
                    using (var fs = new FileStream(xmlFilePath, FileMode.Open))
                    {
                        settings = (BackupSettings)xs.Deserialize(fs);
                        fs.SetLength(0);
                        backupConf.Id = randomIntGuid();
                        settings.ConfigurationList.Add(backupConf);
                        xs.Serialize(fs, settings);
                    }

                    callBack(new CallBackModel {
                        Success = true, Message = "Konfiguracja została zapisana !"
                    });
                }
                catch (Exception ex)
                {
                    LogInfo.LogErrorWrite("Nie udało się zapisać konfiguracji backup'u do pliku", ex);
                    callBack(new CallBackModel {
                        Success = false
                    });
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Waits, till outlook ends and then starts the backup process
        /// </summary>
        /// <param name="config">Stored configuration from outlook plugin</param>
        /// <param name="log">logging delegate to send error information</param>
        /// <returns>number of occurred errors</returns>
        public static int tryBackup(BackupSettings config, Logger log)
        {
            int iError = 0;

            if (config == null)
            {
                log("backup not configured");
                return(0);
            }

            log("Starting backup...please wait...");

            try
            {
                if (config.Items.Count > 0)
                {
                    log("Check whether outlooks is still running ...");
                    if (WaitForProcessEnd(OUTLOOK_PROC, log))
                    {
                        log("No outlook process found");
                        iError += doBackup(config, log);
                        if (!String.IsNullOrEmpty(config.PostBackupCmd))
                        {
                            int iRes = RunPostCmd(config.PostBackupCmd, config.ProfileName, log);
                            iError += iRes;
                        }
                    }
                    else
                    {
                        iError++;
                        log("Error waiting for " + OUTLOOK_PROC);
                    }
                }
                else
                {
                    iError++;
                    log("Error: no files for backup selected");
                }

                //if no errors occurred, save current timestamp
                if (iError == 0)
                {
                    config.LastRun = DateTime.Now;
                    BackupSettingsDao.saveSettings(config);
                }
            }
            catch (InstanceAlreadyRunningException)
            {
                log("Backup already running...");
                iError++;
            }

            return(iError);
        }
        public BackupForm()
        {
            InitializeComponent();

            // Load current settings
            this.settings = new BackupSettings();
            settings.LoadSettings();

            // Populate storage accounts
            UpdateStorageAccounts();
        }
Beispiel #29
0
        static int Main(string[] args)
        {
            int RetCode = 0;

            Dictionary <String, String> argsDict = new Dictionary <String, String>();

            if (!parseArgs(args, argsDict))
            {
                showHelp(args);
                return(0);
            }

            if (argsDict.ContainsKey("/register"))
            {
                RetCode = registerPlugin(true) ? 0 : 1;
            }
            else if (argsDict.ContainsKey("/registersetup"))
            {
                RetCode = registerPlugin(false) ? 0 : 1;
            }
            else if (argsDict.ContainsKey("/unregister"))
            {
                RetCode = unregisterPlugin() ? 0 : 1;
            }
            else if (argsDict.ContainsKey("/backupnow"))
            {
                int iError = 0;
                SafeNativeMethods.AttachConsole(SafeNativeMethods.ATTACH_PARENT_PROCESS);
                try
                {
                    LogToConsole("Reading settings ...");
                    BackupSettings config = BackupSettingsDao.loadSettings();
                    LogToConsole("Reading settings finished");
                    iError = BackupTool.tryBackup(config, LogToConsole);
                }
                catch (Exception e)
                {
                    LogToConsole(e.Message);
                    LogToConsole(e.StackTrace);
                }

                SendKeys.SendWait("{ENTER}");
                SafeNativeMethods.FreeConsole();
                RetCode = iError;
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmMain());
            }

            return(RetCode);
        }
Beispiel #30
0
 public void SetUp()
 {
     this.setting = new BackupSettings(
         this.directoryInfo.FullName,
         BackupSettings.DefaultExtension,
         BackupSettings.DefaultTimeStampFormat,
         3,
         3);
     this.file       = this.directoryInfo.CreateFileInfoInDirectory("Meh.cfg");
     this.backupFile = this.file.WithNewExtension(this.setting.Extension);
 }
		public SqlDatabasesBackup(BackupSettings settings, DatabaseBackupLogger logger, string[] databaseNames)
		{
			this.settings = settings;
			this.logger = logger;
			this.databaseNames = databaseNames;
		}
Beispiel #32
0
		protected override void ApplySettings(HydraTaskSettings settings)
		{
			_settings = new BackupSettings(settings);

			if (settings.IsDefault)
			{
				_settings.Offset = 1;
				_settings.StartFrom = new DateTime(1900, 1, 1);
				_settings.Interval = TimeSpan.FromDays(1);
				_settings.Service = BackupServices.AwsS3;
				_settings.Address = RegionEndpoint.USEast1.SystemName;
				_settings.ServiceRepo = "stocksharp";
				_settings.Login = string.Empty;
				_settings.Password = new SecureString();
			}
		}