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()); } }
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); }
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; }
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); }
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); }
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; } } } }
private FileStoreSync InitializeSyncFileSystem(string folder, SyncDirectionOrder syncDirection, string[] filters) { FileStoreSync fsSync = new FileStoreSync(folder, syncDirection, filters); // Register event handlers for file system sync FotoShoutUtils.Log.LogManager.Info(_logger, "Registering event handlers for file system sync..."); fsSync.AppliedChange += new AppliedChangeEventHandler(OnFileSystemAppliedChange); fsSync.SkippedChange += new SkippedChangeEventHandler(OnFileSystemSkippedChange); fsSync.ItemConflicting += new FotoShoutSyncService.ItemConflictingEventHandler(OnFileSystemItemConflicting); fsSync.ItemConstraint += new FotoShoutSyncService.ItemConstraintEventHandler(OnFileSystemItemConstraint); fsSync.Synchronized += new FotoShoutSyncService.SynchronizedEventHandler(OnFileSystemSynchronized); FotoShoutUtils.Log.LogManager.Info(_logger, "Successfully registered event handlers for file system sync..."); return(fsSync); }
public static void AddScopeToScopesTable(SqlConnection conn, string scope, SyncDirectionOrder order) { CreateScopesTable(conn); string sql = @"DELETE FROM [scopes] WHERE scope = @scope; INSERT INTO [scopes] ([scope] ,[syncorder]) VALUES (@scope, @order)"; SqlCommand command = conn.CreateCommand(); command.CommandText = sql; command.Parameters.AddWithValue("@scope", scope); command.Parameters.AddWithValue("@order", order.ToString()); command.ExecuteNonQuery(); }
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(); }
private FileClientSync InitializeFileClientSync(SyncDirectionOrder syncDirection) { FileClientSync fsSync = new FileClientSync(); fsSync.SyncDirection = syncDirection; // Register event handlers for file system sync FotoShoutUtils.Log.LogManager.Info(_logger, "Registering event handlers for file system sync..."); fsSync.AppliedChange += new AppliedChangeEventHandler(OnFileSystemAppliedChange); fsSync.SkippedChange += new SkippedChangeEventHandler(OnFileSystemSkippedChange); fsSync.ItemConflicting += new FotoShoutUtils.Sync.Files.ItemConflictingEventHandler(OnFileSystemItemConflicting); fsSync.ItemConstraint += new FotoShoutUtils.Sync.Files.ItemConstraintEventHandler(OnFileSystemItemConstraint); fsSync.Synchronized += new FotoShoutUtils.Sync.Files.SynchronizedEventHandler(OnFileSystemSynchronized); FotoShoutUtils.Log.LogManager.Info(_logger, "Successfully registered event handlers for file system sync..."); return(fsSync); }
public static List <_CSyncDetails> Synchronize(string _pScopeName, SyncDirectionOrder _pDirection) { // Connection to SQL Server database SqlConnection serverConn = new SqlConnection(ServerConnString); // Connection to SQL client database SqlConnection clientConn = new SqlConnection(ClientConnString); List <_CSyncDetails> _Statics = new List <_CSyncDetails>(); // Perform Synchronization between SQL Server and the SQL client. SyncOrchestrator syncOrchestrator = new SyncOrchestrator(); // Create provider for SQL Server SqlSyncProvider serverProvider = new SqlSyncProvider(_pScopeName, serverConn); // Set the command timeout and maximum transaction size for the SQL Azure provider. SqlSyncProvider clientProvider = new SqlSyncProvider(_pScopeName, clientConn); clientProvider.CommandTimeout = serverProvider.CommandTimeout = 500; //Set memory allocation to the database providers clientProvider.MemoryDataCacheSize = serverProvider.MemoryDataCacheSize = MemorySize; //Set application transaction size on destination provider. serverProvider.ApplicationTransactionSize = BatchSize; //Count transactions serverProvider.ChangesApplied += new EventHandler <DbChangesAppliedEventArgs>(RemoteProvider_ChangesApplied); // Set Local provider of SyncOrchestrator to the server provider syncOrchestrator.LocalProvider = serverProvider; // Set Remote provider of SyncOrchestrator to the client provider syncOrchestrator.RemoteProvider = clientProvider; // Set the direction of SyncOrchestrator session to Upload and Download syncOrchestrator.Direction = _pDirection; // Create SyncOperations Statistics Object SyncOperationStatistics syncStats = syncOrchestrator.Synchronize(); _Statics.Add(new _CSyncDetails { UploadChangesTotal = syncStats.UploadChangesTotal, SyncStartTime = syncStats.SyncStartTime, DownloadChangesTotal = syncStats.DownloadChangesTotal, SyncEndTime = syncStats.SyncEndTime }); // Shut down database connections. serverConn.Close(); serverConn.Dispose(); clientConn.Close(); clientConn.Dispose(); return(_Statics); }
public void Synchronize(SyncDirectionOrder directionOrder) { try { 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; } if (ApplyLocalChangesFailed != null) { ((SqlSyncProvider)_orchestrator.LocalProvider).ApplyChangeFailed += ApplyLocalChangesFailed; } ((SqlSyncProvider)_orchestrator.RemoteProvider).ChangesSelected += DbSynchronizer_ChangesSelected; SyncOperationStatistics syncStats = _orchestrator.Synchronize(); Log("Start Time: " + syncStats.SyncStartTime); Log("Total Changes Uploaded: " + syncStats.UploadChangesTotal); Log("Total Changes Downloaded: " + syncStats.DownloadChangesTotal); Log("Complete Time: " + syncStats.SyncEndTime); Log(string.Empty); _orchestrator = null; } catch (Exception e) { Log(e.ToString()); _logger.Error(e); } }
/// <summary> /// Utility function that will create a SyncOrchestrator and /// synchronize the two passed in providers /// </summary> /// <param name="localProvider">Local store provider</param> /// <param name="remoteProvider">Remote store provider</param> /// <param name="direction"></param> /// <returns></returns> private SyncOperationStatistics SynchronizeProviders( KnowledgeSyncProvider localProvider, KnowledgeSyncProvider remoteProvider, SyncDirectionOrder direction) { var orchestrator = new SyncOrchestrator(); orchestrator.LocalProvider = localProvider; orchestrator.RemoteProvider = remoteProvider; orchestrator.Direction = direction; // subscribe for errors that occur when applying changes to the client ((SqlSyncProvider)orchestrator.LocalProvider).ChangesSelected += Program_ChangesSelected; ((SqlSyncProvider)orchestrator.LocalProvider).SyncProgress += Program_LocalProgress; ((SqlSyncProvider)orchestrator.LocalProvider).ApplyChangeFailed += Program_ApplyChangeFailed; ((SqlSyncProvider)orchestrator.LocalProvider).ApplyingChanges += Program_ApplyingChanges; ((SqlSyncProvider)orchestrator.LocalProvider).ChangesApplied += Program_ChangesApplied; // These are used for file sync... //((RelationalProviderTestProxy) orchestrator.RemoteProvider).DestinationCallbacks.ItemConflicting += // Program_RemoteItemConflicting; //((RelationalProviderTestProxy) orchestrator.RemoteProvider).DestinationCallbacks.ItemChanging += // Program_RemoteItemChanging; //((RelationalProviderTestProxy) orchestrator.RemoteProvider).DestinationCallbacks.ProgressChanged += // Program_ProgressChange; //((RelationalProviderTestProxy) orchestrator.RemoteProvider).DestinationCallbacks.ItemChangeSkipped += // Program_ItemChangeSkipped; ((SqlSyncProvider)orchestrator.LocalProvider).MemoryDataCacheSize = 100000; ((SqlSyncProvider)orchestrator.LocalProvider).ApplicationTransactionSize = 4096; //Check to see if any provider is a SqlCe provider and if it needs schema CheckIfProviderNeedsSchema(localProvider as SqlSyncProvider); var stats = orchestrator.Synchronize(); return(stats); }
/// <summary> /// Sync a single scope from the client to the server. /// </summary> /// <param name="server">Provider for the server.</param> /// <param name="client">Provider for the client.</param> /// <param name="tablename">The able name to sync.</param> public static SyncOperationStatistics syncscope(SqlConnection server, SqlConnection client, string scope, SyncDirectionOrder order, Action <object, DbApplyingChangesEventArgs> callback, Action <object, DbApplyingChangesEventArgs> mastercallback) { // If we are only doing a download and the scope on the database // is out of date then we need to reprovision the data, but for now just // error. if (order == SyncDirectionOrder.Download && ScopesDiffer(server, client, scope)) { ProgressUpdate("Scope has changed on server. Reprovisoning client"); Provisioning.ProvisionTable(server, client, scope, true); } else if (order != SyncDirectionOrder.Download && ScopesDiffer(server, client, scope)) { throw new DbSyncException("Can not sync twoway tables with changed scopes"); } using (SqlSyncProvider masterProvider = new SqlSyncProvider(scope, server), slaveProvider = new SqlSyncProvider(scope, client)) { SyncOrchestrator orchestrator = new SyncOrchestrator { LocalProvider = slaveProvider, RemoteProvider = masterProvider, Direction = order }; slaveProvider.ApplyingChanges += new EventHandler <DbApplyingChangesEventArgs>(callback); masterProvider.ApplyingChanges += new EventHandler <DbApplyingChangesEventArgs>(mastercallback); slaveProvider.ApplyChangeFailed += slaveProvider_ApplyChangeFailed; return(orchestrator.Synchronize()); } }
/// <summary> /// Returns the scopes and their sync order that are defined in the database. /// </summary> /// <param name="clientconn">The connection string to the client</param> /// <param name="scope">The name of the scope to sync. If blank return /// all scopes.</param> /// <returns>A list of <see cref="Scope"/> that contains a name and order</returns> public static List <Scope> getScopes(string clientconn, string scope) { List <Scope> scopes = new List <Scope>(); using (SqlConnection client = new SqlConnection(clientconn)) { client.Open(); string command = "SELECT scope, syncorder FROM scopes"; SqlCommand query = new SqlCommand(command, client); if (!String.IsNullOrEmpty(scope)) { query.CommandText += " WHERE scope = @scope"; SqlParameter param = new SqlParameter(); param.ParameterName = "@scope"; param.Value = scope; query.Parameters.Add(param); } // We should handle if the table scopes doesn't exist and maybe // grab all the scopes from the database and just sync one way. SqlDataReader reader = query.ExecuteReader(); while (reader.Read()) { string name = reader["scope"].ToString(); string order = reader["syncorder"].ToString(); SyncDirectionOrder syncorder = utils.StringToEnum <SyncDirectionOrder>(order); scopes.Add(new Scope() { name = name, order = syncorder }); } client.Close(); } return(scopes); }
/// <summary> /// Sync a single scope from the client to the server. /// </summary> /// <param name="server">Provider for the server.</param> /// <param name="client">Provider for the client.</param> /// <param name="tablename">The able name to sync.</param> public static SyncOperationStatistics syncscope(SqlConnection server, SqlConnection client, string scope, SyncDirectionOrder order, Action<object, DbApplyingChangesEventArgs> callback, Action<object, DbApplyingChangesEventArgs> mastercallback) { // If we are only doing a download and the scope on the database // is out of date then we need to reprovision the data, but for now just // error. if (order == SyncDirectionOrder.Download && ScopesDiffer(server, client, scope)) { ProgressUpdate("Scope has changed on server. Reprovisoning client"); Provisioning.ProvisionTable(server, client, scope, true); } else if (order != SyncDirectionOrder.Download && ScopesDiffer(server, client, scope)) { throw new DbSyncException("Can not sync twoway tables with changed scopes"); } using (SqlSyncProvider masterProvider = new SqlSyncProvider(scope, server), slaveProvider = new SqlSyncProvider(scope, client)) { SyncOrchestrator orchestrator = new SyncOrchestrator { LocalProvider = slaveProvider, RemoteProvider = masterProvider, Direction = order }; slaveProvider.ApplyingChanges += new EventHandler<DbApplyingChangesEventArgs>(callback); masterProvider.ApplyingChanges += new EventHandler<DbApplyingChangesEventArgs>(mastercallback); slaveProvider.ApplyChangeFailed += slaveProvider_ApplyChangeFailed; return orchestrator.Synchronize(); } }
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 }
public void SyncOperationStatisticsShow(SyncOperationStatistics syncOperationStatistics, SyncDirectionOrder _SyncDirectionOrder, string name) { Console.WriteLine(name); Console.WriteLine("{1} Download Applied:\t {0}", syncOperationStatistics.DownloadChangesApplied, _SyncDirectionOrder); Console.WriteLine("{1} Download Failed:\t {0}", syncOperationStatistics.DownloadChangesFailed, _SyncDirectionOrder); Console.WriteLine("{1} Download Total:\t\t {0}", syncOperationStatistics.DownloadChangesTotal, _SyncDirectionOrder); Console.WriteLine("{1} Upload Applied Total:\t\t {0}", syncOperationStatistics.UploadChangesApplied, _SyncDirectionOrder); Console.WriteLine("{1} Upload Failed Total:\t\t {0}", syncOperationStatistics.UploadChangesFailed, _SyncDirectionOrder); Console.WriteLine("{1} Upload Total:\t\t {0}", syncOperationStatistics.UploadChangesTotal, _SyncDirectionOrder); }
private static void Synchronize(string scopeName, string serverConnectionString, string clientConnectionString, SyncDirectionOrder syncDirectionOrder) { 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(); } } }
public void SetSyncDirection(SyncDirectionOrder syncDirection) { _clientSync.SyncDirection = syncDirection; }
/// <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; } }
public bool InitSync( bool serviceCall, SyncDirectionOrder way, FileSyncScopeFilter scopeFilter, FileSyncOptions fileSyncOptions) { bool retVal = false; set.ErrCount = 0; try { //Generate a unique Id for the source and store it in file or database for refer it further //sourceId = NewSyncGuid(); // SyncId() //Generate a unique Id for the destination and store it in a file or database for refer it further //destId = NewSyncGuid(); //ReplicaId se genereaza in constructor // file sync providers localPro = new FileSyncProvider(set.dirLocalSync, scopeFilter, fileSyncOptions, set.metadataDirectoryPath, Settings.metaFileLoc, set.tempDirectoryPath, set.pathToSaveConflictLoserFiles); remotePro = new FileSyncProvider(set.dirRemote, scopeFilter, fileSyncOptions, set.metadataDirectoryPath, Settings.metaFileRem, set.tempDirectoryPath, set.pathToSaveConflictLoserFiles); // Task curent: Skip delete // ChangeType: // Create A file or folder will be created // Delete A file or folder will be deleted // Update A file or folder will be updated // Rename A file or folder will be renamed remotePro.ApplyingChange += ProviderEvent_ApplyingChange; localPro.ApplyingChange += ProviderEvent_ApplyingChange; // Ask providers to detect changes //FileSyncProvider.DetectChanges( ) is called either implicitly //by the SyncOrchestrator.Synchronize( ) method, //or explicitly if the FileSyncProvider options specifies //that DetectChanges is to be called explicitly DetectChanges(); //sourceId = localPro.ReplicaId; //destId = remotePro.ReplicaId; // Init Sync orchestrator = new SyncOrchestrator(); orchestrator.LocalProvider = localPro; orchestrator.RemoteProvider = remotePro; orchestrator.Direction = way; //orchestrator.SessionProgress += Orchestrator_SessionProgress; retVal = true; } catch //(Exception ex) { //("Sync fail: " + ex.ToString()); CleanUp(); retVal = false; } //finally return(retVal); }
protected abstract void SynchronizeSyncScope(string syncScope, SyncDirectionOrder synDirection, KnowledgeSyncProvider localProvider, KnowledgeSyncProvider remoteProvider);
public Dictionary <string, SyncOperationStatistics> Synchronize(SyncDirectionOrder direction) { Log.Info("[DistributedDb] Synchronize Client Start", this); var result = new Dictionary <string, SyncOperationStatistics>(); foreach (var db in base.Databases) { try { Log.Info("[DistributedDb] Synchronize Client [" + db.Scope + "] Start", this); var clientConn = new SqlConnection(db.ClientConnectionString); var serverConn = new SqlConnection(db.ServerConnectionString); var syncOrchestrator = new SyncOrchestrator(); var client = new SqlSyncProvider(db.Scope, clientConn); var server = new SqlSyncProvider(db.Scope, serverConn); client.CommandTimeout = 3600; server.CommandTimeout = 3600; syncOrchestrator.LocalProvider = client; syncOrchestrator.RemoteProvider = server; syncOrchestrator.Direction = direction; ((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler <DbApplyChangeFailedEventArgs>(SynchronizeClient_ApplyChangeFailed); ((SqlSyncProvider)syncOrchestrator.RemoteProvider).ApplyChangeFailed += new EventHandler <DbApplyChangeFailedEventArgs>(SynchronizeServer_ApplyChangeFailed); ((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyingChanges += new EventHandler <DbApplyingChangesEventArgs>(SynchronizeClient_ApplyingChanges); ((SqlSyncProvider)syncOrchestrator.RemoteProvider).ApplyingChanges += new EventHandler <DbApplyingChangesEventArgs>(SynchronizeServer_ApplyingChanges); ((SqlSyncProvider)syncOrchestrator.LocalProvider).ChangesApplied += new EventHandler <DbChangesAppliedEventArgs>(SynchronizeClient_ChangesApplied); ((SqlSyncProvider)syncOrchestrator.RemoteProvider).ChangesApplied += new EventHandler <DbChangesAppliedEventArgs>(SynchronizeServer_ChangesApplied); ((SqlSyncProvider)syncOrchestrator.LocalProvider).SelectingChanges += new EventHandler <DbSelectingChangesEventArgs>(SynchronizeClient_SelectingChanges); ((SqlSyncProvider)syncOrchestrator.RemoteProvider).SelectingChanges += new EventHandler <DbSelectingChangesEventArgs>(SynchronizeServer_SelectingChanges); ((SqlSyncProvider)syncOrchestrator.LocalProvider).ChangesSelected += new EventHandler <DbChangesSelectedEventArgs>(SynchronizeClient_ChangesSelected); ((SqlSyncProvider)syncOrchestrator.RemoteProvider).ChangesSelected += new EventHandler <DbChangesSelectedEventArgs>(SynchronizeServer_ChangesSelected); //((SqlSyncProvider)syncOrchestrator.LocalProvider).SyncProgress += new EventHandler<DbSyncProgressEventArgs>(Synchronize_SyncProgress); syncOrchestrator.SessionProgress += new EventHandler <SyncStagedProgressEventArgs>(Synchronize_ProgressChanged); var syncStats = syncOrchestrator.Synchronize(); Log.Info("[DistributedDb] Synchronize Client Statistics [" + db.Scope + "] SyncStartTime: " + syncStats.SyncStartTime.ToString("hh:mm:ss.fff"), this); if (syncStats.UploadChangesTotal > 0) { Log.Info("[DistributedDb] Synchronize Client Statistics [" + db.Scope + "] UploadChangesTotal: " + syncStats.UploadChangesTotal, this); } if (syncStats.DownloadChangesTotal > 0) { Log.Info("[DistributedDb] Synchronize Client Statistics [" + db.Scope + "] DownloadChangesTotal: " + syncStats.DownloadChangesTotal, this); } if (syncStats.UploadChangesApplied > 0) { Log.Info("[DistributedDb] Synchronize Client Statistics [" + db.Scope + "] UploadChangesApplied: " + syncStats.UploadChangesApplied, this); } if (syncStats.DownloadChangesApplied > 0) { Log.Info("[DistributedDb] Synchronize Client Statistics [" + db.Scope + "] DownloadChangesApplied: " + syncStats.DownloadChangesApplied, this); } if (syncStats.UploadChangesFailed > 0) { Log.Info("[DistributedDb] Synchronize Client Statistics [" + db.Scope + "] UploadChangesFailed: " + syncStats.UploadChangesFailed, this); } if (syncStats.DownloadChangesFailed > 0) { Log.Info("[DistributedDb] Synchronize Client Statistics [" + db.Scope + "] DownloadChangesFailed: " + syncStats.DownloadChangesFailed, this); } Log.Info("[DistributedDb] Synchronize Client Statistics [" + db.Scope + "] SyncEndTime: " + syncStats.SyncEndTime.ToString("hh:mm:ss.fff"), this); result.Add(db.Scope, syncStats); Log.Info("[DistributedDb] Synchronize Client [" + db.Scope + "] End", this); } catch (Exception ex) { Log.Error("[DistributedDb] Synchronize Client [" + db.Scope + "] Error", ex, this); } } Log.Info("[DistributedDb] Synchronize Client Scope End", this); return(result); }
private DbClientSync InitiateSyncScope(string scopeName, DbSyncScopeDescription scopeDescription, SyncDirectionOrder syncDirection) { Type type = Type.GetType(AppConfig.DbClientSyncClass); if (type == null) { FotoShoutUtils.Log.LogManager.Error(_logger, "The type of the database client sync is not supported."); return(null); } DbClientSync clientSync = (DbClientSync)Activator.CreateInstance(type); // clientSync.ServerConnection = AppConfig.ServerConnection; clientSync.ServerScopeDescription = scopeDescription; clientSync.Configure(AppConfig.SyncAction, scopeName, AppConfig.ClientConnection); if (string.IsNullOrEmpty(AppConfig.SyncAction) || AppConfig.SyncAction.Equals(FotoShoutUtils.Constants.ASV_SYNCACTION_PROVISION, StringComparison.InvariantCultureIgnoreCase)) { // Asign sync direction clientSync.SyncDirection = syncDirection; // Register event handlers for db sync FotoShoutUtils.Log.LogManager.Info(_logger, "Registering event handlers for database sync parties..."); clientSync.ApplyChangeFailed += new ApplyChangeFailedEventHandler(OnDbApplyChangeFailed); clientSync.ItemConflicting += new FotoShoutUtils.Sync.Db.ItemConflictingEventHandler(OnDbItemConflicting); clientSync.ItemConstraint += new FotoShoutUtils.Sync.Db.ItemConstraintEventHandler(OnDbItemConstraint); FotoShoutUtils.Log.LogManager.Info(_logger, "Successfully registered event handlers for database sync parties..."); return(clientSync); } return(null); }
public FileStoreSync(string path, SyncDirectionOrder syncDirection, string[] filters) : base(path, filters) { SyncDirection = syncDirection; }