示例#1
0
        public bool Sync()
        {
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    RoboCommand backup = new RoboCommand();
                    // events
                    backup.OnFileProcessed    += backup_OnFileProcessed;
                    backup.OnCommandCompleted += backup_OnCommandCompleted;
                    // copy options
                    backup.CopyOptions.Source             = ServiceSetting.GetSettingValue(SettingStrings.StoragePath);
                    backup.CopyOptions.Destination        = ConfigurationManager.AppSettings["LocalStoragePath"].Trim('\\');
                    backup.CopyOptions.CopySubdirectories = true;
                    backup.CopyOptions.UseUnbufferedIo    = true;
                    // select options
                    //backup.SelectionOptions.OnlyCopyArchiveFilesAndResetArchiveFlag = true;
                    backup.CopyOptions.Mirror            = true;
                    backup.CopyOptions.Purge             = false;
                    backup.SelectionOptions.ExcludeOlder = true;
                    backup.LoggingOptions.VerboseOutput  = true;
                    // retry options
                    backup.RetryOptions.RetryCount    = 1;
                    backup.RetryOptions.RetryWaitTime = 2;
                    backup.Start();
                    return(true);
                }
                return(false);
            }
        }
示例#2
0
        public bool Sync()
        {
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }

            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                return(false);
            }


            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    foreach (var folder in new [] { "client_versions", "software_uploads" })
                    {
                        RoboCommand backup = new RoboCommand();
                        // events
                        backup.OnError += Backup_OnError;

                        // copy options
                        backup.CopyOptions.Source             = ServiceSetting.GetSettingValue(SettingStrings.StoragePath) + folder;
                        backup.CopyOptions.Destination        = thisComServer.LocalStoragePath + folder.Trim('\\');
                        backup.CopyOptions.CopySubdirectories = true;
                        backup.CopyOptions.UseUnbufferedIo    = true;
                        if (thisComServer.ReplicationRateIpg != 0)
                        {
                            backup.CopyOptions.InterPacketGap = thisComServer.ReplicationRateIpg;
                        }
                        else
                        {
                            backup.CopyOptions.InterPacketGap = 0;
                        }
                        // select options
                        backup.CopyOptions.Mirror = true;
                        backup.CopyOptions.Purge  = true;

                        backup.LoggingOptions.VerboseOutput = false;
                        // retry options
                        backup.RetryOptions.RetryCount    = 3;
                        backup.RetryOptions.RetryWaitTime = 10;
                        backup.Start().Wait();
                    }
                    return(true);
                }
                return(false);
            }
        }
示例#3
0
        /// <summary>
        /// The main method that performs the copy
        /// </summary>
        /// <returns></returns>
        public Task Copy()
        {
            if (!DirExists(CopyParameters.TestDataRepoRootDir))
            {
                throw new Exception("Test data repository root directory not found, " + CopyParameters.TestDataRepoRootDir);
            }

            // Append project name to destination folder
            string destinationDir = Path.Combine(CopyParameters.DestinationRootDir, CopyParameters.Project);

            if (!DirExists(destinationDir))
            {
                throw new Exception("Destination root directory not found, " + destinationDir);
            }

            // Append test data name to test data repository root
            string sourceDir = Path.Combine(CopyParameters.TestDataRepoRootDir, CopyParameters.Name);

            if (!DirExists(sourceDir))
            {
                throw new Exception("Test data directory to copy not found, " + sourceDir);
            }

            destinationDir = Path.Combine(destinationDir, CopyParameters.Name);   // Add the test data name to destination

            LogHelper.Log(LogLevel.INFO, "Source folder = " + sourceDir);
            LogHelper.Log(LogLevel.INFO, "Destination folder = " + destinationDir);

            RoboCopy = new RoboCommand();

            // events
            RoboCopy.OnFileProcessed       += rbc_OnFileProcessed;
            RoboCopy.OnCopyProgressChanged += rbc_OnCopyProgressChanged;
            RoboCopy.OnCommandCompleted    += rbc_OnCommandCompleted;
            // copy options

            RoboCopy.CopyOptions.MultiThreadedCopiesCount = 16;
            RoboCopy.CopyOptions.Source             = sourceDir;
            RoboCopy.CopyOptions.Destination        = destinationDir;
            RoboCopy.CopyOptions.CopySubdirectories = true;
            RoboCopy.CopyOptions.UseUnbufferedIo    = true;
            RoboCopy.CopyOptions.Mirror             = true;
            RoboCopy.CopyOptions.EnableRestartMode  = true;
            RoboCopy.CopyOptions.UseUnbufferedIo    = true;
            RoboCopy.CopyOptions.InterPacketGap     = 0;
            // retry options
            RoboCopy.RetryOptions.RetryCount    = 1;
            RoboCopy.RetryOptions.RetryWaitTime = 2;
            var cpTask = RoboCopy.Start();

            return(cpTask);
        }
示例#4
0
        public void CopyApplicationSite(string source, string destination)
        {
            RoboCommand roboCommand = new RoboCommand();

            //roboCommand.OnFileProcessed += OnFileProcessed;
            roboCommand.OnCommandCompleted            += OnCommandCompleted;
            roboCommand.CopyOptions.Source             = source;
            roboCommand.CopyOptions.Destination        = destination;
            roboCommand.CopyOptions.Mirror             = true;
            roboCommand.CopyOptions.CopySubdirectories = true;
            roboCommand.LoggingOptions.NoFileSizes     = true;
            roboCommand.LoggingOptions.NoFileList      = true;
            roboCommand.LoggingOptions.NoDirectoryList = true;
            roboCommand.LoggingOptions.NoProgress      = true;

            var cmd = roboCommand.Start();

            cmd.Wait();

            ConfigureApplicationSite();
        }
