private void MarkSessionRunning() { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { var sessionQuery = context.RTSessionSet.Where (s => s.SessionUniqueId.Equals(SessionId)); Debug.Assert(sessionQuery.Count() == 1); // we want to keep StartedInStandaloneProcess session status untouched if (sessionQuery.First().State != (int)BusinessModelManager.SessionStateEnum.StartedInStandaloneProcess) { sessionQuery.First().State = (int)BusinessModelManager.SessionStateEnum.Running; } context.TrySaveChanges(); } if (m_syncStateMachine.TryTransit(PipelineSyncCommand.START)) { m_syncStateMachine.CommandTransitFinished(PipelineSyncCommand.START); } else { throw new MigrationException(); } }
private void MarkSessionRunning() { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { var sessionQuery = context.RTSessionSet.Where (s => s.SessionUniqueId.Equals(SessionId)); Debug.Assert(sessionQuery.Count() == 1); // we want to keep StartedInStandaloneProcess session status untouched if (sessionQuery.First().State != (int)BusinessModelManager.SessionStateEnum.StartedInStandaloneProcess) { sessionQuery.First().State = (int)BusinessModelManager.SessionStateEnum.Running; } context.TrySaveChanges(); } // If the OrchestrationStatus for the session is PausedByConflict, it should stay in that state // until all conflict for the session are resolved if (m_syncStateMachine.CurrentState != PipelineState.PausedByConflict) { if (m_syncStateMachine.TryTransit(PipelineSyncCommand.START)) { m_syncStateMachine.CommandTransitFinished(PipelineSyncCommand.START); } else { throw new MigrationException(); } } }
internal void SaveChangeGroupActionStatus(LinkChangeGroup linkGroup) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { var groupQuery = from g in context.RTLinkChangeGroupSet where g.Id == linkGroup.InternalId select g; Debug.Assert(groupQuery.First() != null); RTLinkChangeGroup rtLinkChangeGroup = groupQuery.First(); rtLinkChangeGroup.Status = (int)linkGroup.Status; rtLinkChangeGroup.ContainsConflictedAction = linkGroup.IsConflicted; foreach (LinkChangeAction linkAction in linkGroup.Actions) { if (linkAction.InternalId == LinkChangeAction.INVALID_INTERNAL_ID) { throw new InvalidOperationException("Error updating link change action: action is not persisted in DB."); } RTLinkChangeAction rtLinkChangeAction = context.RTLinkChangeActionSet.Where (lcg => lcg.Id == linkAction.InternalId).First(); rtLinkChangeAction.Status = (int)linkAction.Status; rtLinkChangeAction.Conflicted = linkAction.IsConflicted; rtLinkChangeAction.ServerLinkChangeId = linkAction.ServerLinkChangeId; } context.TrySaveChanges(); } }
/// <summary> /// Updates child action's status to the data store. /// </summary> /// <param name="action"></param> protected override void UpdateChildAction(MigrationAction action) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { var changeActionQuery = context.RTChangeActionSet.Where (ca => ca.ChangeActionId == action.ActionId); int changeActionQueryCount = changeActionQuery.Count(); if (changeActionQueryCount == 0) { return; } Debug.Assert(changeActionQueryCount == 1); RTChangeAction rtChangeAction = changeActionQuery.First(); bool needToUpdateRTChangeAction = false; if (action.State == ActionState.Skipped) { rtChangeAction.IsSubstituted = true; needToUpdateRTChangeAction = true; } if (rtChangeAction.ActionId != action.Action) { rtChangeAction.ActionId = action.Action; needToUpdateRTChangeAction = true; } if (needToUpdateRTChangeAction) { context.TrySaveChanges(); } } }
public void ValidateAndSaveProviderConflictRegistration(int providerInternalId) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { RTProvider providerCache = (from p in context.RTProviderSet where p.Id == providerInternalId select p).First(); Debug.Assert(null != providerCache, "null == providerCache"); Guid providerReferenceName = providerCache.ReferenceName; List <ConflictType> unsavedTypes = new List <ConflictType>(this.RegisteredConflictTypes.Count); bool validateToolkitConflictTypes = providerReferenceName.Equals(Constants.FrameworkSourceId); if (validateToolkitConflictTypes) { foreach (var c in this.RegisteredToolkitConflictTypes) { unsavedTypes.Add(c.Value); } } else { foreach (var c in this.RegisteredConflictTypes) { if (!this.RegisteredToolkitConflictTypes.ContainsKey(c.Key)) { unsavedTypes.Add(c.Value); } } } ValidateSaveConflictType(context, providerReferenceName, providerCache, unsavedTypes, validateToolkitConflictTypes); ValidateSaveResolutionAction(context, providerReferenceName, providerCache, unsavedTypes, validateToolkitConflictTypes); context.TrySaveChanges(); } }
/// <summary> /// Mark all commands as processed for a particular session group. /// </summary> /// <remarks> /// This method is called immediately before a session group is started. If the previous session run crashed, /// leaving some "processing" or "active" commands in the queue, this method is expected to clean them up. /// </remarks> /// <param name="sessionGroupId">The GUID that's used as the unique Id of the subject session group.</param> public void ClearUpUnprocessedCommand(Guid sessionGroupId) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { int newStateValue = (int)PipelineSyncCommandState.New; int processingStateValue = (int)PipelineSyncCommandState.Processing; var cmdQuery = from c in context.RTOrchestrationCommandSet where (c.Status == newStateValue || c.Status == processingStateValue) && c.SessionGroup.GroupUniqueId.Equals(sessionGroupId) orderby c.Id select c; if (cmdQuery.Count() == 0) { return; } foreach (var cmd in cmdQuery) { cmd.Status = (int)PipelineSyncCommandState.Processed; } context.TrySaveChanges(); } }
private int FindCreateArtifactType(ArtifactType artifactType) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { if (string.IsNullOrEmpty(artifactType.ReferenceName)) { throw new ArgumentException(string.Format(MigrationToolkitResources.MissingArtifactTypeRefName)); } if (string.IsNullOrEmpty(artifactType.FriendlyName)) { throw new ArgumentException(string.Format(MigrationToolkitResources.MissingArtifactTypeDispName)); } var artifactTypeQuery = from t in context.RTArtifactTypeSet where t.ReferenceName.Equals(artifactType.ReferenceName) && t.DisplayName.Equals(artifactType.FriendlyName) && t.ArtifactContentType.Equals(artifactType.ContentTypeReferenceName) select t; if (artifactTypeQuery.Count() > 0) { return(artifactTypeQuery.First().Id); } var newType = RTArtifactType.CreateRTArtifactType(0, artifactType.ReferenceName, artifactType.FriendlyName, artifactType.ContentTypeReferenceName); context.AddToRTArtifactTypeSet(newType); context.TrySaveChanges(); return(newType.Id); } }
/// <summary> /// Gets the next active command to be processed. /// </summary> /// <param name="sessionGroupId">The GUID that's used as the unique Id of the subject session group.</param> /// <returns>The next active command; NULL if there is a command being processed or no active command.</returns> public PipelineSyncCommand?GetNextActiveCommand(Guid sessionGroupId) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { int newStateValue = (int)PipelineSyncCommandState.New; int processingStateValue = (int)PipelineSyncCommandState.Processing; var cmdQuery = from c in context.RTOrchestrationCommandSet where (c.Status == newStateValue || c.Status == processingStateValue) && c.SessionGroup.GroupUniqueId.Equals(sessionGroupId) orderby c.Id select c; if (cmdQuery.Count() == 0 || cmdQuery.First().Status == processingStateValue) { return(null); } RTOrchestrationCommand nextCmd = cmdQuery.First(); nextCmd.Status = (int)PipelineSyncCommandState.Processing; context.TrySaveChanges(); return((PipelineSyncCommand)nextCmd.Command); } }
/// <summary> /// Marks a command to be processed. /// </summary> /// <param name="sessionGroupId">The GUID that's used as the unique Id of the subject session group.</param> /// <param name="command">The command to be marked as processed.</param> public void MarkCommandProcessed(Guid sessionGroupId, PipelineSyncCommand command) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { int commandValue = (int)command; int processingStateValue = (int)PipelineSyncCommandState.Processing; var cmdQuery = from c in context.RTOrchestrationCommandSet where c.Command == commandValue && c.Status == processingStateValue && c.SessionGroup.GroupUniqueId.Equals(sessionGroupId) select c; if (cmdQuery.Count() == 0) { return; } foreach (var cmd in cmdQuery) { cmd.Status = (int)PipelineSyncCommandState.Processed; } context.TrySaveChanges(); } }
public void PromoteInAnalysisChangesToReadyForMigration() { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { //todo: convert to sproc int inAnalysisVal = (int)LinkChangeGroup.LinkChangeGroupStatus.InAnalysisTranslated; int translatedVal = LinkChangeAction.GetStatusStorageValue(LinkChangeAction.LinkChangeActionStatus.Translated); int readyForMigrVal = (int)LinkChangeGroup.LinkChangeGroupStatus.ReadyForMigration; var linkActionQuery = from a in context.RTLinkChangeActionSet where a.LinkChangeGroup.SessionGroupUniqueId.Equals(SessionGroupId) && a.LinkChangeGroup.SessionUniqueId.Equals(SessionId) && a.LinkChangeGroup.SourceId.Equals(SourceId) && a.LinkChangeGroup.Status == inAnalysisVal && !a.LinkChangeGroup.ContainsConflictedAction && a.Status == translatedVal && a.Conflicted == false select a; foreach (RTLinkChangeAction linkChangeAction in linkActionQuery) { linkChangeAction.Status = LinkChangeAction.GetStatusStorageValue(LinkChangeAction.LinkChangeActionStatus.ReadyForMigration); } context.TrySaveChanges(); context.BatchUpdateLinkChangeGroupStatus(SessionGroupId, SessionId, SourceId, false, inAnalysisVal, readyForMigrVal); } }
internal RTLinkChangeGroup AddLinkChangeGroup(LinkChangeGroup group) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { var rtLinkChangeGroup = RTLinkChangeGroup.CreateRTLinkChangeGroup( 0, (int)group.Status, false, SessionGroupId, SessionId, SourceId); rtLinkChangeGroup.GroupName = group.GroupName; context.AddToRTLinkChangeGroupSet(rtLinkChangeGroup); int newActiveActionCount = 0; foreach (LinkChangeAction a in group.Actions) { RTLinkChangeAction rtLinkChangeAction = AddChangeAction(a, context); if (rtLinkChangeAction == null) { continue; } rtLinkChangeAction.LinkChangeGroup = rtLinkChangeGroup; ++newActiveActionCount; } if (newActiveActionCount <= 0) { return(null); } context.TrySaveChanges(); group.InternalId = rtLinkChangeGroup.Id; context.Detach(rtLinkChangeGroup); return(rtLinkChangeGroup); } }
protected override void Update() { if (m_usePagedActions) { PagedCollection <IMigrationAction> pagedActions = this.Actions as PagedCollection <IMigrationAction>; pagedActions.SaveActivePage(); } using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { RTChangeGroup rtChangeGroupCache = context.GetObjectByKey(m_runTimeChangeGroup.EntityKey) as RTChangeGroup; switch (Status) { case ChangeStatus.InProgress: rtChangeGroupCache.StartTime = DateTime.UtcNow; break; case ChangeStatus.DeltaComplete: case ChangeStatus.Complete: rtChangeGroupCache.FinishTime = DateTime.UtcNow; break; default: break; } rtChangeGroupCache.Status = (int)Status; rtChangeGroupCache.ReflectedChangeGroupId = ReflectedChangeGroupId; populateMetaData(rtChangeGroupCache); context.TrySaveChanges(); } }
private void InsertServerDiffResultInDB(DateTime diffStartTime, bool allContentsMatch, int durationOfDiffInSeconds, string leftQualifier, string rightQualifier) { using (RuntimeEntityModel runtimeEntityModel = RuntimeEntityModel.CreateInstance()) { RTServerDiffResult serverDiffResult = RTServerDiffResult.CreateRTServerDiffResult( 0, Session.SessionType.ToString(), diffStartTime, durationOfDiffInSeconds, Session.SessionUniqueIdGuid, allContentsMatch, BuildOptionsStringForServerDiffResult(leftQualifier, rightQualifier)); runtimeEntityModel.AddToRTServerDiffResultSet(serverDiffResult); foreach (string serverDiffResultDetail in m_serverDiffResultDetails) { RTServerDiffResultDetail rtServerDiffResultDetail = RTServerDiffResultDetail.CreateRTServerDiffResultDetail( 0, serverDiffResultDetail); rtServerDiffResultDetail.ServerDiffResult = serverDiffResult; runtimeEntityModel.AddToRTServerDiffResultDetailSet(rtServerDiffResultDetail); } runtimeEntityModel.TrySaveChanges(); } }
public virtual void Reload() { if ((m_sessionUniqueId == Guid.Empty) || (m_sourceUniqueId == Guid.Empty)) { throw new MigrationException( string.Format(MigrationToolkitResources.Culture, MigrationToolkitResources.UninitializedHighWaterMark, m_name)); } using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { var highwaterMarksQuery = from hwm in context.RTHighWaterMarkSet where hwm.SessionUniqueId.Equals(m_sessionUniqueId) && hwm.SourceUniqueId.Equals(m_sourceUniqueId) && hwm.Name.Equals(m_name) select hwm; RTHighWaterMark rtHighWaterMark = null; if (highwaterMarksQuery.Count() > 0) { rtHighWaterMark = highwaterMarksQuery.First(); if (rtHighWaterMark.Value != null) { m_current = CreateValueFromString(rtHighWaterMark.Value); } else { m_current = default(T); } } else { rtHighWaterMark = RTHighWaterMark.CreateRTHighWaterMark(0, m_sessionUniqueId, m_sourceUniqueId, m_name); context.AddToRTHighWaterMarkSet(rtHighWaterMark); context.TrySaveChanges(); m_current = default(T); } } /* * using (TfsMigrationConsolidatedDBEntities context = TfsMigrationConsolidatedDBEntities.CreateInstance()) * { * HighWaterMarkEntity highWaterMarkEntity = context.CreateHighWaterMark * (m_sessionUniqueId, * m_sourceUniqueId, * m_name).First<HighWaterMarkEntity>(); * * * // ToDo error handling * if (highWaterMarkEntity.Value == null) * { * m_current = default(T); * } * else * { * m_current = CreateValueFromString(highWaterMarkEntity.Value); * } * }*/ }
public virtual void Update(T newValue) { if (newValue == null) { throw new ArgumentNullException("newValue"); } if ((m_sessionUniqueId == Guid.Empty) || (m_sourceUniqueId == Guid.Empty)) { throw new MigrationException( string.Format(MigrationToolkitResources.Culture, MigrationToolkitResources.UninitializedHighWaterMark, m_name)); } string newValueString = GetValueAsString(newValue); // Todo We probably could use EDM eventing , OnBeforeUpdate(newValue); using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { var highwaterMarksQuery = from hwm in context.RTHighWaterMarkSet where hwm.SessionUniqueId.Equals(m_sessionUniqueId) && hwm.SourceUniqueId.Equals(m_sourceUniqueId) && hwm.Name.Equals(m_name) select hwm; if (highwaterMarksQuery.Count() > 0) { RTHighWaterMark rtHighWaterMark = highwaterMarksQuery.First(); rtHighWaterMark.Value = newValueString; context.TrySaveChanges(); } else { RTHighWaterMark rtHighWaterMark = new RTHighWaterMark(); rtHighWaterMark.SessionUniqueId = m_sessionUniqueId; rtHighWaterMark.SourceUniqueId = m_sourceUniqueId; rtHighWaterMark.Name = m_name; rtHighWaterMark.Value = newValueString; context.AddToRTHighWaterMarkSet(rtHighWaterMark); context.TrySaveChanges(); } } m_current = newValue; }
private void UpdateItemConversionHistory( RTConversionHistory rtConvHist, RuntimeEntityModel context) { foreach (ItemConversionHistory hist in ItemConversionHistory) { if (string.IsNullOrEmpty(hist.SourceItemId) || string.IsNullOrEmpty(hist.TargetItemId)) { throw new MigrationException(MigrationToolkitResources.InvalidConversionHistoryInfo); } string sourceItemVersionStr = string.IsNullOrEmpty(hist.SourceItemVersion) ? Constants.ChangeGroupGenericVersionNumber : hist.SourceItemVersion; RTMigrationItem sourceItem = FindCreateMigrationItem( SourceSideSourceId, hist.SourceItemId, sourceItemVersionStr, context); string targetItemVersionStr = string.IsNullOrEmpty(hist.TargetItemVersion) ? Constants.ChangeGroupGenericVersionNumber : hist.TargetItemVersion; RTMigrationItem targetItem = FindCreateMigrationItem( TargetSideSourceId, hist.TargetItemId, targetItemVersionStr, context); context.TrySaveChanges(); // check if the pair is already in the item_revision_pair table var pairWithSourceItemQuery = from p in context.RTItemRevisionPairSet where (p.LeftMigrationItemId == sourceItem.Id || p.RightMigrationItemId == sourceItem.Id) select p; if (pairWithSourceItemQuery.Count() > 0) { var targetItemInPairQuery = from p in pairWithSourceItemQuery where p.LeftMigrationItemId == targetItem.Id || p.RightMigrationItemId == targetItem.Id select p; if (targetItemInPairQuery.Count() > 0) { continue; } } RTItemRevisionPair pair = RTItemRevisionPair.CreateRTItemRevisionPair( sourceItem.Id, targetItem.Id); pair.LeftMigrationItem = sourceItem; pair.RightMigrationItem = targetItem; pair.ConversionHistory = rtConvHist; } }
public override void BatchUpdateStatus(ChangeGroup[] changeGroups) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { foreach (SqlChangeGroup sqlChangeGroup in changeGroups) { sqlChangeGroup.PersistCurrentStatus(context); } context.TrySaveChanges(); } }
public void SaveLinkChangeGroupTranslationResult(ReadOnlyCollection <LinkChangeGroup> linkChangeGroups) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { foreach (LinkChangeGroup linkChangeGroup in linkChangeGroups) { SaveLinkChangeGroupTranslationResult(linkChangeGroup, context); } context.TrySaveChanges(); } }
private void SavePartialChangeGroup() { if (null != m_runTimeChangeGroup) { return; } SqlChangeGroupManager manager = this.Manager as SqlChangeGroupManager; Debug.Assert(null != manager, "Manager is not a SqlChangeGroupManager for SqlChangeGroup"); using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { try { context.Attach(manager.RunTimeMigrationSource); context.Attach(manager.RuntimeSessionRun); // save group attributes m_runTimeChangeGroup = RTChangeGroup.CreateRTChangeGroup(-1, ExecutionOrder, SessionId, SourceId, (int)ChangeStatus.ChangeCreationInProgress, false); m_runTimeChangeGroup.Owner = Owner; m_runTimeChangeGroup.Comment = Comment; // Store the ChangeTimeUtc value in the RevsionTime column unless the ChangeTimeUtc is not set (MinValue) // If it's not set, store DateTime.MaxValue to indicate that because DateTime.MinValue is outside the range allowed by SQL m_runTimeChangeGroup.RevisionTime = ChangeTimeUtc.Equals(DateTime.MinValue) ? DateTime.MaxValue : ChangeTimeUtc; m_runTimeChangeGroup.StartTime = DateTime.UtcNow; m_runTimeChangeGroup.Name = Name; m_runTimeChangeGroup.ReflectedChangeGroupId = ReflectedChangeGroupId; m_runTimeChangeGroup.UsePagedActions = m_usePagedActions; m_runTimeChangeGroup.IsForcedSync = IsForcedSync; // establish SessionRun association m_runTimeChangeGroup.SessionRun = manager.RuntimeSessionRun; // estabilish MigrationSource association m_runTimeChangeGroup.SourceSideMigrationSource = manager.RunTimeMigrationSource; // save the group context.AddToRTChangeGroupSet(m_runTimeChangeGroup); context.TrySaveChanges(); // record internal Id this.ChangeGroupId = m_runTimeChangeGroup.Id; } finally { context.Detach(m_runTimeChangeGroup); context.Detach(manager.RunTimeMigrationSource); context.Detach(manager.RuntimeSessionRun); } } }
/// <summary> /// Marks a non-syncworkflow session to be completed /// and the parent session group to be completed if all its child /// sessions are in "completed (3)" status /// </summary> private void MigrationSessionCompleted() { // update the session state to Completed // // NOTE: // The sproc called here through EDM sets the Session *Group* to // be completed if all the sibling sessions of the current session (inclusively) // are completed. var updatedRTSessions = m_context.UpdateMigrationSessionStatusToCompleted(SessionId); if (updatedRTSessions.Count() > 0 && WorkFlowType.Frequency == Frequency.OneTime) { // mark Session Group to be OneTimeCompleted (value: 4) // Note: updatedRTSessions has already been enumerated in the EDM imported function UpdateMigrationSessionStatusToCompleted // We have to ask the Context for a new instance of the RTSession, rather than enumerating on updatedRTSessions RTSession rtSession = m_context.RTSessionSet.Where(s => s.SessionUniqueId.Equals(SessionId)).First(); rtSession.SessionGroupReference.Load(); if (rtSession.SessionGroup.State == (int)BusinessModelManager.SessionStateEnum.Completed) { rtSession.SessionGroup.State = (int)BusinessModelManager.SessionStateEnum.OneTimeCompleted; m_context.TrySaveChanges(); } } // update the session sync orchestration state if (m_syncStateMachine.TryTransit(PipelineSyncCommand.STOP)) { m_syncStateMachine.CommandTransitFinished(PipelineSyncCommand.STOP); } var rtSessionRun = m_context.RTSessionRunSet.Where(r => r.Id == m_sessionRunId).FirstOrDefault(); if (null != rtSessionRun) { rtSessionRun.State = (int)BusinessModelManager.SessionStateEnum.Completed; m_context.TrySaveChanges(); } }
/// <summary> /// /// </summary> /// <param name="providerAttributes"></param> /// <returns>True if a new provider is saved; False if an existing one is found</returns> internal static bool TrySaveProvider(ProviderDescriptionAttribute providerAttributes, out int internalId) { using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { var providerQuery = from p in context.RTProviderSet where p.ReferenceName.Equals(providerAttributes.Id) && p.FriendlyName.Equals(providerAttributes.Name) && (p.ProviderVersion.Equals(providerAttributes.Version) || string.IsNullOrEmpty(p.ProviderVersion)) select p; if (providerQuery.Count() > 0) { RTProvider existingProvider = providerQuery.First(); internalId = existingProvider.Id; if (string.IsNullOrEmpty(existingProvider.ProviderVersion)) { // this is possible in older version of the toolkit // we need to fill up the missing info and assume that the provider was not in DB existingProvider.ProviderVersion = providerAttributes.Version; context.TrySaveChanges(); return(true); } else { return(false); } } RTProvider rtProvider = RTProvider.CreateRTProvider(0, providerAttributes.Id, providerAttributes.Name); rtProvider.ProviderVersion = providerAttributes.Version; context.AddToRTProviderSet(rtProvider); context.TrySaveChanges(); internalId = rtProvider.Id; return(true); } }
private bool TakeSource(MigrationConflict conflict) { // find the target-side change action (should be a delta table entry) // SIDE NOTE: // upon detection of a wit edit/edit conflict, we create // 1. an edit/edit conflict for the source side change group/action // 2. a chainonconflictconflict for the target side's (using the source-side conflict id as the scopehint) // look up for target-side conflicted change action id long targetChangeActionId; bool retVal = WITEditEditConflictType.TryGetConflictedTargetChangeActionId(conflict.ConflictDetails, out targetChangeActionId); if (!retVal) { // backward compatibility: // old-style edit/edit conflict details does not include target change action id // in that case, we can't find a change action to complete the anlaysis return(false); } using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { Debug.Assert(conflict.ConflictedChangeAction != null, "Edit/Edit conflict ConflictedCangeAction is NULL"); // Extract all fields updated in the target change action string[] sourceSideChangedFields = ExtractFieldRefNames(conflict.ConflictedChangeAction.MigrationActionDescription); // find the target-side change action (should be a delta table entry) var changeActionQuery = context.RTChangeActionSet.Where(a => a.ChangeActionId == targetChangeActionId); if (changeActionQuery.Count() != 1) { return(false); } RTChangeAction targetChangeAction = changeActionQuery.First(); // drop the source-side updated fields from the target-side change // example: // source side change includes Field1, Field2, Field3 // target side change includes Field1, Field2, Field5, Field 6 // By taking source, we want to migrate Field1, Field2, Field3 to target side // Then migrate Field5, Field 6 to source side, i.e. dropping Field1, Field2 XmlDocument targetSideChanges = new XmlDocument(); targetSideChanges.LoadXml(targetChangeAction.ActionData); DropFields(targetSideChanges, sourceSideChangedFields); // update result for target change targetChangeAction.ActionData = targetSideChanges.OuterXml; SkipChangeWithZeroFieldUpdates(targetChangeAction); context.TrySaveChanges(); return(true); } }
internal override void UpdateStatus(ChangeStatus newChangeStatus) { if (Status != newChangeStatus) { Status = newChangeStatus; using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { PersistCurrentStatus(context); context.TrySaveChanges(); } } }
private void SavePartialChangeGroup() { if (null != m_runTimeChangeGroup) { return; } SqlChangeGroupManager manager = this.Manager as SqlChangeGroupManager; Debug.Assert(null != manager, "Manager is not a SqlChangeGroupManager for SqlChangeGroup"); using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { try { context.Attach(manager.RunTimeMigrationSource); context.Attach(manager.RuntimeSessionRun); // save group attributes m_runTimeChangeGroup = RTChangeGroup.CreateRTChangeGroup(-1, ExecutionOrder, SessionId, SourceId, (int)ChangeStatus.ChangeCreationInProgress, false); m_runTimeChangeGroup.Owner = Owner; m_runTimeChangeGroup.Comment = Comment; m_runTimeChangeGroup.RevisionTime = RevisionTime; m_runTimeChangeGroup.StartTime = DateTime.UtcNow; m_runTimeChangeGroup.Name = Name; m_runTimeChangeGroup.ReflectedChangeGroupId = ReflectedChangeGroupId; m_runTimeChangeGroup.UsePagedActions = m_usePagedActions; // establish SessionRun association m_runTimeChangeGroup.SessionRun = manager.RuntimeSessionRun; // estabilish MigrationSource association m_runTimeChangeGroup.SourceSideMigrationSource = manager.RunTimeMigrationSource; // save the group context.AddToRTChangeGroupSet(m_runTimeChangeGroup); context.TrySaveChanges(); // record internal Id this.ChangeGroupId = m_runTimeChangeGroup.Id; } finally { context.Detach(m_runTimeChangeGroup); context.Detach(manager.RunTimeMigrationSource); context.Detach(manager.RuntimeSessionRun); } } }
protected void MarkRelationshipNoLongerExists(string sourceItemUri, string targetItemUri, string relationship) { var queryByItem = QueryByItem(sourceItemUri); var queryOnRelatedArtifactAndStatus = from link in queryByItem where link.RelationshipExistsOnServer && link.RelatedArtifactId.Equals(targetItemUri) && link.Relationship.Equals(relationship) select link; if (queryByItem.Count() > 0) { queryByItem.First().RelationshipExistsOnServer = false; queryByItem.First().OtherProperty = 0; m_context.TrySaveChanges(); } }
/// <summary> /// Saves the conversion history and associate it with a particular session run and migration source; /// Additionally, mark the Reflected Change Group (the delta table entry of this processed change group) to be sync-ed. /// </summary> /// <param name="sessionRunId">int.MinValue if sessionRunId is not available</param> /// <param name="migrationSourceId"></param> /// <param name="sessionId"></param> /// <param name="reflectedChangeGroupId"></param> /// <returns></returns> internal bool Save( int sessionRunId, Guid migrationSourceId, Guid sessionId, long?reflectedChangeGroupId) { if (string.IsNullOrEmpty(ChangeId)) { return(false); } using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { if (ItemConversionHistory.Count > 0) { var sessionRunQuery = (sessionRunId == int.MinValue) ? from sr in context.RTSessionRunSet where sr.Config.LeftSourceConfig.MigrationSource.UniqueId.Equals(migrationSourceId) || sr.Config.RightSourceConfig.MigrationSource.UniqueId.Equals(migrationSourceId) select sr : context.RTSessionRunSet.Where(sr => sr.Id == sessionRunId); if (sessionRunQuery.Count() == 0) { return(false); } RTSessionRun rtSessionRun = sessionRunQuery.First(); var migrationSourceQuery = context.RTMigrationSourceSet.Where(ms => ms.UniqueId.Equals(migrationSourceId)); if (migrationSourceQuery.Count() == 0) { return(false); } RTMigrationSource rtMigrationSource = migrationSourceQuery.First(); RTConversionHistory rtConvHist = UpdateGroupConvHist(context, rtSessionRun, rtMigrationSource); UpdateItemConversionHistory(rtConvHist, context); } if (!sessionId.Equals(Guid.Empty) && reflectedChangeGroupId.HasValue) { MarkDeltaTableSynced(context, sessionId, reflectedChangeGroupId.Value); } context.TrySaveChanges(); return(true); } }
public HighWaterMark(Guid SessionUniqueId, Guid SourceUniqueId, string name, T defaultValue) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } m_sessionUniqueId = SessionUniqueId; m_sourceUniqueId = SourceUniqueId; m_name = name; using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { var highwaterMarksQuery = from hwm in context.RTHighWaterMarkSet where hwm.SessionUniqueId.Equals(m_sessionUniqueId) && hwm.SourceUniqueId.Equals(m_sourceUniqueId) && hwm.Name.Equals(m_name) select hwm; RTHighWaterMark rtHighWaterMark = null; if (highwaterMarksQuery.Count() > 0) { rtHighWaterMark = highwaterMarksQuery.First(); if (rtHighWaterMark.Value != null) { m_current = CreateValueFromString(rtHighWaterMark.Value); } } else { rtHighWaterMark = RTHighWaterMark.CreateRTHighWaterMark(0, m_sessionUniqueId, m_sourceUniqueId, m_name); context.TrySaveChanges(); } } //using (TfsMigrationConsolidatedDBEntities context = TfsMigrationConsolidatedDBEntities.CreateInstance()) //{ // HighWaterMarkEntity highWaterMarkEntity = context.CreateHighWaterMark(m_sessionUniqueId, m_sourceUniqueId, m_name).First<HighWaterMarkEntity>(); // if (highWaterMarkEntity.Value != null) // { // m_current = CreateValueFromString(highWaterMarkEntity.Value); // } //} }
public override void UpdateLastProcessedItemVersion(Dictionary <string, string> itemVersionPair, long lastChangeGroupId, Guid sourceId) { if (itemVersionPair.Count() == 0) { return; } using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { foreach (var itemVerion in itemVersionPair) { string itemId = itemVerion.Key; string version = itemVerion.Value; var query = from l in context.RTLastProcessedItemVersionsSet where l.ItemId.Equals(itemId) && l.MigrationSourceId.Equals(sourceId) select l; if (query.Count() > 0) { if (string.IsNullOrEmpty(query.First().Version)) { query.First().Version = version; } else { int inDbVersion = int.Parse(query.First().Version); int newVersion = int.Parse(version); if (newVersion > inDbVersion) { query.First().Version = version; } } } else { var newEntry = RTLastProcessedItemVersions.CreateRTLastProcessedItemVersions(sourceId, itemId, version); context.AddToRTLastProcessedItemVersionsSet(newEntry); } } context.TrySaveChanges(); } }
/// <summary> /// Acknowledge all acknowledgeable runtime conflicts /// </summary> /// <param name="context"></param> /// <param name="sessionGroupUniqueId"></param> /// <returns>List resolved conflicts, by Id</returns> internal static IEnumerable <int> AcknowledgeAllActiveConflicts( RuntimeEntityModel context, Guid sessionGroupUniqueId) { List <int> resolvedConflictIds = new List <int>(); IQueryable <RTConflict> activeConflicts = GetActiveAcknowledgeableConflicts(context, sessionGroupUniqueId); foreach (RTConflict c in activeConflicts) { c.Status = 1; // 1: resolved resolvedConflictIds.Add(c.Id); } context.TrySaveChanges(); return(resolvedConflictIds); }
public void FinishTrackingEvent(Guid eventReferenceName) { lock (m_eventTrackCacheLock) { if (!m_eventTrackCache.ContainsKey(eventReferenceName)) { return; } using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { RTSessionRun rtSessionRun = context.RTSessionRunSet.Where (s => s.Id == m_session.InternalSessionRunId).First <RTSessionRun>(); Debug.Assert(rtSessionRun != null, string.Format("Cannot find session run with Id ({0}) to track event", m_session.InternalSessionRunId)); EventTrackingCache cache = m_eventTrackCache[eventReferenceName]; RTGeneralPerformanceData perfData = (from p in context.RTGeneralPerformanceDataSet where p.RuntimeSessionGroupRun.Id == rtSessionRun.SessionGroupRun.Id && p.SessionUniqueId.Equals(rtSessionRun.Config.SessionUniqueId) && p.SourceUniqueId.Equals(m_sourceId) && p.CriterionReferenceName.Equals(eventReferenceName) select p).First <RTGeneralPerformanceData>(); if (null == perfData) { perfData = RTGeneralPerformanceData.CreateRTGeneralPerformanceData( 0, rtSessionRun.Config.SessionUniqueId, m_sourceId, eventReferenceName, cache.FriendlyName); perfData.RuntimeSessionGroupRun = rtSessionRun.SessionGroupRun; } perfData.PerfCounter = cache.Counter; perfData.PerfStartTime = cache.StartTime; perfData.PerfFinishTime = DateTime.Now; context.TrySaveChanges(); } m_eventTrackCache.Remove(eventReferenceName); } }