/// <inheritdoc /> public virtual async Task <OperationContainer> ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { ArgumentGuard.NotNull(operation, nameof(operation)); var primaryId = (TId)operation.Resource.GetTypedId(); ISet <IIdentifiable> secondaryResourceIds = operation.GetSecondaryResources(); await _service.AddToToManyRelationshipAsync(primaryId, operation.Request.Relationship.PublicName, secondaryResourceIds, cancellationToken); return(null); }
protected override void DoFileInteraction(FileInfo fi) { if (!fi.Exists) { return; } OperationContainer container = new OperationContainer(Pawn); container.Load(fi); base.Close(); }
/// <summary> /// Computes a <see cref="OperationContainer"/> that contains update operations on value-sets /// </summary> /// <param name="context"> /// The route of the <see cref="CDP4Common.DTO.SiteDirectory"/> or <see cref="Iteration"/> for which the current <see cref="OperationContainer"/> is valid. /// </param> /// <param name="dtos">The returned <see cref="Dto.Thing"/>s</param> /// <param name="copyThingMap">The copy map containing the original <see cref="Thing"/> associated to their copy</param> /// <returns>The <see cref="OperationContainer"/></returns> public OperationContainer CreateValueSetsUpdateOperations(string context, IEnumerable <Dto.Thing> dtos, IReadOnlyDictionary <Thing, Thing> copyThingMap) { var dtolist = dtos.ToList(); var topContainer = dtolist.SingleOrDefault(x => x is Dto.TopContainer); if (topContainer == null) { throw new InvalidOperationException("No Top container were found in the returned list of dtos."); } // Gets the parameter base which value set shall be updated var copyParameterBases = dtolist.OfType <Dto.ParameterBase>().ToList(); var copyParameterBasesIds = copyParameterBases.Select(p => p.Iid).ToList(); var valuesets = dtolist.Where(dto => dto.ClassKind == ClassKind.ParameterValueSet || dto.ClassKind == ClassKind.ParameterSubscriptionValueSet || dto.ClassKind == ClassKind.ParameterOverrideValueSet).ToList(); this.ComputeRoutes(valuesets, dtolist); var valueSetsClones = valuesets.Select(dto => dto.DeepClone <Dto.Thing>()).ToList(); // The original of the copy are normally in the map var originalParameterBases = copyThingMap.Where(x => copyParameterBasesIds.Contains(x.Value.Iid)).ToList(); // set the values foreach (var copyPair in originalParameterBases) { var copyId = copyPair.Value.Iid; var originalParameter = (ParameterBase)copyPair.Key; var copyDto = copyParameterBases.Single(x => x.Iid == copyId); // value sets to update var copyValueSets = valueSetsClones.Where(x => copyDto.ValueSets.Contains(x.Iid)).ToList(); var defaultValueSet = this.GetDefaultValueSet(originalParameter); if (defaultValueSet == null) { continue; } this.SetValueSetValues(copyValueSets, defaultValueSet); } var operationContainer = new OperationContainer(context, topContainer.RevisionNumber); foreach (var valueSetsClone in valueSetsClones) { var valuesetToUpdate = valuesets.Single(x => x.Iid == valueSetsClone.Iid); var operation = new Operation(valuesetToUpdate, valueSetsClone, OperationKind.Update); operationContainer.AddOperation(operation); } return(operationContainer); }
private object GetRelationshipRightValue(OperationContainer operation) { RelationshipAttribute relationship = operation.Request.Relationship; object rightValue = relationship.GetValue(operation.Resource); if (relationship is HasManyAttribute) { ICollection <IIdentifiable> rightResources = _collectionConverter.ExtractResources(rightValue); return(rightResources.ToHashSet(IdentifiableComparer.Instance)); } return(rightValue); }
/// <inheritdoc /> public virtual async Task <OperationContainer> ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { if (operation == null) { throw new ArgumentNullException(nameof(operation)); } var resource = (TResource)operation.Resource; var updated = await _service.UpdateAsync(resource.Id, resource, cancellationToken); return(updated == null ? null : operation.WithResource(updated)); }
protected virtual async Task <OperationContainer> ProcessOperationAsync(OperationContainer operation, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); TrackLocalIdsForOperation(operation); _targetedFields.Attributes = operation.TargetedFields.Attributes; _targetedFields.Relationships = operation.TargetedFields.Relationships; _request.CopyFrom(operation.Request); return(await _operationProcessorAccessor.ProcessAsync(operation, cancellationToken)); }
private static object GetRelationshipRightValue(OperationContainer operation) { var relationship = operation.Request.Relationship; var rightValue = relationship.GetValue(operation.Resource); if (relationship is HasManyAttribute) { var rightResources = TypeHelper.ExtractResources(rightValue); return(rightResources.ToHashSet(IdentifiableComparer.Instance)); } return(rightValue); }
/// <inheritdoc /> public virtual async Task <OperationContainer> ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { if (operation == null) { throw new ArgumentNullException(nameof(operation)); } var id = (TId)operation.Resource.GetTypedId(); await _service.DeleteAsync(id, cancellationToken); return(null); }
/// <inheritdoc /> public virtual async Task <OperationContainer> ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { ArgumentGuard.NotNull(operation, nameof(operation)); var primaryId = (TId)operation.Resource.GetTypedId(); object rightValue = GetRelationshipRightValue(operation); await _service.SetRelationshipAsync(primaryId, operation.Request.Relationship.PublicName, rightValue, cancellationToken); return(null); }
public void VerifyThatDryCopyDoesNotCopySubscriptionWithInactiveDomain() { this.permissionService.Setup(x => x.CanWrite(It.IsAny <ClassKind>(), It.IsAny <Thing>())).Returns(true); this.session.Setup(x => x.OpenIterations).Returns( new Dictionary <Iteration, Tuple <DomainOfExpertise, Participant> > { { this.iteration1, new Tuple <DomainOfExpertise, Participant>(domain1, null) }, { this.iteration2, new Tuple <DomainOfExpertise, Participant>(domain1, null) } }); this.subscription1.Owner = this.domain3; var iteration2Clone = this.iteration2.Clone(false); var defClone = this.rootDef.Clone(false); defClone.Iid = Guid.NewGuid(); iteration2Clone.Element.Add(defClone); var transactionContext = TransactionContextResolver.ResolveContext(this.iteration2); var context = transactionContext.ContextRoute(); var operationContainer = new OperationContainer(context, this.model2.RevisionNumber); operationContainer.AddOperation(new Operation(this.iteration2.ToDto(), iteration2Clone.ToDto(), OperationKind.Update)); operationContainer.AddOperation(new Operation(this.rootDef.ToDto(), defClone.ToDto(), OperationKind.CopyDefaultValuesChangeOwner)); var copyHandler = new CopyOperationHandler(this.session.Object); copyHandler.ModifiedCopyOperation(operationContainer); var operations = operationContainer.Operations.ToList(); Assert.AreEqual(13, operations.Count); Assert.IsNotEmpty(operationContainer.Context); // check that operation container is correctly built var ownedThings = operationContainer.Operations.Select(x => x.ModifiedThing) .Where(x => x.ClassKind != ClassKind.ParameterSubscription) .OfType <Dto.IOwnedThing>() .ToList(); var dtoOwner = ownedThings.Select(x => x.Owner).Distinct().Single(); Assert.AreEqual(dtoOwner, this.domain1.Iid); var subCount = operationContainer.Operations.Select(x => x.ModifiedThing) .OfType <Dto.ParameterSubscription>().Count(); Assert.AreEqual(0, subCount); }
protected void TrackLocalIdsForOperation(OperationContainer operation) { if (operation.Kind == OperationKind.CreateResource) { DeclareLocalId(operation.Resource); } else { AssignStringId(operation.Resource); } foreach (var secondaryResource in operation.GetSecondaryResources()) { AssignStringId(secondaryResource); } }
/// <inheritdoc /> public virtual async Task <OperationContainer> ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { ArgumentGuard.NotNull(operation, nameof(operation)); TResource newResource = await _service.CreateAsync((TResource)operation.Resource, cancellationToken); if (operation.Resource.LocalId != null) { string serverId = newResource != null ? newResource.StringId : operation.Resource.StringId; ResourceContext resourceContext = _resourceContextProvider.GetResourceContext <TResource>(); _localIdTracker.Assign(operation.Resource.LocalId, resourceContext.PublicName, serverId); } return(newResource == null ? null : operation.WithResource(newResource)); }
/// <inheritdoc /> public virtual async Task <OperationContainer> ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { if (operation == null) { throw new ArgumentNullException(nameof(operation)); } var primaryId = (TId)operation.Resource.GetTypedId(); var secondaryResourceIds = operation.GetSecondaryResources(); await _service.AddToToManyRelationshipAsync(primaryId, operation.Request.Relationship.PublicName, secondaryResourceIds, cancellationToken); return(null); }
public void VerifyExecutionOfOperationAddAndRemove() { var elementDefinition = new ElementDefinition(Guid.NewGuid(), 0); elementDefinition.PartialRoutes.Add("iteration/b58ea73d-350d-4520-b9d9-a52c75ac2b5d"); elementDefinition.PartialRoutes.Add("EngineeringModel/5e5dc7f8-833d-4331-b421-eb2c64fcf64b"); var clone = elementDefinition.DeepClone <ElementDefinition>(); var operation = new Operation(elementDefinition, clone, OperationKind.Update); var operationContainer = new OperationContainer(this.iterationContext); operationContainer.AddOperation(operation); Assert.AreEqual(1, operationContainer.Operations.Count()); operationContainer.RemoveOperation(operation); Assert.AreEqual(0, operationContainer.Operations.Count()); }
/// <summary> /// Executes the Ok Command /// </summary> private async void ExecuteOk() { this.IsBusy = true; this.LoadingMessage = "Exporting..."; try { var creds = new Credentials(this.selectedSession.Credentials.UserName, this.Password, new Uri(this.Path)); // TODO: change this to allow (file) dal selection for export var dal = this.dals.Single(x => x.Metadata.DalType == DalType.File); var dalInstance = (IDal)Activator.CreateInstance(dal.Value.GetType()); var fileExportSession = new Session(dalInstance, creds); // create write var operationContainers = new List <OperationContainer>(); // TODO: allow iteration setup selection by user var openIterations = this.selectedSession.OpenIterations.Select(x => x.Key); foreach (var iteration in openIterations) { var transactionContext = TransactionContextResolver.ResolveContext(iteration); var operationContainer = new OperationContainer(transactionContext.ContextRoute()); var dto = iteration.ToDto(); var operation = new Operation(null, dto, OperationKind.Create); operationContainer.AddOperation(operation); operationContainers.Add(operationContainer); } var result = await dalInstance.Write(operationContainers); this.DialogResult = new BaseDialogResult(true); } catch (Exception ex) { this.ErrorMessage = ex.Message; } finally { this.IsBusy = false; } }
public void VerifyThatWritingMultipleOperationContainersIsNotSupported() { var dal = new WspDal(); this.SetDalToBeOpen(dal); var contextOne = $"/EngineeringModel/{Guid.NewGuid()}/iteration/{Guid.NewGuid()}"; var contextTwo = $"/EngineeringModel/{Guid.NewGuid()}/iteration/{Guid.NewGuid()}"; var operationContainerOne = new OperationContainer(contextOne); var operationContainerTwo = new OperationContainer(contextTwo); var operationContainers = new List <OperationContainer> { operationContainerOne, operationContainerTwo }; Assert.Throws <NotSupportedException>(() => dal.Write(operationContainers)); Assert.Throws <NotSupportedException>(() => dal.Write(operationContainers)); }
private void ValidateOperation(OperationContainer operation) { if (operation.Kind == OperationKind.CreateResource) { DeclareLocalId(operation.Resource); } else { AssertLocalIdIsAssigned(operation.Resource); } foreach (var secondaryResource in operation.GetSecondaryResources()) { AssertLocalIdIsAssigned(secondaryResource); } if (operation.Kind == OperationKind.CreateResource) { AssignLocalId(operation); } }
/// <summary> /// Modify the <see cref="OperationContainer"/> to compensate for operations /// that should be performed by the data-source but is not by the WSP. /// </summary> /// <param name="operationContainer">The <see cref="OperationContainer"/> to modify</param> public void ModifyOperationContainer(OperationContainer operationContainer) { var operationsToAdd = new List <Operation>(); foreach (var operation in operationContainer.Operations) { if (operation.OperationKind == OperationKind.Update) { var possibleStateList = operation.ModifiedThing as PossibleFiniteStateList; if (possibleStateList != null) { operationsToAdd.AddRange(this.ModifyActualStateKindOnDefaultPossibleStateUpdate(possibleStateList)); } } } foreach (var operation in operationsToAdd) { operationContainer.AddOperation(operation); } }
public void VerifyThatModifyShiftCopyOperationsWorks() { this.permissionService.Setup(x => x.CanWrite(It.IsAny <ClassKind>(), It.IsAny <Thing>())).Returns(true); this.session.Setup(x => x.OpenIterations).Returns( new Dictionary <Iteration, Tuple <DomainOfExpertise, Participant> > { { this.iteration1, new Tuple <DomainOfExpertise, Participant>(domain1, null) }, { this.iteration2, new Tuple <DomainOfExpertise, Participant>(domain2, null) } }); var iteration2Clone = this.iteration2.Clone(false); var defClone = this.rootDef.Clone(false); defClone.Iid = Guid.NewGuid(); iteration2Clone.Element.Add(defClone); var transactionContext = TransactionContextResolver.ResolveContext(this.iteration2); var context = transactionContext.ContextRoute(); var operationContainer = new OperationContainer(context, this.model2.RevisionNumber); operationContainer.AddOperation(new Operation(this.iteration2.ToDto(), iteration2Clone.ToDto(), OperationKind.Update)); operationContainer.AddOperation(new Operation(this.rootDef.ToDto(), defClone.ToDto(), OperationKind.Copy)); var copyHandler = new CopyOperationHandler(this.session.Object); copyHandler.ModifiedCopyOperation(operationContainer); var operations = operationContainer.Operations.ToList(); Assert.IsNotEmpty(operationContainer.Context); Assert.AreEqual(14, operations.Count); var operation = operations.Single(x => x.OperationKind == OperationKind.Update); var iteration = (CDP4Common.DTO.Iteration)operation.ModifiedThing; Assert.AreEqual(3, iteration.Element.Count); }
/// <summary> /// Creates <see cref="HttpContent"/> that is added to a POST request /// </summary> /// <param name="token"> /// The POST token that is used to track the POST request in a logger /// </param> /// <param name="operationContainer"> /// The <see cref="OperationContainer"/> that contains the <see cref="Operation"/>s that are part of /// the transaction that is sent to the DAL /// </param> /// <param name="files"> /// A list of file-paths that is used to construct the <see cref="MultipartFormDataContent"/> /// </param> /// <returns> /// An instance of <see cref="StringContent"/> or <see cref="MultipartFormDataContent"/> /// </returns> private HttpContent CreateHttpContent(string token, OperationContainer operationContainer, IEnumerable <string> files = null) { var stream = new MemoryStream(); this.ConstructPostRequestBodyStream(token, operationContainer, stream); var jsonContent = new StreamContent(stream); jsonContent.Headers.Add(Headers.ContentType, "application/json"); jsonContent.Headers.Add(Headers.CDPToken, token); if (files == null) { return(jsonContent); } else { var multipartContent = new MultipartFormDataContent(); multipartContent.Add(jsonContent); foreach (var file in files) { var fileName = Path.GetFileName(file); using (var filestream = System.IO.File.OpenRead(file)) { var contentStream = new MemoryStream(); filestream.CopyTo(contentStream); contentStream.Position = 0; var fileContent = new StreamContent(contentStream); fileContent.Headers.Add("Content-Type", "application/octet-stream"); fileContent.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\""); multipartContent.Add(fileContent); } } return(multipartContent); } }
/// <summary> /// Modify the <see cref="OperationContainer"/> if it contains copy <see cref="Operation"/> /// </summary> /// <param name="operationContainer">The <see cref="OperationContainer"/> to modify</param> public void ModifiedCopyOperation(OperationContainer operationContainer) { var operationsToAdd = new List <Operation>(); var copyOperationCount = operationContainer.Operations.Count(x => x.OperationKind.IsCopyOperation()); if (copyOperationCount > 1) { // TODO: support this if needed throw new NotSupportedException("Only one copy operation per transaction is supported."); } var copyOperation = operationContainer.Operations.SingleOrDefault(x => x.OperationKind.IsCopyOperation()); if (copyOperation == null) { return; } this.ComputeOperations(copyOperation); operationsToAdd.AddRange(this.operations); foreach (var operation in operationsToAdd) { operationContainer.AddOperation(operation); } // remove the copy operations operationContainer.RemoveOperation(copyOperation); // update the update iteration operation var iterationOperation = operationContainer.Operations.Single(x => x.OperationKind == OperationKind.Update); var updatedIteration = iterationOperation.ModifiedThing.QuerySourceThing(); var originalIteration = iterationOperation.OriginalThing.QuerySourceThing(); operationContainer.RemoveOperation(iterationOperation); operationContainer.AddOperation(new Operation(originalIteration.ToDto(), updatedIteration.ToDto(), OperationKind.Update)); }
public void ShowDialog(OperationContainer parent) { if (parent == null) { return; } this.parent = parent; this.Text = parent.Name; Changed = false; FillCollections(parent.Language); FillMembersList(); if (lstMembers.Items.Count > 0) { lstMembers.Items[0].Focused = true; lstMembers.Items[0].Selected = true; } toolNewField.Visible = (parent is IFieldAllower); if (parent.Language == Language.CSharp) { accessOrder = csharpAccessOrder; modifierOrder = csharpModifierOrder; } else { accessOrder = javaAccessOrder; modifierOrder = javaModifierOrder; } errorProvider.SetError(txtSyntax, null); errorProvider.SetError(txtName, null); errorProvider.SetError(cboType, null); base.ShowDialog(); }
public async Task Verify_that_person_can_be_Posted() { var uri = new Uri("http://ocdt-dev.rheagroup.com"); var credentials = new Credentials("admin", "pass", uri); var wspdal = new WspDal(); var dtos = await wspdal.Open(credentials, this.cancelationTokenSource.Token); var siteDirectory = (CDP4Common.DTO.SiteDirectory)dtos.Single(x => x.ClassKind == ClassKind.SiteDirectory); var context = siteDirectory.Route; var operationContainer = new OperationContainer(context, siteDirectory.RevisionNumber); var person = new CDP4Common.DTO.Person(Guid.NewGuid(), 1); person.ShortName = Guid.NewGuid().ToString(); person.Surname = Guid.NewGuid().ToString(); person.GivenName = Guid.NewGuid().ToString(); person.AddContainer(ClassKind.SiteDirectory, Guid.Parse("eb77f3e1-a0f3-412d-8ed6-b8ce881c0145")); var operation1 = new Operation(null, person, OperationKind.Create); operationContainer.AddOperation(operation1); var siteDirectoryClone = siteDirectory.DeepClone <CDP4Common.DTO.SiteDirectory>(); siteDirectoryClone.Person.Add(person.Iid); var operation2 = new Operation(siteDirectory, siteDirectoryClone, OperationKind.Update); operationContainer.AddOperation(operation2); var result = await wspdal.Write(operationContainer); var resultPerson = (CDP4Common.DTO.Person)result.Single(x => x.Iid == person.Iid); Assert.NotNull(resultPerson); }
/// <summary> /// Write all the <see cref="Operation"/>s from an <see cref="OperationContainer"/> asynchronously. /// </summary> /// <param name="operationContainer"> /// The provided <see cref="OperationContainer"/> to write /// </param> /// <param name="files">List of file paths for files to be sent to the datastore</param> /// <returns> /// an await-able <see cref="Task"/> /// </returns> public async Task Write(OperationContainer operationContainer, IEnumerable <string> files) { if (this.ActivePerson == null) { throw new InvalidOperationException("The Write operation cannot be performed when the ActivePerson is null; The Open method must be called prior to performing a Write."); } var filesList = files?.ToList(); if (filesList != null && filesList.Any()) { foreach (var file in filesList) { if (!System.IO.File.Exists(file)) { throw new FileNotFoundException($"File {file} was not found."); } } } var eventArgs = new BeforeWriteEventArgs(operationContainer, filesList); this.BeforeWrite?.Invoke(this, eventArgs); if (eventArgs.Cancelled) { throw new OperationCanceledException("The Write operation was canceled."); } this.Dal.Session = this; var dtoThings = await this.Dal.Write(operationContainer, filesList); var enumerable = dtoThings as IList <CDP4Common.DTO.Thing> ?? dtoThings.ToList(); await this.AfterReadOrWriteOrUpdate(enumerable); }
public async Task VerifyThatFileCanBeUploaded() { this.dal = new WspDal { Session = this.session }; var filename = @"TestData\testfile.pdf"; var directory = TestContext.CurrentContext.TestDirectory; var filepath = Path.Combine(directory, filename); var files = new List <string> { filepath }; var contentHash = "F73747371CFD9473C19A0A7F99BCAB008474C4CA"; var uri = new Uri("https://cdp4services-test.cdp4.org"); this.credentials = new Credentials("admin", "pass", uri); var returned = await this.dal.Open(this.credentials, this.cancelationTokenSource.Token); var engineeringModeliid = Guid.Parse("9ec982e4-ef72-4953-aa85-b158a95d8d56"); var iterationiid = Guid.Parse("e163c5ad-f32b-4387-b805-f4b34600bc2c"); var domainFileStoreIid = Guid.Parse("da7dddaa-02aa-4897-9935-e8d66c811a96"); var fileIid = Guid.NewGuid(); var fileRevisionIid = Guid.NewGuid(); var domainOfExpertiseIid = Guid.Parse("0e92edde-fdff-41db-9b1d-f2e484f12535"); var fileTypeIid = Guid.Parse("b16894e4-acb5-4e81-a118-16c00eb86d8f"); //PDF var participantIid = Guid.Parse("284334dd-e8e5-42d6-bc8a-715c507a7f02"); var originalDomainFileStore = new CDP4Common.DTO.DomainFileStore(domainFileStoreIid, 0); originalDomainFileStore.AddContainer(ClassKind.Iteration, iterationiid); originalDomainFileStore.AddContainer(ClassKind.EngineeringModel, engineeringModeliid); var modifiedDomainFileStore = new CDP4Common.DTO.DomainFileStore(domainFileStoreIid, 0); modifiedDomainFileStore.File.Add(fileIid); modifiedDomainFileStore.AddContainer(ClassKind.Iteration, iterationiid); modifiedDomainFileStore.AddContainer(ClassKind.EngineeringModel, engineeringModeliid); var file = new CDP4Common.DTO.File(fileIid, 0) { Owner = domainOfExpertiseIid }; file.FileRevision.Add(fileRevisionIid); file.AddContainer(ClassKind.DomainFileStore, domainFileStoreIid); file.AddContainer(ClassKind.Iteration, iterationiid); file.AddContainer(ClassKind.EngineeringModel, engineeringModeliid); var fileRevision = new CDP4Common.DTO.FileRevision(fileRevisionIid, 0); fileRevision.Name = "testfile"; fileRevision.ContentHash = contentHash; fileRevision.FileType.Add(new OrderedItem() { K = 1, V = fileTypeIid }); fileRevision.Creator = participantIid; fileRevision.AddContainer(ClassKind.File, fileIid); fileRevision.AddContainer(ClassKind.DomainFileStore, domainFileStoreIid); fileRevision.AddContainer(ClassKind.Iteration, iterationiid); fileRevision.AddContainer(ClassKind.EngineeringModel, engineeringModeliid); var context = $"/EngineeringModel/{engineeringModeliid}/iteration/{iterationiid}"; var operationContainer = new OperationContainer(context); var updateCommonFileStoreOperation = new Operation(originalDomainFileStore, modifiedDomainFileStore, OperationKind.Update); operationContainer.AddOperation(updateCommonFileStoreOperation); var createFileOperation = new Operation(null, file, OperationKind.Create); operationContainer.AddOperation(createFileOperation); var createFileRevisionOperation = new Operation(null, fileRevision, OperationKind.Create); operationContainer.AddOperation(createFileRevisionOperation); Assert.DoesNotThrowAsync(async() => await dal.Write(operationContainer, files)); }
public void VerifyThatWSPPostBodyIsCorrectlyResolves() { var siteDirecortoryIid = Guid.Parse("f289023d-41e8-4aaf-aae5-1be1ecf24bac"); var domainOfExpertiseIid = Guid.NewGuid(); var context = "/SiteDirectory/f289023d-41e8-4aaf-aae5-1be1ecf24bac"; var operationContainer = new OperationContainer(context); var testDtoOriginal = new CDP4Common.DTO.Alias(iid: Guid.NewGuid(), rev: 1) { Content = "content", IsSynonym = false, LanguageCode = "en", }; testDtoOriginal.AddContainer(ClassKind.DomainOfExpertise, domainOfExpertiseIid); testDtoOriginal.AddContainer(ClassKind.SiteDirectory, siteDirecortoryIid); var testDtoModified = new CDP4Common.DTO.Alias(iid: testDtoOriginal.Iid, rev: 1) { Content = "content2", IsSynonym = true, LanguageCode = "en", }; testDtoModified.AddContainer(ClassKind.DomainOfExpertise, domainOfExpertiseIid); testDtoModified.AddContainer(ClassKind.SiteDirectory, siteDirecortoryIid); var testDtoOriginal2 = new CDP4Common.DTO.Definition(iid: Guid.NewGuid(), rev: 1) { Content = "somecontent", LanguageCode = "en", }; testDtoOriginal2.AddContainer(ClassKind.DomainOfExpertise, domainOfExpertiseIid); testDtoOriginal2.AddContainer(ClassKind.SiteDirectory, siteDirecortoryIid); var testDtoModified2 = new CDP4Common.DTO.Definition(iid: testDtoOriginal2.Iid, rev: 1) { Content = "somecontent2", LanguageCode = "en", }; testDtoModified2.AddContainer(ClassKind.DomainOfExpertise, domainOfExpertiseIid); testDtoModified2.AddContainer(ClassKind.SiteDirectory, siteDirecortoryIid); testDtoModified2.Citation.Add(Guid.NewGuid()); testDtoModified2.Citation.Add(Guid.NewGuid()); testDtoModified2.Citation.Add(Guid.NewGuid()); testDtoModified2.Citation.Add(Guid.NewGuid()); testDtoOriginal2.Citation.Add(testDtoModified2.Citation[0]); testDtoOriginal2.Citation.Add(testDtoModified2.Citation[1]); testDtoOriginal2.Citation.Add(testDtoModified2.Citation[2]); testDtoModified2.Citation.Remove(testDtoModified2.Citation[1]); testDtoOriginal2.Note.Add(new OrderedItem() { K = 1234, V = Guid.NewGuid() }); testDtoOriginal2.Note.Add(new OrderedItem() { K = 2345, V = Guid.NewGuid() }); testDtoModified2.Note.Add(new OrderedItem() { K = 234, V = Guid.NewGuid() }); testDtoModified2.Note.Add(new OrderedItem() { K = 2346, V = testDtoOriginal2.Note[1].V }); // make a few operations var operation1 = new Operation(null, testDtoModified, OperationKind.Create); var operation2 = new Operation(null, testDtoModified, OperationKind.Delete); var operation3 = new Operation(testDtoOriginal, testDtoModified, OperationKind.Update); var operation4 = new Operation(testDtoOriginal2, testDtoModified2, OperationKind.Update); operationContainer.AddOperation(operation1); operationContainer.AddOperation(operation2); operationContainer.AddOperation(operation3); operationContainer.AddOperation(operation4); var stream = new MemoryStream(); this.dal.ConstructPostRequestBodyStream(string.Empty, operationContainer, stream); Assert.AreNotEqual(0, stream.Length); }
/// <summary> /// Write all the <see cref="Operation"/>s from an <see cref="OperationContainer"/> asynchronously. /// </summary> /// <param name="operationContainer"> /// The provided <see cref="OperationContainer"/> to write /// </param> /// <returns> /// A list of <see cref="Thing"/>s that has been created or updated since the last Read or Write operation. /// </returns> public override async Task <IEnumerable <Thing> > Write(OperationContainer operationContainer, IEnumerable <string> files = null) { if (this.Credentials == null || this.Credentials.Uri == null) { throw new InvalidOperationException("The CDP4 DAL is not open."); } if (operationContainer == null) { throw new ArgumentNullException(nameof(operationContainer), $"The {nameof(operationContainer)} may not be null"); } if (operationContainer.Operations.Count() == 0) { Logger.Debug("The operationContainer is empty, no round trip to the datasource is made"); return(Enumerable.Empty <Thing>()); } var watch = Stopwatch.StartNew(); var result = new List <Thing>(); if (files != null && files.Any()) { this.OperationContainerFileVerification(operationContainer, files); } var attribute = new QueryAttributes { RevisionNumber = operationContainer.TopContainerRevisionNumber }; var postToken = operationContainer.Token; var resourcePath = $"{operationContainer.Context}{attribute}"; var uriBuilder = this.GetUriBuilder(this.Credentials.Uri, ref resourcePath); Logger.Debug("Resource Path {0}: {1}", postToken, resourcePath); Logger.Debug("CDP4 Services POST: {0} - {1}", postToken, uriBuilder); var requestContent = this.CreateHttpContent(postToken, operationContainer, files); var requestsw = Stopwatch.StartNew(); using (var httpResponseMessage = await this.httpClient.PostAsync(resourcePath, requestContent)) { Logger.Info("CDP4 Services responded in {0} [ms] to POST {1}", requestsw.ElapsedMilliseconds, postToken); requestsw.Stop(); if (httpResponseMessage.StatusCode != HttpStatusCode.OK) { var errorResponse = await httpResponseMessage.Content.ReadAsStringAsync(); var msg = $"The CDP4 Services replied with code {httpResponseMessage.StatusCode}: {httpResponseMessage.ReasonPhrase}: {errorResponse}"; Logger.Error(msg); throw new DalWriteException(msg); } this.ProcessHeaders(httpResponseMessage); using (var resultStream = await httpResponseMessage.Content.ReadAsStreamAsync()) { result.AddRange(this.Serializer.Deserialize(resultStream)); Guid iterationId; if (this.TryExtractIterationIdfromUri(httpResponseMessage.RequestMessage.RequestUri, out iterationId)) { this.SetIterationContainer(result, iterationId); } } } watch.Stop(); Logger.Info("Write Operation completed in {0} [ms]", watch.ElapsedMilliseconds); return(result); }
public void VerifyThatCreatingOverrideCreateSubscriptions() { var domain1 = new CDP4Common.SiteDirectoryData.DomainOfExpertise(Guid.NewGuid(), this.assembler.Cache, this.uri); var domain2 = new CDP4Common.SiteDirectoryData.DomainOfExpertise(Guid.NewGuid(), this.assembler.Cache, this.uri); var model = new EngineeringModel(Guid.NewGuid(), this.assembler.Cache, this.uri); var iteration = new Iteration(Guid.NewGuid(), this.assembler.Cache, this.uri); var elementDef = new ElementDefinition(Guid.NewGuid(), this.assembler.Cache, this.uri) { Owner = domain1 }; var defForUsage = new ElementDefinition(Guid.NewGuid(), this.assembler.Cache, this.uri) { Owner = domain1 }; var usage = new ElementUsage(Guid.NewGuid(), this.assembler.Cache, this.uri) { ElementDefinition = defForUsage }; var parameter = new Parameter(Guid.NewGuid(), this.assembler.Cache, this.uri) { Owner = domain1 }; var parameterSubscription = new ParameterSubscription(Guid.NewGuid(), this.assembler.Cache, this.uri) { Owner = domain2 }; parameter.ParameterSubscription.Add(parameterSubscription); this.assembler.Cache.TryAdd(new CacheKey(parameter.Iid, iteration.Iid), new Lazy <Thing>(() => parameter)); this.assembler.Cache.TryAdd(new CacheKey(parameterSubscription.Iid, iteration.Iid), new Lazy <Thing>(() => parameterSubscription)); this.assembler.Cache.TryAdd(new CacheKey(usage.Iid, iteration.Iid), new Lazy <Thing>(() => usage)); var parameterOverride = new ParameterOverride(Guid.NewGuid(), this.assembler.Cache, this.uri) { Owner = domain1, Parameter = parameter }; usage.ParameterOverride.Add(parameterOverride); model.Iteration.Add(iteration); iteration.Element.Add(elementDef); iteration.Element.Add(defForUsage); elementDef.ContainedElement.Add(usage); defForUsage.Parameter.Add(parameter); var transactionContext = TransactionContextResolver.ResolveContext(iteration); var context = transactionContext.ContextRoute(); var operationContainer = new OperationContainer(context, model.RevisionNumber); operationContainer.AddOperation(new Operation(null, parameterOverride.ToDto(), OperationKind.Create)); operationContainer.AddOperation(new Operation(usage.ToDto(), usage.ToDto(), OperationKind.Update)); var modifier = new OperationModifier(this.session.Object); modifier.ModifyOperationContainer(operationContainer); Assert.AreEqual(3, operationContainer.Operations.Count()); }
private void AdornOperationContainer (OperationContainer container, ITextSnapshot snapshot, LineMap lineMap, CancellationToken cancelToken) { foreach (Operation operation in container.Operations) { SnapshotSpan span; if (!lineMap.TryGetSpan (this.view.TextSnapshot, operation.Id, out span)) continue; Geometry g = this.view.TextViewLines.GetMarkerGeometry (span); if (g == null) continue; Type opType = operation.GetType(); OperationVisuals vs; if (!Mapping.TryGetValue (opType, out vs)) continue; ViewCache viewCache; if (!views.TryGetValue (opType, out viewCache)) views[opType] = viewCache = new ViewCache (vs); InstantView adorner; bool preexisted = viewCache.TryGetView (out adorner); if (!preexisted) { adorner.FontSize = FontSize - 1; adorner.FontFamily = FontFamily; adorner.BorderBrush = BorderBrush; adorner.Foreground = Foreground; } adorner.Tag = operation.Id; OperationViewModel model = adorner.DataContext as OperationViewModel; if (model == null) adorner.DataContext = model = vs.CreateViewModel(); model.Operation = operation; if (operation is Loop) { var loopModel = (LoopViewModel)model; LoopIteration[] iterations = loopModel.Iterations; if (!preexisted || loopModel.Iteration > iterations.Length) loopModel.Iteration = iterations.Length; if (!preexisted) loopModel.IterationChanged += OnIterationChanged; if (iterations.Length > 0) AdornOperationContainer (iterations[loopModel.Iteration - 1], snapshot, lineMap, cancelToken); } Canvas.SetLeft (adorner, g.Bounds.Right + 10); Canvas.SetTop (adorner, g.Bounds.Top + 1); adorner.Height = g.Bounds.Height - 2; adorner.MaxHeight = g.Bounds.Height - 2; if (!preexisted) this.layer.AddAdornment (AdornmentPositioningBehavior.TextRelative, span, null, adorner, OperationAdornerRemoved); } }
internal void TestOperationContainerFileVerification(OperationContainer operationContainer, IEnumerable <string> files) { this.OperationContainerFileVerification(operationContainer, files); }
public override Task <IEnumerable <Thing> > Write(OperationContainer operationContainer, IEnumerable <string> files = null) { throw new NotImplementedException(); }
private void AdornOperationContainer(OperationContainer container, IDictionary<int, int> lineMap, AdornerLayer layer) { foreach (Operation operation in container.Operations) { int ln; if (!lineMap.TryGetValue (operation.Id, out ln)) continue; ln -= 1; int ch = GetCharacterIndexFromLineIndex (ln); int len = GetLineLength (ln); var endRect = GetRectFromCharacterIndex (ch + len - 1, true); Adorner adorner = null; if (operation is Loop) { var loop = (Loop)operation; int iteration; if (!this.currentIterations.TryGetValue (loop.Id, out iteration)) iteration = 0; var loopadorner = new LoopAdorner (this, loop); if (iteration >= loopadorner.Iterations.Length) this.currentIterations[loop.Id] = iteration = 0; loopadorner.CurrentIteration = iteration; loopadorner.IterationChanged += (s, e) => { this.currentIterations[loop.Id] = loopadorner.CurrentIteration; OnMethodCallChanged(); }; adorner = loopadorner; if (loopadorner.Iterations.Length > 0) AdornOperationContainer (loopadorner.Iterations[iteration], lineMap, layer); } else if (operation is StateChange) { adorner = new StateChangeAdorner (this, (StateChange)operation); } else if (operation is ReturnValue) { adorner = new ReturnAdorner (this, (ReturnValue)operation); } if (adorner != null) { double delta = endRect.Height - (endRect.Height * 0.8); adorner.Margin = new Thickness (endRect.X + 2, endRect.Y + (delta / 2), 0, 0); adorner.MaxHeight = endRect.Height; this.adorners.Add (operation.Id, adorner); layer.Add (adorner); } } }