private void markChangeGroupAsObsolete(ChangeGroup changeGroup) { if (changeGroup == null) { return; } changeGroup.Status = ChangeStatus.Obsolete; changeGroup.Save(); }
/// <summary> /// Analyzes the TFS changeset to generate a change group. /// </summary> /// <param name="changeset"></param> /// <returns></returns> private int analyzeChangeset(Changeset changeset) { if (changeset == null) { throw new ArgumentNullException("changeset"); } lazyInit(); TraceManager.TraceInformation("Starting analysis of TFS change {0}", changeset.ChangesetId); int changeCount = 0; ChangeGroup group = m_changeGroupService.CreateChangeGroupForDeltaTable(changeset.ChangesetId.ToString(CultureInfo.InvariantCulture)); populateChangeGroupMetaData(group, changeset); if (changeset != null) { m_algorithms.Initialize(); foreach (Change c in changeset.Changes) { // Either no snapshot start point is specified or we already passed the snapshot start point. if (IsPathMapped(c.Item.ServerItem, changeset.ChangesetId) == MappingResult.Mapped) { try { m_algorithms.Execute(c, group); } catch (MissingMethodException mme) { throw new VersionControlMigrationException( string.Format(TfsVCAdapterResource.Culture, TfsVCAdapterResource.ClientNotSupported), mme); } } } m_algorithms.Finish(group); } changeCount = group.Actions.Count; if (group.Actions.Count > 0) { group.Save(); } if (changeCount == 0) { TraceManager.TraceInformation("No relevent changes found in TFS change {0}", changeset.ChangesetId); } return(changeCount); }
private void generateSnapshotForVCSession() { foreach (var setting in m_configurationService.VcCustomSetting.Settings.Setting) { if (setting.SettingKey == "SnapshotStartPoint") { m_sessionLevelSnapshotTime = parseSnapShotStartPoint(setting.SettingValue); } } m_hwmDelta.Reload(); if (m_hwmDelta.Value >= m_sessionLevelSnapshotTime) { // We've already passed snapshot changeset Id, just return. m_sessionlevelSnapshotCompleted = true; return; } ChangeGroup snapshotGroup = createChangeGroupForSnapshot(m_sessionLevelSnapshotTime, 0); m_clearCaseServer.SetConfigSpecForSnapshotStartPoint(m_sessionLevelSnapshotTime); try { foreach (MappingEntry mappingEntry in m_configurationService.Filters) { if (mappingEntry.Cloak) { continue; } string localMappingPath = m_clearCaseServer.GetViewLocalPathFromServerPath(mappingEntry.Path); foreach (string subDirectory in Directory.GetDirectories(localMappingPath, "*", SearchOption.AllDirectories)) { createAddActionForSnapshot(snapshotGroup, subDirectory, true); } foreach (string subFile in Directory.GetFiles(localMappingPath, "*", SearchOption.AllDirectories)) { createAddActionForSnapshot(snapshotGroup, subFile, false); } } } finally { m_clearCaseServer.ResetConfigSpec(); } snapshotGroup.Save(); m_hwmDelta.Update(m_sessionLevelSnapshotTime); m_changeGroupService.PromoteDeltaToPending(); m_sessionlevelSnapshotCompleted = true; }
/// <summary> /// Gets the share point task updates. /// </summary> /// <param name="viewName">Name of the view.</param> private void GetSharePointTaskUpdates(string viewName) { TraceManager.TraceInformation("WSSWIT:AP:GetSharePointTaskUpdates"); using (SharePoint.Lists sharePointList = new SharePoint.Lists()) { sharePointList.Url = string.Format(CultureInfo.CurrentCulture, "{0}/_vti_bin/lists.asmx", configurationService.ServerUrl); string listName = configurationService.MigrationSource.SourceIdentifier; string username = string.Empty; string password = string.Empty; foreach (CustomSetting customSetting in configurationService.MigrationSource.CustomSettings.CustomSetting) { switch (customSetting.SettingKey) { case "username": { username = customSetting.SettingValue; break; } case "password": { password = customSetting.SettingValue; break; } } } sharePointList.Credentials = new System.Net.NetworkCredential(username, password); TraceManager.TraceInformation("\tWSSWIT:AP:Getting items from the list {0} on {1} with username {2}", listName, sharePointList.Url, username); XElement rawListItems = XDocument.Parse(sharePointList.GetListItems(listName, viewName, (XmlNode)SharePointHelpers.Query, (XmlNode)SharePointHelpers.ViewFields, "0", (XmlNode)SharePointHelpers.QueryOptions, string.Empty).OuterXml).Root; Collection <SharePointListItem> listItems = SharePointHelpers.ParseItems(rawListItems); foreach (SharePointListItem task in listItems) { Guid actionGuid = WellKnownChangeActionId.Add; if (highWaterMarkDelta.Value != DateTime.MinValue && task.ModifiedOn.CompareTo(highWaterMarkDelta.Value) > 0) { actionGuid = WellKnownChangeActionId.Edit; } else { actionGuid = WellKnownChangeActionId.Add; } ChangeGroup changeGroup = CreateChangeGroup(highWaterMarkChangeSet.Value, 0); changeGroup.CreateAction(actionGuid, task, string.Empty, listName, string.Empty, string.Empty, WellKnownContentType.WorkItem.ReferenceName, CreateFieldRevisionDescriptionDoc(task)); changeGroup.Save(); highWaterMarkChangeSet.Update(highWaterMarkChangeSet.Value + 1); } } }
/// <summary> /// Generate the context info table /// </summary> public virtual void GenerateContextInfoTable() { try { ChangeGroup group = m_changeGroupService.CreateChangeGroupForDeltaTable(ContextInformGroupName); if (m_supportedContentTypeOther.ContainsKey(WellKnownContentType.UserGroupList.ReferenceName)) { AddUserGroup(group); } if (m_supportedContentTypeOther.ContainsKey(WellKnownContentType.ValueListCollection.ReferenceName)) { AddGlobalList(group); } if (m_supportedContentTypeOther.ContainsKey(WellKnownContentType.Tfs2008WorkItemFieldMetadata.ReferenceName) || m_supportedContentTypeOther.ContainsKey(WellKnownContentType.Tfs2005WorkItemFieldMetadata.ReferenceName)) { AddOrcasCompatibleWITD(group); } if (m_supportedContentTypeOther.ContainsKey(s_CssNodeChangesContentType.ReferenceName)) { AddCSSNodeChanges(group); } if (group.Actions.Count > 0) { group.Save(); m_changeGroupService.PromoteDeltaToPending(); } else { TraceManager.TraceInformation( "There is no change to WIT metadata since last sync point. Metadata delta generation has been skipped."); } } catch (Exception exception) { if (exception is MigrationUnresolvedConflictException) { return; } ErrorManager errMgr = m_analysisServiceContainer.GetService(typeof(ErrorManager)) as ErrorManager; errMgr.TryHandleException(exception); return; } }
/// <summary> /// Analyzes the TFS changeset to generate a change group. /// </summary> /// <param name="logRecord"></param> /// <returns></returns> private int analyzeChangeset(ChangeSet changeSet, int[] mappedChanges) { if (changeSet == null) { throw new ArgumentNullException("changeSet"); } lazyInit(); TraceManager.TraceInformation("Starting analysis of Subversion revision {0}", changeSet.Revision); int changeCount = 0; ChangeGroup group = m_changeGroupService.CreateChangeGroupForDeltaTable(changeSet.Revision.ToString(CultureInfo.InvariantCulture)); populateChangeGroupMetaData(group, changeSet); if (changeSet != null) { m_algorithm.CurrentChangeset = changeSet; foreach (Change change in changeSet.Changes) { // Either no snapshot start point is specified or we already passed the snapshot start point. if (IsPathMapped(change.FullServerPath)) { m_algorithm.Execute(change, group); } else { m_algorithm.ExecuteNonMapped(change, group, mappedChanges); } } m_algorithm.Finish(group); } changeCount = group.Actions.Count; if (group.Actions.Count > 0) { group.Save(); } if (changeCount == 0) { TraceManager.TraceInformation("No relevent changes found in SVN revision {0}", changeSet.Revision); } return(changeCount); }
/// <summary> /// Generate the delta table /// </summary> public void GenerateDeltaTable() { // Load the current high water mark from any previous run of this session m_hwmDelta.Reload(); m_renameList = null; m_renameListUpdated = false; // Removing the in-progress change groups created by this side (fils system) m_changeGroupService.RemoveInProgressChangeGroups(); if (m_changeGroupService.GetInProgressMigrationInstructionCount() > 0) { // If there are in-progress migration instructions translated from the other side, mark this delta table as contentcon flict detection only. m_contentConflictDetectionOnly = true; TraceManager.TraceInformation("Migration instruction in progress, the delta table will be generated for content conflict detection only"); } else { m_contentConflictDetectionOnly = false; } DateTime newHighWaterMarkTime = DateTime.Now; List <String> pathsToBeVerified = new List <String>(); int versionToBeSynced = 0; // In a two-way sync, versionToBeSynced is set to the last sync point - either the latest changeset migrated from TFS or the latest changeset migrated to TFS // In one way sync, versionToBeSynced is always set to the GetLatestChangesetId of TFS if (m_hwmLastSyncedTfsChangeset != null) { // m_hwmLastSyncedTfsChangeset is the latest TFS changeset migrated to the file system side. // This highwater mark will be set when TfsFileSystemAnalysisProvider is combined with another provider to form a two-way sync. m_hwmLastSyncedTfsChangeset.Reload(); // m_lastHighWaterMarkMigratedToPeer is the latest TFS changeset migrated from this TfsFileSystemAnalysisProvider. m_lastHighWaterMarkMigratedToPeer.Reload(); versionToBeSynced = m_lastHighWaterMarkMigratedToPeer.Value > m_hwmLastSyncedTfsChangeset.Value ? m_lastHighWaterMarkMigratedToPeer.Value : m_hwmLastSyncedTfsChangeset.Value; } else { versionToBeSynced = m_destinationTfs.GetLatestChangesetId(); } FileSystemVerifier fileSystemVerifier = new FileSystemVerifier(); ChangeGroup changeGroup = m_changeGroupService.CreateChangeGroupForDeltaTable(DateTime.Now.ToString()); populateChangeGroupMetaData(changeGroup); foreach (MappingEntry m in ConfigurationService.Filters) { if (m.Cloak) { continue; } string canonicalPath = removeTrailingSlash(m.Path); fileSystemVerifier.AddPathForVerification(canonicalPath); analyzeFolder(canonicalPath, versionToBeSynced, changeGroup); } if (!fileSystemVerifier.Verify()) { TraceManager.TraceError( "Analysis failed as the local file system state was changed during the analysis phase. No changes were created."); markChangeGroupAsObsolete(changeGroup); return; } if (changeGroup.Actions.Count > 0) { // We only want to promote deltas to pending if we actually created and saved a change group. changeGroup.Save(); m_changeGroupService.PromoteDeltaToPending(); } else { markChangeGroupAsObsolete(changeGroup); } m_lastTfsChangesetAnalyzed.Update(versionToBeSynced); m_hwmDelta.Update(newHighWaterMarkTime); TraceManager.TraceInformation(String.Format(CultureInfo.InvariantCulture, TfsFileSystemResources.UpdatedHighWaterMark, newHighWaterMarkTime)); }
private void ComputeDeltaPerRecord( OAdEntity aRecord) { OAdEntityDef aEntityDef = CQWrapper.GetEntityDef(m_userSession, CQWrapper.GetEntityDefName(aRecord)); string recordDispName = CQWrapper.GetEntityDisplayName(aRecord); string recordEntDefName = CQWrapper.GetEntityDefName(aRecord); #region process history bool recordContentIsModified = false; bool maybeNewRecord = false; Dictionary <string, List <ClearQuestRecordItem> > historyDelta = new Dictionary <string, List <ClearQuestRecordItem> >(); Dictionary <string, int> perHistoryFieldLastIndex = new Dictionary <string, int>(); // needed for updating processed delta // find all history fields OAdHistoryFields aHistFields = CQWrapper.GetHistoryFields(aRecord); int historyFldCount = CQWrapper.HistoryFieldsCount(aHistFields); bool containsNewHistory = false; for (int histFldIndex = 0; histFldIndex < historyFldCount; histFldIndex++) { object ob = (object)histFldIndex; OAdHistoryField aHistoryField = CQWrapper.HistoryFieldsItem(aHistFields, ref ob); string historyFieldName = CQWrapper.GetHistoryFieldName(aHistoryField); // find last processed history entry for this history field string lookupItemId = CQDeltaComputationProgressLookupService.CreateHistoryItemId(recordEntDefName, recordDispName, historyFieldName); int startHistIndex = 1 + DeltaComputeProgressService.GetLastProcessedItemVersion(lookupItemId); // find all history in a particular history field int historyCount = CQWrapper.HistoryFieldHistoriesCount(aHistoryField); for (int histIndex = startHistIndex; histIndex < historyCount; histIndex++) { object obHistIndex = (object)histIndex; OAdHistory aHistory = CQWrapper.HistoryFieldHistoriesItem(aHistoryField, ref obHistIndex); CQHistory cqHistory = new CQHistory(aHistory); CQMigrationItem migrationItem = new CQHistoryMigrationItem(recordDispName, historyFieldName, histIndex); if (TranslationService.IsSyncGeneratedItemVersion(ClearQuestRecordItem.GetMigrationRecordId(recordEntDefName, recordDispName), migrationItem.MigrationItemVersion, m_configurationService.SourceId)) { continue; } if (histIndex == 0) { maybeNewRecord = true; } // add unprocessed history fields for processing if (!historyDelta.ContainsKey(historyFieldName)) { historyDelta.Add(historyFieldName, new List <ClearQuestRecordItem>(historyCount)); } historyDelta[aHistoryField.fieldname].Add(new ClearQuestRecordItem(aRecord, aHistory, historyFieldName, histIndex.ToString())); containsNewHistory = true; // based on action type, we decide whether content change is needed int actionType = CQWrapper.GetActionDefType(aEntityDef, cqHistory.Action); switch (actionType) { case CQConstants.ACTION_SUBMIT: break; case CQConstants.ACTION_MODIFY: recordContentIsModified = true; break; case CQConstants.ACTION_CHANGE: break; case CQConstants.ACTION_DUPLICATE: break; case CQConstants.ACTION_UNDUPLICATE: break; case CQConstants.ACTION_IMPORT: break; case CQConstants.ACTION_DELETE: TraceManager.TraceInformation(ClearQuestResource.ClearQuest_Msg_RecordDeleted, recordEntDefName, recordDispName); break; case CQConstants.ACTION_BASE: break; case CQConstants.ACTION_RECORD_SCRIPT_ALIAS: break; } } perHistoryFieldLastIndex.Add(historyFieldName, historyCount - 1); } #endregion #region generate delta for content and history if (maybeNewRecord || recordContentIsModified) { // the first revision, i.e. "Submit", of a CQ record is always hard-coded to be '1' CQMigrationItem contentMigrationAction = new CQMigrationItem(recordDispName, ClearQuestRecordItem.NewRecordVersion); bool isNewRecord = false; if (maybeNewRecord) { isNewRecord = !(DeltaComputeProgressService.IsMigrationItemProcessed(recordDispName, ClearQuestRecordItem.NewRecordVersionValue)); } if (!isNewRecord) { // all subsequent record "MODIFICATIONs" are hard-coded to be "update@<Now.Ticks>" contentMigrationAction.MigrationItemVersion = ClearQuestRecordItem.RecordUpdateVersion + "@" + DateTime.Now.Ticks; } ClearQuestRecordItem recordContentItem = new ClearQuestRecordItem(aRecord, contentMigrationAction.MigrationItemVersion); recordContentItem.CQSession = m_userSession; recordContentItem.Version = contentMigrationAction.MigrationItemVersion; ChangeGroup contentChangeGroup = recordContentItem.CreateChangeGroup( m_changeGroupService, m_migrationContext, isNewRecord && m_isLastRevisionAutoCorrectionEnabled); contentChangeGroup.Save(); if (isNewRecord && !containsNewHistory) { DeltaComputeProgressService.UpdateCache(recordDispName, ClearQuestRecordItem.NewRecordVersionValue); } } var lastHistoryRecordItem = historyDelta[historyDelta.Keys.Last()].Last(); foreach (string histFieldName in historyDelta.Keys) { foreach (ClearQuestRecordItem recordHistItem in historyDelta[histFieldName]) { recordHistItem.CQSession = m_userSession; ChangeGroup changeGroup = recordHistItem.CreateChangeGroup( m_changeGroupService, m_migrationContext, (CQStringComparer.FieldName.Equals(recordHistItem.HistoryFieldName, lastHistoryRecordItem.HistoryFieldName) && recordHistItem.Version.Equals(lastHistoryRecordItem.Version, StringComparison.OrdinalIgnoreCase) && m_isLastRevisionAutoCorrectionEnabled)); changeGroup.Save(); } Debug.Assert(perHistoryFieldLastIndex.ContainsKey(histFieldName), "perHistoryFieldLastIndex.ContainsKey(histFieldName) returns false"); string deltaComputeProcessLookupId = CQDeltaComputationProgressLookupService.CreateHistoryItemId(recordEntDefName, recordDispName, histFieldName); DeltaComputeProgressService.UpdateCache(deltaComputeProcessLookupId, perHistoryFieldLastIndex[histFieldName]); } #endregion #region process attachment OAdAttachmentFields aAttachmentFields = CQWrapper.GetAttachmentFields(aRecord); for (int aAttachmentFieldsIndex = 0; aAttachmentFieldsIndex < CQWrapper.AttachmentsFieldsCount(aAttachmentFields); aAttachmentFieldsIndex++) { object ob = (object)aAttachmentFieldsIndex; OAdAttachmentField aAttachmentField = CQWrapper.AttachmentsFieldsItem(aAttachmentFields, ref ob); string fieldName = CQWrapper.GetAttachmentFieldName(aAttachmentField); ChangeGroup changeGroup = m_changeGroupService.CreateChangeGroupForDeltaTable( string.Format("{0}:{1}:{2}", recordDispName, "Attachments", fieldName)); // process all attachments OAdAttachments attachments = CQWrapper.GetAttachments(aAttachmentField); for (int attachmentIndex = 0; attachmentIndex < CQWrapper.AttachmentsCount(attachments); attachmentIndex++) { object obIndex = (object)attachmentIndex; OAdAttachment aAttachment = CQWrapper.AttachmentsItem(attachments, ref obIndex); ClearQuestAttachmentItem attachmentItem = new ClearQuestAttachmentItem(aRecord, aAttachmentField, aAttachment, UserSessionConnConfig); attachmentItem.CQSession = m_userSession; attachmentItem.CreateChangeAction(changeGroup, lastHistoryRecordItem.Version); } if (changeGroup.Actions.Count > 0) { changeGroup.Save(); } } #endregion }
private void generateDeltaTableForSnapshot(List <string> paths, int snapshotChangeset) { List <string> pathsToGet = new List <string>(); VersionSpec snapshotVersionSpec = new ChangesetVersionSpec(snapshotChangeset); foreach (string mappingPath in paths) { // Always query at one level down the mapping ItemSet itemSet = m_tfsClient.GetItems(mappingPath, snapshotVersionSpec, RecursionType.OneLevel); Item[] items = itemSet.Items; foreach (Item childItem in items) { // Avoid the item itself. if (!VersionControlPath.Equals(childItem.ServerItem, mappingPath)) { pathsToGet.Add(childItem.ServerItem); } } } int countDownToCreateNewChangeGroup = m_snapshotCheckinBatchSize; ChangeGroup batchGroup = createChangeGroupForSnapshot(snapshotChangeset, snapshotChangeset); foreach (string path in pathsToGet) { TraceManager.TraceInformation("Getting snapshot at changeset: {0}, path: {1}", snapshotChangeset, path); ItemSet itemSet = m_tfsClient.GetItems(path, snapshotVersionSpec, RecursionType.Full); Item[] items = itemSet.Items; itemSet = null; TraceManager.TraceInformation("Snapshot contains {0} items", items.Length); for (int i = 0; i < items.Length; i++) { if (FindMappedPath(items[i].ServerItem) != null) { countDownToCreateNewChangeGroup--; if (countDownToCreateNewChangeGroup == 0) { TraceManager.TraceInformation("Saving {0} change actions", m_snapshotCheckinBatchSize); batchGroup.Save(); batchGroup.Actions.Clear(); batchGroup = null; batchGroup = createChangeGroupForSnapshot(snapshotChangeset, snapshotChangeset); countDownToCreateNewChangeGroup = m_snapshotCheckinBatchSize; TraceManager.TraceInformation("Saved {0} change actions", snapshotChangeset); } batchGroup.CreateAction( WellKnownChangeActionId.Add, new TfsMigrationItem(items[i]), null, items[i].ServerItem, null, null, TfsAnalysisAlgorithms.convertContentType(items[i].ItemType), null); } items[i] = null; // Dispose this object to reduce memory consumption. } } if (batchGroup.Actions.Count > 0) { int numRemainingItems = batchGroup.Actions.Count; TraceManager.TraceInformation("Saving {0} change actions", numRemainingItems); batchGroup.Save(); TraceManager.TraceInformation("Saved {0} change actions", numRemainingItems); } }
/// <summary> /// Create a changegroup that contains all change actions needed to bring a migration target to the specificed snapshot /// </summary> /// <param name="changeGroupName">The change group name of the snapshot</param> private void generateSnapshotForVCSession() { foreach (var setting in ConfigurationService.VcCustomSetting.Settings.Setting) { if (setting.SettingKey == "SnapshotStartPoint") { m_sessionLevelSnapshotChangeset = parseSnapShotStartPoint(setting.SettingValue); } else if (setting.SettingKey == "SnapshotBatchSize") { try { m_snapshotCheckinBatchSize = int.Parse(setting.SettingValue); } catch (Exception) { // wrong format, use the default batch size } } } m_hwmDelta.Reload(); if (m_hwmDelta.Value >= m_sessionLevelSnapshotChangeset) { // We've already passed snapshot changeset Id, just return. m_sessionlevelSnapshotCompleted = true; return; } VersionSpec snapshotVersionSpec = new ChangesetVersionSpec(m_sessionLevelSnapshotChangeset); List <string> pathsToGet = new List <string>(); foreach (MappingEntry mappingEntry in ConfigurationService.Filters) { if (mappingEntry.Cloak) { continue; } // Always query at one level down the mapping ItemSet itemSet = m_tfsClient.GetItems(mappingEntry.Path, snapshotVersionSpec, RecursionType.OneLevel); Item[] items = itemSet.Items; foreach (Item childItem in items) { // Avoid the item itself. if (!VersionControlPath.Equals(childItem.ServerItem, mappingEntry.Path)) { pathsToGet.Add(childItem.ServerItem); } } } int countDownToCreateNewChangeGroup = m_snapshotCheckinBatchSize; int batchExecutionOrder = m_sessionLevelSnapshotChangeset; ChangeGroup batchGroup = createChangeGroupForSnapshot(m_sessionLevelSnapshotChangeset, batchExecutionOrder); foreach (string path in pathsToGet) { TraceManager.TraceInformation("Getting snapshot at changeset: {0}, path: {1}", m_sessionLevelSnapshotChangeset, path); ItemSet itemSet = m_tfsClient.GetItems(path, snapshotVersionSpec, RecursionType.Full); Item[] items = itemSet.Items; itemSet = null; TraceManager.TraceInformation("Snapshot contains {0} items", items.Length); for (int i = 0; i < items.Length; i++) { // We want to include the situation where a snapshot on a path is the same as the snapshot of the VC session. // In this situation, we want to include the item in the session snapshot changeset. // So we use changesetId + 1 as the reference changeset id. if (IsPathMapped(items[i].ServerItem, m_sessionLevelSnapshotChangeset + 1) == MappingResult.Mapped) { countDownToCreateNewChangeGroup--; if (countDownToCreateNewChangeGroup == 0) { TraceManager.TraceInformation("Saving {0} change actions", m_snapshotCheckinBatchSize); batchGroup.Save(); batchGroup.Actions.Clear(); batchGroup = null; batchExecutionOrder--; batchGroup = createChangeGroupForSnapshot(m_sessionLevelSnapshotChangeset, batchExecutionOrder); countDownToCreateNewChangeGroup = m_snapshotCheckinBatchSize; TraceManager.TraceInformation("Saved {0} change actions", m_snapshotCheckinBatchSize); } batchGroup.CreateAction( WellKnownChangeActionId.Add, new TfsMigrationItem(items[i]), null, items[i].ServerItem, null, null, TfsAnalysisAlgorithms.convertContentType(items[i].ItemType), null); } items[i] = null; // Dispose this object to reduce memory consumption. } } if (batchGroup.Actions.Count > 0) { int numRemainingItems = batchGroup.Actions.Count; TraceManager.TraceInformation("Saving {0} change actions", numRemainingItems); batchGroup.Save(); TraceManager.TraceInformation("Saved {0} change actions", numRemainingItems); } m_hwmDelta.Update(m_sessionLevelSnapshotChangeset); m_changeGroupService.PromoteDeltaToPending(); m_sessionlevelSnapshotCompleted = true; }
/// <summary> /// Try to process the change group, assuming it contains context sync instructions. /// </summary> /// <param name="nextChangeGroup"></param> /// <returns>true if the change group is a context sync group and it has been processed (either successfully or not)</returns> /// <exception cref="MigrationUnresolvedConflictException"></exception> /// <remarks> /// If sync succeeds, the change group will be marked as 'Completed'; otherwise, a conflict /// will be raised and we do not expect it to be auto-resolved. /// </remarks> private bool TryProcessContextSyncChangeGroup(ChangeGroup changeGroup) { // context sync steps must be strictly ordered, although they may not come in expected order // the following logic sorts them bool foundSyncContextAction = true; MigrationAction[] contextSyncActions = new MigrationAction[6]; foreach (MigrationAction action in changeGroup.Actions) { if (action.Action.Equals(WellKnownChangeActionId.SyncContext)) { Debug.Assert(!string.IsNullOrEmpty(action.FromPath)); if (action.ItemTypeReferenceName.Equals(WellKnownContentType.UserGroupList.ReferenceName)) { contextSyncActions[0] = action; } else if (action.ItemTypeReferenceName.Equals(WellKnownContentType.ValueListCollection.ReferenceName)) { contextSyncActions[1] = action; } else if (action.ItemTypeReferenceName.Equals(WellKnownContentType.Tfs2005WorkItemFieldMetadata.ReferenceName) || action.ItemTypeReferenceName.Equals(WellKnownContentType.Tfs2008WorkItemFieldMetadata.ReferenceName)) { contextSyncActions[2] = action; } else if (action.ItemTypeReferenceName.Equals(TfsConstants.TfsAreaPathsContentTypeRefName)) { contextSyncActions[3] = action; } else if (action.ItemTypeReferenceName.Equals(TfsConstants.TfsIterationPathsContentTypeRefName)) { contextSyncActions[4] = action; } else if (action.ItemTypeReferenceName.Equals(TfsConstants.TfsCSSNodeChangesContentTypeRefName)) { contextSyncActions[5] = action; } } else { foundSyncContextAction = false; break; } } if (!foundSyncContextAction) { return(false); } IMigrationAction currSyncAction = null; try { if (contextSyncActions[0] != null) { currSyncAction = contextSyncActions[0]; SyncUserAccount(currSyncAction.MigrationActionDescription, m_witMetadataSyncPolicy); } if (contextSyncActions[1] != null) { currSyncAction = contextSyncActions[1]; SyncGlobalList(currSyncAction.MigrationActionDescription, m_witMetadataSyncPolicy); } if (contextSyncActions[2] != null) { currSyncAction = contextSyncActions[2]; SyncWorkItemTypeDefinition(currSyncAction.MigrationActionDescription, m_witMetadataSyncPolicy); } if (contextSyncActions[3] != null && !m_migrationSource.WorkItemStore.Core.DisableAreaPathAutoCreation) { // keep for backward compatibility only (replaced by SyncCSSNodeChanges) currSyncAction = contextSyncActions[3]; SyncAreaPaths(currSyncAction.MigrationActionDescription, m_witMetadataSyncPolicy); } if (contextSyncActions[4] != null && !m_migrationSource.WorkItemStore.Core.DisableIterationPathAutoCreation) { // keep for backward compatibility only (replaced by SyncCSSNodeChanges) currSyncAction = contextSyncActions[4]; SyncIterationPaths(currSyncAction.MigrationActionDescription, m_witMetadataSyncPolicy); } if (contextSyncActions[5] != null) { currSyncAction = contextSyncActions[5]; SyncCSSNodeChanges( currSyncAction.MigrationActionDescription, m_migrationSource.WorkItemStore.Core.DisableAreaPathAutoCreation, m_migrationSource.WorkItemStore.Core.DisableIterationPathAutoCreation); } changeGroup.Status = ChangeStatus.Complete; changeGroup.Save(); return(true); } catch (Exception ex) { if (!(ex is MigrationUnresolvedConflictException)) { TraceManager.TraceError(ex.ToString()); // backlog the conflict context sync action/group MigrationConflict genericeConflict = InvalidSubmissionConflictType.CreateConflict( currSyncAction, ex, currSyncAction.ChangeGroup.Name, currSyncAction.ChangeGroup.Name); var conflictManager = m_conflictManagementService.GetService(typeof(ConflictManager)) as ConflictManager; Debug.Assert(null != conflictManager); List <MigrationAction> resolutionActions; ConflictResolutionResult resolveRslt = conflictManager.TryResolveNewConflict(conflictManager.SourceId, genericeConflict, out resolutionActions); Debug.Assert(!resolveRslt.Resolved); return(true); } else { throw; } } }
private void queryHistory(ChangeGroupService changeGroupService) { m_hwmDelta.Reload(); DateTime since = m_hwmDelta.Value; List <CCHistoryRecord> historyRecordList = m_clearCaseServer.GetHistoryRecords(m_configurationService.Filters, since, true); historyRecordList.Sort(); CCVersion version; CCItem currentItem = null; CCItem previousLnItem = null; string previousLnItemLeafName = null; string previousMkElemItemPath = null; List <CCHistoryRecord> processedRecordList = new List <CCHistoryRecord>(); foreach (CCHistoryRecord historyRecord in historyRecordList) { switch (historyRecord.OperationType) { case OperationType.Checkin: version = m_clearCaseServer.ApplicationClass.get_Version(historyRecord.VersionExtendedPath); currentItem = new CCItem(version, ClearCasePath.GetVobName(historyRecord.AbsoluteVobPath)); if (string.Equals(historyRecord.OperationDescription, OperationDescription.Version)) { if (ClearCasePath.Equals(previousMkElemItemPath, currentItem.AbsoluteVobPath)) { // File version checkin following a mkelem, create an Add historyRecord.AbsoluteVobPath = currentItem.AbsoluteVobPath; historyRecord.ChangeAction = WellKnownChangeActionId.Add; historyRecord.IsDirectory = version.IsDirectory; processedRecordList.Add(historyRecord); previousMkElemItemPath = null; } else { // File version checkin following a mkelem, create an Edit historyRecord.AbsoluteVobPath = currentItem.AbsoluteVobPath; historyRecord.ChangeAction = WellKnownChangeActionId.Edit; historyRecord.IsDirectory = version.IsDirectory; processedRecordList.Add(historyRecord); } } else if (string.Equals(historyRecord.OperationDescription, OperationDescription.DirectoryVersion) && (ClearCasePath.Equals(previousMkElemItemPath, currentItem.AbsoluteVobPath))) { // Directory version checkin following a mkelem, create an Add historyRecord.AbsoluteVobPath = currentItem.AbsoluteVobPath; historyRecord.ChangeAction = WellKnownChangeActionId.Add; historyRecord.IsDirectory = version.IsDirectory; processedRecordList.Add(historyRecord); previousMkElemItemPath = null; } break; case OperationType.Mkattr: case OperationType.Mkpool: case OperationType.Mkreplica: case OperationType.Mktype: // ToDo // writeHistoryRecord(historyFields); break; case OperationType.Lnname: version = m_clearCaseServer.ApplicationClass.get_Version(historyRecord.VersionExtendedPath); currentItem = new CCItem(version, ClearCasePath.GetVobName(historyRecord.AbsoluteVobPath)); previousLnItem = currentItem; previousLnItemLeafName = ClearCaseEventSpec.ParseLnNameComment(historyRecord.Comment); break; case OperationType.Mkbranch: // ToDo if (string.Equals(historyRecord.OperationDescription, OperationDescription.Version) || string.Equals(historyRecord.OperationDescription, OperationDescription.DirectoryVersion)) { /*version = m_clearCaseServer.ApplicationClass.get_Version(historyRecord.VersionExtendedPath); * currentItem = new CCItem(version, vob); * historyRecord.AbsoluteVobPath = currentItem.AbsoluteVobPath; * historyRecord.ChangeAction = WellKnownChangeActionId.Add; * historyRecord.IsDirectory = version.IsDirectory; * historyRecordList.Add(historyRecord); * */ } break; case OperationType.Mkelem: if (string.Equals(historyRecord.OperationDescription, OperationDescription.DirectoryElement)) { // Todo /*if (currentState == OperationState.Initialized) * { * currentState = OperationState.CreateDirectoryElement; * currentItem = new Item(historyFields[1], ItemType.Element, m_vobName); * } * else * { * logStateTransitionError(currentState, operationType, operationDescription); * }*/ } else if (string.Equals(historyRecord.OperationDescription, OperationDescription.Branch)) { // Todo /* * if ((currentState == OperationState.AddDirectoryToParent) || (currentState == OperationState.CreateDirectoryElement)) ||{ || currentState = OperationState.CreateDirectoryBranch; || currentItem = new Item(historyFields[1], ItemType.Branch, m_vobName); ||} ||else ||{ || logStateTransitionError(currentState, operationType, operationDescription); ||} * */ } else if (string.Equals(historyRecord.OperationDescription, OperationDescription.DirectoryVersion) || string.Equals(historyRecord.OperationDescription, OperationDescription.Version)) { version = m_clearCaseServer.ApplicationClass.get_Version(historyRecord.VersionExtendedPath); currentItem = new CCItem(version, ClearCasePath.GetVobName(historyRecord.AbsoluteVobPath)); previousMkElemItemPath = currentItem.AbsoluteVobPath; //if (currentState == OperationState.CreateDirectoryBranch) //{ /*version = m_clearCaseServer.ApplicationClass.get_Version(historyFields[1]); * currentItem = new Item(version, vob); * if (IsPathMapped(currentItem.AbsoluteVobPath) && * IsOurChange(ClearCasePath.removeViewLocationFromVersion(version.ExtendedPath, m_clearCaseServer.ViewRootPath))) * { * createMigrationAction( * version, * null, * currentItem.AbsoluteVobPath, * versionTime, * WellKnownChangeActionId.Add, * version.IsDirectory); * }*/ // Verify the version to be 0 //currentState = OperationState.Initialized; //} //else //{ // logStateTransitionError(currentState, operationType, operationDescription); //} } else { //logStateTransitionError(currentState, operationType, operationDescription); } break; case OperationType.Mkhlink: // ToDo // writeHistoryRecord(historyFields); break; case OperationType.Mklabel: break; case OperationType.Rmname: bool isDirectory; string rmItemName = ClearCaseEventSpec.ParseRmNameComment(historyRecord.Comment, out isDirectory); if (rmItemName == null) { TraceManager.TraceWarning(String.Format("Skipping rmname operation: Unable to determine element type from history record comment: '{0}'", historyRecord.Comment)); continue; } version = m_clearCaseServer.ApplicationClass.get_Version(historyRecord.VersionExtendedPath); currentItem = new CCItem(version, ClearCasePath.GetVobName(historyRecord.AbsoluteVobPath)); if (currentItem.Equals(previousLnItem)) { historyRecord.AbsoluteVobPath = ClearCasePath.Combine(currentItem.AbsoluteVobPath, previousLnItemLeafName); historyRecord.AbsoluteVobPathFrom = ClearCasePath.Combine(currentItem.AbsoluteVobPath, rmItemName); historyRecord.ChangeAction = WellKnownChangeActionId.Rename; historyRecord.IsDirectory = isDirectory; processedRecordList.Add(historyRecord); previousLnItem = null; previousLnItemLeafName = null; // todo, path not mapped exception } else { // delete operation historyRecord.AbsoluteVobPath = ClearCasePath.Combine(currentItem.AbsoluteVobPath, rmItemName); historyRecord.ChangeAction = WellKnownChangeActionId.Delete; historyRecord.IsDirectory = isDirectory; processedRecordList.Add(historyRecord); } break; case OperationType.Undefined: break; case OperationType.Mkvob: // Add of Vob itself. // ToDo // writeHistoryRecord(historyFields); default: break; } } reviseHistoryRecordsForRename(processedRecordList); m_hwmEventId.Reload(); long lastProcessedEventId = m_hwmEventId.Value; foreach (CCHistoryRecord historyRecord in processedRecordList) { if (historyRecord.EventId <= lastProcessedEventId) { // The event has been processed in previous sync. TraceManager.TraceInformation("Skipping history record because the event was processed in a previous sync pass of this session"); continue; } if (Utils.IsOurChange(historyRecord)) { TraceManager.TraceInformation("Skipping history record because it represents a change migrated by the Integration Platform"); continue; } if (Utils.IsPathMapped(historyRecord.AbsoluteVobPath, m_configurationService)) { if (historyRecord.ChangeAction == WellKnownChangeActionId.Rename) { if (Utils.IsPathMapped(historyRecord.AbsoluteVobPathFrom, m_configurationService)) { m_currentChangeGroup = createMigrationAction(historyRecord, historyRecord.ChangeAction); } else { // ToDo Path not mapped conflict m_currentChangeGroup = createMigrationAction(historyRecord, WellKnownChangeActionId.Add); } } else { m_currentChangeGroup = createMigrationAction(historyRecord, historyRecord.ChangeAction); } } else { // ToDo path not mapped conflict if ((historyRecord.ChangeAction == WellKnownChangeActionId.Rename) && (Utils.IsPathMapped(historyRecord.AbsoluteVobPathFrom, m_configurationService))) { m_currentChangeGroup = createMigrationAction(historyRecord, WellKnownChangeActionId.Delete); } else { TraceManager.TraceWarning("Skipping history record because the path '{0}' is not mapped in a filter string", historyRecord.AbsoluteVobPath); } } } if (m_currentChangeGroup != null) { m_currentChangeGroup.Save(); } if (processedRecordList.Count > 0) { m_hwmDelta.Update(processedRecordList.Last().VersionTime); } m_changeGroupService.PromoteDeltaToPending(); }
private void generateSnapshotForVCSession() { foreach (var setting in m_configurationService.VcCustomSetting.Settings.Setting) { if (setting.SettingKey == "SnapshotStartPoint") { m_sessionLevelSnapshotTime = parseSnapShotStartPoint(setting.SettingValue); } } m_hwmDelta.Reload(); if (m_hwmDelta.Value >= m_sessionLevelSnapshotTime) { // We've already passed snapshot changeset Id, just return. m_sessionlevelSnapshotCompleted = true; return; } ChangeGroup snapshotGroup = createChangeGroupForSnapshot(m_sessionLevelSnapshotTime, 0); m_clearCaseServer.SetConfigSpecForSnapshotStartPoint(m_sessionLevelSnapshotTime); try { foreach (MappingEntry mappingEntry in m_configurationService.Filters) { if (mappingEntry.Cloak) { continue; } string localMappingPath = m_clearCaseServer.GetViewLocalPathFromServerPath(mappingEntry.Path); foreach (string subDirectory in Directory.GetDirectories(localMappingPath, "*", SearchOption.AllDirectories)) { string serverPath = m_clearCaseServer.GetServerPathFromViewLocalPath(subDirectory); snapshotGroup.CreateAction( WellKnownChangeActionId.Add, new ClearCaseMigrationItem( m_clearCaseServer.ViewName, m_clearCaseServer.ApplicationClass.get_Element(serverPath).Version.ExtendedPath, true), null, serverPath, null, null, WellKnownContentType.VersionControlledFolder.ReferenceName, null); } foreach (string subFile in Directory.GetFiles(localMappingPath, "*", SearchOption.AllDirectories)) { string serverPath = m_clearCaseServer.GetServerPathFromViewLocalPath(subFile); snapshotGroup.CreateAction( WellKnownChangeActionId.Add, new ClearCaseMigrationItem( m_clearCaseServer.ViewName, m_clearCaseServer.ApplicationClass.get_Element(serverPath).Version.ExtendedPath, true), null, serverPath, null, null, WellKnownContentType.VersionControlledFile.ReferenceName, null); } } } finally { m_clearCaseServer.ResetConfigSpec(); } snapshotGroup.Save(); m_hwmDelta.Update(m_sessionLevelSnapshotTime); m_changeGroupService.PromoteDeltaToPending(); m_sessionlevelSnapshotCompleted = true; }