Example #1
0
        static void Main(string[] args)
        {
            string fileSourcePath = @"C:\Users\davamix\Downloads\pruebas\source";
            string fileTargetPath = @"C:\Users\davamix\Downloads\pruebas\target";

            //try
            //{
            FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges | FileSyncOptions.RecycleDeletedFiles | FileSyncOptions.RecyclePreviousFileOnUpdates | FileSyncOptions.RecycleConflictLoserFiles;

            FileSyncScopeFilter filter = new FileSyncScopeFilter();

            filter.FileNameExcludes.Add("*.info");

            DetectChangesOnFileSystemReplica(fileSourcePath, filter, options);
            DetectChangesOnFileSystemReplica(fileTargetPath, filter, options);

            SyncFileSystemReplicaOneWay(fileSourcePath, fileTargetPath, null, options);
            SyncFileSystemReplicaOneWay(fileTargetPath, fileSourcePath, null, options);

            //}
            //catch (Exception e)
            //{
            //        Console.WriteLine("Exception for FileSync provider\n-> {0}", e.Message);
            //}

            Console.WriteLine("FIN");
            Console.Read();
        }
 public bool Sync(string sDir, string tDir, FileSyncScopeFilter filter, FileSyncOptions options)
 {
     try
     {
         _fileEngine.CheckTargetDirExists(tDir);
         var SourceProvider = _fileEngine.CreateProvider(sDir, filter, options);
         var DestinationProvider = _fileEngine.CreateProvider(tDir, filter, options);
         _fileEngine.DetectChanges(SourceProvider);
         SourceProvider = _fileEngine.CreateProvider(sDir, filter, options);
         SourceProvider = _fileEngine.SetPreviewModeFlag(SourceProvider, true);
         DestinationProvider = _fileEngine.SetPreviewModeFlag(DestinationProvider, true);
         DestinationProvider = _fileEngine.AttachApplyingChangeEventHandler(DestinationProvider);
         DestinationProvider = _fileEngine.AttachAppliedChangeEventHandler(DestinationProvider);
         DestinationProvider = _fileEngine.AttachSkippedChangeEventHandler(DestinationProvider);
         var agent = _fileEngine.CreateSyncOrchestrator(SourceProvider, DestinationProvider);
         agent = _fileEngine.SetSyncDirection(agent);
         _fileEngine.Synchronize(agent);
         return true;
     }
     catch (Exception e)
     {
         // log teh error mon
         return false;
     }
 }
Example #3
0
        /// <summary>
        /// Starts the synchronization job
        /// </summary>
        /// <returns>Returns a boolean to indicate if the synchronization was successful</returns>
        private bool InternalStartSync()
        {
            try
            {
                // Configure sync options
                FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                                          FileSyncOptions.RecycleConflictLoserFiles |
                                          FileSyncOptions.RecycleDeletedFiles |
                                          FileSyncOptions.RecyclePreviousFileOnUpdates;

                // Configure sync filters
                FileSyncScopeFilter filter = new FileSyncScopeFilter();

                // Update metadata of the folders before sync to
                // check for any changes or modifications
                DetectChangesonFileSystemReplica(leftPath, filter, options);
                DetectChangesonFileSystemReplica(rightPath, filter, options);

                // Start the 2-way sync
                SyncFileSystemReplicasOneWay(leftPath, rightPath, null, options, false);
                SyncFileSystemReplicasOneWay(rightPath, leftPath, null, options, false);

                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Example #4
0
    public static void SyncFileSystemReplicasOneWay(
            string sourceReplicaRootPath, string destinationReplicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options)
    {
        FileSyncProvider sourceProvider = null;
        FileSyncProvider destinationProvider = null;

        try
        {
            sourceProvider = new FileSyncProvider(
                sourceReplicaRootPath, filter, options);
            destinationProvider = new FileSyncProvider(
                destinationReplicaRootPath, filter, options);

            destinationProvider.AppliedChange +=
                new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);
            destinationProvider.SkippedChange +=
                new EventHandler<SkippedChangeEventArgs>(OnSkippedChange);

            SyncOrchestrator agent = new SyncOrchestrator();
            agent.LocalProvider = sourceProvider;
            agent.RemoteProvider = destinationProvider;
            agent.Direction = SyncDirectionOrder.Upload; // Sync source to destination

            Console.WriteLine("Synchronizing changes to replica: " +
                destinationProvider.RootDirectoryPath);
            agent.Synchronize();
        }
        finally
        {
            // Release resources
            if (sourceProvider != null) sourceProvider.Dispose();
            if (destinationProvider != null) destinationProvider.Dispose();
        }
    }
Example #5
0
        private void SyncFileOperate(string sourceRootPath, string destRootPath, string tempDir, string trashDir)
        {
            FileSyncScopeFilter filter = new FileSyncScopeFilter();

            filter.FileNameExcludes.Add("*.metadata");
            FileSyncOptions options = FileSyncOptions.None;

            //DetectChanges
            DetectChangesOnFileSystemReplica(sourceRootPath, filter, options, sourceRootPath, "filesync.metadata", tempDir, trashDir);
            DetectChangesOnFileSystemReplica(destRootPath, filter, options, destRootPath, "filesync.metadata", tempDir, trashDir);

            try
            {
                ThreadInteropUtils.OpeMainFormControl(() =>
                {
                    this.richTextBox1.Text += "Start synchronizing..." + Environment.NewLine;
                }, this);

                //SyncChanges Both Ways
                SyncOperationStatistics syncOperationStatistics = null;
                SyncFileUtils.SyncFileSystemReplicasOneWay(sourceRootPath, destRootPath, filter, options, sourceRootPath, "filesync.metadata", destRootPath, "filesync.metadata", tempDir, trashDir, ref syncOperationStatistics);

                //ThreadInteropUtils.OpeMainFormControl(() =>
                //{
                //    this.richTextBox1.Text += "Synchronizing file upload changes... " + syncOperationStatistics.UploadChangesApplied.ToString() + Environment.NewLine;
                //}, this);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Example #6
0
        public void SyncFileSystemReplicasOneWay(
            SyncId sourceReplicaId,
            SyncId destinationReplicaId,
            string sourceReplicaRootPath,
            string destinationReplicaRootPath,
            FileSyncScopeFilter filter,
            FileSyncOptions options)
        {
            using (var sourceProvider = createFileSyncProvider(
                sourceReplicaId.GetGuidId(),
                sourceReplicaRootPath,
                filter,
                options))
            using (var destinationProvider = createFileSyncProvider(
                destinationReplicaId.GetGuidId(),
                destinationReplicaRootPath,
                filter,
                options))
            {
                destinationProvider.AppliedChange += destinationProvider_AppliedChange;
                destinationProvider.SkippedChange += destinationProvider_SkippedChange;

                sourceProvider.DetectChanges();
                destinationProvider.DetectChanges();

                synchronizeProviders(destinationProvider, sourceProvider);
            }
        }
Example #7
0
        /// <summary>
        /// InternalExecute
        /// </summary>
        protected override void InternalExecute()
        {
            if (!this.TargetingLocalMachine())
            {
                return;
            }

            // Check that the Source exists
            if (!Directory.Exists(this.Source.GetMetadata("FullPath")))
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Source Folder does not exist: {0}", this.Source.GetMetadata("FullPath")));
                return;
            }

            // Set the sync options
            if (this.SyncOptions != null)
            {
                FileSyncOptions fso = this.SyncOptions.Aggregate(new FileSyncOptions(), (current, opt) => current | (FileSyncOptions)Enum.Parse(typeof(FileSyncOptions), opt.ItemSpec));
                this.syncOptions = fso;
                this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "SyncOptions set: {0}", this.syncOptions));
            }

            switch (this.TaskAction)
            {
            case "SyncFolders":
                this.SyncFolders();
                break;

            default:
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
                return;
            }
        }
