Esempio n. 1
0
        protected override void SynchronizeSyncScope(string syncScope, SyncDirectionOrder synDirection, KnowledgeSyncProvider localProvider, KnowledgeSyncProvider remoteProvider)
        {
            // Create the sync orchestrator
            SyncOrchestrator orchestrator = new SyncOrchestrator();

            // Set local provider of orchestrator to a sync provider associated with the sync scope in the client database
            orchestrator.LocalProvider = localProvider;
            // Set remote provider of orchestrator to a sync provider associated with the sync scope in the server database
            orchestrator.RemoteProvider = remoteProvider;
            // Set the direction of sync session
            orchestrator.Direction = synDirection;

            // Use sync-callbacks for conflicting items
            SyncCallbacks destCallbacks = ((KnowledgeSyncProvider)orchestrator.RemoteProvider).DestinationCallbacks;

            destCallbacks.ItemConflicting += new EventHandler <ItemConflictingEventArgs>(OnItemConfliting);
            destCallbacks.ItemConstraint  += new EventHandler <ItemConstraintEventArgs>(OnItemConstraint);

            // Subcribe for errors that occur when applying changes to the client
            ((SqlSyncProvider)orchestrator.LocalProvider).ApplyChangeFailed += new EventHandler <DbApplyChangeFailedEventArgs>(OnApplyChangeFailed);
            ((SqlSyncProvider)orchestrator.LocalProvider).ChangesApplied    += new EventHandler <DbChangesAppliedEventArgs>(OnChangesApplied);

            // Execute the synchronize process
            SyncOperationStatistics syncStats = orchestrator.Synchronize();

            // Notify a synchronization took place
            DbSynchronizedEventArgs ev = new DbSynchronizedEventArgs(syncStats);

            OnSynchronized(orchestrator, ev);

            destCallbacks.ItemConflicting -= new EventHandler <ItemConflictingEventArgs>(OnItemConfliting);
            destCallbacks.ItemConstraint  -= new EventHandler <ItemConstraintEventArgs>(OnItemConstraint);
            ((SqlSyncProvider)orchestrator.LocalProvider).ApplyChangeFailed -= new EventHandler <DbApplyChangeFailedEventArgs>(OnApplyChangeFailed);
        }
Esempio n. 2
0
        public static void Synchronize(EndpointAddress remoteAddress)
        {
            SyncServiceClient serviceClient = serviceProxy(remoteAddress);

            downloadDatabase(serviceClient);

            using (var localDbConnection = new SqlCeConnection(Constants.LocalConnectionString))
            {
                using (var remoteDbConnection = new SqlCeConnection(Constants.RemoteConnectionString))
                {
                    var syncOrchestrator = new SyncOrchestrator
                    {
                        Direction      = SyncDirectionOrder.DownloadAndUpload,
                        RemoteProvider =
                            new SqlCeSyncProvider("SyncScope", remoteDbConnection),
                        LocalProvider = new SqlCeSyncProvider("SyncScope", localDbConnection)
                    };

                    syncOrchestrator.Synchronize();

                    uploadDatabase(serviceClient);
                }
            }

            ContactsManager.Current.RefreshCache();
            CompaniesManager.Current.RefreshCache();
        }
Esempio n. 3
0
        public void Run()
        {
            var syncOrchestrator = new SyncOrchestrator();

            var localProvider  = new SqlSyncProvider(configuration.ScopeName, configuration.ClientSqlConnection);
            var remoteProvider = new SqlSyncProvider(configuration.ScopeName, configuration.ServerSqlConnection);

            localProvider.ChangesSelected  += new EventHandler <DbChangesSelectedEventArgs>(localProvider_ChangesSelected);
            remoteProvider.ChangesSelected += new EventHandler <DbChangesSelectedEventArgs>(remoteProvider_ChangesSelected);

            syncOrchestrator.LocalProvider  = localProvider;
            syncOrchestrator.RemoteProvider = remoteProvider;

            syncOrchestrator.Direction = SyncDirectionOrder.UploadAndDownload;


            //((SqlSyncProvider)syncOrchestrator.RemoteProvider).SyncProgress += new EventHandler<DbSyncProgressEventArgs>(serverSyncProvider_SyncProgress);
            //((SqlSyncProvider)syncOrchestrator.LocalProvider).SyncProgress += new EventHandler<DbSyncProgressEventArgs>(clientSyncProvider_SyncProgress);

            ((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler <DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);


            Console.WriteLine("Start Time: " + DateTime.Now);
            var syncStats = syncOrchestrator.Synchronize();

            // print statistics
            //Console.WriteLine("Start Time: " + syncStats.SyncStartTime);
            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);
            Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);
            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);
            Console.WriteLine(String.Empty);
        }
