public void ConversionResultConstructorDoubleStringNullTest() { ConversionResult res = new ConversionResult (0, Convert.ToString (null)); Assert.IsNotNull (res); Assert.AreEqual (0, res.Value); Assert.AreEqual (Result.NoError, res.Result); Assert.AreEqual (null, res.Symbol); }
public void ConversionResultConstructorDoubleResultTest() { ConversionResult res = new ConversionResult (10.5, Result.GenericError); Assert.IsNotNull (res); Assert.AreEqual (10.5, res.Value); Assert.AreEqual (Result.GenericError, res.Result); Assert.AreEqual (null, res.Symbol); }
private void AddAttachment(IMigrationAction action, ConversionResult convRslt) { string attName = UtilityMethods.ExtractAttachmentName(action); string lengthStr = UtilityMethods.ExtractAttachmentLength(action); string attComment = UtilityMethods.ExtractAttachmentComment(action); string ownerRecordDisplayName = FindTargetWorkItemId(action); string ownerRecordType = UtilityMethods.ExtractRecordType(action); string filePath = Path.Combine(m_configurationService.WorkspaceRoot, ownerRecordDisplayName + attName); try { // find the entity OAdEntity entity = CQWrapper.GetEntity(m_userSession, ownerRecordType, ownerRecordDisplayName); if (AttachmentExists(entity, attName, attComment, lengthStr)) { action.State = ActionState.Skipped; return; } // find the change action def name string entityDefName = CQWrapper.GetEntityDefName(entity); OAdEntityDef entityDef = CQWrapper.GetEntityDef(m_userSession, entityDefName); string modifyActionDefName = FindCQActionDefName(entityDef, CQConstants.ACTION_MODIFY); // mark entity to be editable CQWrapper.EditEntity(m_userSession, entity, modifyActionDefName); // cache the current history count for all "history fields" // i.e. pairs of HistoryFieldName, count Dictionary <string, int> recordHistoryCountCache = new Dictionary <string, int>(); BuildRecordHistoryCountCache(entity, recordHistoryCountCache); action.SourceItem.Download(filePath); string attachmentField = m_migrationContext.GetAttachmentSinkField(entityDefName); string retVal = CQWrapper.AddAttachmentFieldValue(entity, attachmentField, attName, filePath); if (!string.IsNullOrEmpty(retVal)) { // teyang_todo attachment conflict } retVal = CQWrapper.Validate(entity); if (!string.IsNullOrEmpty(retVal)) { // [teyang] TODO conflict management throw new InvalidOperationException(); } retVal = CQWrapper.Commmit(entity); if (!string.IsNullOrEmpty(retVal)) { // [teyang] TODO conflict management throw new InvalidOperationException(); } if (action.State == ActionState.Pending) { action.State = ActionState.Complete; } // ********* // now comparing to the cache, so that we can clearly identify the item:version pairs // e.g. TargetCQRecordDisplayName : HistoryFieldName::LatestHistoryIndex Dictionary <string, int[]> updatedHistoryIndices = new Dictionary <string, int[]>(); FindUpdatedHistoryIndices(entity, recordHistoryCountCache, updatedHistoryIndices); recordHistoryCountCache.Clear(); foreach (string histFieldName in updatedHistoryIndices.Keys) { foreach (int histIndex in updatedHistoryIndices[histFieldName]) { UpdateConversionHistory(action, ownerRecordDisplayName, CQHistoryMigrationItem.CreateHistoryItemVersion(histFieldName, histIndex), convRslt); } } } finally { if (File.Exists(filePath)) { File.Delete(filePath); } } }
public ConversionResult ProcessChangeGroup(ChangeGroup changeGroup) { Guid targetSideSourceId = m_configurationService.SourceId; Guid sourceSideSourceId = m_configurationService.MigrationPeer; ConversionResult convRslt = new ConversionResult(sourceSideSourceId, targetSideSourceId); try { int skippedActionCount = 0; foreach (IMigrationAction action in changeGroup.Actions) { if (IsSourceWorkItemInBacklog(action)) { continue; } if (action.State == ActionState.Skipped) { ++skippedActionCount; continue; } if (action.MigrationActionDescription == null || action.MigrationActionDescription.DocumentElement == null) { throw new MigrationException(ClearQuestResource.ClearQuest_Error_InvalidActionDescription, action.ActionId); } if (action.Action == WellKnownChangeActionId.Add) { AddRecord(action, convRslt); } else if (action.Action == WellKnownChangeActionId.Edit) { EditRecord(action, convRslt); } else if (action.Action == WellKnownChangeActionId.AddAttachment) { AddAttachment(action, convRslt); } else if (action.Action == WellKnownChangeActionId.DelAttachment) { DeleteAttachment(action, convRslt); } else { action.State = ActionState.Skipped; } if (action.State == ActionState.Skipped) { ++skippedActionCount; } } if (skippedActionCount == changeGroup.Actions.Count) { convRslt.ChangeId = Microsoft.TeamFoundation.Migration.Toolkit.Constants.MigrationResultSkipChangeGroup; } } catch (ClearQuestCOMDllNotFoundException cqComNotFoundEx) { if (!UtilityMethods.HandleCOMDllNotFoundException(cqComNotFoundEx, ErrorManager, m_conflictManagerService)) { convRslt.ContinueProcessing = false; } } catch (ClearQuestCOMCallException cqComCallEx) { if (!UtilityMethods.HandleCQComCallException(cqComCallEx, ErrorManager, m_conflictManagerService)) { convRslt.ContinueProcessing = false; } } catch (Exception ex) { if (!UtilityMethods.HandleGeneralException(ex, ErrorManager, m_conflictManagerService)) { convRslt.ContinueProcessing = false; } } return(convRslt); }
public void Failed_Throws_With_Null_Argument() { Assert.Throws <ArgumentNullException>(() => ConversionResult.Failed(exception: null)); }
protected override ConversionResult <DateTime> ConvertBack(string value, Type targetType, object parameter, CultureInfo culture) { var result = DateTime.Parse(value, CultureInfo.InvariantCulture); return(ConversionResult <DateTime> .SetValue(result)); }
protected override ConversionResult <Uri> Convert(string value, Type targetType, object parameter, CultureInfo culture) { var uri = Uri.Parse(value); return(ConversionResult <Uri> .SetValue(uri)); }
public OfficeToXpsConversionResult(ConversionResult result, string resultText, Exception exc) : this(result, resultText) { ResultError = exc; }
protected override ConversionResult <ViewStates> Convert(bool isVisible, Type targetType, object parameter, CultureInfo culture) { var visibility = isVisible ? ViewStates.Visible : ViewStates.Invisible; return(ConversionResult <ViewStates> .SetValue(visibility)); }
protected override ConversionResult <int> Convert(VacationType value, Type targetType, object parameter, CultureInfo culture) { return(ConversionResult <int> .SetValue((int)value)); }
public void ConversionResultConstructorDoubleStringTest() { ConversionResult res = new ConversionResult (10.5, "lb"); Assert.IsNotNull (res); Assert.AreEqual (10.5, res.Value); Assert.AreEqual (Result.NoError, res.Result); Assert.AreEqual ("lb", res.Symbol); }
public void ConversionResultValueTest() { ConversionResult res = new ConversionResult (12.1); Assert.IsNotNull (res); Assert.AreEqual (12.1, res.Value); res.Value = 0.33; Assert.AreEqual (0.33, res.Value); }
public void ConversionResultSymbolTest() { ConversionResult res = new ConversionResult (12.1, "ft"); Assert.IsNotNull (res); Assert.AreEqual ("ft", res.Symbol); res.Symbol = "C"; Assert.AreEqual ("C", res.Symbol); }
/// <summary> /// /// </summary> /// <param name="entity"></param> /// <param name="action"></param> /// <param name="convRslt"></param> /// <param name="stateTransitFieldNode"></param> /// <param name="skipFields"></param> /// <returns></returns> private bool ChangeRecordState( OAdEntity entity, IMigrationAction action, ConversionResult convRslt, XmlNode stateTransitFieldNode, out List <string> processedFields) { processedFields = new List <string>(); string destState = UtilityMethods.ExtractSingleFieldValue(stateTransitFieldNode); Debug.Assert(!string.IsNullOrEmpty(destState), "string.IsNullOrEmpty(newState)"); // get the record's display name for updating conversion history string recordDisplayName = CQWrapper.GetEntityDisplayName(entity); string entityDefName = CQWrapper.GetEntityDefName(entity); // find the current state OAdFieldInfo aFldInfo = CQWrapper.GetEntityFieldValue(entity, m_migrationContext.GetStateField(entityDefName)); string srcState = CQWrapper.GetFieldValue(aFldInfo); if (CQStringComparer.StateName.Equals(srcState, destState)) { // state does not change, skip this action return(false); } // find action def name OAdEntityDef entityDef = CQWrapper.GetEntityDef(m_userSession, entityDefName); string[] changeActionNames = CQUtilityMethods.FindAllActionNameByTypeAndStateTransition(entityDef, srcState, destState, CQConstants.ACTION_CHANGE); if (changeActionNames.Length == 0) { // [teyang] todo error handling throw new InvalidOperationException(); } string changeActionName = changeActionNames[0]; // ********* // cache the current history count for all "history fields" // i.e. pairs of HistoryFieldName, count Dictionary <string, int> recordHistoryCountCache = new Dictionary <string, int>(); BuildRecordHistoryCountCache(entity, recordHistoryCountCache); StringBuilder updateLog = new StringBuilder(); PrintUpdateLogHeader(action, updateLog); // mark entity to be editable with the desired state-change action) CQWrapper.EditEntity(m_userSession, entity, changeActionName); XmlNodeList columns = action.MigrationActionDescription.SelectNodes("/WorkItemChanges/Columns/Column"); if (null == columns) { throw new MigrationException(ClearQuestResource.ClearQuest_Error_InvalidActionDescription, action.ActionId); } foreach (XmlNode columnData in columns) { string stringVal = columnData.FirstChild.InnerText; string fieldName = columnData.Attributes["ReferenceName"].Value; Debug.Assert(!string.IsNullOrEmpty(fieldName), "Field ReferenceName is absent in the Migration Description"); OAdFieldInfo aFieldInfo = CQWrapper.GetEntityFieldValue(entity, fieldName); int fieldRequiredness = CQWrapper.GetRequiredness(aFieldInfo); if (fieldRequiredness != CQConstants.MANDATORY) { // skipping all non-mandatory fields continue; } int attempt1Count = 0; if (!SetFieldValue(action, entity, fieldName, stringVal, ref attempt1Count)) { return(false); } AddFieldToUpdateLog(fieldName, stringVal, updateLog); processedFields.Add(fieldName); } AddLineToUpdateLog(updateLog); int attempt2Count = 0; if (!SetFieldValue(action, entity, NoteEntryFieldName, updateLog.ToString(), ref attempt2Count)) { return(false); } string retVal = CQWrapper.Validate(entity); if (!string.IsNullOrEmpty(retVal)) { // [teyang] TODO conflict handling throw new InvalidOperationException(retVal); } retVal = CQWrapper.Commmit(entity); if (!string.IsNullOrEmpty(retVal)) { // [teyang] TODO conflict handling throw new InvalidOperationException(retVal); } if (action.State == ActionState.Pending) { action.State = ActionState.Complete; } // ********* // now comparing to the cache, so that we can clearly identify the item:version pairs // e.g. TargetCQRecordDisplayName : HistoryFieldName::LatestHistoryIndex Dictionary <string, int[]> updatedHistoryIndices = new Dictionary <string, int[]>(); FindUpdatedHistoryIndices(entity, recordHistoryCountCache, updatedHistoryIndices); recordHistoryCountCache.Clear(); foreach (string histFieldName in updatedHistoryIndices.Keys) { foreach (int histIndex in updatedHistoryIndices[histFieldName]) { UpdateConversionHistory(action, recordDisplayName, CQHistoryMigrationItem.CreateHistoryItemVersion(histFieldName, histIndex), convRslt); } } return(true); }
protected override ConversionResult <string> Convert(int value, Type targetType, object parameter, CultureInfo culture) { return(ConversionResult <string> .SetValue(value.ToString())); }
protected override ConversionResult <ViewStates> Convert(bool value, Type targetType, object parameter, CultureInfo culture) { var viewState = value ? ViewStates.Visible : ViewStates.Gone; return(ConversionResult <ViewStates> .SetValue(viewState)); }
public OfficeToXpsConversionResult(ConversionResult result) : this() { Result = result; }
public OfficeToXpsConversionResult(ConversionResult result, string resultText) : this(result) { ResultText = resultText; }
public void ConversionResultResultTest() { ConversionResult res = new ConversionResult (Result.GenericError); Assert.IsNotNull (res); Assert.AreEqual (Result.GenericError, res.Result); res.Result = Result.UnitNotFound; Assert.AreEqual (Result.UnitNotFound, res.Result); }
protected override ConversionResult <string> Convert(DateTime value, Type targetType, object parameter, CultureInfo culture) { var year = value.Year.ToString(); return(ConversionResult <string> .SetValue(year)); }
protected override ConversionResult <string> Convert(int value, Type targetType, object parameter, CultureInfo culture) { var text = value == 0 ? Strings.SelectFields : value.ToString(); return(ConversionResult <string> .SetValue(text)); }
protected override ConversionResult <string> Convert(DateTime value, Type targetType, object parameter, CultureInfo culture) { var result = value.ToShortTimeString(); return(ConversionResult <string> .SetValue(result)); }
protected override ConversionResult <TValue> Convert(TSource value, Type targetType, object parameter, CultureInfo culture) { return(ConversionResult <TValue> .SetValue(GetMapping(parameter).Convert.Invoke(value))); }
protected override ConversionResult <string> Convert(DateTime value, Type targetType, object parameter, CultureInfo culture) { var text = value.ToString("dd", CultureInfo.CurrentCulture); return(ConversionResult <string> .SetValue(text)); }
private ConversionResult GetMarketAmountInBase( OrderAction orderAction, IEnumerable <IOrderBook> orderBooks, AssetWithAmount from, string assetTo, IReadOnlyDictionary <string, Assets.Client.Models.v3.Asset> assetsDict, IEnumerable <Assets.Client.Models.v3.AssetPair> assetPairs, Core.Domain.MarketProfile marketProfile) { var result = new ConversionResult(); var assetPair = GetPairWithAssets(assetPairs, from.AssetId, assetTo); if (!IsInputValid(from, assetTo, assetsDict) || assetPair == null) { result.Result = OperationResult.InvalidInputParameters; return(result); } if (from.AssetId == assetTo) { result.From = result.To = from; result.Price = result.VolumePrice = 1; result.Result = OperationResult.Ok; return(result); } orderAction = IsInverted(assetPair, assetTo) ? orderAction.ViceVersa() : orderAction; var isBuy = orderAction == OrderAction.Buy; var orderBook = orderBooks.FirstOrDefault(x => x.AssetPair == assetPair.Id && x.IsBuy == isBuy); if (orderBook == null) { result.Result = OperationResult.NoLiquidity; return(result); } if (IsInverted(assetPair, assetTo)) { orderBook.Invert(); } orderBook.Order(); double sum = 0; double priceSum = 0; int n = 0; var neededSum = double.MaxValue; foreach (var line in orderBook.Prices) { if (n != 0 && sum >= neededSum) { break; } sum += Math.Abs(line.Volume); priceSum += line.Price; n++; neededSum = from.Amount * GetRate(assetTo, assetPair, priceSum / n); } if (n == 0) { result.Result = OperationResult.NoLiquidity; return(result); } var price = priceSum / n; result.From = from; var rate = GetRate(assetTo, assetPair, price); var displayRate = GetRate(from.AssetId, assetPair, price); result.To = new AssetWithAmount { AssetId = assetTo, Amount = (rate * from.Amount).TruncateDecimalPlaces(assetsDict[assetTo].Accuracy, orderAction == OrderAction.Buy) }; result.Result = sum < neededSum ? OperationResult.NoLiquidity : OperationResult.Ok; result.Price = GetRate( from.AssetId, assetPair, marketProfile.GetPrice(assetPair.Id, orderAction).GetValueOrDefault()); result.VolumePrice = displayRate; return(result); }
private void DeleteAttachment(IMigrationAction action, ConversionResult convRslt) { throw new NotImplementedException(); }
protected override ConversionResult <string> ConvertBack(DateTime value, Type targetType, object parameter, CultureInfo culture) { return(ConversionResult <string> .SetValue(value.ToString(DateFormat))); }
private void ModifyRecordContent( OAdEntity entity, IMigrationAction action, ConversionResult convRslt, List <string> skipFields) { XmlNodeList columns = action.MigrationActionDescription.SelectNodes("/WorkItemChanges/Columns/Column"); if (null == columns) { throw new MigrationException(ClearQuestResource.ClearQuest_Error_InvalidActionDescription, action.ActionId); } // get the record's display name for updating conversion history string recordDisplayName = CQWrapper.GetEntityDisplayName(entity); // ********* // cache the current history count for all "history fields" // i.e. pairs of HistoryFieldName, count Dictionary <string, int> recordHistoryCountCache = new Dictionary <string, int>(); BuildRecordHistoryCountCache(entity, recordHistoryCountCache); SetRecordEditable(entity); StringBuilder updateLog = new StringBuilder(); PrintUpdateLogHeader(action, updateLog); string entityDefName = CQWrapper.GetEntityDefName(entity); string stateTransitionFieldDefName = m_migrationContext.GetStateField(entityDefName); string retVal; bool recordIsUpdated = false; foreach (XmlNode columnData in columns) { string stringVal = columnData.FirstChild.InnerText; string fieldName = columnData.Attributes["ReferenceName"].Value; Debug.Assert(!string.IsNullOrEmpty(fieldName), "Field ReferenceName is absent in the Migration Description"); if (CQStringComparer.FieldName.Equals(fieldName, stateTransitionFieldDefName) || (null != skipFields && skipFields.Contains(fieldName, CQStringComparer.FieldName))) { // skip or "State" field, as it has already been submitted in a separate history/revision continue; } bool setFieldValue = false; OAdFieldInfo aFieldInfo = CQWrapper.GetEntityFieldValue(entity, fieldName); int fieldRequiredness = CQWrapper.GetRequiredness(aFieldInfo); switch (fieldRequiredness) { case CQConstants.MANDATORY: case CQConstants.OPTIONAL: setFieldValue = true; break; case CQConstants.READONLY: // [teyang] TODO conflict handling TraceManager.TraceWarning("Field {0} is READONLY", fieldName); setFieldValue = false; break; case CQConstants.USEHOOK: // [teyang] TODO conflict handling TraceManager.TraceWarning("Field {0} is USEHOOK", fieldName); setFieldValue = false; break; default: throw new InvalidOperationException(); } if (setFieldValue) { int attempt1Count = 0; if (!SetFieldValue(action, entity, fieldName, stringVal, ref attempt1Count)) { return; } AddFieldToUpdateLog(fieldName, stringVal, updateLog); recordIsUpdated = true; } } if (!recordIsUpdated) { // no update has been made to the record, mark this action to be skipped CQWrapper.Revert(entity); if (action.State == ActionState.Pending) { action.State = ActionState.Skipped; } return; } AddLineToUpdateLog(updateLog); int attempt2Count = 0; if (!SetFieldValue(action, entity, NoteEntryFieldName, updateLog.ToString(), ref attempt2Count)) { return; } retVal = CQWrapper.Validate(entity); if (!string.IsNullOrEmpty(retVal)) { IEnumerable <Microsoft.TeamFoundation.Migration.ClearQuestAdapter.CQTextParser.RecordValidationResult> validationResults; if (CQTextParser.RecordValidationTextParser.TryParse(retVal, out validationResults)) { foreach (CQTextParser.RecordValidationResult rslt in validationResults) { MigrationConflict conflict = ClearQuestInvalidFieldValueConflictType.CreateConflict(rslt, action); List <MigrationAction> actions; var resolutionRslt = m_conflictManagerService.TryResolveNewConflict(m_conflictManagerService.SourceId, conflict, out actions); if (!resolutionRslt.Resolved) { action.ChangeGroup.ContainsBackloggedAction = true; return; } } } else { throw new InvalidOperationException(retVal); } } retVal = CQWrapper.Commmit(entity); if (!string.IsNullOrEmpty(retVal)) { // [teyang] TODO: invalid update conflict handling throw new InvalidOperationException(retVal); } if (action.State == ActionState.Pending) { action.State = ActionState.Complete; } // ********* // now comparing to the cache, so that we can clearly identify the item:version pairs // e.g. TargetCQRecordDisplayName : HistoryFieldName::LatestHistoryIndex Dictionary <string, int[]> updatedHistoryIndices = new Dictionary <string, int[]>(); FindUpdatedHistoryIndices(entity, recordHistoryCountCache, updatedHistoryIndices); recordHistoryCountCache.Clear(); foreach (string histFieldName in updatedHistoryIndices.Keys) { foreach (int histIndex in updatedHistoryIndices[histFieldName]) { UpdateConversionHistory(action, recordDisplayName, CQHistoryMigrationItem.CreateHistoryItemVersion(histFieldName, histIndex), convRslt); } } }
private static Dictionary <string, NamedFact> GetConvertedNamedFacts <TTargetCompiler>(List <NamedFact> runnableTestsInSource, ConversionResult convertedText) where TTargetCompiler : ICompiler, new() { string code = convertedText.ConvertedCode; var targetCompiler = new TTargetCompiler(); var compiledTarget = targetCompiler.AssemblyFromCode(targetCompiler.CreateTree(code), AdditionalReferences); var runnableTestsInTarget = XUnitFactDiscoverer.GetNamedFacts(compiledTarget).ToDictionary(f => f.Name); Assert.Equal(runnableTestsInSource.Select(f => f.Name), runnableTestsInTarget.Keys); return(runnableTestsInTarget); }
private void AddRecord(IMigrationAction action, ConversionResult convRslt) { string recordType = UtilityMethods.ExtractRecordType(action); OAdEntity newRecord = CQWrapper.BuildEntity(m_userSession, recordType); string validationRsltString = string.Empty; List <string> processedFields = new List <string>(); #region add new record with MANDATORY field values if (!SetMandatoryFields(action, ref newRecord, out processedFields)) { return; } bool unResolvedConflictExists = false; bool validationErrorExists = false; validationRsltString = CQWrapper.Validate(newRecord); if (!string.IsNullOrEmpty(validationRsltString)) { validationErrorExists = true; IEnumerable <CQTextParser.RecordValidationResult> validationResults; if (CQTextParser.RecordValidationTextParser.TryParse(validationRsltString, out validationResults)) { foreach (CQTextParser.RecordValidationResult rslt in validationResults) { MigrationConflict conflict = ClearQuestInvalidFieldValueConflictType.CreateConflict(rslt, action); List <MigrationAction> actions; var resolutionRslt = m_conflictManagerService.TryResolveNewConflict(m_conflictManagerService.SourceId, conflict, out actions); if (!resolutionRslt.Resolved) { unResolvedConflictExists = true; break; } } } else { throw new InvalidOperationException(validationRsltString); } } if (unResolvedConflictExists) { return; } else if (validationErrorExists) { // All conflicts are resolved. Try re-applying the changes newRecord.Revert(); SetRecordEditable(newRecord); if (!SetMandatoryFields(action, ref newRecord, out processedFields)) { return; } else { validationRsltString = CQWrapper.Validate(newRecord); if (!string.IsNullOrEmpty(validationRsltString)) { IEnumerable <CQTextParser.RecordValidationResult> validationResults; if (CQTextParser.RecordValidationTextParser.TryParse(validationRsltString, out validationResults) && validationResults.Count() > 0) { CQTextParser.RecordValidationResult rslt = validationResults.First(); MigrationConflict conflict = ClearQuestInvalidFieldValueConflictType.CreateConflict(rslt, action); m_conflictManagerService.BacklogUnresolvedConflict(m_conflictManagerService.SourceId, conflict, false); return; } else { throw new InvalidOperationException(validationRsltString); } } } } validationRsltString = CQWrapper.Commmit(newRecord); if (!string.IsNullOrEmpty(validationRsltString)) { // [teyang] TODO: invalid update conflict handling throw new InvalidOperationException(validationRsltString); } string newRecordDisplayName = CQWrapper.GetEntityDisplayName(newRecord); if (action.State == ActionState.Pending) { action.State = ActionState.Complete; } UpdateConversionHistory(action, newRecordDisplayName, ClearQuestRecordItem.NewRecordVersion, convRslt); #endregion #region update the new record with remaining field values ModifyRecordContent(newRecord, action, convRslt, processedFields); #endregion }
public async Task Work_file_reuploading_works_correctly_and_number_of_reuploads_is_minimized() { // Arrange RemoteWorkFile wf1 = await this.UploadPlainTextAsync(Util.RestClient.CreateAffinitySession(), "File 1"); RemoteWorkFile wf2 = await this.UploadPlainTextAsync(Util.RestClient.CreateAffinitySession(), "File 2"); // Make sure we get at least one distinct affinity token int i = 2; while (wf1.AffinityToken == wf2.AffinityToken && i < 100) { wf2 = await this.UploadPlainTextAsync(Util.RestClient.CreateAffinitySession(), $"File 2"); i++; } // Try to create some files with the same affinity AffinitySession affinitySession = Util.RestClient.CreateAffinitySession(); RemoteWorkFile wf3 = await this.UploadPlainTextAsync(affinitySession, "File 3"); RemoteWorkFile wf4 = await this.UploadPlainTextAsync(affinitySession, "File 4"); RemoteWorkFile wf5 = await this.UploadPlainTextAsync(affinitySession, "File 5"); RemoteWorkFile wf6 = await this.UploadPlainTextAsync(affinitySession, "File 6"); RemoteWorkFile wf7 = await this.UploadPlainTextAsync(affinitySession, "File 7"); RemoteWorkFile wf8 = await this.UploadPlainTextAsync(affinitySession, "File 8"); RemoteWorkFile wf9 = await this.UploadPlainTextAsync(affinitySession, "File 9"); RemoteWorkFile wf10 = await this.UploadPlainTextAsync(affinitySession, "File 10"); var doc1 = new ConversionSourceDocument(wf1); var doc2 = new ConversionSourceDocument(wf2); var doc3 = new ConversionSourceDocument(wf3); var doc4 = new ConversionSourceDocument(wf4); var doc5 = new ConversionSourceDocument(wf5); var doc6 = new ConversionSourceDocument(wf6); var doc7 = new ConversionSourceDocument(wf7); var doc8 = new ConversionSourceDocument(wf8); var doc9 = new ConversionSourceDocument(wf9); var doc10 = new ConversionSourceDocument(wf10); var sourceDocuments = new[] { doc1, doc2, doc3, doc4, doc5, doc6, doc7, doc8, doc9, doc10 }; // Validate that we actually have distinct affinity IEnumerable <string> distinctAffinityTokensBefore = sourceDocuments.Select(x => x.RemoteWorkFile.AffinityToken).Distinct(); Assert.IsTrue(distinctAffinityTokensBefore.Count() > 1); string mostFrequentAffinityToken = sourceDocuments.GroupBy(x => x.RemoteWorkFile.AffinityToken).OrderByDescending(x => x.Count()).Select(x => x.Key).First(); // Act ConversionResult output = await Util.CreatePrizmDocServerClient().CombineToPdfAsync(sourceDocuments); // Assert that the ConversionSourceDocument instances all now have RemoteWorkFile instances with the same affinity token. IEnumerable <string> distinctAffinityTokensAfter = sourceDocuments.Select(x => x.RemoteWorkFile.AffinityToken).Distinct(); Assert.AreEqual(1, distinctAffinityTokensAfter.Count()); Assert.AreEqual(mostFrequentAffinityToken, distinctAffinityTokensAfter.Single()); string outputFileText = string.Join("\n", await TextUtil.ExtractPagesText(output.RemoteWorkFile)); Assert.AreEqual(@"File 1File 2File 3File 4File 5File 6File 7File 8File 9File 10", outputFileText.Replace("\r", string.Empty).Replace("\n", string.Empty)); }
private static bool WillOverwriteSource(ConversionResult convertedFile) { return(string.Equals(convertedFile.SourcePathOrNull, convertedFile.TargetPathOrNull, StringComparison.OrdinalIgnoreCase)); }
protected override ConversionResult <string> Convert(DateTime value, Type targetType, object parameter, CultureInfo culture) { var month = value.ToString("MMM", CultureInfo.CurrentCulture).ToUpper(CultureInfo.CurrentCulture); return(ConversionResult <string> .SetValue(month)); }
public virtual IConversionResult ConvertTo(decimal value, IUnitOfMeasure toUnit) { var conversionResult = new ConversionResult(Type, this, toUnit, value, 0); return(conversionResult); }
private ConflictResolutionResult ResolveBySubmitMissingChanges( IServiceContainer serviceContainer, MigrationConflict conflict, ConflictResolutionRule rule, out List <MigrationAction> actions) { actions = null; var retVal = new ConflictResolutionResult(false, ConflictResolutionType.Other); WITTranslationService translationService = serviceContainer.GetService(typeof(ITranslationService)) as WITTranslationService; Debug.Assert(null != translationService, "translationService is not initialized or not a wit translation service"); using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance()) { RTSessionGroup rtSessionGroup = FindSessionGroupForConflictedAction(conflict, context); if (null == rtSessionGroup) { return(retVal); } BM.BusinessModelManager bmm = new BM.BusinessModelManager(); BM.Configuration sessionGroupConfig = bmm.LoadConfiguration(rtSessionGroup.GroupUniqueId); // find target-side migration source config var parentChangeGroup = FindChangeGroupForConflictedAction(conflict, context); Guid targetMigrationSourceId = parentChangeGroup.SourceUniqueId; BM.MigrationSource targetMigrationSourceConfig = sessionGroupConfig.SessionGroup.MigrationSources[targetMigrationSourceId]; if (null == targetMigrationSourceConfig) { return(retVal); } // find source-side migration source config RTSession rtSession = FindSessionForConflictedAction(conflict, context); BM.Session parentSession = null; foreach (BM.Session s in sessionGroupConfig.SessionGroup.Sessions.Session) { if (new Guid(s.SessionUniqueId).Equals(rtSession.SessionUniqueId)) { parentSession = s; break; } } if (parentSession == null) { return(retVal); } Guid sourceMigrationSourceId = ((new Guid(parentSession.LeftMigrationSourceUniqueId)).Equals(targetMigrationSourceId)) ? new Guid(parentSession.RightMigrationSourceUniqueId) : new Guid(parentSession.LeftMigrationSourceUniqueId); BM.MigrationSource sourceMigrationSourceConfig = sessionGroupConfig.SessionGroup.MigrationSources[sourceMigrationSourceId]; if (null == sourceMigrationSourceConfig) { return(retVal); } string sourceServerUrl = sourceMigrationSourceConfig.ServerUrl; string sourceTeamProject = sourceMigrationSourceConfig.SourceIdentifier; string targetServerUrl = targetMigrationSourceConfig.ServerUrl; string targetTeamProject = targetMigrationSourceConfig.SourceIdentifier; string srcWorkItemIdStr = TfsMigrationWorkItemStore.GetSourceWorkItemId(conflict.ConflictedChangeAction); Debug.Assert(!string.IsNullOrEmpty(srcWorkItemIdStr), "srcWorkItemId is null or empty"); int srcWorkItemId; if (!int.TryParse(srcWorkItemIdStr, out srcWorkItemId)) { return(retVal); } string srcRevRanges = rule.DataFieldDictionary[HistoryNotFoundSubmitMissingChangesAction.DATAKEY_REVISION_RANGE]; int[] sourceRevToSync = new int[0]; if (string.IsNullOrEmpty(srcRevRanges)) { sourceRevToSync = ExtractMissingRevs(conflict.ConflictedChangeAction); } else { if (!IntegerRange.TryParseRangeString(srcRevRanges, out sourceRevToSync)) { return(retVal); } } if (sourceRevToSync.Length == 0) { return(retVal); } try { // compute delta from source side TfsWITAnalysisProvider analysisProvider = new TfsWITAnalysisProvider(sourceServerUrl, sourceTeamProject); WorkItem sourceWorkItem = analysisProvider.GetWorkItem(srcWorkItemId); Hist.MigrationAction[] sourceRevDetails = new Hist.MigrationAction[sourceRevToSync.Length]; for (int revIndex = 0; revIndex < sourceRevToSync.Length; ++revIndex) { var details = new TfsWITRecordDetails(sourceWorkItem, sourceRevToSync[revIndex]); SanitizeDetails(details); translationService.MapWorkItemTypeFieldValues( sourceWorkItem.Id.ToString(), details.DetailsDocument, sourceMigrationSourceId); TfsConstants.ChangeActionId actionId = (sourceRevToSync[revIndex] == 1 ? TfsConstants.ChangeActionId.Add : TfsConstants.ChangeActionId.Edit); sourceRevDetails[revIndex] = new Hist.MigrationAction(sourceWorkItem.Id.ToString(), details, actionId); } // migrate to target side TfsWITMigrationProvider migrationProvider = new TfsWITMigrationProvider(targetServerUrl, targetTeamProject, string.Empty); Hist.ConversionResult conversionResult = migrationProvider.ProcessChangeGroup(sourceRevDetails); // update conversion history ConversionResult convRslt = new ConversionResult(sourceMigrationSourceId, targetMigrationSourceId); convRslt.ChangeId = HistoryNotFoundResolutionChangeId; convRslt.ContinueProcessing = true; foreach (var itemConvHist in conversionResult.ItemConversionHistory) { convRslt.ItemConversionHistory.Add(new ItemConversionHistory( itemConvHist.SourceItemId, itemConvHist.SourceItemVersion, itemConvHist.TargetItemId, itemConvHist.TargetItemVersion)); } parentChangeGroup.SessionRunReference.Load(); int sessionRunId = parentChangeGroup.SessionRun.Id; convRslt.Save(sessionRunId, sourceMigrationSourceId); } catch (Exception ex) { TraceManager.TraceException(ex); retVal.Comment = ex.ToString(); return(retVal); } } retVal.Resolved = true; return(retVal); }
public ConversionResult ProcessChangeGroup(ChangeGroup changeGroup) { try { Guid targetSideSourceId = m_configurationService.SourceId; Guid sourceSideSourceId = m_configurationService.MigrationPeer; ConversionResult changeResult = new ConversionResult(sourceSideSourceId, targetSideSourceId); changeResult.ChangeId = string.Empty; if (TryProcessContextSyncChangeGroup(changeGroup)) { // by leaving the ChangeId as empty string, we instruct the platform // migration engine not to update the conversion history for this change group return(changeResult); } m_migrationSource.WorkItemStore.SubmitChanges(changeGroup, changeResult, sourceSideSourceId); if (!string.IsNullOrEmpty(changeResult.ChangeId)) { TraceManager.TraceInformation(string.Format( "Completed migration, result change: {0}", changeResult.ChangeId)); /* Enable for verbose logging of attachment changes ... * if (changeGroup.Actions.Count > 0 && * (changeGroup.Actions[0].Action == WellKnownChangeActionId.AddAttachment || * changeGroup.Actions[0].Action == WellKnownChangeActionId.DelAttachment)) * { * string [] nameParts = changeGroup.Name.Split(new char[] { ':' }); * if (!string.IsNullOrEmpty(nameParts[0])) * { * foreach (IMigrationAction action in changeGroup.Actions) * { * * if (action.Action == WellKnownChangeActionId.AddAttachment) * { * TraceManager.TraceVerbose(String.Format("Added attachment from work item {0} to '{1}'", * nameParts[0], action.SourceItem.DisplayName)); * } * else if (action.Action == WellKnownChangeActionId.DelAttachment) * { * TraceManager.TraceVerbose(String.Format("Deleted attachment from work item {0} to '{1}'", * nameParts[0], action.SourceItem.DisplayName)); * } * } * } * } */ } return(changeResult); } catch (Exception exception) { if (!(exception is MigrationUnresolvedConflictException)) { ErrorManager errMgr = m_migrationServiceContainer.GetService(typeof(ErrorManager)) as ErrorManager; errMgr.TryHandleException(exception); } // by setting "ContinueProcessing" to true, we instruct the platform migration engine to continue // processing the following change groups (migration instructions) var convRslt = new ConversionResult(m_configurationService.MigrationPeer, m_configurationService.SourceId); convRslt.ContinueProcessing = true; return(convRslt); } }
/// <summary> /// Returns an <Typ>XPathNavigator</Typ> that points to the <manifest> node of the package manifest. /// </summary> /// <exception cref="InvalidPackageException">The imsmanifest.xml file is missing from the package, or the /// <manifest> is missing from the imsmanifest.xml file.</exception> internal void CreateManifestNavigator(ValidationBehavior lrmValidation, bool fixLrmViolations, out ValidationResults log, out XPathNavigator manifest) { Stream stream; log = null; manifest = null; // Get Index.xml -- see if it's Class Server package. This is an optimization since the imsmanifest.xml // stream can be gotten directly. if (FileExists("Index.xml")) { using (stream = GetFileStream("Index.xml")) { // Allow this conversion to occur again if this method is called, but cache // the result for use by the GetFileStream("imsmanifest.xml") method. m_result = ManifestConverter.ConvertFromIndexXml(stream, GetFilePaths(), fixLrmViolations, lrmValidation); } log = m_result.Log; manifest = m_result.Manifest; } else { // If it was not a Class Server package, then see if it's a SCORM package try { stream = GetFileStream("imsmanifest.xml"); } catch (FileNotFoundException) { throw new InvalidPackageException(Resources.ImsManifestXmlMissing); } catch (DirectoryNotFoundException) { throw new InvalidPackageException(Resources.ImsManifestXmlMissing); } using (stream) { try { XPathDocument doc = new XPathDocument(stream); XPathNavigator nav = doc.CreateNavigator(); // move to the first manifest node. First try SCORM 2004 XPathExpression expr = Helper.CreateExpressionV1p3(nav, Helper.Strings.Imscp + ":" + Helper.Strings.Manifest); manifest = nav.SelectSingleNode(expr); if (manifest == null) { // Didn't find a SCORM 2004 manifest node. Try SCORM 1.2. expr = Helper.CreateExpressionV1p2(nav, Helper.Strings.Imscp + ":" + Helper.Strings.Manifest); manifest = nav.SelectSingleNode(expr); if (manifest == null) { throw new InvalidPackageException(String.Format(CultureInfo.CurrentCulture, ValidatorResources.RequiredElementMissing, Helper.Strings.Manifest, ValidatorResources.ManifestNodeMissing)); } } } catch (XmlException e) { throw new InvalidPackageException(ValidatorResources.BadXmlInManifest, e); } } } }
public void ConversionResultConstructorDoubleZeroTest() { ConversionResult res = new ConversionResult ((double)0); Assert.IsNotNull (res); Assert.AreEqual (0, res.Value); Assert.AreEqual (Result.NoError, res.Result); Assert.AreEqual (null, res.Symbol); }