Example #8
0
        private static void Main(string[] args)
        {
            const string replica1RootPath = "_R0";
            const string replica2RootPath = "_R1";

            if (Directory.Exists(replica1RootPath))
            {
                Directory.Delete(replica1RootPath, true);
            }
            Directory.CreateDirectory(replica1RootPath);

            if (Directory.Exists(replica2RootPath))
            {
                Directory.Delete(replica2RootPath, true);
            }
            Directory.CreateDirectory(replica2RootPath);

            try
            {
                // Set options for the synchronization operation
                const FileSyncOptions options =
                    FileSyncOptions.ExplicitDetectChanges |
                    FileSyncOptions.RecycleDeletedFiles |
                    FileSyncOptions.RecyclePreviousFileOnUpdates |
                    FileSyncOptions.RecycleConflictLoserFiles;

                var filter = new FileSyncScopeFilter();
                //filter.FileNameExcludes.Add("*.lnk"); // Exclude all *.lnk files

                Guid replica1Guid = Guid.Parse("181517DE-B950-4e62-9582-56F01884288D");
                Guid replica2Guid = Guid.Parse("86C9D79E-679D-4d33-A051-AA4EEFF17E55");

                using (var provider0 = new FileSyncProvider(replica1Guid, replica1RootPath, filter, options))
                {
                    using (var provider1 = new FileSyncProvider(replica2Guid, replica2RootPath, filter, options))
                    //using (var provider1 = new TestProvider(replica2Guid, Path.Combine(replica2RootPath, "_replica.sdf")))
                    {
                        var agent = CreateAgent(
                            provider0,
                            provider1
                            );

                        while (true)
                        {
                            provider0.DetectChanges();
                            provider1.DetectChanges();

                            agent.Synchronize();

                            Thread.Sleep(25);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nException from File Synchronization Provider:\n" + e);
            }
        }
Example #9
0
        /// <summary>
        /// Does Sync operation to store change events into a list of FileData objects
        /// </summary>
        private int InternalPreviewSync()
        {
            try
            {
                fileData = new List <FileData>();

                // Configure sync options
                FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                                          FileSyncOptions.RecycleConflictLoserFiles |
                                          FileSyncOptions.RecycleDeletedFiles |
                                          FileSyncOptions.RecyclePreviousFileOnUpdates;


                // Configure sync filters
                FileSyncScopeFilter filter = new FileSyncScopeFilter();
                filter.SubdirectoryExcludes.Add(TRACKBACK_FOLDER_NAME);
                filter.FileNameExcludes.Add(METADATA_FILE_NAME);

                // Add filters for file types
                for (int i = 0; i < excludeData.ExcludeFileTypeList.Count; i++)
                {
                    filter.FileNameExcludes.Add("*" + excludeData.ExcludeFileTypeList[i]);
                }

                // Add filters for file names
                for (int i = 0; i < excludeData.ExcludeFileNameList.Count; i++)
                {
                    filter.FileNameExcludes.Add(excludeData.ExcludeFileNameList[i]);
                }

                // Add filters for folders
                for (int i = 0; i < excludeData.ExcludeFolderList.Count; i++)
                {
                    filter.SubdirectoryExcludes.Add(excludeData.ExcludeFolderList[i]);
                }

                // Update metadata of the folders before sync to
                // check for any changes or modifications
                DetectChangesonFileSystemReplica(leftPath, filter, options);
                DetectChangesonFileSystemReplica(rightPath, filter, options);

                // Start the 2-way sync
                SyncFileSystemReplicasOneWay(leftPath, rightPath, null, options);
                SyncFileSystemReplicasOneWay(rightPath, leftPath, null, options);
                return(0);
            }
            catch (SyncException)
            {
                return(1);
            }
            catch (DirectoryNotFoundException)
            {
                return(2);
            }
            catch (Exception)
            {
                return(3);
            }
        }
Example #10
0
 public FileSyncInfo(string syncAction, string replicaRootPath, string[] filters, FileSyncOptions syncOptions, string serverSyncClass = null)
     : base(syncAction)
 {
     ServerSyncClass = string.IsNullOrEmpty(serverSyncClass) ? FileSyncInfo.FILESYNC_CLASS : serverSyncClass;
     ReplicaRootPath = replicaRootPath;
     Filters         = filters;
     SyncOptions     = syncOptions;
 }
Example #11
0
        public void Configure(string syncAction, string replicaRootPath, string[] filters, FileSyncOptions syncOptions)
        {
            ReplicaRootPath = replicaRootPath;
            SetScopeFilter(filters);
            SyncOptions = syncOptions;

            DetectChanges();
        }
        /// <summary>
        /// Run method, executed by a dedicated Task to analyze file system changes and start syncing operations
        /// </summary>
        private void Run()
        {
            // Set options for the synchronization operation
            FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                                      FileSyncOptions.RecycleDeletedFiles |
                                      FileSyncOptions.RecyclePreviousFileOnUpdates;

            FileSyncScopeFilter filter = new FileSyncScopeFilter();

            if (AppSettings.Default.ExcludedFiles.Trim().Length > 0)
            {
                var excludedTypes = AppSettings.Default.ExcludedFiles.Split(',');
                foreach (var exType in excludedTypes)
                {
                    if (exType != null && exType.Trim().Length > 0)
                    {
                        filter.FileNameExcludes.Add(exType);
                    }
                }
            }
            else
            {
                Logger.Log("No file filter specified", LogInfo.Info, VerbosityInfoLevel.V2);
            }
            if (AppSettings.Default.ExcludedFolders.Trim().Length > 0)
            {
                var excludedFolders = AppSettings.Default.ExcludedFolders.Split(',');
                foreach (var exFolder in excludedFolders)
                {
                    if (exFolder != null && exFolder.Trim().Length > 0)
                    {
                        filter.SubdirectoryExcludes.Add(exFolder);
                    }
                }
            }
            else
            {
                Logger.Log("No folder filter specified", LogInfo.Info, VerbosityInfoLevel.V2);
            }

            while (running)
            {
                try
                {
                    DetectChangesOnFileSystemReplica(AppSettings.Default.Path1, filter, options);
                    DetectChangesOnFileSystemReplica(AppSettings.Default.Path2, filter, options);

                    SyncFileSystemReplicasOneWay(AppSettings.Default.Path1, AppSettings.Default.Path2, filter, options);
                    SyncFileSystemReplicasOneWay(AppSettings.Default.Path2, AppSettings.Default.Path1, filter, options);
                }
                catch (Exception e)
                {
                    Logger.Log("Error on sync provider execution:\n {0}", LogInfo.Error, VerbosityInfoLevel.V1, e.ToString());
                }
                Thread.Sleep(AppSettings.Default.CheckIntervalSec * 1000);
            }
        }
Example #13
0
 public void DetectChangesOnFileSystemReplica(
     SyncId replicaId,
     string replicaRootPath,
     FileSyncScopeFilter filter,
     FileSyncOptions options)
 {
     using (var provider = createFileSyncProvider(replicaId.GetGuidId(), replicaRootPath, filter, options))
         provider.DetectChanges();
 }
Example #14
0
        public static void SyncFileSystemReplicasOneWay(
            string sourceReplicaRootPath, string destinationReplicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider      = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                // Instantiate source and destination providers, with a null filter (the filter
                // was specified in DetectChangesOnFileSystemReplica()), and options for both.
                sourceProvider = new FileSyncProvider(
                    sourceReplicaRootPath, filter, options);
                destinationProvider = new FileSyncProvider(
                    destinationReplicaRootPath, filter, options);

                // Register event handlers so that we can write information
                // to the console.
                //destinationProvider.AppliedChange +=
                //    new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);
                //destinationProvider.SkippedChange +=
                //    new EventHandler<SkippedChangeEventArgs>(OnSkippedChange);

                // Use SyncCallbacks for conflicting items.
                //SyncCallbacks destinationCallbacks = destinationProvider.DestinationCallbacks;
                //destinationCallbacks.ItemConflicting += new EventHandler<ItemConflictingEventArgs>(OnItemConflicting);
                //destinationCallbacks.ItemConstraint += new EventHandler<ItemConstraintEventArgs>(OnItemConstraint);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = sourceProvider;
                agent.RemoteProvider = destinationProvider;
                agent.Direction      = SyncDirectionOrder.Upload; // Upload changes from the source to the destination.

                Console.WriteLine("Synchronizing changes to replica: " +
                                  destinationProvider.RootDirectoryPath);
                agent.Synchronize();
            }
            finally
            {
                // Release resources.
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (destinationProvider != null)
                {
                    destinationProvider.Dispose();
                }
            }
        }
Example #15
0
        public override TaskStatus Run()
        {
            this.Info("Synchronising folders...");

            bool success = true;

            try
            {
                string idFileName = "filesync.id";

                Guid replica1Id = GetReplicaId(Path.Combine(this.SrcFolder, idFileName));
                Guid replica2Id = GetReplicaId(Path.Combine(this.destFolder, idFileName));

                // Set options for the sync operation
                FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                                          FileSyncOptions.RecycleDeletedFiles | FileSyncOptions.RecyclePreviousFileOnUpdates | FileSyncOptions.RecycleConflictLoserFiles;

                FileSyncScopeFilter filter = new FileSyncScopeFilter();
                filter.FileNameExcludes.Add(idFileName); // Exclude the id file

                // Explicitly detect changes on both replicas upfront, to avoid two change
                // detection passes for the two-way sync
                DetectChangesOnFileSystemReplica(replica1Id, this.SrcFolder, filter, options);
                DetectChangesOnFileSystemReplica(replica2Id, this.destFolder, filter, options);

                // Sync source to destination
                SyncFileSystemReplicasOneWay(replica1Id, replica2Id, this.SrcFolder, this.destFolder, filter, options);
                success &= true;
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Error from File Sync Provider: {0}\n", e.Message);
                success &= false;
            }

            Status status = Status.Success;

            if (!success)
            {
                status = Status.Error;
            }

            this.Info("Task finished.");
            return(new TaskStatus(status, false));
        }
Example #16
0
        private void button2_Click_1(object sender, EventArgs e)
        {
            FileSyncProvider sourceProvider      = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                FileSyncScopeFilter filter = new FileSyncScopeFilter();
                filter.FileNameExcludes.Add("*.metadata");
                FileSyncOptions options = FileSyncOptions.None;

                sourceProvider      = new FileSyncProvider(sourceRootPath, filter, options);
                destinationProvider = new FileSyncProvider(destRootPath, filter, options);

                //destinationProvider.AppliedChange += new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);
                //destinationProvider.SkippedChange += new EventHandler<SkippedChangeEventArgs>(OnSkippedChange);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = sourceProvider;
                agent.RemoteProvider = destinationProvider;
                //agent.Direction = SyncDirectionOrder.Upload; // Sync source to destination
                agent.Direction = SyncDirectionOrder.DownloadAndUpload; // Sync source to destination
                Console.WriteLine("Synchronizing changes to replica: " + destinationProvider.RootDirectoryPath);
                System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                stopwatch.Start();

                agent.Synchronize();

                stopwatch.Stop();
                this.richTextBox1.Text = "Sync framework test total time:" + stopwatch.ElapsedMilliseconds + "ms";
            }
            catch (Exception exc)
            {
                throw exc;
            }
            finally
            {
                // Release resources
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (destinationProvider != null)
                {
                    destinationProvider.Dispose();
                }
            }
        }
Example #17
0
        public static void WatchFileSystem(string sourceDirectory, string targetDirectory)
        {
            if (string.IsNullOrEmpty(sourceDirectory) || string.IsNullOrEmpty(targetDirectory) ||
                !Directory.Exists(sourceDirectory) || !Directory.Exists(targetDirectory))
            {
                return;
            }

            try
            {
                // Set options for the synchronization operation
                FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                                          FileSyncOptions.RecycleDeletedFiles |
                                          FileSyncOptions.RecyclePreviousFileOnUpdates |
                                          FileSyncOptions.RecycleConflictLoserFiles;

                FileSyncScopeFilter filter = new FileSyncScopeFilter();
                //filter.FileNameExcludes.Add("*.lnk"); // Exclude all *.lnk files
                filter.FileNameIncludes.Add("*.mp4");
                filter.FileNameIncludes.Add("*.mkv");
                filter.FileNameIncludes.Add("*.avi");
                filter.FileNameIncludes.Add("*.divx");
                filter.FileNameIncludes.Add("*.png");
                filter.FileNameIncludes.Add("*.jpg");
                filter.FileNameIncludes.Add("*.gif");
                filter.FileNameIncludes.Add("*.zip");
                filter.FileNameIncludes.Add("*.rar");
                filter.FileNameIncludes.Add("*.mp3");

                // Explicitly detect changes on both replicas upfront, to avoid two change
                // detection passes for the two-way synchronization

                //DetectChangesOnFileSystemReplica(
                //        sourceDirectory, filter, null);
                //DetectChangesOnFileSystemReplica(
                //    targetDirectory, filter, options);

                // Synchronization in both directions
                SyncFileSystemReplicasOneWay(sourceDirectory, targetDirectory, filter, options);
                //SyncFileSystemReplicasOneWay(sourceDirectory, targetDirectory, null, options);
            }
            catch (Exception e)
            {
                Logging.Log("\nException from File Synchronization Provider:\n" + e.ToString());
            }
        }
Example #18
0
        /// <summary>
        /// Does actual presync preparations
        /// </summary>
        /// <returns></returns>
        private bool InternalPreSync()
        {
            try
            {
                // Reset all counters before every synchronization
                countChanges            = 0;
                countDoneChanges        = 0;
                freeDiskSpaceForLeft    = 0;
                freeDiskSpaceForRight   = 0;
                diskSpaceNeededForLeft  = 0;
                diskSpaceNeededForRight = 0;
                isCheckForLeftDone      = false;

                // Configure sync options
                FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                                          FileSyncOptions.RecycleConflictLoserFiles |
                                          FileSyncOptions.RecycleDeletedFiles |
                                          FileSyncOptions.RecyclePreviousFileOnUpdates;


                // Configure sync filters
                FileSyncScopeFilter filter = new FileSyncScopeFilter();

                // Update metadata of the folders before sync to
                // check for any changes or modifications
                DetectChangesonFileSystemReplica(leftPath, filter, options);
                DetectChangesonFileSystemReplica(rightPath, filter, options);

                // Start the 2-way sync
                if (!SyncFileSystemReplicasOneWay(leftPath, rightPath, null, options, true))
                {
                    return(false);
                }
                if (!SyncFileSystemReplicasOneWay(rightPath, leftPath, null, options, true))
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Example #19
0
    public static void DetectChangesOnFileSystemReplica(
            string replicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options)
    {
        FileSyncProvider provider = null;

        try
        {
            provider = new FileSyncProvider(replicaRootPath, filter, options);
            provider.DetectChanges();
        }
        finally
        {
            // Release resources
            if (provider != null)
                provider.Dispose();
        }
    }
        /// <summary>
        /// Synchronize two folders (source and destination). The sync operation is ONE WAY only (From source to destination)
        /// </summary>
        /// <param name="sourceReplicaRootPath">source syncing path</param>
        /// <param name="destinationReplicaRootPath">destination syncing path</param>
        /// <param name="filter">syncing filter</param>
        /// <param name="options">syncing options</param>
        private void SyncFileSystemReplicasOneWay(
            string sourceReplicaRootPath, string destinationReplicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider      = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(
                    sourceReplicaRootPath, filter, options);
                destinationProvider = new FileSyncProvider(
                    destinationReplicaRootPath, filter, options);

                destinationProvider.AppliedChange  += new EventHandler <AppliedChangeEventArgs>(OnAppliedChange);
                destinationProvider.SkippedChange  += new EventHandler <SkippedChangeEventArgs>(OnSkippedChange);
                destinationProvider.ApplyingChange += DestinationProvider_ApplyingChange;

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = sourceProvider;
                agent.RemoteProvider = destinationProvider;
                agent.Direction      = SyncDirectionOrder.Upload; // Sync source to destination


                var ret = agent.Synchronize();

                if (ret.UploadChangesTotal != 0)
                {
                    Logger.Log("Synchronizing '{0}', tot changes={1} ({2} done/{3} errors)", LogInfo.Info, VerbosityInfoLevel.V3, destinationProvider.RootDirectoryPath, ret.UploadChangesTotal, ret.UploadChangesApplied, ret.UploadChangesFailed);
                }
            }
            finally
            {
                // Release resources
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (destinationProvider != null)
                {
                    destinationProvider.Dispose();
                }
            }
        }
Example #21
0
        /// <summary>
        /// Start the synchronization in one direction
        /// </summary>
        /// <param name="sourcePath">This parameter holds the source folder path</param>
        /// <param name="destPath">This parameter holds the destination folder path</param>
        /// <param name="filter">This parameter is the filter which will be used during synchronization</param>
        /// <param name="options">This parameter holds the synchronization options</param>
        private void SyncFileSystemReplicasOneWay(string sourcePath, string destPath,
                                                  FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider destProvider   = null;

            try
            {
                sourceProvider = new FileSyncProvider(sourcePath, filter, options);
                destProvider   = new FileSyncProvider(destPath, filter, options);

                sourceProvider.PreviewMode = true;
                destProvider.PreviewMode   = true;


                destProvider.Configuration.ConflictResolutionPolicy = ConflictResolutionPolicy.ApplicationDefined;
                SyncCallbacks destinationCallBacks = destProvider.DestinationCallbacks;
                destinationCallBacks.ItemConflicting += new EventHandler <ItemConflictingEventArgs>(OnItemConflicting);
                destinationCallBacks.ItemConstraint  += new EventHandler <ItemConstraintEventArgs>(OnItemConstraint);


                destProvider.ApplyingChange += new EventHandler <ApplyingChangeEventArgs>(OnApplyingChange);


                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = sourceProvider;
                agent.RemoteProvider = destProvider;
                agent.Direction      = SyncDirectionOrder.Upload;

                agent.Synchronize();
            }
            finally
            {
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (destProvider != null)
                {
                    destProvider.Dispose();
                }
            }
        }
Example #22
0
        /// <summary>
        /// Detect the changes done to the folder
        /// <para>Updates the metadata</para>
        /// </summary>
        /// <param name="replicaRootPath">This parameter is the folder path to be checked</param>
        /// <param name="filter">This parameter is the filter which will be used during synchronization</param>
        /// <param name="options">This parameter holds the synchronization options</param>
        private static void DetectChangesonFileSystemReplica(
            string replicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider provider = null;

            try
            {
                provider = new FileSyncProvider(replicaRootPath, filter, options);
                provider.DetectChanges();
            }
            finally
            {
                // Release resources or memory
                if (provider != null)
                {
                    provider.Dispose();
                }
            }
        }
Example #23
0
        public void SyncFileSystemReplicasOneWay(
            string sourceReplicaRootPath, string destinationReplicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider      = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(
                    sourceReplicaRootPath, filter, options);
                destinationProvider = new FileSyncProvider(
                    destinationReplicaRootPath, filter, options);

                destinationProvider.AppliedChange +=
                    new EventHandler <AppliedChangeEventArgs>(OnAppliedChange);
                destinationProvider.SkippedChange +=
                    new EventHandler <SkippedChangeEventArgs>(OnSkippedChange);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = sourceProvider;
                agent.RemoteProvider = destinationProvider;
                agent.Direction      = SyncDirectionOrder.DownloadAndUpload; // Sync source to destination

                //Console.WriteLine("Synchronizing changes to replica: " +
                //    destinationProvider.RootDirectoryPath);
                logException.LogExceptionToDisk("Synchronizing changes to replica: " + destinationProvider.RootDirectoryPath);
                agent.Synchronize();
            }
            finally
            {
                // Release resources
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (destinationProvider != null)
                {
                    destinationProvider.Dispose();
                }
            }
        }
Example #24
0
        public void DetectChangesOnFileSystemReplica(
            Guid replicaId, string replicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider provider = null;

            try
            {
                provider = new FileSyncProvider(replicaId, replicaRootPath, filter, options);
                provider.DetectChanges();
            }
            finally
            {
                // Release resources
                if (provider != null)
                {
                    provider.Dispose();
                }
            }
        }
Example #25
0
        public void SyncFileSystemReplicasOneWay(
            Guid sourceReplicaId, Guid destinationReplicaId,
            string sourceReplicaRootPath, string destinationReplicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider      = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(
                    sourceReplicaId, sourceReplicaRootPath, filter, options);
                destinationProvider = new FileSyncProvider(
                    destinationReplicaId, destinationReplicaRootPath, filter, options);

                destinationProvider.AppliedChange += OnAppliedChange;
                destinationProvider.SkippedChange += OnSkippedChange;

                var agent = new SyncOrchestrator
                {
                    LocalProvider  = sourceProvider,
                    RemoteProvider = destinationProvider,
                    Direction      = SyncDirectionOrder.Upload
                };

                InfoFormat("Synchronizing changes to replica: {0}", destinationProvider.RootDirectoryPath);
                agent.Synchronize();
            }
            finally
            {
                // Release resources
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (destinationProvider != null)
                {
                    destinationProvider.Dispose();
                }
            }
        }