Esempio n. 4
0
        static SyncOperationStatistics sync(string scope, SyncDirectionOrder order)
        {
            using (SqlSyncProvider masterProvider = new SqlSyncProvider { ScopeName = scope },
                     slaveProvider = new SqlSyncProvider { ScopeName = scope })
            {
                using (SqlConnection master = new SqlConnection(Settings.Default.ServerConnectionString),
                                     slave = new SqlConnection(Settings.Default.ClientConnectionString))
                {
                    masterProvider.Connection = master;
                    slaveProvider.Connection = slave;

                    SyncOrchestrator orchestrator = new SyncOrchestrator
                    {
                        LocalProvider = slaveProvider,
                        RemoteProvider = masterProvider,
                        Direction = order
                    };
                    if (scope == "OneWay")
                    {
                        slaveProvider.ApplyChangeFailed += new EventHandler<Microsoft.Synchronization.Data.DbApplyChangeFailedEventArgs>(slaveProvider_ApplyChangeFailed);
                    }
                    try
                    {
                        SyncOperationStatistics stats = orchestrator.Synchronize();
                        return stats;
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine(ex.Message);
                        return null;
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            //create a connection to the second compact database
            SqlCeConnection clientConn = new SqlCeConnection(@"Data Source='C:\VisualStudioProjects\SyncSQLServerAndSQLCompact\ClientSQLCompactDB\SyncCompactDB2.sdf'");

            //create connection to the server database
            SqlConnection serverConn = new SqlConnection("Data Source=localhost; Initial Catalog=SyncDB; Integrated Security=True");

            // create a sync orchestrator
            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();

            // set the local provider to a CE sync provider associated with the
            // ProductsScope in the Sync Compact DB 2 database
            syncOrchestrator.LocalProvider = new SqlCeSyncProvider("ProductsScope", clientConn);

            // set the remote provider to a server sync provider associated with the
            // ProductsScope in the Sync DB server database
            syncOrchestrator.RemoteProvider = new SqlSyncProvider("ProductsScope", serverConn);

            // set the diretion to Upload and Download
            syncOrchestrator.Direction = SyncDirectionOrder.UploadAndDownload;

            // subscribe for errors that occur when applying changes to the client
            ((SqlCeSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler <DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);

            // execute the synchronization process
            SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();

            //print sync statistics
            Console.WriteLine("Start Time: " + syncStats.SyncStartTime);
            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);
            Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);
            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);
            Console.WriteLine(String.Empty);
        }
Esempio n. 6
0
        public void Synchronize(SyncDirectionOrder directionOrder)
        {
            SqlConnection remoteConnection = new SqlConnection(RemoteConfiguration.ConnectionString);
            SqlConnection localConnection  = new SqlConnection(LocalConfiguration.ConnectionString);

            _orchestrator = new SyncOrchestrator();

            _orchestrator.LocalProvider  = new SqlSyncProvider(LocalConfiguration.ScopeName, localConnection, LocalConfiguration.ObjectPrefix, LocalConfiguration.ObjectSchema);
            _orchestrator.RemoteProvider = new SqlSyncProvider(RemoteConfiguration.ScopeName, remoteConnection, RemoteConfiguration.ObjectPrefix, RemoteConfiguration.ObjectSchema);

            _orchestrator.Direction = directionOrder;

            if (RemoteChangesSelected != null)
            {
                ((SqlSyncProvider)_orchestrator.RemoteProvider).ChangesSelected += RemoteChangesSelected;
            }
            ((SqlSyncProvider)_orchestrator.RemoteProvider).CommandTimeout = 0;
            if (ApplyLocalChangesFailed != null)
            {
                ((SqlSyncProvider)_orchestrator.LocalProvider).ApplyChangeFailed += ApplyLocalChangesFailed;
            }
            ((SqlSyncProvider)_orchestrator.LocalProvider).CommandTimeout = 0;

            ((SqlSyncProvider)_orchestrator.RemoteProvider).ChangesSelected += DbSynchronizer_ChangesSelected;

            SyncOperationStatistics syncStats = _orchestrator.Synchronize();

            Log("Начало синхронизации: " + syncStats.SyncStartTime);
            Log("Changes Uploaded: " + syncStats.UploadChangesTotal);
            Log("Changes Downloaded: " + syncStats.DownloadChangesTotal);
            Log("Окончание синхронизации: " + syncStats.SyncEndTime);
            Log(string.Empty);
            _orchestrator = null;
        }
Esempio n. 7
0
        public static SyncOrchestrator CreateAgent(
            FileSyncProvider sourceProvider,
            FileSyncProvider destinationProvider
            )
        {
            sourceProvider.AppliedChange += OnAppliedChange;
            sourceProvider.SkippedChange += OnSkippedChange;

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

            var agent = new SyncOrchestrator();

            agent.LocalProvider  = sourceProvider;
            agent.RemoteProvider = destinationProvider;
            agent.Direction      =
                SyncDirectionOrder.DownloadAndUpload
                //SyncDirectionOrder.Upload // Sync source to destination
            ;

            Console.WriteLine(
                "Synchronizing changes between {0} <-> {1}",
                sourceProvider.RootDirectoryPath,
                destinationProvider.RootDirectoryPath
                );

            return
                (agent);
        }
Esempio n. 8
0
        public static void synchronize()
        {
            string s2 = str[1];
            string st = folderA + "\\" + s2;

            try
            {
                FileSyncProvider providerA = new FileSyncProvider(Guid.NewGuid(), st);
                FileSyncProvider providerB = new FileSyncProvider(Guid.NewGuid(), s);

                // Ask providers to detect changes
                providerA.DetectChanges();
                providerB.DetectChanges();

                // Sync changes
                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = providerA;
                agent.RemoteProvider = providerB;
                agent.Direction      = SyncDirectionOrder.UploadAndDownload;
                agent.Synchronize();
                Console.WriteLine("Files are  synchronized");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        static void Main(string[] args)
        {
            //<snippetOCSv2_CS_Basic_NTier_SyncOrchestrator>
            KnowledgeSyncProvider localProvider;
            KnowledgeSyncProvider remoteProvider;

            string localConnection = @"Data Source = localhost; Initial Catalog = SyncSamplesDb_Peer1; " +
                                     "Integrated Security = True";
            string remoteConnection = @"http://localhost:8000/Sync/SyncService";
            string scopeName        = "Sales";

            SampleSyncProvider sampleSyncProvider = new SampleSyncProvider();

            localProvider  = sampleSyncProvider.SetupSyncProvider(scopeName, localConnection);
            remoteProvider = new SyncProxy(scopeName, remoteConnection);

            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();

            syncOrchestrator.LocalProvider  = localProvider;
            syncOrchestrator.RemoteProvider = remoteProvider;

            syncOrchestrator.Direction = SyncDirectionOrder.Download;
            syncOrchestrator.Synchronize();
            //</snippetOCSv2_CS_Basic_NTier_SyncOrchestrator>
        }
Esempio n. 10
0
        public void Synchronize(SyncDirectionOrder syncDirection, KnowledgeSyncProvider localProvider, KnowledgeSyncProvider remoteProvider, uint batchSize)
        {
            FileStoreSync fileStoreSync = localProvider as FileStoreSync;

            fileStoreSync.RequestedBatchSize = batchSize;
            ((FileStoreProxy)remoteProvider).RequestedBatchSize = batchSize;

            // Use sync-callbacks for conflicting items
            SyncCallbacks destCallbacks = localProvider.DestinationCallbacks;

            destCallbacks.ItemConflicting += new EventHandler <ItemConflictingEventArgs>(OnItemConflicting);
            destCallbacks.ItemConstraint  += new EventHandler <ItemConstraintEventArgs>(OnItemConstraint);

            localProvider.Configuration.ConflictResolutionPolicy  = ConflictResolutionPolicy.SourceWins;
            remoteProvider.Configuration.ConflictResolutionPolicy = ConflictResolutionPolicy.SourceWins;

            // Initiate orchestrator and sync
            SyncOrchestrator orchestrator = new SyncOrchestrator();

            orchestrator.LocalProvider  = localProvider;
            orchestrator.RemoteProvider = remoteProvider;

            // Set sync direction
            orchestrator.Direction = syncDirection;
            // Execute the synchronize process
            SyncOperationStatistics syncStats = orchestrator.Synchronize();

            // Notify a synchronization took place
            FileSystemSynchronizedEventArgs ev = new FileSystemSynchronizedEventArgs(syncStats);

            OnSynchronized(orchestrator, ev);
        }
        public async Task Clone_CloneGraphSyncsMutateOnCloneCalled()
        {
            await SyncOrchestrator.Clone(ContentItem);

            A.CallTo(() => CloneGraphSync.MutateOnClone(ContentItem, ContentManager, null))
            .MustHaveHappened();
        }
        public void Synchronize()
        {
            LogUtilities.LogTracingLevels();

            var clientSyncProvider = new SqlSyncProvider("FullScope", SqlConnectionFactory.DefaultClientConnection);
            clientSyncProvider.ApplyChangeFailed += ClientApplyChangeFailed;
            clientSyncProvider.ChangesSelected += ClientSyncProviderOnChangesSelected;

            var serverSyncProvider = new SqlSyncProvider("FullScope", SqlConnectionFactory.DefaultServerConnection);
            serverSyncProvider.ApplyChangeFailed += ServerApplyChangeFailed;
            serverSyncProvider.ChangesSelected += ServerSyncProviderOnChangesSelected;
            // create the sync orhcestrator
            var syncOrchestrator = new SyncOrchestrator
            {
                LocalProvider = clientSyncProvider,
                RemoteProvider = serverSyncProvider,
                Direction = SyncDirectionOrder.UploadAndDownload
            };
            // execute the synchronization process
            var syncStats = syncOrchestrator.Synchronize();

            //TODO: einzelne Spalten synchronisierbar?

            // print statistics
            Console.WriteLine("Start Time: " + syncStats.SyncStartTime);
            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);
                // Changes from Client to Server (LocalSyncProvider to RemoteSyncProvider)
            Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);
                // Changes from Server to Client (RemoteSyncProvider to LocalSyncProvider)
            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);
            Console.WriteLine(string.Empty);
            Console.ReadLine();
        }
 private static void Synchronize(string scopeName,
                                 string serverConnectionString,
                                 string clientConnectionString, SyncDirectionOrder syncDirectionOrder)
 {
     try
     {
         using (SqlConnection serverConnection = new
                                                 SqlConnection(serverConnectionString))
         {
             using (SqlConnection clientConnection
                        = new SqlConnection(clientConnectionString))
             {
                 var agent = new SyncOrchestrator
                 {
                     LocalProvider = new
                                     SqlSyncProvider(scopeName, clientConnection),
                     RemoteProvider = new SqlSyncProvider(scopeName, serverConnection),
                     Direction      = syncDirectionOrder
                 };
                 (agent.RemoteProvider as RelationalSyncProvider).SyncProgress +=
                     new EventHandler <DbSyncProgressEventArgs>
                         (dbProvider_SyncProgress);
                 (agent.LocalProvider as RelationalSyncProvider).ApplyChangeFailed +=
                     new EventHandler <DbApplyChangeFailedEventArgs>(dbProvider_SyncProcessFailed);
                 (agent.RemoteProvider as RelationalSyncProvider).ApplyChangeFailed += new EventHandler <DbApplyChangeFailedEventArgs>
                                                                                           (dbProvider_SyncProcessFailed);
                 agent.Synchronize();
             }
         }
     }
     catch (Exception ex)
     {
         Common.WriteLog(System.DateTime.Now.ToString() + ": " + ex.ToString());
     }
 }
        public static void Synchronize(EndpointAddress remoteAddress)
        {
            SyncServiceClient serviceClient = serviceProxy(remoteAddress);

            downloadDatabase(serviceClient);

            using (var localDbConnection = new SqlCeConnection(Constants.LocalConnectionString))
            {
                using (var remoteDbConnection = new SqlCeConnection(Constants.RemoteConnectionString))
                {
                    var syncOrchestrator = new SyncOrchestrator
                                               {
                                                   Direction = SyncDirectionOrder.DownloadAndUpload,
                                                   RemoteProvider =
                                                       new SqlCeSyncProvider("SyncScope", remoteDbConnection),
                                                   LocalProvider = new SqlCeSyncProvider("SyncScope", localDbConnection)
                                               };

                    syncOrchestrator.Synchronize();

                    uploadDatabase(serviceClient);
                }
            }

            ContactsManager.Current.RefreshCache();
            CompaniesManager.Current.RefreshCache();
        }