示例#5
0
        private void CopyForm_Load(object sender, EventArgs e)
        {
            _RoboCommand = new RoboCommand();

            // event handlers
            _RoboCommand.OnCommandError        += _RoboCommand_OnCommandError;
            _RoboCommand.OnError               += _RoboCommand_OnError;
            _RoboCommand.OnCopyProgressChanged += _RoboCommand_OnCopyProgressChanged;
            _RoboCommand.OnFileProcessed       += _RoboCommand_OnFileProcessed;
            _RoboCommand.OnCommandCompleted    += _RoboCommand_OnCommandCompleted;

            // _RoboCommand options
            _RoboCommand.CopyOptions.Source = ProfileManager.CurrentProfile.Source;
            //
            _RoboCommand.CopyOptions.Destination = ProfileManager.CurrentProfile.Destination;
            //
            _RoboCommand.CopyOptions.FileFilter = ProfileManager.CurrentProfile.FileFilter;
            //
            if (ProfileManager.CurrentProfile.Mirror)
            {
                _RoboCommand.CopyOptions.Mirror = true;
            }
            else
            {
                if (ProfileManager.CurrentProfile.CopySubdirectoriesIncludingEmpty)
                {
                    _RoboCommand.CopyOptions.CopySubdirectoriesIncludingEmpty = true;
                }
                else
                {
                    _RoboCommand.CopyOptions.CopySubdirectories = ProfileManager.CurrentProfile.CopySubdirectories;
                }
                //
                _RoboCommand.CopyOptions.Purge = ProfileManager.CurrentProfile.Purge;
            }
            //
            if (ProfileManager.CurrentProfile.EnableRestartMode && ProfileManager.CurrentProfile.EnableBackupMode)
            {
                _RoboCommand.CopyOptions.EnableRestartModeWithBackupFallback = true;
            }
            else
            {
                _RoboCommand.CopyOptions.EnableRestartMode = ProfileManager.CurrentProfile.EnableRestartMode;
                _RoboCommand.CopyOptions.EnableBackupMode  = ProfileManager.CurrentProfile.EnableBackupMode;
            }
            //
            _RoboCommand.CopyOptions.UseUnbufferedIo = ProfileManager.CurrentProfile.UseUnbufferedIo;
            //
            if (ProfileManager.CurrentProfile.EnableEfsRawMode || ProfileManager.CurrentProfile.InterPacketGap > 0)
            {
                _RoboCommand.CopyOptions.EnableEfsRawMode = ProfileManager.CurrentProfile.EnableEfsRawMode;
                _RoboCommand.CopyOptions.InterPacketGap   = ProfileManager.CurrentProfile.InterPacketGap;
            }
            else
            {
                _RoboCommand.CopyOptions.MultiThreadedCopiesCount = ProfileManager.CurrentProfile.MultiThreadedCopiesCount;
            }
            //
            _RoboCommand.CopyOptions.Depth = ProfileManager.CurrentProfile.Depth;
            //
            _RoboCommand.CopyOptions.FatFiles = ProfileManager.CurrentProfile.FatFiles;
            //
            _RoboCommand.CopyOptions.TurnLongPathSupportOff = ProfileManager.CurrentProfile.TurnLongPathSupportOff;
            //
            _RoboCommand.CopyOptions.CopySymbolicLink = ProfileManager.CurrentProfile.CopySymobolicLink;
            //
            _RoboCommand.CopyOptions.DoNotUseWindowsCopyOffload = ProfileManager.CurrentProfile.DoNotUseWindowsCopyOffload;
            //
            _RoboCommand.CopyOptions.CheckPerFile = ProfileManager.CurrentProfile.CheckPerFile;
            //
            _RoboCommand.CopyOptions.CopyFlags = ProfileManager.CurrentProfile.FileCopyFlags.ToString();
            //
            _RoboCommand.CopyOptions.DirectoryCopyFlags = ProfileManager.CurrentProfile.DirectoryCopyFlags.ToString();
            //
            _RoboCommand.CopyOptions.AddAttributes = ProfileManager.CurrentProfile.AddAttributes.ToString();
            //
            _RoboCommand.CopyOptions.RemoveAttributes = ProfileManager.CurrentProfile.RemoveAttributes.ToString();
            //

            /*_RoboCommand.CopyOptions.MoveFiles = ProfileManager.Current.MoveFiles;
             * //
             * _RoboCommand.CopyOptions.MoveFilesAndDirectories = ProfileManager.Current.MoveFilesAndDirectories;
             * //
             * _RoboCommand.CopyOptions.CreateDirectoryAndFileTree = ProfileManager.Current.CreateDirectoryAndFileTree;*/
            //
            _RoboCommand.RetryOptions.RetryCount = ProfileManager.CurrentProfile.RetryCount;
            //
            _RoboCommand.RetryOptions.RetryWaitTime = ProfileManager.CurrentProfile.RetryWaitTime;

            _Stopwatch = new Stopwatch();
            _Stopwatch.Start();

            _RoboCommand.Start();

            PauseResumeButton.Enabled = true;
        }