Example #26
0
        public static void DetectChangesOnFileSystemReplica(
            SyncId syncid, string replicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options,
            DirectoryInfo syncDir,
            string metadataName)
        {
            FileSyncProvider provider = null;

            try
            {
                provider = new FileSyncProvider(
                    syncid.GetGuidId(), replicaRootPath, filter, options, syncDir.FullName, metadataName, syncDir.FullName, null);
                provider.DetectChanges();
            }
            finally
            {
                // Release resources
                if (provider != null)
                    provider.Dispose();
            }
        }
Example #27
0
    public static void Main(string[] args)
    {
        if (args.Length < 2 ||
            string.IsNullOrEmpty(args[0]) || string.IsNullOrEmpty(args[1]) ||
            !Directory.Exists(args[0]) || !Directory.Exists(args[1]))
        {
            Console.WriteLine(
                "Usage: FileSyncSample [valid directory path 1] [valid directory path 2]");
            return;
        }

        string replica1RootPath = args[0];
        string replica2RootPath = args[1];

        try
        {
            // Set options for the sync operation
            FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                                      FileSyncOptions.RecycleDeletedFiles | FileSyncOptions.RecyclePreviousFileOnUpdates | FileSyncOptions.RecycleConflictLoserFiles;

            FileSyncScopeFilter filter = new FileSyncScopeFilter();
            filter.FileNameExcludes.Add("*.lnk"); // Exclude all *.lnk files

            // Explicitly detect changes on both replicas upfront, to avoid two change
            // detection passes for the two-way sync
            DetectChangesOnFileSystemReplica(
                replica1RootPath, filter, options);
            DetectChangesOnFileSystemReplica(
                replica2RootPath, filter, options);

            // Sync in both directions
            SyncFileSystemReplicasOneWay(replica1RootPath, replica2RootPath, null, options);
            SyncFileSystemReplicasOneWay(replica2RootPath, replica1RootPath, null, options);
        }
        catch (Exception e)
        {
            Console.WriteLine("\nException from File Sync Provider:\n" + e.ToString());
        }
    }