Esempio n. 15
0
        private void m_constructPipelinesBW_DoWork(object sender, DoWorkEventArgs e)
        {
            bool constructPipelines = (bool)e.Argument;

            // 3 ways to get here:
            // 1. open existing config
            // 2. start existing config
            // 3. automated testing
            if (constructPipelines && !m_constructedPipelineId.Equals(Config.SessionGroupUniqueId))
            {
                // 3 ways to get here:
                // 1. open existing config that has been run before
                // 2. start existing config for the first time
                // 3. automated testing
                try
                {
                    Sync = new SyncOrchestrator(Config);
                    Sync.ConstructPipelines();

                    if (ShellViewModel != null)
                    {
                        ShellViewModel.LoadConflictTypes();
                    }
                    m_constructedPipelineId = Config.SessionGroupUniqueId;
                }
                catch (Exception ex)
                {
                    e.Result = (object)ex;
                }
            }
        }
Esempio n. 16
0
        public static void Synchronize(string sqlConnectionString)
        {
            bool isScopeExists = ScopeHelper.CheckScope(sqlConnectionString, true);

            if (!isScopeExists)
            {
                ScopeHelper.CreateScope(sqlConnectionString, true);
            }

            using (var localDbConnection = new SqlCeConnection(Constants.LocalConnectionString))
                using (var remoteDbConnection = new SqlConnection(sqlConnectionString))
                {
                    var syncOrchestrator = new SyncOrchestrator
                    {
                        Direction      = SyncDirectionOrder.DownloadAndUpload,
                        RemoteProvider =
                            new SqlSyncProvider("SyncScope", remoteDbConnection),
                        LocalProvider = new SqlCeSyncProvider("SyncScope", localDbConnection)
                    };

                    syncOrchestrator.Synchronize();
                }

            ContactsManager.Current.RefreshCache();
            CompaniesManager.Current.RefreshCache();
        }
Esempio n. 17
0
        private void ReplicarAmbitos(SyncOrchestrator orchestrator, List <DbSyncScopeDescription> Ambitos, ParametrosReplica parametrosReplica) //int timeOut, uint tamañoDeCache)
        {
            foreach (DbSyncScopeDescription ambito in Ambitos)
            {
                //////////////// PROVEEDORES DE REPLICA (CONOCEN LA LOGICA DEL MOTOR DE DATOS A REPLICAR)  ////////////////
                SqlSyncProvider proveedorLocal  = this.ObtenerProveedor(ambito.ScopeName, conexionLocalSql, parametrosReplica.tamañoDeCache, parametrosReplica.TamañoDeTransaccion);
                SqlSyncProvider proveedorRemoto = this.ObtenerProveedor(ambito.ScopeName, conexionRemotoSql, parametrosReplica.tamañoDeCache, parametrosReplica.TamañoDeTransaccion);

                proveedorLocal.CommandTimeout  = parametrosReplica.TimeOut;
                proveedorRemoto.CommandTimeout = parametrosReplica.TimeOut;

                orchestrator.LocalProvider  = proveedorLocal;
                orchestrator.RemoteProvider = proveedorRemoto;

                try
                {
                    bool replicar    = true;
                    int  anclaActual = this.ObtenerAnclaActual();
                    if (parametrosReplica.ReplicarSoloAmbitosconCambios)
                    {
                        replicar = this.ElAmbitoTieneNovedades(ambito);
                    }
                    if (replicar)
                    {
                        SyncOperationStatistics statsUpload = orchestrator.Synchronize();
                        this.loguearEstadisticas(statsUpload, ambito);
                        this.ActualizarAnclaDeSincronizacion(anclaActual, ambito);
                    }
                }
                catch (Exception error)
                {
                    this.loguear("Error al replicar el ambito: " + ambito.ScopeName + " Error: " + error.ToString());
                }
            }
        }
Esempio n. 18
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();
        }
    }
Esempio n. 19
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();
                }
            }
        }
Esempio n. 20
0
        public static void Sync()
        {
            SqlConnection serverConn = new SqlConnection(sServerConnection);

            SqlConnection clientConn = new SqlConnection(sClientConnection);

            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();

            syncOrchestrator.LocalProvider = new SqlSyncProvider(sScope, clientConn);

            syncOrchestrator.RemoteProvider = new SqlSyncProvider(sScope, serverConn);

            syncOrchestrator.Direction = SyncDirectionOrder.Upload;

            ((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler <DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);

            SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();

            Console.WriteLine("Start Time: " + syncStats.SyncStartTime);

            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);

            //Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);

            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);

            Console.WriteLine(String.Empty);

            Console.ReadLine();
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="errRegService"></param>
        /// <param name="reportingSettings"></param>
        /// <param name="syncOrchestrator"></param>
        public ErrorRoutingAlgorithm(
            ErrorRegistrationService errRegService,
            BM.ReportingSettings reportingSettings,
            SyncOrchestrator syncOrchestrator)
        {
            m_errRegService     = errRegService;
            m_reportingSettings = reportingSettings;

            // add default EventLog Channel
            m_routingChannels.Add(new EventLogChannel());
            m_routingChannels.Add(new TraceLogChannel());

            if (null != m_reportingSettings &&
                (reportingSettings.EnableDebugAssertion ||
                 reportingSettings.ReportingLevel >= (int)ReportingLevel.RaiseDebugAssertion))
            {
                // configured to add DebugAssertion Channel
                // todo: remove this when we want to cleanly rely on build flavor to enable
                // debug failure
                m_routingChannels.Add(new DebugAssertChannel());
            }

            bool blockingSessionEnabledByDefault =
                (null != m_reportingSettings && reportingSettings.ReportingLevel >= (int)ReportingLevel.BlockSessionGroup);

            m_routingChannels.Add(new BlockingSessionGroupChannel(syncOrchestrator, blockingSessionEnabledByDefault));
        }
Esempio n. 22
0
        static void DoSync(KnowledgeSyncProvider providerNameA, KnowledgeSyncProvider providerNameB, SyncDirectionOrder syncOrder)
        {
            SyncOperationStatistics stats;

            // Set the provider's conflict resolution policy since we are doing remote sync, we don't
            // want to see callbacks.
            providerNameA.Configuration.ConflictResolutionPolicy = ConflictResolutionPolicy.DestinationWins;
            providerNameB.Configuration.ConflictResolutionPolicy = ConflictResolutionPolicy.DestinationWins;

            //Sync providers
            Console.WriteLine("Sync A -{0} and B -{1}...", providerNameA.ToString(), providerNameB.ToString());
            SyncOrchestrator agent = new SyncOrchestrator();

            agent.Direction      = syncOrder;
            agent.LocalProvider  = providerNameA;
            agent.RemoteProvider = providerNameB;
            stats = agent.Synchronize();

            // Display the SyncOperationStatistics
            Console.WriteLine("Download Applied:\t {0}", stats.DownloadChangesApplied);
            Console.WriteLine("Download Failed:\t {0}", stats.DownloadChangesFailed);
            Console.WriteLine("Download Total:\t\t {0}", stats.DownloadChangesTotal);
            Console.WriteLine("Upload Total:\t\t {0}", stats.UploadChangesApplied);
            Console.WriteLine("Upload Total:\t\t {0}", stats.UploadChangesFailed);
            Console.WriteLine("Upload Total:\t\t {0}", stats.UploadChangesTotal);

            //Show the results of sync
        }