示例#6
0
        /// <summary>
        /// Start transferring data from a given source directory to the destination
        /// location that is derived from TxTargetUser. Requires CopyState to be in
        /// status "Stopped", sets CopyState to "Active" and FilecopyFinished to
        /// false. The currently processed path is stored in the global status
        /// variable CurrentTransferSrc.
        /// </summary>
        /// <param name="sourcePath">The full path to a folder. By convention, the
        /// LAST element of the path has to match the target user name!</param>
        private void StartTransfer(string sourcePath)
        {
            // only proceed when in a valid state:
            if (_transferState != TxState.Stopped)
            {
                return;
            }

            var totalSize = FsUtils.GetDirectorySize(sourcePath);

            if (totalSize == 0)
            {
                Log.Warn("Total size of all files in [{0}] is zero, NOT STARTING a transfer!",
                         sourcePath);
                // we also have to move it out of the way, otherwise it will block all transfers:
                var sourceDir       = new DirectoryInfo(sourcePath);
                var errorTargetPath = Path.Combine(_config.ErrorPath, TimeUtils.Timestamp());
                sourceDir.MoveTo(errorTargetPath);
                Log.Warn("Moved empty directory tree [{0}] to [{1}].", sourcePath, errorTargetPath);
                return;
            }
            Log.Debug("Size of all files under [{0}] is {1} bytes ({2})",
                      sourcePath, totalSize, Conv.BytesToString(totalSize));
            _status.CurrentTransferSize = totalSize;
            _status.CurrentTransferSrc  = sourcePath;

            // the user name is expected to be the last part of sourcePath:
            _status.TxTargetUser = new DirectoryInfo(sourcePath).Name;
            FsUtils.CreateNewDirectory(_status.TxTargetTmp, false);

            _transferState             = TxState.Active;
            _status.TransferInProgress = true;

            _roboCommand = new RoboCommand();
            try {
                // events
                _roboCommand.OnCopyProgressChanged += RsProgressChanged;
                _roboCommand.OnFileProcessed       += RsFileProcessed;
                _roboCommand.OnCommandCompleted    += RsCommandCompleted;

                // copy options
                _roboCommand.CopyOptions.Source      = sourcePath;
                _roboCommand.CopyOptions.Destination = _status.TxTargetTmp;

                // limit the transfer bandwidth by waiting between packets:
                _roboCommand.CopyOptions.InterPacketGap = _config.InterPacketGap;

                // /S :: copy Subdirectories, but not empty ones
                // _roboCommand.CopyOptions.CopySubdirectories = true;

                // /E :: copy subdirectories, including Empty ones
                _roboCommand.CopyOptions.CopySubdirectoriesIncludingEmpty = true;

                // /PF :: check run hours on a Per File (not per pass) basis
                // _roboCommand.CopyOptions.CheckPerFile = true;

                // /SECFIX ::  fix file security on all files, even skipped files
                // _roboCommand.CopyOptions.FixFileSecurityOnAllFiles = true;

                // copyflags :
                //     D=Data, A=Attributes, T=Timestamps
                //     S=Security=NTFS ACLs, O=Owner info, U=aUditing info
                _roboCommand.CopyOptions.CopyFlags = _config.CopyFlags;

                // /DCOPY :: directory copy settings (T=Timestamps)
                _roboCommand.CopyOptions.DirectoryCopyFlags = _config.DirectoryCopyFlags;

                // select options
                _roboCommand.SelectionOptions.ExcludeOlder = true;
                // retry options
                _roboCommand.RetryOptions.RetryCount    = 0;
                _roboCommand.RetryOptions.RetryWaitTime = 0;

                // robocopy logging (NOTE: the "OutputToRoboSharpAndLog" option is required as
                // otherwise messages will go to the log only and can't be processed by RoboSharp
                // any more, resulting in no callbacks and therefore no progress reports etc.)
                if (!string.IsNullOrWhiteSpace(_config.RoboCopyLog))
                {
                    Log.Debug("Setting RoboCopy log file to [{0}]", _config.RoboCopyLog);
                    _roboCommand.LoggingOptions = new LoggingOptions {
                        LogPath = _config.RoboCopyLog,
                        OutputToRoboSharpAndLog = true,
                        VerboseOutput           = true
                    };
                }
                _roboCommand.Start();

                Log.Info("Transfer started, total size: {0}",
                         Conv.BytesToString(_status.CurrentTransferSize));
                Log.Trace("RoboCopy command options: {0}", _roboCommand.CommandOptions);
            }
            catch (ManagementException ex) {
                Log.Error("Error in StartTransfer(): {0}", ex.Message);
            }
        }
示例#7
0
        public void Backup()
        {
            copy = new RoboCommand();
            copy.OnFileProcessed       += copy_OnFileProcessed;
            copy.OnCommandError        += copy_OnCommandError;
            copy.OnError               += copy_OnError;
            copy.OnCopyProgressChanged += copy_OnCopyProgressChanged;
            copy.OnCommandCompleted    += copy_OnCommandCompleted;
            // copy options
            copy.CopyOptions.Source             = Source.Text;
            copy.CopyOptions.Destination        = Destination.Text;
            copy.CopyOptions.FileFilter         = FileFilter.Text;
            copy.CopyOptions.CopySubdirectories = CopySubDirectories.IsChecked ?? false;
            copy.CopyOptions.CopySubdirectoriesIncludingEmpty = CopySubdirectoriesIncludingEmpty.IsChecked ?? false;
            if (!string.IsNullOrWhiteSpace(Depth.Text))
            {
                copy.CopyOptions.Depth = Convert.ToInt32(Depth.Text);
            }
            copy.CopyOptions.EnableRestartMode = EnableRestartMode.IsChecked ?? false;
            copy.CopyOptions.EnableBackupMode  = EnableBackupMode.IsChecked ?? false;
            copy.CopyOptions.EnableRestartModeWithBackupFallback = EnableRestartModeWithBackupFallback.IsChecked ?? false;
            copy.CopyOptions.UseUnbufferedIo       = UseUnbufferedIo.IsChecked ?? false;
            copy.CopyOptions.EnableEfsRawMode      = EnableEfsRawMode.IsChecked ?? false;
            copy.CopyOptions.CopyFlags             = CopyFlags.Text;
            copy.CopyOptions.CopyFilesWithSecurity = CopyFilesWithSecurity.IsChecked ?? false;
            copy.CopyOptions.CopyAll = CopyAll.IsChecked ?? false;
            copy.CopyOptions.RemoveFileInformation     = RemoveFileInformation.IsChecked ?? false;
            copy.CopyOptions.FixFileSecurityOnAllFiles = FixFileSecurityOnAllFiles.IsChecked ?? false;
            copy.CopyOptions.FixFileTimesOnAllFiles    = FixFileTimesOnAllFiles.IsChecked ?? false;
            copy.CopyOptions.Purge     = Purge.IsChecked ?? false;
            copy.CopyOptions.Mirror    = Mirror.IsChecked ?? false;
            copy.CopyOptions.MoveFiles = MoveFiles.IsChecked ?? false;
            copy.CopyOptions.MoveFilesAndDirectories    = MoveFilesAndDirectories.IsChecked ?? false;
            copy.CopyOptions.AddAttributes              = AddAttributes.Text;
            copy.CopyOptions.RemoveAttributes           = RemoveAttributes.Text;
            copy.CopyOptions.CreateDirectoryAndFileTree = CreateDirectoryAndFileTree.IsChecked ?? false;
            copy.CopyOptions.FatFiles = FatFiles.IsChecked ?? false;
            copy.CopyOptions.TurnLongPathSupportOff = TurnLongPathSupportOff.IsChecked ?? false;
            if (!string.IsNullOrWhiteSpace(MonitorSourceChangesLimit.Text))
            {
                copy.CopyOptions.MonitorSourceChangesLimit = Convert.ToInt32(MonitorSourceChangesLimit.Text);
            }
            if (!string.IsNullOrWhiteSpace(MonitorSourceTimeLimit.Text))
            {
                copy.CopyOptions.MonitorSourceTimeLimit = Convert.ToInt32(MonitorSourceTimeLimit.Text);
            }

            // select options
            copy.SelectionOptions.OnlyCopyArchiveFiles = OnlyCopyArchiveFiles.IsChecked ?? false;
            copy.SelectionOptions.OnlyCopyArchiveFilesAndResetArchiveFlag = OnlyCopyArchiveFilesAndResetArchiveFlag.IsChecked ?? false;
            copy.SelectionOptions.IncludeAttributes     = IncludeAttributes.Text;
            copy.SelectionOptions.ExcludeAttributes     = ExcludeAttributes.Text;
            copy.SelectionOptions.ExcludeFiles          = ExcludeFiles.Text;
            copy.SelectionOptions.ExcludeDirectories    = ExcludeDirectories.Text;
            copy.SelectionOptions.ExcludeOlder          = ExcludeOlder.IsChecked ?? false;
            copy.SelectionOptions.ExcludeJunctionPoints = ExcludeJunctionPoints.IsChecked ?? false;

            // retry options
            if (!string.IsNullOrWhiteSpace(RetryCount.Text))
            {
                copy.RetryOptions.RetryCount = Convert.ToInt32(RetryCount.Text);
            }
            if (!string.IsNullOrWhiteSpace(RetryWaitTime.Text))
            {
                copy.RetryOptions.RetryWaitTime = Convert.ToInt32(RetryWaitTime.Text);
            }

            // logging options
            copy.LoggingOptions.VerboseOutput = VerboseOutput.IsChecked ?? false;
            copy.LoggingOptions.NoFileSizes   = NoFileSizes.IsChecked ?? false;
            copy.LoggingOptions.NoProgress    = NoProgress.IsChecked ?? false;

            copy.Start();
        }