Example #28
0
        public bool SyncNotes()
        {
            logException.LogExceptionToDisk("Inside Sync Notes...");
            string localPath  = ConfigurationManager.AppSettings["localPath"];  //@"C:\Users\rpoondla\Documents\Visual Studio 2015\Projects\OneNoteApplication\OneNoteApplication\bin\Debug"; //args[0];
            string remotePath = ConfigurationManager.AppSettings["RemotePath"]; //@"\\10.213.154.154\f\Ravali"; //args[1];

            logException.LogExceptionToDisk("localPath: " + localPath + "RemotePath: " + remotePath);

            try
            {
                // Set options for the synchronization operation
                FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                                          FileSyncOptions.RecycleDeletedFiles |
                                          FileSyncOptions.RecyclePreviousFileOnUpdates |
                                          FileSyncOptions.RecycleConflictLoserFiles;

                FileSyncScopeFilter filter = new FileSyncScopeFilter();
                filter.FileNameIncludes.Add("*.txt");  //FileNameExcludes.Add("*.lnk"); // Exclude all *.lnk files

                // Explicitly detect changes on both replicas upfront, to avoid two change
                // detection passes for the two-way synchronization

                DetectChangesOnFileSystemReplica(
                    localPath, filter, options);
                DetectChangesOnFileSystemReplica(
                    remotePath, filter, options);

                // Synchronization in both directions
                SyncFileSystemReplicasOneWay(localPath, remotePath, null, options);
                SyncFileSystemReplicasOneWay(remotePath, localPath, null, options);
            }
            catch (Exception e)
            {
                logException.LogExceptionToDisk("\nException from File Synchronization Provider:\n" + e.ToString());
                return(false);
            }
            return(true);
        }