Esempio n. 23
0
 public Synchronizer(string destinationDeviceRoot, IEnumerable <FileSource> groups, long maxInKilobytes)
 {
     _groups         = groups;
     _maxInKilobytes = maxInKilobytes;
     SetDestinationFolderPath(destinationDeviceRoot);
     _agent = new SyncOrchestrator();
 }
Esempio n. 24
0
        public AzureSynchronizer(RemoteInfo ri, string container, SynchronizeDirection syncDirection)
        {
            disposed = false;
            string _containerName = container;

            //
            // Setup Store and Provider
            //
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentialsAccountAndKey(ri.accountName, ri.accountKey), true);
            AzureBlobStore      blobStore      = new AzureBlobStore(_containerName, storageAccount);

            Console.WriteLine("Successfully created/attached to container {0}.", _containerName);
            AzureBlobSyncProvider azureProvider = new AzureBlobSyncProvider(_containerName, blobStore);

            azureProvider.ApplyingChange += new EventHandler <ApplyingBlobEventArgs>(UploadingFile);

            orchestrator = new SyncOrchestrator();
            orchestrator.RemoteProvider = azureProvider;

            if (syncDirection == SynchronizeDirection.Upload)
            {
                orchestrator.Direction = SyncDirectionOrder.Upload;
            }
            else if (syncDirection == SynchronizeDirection.Download)
            {
                orchestrator.Direction = SyncDirectionOrder.Download;
            }
        }
Esempio n. 25
0
        public SyncOperationStatistics Sync()
        {
            SyncOperationStatistics statistics = null;
            try
            {

                SyncOrchestrator orch = new SyncOrchestrator
                {
                    LocalProvider = new SqlSyncProvider(_scopeName, _sqlServerConn),
                    RemoteProvider = new SqlSyncProvider(_scopeName, _sqlAzureConn),
                    Direction = SyncDirectionOrder.UploadAndDownload
                };


                 statistics = orch.Synchronize();

            }
            catch (Exception)
            {
                _sqlServerConn.Close();
                _sqlAzureConn.Close();
                return statistics;
            }

            _sqlServerConn.Close();
            _sqlAzureConn.Close();
            return statistics;

        }
Esempio n. 26
0
        public void Synchronize(SyncDirectionOrder syncDirection, KnowledgeSyncProvider localProvider, KnowledgeSyncProvider remoteProvider)
        {
            // Register event handlers
            FileSyncProvider fileSyncProvider = localProvider as FileSyncProvider;

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

            // Use sync-callbacks for conflicting items
            SyncCallbacks destCallbacks = localProvider.DestinationCallbacks;

            destCallbacks.ItemConflicting += new EventHandler <ItemConflictingEventArgs>(OnItemConflicting);
            destCallbacks.ItemConstraint  += new EventHandler <ItemConstraintEventArgs>(OnItemConstraint);

            // Initiate orchestrator and sync
            SyncOrchestrator orchestrator = new SyncOrchestrator();

            orchestrator.LocalProvider  = localProvider;
            orchestrator.RemoteProvider = remoteProvider;

            // Set sync direction
            orchestrator.Direction = syncDirection;
            // Execute the synchronize process
            SyncOperationStatistics syncStats = orchestrator.Synchronize();

            // Notify a synchronization took place
            FileSystemSynchronizedEventArgs ev = new FileSystemSynchronizedEventArgs(syncStats);

            OnSynchronized(orchestrator, ev);
        }
Esempio n. 27
0
        public override void _sync(object input)
        {
            DiskService other        = (DiskService)input;
            var         diskSettings = this.DeployerSettings.castTo <DiskServiceSettings>();
            var         storage      = this.GlobalSettings.GetDefaultContentStorage();

            // Generate a unique virtual disk for this application
            DiskServiceSettings otherSettings = other.DeployerSettings.castTo <DiskServiceSettings>();

            foreach (var mount in diskSettings.mounts)
            {
                string           pathOri  = UtilsSystem.EnsureDirectoryExists(other.Deployment.GetRuntimeSettingsToDeploy()["services." + otherSettings.id + ".mount.files.path"]);
                string           pathDest = UtilsSystem.EnsureDirectoryExists(this.Deployment.GetRuntimeSettingsToDeploy()["services." + diskSettings.id + ".mount.files.path"]);
                FileSyncProvider ori      = new FileSyncProvider(pathOri);
                FileSyncProvider dest     = new FileSyncProvider(pathDest);

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = ori;
                agent.RemoteProvider = dest;
                agent.Direction      = SyncDirectionOrder.Upload;

                SyncOperationStatistics syncStats = agent.Synchronize();
                this.Logger.LogInfo(
                    true,
                    "Synchronization stats \n\n local provider {0} to remote {1}\n upload changes applied {2}\n {3} upload changes failed",
                    pathOri,
                    pathDest,
                    syncStats.UploadChangesApplied,
                    syncStats.UploadChangesFailed);
                ori.Dispose();
                dest.Dispose();
            }
        }
 private void Initialize(
     BM.ErrorManagement configuration,
     SyncOrchestrator syncOrchestrator)
 {
     m_errRegService    = new ErrorRegistrationService(configuration.ErrorRouters);
     m_routingAlgorithm = new ErrorRoutingAlgorithm(m_errRegService, configuration.ReportingSettings, syncOrchestrator);
     m_syncOrchestrator = syncOrchestrator;
 }
Esempio n. 29
0
        // Main sync happens here
        private static void SynchronizeOnce(
            FileSyncScopeFilter filter,
            string localPathName,
            string containerName,
            CloudStorageAccount storageAccount)
        {
            // Setup Provider
            AzureBlobStore blobStore = new AzureBlobStore(containerName, storageAccount);

            AzureBlobSyncProvider azureProvider = new AzureBlobSyncProvider(containerName, blobStore);

            azureProvider.ApplyingChange += new EventHandler <ApplyingBlobEventArgs>(UploadingFile);

            FileSyncProvider fileSyncProvider = null;

            if (filter == null)
            {
                try
                {
                    fileSyncProvider = new FileSyncProvider(localPathName);
                }
                catch (ArgumentException)
                {
                    fileSyncProvider = new FileSyncProvider(Guid.NewGuid(), localPathName);
                }
            }
            else
            {
                try
                {
                    fileSyncProvider = new FileSyncProvider(localPathName, filter, FileSyncOptions.None);
                }
                catch (ArgumentException)
                {
                    fileSyncProvider = new FileSyncProvider(Guid.NewGuid(), localPathName, filter, FileSyncOptions.None);
                }
            }

            fileSyncProvider.ApplyingChange += new EventHandler <ApplyingChangeEventArgs>(WindowsAzureBlob2FileSystemSync.DownloadingFile);

            try
            {
                SyncOrchestrator orchestrator = new SyncOrchestrator();
                orchestrator.LocalProvider  = fileSyncProvider;
                orchestrator.RemoteProvider = azureProvider;
                orchestrator.Direction      = SyncDirectionOrder.DownloadAndUpload;

                orchestrator.Synchronize();
            }
            catch (Exception ex)
            {
                Trace.TraceError("Failed to Synchronize. Error: {0}", ex.Message);
            }
            finally
            {
                fileSyncProvider.Dispose();
            }
        }
Esempio n. 30
0
        /// <summary>
        ///     Syncronize 2 folders
        /// </summary>
        /// <param name="SourceFolder"></param>
        /// <param name="DestinationFolder"></param>
        public static void SyncFolders(string SourceFolder, string DestinationFolder)
        {
            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();


            syncOrchestrator.LocalProvider  = new FileSyncProvider(SourceFolder);
            syncOrchestrator.RemoteProvider = new FileSyncProvider(DestinationFolder);
            syncOrchestrator.Synchronize();
        }