示例#8
0
        private void PerformBackup(object sender, EventArgs eventArgs)
        {
            taskbarIcon.TrayBalloonTipClicked -= PerformBackup;
            if (MessageBox.Show("Soll das Backup jetzt wirklich gestartet werden?", "Backup starten?", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                BaloonTipDisplayed = false;
                return;
            }

            string backupRoot      = string.Empty;
            string exclusionString = string.Empty;

            CopyExecuting = true;

            foreach (string exclude in ApplicationConfiguration.Exclusions)
            {
                exclusionString = exclusionString + exclude + " ";
            }

            DriveInfo[] drives = System.IO.DriveInfo.GetDrives();

            foreach (DriveInfo drive in drives)
            {
                if (!drive.IsReady)
                {
                    continue;
                }

                if (Directory.Exists(System.IO.Path.Combine(drive.RootDirectory.FullName, "USBBackup", ApplicationConfiguration.UniqueIdentifyer)))
                {
                    backupRoot = System.IO.Path.Combine(drive.RootDirectory.FullName, "USBBackup", ApplicationConfiguration.UniqueIdentifyer);
                    break;
                }
            }

            if (backupRoot == string.Empty)
            {
                taskbarIcon.ShowBalloonTip("Fehler beim Durchführen des Backups", "Das Laufwerk war nicht bereit zum Schreiben.\r\nBitte versuchen Sie es erneut.", BalloonIcon.Error);

                return;
            }

            string rootBackupRoot = backupRoot;

            RunningCopyOperations = 0;

            foreach (string backupSourceRoot in ApplicationConfiguration.BackupFolders)
            {
                if (!Directory.Exists(backupSourceRoot))
                {
                    continue;
                }

                DirectoryInfo info = new DirectoryInfo(backupSourceRoot);
                backupRoot = CreateParentDirectory(rootBackupRoot, info);

                RoboCommand robo = new RoboCommand();
                robo.CopyOptions.Source      = backupSourceRoot;
                robo.CopyOptions.Destination = backupRoot;
                robo.CopyOptions.CopySubdirectoriesIncludingEmpty = true;
                robo.RetryOptions.RetryCount             = 10;
                robo.RetryOptions.RetryWaitTime          = 5;
                robo.SelectionOptions.ExcludeDirectories = exclusionString;
                robo.OnCommandCompleted += Robo_OnCopyCompleted;
                robo.OnCommandError     += Robo_OnCopyError;
                robo.OnFileProcessed    += delegate(object o, RoboSharp.FileProcessedEventArgs e) { };
                robo.Start();
                taskbarIcon.ToolTipText = "USB-Backup - Backup läuft...";
                RunningCopyOperations++;
            }
        }
示例#9
0
        public async Task Execute(IJobExecutionContext context)
        {
            Debug.WriteLine(string.Format("'{0}' tick: {1}", context.JobDetail.Key.Name.ToString().Substring(0, 5), DateTime.Now));

            // Notify the UI that the job is now running.
            BackupInfoViewModel.SetBackupItemStatus(context.JobDetail.Key.Name.ToString(), (int)StatusCodes.RUNNING);

            JobDataMap dataMap = context.JobDetail.JobDataMap;

            string originPath = dataMap.GetString("originPath");
            string backupPath = dataMap.GetString("backupPath");

            if (originPath.EndsWith(@"\"))
            {
                // Copy directory
                try
                {
                    Debug.WriteLine(string.Format("{0} Copying directory: '{1}' to '{2}'", DateTime.Now, originPath, backupPath));

                    RoboCommand roboCopy = new RoboCommand();

                    // Copy options
                    roboCopy.CopyOptions.Source             = originPath;
                    roboCopy.CopyOptions.Destination        = Path.Combine(backupPath, Path.GetFileName(Path.GetDirectoryName(originPath)));
                    roboCopy.CopyOptions.CopySubdirectories = true;
                    roboCopy.CopyOptions.UseUnbufferedIo    = true;
                    roboCopy.CopyOptions.Mirror             = true;

                    // Selection options
                    roboCopy.SelectionOptions.IncludeSame    = false;
                    roboCopy.SelectionOptions.IncludeTweaked = true;
                    roboCopy.SelectionOptions.ExcludeOlder   = true;

                    // Retry options
                    roboCopy.RetryOptions.RetryCount    = 3;
                    roboCopy.RetryOptions.RetryWaitTime = 5;

                    // Start and wait for the robocopy to finish.
                    await roboCopy.Start();
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in BackupJob.Execute() folder " + e.Message);

                    // Notify the UI that the job has errored.
                    BackupInfoViewModel.SetBackupItemStatus(context.JobDetail.Key.Name.ToString(), (int)StatusCodes.ERROR);
                }
            }
            else
            {
                // Copy file
                try
                {
                    Debug.WriteLine(string.Format("{0} Copying file: '{1}' to '{2}'", DateTime.Now, originPath, backupPath));

                    RoboCommand roboCopy = new RoboCommand();

                    //Debug.WriteLine(Path.GetDirectoryName(originPath));
                    //Debug.WriteLine(backupPath);
                    //Debug.WriteLine(Path.GetFileName(originPath));

                    // Copy options
                    roboCopy.CopyOptions.Source      = Path.GetDirectoryName(originPath);
                    roboCopy.CopyOptions.Destination = backupPath;
                    roboCopy.CopyOptions.FileFilter  = new string[] { Path.GetFileName(originPath) };

                    // Selection options
                    roboCopy.SelectionOptions.IncludeSame    = false;
                    roboCopy.SelectionOptions.IncludeTweaked = true;
                    roboCopy.SelectionOptions.ExcludeOlder   = true;

                    // Retry options
                    roboCopy.RetryOptions.RetryCount    = 3;
                    roboCopy.RetryOptions.RetryWaitTime = 5;

                    // Start and wait for the robocopy to finish.
                    await roboCopy.Start();
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in BackupJob.Execute() file" + e.Message);

                    // Notify the UI that the job has errored.
                    BackupInfoViewModel.SetBackupItemStatus(context.JobDetail.Key.Name.ToString(), (int)StatusCodes.ERROR);
                }
            }
            Debug.WriteLine(string.Format("Copy job '{0}' completed at: {1}", context.JobDetail.Key.Name.ToString().Substring(0, 5), DateTime.Now));

            // If the backup was successful, then update information for the item and save the BackupItem collection config to file.
            BackupInfoViewModel.NotifyItemHasBeenBackedUp(context.JobDetail.Key.Name);
            BackupInfoViewModel.UpdateNextBackupDate(context.JobDetail.Key.Name);
            BackupInfoViewModel.SaveConfig();
        }
            private void BeginRestore()
            {
                if (Utilities.IsGameRunning(Game))
                {
                    M3L.ShowDialog(window, M3L.GetString(M3L.string_interp_dialogCannotRestoreXWhileItIsRunning, Game.ToGameName()), M3L.GetString(M3L.string_gameRunning), MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var useNewMethod = M3L.ShowDialog(window,
                                                  M3L.GetString(M3L.string_beta_useNewRestoreMethod),
                                                  M3L.GetString(M3L.string_useBetaFeatureQuestion), MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;

                bool restore = RestoreTarget.IsCustomOption || useNewMethod; //custom option is restore to custom location

                restore = restore || M3L.ShowDialog(window, M3L.GetString(M3L.string_dialog_restoringXWillDeleteGameDir, Game.ToGameName()), M3L.GetString(M3L.string_gameTargetWillBeDeleted), MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes;
                if (restore)
                {
                    NamedBackgroundWorker nbw = new NamedBackgroundWorker(Game + @"-Restore");
                    nbw.WorkerReportsProgress = true;
                    nbw.ProgressChanged      += (a, b) =>
                    {
                        if (b.UserState is double d)
                        {
                            TaskbarHelper.SetProgress(d);
                        }
                    };
                    nbw.DoWork += (a, b) =>
                    {
                        RestoreInProgress = true;
                        // Nuke the LODs
                        if (!RestoreTarget.IsCustomOption && RestoreTarget.Game.IsOTGame())
                        {
                            Log.Information($@"Resetting LODs for {RestoreTarget.Game}");
                            Utilities.SetLODs(RestoreTarget, false, false, false);
                        }

                        string restoreTargetPath = b.Argument as string;
                        string backupPath        = BackupLocation;

                        if (!useNewMethod)
                        {
                            BackupStatusLine2 = M3L.GetString(M3L.string_deletingExistingGameInstallation);
                            if (Directory.Exists(restoreTargetPath))
                            {
                                if (Directory.GetFiles(restoreTargetPath).Any() ||
                                    Directory.GetDirectories(restoreTargetPath).Any())
                                {
                                    Log.Information(@"Deleting existing game directory: " + restoreTargetPath);
                                    try
                                    {
                                        bool deletedDirectory =
                                            Utilities.DeleteFilesAndFoldersRecursively(restoreTargetPath);
                                        if (deletedDirectory != true)
                                        {
                                            b.Result = RestoreResult.ERROR_COULD_NOT_DELETE_GAME_DIRECTORY;
                                            return;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //todo: handle this better
                                        Log.Error(
                                            $@"Exception deleting game directory: {restoreTargetPath}: {ex.Message}");
                                        b.Result = RestoreResult.EXCEPTION_DELETING_GAME_DIRECTORY;
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                Log.Error(@"Game directory not found! Was it removed while the app was running?");
                            }

                            var created = Utilities.CreateDirectoryWithWritePermission(restoreTargetPath);
                            if (!created)
                            {
                                b.Result = RestoreResult.ERROR_COULD_NOT_CREATE_DIRECTORY;
                                return;
                            }
                        }

                        BackupStatusLine2 = M3L.GetString(M3L.string_restoringGameFromBackup);
                        if (restoreTargetPath != null)
                        {
                            //callbacks

                            #region callbacks

                            void fileCopiedCallback()
                            {
                                ProgressValue++;
                                if (ProgressMax != 0)
                                {
                                    nbw.ReportProgress(0, ProgressValue * 1.0 / ProgressMax);
                                }
                            }

                            string dlcFolderpath   = MEDirectories.GetDLCPath(Game, backupPath) + '\\'; //\ at end makes sure we are restoring a subdir
                            int    dlcSubStringLen = dlcFolderpath.Length;
                            Debug.WriteLine(@"DLC Folder: " + dlcFolderpath);
                            Debug.Write(@"DLC Folder path len:" + dlcFolderpath);

                            bool aboutToCopyCallback(string fileBeingCopied)
                            {
                                if (fileBeingCopied.Contains(@"\cmmbackup\"))
                                {
                                    return(false);                                          //do not copy cmmbackup files
                                }
                                Debug.WriteLine(fileBeingCopied);
                                if (fileBeingCopied.StartsWith(dlcFolderpath, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    //It's a DLC!
                                    string dlcname = fileBeingCopied.Substring(dlcSubStringLen);
                                    int    index   = dlcname.IndexOf('\\');
                                    if (index > 0) //Files directly in the DLC directory won't have path sep
                                    {
                                        try
                                        {
                                            dlcname = dlcname.Substring(0, index);
                                            if (MEDirectories.OfficialDLCNames(RestoreTarget.Game).TryGetValue(dlcname, out var hrName))
                                            {
                                                BackupStatusLine2 = M3L.GetString(M3L.string_interp_restoringX, hrName);
                                            }
                                            else
                                            {
                                                BackupStatusLine2 = M3L.GetString(M3L.string_interp_restoringX, dlcname);
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Crashes.TrackError(e, new Dictionary <string, string>()
                                            {
                                                { @"Source", @"Restore UI display callback" },
                                                { @"Value", fileBeingCopied },
                                                { @"DLC Folder path", dlcFolderpath }
                                            });
                                        }
                                    }
                                }
                                else
                                {
                                    //It's basegame
                                    if (fileBeingCopied.EndsWith(@".bik"))
                                    {
                                        BackupStatusLine2 = M3L.GetString(M3L.string_restoringMovies);
                                    }
                                    else if (new FileInfo(fileBeingCopied).Length > 52428800)
                                    {
                                        BackupStatusLine2 = M3L.GetString(M3L.string_interp_restoringX, Path.GetFileName(fileBeingCopied));
                                    }
                                    else
                                    {
                                        BackupStatusLine2 = M3L.GetString(M3L.string_restoringBasegame);
                                    }
                                }

                                return(true);
                            }

                            void totalFilesToCopyCallback(int total)
                            {
                                ProgressValue         = 0;
                                ProgressIndeterminate = false;
                                ProgressMax           = total;
                            }

                            #endregion

                            BackupStatus = M3L.GetString(M3L.string_restoringGame);

                            // LE: Backup Config file so settings don't get lost
                            string configText = null;
                            var    configPath = RestoreTarget.Game.IsLEGame() ? M3Directories.GetLODConfigFile(RestoreTarget) : null;
                            if (File.Exists(configPath))
                            {
                                configText = File.ReadAllText(configPath); // backup to memory
                            }

                            Log.Information($@"Copying backup to game directory: {backupPath} -> {restoreTargetPath}");
                            if (useNewMethod)
                            {
                                string      CurrentRCFile = null;
                                RoboCommand rc            = new RoboCommand();
                                rc.CopyOptions.Destination = restoreTargetPath;
                                rc.CopyOptions.Source      = backupPath;
                                rc.CopyOptions.Mirror      = true;
                                rc.CopyOptions.MultiThreadedCopiesCount = 2;
                                rc.OnCopyProgressChanged += (sender, args) =>
                                {
                                    ProgressIndeterminate = false;
                                    ProgressValue         = (int)args.CurrentFileProgress;
                                    ProgressMax           = 100;
                                };
                                rc.OnFileProcessed += (sender, args) =>
                                {
                                    if (args.ProcessedFile.Name.StartsWith(backupPath) && args.ProcessedFile.Name.Length > backupPath.Length)
                                    {
                                        CurrentRCFile     = args.ProcessedFile.Name.Substring(backupPath.Length + 1);
                                        BackupStatusLine2 = M3L.GetString(M3L.string_interp_copyingX, CurrentRCFile);
                                    }
                                };
                                rc.Start().Wait();
                            }
                            else
                            {
                                CopyDir.CopyAll_ProgressBar(new DirectoryInfo(backupPath),
                                                            new DirectoryInfo(restoreTargetPath),
                                                            totalItemsToCopyCallback: totalFilesToCopyCallback,
                                                            aboutToCopyCallback: aboutToCopyCallback,
                                                            fileCopiedCallback: fileCopiedCallback,
                                                            ignoredExtensions: new[] { @"*.pdf", @"*.mp3" });
                            }

                            Log.Information(@"Restore of game data has completed");

                            if (configText != null)
                            {
                                // Restore config file
                                try
                                {
                                    Directory.CreateDirectory(Directory.GetParent(configPath).FullName);
                                    File.WriteAllText(configPath, configText);
                                    Log.Information(@"Restored config file");
                                }
                                catch (Exception e)
                                {
                                    Log.Error($@"Could not restore config file: {e.Message}");
                                }
                            }
                            BackupCopyFinished(restoreTargetPath);
                        }
                    };
                    nbw.RunWorkerCompleted += (a, b) =>
                    {
                        if (b.Error != null)
                        {
                            Log.Error($@"Exception occurred in {nbw.Name} thread: {b.Error.Message}");
                        }
                        TaskbarHelper.SetProgressState(TaskbarProgressBarState.NoProgress);
                        if (b.Result is RestoreResult result)
                        {
                            switch (result)
                            {
                            case RestoreResult.ERROR_COULD_NOT_CREATE_DIRECTORY:
                                Analytics.TrackEvent(@"Restored game", new Dictionary <string, string>()
                                {
                                    { @"Game", Game.ToString() },
                                    { @"Result", @"Failure, Could not create target directory" }
                                });
                                M3L.ShowDialog(window, M3L.GetString(M3L.string_dialogCouldNotCreateGameDirectoryAfterDeletion), M3L.GetString(M3L.string_errorRestoringGame), MessageBoxButton.OK, MessageBoxImage.Error);
                                break;

                            case RestoreResult.ERROR_COULD_NOT_DELETE_GAME_DIRECTORY:
                                Analytics.TrackEvent(@"Restored game", new Dictionary <string, string>()
                                {
                                    { @"Game", Game.ToString() },
                                    { @"Result", @"Failure, Could not delete existing game directory" }
                                });
                                M3L.ShowDialog(window, M3L.GetString(M3L.string_dialogcouldNotFullyDeleteGameDirectory), M3L.GetString(M3L.string_errorRestoringGame), MessageBoxButton.OK, MessageBoxImage.Error);
                                break;

                            case RestoreResult.EXCEPTION_DELETING_GAME_DIRECTORY:
                                Analytics.TrackEvent(@"Restored game", new Dictionary <string, string>()
                                {
                                    { @"Game", Game.ToString() },
                                    { @"Result", @"Failure, Exception deleting existing game directory" }
                                });
                                M3L.ShowDialog(window, M3L.GetString(M3L.string_dialogErrorOccuredDeletingGameDirectory), M3L.GetString(M3L.string_errorRestoringGame), MessageBoxButton.OK, MessageBoxImage.Error);
                                break;

                            case RestoreResult.RESTORE_OK:
                                Analytics.TrackEvent(@"Restored game", new Dictionary <string, string>()
                                {
                                    { @"Game", Game.ToString() },
                                    { @"Result", @"Success" }
                                });
                                break;
                            }
                        }

                        EndRestore();
                        CommandManager.InvalidateRequerySuggested();
                    };
                    var restoreTargetPath = RestoreTarget.TargetPath;
                    if (RestoreTarget.IsCustomOption)
                    {
                        CommonOpenFileDialog m = new CommonOpenFileDialog
                        {
                            IsFolderPicker   = true,
                            EnsurePathExists = true,
                            Title            = M3L.GetString(M3L.string_selectNewRestoreDestination)
                        };
                        if (m.ShowDialog() == CommonFileDialogResult.Ok)
                        {
                            //Check empty
                            restoreTargetPath = m.FileName;
                            if (Directory.Exists(restoreTargetPath))
                            {
                                if (Directory.GetFiles(restoreTargetPath).Length > 0 || Directory.GetDirectories(restoreTargetPath).Length > 0)
                                {
                                    Log.Warning($@"The selected restore directory is not empty: {restoreTargetPath}");
                                    //Directory not empty
                                    if (!useNewMethod)
                                    {
                                        M3L.ShowDialog(window,
                                                       M3L.GetString(M3L
                                                                     .string_dialogDirectoryIsNotEmptyLocationToRestoreToMustBeEmpty),
                                                       M3L.GetString(M3L.string_cannotRestoreToThisLocation), MessageBoxButton.OK,
                                                       MessageBoxImage.Error);
                                        return;
                                    }
                                    else
                                    {
                                        // Warn user
                                        var shouldContinue = MessageBoxResult.Yes == M3L.ShowDialog(window,
                                                                                                    M3L.GetString(M3L.string_interp_directoryNotEmptyWillDeleteEverything, restoreTargetPath),
                                                                                                    M3L.GetString(M3L.string_directoryNotEmpty), MessageBoxButton.YesNo, MessageBoxImage.Warning);
                                        if (!shouldContinue)
                                        {
                                            return;
                                        }
                                        Log.Warning($@"The user is continuing to new-gen restore on existing directory anyways");
                                    }
                                }

                                //TODO: PREVENT RESTORING TO DOCUMENTS/BIOWARE
                            }

                            Analytics.TrackEvent(@"Chose to restore game to custom location", new Dictionary <string, string>()
                            {
                                { @"Game", Game.ToString() },
                                { @"New-gen", useNewMethod.ToString() }
                            });
                        }
                        else
                        {
                            return;
                        }
                    }

                    RefreshTargets = true;
                    TaskbarHelper.SetProgress(0);
                    TaskbarHelper.SetProgressState(TaskbarProgressBarState.Normal);
                    nbw.RunWorkerAsync(restoreTargetPath);
                }
            }
示例#11
0
        public void Backup()
        {
            Debugger.Instance.DebugMessageEvent += DebugMessage;

            copy = new RoboCommand();
            copy.OnFileProcessed += copy_OnFileProcessed;
            copy.OnCommandError += copy_OnCommandError;
            copy.OnError += copy_OnError;
            copy.OnCopyProgressChanged += copy_OnCopyProgressChanged;
            copy.OnCommandCompleted += copy_OnCommandCompleted;
            // copy options
            copy.CopyOptions.Source = Source.Text;
            copy.CopyOptions.Destination = Destination.Text;
            copy.CopyOptions.FileFilter = FileFilter.Text;
            copy.CopyOptions.CopySubdirectories = CopySubDirectories.IsChecked ?? false;
            copy.CopyOptions.CopySubdirectoriesIncludingEmpty = CopySubdirectoriesIncludingEmpty.IsChecked ?? false;
            if (!string.IsNullOrWhiteSpace(Depth.Text))
                copy.CopyOptions.Depth = Convert.ToInt32(Depth.Text);
            copy.CopyOptions.EnableRestartMode = EnableRestartMode.IsChecked ?? false;
            copy.CopyOptions.EnableBackupMode = EnableBackupMode.IsChecked ?? false;
            copy.CopyOptions.EnableRestartModeWithBackupFallback = EnableRestartModeWithBackupFallback.IsChecked ?? false;
            copy.CopyOptions.UseUnbufferedIo = UseUnbufferedIo.IsChecked ?? false;
            copy.CopyOptions.EnableEfsRawMode = EnableEfsRawMode.IsChecked ?? false;
            copy.CopyOptions.CopyFlags = CopyFlags.Text;
            copy.CopyOptions.CopyFilesWithSecurity = CopyFilesWithSecurity.IsChecked ?? false;
            copy.CopyOptions.CopyAll = CopyAll.IsChecked ?? false;
            copy.CopyOptions.RemoveFileInformation = RemoveFileInformation.IsChecked ?? false;
            copy.CopyOptions.FixFileSecurityOnAllFiles = FixFileSecurityOnAllFiles.IsChecked ?? false;
            copy.CopyOptions.FixFileTimesOnAllFiles = FixFileTimesOnAllFiles.IsChecked ?? false;
            copy.CopyOptions.Purge = Purge.IsChecked ?? false;
            copy.CopyOptions.Mirror = Mirror.IsChecked ?? false;
            copy.CopyOptions.MoveFiles = MoveFiles.IsChecked ?? false;
            copy.CopyOptions.MoveFilesAndDirectories = MoveFilesAndDirectories.IsChecked ?? false;
            copy.CopyOptions.AddAttributes = AddAttributes.Text;
            copy.CopyOptions.RemoveAttributes = RemoveAttributes.Text;
            copy.CopyOptions.CreateDirectoryAndFileTree = CreateDirectoryAndFileTree.IsChecked ?? false;
            copy.CopyOptions.FatFiles = FatFiles.IsChecked ?? false;
            copy.CopyOptions.TurnLongPathSupportOff = TurnLongPathSupportOff.IsChecked ?? false;
            if (!string.IsNullOrWhiteSpace(MonitorSourceChangesLimit.Text))
                copy.CopyOptions.MonitorSourceChangesLimit = Convert.ToInt32(MonitorSourceChangesLimit.Text);
            if (!string.IsNullOrWhiteSpace(MonitorSourceTimeLimit.Text))
                copy.CopyOptions.MonitorSourceTimeLimit = Convert.ToInt32(MonitorSourceTimeLimit.Text);

            // select options
            copy.SelectionOptions.OnlyCopyArchiveFiles = OnlyCopyArchiveFiles.IsChecked ?? false;
            copy.SelectionOptions.OnlyCopyArchiveFilesAndResetArchiveFlag = OnlyCopyArchiveFilesAndResetArchiveFlag.IsChecked ?? false;
            copy.SelectionOptions.IncludeAttributes = IncludeAttributes.Text;
            copy.SelectionOptions.ExcludeAttributes = ExcludeAttributes.Text;
            copy.SelectionOptions.ExcludeFiles = ExcludeFiles.Text;
            copy.SelectionOptions.ExcludeDirectories = ExcludeDirectories.Text;
            copy.SelectionOptions.ExcludeOlder = ExcludeOlder.IsChecked ?? false;
            copy.SelectionOptions.ExcludeJunctionPoints = ExcludeJunctionPoints.IsChecked ?? false;

            // retry options
            if (!string.IsNullOrWhiteSpace(RetryCount.Text))
                copy.RetryOptions.RetryCount = Convert.ToInt32(RetryCount.Text);
            if (!string.IsNullOrWhiteSpace(RetryWaitTime.Text))
                copy.RetryOptions.RetryWaitTime = Convert.ToInt32(RetryWaitTime.Text);

            // logging options
            copy.LoggingOptions.VerboseOutput = VerboseOutput.IsChecked ?? false;
            copy.LoggingOptions.NoFileSizes = NoFileSizes.IsChecked ?? false;
            copy.LoggingOptions.NoProgress = NoProgress.IsChecked ?? false;

            copy.Start();
        }
示例#12
0
        public bool SyncToCom(List <int> imageIds)
        {
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }

            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                return(false);
            }


            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    foreach (var imageId in imageIds)
                    {
                        var image = new ServiceImage().GetImage(imageId);
                        if (string.IsNullOrEmpty(image.Name))
                        {
                            continue;
                        }
                        var sourcePath = Path.Combine(ServiceSetting.GetSettingValue(SettingStrings.StoragePath), "images", image.Name);
                        var destPath   = Path.Combine(thisComServer.LocalStoragePath, "images", image.Name).TrimEnd('\\');

                        using (RoboCommand backup = new RoboCommand())
                        {
                            // events

                            /*backup.OnFileProcessed += backup_OnFileProcessed;
                             * backup.OnCommandCompleted += backup_OnCommandCompleted;
                             * backup.OnCopyProgressChanged += Backup_OnCopyProgressChanged;
                             */
                            backup.OnError += Backup_OnError;
                            // copy options
                            backup.CopyOptions.Source             = sourcePath;
                            backup.CopyOptions.Destination        = destPath;
                            backup.CopyOptions.CopySubdirectories = true;
                            backup.SelectionOptions.IncludeSame   = true;
                            backup.CopyOptions.UseUnbufferedIo    = true;
                            if (thisComServer.ReplicationRateIpg != 0)
                            {
                                backup.CopyOptions.InterPacketGap = thisComServer.ReplicationRateIpg;
                            }
                            else
                            {
                                backup.CopyOptions.InterPacketGap = 0;
                            }
                            // select options
                            backup.CopyOptions.Mirror           = true;
                            backup.CopyOptions.Purge            = true;
                            backup.LoggingOptions.VerboseOutput = false;

                            backup.SelectionOptions.ExcludeFiles = "guid";
                            // retry options
                            backup.RetryOptions.RetryCount    = 3;
                            backup.RetryOptions.RetryWaitTime = 60;

                            backup.Start().Wait();
                            if (backup.Results.Status.ExitCodeValue == 0 || backup.Results.Status.ExitCodeValue == 1)
                            {
                                //backup succesful, copy the guid now
                                try
                                {
                                    var guidPath = Path.Combine(sourcePath, "guid");
                                    File.Copy(guidPath, destPath + Path.DirectorySeparatorChar + "guid");
                                }
                                catch (Exception ex)
                                {
                                    Logger.Error(ex.Message);
                                    Logger.Error("Could Not Replicate Image " + image.Name);
                                }
                            }
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }