Exemplo n.º 1
1
 private void CollectStatistics(SyncOperationStatistics stats)
 {
     _syncStats = new SyncStatistics(stats);
 }
        protected void loguearEstadisticas(SyncOperationStatistics estadisticas, DbSyncScopeDescription ambito)
        {
            string message = "";
            message = message + "\n\rEstadisticas de la replica de Sync Framework ambito " + ambito.ScopeName + " cant. tablas: " + ambito.Tables.Count + "";
            message = message + "\n\r\tHora de inicio:\t" + estadisticas.SyncStartTime.ToString();
            message = message + "\n\r\tHora de fin:\t" + estadisticas.SyncEndTime.ToString();
            message = message + "\n\r\tSubida cambios aplicados\t:" + estadisticas.UploadChangesApplied.ToString();
            message = message + "\n\r\tSubida cambios c/error\t:" + estadisticas.UploadChangesFailed.ToString();
            message = message + "\n\r\tSubida cambios Total\t:" + estadisticas.UploadChangesTotal.ToString();
            message = message + "\n\r\tBajada cambios aplicados\t:" + estadisticas.DownloadChangesApplied.ToString();
            message = message + "\n\r\tBajada cambios c/error\t:" + estadisticas.DownloadChangesFailed.ToString();
            message = message + "\n\r\tBajada cambios Total\t:" + estadisticas.DownloadChangesTotal.ToString();

            this.loguear("Estadisticas", message);
        }
Exemplo n.º 3
0
 public void ShowStatistics(SyncOperationStatistics syncStats)
 {
     string message = "";
     listSyncProgress.Items.Add(message);
     message = "-----Sync Statistics -----";
     listSyncProgress.Items.Add(message);
     message = "Sync Start Time :" + syncStats.SyncStartTime.ToString();
     listSyncProgress.Items.Add(message);
     message = "Sync End Time   :" + syncStats.SyncEndTime.ToString();
     listSyncProgress.Items.Add(message);
     message = "Upload Changes Applied :" + syncStats.UploadChangesApplied.ToString();
     listSyncProgress.Items.Add(message);
     message = "Upload Changes Failed  :" + syncStats.UploadChangesFailed.ToString();
     listSyncProgress.Items.Add(message);
     message = "Upload Changes Total   :" + syncStats.UploadChangesTotal.ToString();
     listSyncProgress.Items.Add(message);
     message = "Download Changes Applied :" + syncStats.DownloadChangesApplied.ToString();
     listSyncProgress.Items.Add(message);
     message = "Download Changes Failed  :" + syncStats.DownloadChangesFailed.ToString();
     listSyncProgress.Items.Add(message);
     message = "Download Changes Total   :" + syncStats.DownloadChangesTotal.ToString();
     listSyncProgress.Items.Add(message);
     Application.DoEvents();
 }