Esempio n. 31
0
 public Synchronizer(string destinationFolderPath, IEnumerable <FileGroup> groups, long totalAvailableOnDeviceInKilobytes, IProgress progress)
 {
     _groups = groups;
     _totalAvailableOnDeviceInKilobytes = totalAvailableOnDeviceInKilobytes;
     Guard.AgainstNull(progress, "progress");
     _progress = progress;
     _agent    = new SyncOrchestrator();
     DestinationRootForThisUser = destinationFolderPath;
 }
Esempio n. 32
0
        private void syncButton_Click(object sender, EventArgs e)
        {
            using (SqlSyncProvider masterProvider = new SqlSyncProvider {
                ScopeName = this.scopeNameTextBox.Text
            }, slaveProvider = new SqlSyncProvider {
                ScopeName = this.scopeNameTextBox.Text
            })
            {
                using (SqlConnection master = new SqlConnection(Settings.Default.MasterConnectionString), slave = new SqlConnection(Settings.Default.SlaveConnectionString))
                {
                    string masterScopeConfig;
                    string slaveScopeConfig;

                    using (SqlCommand command = master.CreateCommand())
                    {
                        master.Open();
                        command.CommandText = string.Format("SELECT scope_config.config_data FROM scope_config INNER JOIN scope_info ON scope_config.config_id = scope_info.scope_config_id WHERE scope_info.sync_scope_name = N'{0}'", TableName);
                        masterScopeConfig   = command.ExecuteScalar() as string;
                        master.Close();
                    }

                    using (SqlCommand command = slave.CreateCommand())
                    {
                        slave.Open();
                        command.CommandText = string.Format("SELECT scope_config.config_data FROM scope_config INNER JOIN scope_info ON scope_config.config_id = scope_info.scope_config_id WHERE scope_info.sync_scope_name = N'{0}'", TableName);
                        slaveScopeConfig    = command.ExecuteScalar() as string;
                        slave.Close();
                    }

                    if (masterScopeConfig != slaveScopeConfig)
                    {
                        MessageBox.Show("The master scope does not match the slave scope", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    masterProvider.Connection = master;
                    slaveProvider.Connection  = slave;
                    SyncOrchestrator orchestrator = new SyncOrchestrator
                    {
                        LocalProvider  = slaveProvider,
                        RemoteProvider = masterProvider,
                        Direction      = SyncDirectionOrder.UploadAndDownload
                    };

                    try
                    {
                        SyncOperationStatistics stats = orchestrator.Synchronize();
                        MessageBox.Show("Downloaded: " + stats.DownloadChangesTotal + "Uploaded: " + stats.UploadChangesApplied, "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Sync Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Esempio n. 33
0
        static public SyncOperationStatistics MicrosoftSync(this SessionBase sessionToUpdate, SessionBase sessionToRead)
        {
            SyncProvider     sourceProvider = new SyncProvider(sessionToRead);
            SyncProvider     destProvider   = new SyncProvider(sessionToUpdate);
            SyncOrchestrator syncAgent      = new SyncOrchestrator();

            syncAgent.LocalProvider  = sourceProvider;
            syncAgent.RemoteProvider = destProvider;
            return(syncAgent.Synchronize());
        }
        public Task Clone_MergeGraphSyncerThrows_ExceptionPropagates()
        {
            A.CallTo(() => PreviewAllowSync.Result)
            .Returns(AllowSyncResult.Allowed);

            A.CallTo(() => PreviewMergeGraphSyncer.SyncToGraphReplicaSet())
            .Throws(() => new Exception());

            return(Assert.ThrowsAsync <Exception>(() => SyncOrchestrator.Clone(ContentItem)));
        }
Esempio n. 35
0
        private static void Run(SyncOrchestrator orchestrator)
        {
            var syncStats = orchestrator.Synchronize();

            Console.WriteLine("Start Time: " + syncStats.SyncStartTime);
            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);
            Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);
            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);
            Console.WriteLine(String.Empty);
        }
Esempio n. 36
0
        /// <summary>
        /// Replicates the <see cref="TVA.Historian.IArchive"/>.
        /// </summary>
        protected override void ReplicateArchive()
        {
            // Connect to remote share if specified.
            string archiveLocation = ArchiveLocation;
            string replicaLocation = ReplicaLocation;
            if (replicaLocation.StartsWith(@"\\") && replicaLocation.Contains(':') && replicaLocation.Contains('@'))
            {
                // Format: \\[<domain>\]<username>:<password>@<network share>
                string share = @"\\" + replicaLocation.Substring(replicaLocation.IndexOf('@') + 1);
                string login = replicaLocation.Substring(2, replicaLocation.IndexOf(':') - 2);
                string password = replicaLocation.Substring(replicaLocation.IndexOf(':') + 1, replicaLocation.IndexOf('@') - replicaLocation.IndexOf(':') - 1);

                replicaLocation = share;
                string[] loginParts = login.Split('\\');
                if (loginParts.Length == 2)
                    FilePath.ConnectToNetworkShare(replicaLocation, loginParts[0], password, loginParts[1]);
                else
                    FilePath.ConnectToNetworkShare(replicaLocation, login, password, Environment.UserDomainName);
            }

            FileSyncProvider syncSource = null;
            FileSyncProvider syncDestination = null;
            try
            {
                // Setup file synchronization filter.
                FileSyncScopeFilter synchFilter = new FileSyncScopeFilter();
                synchFilter.FileNameIncludes.Add("*_to_*.d");

                // Setup file synchronization providers.
                syncSource = new FileSyncProvider(archiveLocation, synchFilter, FileSyncOptions.CompareFileStreams);
                syncDestination = new FileSyncProvider(replicaLocation, synchFilter, FileSyncOptions.CompareFileStreams);
                syncDestination.ApplyingChange += SyncDestination_ApplyingChange;
                syncDestination.AppliedChange += SyncDestination_AppliedChange;

                // Setup and start file synchronization agent.
                SyncOrchestrator syncAgent = new SyncOrchestrator();
                syncAgent.LocalProvider = syncSource;
                syncAgent.RemoteProvider = syncDestination;
                syncAgent.Direction = SyncDirectionOrder.Upload;
                syncAgent.Synchronize();
            }
            finally
            {
                // Release resource used by synchronization providers.
                if (syncSource != null)
                    syncSource.Dispose();

                if (syncDestination != null)
                    syncDestination.Dispose();
            }
        }
Esempio n. 37
0
       public void Synchronize(KnowledgeSyncProvider destinationProvider, KnowledgeSyncProvider sourceProvider, ConflictResolutionPolicy destinationPol, ConflictResolutionPolicy sourcePol, SyncDirectionOrder SyncOrder, uint batchSize, string scopeName)
       {
           ((LocalStore)destinationProvider).RequestedBatchSize = batchSize;
           ((RemoteStore)sourceProvider).RequestedBatchSize = batchSize;

           destinationProvider.Configuration.ConflictResolutionPolicy = destinationPol;
           sourceProvider.Configuration.ConflictResolutionPolicy = sourcePol;

           SyncOrchestrator syncAgent = new SyncOrchestrator();

           syncAgent.LocalProvider = destinationProvider;
           syncAgent.RemoteProvider = sourceProvider;
           syncAgent.Direction = SyncOrder;

           syncAgent.Synchronize();
       }
Esempio n. 38
0
 public static void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             //_networkListManager.NetworkConnectivityChanged -= _networkListManager_NetworkConnectivityChanged;
         }
         if (_agent.State != SyncOrchestratorState.Ready)
         {
             _agent.Cancel();
             _agent = null;
         }
         _disposed = true;
     }
 }
Esempio n. 39
0
        static void Main(string[] args)
        {
            SqlCeConnection clientConn = new SqlCeConnection(@"Data Source='C:\dev\SyncTest\SyncSQLServerAndSQLCompact\data\SyncCompactDB.sdf'");
            SqlConnection serverConn = new SqlConnection(@"Data Source=.\SQL2008; Initial Catalog=SyncDB; Integrated Security=True");
            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();
            syncOrchestrator.LocalProvider = new SqlCeSyncProvider("ProductsScope", clientConn);
            syncOrchestrator.RemoteProvider = new SqlSyncProvider("ProductsScope", serverConn);
            syncOrchestrator.Direction = SyncDirectionOrder.UploadAndDownload;
            ((SqlCeSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);
            SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();

            Console.WriteLine("Start Time: " + syncStats.SyncStartTime);
            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);
            Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);
            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);
            Console.WriteLine(String.Empty);
        }