Example #29
0
        private bool SyncFolders()
        {
            var success = true;

            try
            {
                const string idFileName = "filesync.id";

                var replica1Id = GetReplicaId(Path.Combine(SrcFolder, idFileName));
                var replica2Id = GetReplicaId(Path.Combine(DestFolder, idFileName));

                // Set options for the sync operation
                const FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                                                FileSyncOptions.RecycleDeletedFiles | FileSyncOptions.RecyclePreviousFileOnUpdates | FileSyncOptions.RecycleConflictLoserFiles;

                var filter = new FileSyncScopeFilter();
                filter.FileNameExcludes.Add(idFileName); // Exclude the id file

                // Explicitly detect changes on both replicas upfront, to avoid two change
                // detection passes for the two-way sync
                DetectChangesOnFileSystemReplica(replica1Id, SrcFolder, filter, options);
                DetectChangesOnFileSystemReplica(replica2Id, DestFolder, filter, options);

                // Sync source to destination
                SyncFileSystemReplicasOneWay(replica1Id, replica2Id, SrcFolder, DestFolder, filter, options);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Error from File Sync Provider: {0}\n", e.Message);
                success = false;
            }
            return(success);
        }
Example #30
0
        private void SyncFileSystem(
            string sourcePath, string destinationPath)
        {
            FileSyncProvider    sourceProvider      = null;
            FileSyncProvider    destinationProvider = null;
            FileSyncScopeFilter filter = new FileSyncScopeFilter();

            filter.FileNameIncludes.Add("*.zip");
            FileSyncOptions options = FileSyncOptions.None;

            try
            {
                sourceProvider = new FileSyncProvider(
                    sourcePath, filter, options);
                destinationProvider = new FileSyncProvider(
                    destinationPath, filter, options);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = sourceProvider;
                agent.RemoteProvider = destinationProvider;
                agent.Direction      = SyncDirectionOrder.Upload;

                agent.Synchronize();
            }
            finally
            {
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (destinationProvider != null)
                {
                    destinationProvider.Dispose();
                }
            }
        }
Example #31
0
        // Create a provider, and detect changes on the replica that the provider
        // represents.
        public static void DetectChangesOnFileSystemReplica(
            string replicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider provider = null;

            //FileSyncProvider provider;

            try
            {
                //3provider = new FileSyncProvider("C:\\inetpub\\wwwroot\\MAKRO\\Repository");
                provider = new FileSyncProvider(replicaRootPath, filter, options);
                //1provider = new FileSyncProvider(replicaRootPath);
                provider.DetectChanges();
            }
            finally
            {
                // Release resources.
                if (provider != null)
                {
                    provider.Dispose();
                }
            }
        }
Example #32
0
        private void SyncFileSystemReplicasOneWay(
                string sourceReplicaRootPath, string destinationReplicaRootPath,
                FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(
                    sourceReplicaRootPath, filter, options);

                destinationProvider = new FileSyncProvider(
                    destinationReplicaRootPath, filter, options);
                destinationProvider.AppliedChange +=  new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);
                destinationProvider.SkippedChange += new EventHandler<SkippedChangeEventArgs>(OnSkippedChange);
                destinationProvider.CopyingFile += new EventHandler<CopyingFileEventArgs>(OnCopyingFile);
                SyncOrchestrator agent = new SyncOrchestrator();

                agent.LocalProvider = sourceProvider;
                agent.RemoteProvider = destinationProvider;
                agent.Direction = SyncDirectionOrder.Upload; 

                agent.Synchronize();
                notifier.NotifyInfo("Backup in progress..");
            }
            catch(Exception ex)
            {
                notifier.NotifyError(ex.Message);
            }
            finally
            {                
                if (sourceProvider != null) sourceProvider.Dispose();
                if (destinationProvider != null) destinationProvider.Dispose();
            }
        }