Exemplo n.º 4
0
        public bool RunSync()
        {
            SerSettings.run = true;
            count           = 0;

            bool retVal = (SerSettings.dirLocal != null &&
                           Directory.Exists(SerSettings.dirLocal));

            if (retVal)
            {
                eggs.Start();

                foreach (string s in Directory.GetDirectories(SerSettings.dirLocal))
                {
                    mapNetwork = false;
                    stats      = null;
                    egg        = eggs.GetEgg(s);
                    isHatched  = (egg != null);

                    idx = 0;

                    if (!isHatched)
                    {
                        idx = s.LastIndexOf(Settings.backSlash) + 1; // path length
                    }
                    if (idx > 0 || isHatched)
                    {
                        if (!isHatched)
                        {
                            rs = s.Substring(idx, s.Length - idx);
                        }
                        aux = rs;

                        if (rs.Contains(Settings.chSlash) || isHatched)
                        {
                            if (!isHatched)
                            {
                                rs = Settings.GetDirRemoteName(rs);

                                if (rs[0] != Settings.backSlash)
                                {
                                    rs = rs.Insert(1, ":");                              // director local
                                }
                                //Checks if the last character is \ as this causes error on mapping a drive.
                                if (rs.Substring(rs.Length - 1, 1) == @"\")
                                {
                                    rs = rs.Substring(0, rs.Length - 1);
                                }
                            }
                            else
                            {
                                rs = egg.orc.set.dirRemote;
                            }

                            res = (Directory.Exists(rs) && Utils.DirectoryExists(rs));

                            //Lib.WrLog(string.Format(":--> {0} ", rs));

                            // && (Char.IsNumber(rs[2]) || Char.IsNumber(rs[3]))
                            if (Utils.IsRemotePath(rs)) //  ---> TRULLY REMOTE <---
                            {
                                //if (Utils.IsDriveMapped(Settings.mapNetDrives[Settings.mapNetIdx] + Settings.backSlash))
                                //{
                                //    //Utils.ExecuteCommand(string.Format("net use {0} /delete", Settings.mapNetDrive));
                                //    l.DisconnectNetworkDrive(Settings.mapNetDrives[Settings.mapNetIdx], true);

                                //    // System.Threading.Thread.Sleep(100);
                                //}

                                //Utils.ExecuteCommand(string.Format("net use {0} {1} /user:{2} {3} /persistent:no", Settings.mapNetDrive, rs, usr, pas));
                                //Utils.ExecuteCommand("net use V: \"\\\\10.10.10.47\\video\\gi test\" /user:GI 1qaz@WSX");
                                //$$10.10.10.47$video$gi test
                                //\\10.10.10.47\video\gi test

                                //DriveSettings.MapNetworkDrive("W", "\\\\10.10.10.47\\video\\gi test", "GI", "1qaz@WSX");

                                // get user and password from the Passwords file
                                pasFileLastWriteTime = DateTime.MinValue;
                                bool pasFileUpdate = false;

                                if (egg != null && File.Exists(SerSettings.passwFilePath))
                                {
                                    pasFileLastWriteTime = (new FileInfo(SerSettings.passwFilePath)).LastWriteTime;
                                    pasFileUpdate        = eggs.pasFileLastWriteTimeVal != pasFileLastWriteTime.Second;
                                }

                                if (egg == null || pasFileUpdate)
                                {
                                    Settings.SearchPasswordFile(
                                        SerSettings.passwFilePath,
                                        aux, ref usr, ref pas);

                                    if (pasFileUpdate)
                                    {
                                        eggs.pasFileLastWriteTimeVal = pasFileLastWriteTime.Second;
                                        egg.usr = usr;
                                        egg.pas = pas;
                                    }

                                    //usr = "******";
                                    //pas = "******";
                                }


                                if (egg != null)
                                {
                                    usr = egg.usr;
                                    pas = egg.pas;
                                }

                                if (!string.IsNullOrEmpty(usr))
                                {
                                    //if (s[s.Length - 1] == 'w')
                                    //Utils.ExecuteCommand("net use C: \"\\\\10.10.10.47\\home\\www\" /user:GI 1qaz@WSX", @"c:\_sync\$$_temp");


                                    //try
                                    //{
                                    //    Utils.ExecuteCommand(string.Format("net use {0} \"{1}\" /user:{2} {3}", "\\", rs, usr, pas), @"C:\_sync\$$_temp");
                                    //    mapNetwork = true;
                                    //    res = true;
                                    //}
                                    //catch
                                    //{
                                    //    res = false;
                                    //}

                                    // DirectoryInfo di = new DirectoryInfo(rs);
                                    ///DirectorySecurity ds = di.GetAccessControl();
                                    ///

                                    //foreach (AccessRule rule in ds.GetAccessRules(true, true, typeof(NTAccount)))
                                    //{
                                    //Lib.WrLog(string.Format("Identity = {0}; Access = {1}",
                                    //rule.IdentityReference.Value, rule.AccessControlType));
                                    //}

                                    connectStringResult = PinvokeWindowsNetworking.connectToRemote(rs, usr, pas);

                                    if (connectStringResult == null)
                                    {
                                        mapNetwork = true;
                                        res        = true;
                                    }
                                    else
                                    {
                                        Lib.WrLog(rs + connectStringResult);
                                        res = false;
                                    }

                                    //if (l.MapNetworkDrive(rs, Settings.mapNetDrives[Settings.mapNetIdx], usr, pas) == 0)
                                    //{
                                    //    mapNetwork = true;
                                    //    res = true;
                                    //}
                                    //else
                                    //{
                                    //    res = false;
                                    //}
                                }
                            }

                            //VwSync.Imperson.DoWorkUnderImpersonation(rs);

                            if (res)
                            {
                                ++count;
                                try
                                {
                                    if (isHatched)
                                    {
                                        o = egg.orc;
                                        o.DetectChanges();
                                        stats = o.SyncOperationExecute();
                                    }
                                    else
                                    {
                                        o     = new Orchestrator(new Settings(SerSettings.dirLocal, rs));
                                        stats = o.Sync(true, SerSettings.dirLocal, rs);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (o.set.ErrCount < Settings.ErrCountMax)
                                    {
                                        ++o.set.ErrCount;
                                    }
                                    if (egg != null)
                                    {
                                        egg.err = ex;
                                    }
                                }

                                //string
                                //    s1 = (o.GetIdLocal() == null) ? "null" : o.GetIdLocal().ToString(),
                                //    s2 = (o.GetIdRemote() == null) ? "null" : o.GetIdRemote().ToString();
                                //Lib.WrLog(string.Format("{0} {1} :: ===>{2} {3} {4}",
                                //        res, rs, VwSync.Imperson.mesaj, s1, s2));



                                execTime = 0;

                                if (stats != null)
                                {
                                    execTime = stats.SyncEndTime.Subtract(stats.SyncStartTime).Milliseconds;

                                    if (!isHatched)
                                    {
                                        egg = new Egg();
                                        egg.lastExecTimeMs = execTime;
                                        egg.dir            = s;
                                        egg.orc            = o;
                                        egg.isMapped       = mapNetwork;

                                        egg.usr = usr;
                                        egg.pas = pas;

                                        eggs.AddEgg(egg);
                                    }

                                    if (egg != null)
                                    {
                                        egg.wasChecked = true;
                                    }
                                }

                                ultimulTimpTotalDeExecutie += execTime;

                                Lib.WrLog(string.Format(" done {0} in {1}ms", rs, execTime));


                                //Lib.WrLog("xxmapNetwork0" + mapNetwork.ToString());
                                //if (mapNetwork)
                                //{
                                //    Lib.WrLog("xxmapNetwork1");
                                //    Utils.ExecuteCommand(string.Format("net use {0} /delete", Settings.mapNetDrives[Settings.mapNetIdx]));
                                //    //DriveSettings.DisconnectNetworkDrive(Settings.mapNetDrives[Settings.mapNetIdx], true);
                                //}

                                if (!SerSettings.run)
                                {
                                    return(false);
                                }
                            }
                        }

                        if (mapNetwork)
                        {
                            PinvokeWindowsNetworking.disconnectRemote(rs);
                        }
                    }
                }

                retVal = count > 0;

                eggs.Stop();



                Lib.WrLog(eggs.GetCount().ToString());
            }

            SerSettings.run = false;
            return(retVal);
        }
 public SyncResults(string message,
                    SyncOperationStatistics stats)
 {
     Message = message;
     Stats   = stats;
 }
 public FileSystemSynchronizedEventArgs(SyncOperationStatistics syncStats)
     : base(syncStats)
 {
 }
Exemplo n.º 7
0
 public DbSynchronizedEventArgs(SyncOperationStatistics syncStats)
     : base(syncStats)
 {
 }
Exemplo n.º 8
0
        private static void ShowStatistics(SyncOperationStatistics syncStats)
        {
            string message;

            message = "\tSync Start Time :" + syncStats.SyncStartTime;
            Console.WriteLine(message);
            message = "\tSync End Time :" + syncStats.SyncEndTime;
            Console.WriteLine(message);

            message = "\tUpload Changes Applied :" + syncStats.UploadChangesApplied;
            Console.WriteLine(message);
            message = "\tUpload Changes Failed :" + syncStats.UploadChangesFailed;
            Console.WriteLine(message);
            message = "\tUpload Changes Total :" + syncStats.UploadChangesTotal;
            Console.WriteLine(message);
 
            message = "\tDownload Changes Applied :" + syncStats.DownloadChangesApplied;
            Console.WriteLine(message);
            message = "\tDownload Changes Failed :" + syncStats.DownloadChangesFailed;
            Console.WriteLine(message);
            message = "\tDownload Changes Total :" + syncStats.DownloadChangesTotal;
            Console.WriteLine(message);
        } 
Exemplo n.º 9
0
        /// <summary>
        /// Create a backup of remote folder to backup directory, return false in case of upload/download failures (restartable)
        /// throws exception in case of general fault
        /// </summary>
        /// <returns>true if operation finished without faults</returns>
        private bool Backup()
        {
            Guid   backupGuid         = Guid.NewGuid();
            String backupFullPath     = Path.Combine(BackupPath, String.Format(Consts.Backup.SubfolderIncompleteFormat, DateTime.Now));
            String backupCompletePath = Path.Combine(BackupPath, String.Format(Consts.Backup.SubfolderCompleteFormat, DateTime.Now));
            String metafileFolder     = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                                                     Consts.Application.ProfileFolder);
            String backupMetadataFile = String.Format(Consts.Application.MetadataFileFormat, backupGuid.ToString());

            try
            {
                if (State != SyncPairState.Ready)
                {
                    // need to init pair first
                    Init();

                    if (State != SyncPairState.Ready)
                    {
                        return(false);
                    }
                }

                State = SyncPairState.BackingUp;


                // set sync framework environment
                FileSyncScopeFilter filterBackup = new FileSyncScopeFilter();

                if (!Directory.Exists(backupFullPath))
                {
                    Directory.CreateDirectory(backupFullPath);
                }

                if (!Directory.Exists(metafileFolder))
                {
                    Directory.CreateDirectory(metafileFolder);
                }

                FileSyncProvider backupProvider = new FileSyncProvider(backupGuid, backupFullPath, filterBackup,
                                                                       FileSyncOptions.RecycleConflictLoserFiles | FileSyncOptions.RecycleDeletedFiles,
                                                                       metafileFolder, backupMetadataFile, backupFullPath, null);

                backupProvider.Configuration.ConflictResolutionPolicy = ConflictResolutionPolicy.SourceWins;

                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider  = remoteProvider;
                agent.RemoteProvider = backupProvider;
                agent.Direction      = SyncDirectionOrder.DownloadAndUpload;

                SyncOperationStatistics stats = agent.Synchronize();

                // removing metadata file, since it won't be used anymore
                File.Delete(Path.Combine(metafileFolder, backupMetadataFile));

                if ((stats.DownloadChangesFailed + stats.UploadChangesFailed) > 0)
                {
                    // this could be fixed by subsequent backup retry, leaving folder as is
                    Log.Write(String.Format("Problems during backup operation of pair [{0}]<=>[{1}], backup folder [{2}]: {3} download errors, {4} upload errors. Pair processing will continue.",
                                            LocalPath, RemotePath, backupFullPath, stats.DownloadChangesFailed, stats.UploadChangesFailed));
                }

                Directory.Move(backupFullPath, backupCompletePath);

                State = SyncPairState.Ready;
                return((stats.DownloadChangesFailed + stats.UploadChangesFailed) == 0);
            }
            catch (Exception ex)
            {
                // exceptions usually mean that this backup operation failed, subsequent restart probably will not help
                Log.Write(String.Format("Error during backup operation or pair [{0}]<=>[{1}], backup folder [{2}], backup parts will be removed", LocalPath, RemotePath, backupFullPath), ex);

                // trying to remove inconsistent parts
                try
                {
                    Directory.Delete(backupFullPath, true);
                }
                catch (Exception) { }

                try
                {
                    File.Delete(Path.Combine(metafileFolder, backupMetadataFile));
                }
                catch (Exception) { }
                throw ex;
            }
        }
Exemplo n.º 10
0
        public bool Sync(string clientConnectionstring)
        {
            SqlConnection clientConnection = new SqlConnection();

            clientConnection.ConnectionString = @"Data Source=(localdb)\v11.0;Initial Catalog=VideothequeDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";


            // ServerSideSync
            String          scope          = "VideoScope";
            SqlSyncProvider serverProvider = new SqlSyncProvider();

            serverProvider.ScopeName  = scope;
            serverProvider.Connection = new SqlConnection();
            serverProvider.Connection.ConnectionString = @"Data Source =(localdb)\v11.0; Initial Catalog = MoviesDB; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = True; ApplicationIntent = ReadWrite; MultiSubnetFailover = False";


            //Config of the Scope
            DbSyncScopeDescription   scopeDesc    = new DbSyncScopeDescription(scope);
            SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning((System.Data.SqlClient.SqlConnection)serverProvider.Connection);

            if (!serverConfig.ScopeExists(scope))
            {
                serverProvider.ObjectSchema = "dbo.";

                scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Actor", (System.Data.SqlClient.SqlConnection)serverProvider.Connection));
                scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Director", (System.Data.SqlClient.SqlConnection)serverProvider.Connection));
                scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Genre", (System.Data.SqlClient.SqlConnection)serverProvider.Connection));
                scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Movie", (System.Data.SqlClient.SqlConnection)serverProvider.Connection));
                scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("MovieActor", (System.Data.SqlClient.SqlConnection)serverProvider.Connection));
                scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("MovieDirector", (System.Data.SqlClient.SqlConnection)serverProvider.Connection));
                scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("MovieGenre", (System.Data.SqlClient.SqlConnection)serverProvider.Connection));

                serverConfig.PopulateFromScopeDescription(scopeDesc);

                //indicate that the base table already exists and does not need to be created
                serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip);
                //provision the server
                serverConfig.Apply();
            }

            //ClientSideSyncserverConfig
            SqlSyncProvider clientProvider = new SqlSyncProvider();

            clientProvider.ScopeName  = scope;
            clientProvider.Connection = new SqlConnection();
            clientProvider.Connection.ConnectionString = @"Data Source=(localdb)\v11.0;Initial Catalog=VideothequeDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

            //Config of the Scope
            DbSyncScopeDescription   scopeDescClient = new DbSyncScopeDescription(scope);
            SqlSyncScopeProvisioning clientConfig    = new SqlSyncScopeProvisioning((System.Data.SqlClient.SqlConnection)clientProvider.Connection);

            if (!clientConfig.ScopeExists(scope))
            {
                serverProvider.ObjectSchema = "dbo.";

                scopeDescClient.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Actor", (System.Data.SqlClient.SqlConnection)clientProvider.Connection));
                scopeDescClient.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Director", (System.Data.SqlClient.SqlConnection)clientProvider.Connection));
                scopeDescClient.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Genre", (System.Data.SqlClient.SqlConnection)clientProvider.Connection));
                scopeDescClient.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Movie", (System.Data.SqlClient.SqlConnection)clientProvider.Connection));
                scopeDescClient.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("MovieActor", (System.Data.SqlClient.SqlConnection)clientProvider.Connection));
                scopeDescClient.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("MovieDirector", (System.Data.SqlClient.SqlConnection)clientProvider.Connection));
                scopeDescClient.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("MovieGenre", (System.Data.SqlClient.SqlConnection)clientProvider.Connection));

                clientConfig.PopulateFromScopeDescription(scopeDescClient);

                //indicate that the base table already exists and does not need to be created
                clientConfig.SetCreateTableDefault(DbSyncCreationOption.Skip);
                //provision the server
                clientConfig.Apply();
            }



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

            syncOrchestrator.LocalProvider = serverProvider;

            // set the remote provider of orchestrator to a server sync provider associated with
            // the ProductsScope in the SyncDB server database
            syncOrchestrator.RemoteProvider = clientProvider;
            // 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
            ((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler <DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);



            SyncConflictResolver ConflictResolver = new SyncConflictResolver();

            ConflictResolver.ClientDeleteServerUpdateAction = ResolveAction.ServerWins;
            ConflictResolver.ClientUpdateServerDeleteAction = ResolveAction.ServerWins;
            ConflictResolver.ClientInsertServerInsertAction = ResolveAction.ServerWins;

            // execute the synchronization process

            SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();

            // print statistics

            return(true);
        }
