Beispiel #1
0
        /// <summary>
        /// Register all conflict types with the conflict manager.
        /// </summary>
        /// <param name="conflictManager"></param>
        public virtual void RegisterConflictTypes(ConflictManager conflictManager)
        {
            if (conflictManager == null)
            {
                throw new ArgumentNullException("conflictManager");
            }

            m_conflictManagementService = conflictManager;
            m_conflictManagementService.RegisterConflictType(new VCInvalidPathConflictType());
            m_conflictManagementService.RegisterConflictType(new VCPathNotMappedConflictType());
            m_conflictManagementService.RegisterConflictType(new VCBranchParentNotFoundConflictType());
            m_conflictManagementService.RegisterConflictType(new GenericConflictType());
            m_conflictManagementService.RegisterConflictType(new TFSHistoryNotFoundConflictType());
            m_conflictManagementService.RegisterConflictType(new UnhandledChangeTypeConflictType(m_validChangeTypes));
        }
Beispiel #2
0
 public static bool HandleGeneralException(
     Exception ex,
     ErrorManager errorManager,
     ConflictManager conflictManager)
 {
     if (null != errorManager)
     {
         errorManager.TryHandleException(ex, conflictManager);
         return(false);
     }
     else
     {
         TraceManager.TraceException(ex);
         return(false);
     }
 }
Beispiel #3
0
        public void RegisterConflictTypes(ConflictManager conflictManager, Guid sourceId)
        {
            if (conflictManager == null)
            {
                throw new ArgumentNullException("conflictManager");
            }
            m_conflictManager = conflictManager;

            m_conflictManager.RegisterConflictType(new GenericConflictType());

            m_conflictManager.RegisterConflictType(sourceId, new ClearQuestGenericConflictType(),
                                                   SyncOrchestrator.ConflictsSyncOrchOptions.StopConflictedSessionCurrentTrip);

            m_conflictManager.RegisterConflictType(sourceId, new ClearQuestMissingCQDllConflictType(),
                                                   SyncOrchestrator.ConflictsSyncOrchOptions.StopConflictedSession);
        }
Beispiel #4
0
        private void RegisterSessionSpecificConflicts(ConflictManager conflictManagementService, SessionTypeEnum sessionType)
        {
            switch (sessionType)
            {
            case SessionTypeEnum.VersionControl:
                RegisterVCContentConflicts(conflictManagementService);
                break;

            case SessionTypeEnum.WorkItemTracking:
                RegisterWITBasicConflicts(conflictManagementService);
                break;

            default:
                throw new InvalidOperationException();
            }
        }
Beispiel #5
0
        public static ConflictStatus GetConflictStatusForDocument(DocumentsOperationContext context, string id, string changeVector, out bool hasLocalClusterTx)
        {
            hasLocalClusterTx = false;

            //tombstones also can be a conflict entry
            var            conflicts = context.DocumentDatabase.DocumentsStorage.ConflictsStorage.GetConflictsFor(context, id);
            ConflictStatus status;

            if (conflicts.Count > 0)
            {
                foreach (var existingConflict in conflicts)
                {
                    status = ChangeVectorUtils.GetConflictStatus(changeVector, existingConflict.ChangeVector);
                    if (status == ConflictStatus.Conflict)
                    {
                        ConflictManager.AssertChangeVectorNotNull(existingConflict.ChangeVector);
                        return(ConflictStatus.Conflict);
                    }
                }
                // this document will resolve the conflicts when putted
                return(ConflictStatus.Update);
            }

            var    result = context.DocumentDatabase.DocumentsStorage.GetDocumentOrTombstone(context, id);
            string local;

            if (result.Document != null)
            {
                local             = result.Document.ChangeVector;
                hasLocalClusterTx = result.Document.Flags.Contain(DocumentFlags.FromClusterTransaction);
            }
            else if (result.Tombstone != null)
            {
                local             = result.Tombstone.ChangeVector;
                hasLocalClusterTx = result.Tombstone.Flags.Contain(DocumentFlags.FromClusterTransaction);
            }
            else
            {
                return(ConflictStatus.Update); //document with 'id' doesn't exist locally, so just do PUT
            }
            status = GetConflictStatusForDocument(context, changeVector, local);
            if (status == ConflictStatus.Conflict)
            {
                ConflictManager.AssertChangeVectorNotNull(local);
            }
            return(status);
        }
        private void RegisterServices(Guid sourceId)
        {
            Debug.Assert(m_serviceContainers.ContainsKey(sourceId),
                         string.Format(MigrationToolkitResources.UnknownSourceId, sourceId));

            ConflictManager conflictManagementService = new ConflictManager(sourceId);

            conflictManagementService.ScopeId = new Guid(m_session.Configuration.SessionUniqueId);
            m_serviceContainers[sourceId].AddService(typeof(ConflictManager), conflictManagementService);
            conflictManagementService.InitializePhase1(m_serviceContainers[sourceId]);

            RegisterConflictTypes(conflictManagementService);

            ICommentDecorationService commentDecorationService = new CommentDecorationService(m_session, m_serviceContainers[sourceId]);

            m_serviceContainers[sourceId].AddService(typeof(ICommentDecorationService), commentDecorationService);
        }
Beispiel #7
0
 internal static ConflictResolutionResult HandleInsufficientPriviledgeException(
     ClearQuestInsufficientPrivilegeException privEx,
     ConflictManager conflictManager)
 {
     if (null != conflictManager)
     {
         MigrationConflict conflict = ClearQuestInsufficentPrivilegeConflictType.CreateConflict(
             privEx.UserName, privEx.UserPrivilegeValue);
         List <MigrationAction> outActions;
         return(conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out outActions));
     }
     else
     {
         TraceManager.TraceException(privEx);
         return(new ConflictResolutionResult(false, ConflictResolutionType.Other));
     }
 }
 public ConflictResolutionResult Resolve(IServiceContainer serviceContainer, MigrationConflict conflict, ConflictResolutionRule rule, out List <MigrationAction> actions)
 {
     actions = null;
     if (rule.ActionRefNameGuid.Equals(new VCChangeGroupInProgressConflictWaitAction().ReferenceName))
     {
         return(new ConflictResolutionResult(true, ConflictResolutionType.Retry));
     }
     if (rule.ActionRefNameGuid.Equals(new VCChangeGroupInProgressConflictSuppressAction().ReferenceName))
     {
         ConflictManager conflictManager = (ConflictManager)serviceContainer.GetService(typeof(ConflictManager));
         RemoveInProgressChangeGroupsInSession(conflictManager.ScopeId);
         return(new ConflictResolutionResult(true, ConflictResolutionType.SuppressedConflictedChangeGroup));
     }
     else
     {
         return(new ConflictResolutionResult(false, ConflictResolutionType.UnknownResolutionAction));
     }
 }
Beispiel #9
0
        /// <summary>
        /// Registers conflict types supported by the provider.
        /// </summary>
        /// <param name="conflictManager"></param>
        public virtual void RegisterConflictTypes(ConflictManager conflictManager)
        {
            if (null == conflictManager)
            {
                throw new ArgumentNullException("conflictManager");
            }
            m_conflictManagementService = conflictManager;

            m_conflictManagementService.RegisterConflictType(new GenericConflictType());
            m_conflictManagementService.RegisterConflictType(new CCAttrTypeNotFoundConflictType());
            m_conflictManagementService.RegisterConflictType(new VCFilePropertyCreationConflictType());
            m_conflictManagementService.RegisterConflictType(new VCInvalidLabelNameConflictType());
            m_conflictManagementService.RegisterConflictType(new VCLabelCreationConflictType());
            m_conflictManagementService.RegisterConflictType(new VCContentConflictType());
            m_conflictManagementService.RegisterConflictType(new VCNameSpaceContentConflictType());
            m_conflictManagementService.RegisterConflictType(new VCInvalidPathConflictType());
            m_conflictManagementService.RegisterConflictType(new CCCheckinConflictType());
        }
Beispiel #10
0
        private void ProviderDetectConflicts(Guid targetSystemId, ChangeGroupService targetChangeGroupService)
        {
            Debug.Assert(m_serviceContainers.ContainsKey(targetSystemId),
                         string.Format(MigrationToolkitResources.UnknownSourceId, targetSystemId));

            IAnalysisProvider targetAnalysisProvider;

            if (!m_analysisProviders.TryGetValue(targetSystemId, out targetAnalysisProvider))
            {
                throw new MigrationException(string.Format(
                                                 MigrationToolkitResources.Culture,
                                                 MigrationToolkitResources.UnknownSourceId,
                                                 targetSystemId));
            }

            try
            {
                int pageNumber = 0;
                IEnumerable <ChangeGroup> changeGroups;
                do
                {
                    TraceManager.TraceInformation("Loading {0} ChangeGroup(s)", m_pageSize);
                    changeGroups = targetChangeGroupService.NextMigrationInstructionTablePage(pageNumber++, m_pageSize, true, false);

                    foreach (ChangeGroup nextChangeGroup in changeGroups)
                    {
                        TraceManager.TraceInformation("Target AnalysisProvider detecting conflicts in ChangeGroup #{0}", nextChangeGroup.ChangeGroupId);
                        targetAnalysisProvider.DetectConflicts(nextChangeGroup);
                    }
                }while (changeGroups.Count() == m_pageSize);
            }
            catch (MigrationUnresolvedConflictException)
            {
                // We have already created an unresolved conflict, just return.
                return;
            }
            catch (Exception e)
            {
                ConflictManager manager = m_serviceContainers[targetSystemId].GetService(typeof(ConflictManager)) as ConflictManager;
                ErrorManager.TryHandleException(e, manager);
            }
        }
Beispiel #11
0
        private ConflictResolutionResult TryResolveConflict(
            string sourceSideItemId,
            IMigrationAction sourceSideAction,
            string targetWiId,
            IMigrationAction targetSideAction)
        {
            string conflictDetails = WITEditEditConflictType.CreateConflictDetails(sourceSideItemId,
                                                                                   sourceSideAction,
                                                                                   targetWiId,
                                                                                   targetSideAction);
            string scopeHint = WITEditEditConflictType.CreateScopeHint(sourceSideItemId,
                                                                       sourceSideAction.Version,
                                                                       targetWiId,
                                                                       targetSideAction.Version);
            MigrationConflict editEditConflict = new WITEditEditConflictType().CreateConflict(conflictDetails, scopeHint, sourceSideAction);

            List <MigrationAction> resolutionActions;

            return(ConflictManager.TryResolveNewConflict(ConflictManager.SourceId, editEditConflict, out resolutionActions));
        }
Beispiel #12
0
        /// <summary>
        /// Register all conflict handlers with ConflictManager
        /// </summary>
        /// <param name="conflictManager"></param>
        public void RegisterConflictTypes(ConflictManager conflictManager)
        {
            if (conflictManager == null)
            {
                throw new ArgumentNullException("conflictManager");
            }

            m_conflictManagerService = conflictManager;

            m_conflictManagerService.RegisterConflictType(new GenericConflictType());

            m_conflictManagerService.RegisterConflictType(new ClearQuestGenericConflictType(),
                                                          SyncOrchestrator.ConflictsSyncOrchOptions.StopConflictedSessionCurrentTrip);

            m_conflictManagerService.RegisterConflictType(new ClearQuestMissingCQDllConflictType(),
                                                          SyncOrchestrator.ConflictsSyncOrchOptions.StopConflictedSession);

            m_conflictManagerService.RegisterConflictType(new ClearQuestInsufficentPrivilegeConflictType(),
                                                          SyncOrchestrator.ConflictsSyncOrchOptions.StopConflictedSession);
        }
Beispiel #13
0
        /// <summary>
        /// Registers conflict types supported by the provider.
        /// </summary>
        /// <param name="conflictManager"></param>
        public virtual void RegisterConflictTypes(ConflictManager conflictManager)
        {
            if (null == conflictManager)
            {
                throw new ArgumentNullException("conflictManager");
            }
            m_conflictManagementService = conflictManager;

            m_conflictManagementService.RegisterConflictType(new InvalidFieldValueConflictType(), SyncOrchestrator.ConflictsSyncOrchOptions.Continue);
            m_conflictManagementService.RegisterConflictType(new WorkItemTypeNotExistConflictType(),
                                                             SyncOrchestrator.ConflictsSyncOrchOptions.Continue);
            m_conflictManagementService.RegisterConflictType(new WITUnmappedWITConflictType(),
                                                             SyncOrchestrator.ConflictsSyncOrchOptions.Continue);
            m_conflictManagementService.RegisterConflictType(new FileAttachmentOversizedConflictType(), SyncOrchestrator.ConflictsSyncOrchOptions.Continue);
            m_conflictManagementService.RegisterConflictType(new GenericConflictType());
            m_conflictManagementService.RegisterConflictType(new WitGeneralConflictType());
            m_conflictManagementService.RegisterConflictType(new InvalidFieldConflictType(), SyncOrchestrator.ConflictsSyncOrchOptions.Continue);
            m_conflictManagementService.RegisterConflictType(new ExcessivePathConflictType(), SyncOrchestrator.ConflictsSyncOrchOptions.Continue);
            m_conflictManagementService.RegisterConflictType(new WorkItemHistoryNotFoundConflictType(), SyncOrchestrator.ConflictsSyncOrchOptions.Continue);
            m_conflictManagementService.RegisterConflictType(new InvalidSubmissionConflictType(), SyncOrchestrator.ConflictsSyncOrchOptions.Continue);
        }
Beispiel #14
0
        public void Initialize(ServiceContainer serviceContainer)
        {
            Debug.Assert(null != serviceContainer, "ServiceContainer is NULL");

            m_serviceContainer = serviceContainer;

            m_linkTranslationService = serviceContainer.GetService(typeof(ILinkTranslationService)) as ILinkTranslationService;
            Debug.Assert(null != m_linkTranslationService, "ILinkTranslationService has not been properly initialized");

            m_configurationService = serviceContainer.GetService(typeof(ConfigurationService)) as ConfigurationService;
            Debug.Assert(null != m_configurationService, "ConfigurationService has not been properly initialized");

            m_hwmLink = new HighWaterMark <DateTime>(ClearQuestConstants.CqLinkHwm);
            m_configurationService.RegisterHighWaterMarkWithSession(m_hwmLink);

            m_linkConfigLookupService = m_linkTranslationService.LinkConfigurationLookupService;

            m_conflictManager = serviceContainer.GetService(typeof(ConflictManager)) as ConflictManager;

            InitializeClient();

            RegisterArtifactHandlers();

            MigrationSource migrSrcConfig = m_configurationService.MigrationSource;

            Debug.Assert(null != migrSrcConfig, "cannot get MigrationSource config from Session");
            foreach (CustomSetting setting in migrSrcConfig.CustomSettings.CustomSetting)
            {
                if (setting.SettingKey.Equals(ClearQuestConstants.CqWebRecordUrlBaseSettingKey, StringComparison.OrdinalIgnoreCase))
                {
                    string urlFormat           = setting.SettingValue;
                    var    recordHyperLinkType = new ClearQuestWebRecordLinkType(urlFormat);
                    m_supportedLinkTypes.Add(recordHyperLinkType.ReferenceName, recordHyperLinkType);
                    ExtractLinkChangeActionsCallback += ((ILinkHandler)recordHyperLinkType).ExtractLinkChangeActions;
                    break;
                }
            }
        }
        public void InitializeServices(IServiceContainer migrationServiceContainer)
        {
            m_migrationServiceContainer = migrationServiceContainer;

            m_changeGroupService = (ChangeGroupService)m_migrationServiceContainer.GetService(typeof(ChangeGroupService));
            Debug.Assert(m_changeGroupService != null, "Change group service is not initialized");

            m_changeGroupService.RegisterDefaultSourceSerializer(new ClearQuestRecordItemSerializer());
            //m_changeGroupService.RegisterSourceSerializer(
            //    WellKnownChangeActionId.SyncContext, new WorkItemContextSyncMigrationItemSerializer());
            m_changeGroupService.RegisterSourceSerializer(
                WellKnownChangeActionId.AddAttachment, new ClearQuestAttachmentItemSerializer());
            m_changeGroupService.RegisterSourceSerializer(
                WellKnownChangeActionId.DelAttachment, new ClearQuestAttachmentItemSerializer());

            m_configurationService = (ConfigurationService)m_migrationServiceContainer.GetService(typeof(ConfigurationService));
            Debug.Assert(m_configurationService != null, "Configuration service is not initialized");

            m_commentDecorationService = (ICommentDecorationService)m_migrationServiceContainer.GetService(typeof(ICommentDecorationService));
            Debug.Assert(m_commentDecorationService != null, "Comment decoration service is not initialized");

            m_conflictManagerService = migrationServiceContainer.GetService(typeof(ConflictManager)) as ConflictManager;
        }