Esempio n. 40
0
        public AzureSynchronizer(RemoteInfo ri, string container, SynchronizeDirection syncDirection)
        {
            disposed = false;
            string _containerName = container;

            //
            // Setup Store and Provider
            //
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentialsAccountAndKey(ri.accountName, ri.accountKey), true);
            AzureBlobStore blobStore = new AzureBlobStore(_containerName, storageAccount);
            Console.WriteLine("Successfully created/attached to container {0}.", _containerName);
            AzureBlobSyncProvider azureProvider = new AzureBlobSyncProvider(_containerName, blobStore);
            azureProvider.ApplyingChange += new EventHandler<ApplyingBlobEventArgs>(UploadingFile);

            orchestrator = new SyncOrchestrator();
            orchestrator.RemoteProvider = azureProvider;

            if (syncDirection == SynchronizeDirection.Upload)
                orchestrator.Direction = SyncDirectionOrder.Upload;
            else if (syncDirection == SynchronizeDirection.Download)
                orchestrator.Direction = SyncDirectionOrder.Download;
        }
Esempio n. 41
0
        public static void Sincronizar(string pastaOrigem, 
            string pastaDestino,
            FileSyncScopeFilter filtro)
        {
            FileSyncProvider providerOrigem = null;
            FileSyncProvider providerDestino = null;

            try
            {
                const FileSyncOptions opcoes = FileSyncOptions.ExplicitDetectChanges |
                               FileSyncOptions.RecycleDeletedFiles |
                               FileSyncOptions.RecyclePreviousFileOnUpdates |
                               FileSyncOptions.RecycleConflictLoserFiles;

                providerOrigem = new FileSyncProvider(pastaOrigem, filtro, opcoes);

                providerDestino = new FileSyncProvider(pastaDestino, filtro, opcoes);

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

                var agent = new SyncOrchestrator
                {
                    LocalProvider = providerOrigem,
                    RemoteProvider = providerDestino,
                    Direction = SyncDirectionOrder.Upload
                };

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

                agent.Synchronize();
            }
            finally
            {
                if (providerOrigem != null) providerOrigem.Dispose();
                if (providerDestino != null) providerDestino.Dispose();
            }
        }
Esempio n. 42
0
        static void Main(string[] args)
        {
            string dbpath = @"SyncSoccerScore.sdf";
            SqlCeConnection clientConn = new SqlCeConnection(@"Data Source='" + dbpath + "'");

            // create a connection to the SyncCompactDB database
            //SqlCeConnection clientConn = new SqlCeConnection(@"Data Source='G:\htmlconvertsql\SqlCompact_20110520\Tools\SyncSoccerScore.sdf'");

            // create a connection to the SyncDB server database
            SqlConnection serverConn = new SqlConnection(@"Data Source=localhost; Initial Catalog=G:\htmlconvertsql\match_analysis_pdm.mdf; Integrated Security=True");

            // create the sync orhcestrator
            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();

            // set local provider of orchestrator to a CE sync provider associated with the 
            // ProductsScope in the SyncCompactDB compact client database
            syncOrchestrator.LocalProvider = new SqlCeSyncProvider("match_analysisScope", clientConn);

            // set the remote provider of orchestrator to a server sync provider associated with
            // the ProductsScope in the SyncDB server database
            syncOrchestrator.RemoteProvider = new SqlSyncProvider("match_analysisScope", serverConn);

            // set the direction of sync session to Upload and Download
            syncOrchestrator.Direction = SyncDirectionOrder.UploadAndDownload;

            // subscribe for errors that occur when applying changes to the client
            ((SqlCeSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);

            // execute the synchronization process
            SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();

            // print statistics
            Console.WriteLine("Start Time: " + syncStats.SyncStartTime);
            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);
            Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);
            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);
            Console.WriteLine(String.Empty);
        }
        private static void Main(string[] args)
        {
            SyncOrchestrator sync = new SyncOrchestrator();
            string scopeName = "test";
            SqlConnection localData = new SqlConnection(@"Data Source=nipun;Initial Catalog=ClientData;Integrated Security=True;");
            SqlConnection serverData = new SqlConnection(@"Data Source=nipun;Initial Catalog=ServerData;Integrated Security=True;");

            SqlSyncProvider localProvider = new SqlSyncProvider(scopeName, localData);
            SqlSyncProvider serverProvider = new SqlSyncProvider(scopeName, serverData);

            SqlSyncScopeProvisioning scopeProvisionLocal = new SqlSyncScopeProvisioning(localData);
            if (!scopeProvisionLocal.ScopeExists(scopeName))
            {
                DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(scopeName);
                scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("abc", localData));
                scopeProvisionLocal.PopulateFromScopeDescription(scopeDesc);
                scopeProvisionLocal.SetCreateTableDefault(DbSyncCreationOption.Skip);
                scopeProvisionLocal.Apply();
            }

            SqlSyncScopeProvisioning scopeProvisionRemote = new SqlSyncScopeProvisioning(serverData);
            if (!scopeProvisionRemote.ScopeExists(scopeName))
            {
                DbSyncScopeDescription scopeDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope(scopeName, localData);
                scopeProvisionRemote.PopulateFromScopeDescription(scopeDesc);
                scopeProvisionRemote.Apply();
            }

            SqlSyncScopeProvisioning romve = new SqlSyncScopeProvisioning(localData);
            sync.LocalProvider = localProvider;
            sync.RemoteProvider = serverProvider;
            SyncOperationStatistics stats = sync.Synchronize();
            Console.WriteLine("Update Data:\t\t {0}", stats.UploadChangesApplied);
            Console.WriteLine("Update Data ChangesFailed:\t\t {0}", stats.UploadChangesFailed);
            Console.WriteLine("Update Data Changes:\t\t {0}", stats.UploadChangesTotal);
            Console.ReadLine();
        }
        public static void Synchronize(string sqlConnectionString)
        {
            bool isScopeExists = ScopeHelper.CheckScope(sqlConnectionString, true);

            if (!isScopeExists)
                ScopeHelper.CreateScope(sqlConnectionString, true);

            using (var localDbConnection = new SqlCeConnection(Constants.LocalConnectionString))
            using (var remoteDbConnection = new SqlConnection(sqlConnectionString))
            {
                var syncOrchestrator = new SyncOrchestrator
                                           {
                                               Direction = SyncDirectionOrder.DownloadAndUpload,
                                               RemoteProvider =
                                                   new SqlSyncProvider("SyncScope", remoteDbConnection),
                                               LocalProvider = new SqlCeSyncProvider("SyncScope", localDbConnection)
                                           };

                syncOrchestrator.Synchronize();
            }

            ContactsManager.Current.RefreshCache();
            CompaniesManager.Current.RefreshCache();
        }
Esempio n. 45
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();
            }
        }
Esempio n. 46
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();
            }
        }