Example #33
0
        //public static void DetectChangesOnFileSystemReplica(
        //string replicaRootPath,
        //FileSyncScopeFilter filter, FileSyncOptions options)
        //{
        //    FileSyncProvider provider = null;

        //    try
        //    {
        //        provider = new FileSyncProvider(replicaRootPath, filter, options);
        //        provider.DetectChanges();

        //    }
        //    finally
        //    {
        //        // Release resources
        //        if (provider != null)
        //            provider.Dispose();
        //    }
        //}

        public static void SyncFileSystemReplicasOneWay(
            string sourceReplicaRootPath, string destinationReplicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider      = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(
                    sourceReplicaRootPath, filter, options);

                //filter.SubdirectoryExcludes.Add(@".\");

                destinationProvider = new FileSyncProvider(
                    destinationReplicaRootPath, filter, options);

                sourceProvider.AppliedChange +=
                    new EventHandler <AppliedChangeEventArgs>(OnAppliedChange);
                sourceProvider.SkippedChange +=
                    new EventHandler <SkippedChangeEventArgs>(OnSkippedChange);


                sourceProvider.DetectChanges();

                sourceProvider.CopyingFile += (s, a) =>
                {
                    string file    = a.FilePath;
                    int    percent = a.PercentCopied;
                };
                sourceProvider.AppliedChange += (s, a) =>
                {
                    string file   = a.NewFilePath;
                    var    change = a.ChangeType;
                };
                sourceProvider.DetectedChanges += (s, a) =>
                {
                    //a.TotalDirectoriesFound
                };

                destinationProvider.CopyingFile += (s, a) =>
                {
                    string file    = a.FilePath;
                    int    percent = a.PercentCopied;
                    FileIO.FileTransferProgress(null, new FileTransferProgressEventArgs(percent, Path.GetFileName(file)));
                };
                destinationProvider.AppliedChange += (s, a) =>
                {
                    string file = a.NewFilePath;
                };
                destinationProvider.AppliedChange += (s, a) =>
                {
                    if (a.ChangeType == ChangeType.Delete)
                    {
                        return;
                    }

                    string file       = a.NewFilePath;
                    string serverPath = FileIO.GetPath(destinationReplicaRootPath) + file;
                    if (FileIO.IsDirectory(serverPath))
                    {
                        return;
                    }
                    FileIO.FinshedFileTransfer(null, new FinshedFileTransferEventArgs(Path.GetFileName(serverPath)));
                    string localDirectory = FileIO.GetPath(FileIO.GetPath(sourceReplicaRootPath) + file);
                    string localFile      = localDirectory + Path.GetFileName(file);
                    string topLevelDir    = FileIO.GetPath(sourceReplicaRootPath) + FileIO.GetTopLevelFolder(file);
                    try
                    {
                        File.Delete(localFile);
                    }
                    catch (Exception ex) { Logging.Log(ex.Message); }

                    if (topLevelDir == FileIO.GetPath(sourceReplicaRootPath))
                    {
                        return;
                    }
                    //bool isMoreTransfers = filter.FileNameIncludes.Any(x => Directory.GetFiles(localDirectory, x) != null);
                    foreach (string filterVal in filter.FileNameIncludes)
                    {
                        if (Directory.EnumerateFiles(topLevelDir, filterVal, SearchOption.AllDirectories).Count() > 0)
                        {
                            return;
                        }
                    }

                    //if (isMoreTransfers) return;

                    try
                    {
                        FileIO.ForceDeleteDirectory(topLevelDir);
                    }
                    catch (Exception ex) { Logging.Log(ex.Message); }
                };

                //SyncOrchestrator agent = new SyncOrchestrator();
                _agent.LocalProvider  = sourceProvider;
                _agent.RemoteProvider = destinationProvider;
                _agent.Direction      = SyncDirectionOrder.Upload;

                Logging.Log("Synchronizing changes to replica: " +
                            destinationProvider.RootDirectoryPath);

                _agent.StateChanged += (s, a) =>
                {
                    if (a.OldState == SyncOrchestratorState.Uploading && a.NewState == SyncOrchestratorState.Ready)
                    {
                        string path         = FileIO.GetPath(destinationReplicaRootPath);
                        string metadataFile = path + _metadataFile;

                        try
                        {
                            Logging.Log("Syncronization complete, cleanning up...");
                            File.Delete(metadataFile);
                            foreach (string tmpFile in Directory.EnumerateFiles(path, "*.tmp"))
                            {
                                File.Delete(tmpFile);
                            }
                            //FileSync.WatchFileSystem(sourceReplicaRootPath, destinationReplicaRootPath);
                        }
                        catch (Exception ex)
                        {
                            Logging.LogError(ex.Message);
                        }
                    }
                };
                _agent.SessionProgress += (s, a) =>
                {
                    uint p = a.CompletedWork;
                };
                _agent.Synchronize();
                //keep background worker alive
                //while (true) { };
            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message);
            }
            finally
            {
                // Release resources
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (destinationProvider != null)
                {
                    destinationProvider.Dispose();
                }
                //if (_agent != null) _agent.Cancel(); _agent = null;
            }
        }
Example #34
0
        public static void DetectChangesOnFileSystemReplica(string replicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options, string metadataPath, string metadataFile, string tempDir, string trashDir)
        {
            FileSyncProvider provider = null;

            try
            {
                provider = new FileSyncProvider(replicaRootPath, filter, options, metadataPath, metadataFile, tempDir, trashDir);
                provider.DetectChanges();
            }
            finally
            {
                // Release resources
                if (provider != null)
                {
                    provider.Dispose();
                }
            }
        }
        /// <summary>
        /// Start the synchronization in one direction
        /// </summary>
        /// <param name="sourcePath">This parameter holds the source folder path</param>
        /// <param name="destPath">This parameter holds the destination folder path</param>
        /// <param name="filter">This parameter is the filter which will be used during synchronization</param>
        /// <param name="options">This parameter holds the synchronization options</param>
        /// <param name="isPreview">This parameter is a boolean which indicates if this method should be run in preview mode</param>
        /// <returns>Returns a boolean to indicate if the the synchronization was successful</returns>
        private bool SyncFileSystemReplicasOneWay(string sourcePath, string destPath,
            FileSyncScopeFilter filter, FileSyncOptions options, bool isPreview)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider destProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(sourcePath, filter, options);
                destProvider = new FileSyncProvider(destPath, filter, options);

                // When it's in preview mode, no actual changes are done.
                // This mode is used to compute the number of changes that will be carried out later
                if (isPreview)
                {
                    sourceProvider.PreviewMode = true;
                    destProvider.PreviewMode = true;
                }
                else
                {
                    sourceProvider.PreviewMode = false;
                    destProvider.PreviewMode = false;
                }

                if (isPreview)
                {
                    if (!isCheckForLeftDone)
                    {
                        freeDiskSpaceForLeft = GetFreeDiskSpaceInBytes(sourcePath.Substring(0, 1));
                        freeDiskSpaceForRight = GetFreeDiskSpaceInBytes(destPath.Substring(0, 1));
                    }
                }

                destProvider.Configuration.ConflictResolutionPolicy = ConflictResolutionPolicy.ApplicationDefined;
                SyncCallbacks destinationCallBacks = destProvider.DestinationCallbacks;
                destinationCallBacks.ItemConflicting += new EventHandler<ItemConflictingEventArgs>(OnItemConflicting);

                if (isPreview)
                    destProvider.ApplyingChange += new EventHandler<ApplyingChangeEventArgs>(OnApplyingChange);
                else
                    destProvider.AppliedChange += new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);

                agent = new SyncOrchestrator();
                agent.LocalProvider = sourceProvider;
                agent.RemoteProvider = destProvider;
                agent.Direction = SyncDirectionOrder.Upload;

                agent.Synchronize();

                if (isPreview)
                    return CheckSpace();

                return true;
            }
            catch (SyncAbortedException e)
            {
                throw e;
            }
            finally
            {
                if (sourceProvider != null) sourceProvider.Dispose();
                if (destProvider != null) destProvider.Dispose();
            }
        }
 public void SyncFileSystemReplicasOneWay(SyncId sourceReplicaId, SyncId destinationReplicaId, string sourceReplicaRootPath, string destinationReplicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options)
 {
     throw new System.NotImplementedException();
 }
Example #37
0
        public static void SyncFileSystems(
            string source,
            string dest,
            FileSyncScopeFilter filter,
            FileSyncOptions options)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider destProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(source, filter, options);
                destProvider = new FileSyncProvider(dest, filter, options);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider = sourceProvider;
                agent.RemoteProvider = destProvider;
                agent.Direction = SyncDirectionOrder.Upload;

                destProvider.AppliedChange += destProvider_AppliedChange;
                destProvider.SkippedChange += destProvider_SkippedChange;

                // call backs so we can monitor...
                SyncCallbacks destCallbacks = destProvider.DestinationCallbacks;

                destCallbacks.ItemConflicting += destCallbacks_ItemConflicting;
                destCallbacks.ItemConstraint += destCallbacks_ItemConstraint;

                Console.WriteLine("sync to {0} from {1}", source, dest); 
                agent.Synchronize(); 
            }
            finally {
                if (sourceProvider != null)
                    sourceProvider.Dispose();
                if ( destProvider != null ) 
                    destProvider.Dispose() ; 
            }
        }
Example #38
0
        /// <summary>
        /// InternalExecute
        /// </summary>
        protected override void InternalExecute()
        {
            if (!this.TargetingLocalMachine())
            {
                return;
            }

            // Check that the Source exists
            if (!Directory.Exists(this.Source.GetMetadata("FullPath")))
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Source Folder does not exist: {0}", this.Source.GetMetadata("FullPath")));
                return;
            }

            // Set the sync options
            if (this.SyncOptions != null)
            {
                FileSyncOptions fso = this.SyncOptions.Aggregate(new FileSyncOptions(), (current, opt) => current | (FileSyncOptions)Enum.Parse(typeof(FileSyncOptions), opt.ItemSpec));
                this.syncOptions = fso;
                this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "SyncOptions set: {0}", this.syncOptions));
            }

            switch (this.TaskAction)
            {
                case "SyncFolders":
                    this.SyncFolders();
                    break;
                default:
                    this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
                    return;
            }
        }
 public void DetectChangesOnFileSystemReplica(SyncId replicaId, string replicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options)
 {
     throw new System.NotImplementedException();
 }