Exemplo n.º 11
0
        public static string Synchronise(string syncScope, string pProviderConnectionString, string pClientConnectionString)
        {
            try
            {
                // If all these sync requests are atomic, what happens if there are joined tables, triggers etc?
                // Can sync requests be combined?

                SqlConnection clientConn = new SqlConnection(pProviderConnectionString);

                SqlConnection serverConn = new SqlConnection(pClientConnectionString);

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

                // set local provider of orchestrator to a sync provider associated with the
                // ProductsScope in the SyncExpressDB express client database
                syncOrchestrator.LocalProvider = new SqlSyncProvider(syncScope, 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(syncScope, serverConn);

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

                //If there is an error, 'Program-ApplyChangeFailed()' will be called.
                //This method needs access to the 'stats' string.
                string stats = "";

                // 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

                stats = "\r\n" + syncScope + ": " + syncStats.SyncStartTime + "\r\n";
                stats = stats + "Start Time: " + syncStats.SyncStartTime + "\r\n";
                stats = stats + "Total Changes Uploaded: " + syncStats.UploadChangesTotal + "\r\n";
                stats = stats + "Total Changes Downloaded: " + syncStats.DownloadChangesTotal + "\r\n";
                stats = stats + "Complete Time: " + syncStats.SyncEndTime + "\r\n";

                Logs.SyncLog.WriteLine(stats);

                return(stats);

                void Program_ApplyChangeFailed(object sender, DbApplyChangeFailedEventArgs e)
                {
                    // display conflict type
                    stats += "\r\n" + e.Conflict.Type;

                    // display error message
                    stats += "\r\n" + e.Error;
                }
            }
            catch (Exception e)
            {
                string            message = "There was an error whilst syncing the data. Did you loose connection?";
                string            caption = "Sync Error";
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                DialogResult      result;

                // Displays the MessageBox.

                result = MessageBox.Show(message, caption, buttons);

                if (result == DialogResult.Yes)
                {
                    // Closes the parent form.

                    //this.Close();
                }

                Debug.WriteLine("Exception whilst syncing = " + e);
                return("There was an exception whilst syncing: " + e);
            }
        }
Exemplo n.º 12
0
 private void CollectStatistics(SyncOperationStatistics stats)
 {
     _syncStats = new SyncStatistics(stats);
 }
Exemplo n.º 13
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;
            }
        }
Exemplo n.º 14
0
 public SyncStatistics(SyncOperationStatistics innerStats)
 {
     InnerSyncStatistics = innerStats;
 }
Exemplo n.º 15
0
 public SyncStatistics(SyncOperationStatistics innerStats)
 {
     InnerSyncStatistics = innerStats;
 }
Exemplo n.º 16
0
 public SynchronizedEventArgs(SyncOperationStatistics syncStats)
 {
     _syncStats = syncStats;
 }