Beispiel #16
0
        /// <summary>
        /// Initialize the adapter services
        /// </summary>
        /// <param name="analysisServiceContainer"></param>
        public void InitializeServices(IServiceContainer analysisServiceContainer)
        {
            m_analysisServiceContainer = analysisServiceContainer;

            m_changeGroupService = (ChangeGroupService)m_analysisServiceContainer.GetService(typeof(ChangeGroupService));
            Debug.Assert(m_changeGroupService != null, "Change group service is not initialized");

            m_changeGroupService.RegisterDefaultSourceSerializer(new ClearQuestRecordItemSerializer());
            //m_changeGroupService.RegisterSourceSerializer(
            //    WellKnownChangeActionId.SyncContext, new WorkItemContextSyncMigrationItemSerializer());
            m_changeGroupService.RegisterSourceSerializer(
                WellKnownChangeActionId.AddAttachment, new ClearQuestAttachmentItemSerializer());
            m_changeGroupService.RegisterSourceSerializer(
                WellKnownChangeActionId.DelAttachment, new ClearQuestAttachmentItemSerializer());

            m_configurationService = (ConfigurationService)m_analysisServiceContainer.GetService(typeof(ConfigurationService));
            Debug.Assert(m_configurationService != null, "Configuration service is not initialized");

            m_conflictManagerService = m_analysisServiceContainer.GetService(typeof(ConflictManager)) as ConflictManager;

            m_hwmDelta = new HighWaterMark <DateTime>(ClearQuestConstants.CqRecordHwm);
            m_configurationService.RegisterHighWaterMarkWithSession(m_hwmDelta);
        }
        /// <summary>
        /// Establish migration context (e.g. WIT metadata sync) on the "sourceId" side
        /// </summary>
        /// <param name="sourceId"></param>
        internal virtual void EstablishContext(Guid sourceId)
        {
            Debug.Assert(m_serviceContainers.ContainsKey(sourceId),
                         string.Format(MigrationToolkitResources.UnknownSourceId, sourceId));

            IMigrationProvider migrationProvider;

            if (!m_migrationProviders.TryGetValue(sourceId, out migrationProvider))
            {
                throw new MigrationException(string.Format(
                                                 MigrationToolkitResources.Culture,
                                                 MigrationToolkitResources.UnknownSourceId,
                                                 sourceId));
            }

            Guid masterSourceId = GetMasterSourceId(sourceId);

            Debug.Assert(!masterSourceId.Equals(Guid.Empty));

            ChangeGroupService sourceSystemChangeGroupService =
                m_serviceContainers[masterSourceId].GetService(typeof(ChangeGroupService)) as ChangeGroupService;

            try
            {
                migrationProvider.EstablishContext(sourceSystemChangeGroupService);
            }
            catch (MigrationUnresolvedConflictException)
            {
                // We have already created an unresolved conflict, just return.
                return;
            }
            catch (Exception e)
            {
                ConflictManager manager = m_serviceContainers[sourceId].GetService(typeof(ConflictManager)) as ConflictManager;
                ErrorManager.TryHandleException(e, manager);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Initialize analysis services
        /// </summary>
        private void RegisterServices(Guid sourceId, RuntimeSession session)
        {
            Debug.Assert(m_serviceContainers.ContainsKey(sourceId),
                         string.Format(MigrationToolkitResources.UnknownSourceId, sourceId));

            ChangeActionRegistrationService changeActionRegistrationService = new ChangeActionRegistrationService();

            m_serviceContainers[sourceId].AddService(typeof(ChangeActionRegistrationService), changeActionRegistrationService);

            ContentTypeRegistrationService contentTypeRegistrationService = new ContentTypeRegistrationService();

            m_serviceContainers[sourceId].AddService(typeof(ContentTypeRegistrationService), contentTypeRegistrationService);

            ConflictManager conflictManagementService = new ConflictManager(sourceId);

            conflictManagementService.ScopeId = new Guid(m_session.Configuration.SessionUniqueId);
            m_serviceContainers[sourceId].AddService(typeof(ConflictManager), conflictManagementService);
            conflictManagementService.InitializePhase1(m_serviceContainers[sourceId]);

            RegisterGenericeConflicts(conflictManagementService);
            RegisterSessionSpecificConflicts(conflictManagementService, session.Configuration.SessionType);

            ICommentDecorationService commentDecorationService = new CommentDecorationService(m_session, m_serviceContainers[sourceId]);

            m_serviceContainers[sourceId].AddService(typeof(ICommentDecorationService), commentDecorationService);

            ChangeGroupService changeGroupService = m_serviceContainers[sourceId].GetService(typeof(ChangeGroupService)) as ChangeGroupService;

            if (changeGroupService != null)
            {
                changeGroupService.PreChangeGroupSaved += new EventHandler <ChangeGroupEventArgs>(changeGroupService_PreChangeGroupSaved);
                if (!m_changeGroupServices.ContainsKey(sourceId))
                {
                    m_changeGroupServices.Add(sourceId, changeGroupService);
                }
            }
        }
        private void IndexActiveMods(object sender, RoutedEventArgs e)
        {
            try
            {
                var stopwatch = Stopwatch.StartNew();

                var filename        = Constants.modChangesFileName;
                var detailsFilename = Constants.DetailChangesFileName;


                var changes = new Dictionary <string, List <Dictionary <string, string> > >();
                var cm      = new ConflictManager();

                var ordered      = ModList.Where(c => c.Active).OrderBy(c => c.Order).ToList();
                var baseGameData = new GameData();

                foreach (var item in new string[6] {
                    "gamedata.base",
                    "Newwworld.mod",
                    "Dialogue.mod",
                    "Vitali.mod",
                    "Nizu.mod",
                    "rebirth.mod"
                })
                {
                    cm.LoadMods(Path.Combine(LoadService.config.GamePath, "data", item), ModMode.BASE, baseGameData);
                }

                foreach (var mod in ordered)
                {
                    cm.LoadMods(mod.FilePath, ModMode.ACTIVE, baseGameData);
                }

                baseGameData.resolveAllReferences();

                cm.LoadBaseChanges(baseGameData);

                baseGameData = null;

                foreach (var mod in ordered)
                {
                    Console.WriteLine($"{mod.DisplayName} Loading...");
                    var gd = new GameData();

                    cm.LoadMods(mod.FilePath, ModMode.ACTIVE, gd);

                    cm.ListOfGameData.Add(gd);


                    if (!Directory.Exists("indexedMods"))
                    {
                        Directory.CreateDirectory("indexedMods");
                    }
                    File.WriteAllText($"indexedMods/{mod.DisplayName}", JsonConvert.SerializeObject(new { gd.Signature, mod.DisplayName, gd.header.Version, gd.items }, new JsonSerializerSettings {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }));
                }



                stopwatch.Stop();
                Console.WriteLine(stopwatch.ElapsedMilliseconds / 1000 + " Seconds Elapsed");
            }
            catch (Exception ex)
            {
                MessageBox.Show("I'm working on this feature... it's complicated :)");
            }
        }
Beispiel #20
0
 private void RegisterGenericeConflicts(ConflictManager conflictManagementService)
 {
     conflictManagementService.RegisterToolkitConflictType(
         new GenericConflictType(),
         SyncOrchestrator.ConflictsSyncOrchOptions.StopConflictedSessionCurrentTrip);
 }
        internal void Migrate(Guid targetSideSourceId, SessionOrchestrationPolicy orchPolicy)
        {
            try
            {
                Debug.Assert(m_serviceContainers.ContainsKey(targetSideSourceId), string.Format(MigrationToolkitResources.UnknownSourceId, targetSideSourceId));

                ChangeGroupService changegroupService = (ChangeGroupService)m_serviceContainers[targetSideSourceId].GetService(
                    typeof(ChangeGroupService));
                Debug.Assert(changegroupService != null, string.Format("Change group service on {0} is not loaded", targetSideSourceId));

                changegroupService.DemoteInProgressActionsToPending();

                int pageNumber = 0;
                IEnumerable <ChangeGroup> changeGroups = null;

                long?firstConflictedChangeGroupId = null;
                if (StopMigrationEngineOnBasicConflict)
                {
                    firstConflictedChangeGroupId = changegroupService.GetFirstConflictedChangeGroup(ChangeStatus.Pending);
                }

                do
                {
                    // NOTE: we do not increment pageNumber here, because the processed ChangeGroups are marked "Complete" and no longer
                    //       appear in the table
                    TraceManager.TraceInformation("Loading {0} ChangeGroup(s)", m_pageSize);
                    changeGroups = changegroupService.NextMigrationInstructionTablePage(pageNumber, m_pageSize, false, false);

                    foreach (ChangeGroup nextChangeGroup in changeGroups)
                    {
                        if (firstConflictedChangeGroupId.HasValue &&
                            firstConflictedChangeGroupId <= nextChangeGroup.ChangeGroupId)
                        {
                            // we should not process any conflicted change group or the following ones
                            // if StopMigrationEngineOnBasicConflict is the policy
                            return;
                        }

                        //ToDo Session.OnMigratingChangeStarting(args);
                        TraceManager.TraceInformation("Processing ChangeGroup #{0}", nextChangeGroup.ChangeGroupId);
                        ProcessMigrInstructionTableEntry(nextChangeGroup, targetSideSourceId);
                        nextChangeGroup.UpdateStatus(ChangeStatus.InProgress);

                        if (NoActiveMigrationInstructionInChangeGroup(nextChangeGroup))
                        {
                            nextChangeGroup.Complete();
                            continue;
                        }

                        ConversionResult result;
                        try
                        {
                            result = m_migrationProviders[targetSideSourceId].ProcessChangeGroup(nextChangeGroup);
                        }
                        catch (MigrationUnresolvedConflictException)
                        {
                            // We have already created an unresolved conflict, just return.
                            return;
                        }
                        catch (Exception e)
                        {
                            ConflictManager manager = m_serviceContainers[targetSideSourceId].GetService(typeof(ConflictManager)) as ConflictManager;
                            ErrorManager.TryHandleException(e, manager);
                            return;
                        }

                        if (!result.ContinueProcessing)
                        {
                            return;
                        }

                        if (!string.IsNullOrEmpty(result.ChangeId))
                        {
                            FinishChangeGroupMigration(nextChangeGroup, result);
                            InvokePostChangeGroupMigrationAddins(targetSideSourceId, nextChangeGroup);
                        }
                        orchPolicy.Check();
                    }
                }while (changeGroups.Count() == m_pageSize);
            }
            catch (Microsoft.TeamFoundation.Migration.Toolkit.SessionOrchestrationPolicy.StopSingleTripException)
            {
                throw;
            }
            catch (Microsoft.TeamFoundation.Migration.Toolkit.SessionOrchestrationPolicy.StopSessionException)
            {
                throw;
            }
            catch (Exception e)
            {
                ConflictManager manager = m_serviceContainers[targetSideSourceId].GetService(typeof(ConflictManager)) as ConflictManager;
                ErrorManager.TryHandleException(e, manager);
            }
        }
 private void RegisterConflictTypes(ConflictManager manager)
 {
     manager.RegisterConflictType(
         new GenericConflictType(),
         SyncOrchestrator.ConflictsSyncOrchOptions.StopConflictedSessionCurrentTrip);
 }
Beispiel #23
0
 private void RegisterVCContentConflicts(ConflictManager conflictManagementService)
 {
     conflictManagementService.RegisterToolkitConflictType(new VCContentConflictType());
     conflictManagementService.RegisterToolkitConflictType(new VCNameSpaceContentConflictType());
 }
Beispiel #24
0
        /// <summary>
        /// Generate migration instructions
        /// </summary>
        internal void GenerateMigrationInstructions(Guid targetSystemId)
        {
            try
            {
                // Given target system, find change group service for source and for ourselves...
                ConfigurationService configurationService = m_serviceContainers[targetSystemId].GetService(typeof(ConfigurationService)) as ConfigurationService;

                // ToDo, not sure, we can probably just pass in ource system id to let target change group service to load it. But source/target may be different, not sqlchangegroupmanager
                ChangeGroupService sourceChangeGroupService = m_serviceContainers[configurationService.MigrationPeer].GetService(typeof(ChangeGroupService)) as ChangeGroupService;
                ChangeGroupService targetChangeGroupService = m_serviceContainers[targetSystemId].GetService(typeof(ChangeGroupService)) as ChangeGroupService;

                // CopySourceDeltaTableToTarget
                //ChangeGroup deltaTableEntry;

                if (StopMigrationEngineOnBasicConflict)
                {
                    // if one of the delta table entry on source side is conflicted, we stop
                    long?firstConflictedChangeGroupId = sourceChangeGroupService.GetFirstConflictedChangeGroup(ChangeStatus.DeltaPending);
                    if (firstConflictedChangeGroupId.HasValue)
                    {
                        return;
                    }

                    // if one of the migration instruction for target side is conflict, we also stop
                    firstConflictedChangeGroupId = targetChangeGroupService.GetFirstConflictedChangeGroup(ChangeStatus.Pending);
                    if (firstConflictedChangeGroupId.HasValue)
                    {
                        return;
                    }
                }

                ChangeActionRegistrationService changeActionRegistrationService =
                    m_serviceContainers[targetSystemId].GetService(typeof(ChangeActionRegistrationService)) as ChangeActionRegistrationService;

                int pageNumber = 0;
                IEnumerable <ChangeGroup> changeGroups;
                do
                {
                    // NOTE: we do not increment pageNumber here, because the processed ChangeGroups are marked "DeltaComplete" and no longer
                    //       appear in the delta table
                    changeGroups = sourceChangeGroupService.NextDeltaTablePage(pageNumber, m_pageSize, false);
                    foreach (ChangeGroup deltaTableEntry in changeGroups)
                    {
                        TraceManager.TraceInformation(string.Format(
                                                          "Generating migration instruction for ChangeGroup {0}",
                                                          deltaTableEntry.ChangeGroupId));

                        ChangeGroup migrationInstructionChangeGroup = targetChangeGroupService.CreateChangeGroupForMigrationInstructionTable(deltaTableEntry);

                        // NOTE:
                        // migration instruction change group is created using the target change group manager/service
                        // however, the MigrationItems in it are created by the source-side adapter
                        // by setting the UseOtherSideMigrationItemSerializers flag, we tell this change group to use the source-side change group manager
                        // to find the registered IMigrationItem serializer to persist these MigrationItems
                        migrationInstructionChangeGroup.UseOtherSideMigrationItemSerializers = true;

                        migrationInstructionChangeGroup.ReflectedChangeGroupId = deltaTableEntry.ChangeGroupId;

                        foreach (MigrationAction action in deltaTableEntry.Actions)
                        {
                            try
                            {
                                BeforeCopyDeltaTableEntryToMigrationInstructionTable(action, configurationService.MigrationPeer);
                            }
                            catch (UnmappedWorkItemTypeException unmappedWITEx)
                            {
                                ConflictManager conflictManager =
                                    m_serviceContainers[configurationService.MigrationPeer].GetService(typeof(ConflictManager)) as ConflictManager;

                                var conflict = WITUnmappedWITConflictType.CreateConflict(unmappedWITEx.SourceWorkItemType, action);

                                List <MigrationAction> actions;
                                var result = conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out actions);

                                if (!result.Resolved)
                                {
                                    continue;
                                }
                                else
                                {
                                    if (result.ResolutionType == ConflictResolutionType.SkipConflictedChangeAction)
                                    {
                                        action.State = ActionState.Skipped;
                                        continue;
                                    }
                                    else
                                    {
                                        // NOTE:
                                        // So far this conflict can only be:
                                        // 1. manually resolved (skipped) AFTER
                                        //    the configuration is updated with the requirement WIT mapping;
                                        // 2. skipping the conflicted migration action (i.e. not migrating the source
                                        //    Work Item type.
                                        Debug.Assert(
                                            false,
                                            string.Format("WITUnmappedWITConflict is auto-resolved. Skipping this assertion will SKIP the original conflicted action '{0}'.",
                                                          action.ActionId.ToString()));
                                        action.State = ActionState.Skipped;
                                        continue;
                                    }
                                }
                            }

                            if (action.State == ActionState.Skipped || action.ChangeGroup.ContainsBackloggedAction)
                            {
                                continue;
                            }
                            ChangeActionHandler actionHandler;
                            if (changeActionRegistrationService.TryGetChangeActionHandler(action.Action, action.ItemTypeReferenceName, out actionHandler))
                            {
                                try
                                {
                                    actionHandler(action, migrationInstructionChangeGroup);
                                }
                                catch (MigrationUnresolvedConflictException)
                                {
                                    // We have already created an unresolved conflict, just return.
                                    return;
                                }
                                catch (Exception e)
                                {
                                    ConflictManager manager = m_serviceContainers[targetSystemId].GetService(typeof(ConflictManager)) as ConflictManager;
                                    ErrorManager.TryHandleException(e, manager);
                                }
                            }
                            else
                            {
                                string            analysisProviderName;
                                IAnalysisProvider analysisProvider;
                                if (m_analysisProviders.TryGetValue(targetSystemId, out analysisProvider))
                                {
                                    analysisProviderName = analysisProvider.GetType().ToString();
                                }
                                else
                                {
                                    Debug.Fail("Unable to find IAnalysisProvider with Id: " + targetSystemId);
                                    analysisProviderName = "Unknown";
                                }
                                throw new MigrationException(
                                          string.Format(MigrationToolkitResources.Culture, MigrationToolkitResources.UnknownChangeAction,
                                                        action.Action.ToString(), analysisProviderName));
                            }
                        }

                        if (!migrationInstructionChangeGroup.ContainsBackloggedAction &&
                            migrationInstructionChangeGroup.Actions.Count > 0)
                        {
                            ChangeStatus status = migrationInstructionChangeGroup.Status;
                            migrationInstructionChangeGroup.Status = ChangeStatus.ChangeCreationInProgress;
                            migrationInstructionChangeGroup.Owner  = deltaTableEntry.Owner; // owner may be translated too
                            // Save the partial Change group into DB.
                            migrationInstructionChangeGroup.Save();

                            // Commit the status change together.
                            migrationInstructionChangeGroup.Status = status;
                            deltaTableEntry.Status = ChangeStatus.DeltaComplete;
                            migrationInstructionChangeGroup.Manager.BatchUpdateStatus(
                                new ChangeGroup[] { migrationInstructionChangeGroup, deltaTableEntry });
                        }
                        else
                        {
                            // If all change actions in the delta table entry are skipped.
                            // Just mark the delta table entry as completed.
                            deltaTableEntry.UpdateStatus(ChangeStatus.DeltaComplete);
                        }

                        if (this.StopRequested)
                        {
                            return;
                        }
                    }
                }while (changeGroups.Count() == m_pageSize);

                DetectBasicConflicts(targetChangeGroupService, targetSystemId, configurationService.MigrationPeer);

                if (this.StopRequested)
                {
                    return;
                }

                ProviderDetectConflicts(targetSystemId, targetChangeGroupService);

                if (this.StopRequested)
                {
                    return;
                }

                // dispose the target side delta table entries after we've done all conflict analysis
                targetChangeGroupService.BatchMarkMigrationInstructionsAsPending();
            }
            catch (Exception e)
            {
                ConflictManager manager = m_serviceContainers[targetSystemId].GetService(typeof(ConflictManager)) as ConflictManager;
                ErrorManager.TryHandleException(e, manager);
            }
        }
        private bool SubmitWorkItemLinkChanges(
            LinkChangeGroup linkChanges,
            ServiceContainer serviceContainer,
            ConfigurationService configService,
            ITranslationService translationService,
            TfsLinkingProviderBase.LinkSubmissionPhase submissionPhase)
        {
            var linkChangeActions = ExtractWorkItemLinkChanges(linkChanges);

            if (linkChangeActions.Count == 0)
            {
                return(true);
            }

            ConflictManager conflictManageer         = serviceContainer.GetService(typeof(ConflictManager)) as ConflictManager;
            var             updatedocsForEditLinks   = new List <XmlDocument>(linkChangeActions.Count);
            var             updateDocsForAddLinks    = new List <XmlDocument>(linkChangeActions.Count);
            var             updateDocsForDeleteLinks = new List <XmlDocument>(linkChangeActions.Count);
            Dictionary <int, LinkChangeAction> docForEditlinksToActionMap   = new Dictionary <int, LinkChangeAction>();
            Dictionary <int, LinkChangeAction> docForAddlinksToActionMap    = new Dictionary <int, LinkChangeAction>();
            Dictionary <int, LinkChangeAction> docForDeletelinksToActionMap = new Dictionary <int, LinkChangeAction>();

            for (int i = 0; i < linkChangeActions.Count; ++i)
            {
                if (linkChangeActions[i].Status != LinkChangeAction.LinkChangeActionStatus.ReadyForMigration ||
                    linkChangeActions[i].IsConflicted)
                {
                    continue;
                }

                if (!ProcessActionInCurrentSubmissionPhase(linkChangeActions[i], submissionPhase))
                {
                    continue;
                }

                var tfsUpdateDocument = InitializeUpdateDocument();

                var handler = linkChangeActions[i].Link.LinkType as ILinkHandler;
                Debug.Assert(null != handler);

                handler.UpdateTfs(tfsUpdateDocument, linkChangeActions[i]);

                if (linkChangeActions[i].ChangeActionId.Equals(WellKnownChangeActionId.Add))
                {
                    docForAddlinksToActionMap.Add(updateDocsForAddLinks.Count, linkChangeActions[i]);
                    updateDocsForAddLinks.Add(tfsUpdateDocument.UpdateDocument);
                }
                else if (linkChangeActions[i].ChangeActionId.Equals(WellKnownChangeActionId.Delete))
                {
                    docForDeletelinksToActionMap.Add(updateDocsForDeleteLinks.Count, linkChangeActions[i]);
                    updateDocsForDeleteLinks.Add(tfsUpdateDocument.UpdateDocument);
                }
                else if (linkChangeActions[i].ChangeActionId.Equals(WellKnownChangeActionId.Edit))
                {
                    docForEditlinksToActionMap.Add(updatedocsForEditLinks.Count, linkChangeActions[i]);
                    updatedocsForEditLinks.Add(tfsUpdateDocument.UpdateDocument);
                }
                else
                {
                    TraceManager.TraceVerbose("Change action '{0}' in Link Change Group '{1}' is not supported.",
                                              linkChangeActions[i].ChangeActionId.ToString(), linkChanges.GroupName);
                    linkChangeActions[i].Status = LinkChangeAction.LinkChangeActionStatus.Completed;
                }
            }

            bool succeeded = true;

            if (updatedocsForEditLinks.Count > 0)
            {
                succeeded &= SubmitBatchedAddOrDeleteLinkChanges(
                    updatedocsForEditLinks, docForEditlinksToActionMap, translationService, configService, conflictManageer);
            }
            if (updateDocsForDeleteLinks.Count > 0)
            {
                succeeded &= SubmitBatchedAddOrDeleteLinkChanges(
                    updateDocsForDeleteLinks, docForDeletelinksToActionMap, translationService, configService, conflictManageer);
            }
            if (updateDocsForAddLinks.Count > 0)
            {
                succeeded &= SubmitBatchedAddOrDeleteLinkChanges(
                    updateDocsForAddLinks, docForAddlinksToActionMap, translationService, configService, conflictManageer);
            }
            return(succeeded);
        }
        private bool SubmitBatchedAddOrDeleteLinkChanges(
            List <XmlDocument> updateDocuments,
            Dictionary <int, LinkChangeAction> updateDocIndexToLinkChangeActionMap,
            ITranslationService translationService,
            ConfigurationService configService,
            ConflictManager conflictManager)
        {
            bool succeeded = true;

            UpdateResult[] results = TfsBatchUpdateHelper.Submit(Core, WorkItemServer, updateDocuments.ToArray());
            if (results.Length != updateDocuments.Count)
            {
                throw new SynchronizationEngineException("Wrong number of link update results.");
            }

            // Collect list of successful LinkChangeActions (for LinkTypes with GetsActionsFromLinkChangeHistory true) to pass to SetServerLinkChangeIds()
            List <LinkChangeAction> actionsNeedingServerLinkIdSet = new List <LinkChangeAction>();

            for (int i = 0; i < results.Length; ++i)
            {
                UpdateResult rslt = results[i];

                if (rslt.Exception != null)
                {
                    if (rslt.Exception.Message.Contains("The specified link already exists"))
                    {
                        // it is ok to eat this exception

                        // mark the change action completed so it is not retried later
                        LinkChangeAction action = updateDocIndexToLinkChangeActionMap[i];
                        action.Status = LinkChangeAction.LinkChangeActionStatus.Skipped;

                        TraceManager.TraceInformation("Tried to add a link that already exists so skipping it: " + GetLinkChangeActionDescription(action));

                        System.Web.Services.Protocols.SoapException soapException = rslt.Exception as System.Web.Services.Protocols.SoapException;
                        if (soapException != null)
                        {
                            TraceManager.TraceVerbose("SoapException.Detail.InnerXml for ignored exception: " + soapException.Detail.InnerXml);
                        }
                    }
                    else if (updateDocIndexToLinkChangeActionMap[i].ChangeActionId == WellKnownChangeActionId.Delete && rslt.Exception.Message.Contains("This specified link does not exist"))
                    {
                        // it is ok to eat this exception and skip the action

                        // mark the change action completed so it is not retried later
                        LinkChangeAction action = updateDocIndexToLinkChangeActionMap[i];
                        action.Status = LinkChangeAction.LinkChangeActionStatus.Skipped;

                        TraceManager.TraceInformation("Tried to delete a link that does not exist so skipping it: " + GetLinkChangeActionDescription(action));

                        System.Web.Services.Protocols.SoapException soapException = rslt.Exception as System.Web.Services.Protocols.SoapException;
                        if (soapException != null)
                        {
                            TraceManager.TraceVerbose("SoapException.Detail.InnerXml for ignored exception: " + soapException.Detail.InnerXml);
                        }
                    }
                    else if (rslt.Exception is System.Web.Services.Protocols.SoapException &&
                             null != rslt.Exception.Message &&
                             rslt.Exception.Message.StartsWith(
                                 TFSMulitpleParentLinkConflictType.SingleParentViolationMessage,
                                 StringComparison.OrdinalIgnoreCase))
                    {
                        MigrationConflict conflict = TFSMulitpleParentLinkConflictType.CreateConflict(
                            updateDocIndexToLinkChangeActionMap[i], rslt.Exception);

                        List <MigrationAction> actions;
                        var resolutionRslt = conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out actions);
                        if (!resolutionRslt.Resolved)
                        {
                            updateDocIndexToLinkChangeActionMap[i].IsConflicted = true;
                            succeeded = false;
                        }
                    }
                    else if (rslt.Exception is System.Web.Services.Protocols.SoapException &&
                             null != rslt.Exception.Message &&
                             rslt.Exception.Message.StartsWith(
                                 TFSCyclicLinkConflictType.CircularityLinkHierarchyViolationMessage,
                                 StringComparison.OrdinalIgnoreCase))
                    {
                        ILinkProvider linkProvider = ServiceContainer.GetService(typeof(ILinkProvider)) as ILinkProvider;
                        Debug.Assert(null != linkProvider, "linkProvider is NULL");

                        LinkChangeAction          conflictedAction = updateDocIndexToLinkChangeActionMap[i];
                        NonCyclicReferenceClosure linkRefClosure   =
                            linkProvider.CreateNonCyclicLinkReferenceClosure(conflictedAction.Link.LinkType, conflictedAction.Link.SourceArtifact);

                        MigrationConflict conflict = TFSCyclicLinkConflictType.CreateConflict(conflictedAction, rslt.Exception, linkRefClosure);

                        List <MigrationAction> actions;
                        var resolutionRslt = conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out actions);
                        if (!resolutionRslt.Resolved)
                        {
                            updateDocIndexToLinkChangeActionMap[i].IsConflicted = true;
                            succeeded = false;
                        }
                    }
                    else if (rslt.Exception is System.Web.Services.Protocols.SoapException &&
                             null != rslt.Exception.Message &&
                             rslt.Exception.Message.StartsWith(
                                 TFSModifyLockedWorkItemLinkConflictType.ModifyLockedWorkItemLinkViolationMessage,
                                 StringComparison.OrdinalIgnoreCase))
                    {
                        MigrationConflict conflict = TFSModifyLockedWorkItemLinkConflictType.CreateConflict(
                            updateDocIndexToLinkChangeActionMap[i], rslt.Exception);

                        List <MigrationAction> actions;
                        var resolutionRslt = conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out actions);
                        if (!resolutionRslt.Resolved)
                        {
                            updateDocIndexToLinkChangeActionMap[i].IsConflicted = true;
                        }
                        // returning "not succeeded" so that the caller keeps this change group in "ReadyForMigration" status
                        succeeded = false;
                    }
                    else if (rslt.Exception is System.Web.Services.Protocols.SoapException &&
                             null != rslt.Exception.Message &&
                             (rslt.Exception.Message.StartsWith(TFSLinkAccessViolationConflictType.LinkAccessViolationMessage1, StringComparison.OrdinalIgnoreCase) ||
                              rslt.Exception.Message.StartsWith(TFSLinkAccessViolationConflictType.LinkAccessViolationMessage2, StringComparison.OrdinalIgnoreCase)))
                    {
                        MigrationConflict conflict = TFSLinkAccessViolationConflictType.CreateConflict(
                            updateDocIndexToLinkChangeActionMap[i], rslt.Exception);

                        List <MigrationAction> actions;
                        var resolutionRslt = conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out actions);
                        if (!resolutionRslt.Resolved)
                        {
                            updateDocIndexToLinkChangeActionMap[i].IsConflicted = true;
                        }
                        // returning "not succeeded" so that the caller keeps this change group in "ReadyForMigration" status
                        succeeded = false;
                    }
                    else
                    {
                        LinkChangeAction action = updateDocIndexToLinkChangeActionMap[i];
                        // TODO
                        // Try resolve conflict and push to backlog if resolution fails
                        action.IsConflicted = true;

                        TraceManager.TraceError(String.Format(CultureInfo.InvariantCulture,
                                                              "Exception processing {0}: {1}", GetLinkChangeActionDescription(action), rslt.Exception.ToString()));
                        succeeded = false;
                    }
                }
                else // rslt.Exception == null
                {
                    LinkChangeAction successfulAction = updateDocIndexToLinkChangeActionMap[i];
                    MarkLinkChangeActionCompleted(successfulAction);

                    TraceManager.TraceVerbose("Successful " + GetLinkChangeActionDescription(successfulAction));

                    List <LinkChangeAction> updatedActions = new List <LinkChangeAction>();
                    updatedActions.Add(successfulAction);

                    if (successfulAction.Link.LinkType.GetsActionsFromLinkChangeHistory)
                    {
                        actionsNeedingServerLinkIdSet.Add(successfulAction);
                    }

                    UpdateLinkConversionHistory(configService, translationService, rslt, updatedActions);
                }
            }

            SetServerLinkChangeIds(actionsNeedingServerLinkIdSet);

            return(succeeded);
        }