Example #40
0
        public static void DetectChanges(string root, FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider provider = null;
            try
            {

                provider = new FileSyncProvider(root, filter, options);
                provider.DetectChanges();
            }
            finally
            {
                if (provider != null)
                    provider.Dispose();
            }
        }
Example #41
0
        public static void SyncFileSystemReplicasOneWay(
            SyncId sourceId, SyncId destId,
            string sourceReplicaRootPath, string destinationReplicaRootPath,
            DirectoryInfo syncDir,
            string sourceMetadata, string targetMetadata,
            FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(
                    sourceId.GetGuidId(), sourceReplicaRootPath, filter, options, syncDir.FullName, sourceMetadata, syncDir.FullName,
                    null);
                destinationProvider = new FileSyncProvider(
                    destId.GetGuidId(), destinationReplicaRootPath, filter, options, syncDir.FullName, targetMetadata, syncDir.FullName,
                    null);

                destinationProvider.AppliedChange += OnAppliedChange;
                destinationProvider.SkippedChange += OnSkippedChange;

                SyncOrchestrator agent = new SyncOrchestrator
                {
                    LocalProvider = sourceProvider,
                    RemoteProvider = destinationProvider,
                    Direction = SyncDirectionOrder.Upload
                };
                // Sync source to destination

                //Console.WriteLine("Synchronizing changes to replica: " +
                //   destinationProvider.RootDirectoryPath);
                agent.Synchronize();
            }
            finally
            {
                // Release resources
                if (sourceProvider != null) sourceProvider.Dispose();
                if (destinationProvider != null) destinationProvider.Dispose();
            }
        }
Example #42
0
        private static void SyncFileSystemReplicaOneWay(string replicaSourcePath, string replicaTargetPath, FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider targetProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(replicaSourcePath, filter, options);
                targetProvider = new FileSyncProvider(replicaTargetPath, filter, options);

                targetProvider.AppliedChange += new EventHandler <AppliedChangeEventArgs>(OnAppliedChange);
                targetProvider.SkippedChange += new EventHandler <SkippedChangeEventArgs>(OnSkippedChange);

                SyncCallbacks targetCallbacks = targetProvider.DestinationCallbacks;
                targetCallbacks.ItemConflicting += new EventHandler <ItemConflictingEventArgs>(OnItemConflicting);
                targetCallbacks.ItemConstraint  += new EventHandler <ItemConstraintEventArgs>(OnItemConstraint);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = sourceProvider;
                agent.RemoteProvider = targetProvider;
                agent.Direction      = SyncDirectionOrder.Upload;

                Console.WriteLine("Sincronizando cambios: {0}", targetProvider.RootDirectoryPath);

                agent.Synchronize();
            }
            finally
            {
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (targetProvider != null)
                {
                    targetProvider.Dispose();
                }
            }
        }
Example #43
0
        private static void DetectChangesOnFileSystemReplica(string replicaPath, FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider provider = null;

            try
            {
                provider = new FileSyncProvider(replicaPath, filter, options);
                provider.DetectChanges();
            }
            finally
            {
                if (provider != null)
                {
                    provider.Dispose();
                }
            }
        }
        /// <summary>
        /// Start the synchronization in one direction
        /// </summary>
        /// <param name="sourcePath">This parameter holds the source folder path</param>
        /// <param name="destPath">This parameter holds the destination folder path</param>
        /// <param name="filter">This parameter is the filter which will be used during synchronization</param>
        /// <param name="options">This parameter holds the synchronization options</param>
        private void SyncFileSystemReplicasOneWay(string sourcePath, string destPath,
        FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider destProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(sourcePath, filter, options);
                destProvider = new FileSyncProvider(destPath, filter, options);

                sourceProvider.PreviewMode = true;
                destProvider.PreviewMode = true;

                destProvider.Configuration.ConflictResolutionPolicy = ConflictResolutionPolicy.ApplicationDefined;
                SyncCallbacks destinationCallBacks = destProvider.DestinationCallbacks;
                destinationCallBacks.ItemConflicting += new EventHandler<ItemConflictingEventArgs>(OnItemConflicting);
                destinationCallBacks.ItemConstraint += new EventHandler<ItemConstraintEventArgs>(OnItemConstraint);

                destProvider.ApplyingChange += new EventHandler<ApplyingChangeEventArgs>(OnApplyingChange);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider = sourceProvider;
                agent.RemoteProvider = destProvider;
                agent.Direction = SyncDirectionOrder.Upload;

                agent.Synchronize();
            }
            finally
            {
                if (sourceProvider != null) sourceProvider.Dispose();
                if (destProvider != null) destProvider.Dispose();
            }
        }
Example #45
0
        public FileSyncProvider CreateProvider(string RootPath, FileSyncScopeFilter filter, FileSyncOptions options)
        {
            //throw new NotImplementedException();
            FileSyncProvider provider = null;

            try
            {
                provider = new FileSyncProvider(RootPath, filter, options);
            }
            catch (Exception e)
            {
                throw e;
            }
            return provider;
        }
Example #46
0
        private void SyncFileSystemReplicasOneWay(string sourceReplicaRootPath, string destinationReplicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                // Instantiate source and destination providers, with a null filter (the filter
                // was specified in DetectChangesOnFileSystemReplica()), and options for both.
                sourceProvider = new FileSyncProvider(sourceReplicaRootPath, filter, options);
                destinationProvider = new FileSyncProvider(destinationReplicaRootPath, filter, options);

                // Register event handlers so that we can write information
                // to the console.
                destinationProvider.AppliedChange += new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);
                destinationProvider.SkippedChange += new EventHandler<SkippedChangeEventArgs>(OnSkippedChange);

                // Use SyncCallbacks for conflicting items.
                SyncCallbacks destinationCallbacks = destinationProvider.DestinationCallbacks;
                destinationCallbacks.ItemConflicting += new EventHandler<ItemConflictingEventArgs>(OnItemConflicting);
                destinationCallbacks.ItemConstraint += new EventHandler<ItemConstraintEventArgs>(OnItemConstraint);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider = sourceProvider;
                agent.RemoteProvider = destinationProvider;
                agent.Direction = SyncDirectionOrder.Upload; // Upload changes from the source to the destination.

                //Console.WriteLine("Synchronizing changes to replica: " + destinationProvider.RootDirectoryPath);
                if (logger != null)
                {
                    logger.Info("Synchronizing changes to replica: " + destinationProvider.RootDirectoryPath);
                }
                agent.Synchronize();
            }
            finally
            {
                // Release resources.
                if (sourceProvider != null) sourceProvider.Dispose();
                if (destinationProvider != null) destinationProvider.Dispose();
            }
        }
Example #47
0
 //This is our way of abstracting out this dependency since I'm sure it probably ties
 // us to the filesystem.
 private FileSyncProvider createFileSyncProvider(Guid replicaId, string replicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options)
 {
     var provider = new FileSyncProvider(replicaId, replicaRootPath, filter, options);
     return provider;
 }