Esempio n. 47
0
        private void Synchronize(bool startFromScratch = false)
        {
            lock (startSyncLock)
            {
                if (isSyncing) { changesWhileSync = true; return; }
                isSyncing = true;
                changesWhileSync = false;
            }
            if (SyncStarted != null) { SyncStarted(this, null); }

            if (startFromScratch)
            {
                if (File.Exists(metadataFile))
                {
                    File.Delete(metadataFile);
                }
            }
            var fileProvider = new FileSyncProvider(
                localFolder,
                new FileSyncScopeFilter(),
                FileSyncOptions.RecycleDeletedFiles | FileSyncOptions.RecycleConflictLoserFiles,
                Path.GetDirectoryName(metadataFile),
                Path.GetFileName(metadataFile),
                Path.GetTempPath(),
                null
                );
            fileProvider.AppliedChange += (s, e) => AppliedChange(s, e.ChangeType, e.OldFilePath, e.NewFilePath);
            fileProvider.SkippedChange += (s, e) => { var t = e; };

            var remote = new MegaKnowledgeProvider(remoteStore);
            if (startFromScratch)
            {
                remote.ResetDatabase();
            }

            remote.AppliedChange += (s, e) => AppliedChange(s, e.ChangeType, e.OldFilePath, e.NewFilePath);
            // do we need this?
            remote.DestinationCallbacks.ItemConstraint += (s, e) => 
            { 
                e.SetResolutionAction(ConstraintConflictResolutionAction.SkipChange);
            };
            remote.DestinationCallbacks.ItemConflicting += (s, e) => { e.SetResolutionAction(ConflictResolutionAction.Merge); };

            try
            {
                var agent = new SyncOrchestrator();
                agent.RemoteProvider = remote;
                agent.Direction = SyncDirectionOrder.UploadAndDownload;
                agent.LocalProvider = fileProvider;
                var status = agent.Synchronize();
                remoteStore.CleanTemp();
                if (remote.NeedResync)
                {
                    syncTimer.Stop();
                    syncTimer.Start();
                }
            }
            catch (Exception e)
            {
                remote.ResetDatabase();
                if (File.Exists(metadataFile))
                {
                    File.Delete(metadataFile);
                }
                OnError("Sync has encountered a severe problem. Trying to resync from scratch...", e);
                syncTimer.Stop();
                syncTimer.Start();
            }
            finally
            {
                fileProvider.Dispose();
                remote = null;
                lock (startSyncLock)
                {
                    if (changesWhileSync)
                    {
                        syncTimer.Stop();
                        syncTimer.Start();
                    }
                    isSyncing = false;
                }
                if (SyncEnded != null) { SyncEnded(this, null); }
            }

        }
Esempio n. 48
0
        private void SubscribeEvents(SyncOrchestrator syncAgent)
        {
            if (syncAgent != null)
            {
                syncAgent.SessionProgress -= OnSessionProgress;
                syncAgent.StateChanged -= OnSessionStateChanged;

                syncAgent.SessionProgress += OnSessionProgress;
                syncAgent.StateChanged += OnSessionStateChanged;
            }
        }
Esempio n. 49
0
        /// <summary>
        /// Does the sync. Выполняется в другом потоке отличном от AddinModule
        /// </summary>
        /// <param name="oItemType">Type of the o item.</param>
        private void DoSync(Outlook.OlItemType oItemType)
        {
            //reset last error
            LastSyncErrorDescr = string.Empty;
            LastSyncErrorOccur = false;
            //reset skipped items
            _skippedItems.Clear();

            KnowledgeSyncProvider localProvider = null;
            KnowledgeSyncProvider remoteProvider = null;
            CurrentProcessedSyncType = oItemType;
            try
            {
                remoteProvider = GetRemoteSyncProvidersBySyncType(oItemType);
                localProvider = GetLocalSyncProviderBySyncType(oItemType);

                if (localProvider != null)
                {
                    //Create sync session
                    if (_syncAgent == null)
                    {
                        _syncAgent = new SyncOrchestrator();
                        //Subscribe sync framework events
                        SubscribeEvents(_syncAgent);
                    }

                    //ISyncProviderSetting providerSetting = localProvider.ProviderSetting;
                    ISyncProviderSetting providerSetting = localProvider as ISyncProviderSetting;
                    if (providerSetting != null)
                    {

                        SyncDirectionOrder direction = providerSetting.SyncDirectionOrderSetting;
                        ConflictResolutionPolicy conflictResolution = providerSetting.ConflictResolutionPolicySetting;

                        remoteProvider.Configuration.ConflictResolutionPolicy = conflictResolution;
                        localProvider.Configuration.ConflictResolutionPolicy = conflictResolution;

                        _syncAgent.Direction = direction;
                        _syncAgent.LocalProvider = localProvider;
                        _syncAgent.RemoteProvider = remoteProvider;

                        //Subscribe to knowledege provider events
                        SubscribeEvents(localProvider);
                        SubscribeEvents(remoteProvider);
                        //raise sync process begin event
                        OnSyncProcessBegin(new SyncProcessEventArgs());

                        SyncOperationStatistics syncStats = _syncAgent.Synchronize();
                        CollectStatistics(syncStats);
                    }
                }
            }
            catch (UriFormatException e)
            {
                DebugAssistant.Log(DebugSeverity.Error, e.Message);
                LastSyncErrorOccur = true;
                LastSyncErrorDescr = OutlookAddin.Resources.ERR_SYNC_SERVICE_INVALID_URL;
                //DebugAssistant.Log(DebugSeverity.Error | DebugSeverity.MessageBox,
                //					OutlookAddin.Resources.ERR_SYNC_SERVICE_INVALID_URL);
            }
            catch (SoapException e)
            {
                LastSyncErrorOccur = true;
                SyncronizationServiceError syncError = SoapErrorHandler.HandleError(e);

                string msg = OutlookAddin.Resources.ERR_SYNC_SERVICE_UKNOW;
                if (syncError != null)
                {
                    DebugAssistant.Log(DebugSeverity.Error, syncError.errorType.ToString() + " "
                                        + syncError.message + " " + syncError.stackTrace);

                    switch (syncError.errorType)
                    {
                        case SyncronizationServiceError.eServiceErrorType.AuthFailed:
                            msg = Resources.ERR_SYNC_SERVICE_AUTH_FAILED;
                            break;
                        case SyncronizationServiceError.eServiceErrorType.NotAuthRequest:
                            msg = Resources.ERR_SYNC_SERVICE_NOT_AUTH;
                            break;
                        case SyncronizationServiceError.eServiceErrorType.ProviderNotSpecified:
                            msg = Resources.ERR_SYNC_SERVICE_INVALID_PROVIDER;
                            break;
                        case SyncronizationServiceError.eServiceErrorType.SyncFramework:
                            msg = Resources.ERR_SYNC_SERVICE_FRAMEWORK;
                            break;
                        case SyncronizationServiceError.eServiceErrorType.SyncProvider:
                            msg = Resources.ERR_SYNC_SERVICE_PROVIDER;
                            break;
                        case SyncronizationServiceError.eServiceErrorType.ServerError:
                            msg = Resources.ERR_SYNC_SERVICE_SERVER;
                            break;
                        case SyncronizationServiceError.eServiceErrorType.Undef:
                            msg = Resources.ERR_SYNC_SERVICE_UKNOW;
                            break;
                    }
                }

                LastSyncErrorDescr = msg;

                //DebugAssistant.Log(DebugSeverity.Error | DebugSeverity.MessageBox, msg);
            }
            catch (System.Net.WebException e)
            {
                LastSyncErrorOccur = true;
                LastSyncErrorDescr = Resources.ERR_SYNC_CONNECTION;
                DebugAssistant.Log(DebugSeverity.Error, e.Message);
            }
            catch (Exception e)
            {
                LastSyncErrorOccur = true;
                LastSyncErrorDescr = OutlookAddin.Resources.ERR_ADDIN_UNKNOW;
                DebugAssistant.Log(DebugSeverity.Error, e.Message);
                //DebugAssistant.Log(DebugSeverity.Error | DebugSeverity.MessageBox, OutlookAddin.Resources.ERR_ADDIN_UNKNOW);
            }
            finally
            {
                if (localProvider != null)
                {
                    localProvider.EndSession(null);
                }
                if (remoteProvider != null)
                {
                    remoteProvider.EndSession(null);
                }
                OnSyncProcessEnd(new SyncProcessEventArgs());
                CurrentProcessedSyncType = null;

            }
        }