Beispiel #27
0
 public void RegisterConflictTypes(ConflictManager conflictManager)
 {
 }
        protected override TfsUpdateDocument SubmitAttachmentChanges(IMigrationAction action, ConflictManager conflictMgrService)
        {
            /*
             * retrieve change details
             */
            XmlDocument desc     = action.MigrationActionDescription;
            XmlElement  rootNode = desc.DocumentElement;

            Debug.Assert(null != rootNode);
            XmlNode attachmentNode   = rootNode.FirstChild;
            string  originalName     = attachmentNode.Attributes["Name"].Value;
            string  utcCreationDate  = attachmentNode.Attributes["UtcCreationDate"].Value;
            string  utcLastWriteDate = attachmentNode.Attributes["UtcLastWriteDate"].Value;
            string  length           = attachmentNode.Attributes["Length"].Value;
            string  comment          = attachmentNode.FirstChild.InnerText;
            int     targetWorkItemId = FindTargetWorkItemId(action, conflictMgrService);
            string  targetRevision   = rootNode.Attributes["TargetRevision"].Value;

            /*
             * create operation document
             */
            TfsUpdateDocument tfsUpdateDocument = InitializeUpdateDocument();

            tfsUpdateDocument.CreateWorkItemUpdateDoc(targetWorkItemId.ToString(), targetRevision);

            /*
             * insert Connector specific comment
             */
            WorkItem item = WorkItemStore.GetWorkItem(targetWorkItemId);

            Debug.Assert(null != item, "target work item does not exist");
            tfsUpdateDocument.InsertConversionHistoryCommentToHistory(item.Type.Name, GenerateMigrationHistoryComment(action));

            int[] fileId = FindAttachmentFileId(targetWorkItemId, originalName,
                                                utcCreationDate, utcLastWriteDate, length, comment);

            /*
             * delete attachment
             */
            if (action.Action == WellKnownChangeActionId.DelAttachment)
            {
                if (fileId.Length == 0)
                {
                    action.State = ActionState.Skipped;
                    return(null);
                }
                else
                {
                    tfsUpdateDocument.RemoveAttachment(fileId[0]);
                    return(tfsUpdateDocument);
                }
            }

            /*
             * add attachment
             */
            try
            {
                string sourceStoreCountString = attachmentNode.Attributes["CountInSourceSideStore"].Value;
                int    sourceStoreCount;
                if (int.TryParse(sourceStoreCountString, out sourceStoreCount))
                {
                    if (sourceStoreCount <= fileId.Length)
                    {
                        action.State = ActionState.Skipped;
                        return(null);
                    }
                }
            }
            catch (Exception e)
            {
                TraceManager.TraceVerbose(e.ToString());
                // for backward compatibility, just proceed
            }

            if (AttachmentIsOversized(length))
            {
                MigrationConflict conflict = new FileAttachmentOversizedConflictType().CreateConflict(
                    originalName, length, MaxAttachmentSize, targetWorkItemId.ToString(), Core.ServerName, Core.Config.Project, action);

                List <MigrationAction>   actions;
                ConflictResolutionResult resolveRslt = conflictMgrService.TryResolveNewConflict(conflictMgrService.SourceId, conflict, out actions);

                if (!resolveRslt.Resolved)
                {
                    return(null);
                }

                if (resolveRslt.ResolutionType == ConflictResolutionType.SuppressedConflictedChangeAction)
                {
                    action.State = ActionState.Skipped;
                    return(null);
                }

                if (resolveRslt.ResolutionType == ConflictResolutionType.Other)
                {
                    // conflict resolved, just proceed
                }
                else
                {
                    throw new NotImplementedException();
                }
            }

            Guid fileGuid = Guid.NewGuid();

            tfsUpdateDocument.AddAttachment(originalName, XmlConvert.ToString(fileGuid),
                                            utcCreationDate, utcLastWriteDate, length, comment);

            // get areaNodeUri - required by Dev10 OM
            Project project        = item.Project;
            string  projectNodeUri = (project.Uri).ToString();
            string  areaNodeUri    = string.Empty;

            if (project.Id == item.AreaId)
            {
                areaNodeUri = Core.AreaNodeUri;
            }
            else
            {
                // Loop through the area root nodes looking for the one we're on
                foreach (Node node in project.AreaRootNodes)
                {
                    // It could be one of the root nodes
                    if (node.Id == item.AreaId)
                    {
                        areaNodeUri = node.Uri.ToString();
                        break;
                    }

                    // Now check if it is a child of the current area root node
                    try
                    {
                        Node node2 = node.FindNodeInSubTree(item.AreaId);
                        areaNodeUri = node2.Uri.ToString();
                        break;
                    }
                    catch (DeniedOrNotExistException)
                    {
                        // Ignore if not found, go onto the next area root node
                        continue;
                    }
                }
            }

            //Now upload the file since that has to be done before the Xml batch is executed.
            Debug.Assert(!string.IsNullOrEmpty(LocalWorkDir));
            string filePath = Path.Combine(LocalWorkDir, fileGuid.ToString());

            action.SourceItem.Download(filePath);
            using (var strm = File.OpenRead(filePath))
            {
                var f = new FileAttachment();
                f.AreaNodeUri  = areaNodeUri;
                f.ProjectUri   = projectNodeUri;
                f.FileNameGUID = fileGuid;
                f.LocalFile    = strm; // attachment.GetFileContents();

                WorkItemServer.UploadFile(f);
            }

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            return(tfsUpdateDocument);
        }
        public void CheckConflicts(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ModList.Where(c => c.Active).Count() == 0)
                {
                    MessageBox.Show("you should have mods to check conflicts");
                    return;
                }
                var current = 0;
                var length  = 0;

                ExecuteWorker((object sender, DoWorkEventArgs args) =>
                {
                    var changes = new Dictionary <string, List <Dictionary <string, string> > >();
                    var cm      = new ConflictManager();

                    var ordered      = ModList.Where(c => c.Active).OrderBy(c => c.Order).ToList();
                    length           = ordered.Count * 2;
                    var baseGameData = new GameData();

                    foreach (var item in new string[6] {
                        "gamedata.base",
                        "Newwworld.mod",
                        "Dialogue.mod",
                        "Vitali.mod",
                        "Nizu.mod",
                        "rebirth.mod"
                    })
                    {
                        cm.LoadMods(Path.Combine(LoadService.config.GamePath, "data", item), ModMode.BASE, baseGameData);
                    }

                    foreach (var mod in ordered)
                    {
                        cm.LoadMods(mod.FilePath, ModMode.ACTIVE, baseGameData);
                        current++;
                        (sender as BackgroundWorker).ReportProgress(current.Percent(length));
                    }

                    baseGameData.resolveAllReferences();

                    cm.LoadBaseChanges(baseGameData);

                    baseGameData = null;

                    foreach (var mod in ordered)
                    {
                        Console.WriteLine($"{mod.DisplayName} Loading...");
                        var gd = new GameData();

                        cm.LoadMods(mod.FilePath, ModMode.ACTIVE, gd);

                        cm.ListOfGameData.Add(gd);
                        current++;
                        (sender as BackgroundWorker).ReportProgress(current.Percent(length));
                    }


                    MessageBox.Show("hey, i completed the changes, i'm generating a report, it'll take a while if your mods has alot of changes.");

                    cm.LoadChanges();

                    //if (!Directory.Exists("reports"))
                    //    Directory.CreateDirectory("reports");

                    //var filename = Constants.modChangesFileName;
                    //var detailsFilename = Constants.DetailChangesFileName;


                    //Console.WriteLine("writing reports");
                    //var list = new Task[] {
                    //Task.Run(() => { File.WriteAllText(filename, JsonConvert.SerializeObject(cm.conflictIndex)); }),
                    //Task.Run(() => { File.WriteAllText(detailsFilename, JsonConvert.SerializeObject(cm.DetailIndex)); }),
                    ////Task.Run(() => {
                    ////    foreach (var item in cm.listOfTags)
                    ////    {
                    ////        File.WriteAllText($"reports/{item.Key}", JsonConvert.SerializeObject(item.Value.Select(c=>c.ToString())));
                    ////    }
                    ////})
                    //};

                    //Task.WaitAll(list);

                    ConflictIndex = cm.conflictIndex;
                    DetailIndex   = cm.DetailIndex;

                    Parallel.ForEach(ConflictIndex.Keys, (key) =>
                    {
                        if (ConflictIndex[key].Mod.Count == 1)
                        {
                            return;
                        }
                        foreach (var modName in ConflictIndex[key].Mod)
                        {
                            var mod = ModList.FirstOrDefault(c => c.FileName == modName);
                            if (!mod.Conflicts.Any(q => q == key))
                            {
                                mod.Conflicts.Push(key);
                            }
                            current++;
                            (sender as BackgroundWorker).ReportProgress(current.Percent(length));
                        }
                    });

                    UpdateListView();
                });
            }
            catch (Exception)
            {
                MessageBox.Show("I'm working on this feature... it's complicated :)");
            }
        }
Beispiel #30
0
 /// <summary>
 /// Register adapter's conflict handlers.
 /// </summary>
 /// <param name="conflictManager"></param>
 public override void RegisterConflictTypes(ConflictManager conflictManager)
 {
     TraceManager.TraceInformation("WSSVC:AP:RegisterConflictTypes");
     conflictManagementService = conflictManager;
     conflictManagementService.RegisterConflictType(new GenericConflictType());
 }