Example #48
0
        //public static void DetectChangesOnFileSystemReplica(
        //string replicaRootPath,
        //FileSyncScopeFilter filter, FileSyncOptions options)
        //{
        //    FileSyncProvider provider = null;
        //    try
        //    {
        //        provider = new FileSyncProvider(replicaRootPath, filter, options);
        //        provider.DetectChanges();
        //    }
        //    finally
        //    {
        //        // Release resources
        //        if (provider != null)
        //            provider.Dispose();
        //    }
        //}
        public static void SyncFileSystemReplicasOneWay(
                string sourceReplicaRootPath, string destinationReplicaRootPath,
                FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(
                    sourceReplicaRootPath, filter, options);

                //filter.SubdirectoryExcludes.Add(@".\");

                destinationProvider = new FileSyncProvider(
                    destinationReplicaRootPath, filter, options);

                sourceProvider.AppliedChange +=
                    new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);
                sourceProvider.SkippedChange +=
                    new EventHandler<SkippedChangeEventArgs>(OnSkippedChange);

                sourceProvider.DetectChanges();

                sourceProvider.CopyingFile += (s, a) =>
                {
                    string file = a.FilePath;
                    int percent = a.PercentCopied;
                };
                sourceProvider.AppliedChange += (s, a) =>
                {
                    string file = a.NewFilePath;
                    var change = a.ChangeType;
                };
                sourceProvider.DetectedChanges += (s, a) =>
                {
                    //a.TotalDirectoriesFound
                };

                destinationProvider.CopyingFile += (s, a) =>
                {
                    string file = a.FilePath;
                    int percent = a.PercentCopied;
                    FileIO.FileTransferProgress(null, new FileTransferProgressEventArgs(percent, Path.GetFileName(file)));
                };
                destinationProvider.AppliedChange += (s, a) =>
                {
                    string file = a.NewFilePath;
                };
                destinationProvider.AppliedChange += (s, a) =>
                {
                    if (a.ChangeType == ChangeType.Delete) return;

                    string file = a.NewFilePath;
                    string serverPath = FileIO.GetPath(destinationReplicaRootPath) + file;
                    if (FileIO.IsDirectory(serverPath)) return;
                    FileIO.FinshedFileTransfer(null, new FinshedFileTransferEventArgs(Path.GetFileName(serverPath)));
                    string localDirectory = FileIO.GetPath(FileIO.GetPath(sourceReplicaRootPath) + file);
                    string localFile = localDirectory + Path.GetFileName(file);
                    string topLevelDir = FileIO.GetPath(sourceReplicaRootPath) + FileIO.GetTopLevelFolder(file);
                    try
                    {
                        File.Delete(localFile);
                    }
                    catch (Exception ex) { Logging.Log(ex.Message); }

                    if (topLevelDir == FileIO.GetPath(sourceReplicaRootPath)) return;
                   //bool isMoreTransfers = filter.FileNameIncludes.Any(x => Directory.GetFiles(localDirectory, x) != null);
                    foreach(string filterVal in filter.FileNameIncludes)
                    {
                        if (Directory.EnumerateFiles(topLevelDir, filterVal, SearchOption.AllDirectories).Count() > 0) return;
                    }

                    //if (isMoreTransfers) return;

                    try
                    {
                        FileIO.ForceDeleteDirectory(topLevelDir);
                    }
                    catch (Exception ex) { Logging.Log(ex.Message); }
                };

                //SyncOrchestrator agent = new SyncOrchestrator();
                _agent.LocalProvider = sourceProvider;
                _agent.RemoteProvider = destinationProvider;
                _agent.Direction = SyncDirectionOrder.Upload;

                Logging.Log("Synchronizing changes to replica: " +
                    destinationProvider.RootDirectoryPath);

                _agent.StateChanged += (s, a) =>
                {
                    if (a.OldState == SyncOrchestratorState.Uploading && a.NewState == SyncOrchestratorState.Ready)
                    {
                        string path = FileIO.GetPath(destinationReplicaRootPath);
                        string metadataFile = path + _metadataFile;

                        try
                        {
                            Logging.Log("Syncronization complete, cleanning up...");
                            File.Delete(metadataFile);
                            foreach (string tmpFile in Directory.EnumerateFiles(path, "*.tmp"))
                            {
                                File.Delete(tmpFile);
                            }
                            //FileSync.WatchFileSystem(sourceReplicaRootPath, destinationReplicaRootPath);
                        }
                        catch (Exception ex)
                        {
                            Logging.LogError(ex.Message);
                        }

                    }
                };
                _agent.SessionProgress += (s, a) =>
                {
                    uint p = a.CompletedWork;
                };
                _agent.Synchronize();
                //keep background worker alive
                //while (true) { };
            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message);
            }
            finally
            {
                // Release resources
                if (sourceProvider != null) sourceProvider.Dispose();
                if (destinationProvider != null) destinationProvider.Dispose();
                //if (_agent != null) _agent.Cancel(); _agent = null;
            }
        }
Example #49
0
        //public static void SyncFileSystemReplicasOneWay(string sourceReplicaRootPath, string destinationReplicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options, string metadataPath1, string metadataFile1, string metadataPath2, string metadataFile2, string tempDir = null, string trashDir = null)
        //{
        //    FileSyncProvider sourceProvider = null;
        //    FileSyncProvider destProvider = null;
        //    try
        //    {
        //        sourceProvider = new FileSyncProvider(sourceReplicaRootPath, filter, options);
        //        destProvider = new FileSyncProvider(destinationReplicaRootPath, filter, options);

        //        sourceProvider.DetectChanges();
        //        destProvider.DetectChanges();

        //        //启动和控制同步会话。
        //        SyncOrchestrator agent = new SyncOrchestrator();
        //        agent.LocalProvider = sourceProvider;
        //        agent.RemoteProvider = destProvider;
        //        agent.Direction = SyncDirectionOrder.Upload;

        //        agent.Synchronize();    //此处开始执行文件(夹)同步。
        //    }
        //    finally
        //    {
        //        if (sourceProvider != null) sourceProvider.Dispose();
        //        if (destProvider != null) destProvider.Dispose();
        //    }
        //}

        public static void SyncFileSystemReplicasOneWay(string sourceReplicaRootPath, string destinationReplicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options, string metadataPath1, string metadataFile1, string metadataPath2, string metadataFile2, string tempDir, string trashDir,
                                                        ref SyncOperationStatistics syncOperationStatistics)
        {
            FileSyncProvider sourceProvider      = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                sourceProvider      = new FileSyncProvider(sourceReplicaRootPath, filter, options, metadataPath1, metadataFile1, tempDir, trashDir);
                destinationProvider = new FileSyncProvider(destinationReplicaRootPath, filter, options, metadataPath2, metadataFile2, tempDir, trashDir);

                //destinationProvider.AppliedChange += new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);
                //destinationProvider.SkippedChange += new EventHandler<SkippedChangeEventArgs>(OnSkippedChange);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = sourceProvider;
                agent.RemoteProvider = destinationProvider;
                agent.Direction      = SyncDirectionOrder.Upload; // Sync source to destination
                Console.WriteLine("Synchronizing changes to replica: " + destinationProvider.RootDirectoryPath);
                syncOperationStatistics = agent.Synchronize();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                // Release resources
                if (sourceProvider != null)
                {
                    sourceProvider.Dispose();
                }
                if (destinationProvider != null)
                {
                    destinationProvider.Dispose();
                }
            }
        }
Example #50
0
        public static void OneWaySyncFileSystemReplicas(string sourceReplicaRootPath, string destinationReplicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider path1Provider = null;
            FileSyncProvider path2Provider = null;

            try
            {
                path1Provider = new FileSyncProvider(sourceReplicaRootPath, filter, options);
                path2Provider = new FileSyncProvider(destinationReplicaRootPath, filter, options);

                path2Provider.SkippedChange += OnSkippedChange;
                path2Provider.AppliedChange += OnAppliedChange;

                SyncOrchestrator manager = new SyncOrchestrator();
                manager.LocalProvider = path1Provider;
                manager.RemoteProvider = path2Provider;
                manager.Direction = SyncDirectionOrder.Upload;
                manager.Synchronize();
            }
            finally
            {
                if (path1Provider != null)
                    path1Provider.Dispose();
                if (path2Provider != null)
                    path2Provider.Dispose();
            }
        }