Esempio n. 50
0
        private void syncButton_Click(object sender, EventArgs e)
        {
            using (SqlSyncProvider masterProvider = new SqlSyncProvider { ScopeName = this.scopeNameTextBox.Text }, slaveProvider = new SqlSyncProvider { ScopeName = this.scopeNameTextBox.Text })
            {
                using (SqlConnection master = new SqlConnection(Settings.Default.MasterConnectionString), slave = new SqlConnection(Settings.Default.SlaveConnectionString))
                {
                    string masterScopeConfig;
                    string slaveScopeConfig;

                    using (SqlCommand command = master.CreateCommand())
                    {
                        master.Open();
                        command.CommandText = string.Format("SELECT scope_config.config_data FROM scope_config INNER JOIN scope_info ON scope_config.config_id = scope_info.scope_config_id WHERE scope_info.sync_scope_name = N'{0}'", TableName);
                        masterScopeConfig = command.ExecuteScalar() as string;
                        master.Close();
                    }

                    using (SqlCommand command = slave.CreateCommand())
                    {
                        slave.Open();
                        command.CommandText = string.Format("SELECT scope_config.config_data FROM scope_config INNER JOIN scope_info ON scope_config.config_id = scope_info.scope_config_id WHERE scope_info.sync_scope_name = N'{0}'", TableName);
                        slaveScopeConfig = command.ExecuteScalar() as string;
                        slave.Close();
                    }

                    if (masterScopeConfig != slaveScopeConfig)
                    {
                        MessageBox.Show("The master scope does not match the slave scope", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    masterProvider.Connection = master;
                    slaveProvider.Connection = slave;
                    SyncOrchestrator orchestrator = new SyncOrchestrator
                                                        {
                                                            LocalProvider = slaveProvider,
                                                            RemoteProvider = masterProvider,
                                                            Direction = SyncDirectionOrder.UploadAndDownload
                                                        };

                    try
                    {
                        SyncOperationStatistics stats = orchestrator.Synchronize();
                        MessageBox.Show("Downloaded: " + stats.DownloadChangesTotal + "Uploaded: " + stats.UploadChangesApplied, "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Sync Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Esempio n. 51
0
 public bool Synchronize(SyncOrchestrator agent)
 {
     //throw new NotImplementedException();
     try
     {
         agent.Synchronize();
         return true;
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Esempio n. 52
0
 public SyncOrchestrator CreateSyncOrchestrator(FileSyncProvider source, FileSyncProvider destination)
 {
     //throw new NotImplementedException();
     SyncOrchestrator agent = new SyncOrchestrator();
     agent.LocalProvider = source;
     agent.RemoteProvider = destination;
     return agent;
 }
        //int timeOut, uint tamañoDeCache)
        private void ReplicarAmbitos(SyncOrchestrator orchestrator, List<DbSyncScopeDescription> Ambitos, ParametrosReplica parametrosReplica )
        {
            foreach (DbSyncScopeDescription ambito in Ambitos)
            {
                //////////////// PROVEEDORES DE REPLICA (CONOCEN LA LOGICA DEL MOTOR DE DATOS A REPLICAR)  ////////////////
                SqlSyncProvider proveedorLocal = this.ObtenerProveedor(ambito.ScopeName, conexionLocalSql, parametrosReplica.tamañoDeCache, parametrosReplica.TamañoDeTransaccion);
                SqlSyncProvider proveedorRemoto = this.ObtenerProveedor(ambito.ScopeName, conexionRemotoSql, parametrosReplica.tamañoDeCache, parametrosReplica.TamañoDeTransaccion);

                proveedorLocal.CommandTimeout = parametrosReplica.TimeOut;
                proveedorRemoto.CommandTimeout = parametrosReplica.TimeOut;

                orchestrator.LocalProvider = proveedorLocal;
                orchestrator.RemoteProvider = proveedorRemoto;

                try
                {
                    bool replicar = true;
                    int anclaActual = this.ObtenerAnclaActual();
                    if (parametrosReplica.ReplicarSoloAmbitosconCambios)
                    {
                        replicar = this.ElAmbitoTieneNovedades( ambito );
                    }
                    if (replicar)
                    {
                        SyncOperationStatistics statsUpload = orchestrator.Synchronize();
                        this.loguearEstadisticas(statsUpload, ambito);
                        this.ActualizarAnclaDeSincronizacion(anclaActual, ambito);
                    }
                }
                catch (Exception error)
                {
                    this.loguear("Error al replicar el ambito: " + ambito.ScopeName + " Error: " + error.ToString());
                }

            }
        }
        private SyncOrchestrator ObtenerOrquestadorDeReplica(ParametrosReplica parametros)
        {
            SyncOrchestrator orchestrator = new SyncOrchestrator();
            if (parametros.SitioDeSubida)
                orchestrator.Direction = SyncDirectionOrder.Upload;
            else
                orchestrator.Direction = SyncDirectionOrder.Download;

            if (this.SuscribirATodosLosEventos)
            {
                orchestrator.SessionProgress += new EventHandler<SyncStagedProgressEventArgs>(this.orchestrator_SessionProgress);
                orchestrator.StateChanged += new EventHandler<SyncOrchestratorStateChangedEventArgs>(this.orchestrator_StateChanged);
            }
            return orchestrator;
        }
Esempio n. 55
0
 public SyncOrchestrator SetSyncDirection(SyncOrchestrator agent)
 {
     //throw new NotImplementedException();
     agent.Direction = SyncDirectionOrder.Upload;
     return agent;
 }
Esempio n. 56
0
        public static void Sync()
        {
            // create the sync orhcestrator
            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();

            // set local provider of orchestrator to a CE sync provider associated with the
            // ProductsScope in the SyncCompactDB compact client database
            syncOrchestrator.LocalProvider = new SqlSyncProvider("AllSyncScope", clientConn);

            // set the remote provider of orchestrator to a server sync provider associated with
            // the ProductsScope in the SyncDB server database
            syncOrchestrator.RemoteProvider = new SqlSyncProvider("AllSyncScope", serverConn);

            // set the direction of sync session to Upload and Download
            syncOrchestrator.Direction = SyncDirectionOrder.DownloadAndUpload;
            try
            {
                syncOrchestrator.Synchronize();
            }
            catch (Exception ex)
            {
            }
        }
        private void Sync()
        {
            // create the sync orhcestrator
            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();

            // set local provider of orchestrator to a sync provider associated with the
            // MySyncScope in the client database
            syncOrchestrator.LocalProvider = new SqlSyncProvider("MySyncScope", clientConn);

            // set the remote provider of orchestrator to a server sync provider associated with
            // the MySyncScope in the server database
            syncOrchestrator.RemoteProvider = new SqlSyncProvider("MySyncScope", serverConn);

            // set the direction of sync session to Upload and Download
            syncOrchestrator.Direction = SyncDirectionOrder.DownloadAndUpload;

            // subscribe for errors that occur when applying changes to the client
            ((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);

            // execute the synchronization process
            SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();

            // print statistics
            Console.WriteLine("Start Time: " + syncStats.SyncStartTime);
            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);
            Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);
            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);
            Console.WriteLine(String.Empty);
            Console.ReadLine();
        }
Esempio n. 58
0
        //
        // Synchronize Call
        //
        private void buttonSynchronize_Click(object sender, EventArgs e)
        {
            try
            {

                //
                // 1. Create instance of the sync components (peer, agent, peer)
                // This demo illustrates direct connection to server database. In this scenario,
                // all sync components reside in the sample process.
                //
                DbSyncProvider localProvider = new DbSyncProvider();
                DbSyncProvider remoteProvider = new DbSyncProvider();

                localProvider = SetupSyncProvider(GetFromPeerConnectionString(), localProvider);
                localProvider.SyncProviderPosition = SyncProviderPosition.Local;

                remoteProvider = SetupSyncProvider(GetToPeerConnectionString(), remoteProvider);
                remoteProvider.SyncProviderPosition = SyncProviderPosition.Remote;

                SyncOrchestrator syncOrchestrator = new SyncOrchestrator();
                // syncdirection: local->remote
                syncOrchestrator.LocalProvider = localProvider;
                syncOrchestrator.RemoteProvider = remoteProvider;
                syncOrchestrator.Direction = SyncDirectionOrder.Upload;
                syncOrchestrator.SessionProgress += new EventHandler<SyncStagedProgressEventArgs>(ProgressChanged);

                _progressForm = new ProgressForm();
                _progressForm.Show();
                SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();

                _progressForm.ShowStatistics(syncStats);
                // Update the UI
                _progressForm.EnableClose();
                _progressForm = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                if (_progressForm != null)
                {
                    _progressForm.EnableClose();
                    _progressForm = null;
                }
            }
        }
        /// <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();
            }
        }
Esempio n. 60
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();
            }
        }