Beispiel #1
0
        /// <summary>
        /// Insert a new database record, or updates one if it already exists from the supplied data transfer object.
        /// This is typically used during the import of existing data to the Database.
        /// </summary>
        /// <param name="transaction">
        /// The current <see cref="NpgsqlTransaction"/> to the database.
        /// </param>
        /// <param name="partition">
        /// The database partition (schema) where the requested resource will be stored.
        /// </param>
        /// <param name="parameterValueSet">
        /// The parameterValueSet DTO that is to be persisted.
        /// </param>
        /// <param name="container">
        /// The container of the DTO to be persisted.
        /// </param>
        /// <returns>
        /// True if the concept was successfully persisted.
        /// </returns>
        public virtual bool Upsert(NpgsqlTransaction transaction, string partition, CDP4Common.DTO.ParameterValueSet parameterValueSet, CDP4Common.DTO.Thing container = null)
        {
            var valueTypeDictionaryAdditions = new Dictionary <string, string>();

            base.Upsert(transaction, partition, parameterValueSet, container);

            using (var command = new NpgsqlCommand())
            {
                var sqlBuilder = new System.Text.StringBuilder();

                sqlBuilder.AppendFormat("INSERT INTO \"{0}\".\"ParameterValueSet\"", partition);
                sqlBuilder.AppendFormat(" (\"Iid\", \"Container\")");
                sqlBuilder.AppendFormat(" VALUES (:iid, :container)");

                command.Parameters.Add("iid", NpgsqlDbType.Uuid).Value       = parameterValueSet.Iid;
                command.Parameters.Add("container", NpgsqlDbType.Uuid).Value = container.Iid;
                sqlBuilder.Append(" ON CONFLICT (\"Iid\")");
                sqlBuilder.Append(" DO UPDATE ");
                sqlBuilder.Append(" SET \"Container\"");
                sqlBuilder.Append(" = :container;");

                command.CommandText = sqlBuilder.ToString();
                command.Connection  = transaction.Connection;
                command.Transaction = transaction;

                this.ExecuteAndLogCommand(command);
            }

            return(true);
        }
Beispiel #2
0
        /// <summary>
        /// Update a database record from the supplied data transfer object.
        /// </summary>
        /// <param name="transaction">
        /// The current <see cref="NpgsqlTransaction"/> to the database.
        /// </param>
        /// <param name="partition">
        /// The database partition (schema) where the requested resource will be updated.
        /// </param>
        /// <param name="parameterValueSet">
        /// The ParameterValueSet DTO that is to be updated.
        /// </param>
        /// <param name="container">
        /// The container of the DTO to be updated.
        /// </param>
        /// <returns>
        /// True if the concept was successfully updated.
        /// </returns>
        public virtual bool Update(NpgsqlTransaction transaction, string partition, CDP4Common.DTO.ParameterValueSet parameterValueSet, CDP4Common.DTO.Thing container = null)
        {
            bool isHandled;
            var  valueTypeDictionaryAdditions = new Dictionary <string, string>();
            var  beforeUpdate = this.BeforeUpdate(transaction, partition, parameterValueSet, container, out isHandled, valueTypeDictionaryAdditions);

            if (!isHandled)
            {
                beforeUpdate = beforeUpdate && base.Update(transaction, partition, parameterValueSet, container);

                using (var command = new NpgsqlCommand())
                {
                    var sqlBuilder = new System.Text.StringBuilder();
                    sqlBuilder.AppendFormat("UPDATE \"{0}\".\"ParameterValueSet\"", partition);
                    sqlBuilder.AppendFormat(" SET \"Container\"");
                    sqlBuilder.AppendFormat(" = :container");
                    sqlBuilder.AppendFormat(" WHERE \"Iid\" = :iid;");

                    command.Parameters.Add("iid", NpgsqlDbType.Uuid).Value       = parameterValueSet.Iid;
                    command.Parameters.Add("container", NpgsqlDbType.Uuid).Value = container.Iid;

                    command.CommandText = sqlBuilder.ToString();
                    command.Connection  = transaction.Connection;
                    command.Transaction = transaction;

                    this.ExecuteAndLogCommand(command);
                }
            }

            return(this.AfterUpdate(beforeUpdate, transaction, partition, parameterValueSet, container));
        }
Beispiel #3
0
        public void VerifyThatAfterUpdateStateChangesWorks()
        {
            var originalThing = this.parameter.DeepClone <Thing>();

            this.valueSetService.Setup(
                x => x.DeleteConcept(null, "partition", It.IsAny <ParameterValueSet>(), this.parameter)).Returns(true);

            this.parameter.ParameterType = this.cptParameterType.Iid;

            this.parameter.StateDependence = null;
            var valueset = new ParameterValueSet(Guid.NewGuid(), 0);

            this.parameter.ValueSet.Add(valueset.Iid);

            var updatedParameter = new Parameter(this.parameter.Iid, 0)
            {
                StateDependence = this.actualList.Iid
            };

            updatedParameter.ValueSet.Add(valueset.Iid);
            updatedParameter.ParameterType = this.cptParameterType.Iid;

            this.sideEffect.AfterUpdate(updatedParameter, this.elementDefinition, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object);

            this.valueSetService.Verify(x => x.CreateConcept(null, "partition", It.Is <ParameterValueSet>(vs => vs.ActualState == this.actualState1.Iid), updatedParameter, -1), Times.Exactly(1));
            this.valueSetService.Verify(x => x.CreateConcept(null, "partition", It.Is <ParameterValueSet>(vs => vs.ActualState == this.actualState2.Iid), updatedParameter, -1), Times.Exactly(1));
        }
        public void VerifyThatValueArrayAreSerializedCorrectly()
        {
            this.serializer = new Cdp4JsonSerializer(this.metadataprovider, new Version(1, 0, 0));

            var parameterValueSet = new Dto.ParameterValueSet(Guid.NewGuid(), 1);
            var valuearray        = new[] { "123", "abc" };

            parameterValueSet.Manual    = new ValueArray <string>(valuearray);
            parameterValueSet.Computed  = new ValueArray <string>(valuearray);
            parameterValueSet.Reference = new ValueArray <string>(valuearray);
            parameterValueSet.Published = new ValueArray <string>(valuearray);

            using (var memoryStream = new MemoryStream())
            {
                this.serializer.SerializeToStream(new[] { parameterValueSet }, memoryStream);
                memoryStream.Position = 0;

                using (var reader = new StreamReader(memoryStream))
                {
                    var txt = reader.ReadToEnd();

                    // output:  "manual":"[\"123\",\"abc\"]"
                    Assert.IsTrue(txt.Contains("\"manual\":\"[\\\"123\\\",\\\"abc\\\"]\""));
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// The mapping from a database record to data transfer object.
        /// </summary>
        /// <param name="reader">
        /// An instance of the SQL reader.
        /// </param>
        /// <returns>
        /// A deserialized instance of <see cref="CDP4Common.DTO.ParameterValueSet"/>.
        /// </returns>
        public virtual CDP4Common.DTO.ParameterValueSet MapToDto(NpgsqlDataReader reader)
        {
            string tempModifiedOn;
            string tempPublished;
            string tempFormula;
            string tempComputed;
            string tempManual;
            string tempReference;
            string tempValueSwitch;

            var valueDict      = (Dictionary <string, string>)reader["ValueTypeSet"];
            var iid            = Guid.Parse(reader["Iid"].ToString());
            var revisionNumber = int.Parse(valueDict["RevisionNumber"]);

            var dto = new CDP4Common.DTO.ParameterValueSet(iid, revisionNumber);

            dto.ExcludedPerson.AddRange(Array.ConvertAll((string[])reader["ExcludedPerson"], Guid.Parse));
            dto.ExcludedDomain.AddRange(Array.ConvertAll((string[])reader["ExcludedDomain"], Guid.Parse));
            dto.ActualState  = reader["ActualState"] is DBNull ? (Guid?)null : Guid.Parse(reader["ActualState"].ToString());
            dto.ActualOption = reader["ActualOption"] is DBNull ? (Guid?)null : Guid.Parse(reader["ActualOption"].ToString());

            if (valueDict.TryGetValue("ModifiedOn", out tempModifiedOn))
            {
                dto.ModifiedOn = Utils.ParseUtcDate(tempModifiedOn);
            }

            if (valueDict.TryGetValue("Published", out tempPublished))
            {
                dto.Published = tempPublished.FromHstoreToValueArray <string>();
            }

            if (valueDict.TryGetValue("Formula", out tempFormula))
            {
                dto.Formula = tempFormula.FromHstoreToValueArray <string>();
            }

            if (valueDict.TryGetValue("Computed", out tempComputed))
            {
                dto.Computed = tempComputed.FromHstoreToValueArray <string>();
            }

            if (valueDict.TryGetValue("Manual", out tempManual))
            {
                dto.Manual = tempManual.FromHstoreToValueArray <string>();
            }

            if (valueDict.TryGetValue("Reference", out tempReference))
            {
                dto.Reference = tempReference.FromHstoreToValueArray <string>();
            }

            if (valueDict.TryGetValue("ValueSwitch", out tempValueSwitch))
            {
                dto.ValueSwitch = Utils.ParseEnum <CDP4Common.EngineeringModelData.ParameterSwitchKind>(tempValueSwitch);
            }

            return(dto);
        }
        public void VerifyThatCreateValueSetsUpdateOperationsWorksStateOptionDependent()
        {
            var valueset1 = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            valueset1.Manual = new ValueArray <string>(manual);
            this.parameter1.ValueSet.Add(valueset1);
            valueset1.ActualOption = this.option1;
            valueset1.ActualState  = this.as1;

            var valueset2 = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            valueset2.Manual = new ValueArray <string>();
            this.parameter1.ValueSet.Add(valueset2);
            valueset2.ActualOption = this.option2;
            valueset2.ActualState  = this.as1;

            this.parameter1.IsOptionDependent     = true;
            this.parameter1Copy.IsOptionDependent = true;
            this.parameter1.StateDependence       = this.asl1;

            var modeldto     = this.model2.ToDto();
            var iterationDto = (Dto.Iteration) this.iteration2.ToDto();
            var def2Dto      = new Dto.ElementDefinition(this.def2Copy.Iid, 2);
            var parameterDto = new Dto.Parameter(this.parameter1Copy.Iid, 2);

            parameterDto.IsOptionDependent = true;
            var newValueSet = new Dto.ParameterValueSet(Guid.NewGuid(), 2);

            iterationDto.Element.Add(def2Dto.Iid);
            def2Dto.Parameter.Add(parameterDto.Iid);
            parameterDto.ValueSet.Add(newValueSet.Iid);

            var returnedDto = new List <Dto.Thing>
            {
                modeldto,
                iterationDto,
                def2Dto,
                parameterDto,
                newValueSet
            };

            var transactionContext = TransactionContextResolver.ResolveContext(this.iteration2);
            var context            = transactionContext.ContextRoute();

            var operationCreator   = new ValueSetOperationCreator(this.session.Object);
            var operationContainer = operationCreator.CreateValueSetsUpdateOperations(context, returnedDto, this.map);

            var operation = operationContainer.Operations.Single();
            var original  = (Dto.ParameterValueSet)operation.OriginalThing;
            var modified  = (Dto.ParameterValueSet)operation.ModifiedThing;

            Assert.AreNotEqual(original.Manual, modified.Manual);
        }
        public void VerifyThatCreateValueSetsUpdateOperationsWorks()
        {
            var valueset = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            valueset.Manual = new ValueArray <string>(manual);
            this.parameter1.ValueSet.Add(valueset);

            var subscriptionvalueset = new ParameterSubscriptionValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            subscriptionvalueset.Manual = new ValueArray <string>(manual);
            this.subscription1.ValueSet.Add(subscriptionvalueset);

            var modeldto     = this.model2.ToDto();
            var iterationDto = (Dto.Iteration) this.iteration2.ToDto();
            var def2Dto      = new Dto.ElementDefinition(this.def2Copy.Iid, 2);
            var parameterDto = new Dto.Parameter(this.parameter1Copy.Iid, 2);
            var newValueSet  = new Dto.ParameterValueSet(Guid.NewGuid(), 2);

            var subscription         = new Dto.ParameterSubscription(this.subscriptionCopy.Iid, 1);
            var subscriptionValueSet = new Dto.ParameterSubscriptionValueSet(Guid.NewGuid(), 1);

            iterationDto.Element.Add(def2Dto.Iid);
            def2Dto.Parameter.Add(parameterDto.Iid);
            parameterDto.ValueSet.Add(newValueSet.Iid);
            parameterDto.ParameterSubscription.Add(subscription.Iid);
            subscription.ValueSet.Add(subscriptionValueSet.Iid);

            var returnedDto = new List <Dto.Thing>
            {
                modeldto,
                iterationDto,
                def2Dto,
                parameterDto,
                newValueSet,
                subscription,
                subscriptionValueSet
            };

            var transactionContext = TransactionContextResolver.ResolveContext(this.iteration2);
            var context            = transactionContext.ContextRoute();

            var operationCreator   = new ValueSetOperationCreator(this.session.Object);
            var operationContainer = operationCreator.CreateValueSetsUpdateOperations(context, returnedDto, this.map);

            Assert.AreEqual(2, operationContainer.Operations.Count());
            var operation   = operationContainer.Operations.Single(x => x.OriginalThing.ClassKind == ClassKind.ParameterValueSet);
            var originalPvs = (Dto.ParameterValueSet)operation.OriginalThing;
            var modifiedPvs = (Dto.ParameterValueSet)operation.ModifiedThing;

            Assert.AreNotEqual(originalPvs.Manual, modifiedPvs.Manual);
        }
        /// <summary>
        /// Create a <see cref="ParameterValueSet"/> with a specific option and state. The old value set is used if it exists, otherwise default values are used
        /// </summary>
        /// <param name="oldValue">The old <see cref="ParameterValueSet"/></param>
        /// <param name="parameter">The current <see cref="Parameter"/></param>
        /// <param name="actualOption">The actual <see cref="CDP4Common.DTO.Option"/></param>
        /// <param name="actualState">The <see cref="ActualFiniteState"/></param>
        /// <param name="transaction">The transaction</param>
        /// <param name="partition">The partition</param>
        /// <param name="securityContext">The security context</param>
        /// <returns>The created <see cref="ParameterValueSet"/></returns>
        private ParameterValueSet CreateParameterValueSet(ParameterValueSet oldValue, Parameter parameter, Guid?actualOption, Guid?actualState, NpgsqlTransaction transaction, string partition, ISecurityContext securityContext)
        {
            this.DefaultValueSetFactory.Load(transaction, securityContext);
            var defaultValue = this.DefaultValueSetFactory.CreateDefaultValueArray(parameter.ParameterType);

            var isOldValueNull = oldValue == null;
            var valueSet       = new ParameterValueSet(Guid.NewGuid(), 1)
            {
                Manual       = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Manual),
                Computed     = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Computed),
                Reference    = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Reference),
                Published    = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Published),
                Formula      = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Formula),
                ActualOption = actualOption,
                ActualState  = actualState,
                ValueSwitch  = isOldValueNull ? CDP4Common.EngineeringModelData.ParameterSwitchKind.MANUAL : oldValue.ValueSwitch
            };

            this.ParameterValueSetService.CreateConcept(transaction, partition, valueSet, parameter);
            return(valueSet);
        }
        public void VerifyInvalidOperationException()
        {
            var valueset1 = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            valueset1.Manual = new ValueArray <string>(manual);
            this.parameter1.ValueSet.Add(valueset1);
            valueset1.ActualOption = this.option1;
            valueset1.ActualState  = this.as1;

            var modeldto     = this.model2.ToDto();
            var iterationDto = (Dto.Iteration) this.iteration2.ToDto();
            var def2Dto      = new Dto.ElementDefinition(this.def2Copy.Iid, 2);
            var parameterDto = new Dto.Parameter(this.parameter1Copy.Iid, 2);

            parameterDto.IsOptionDependent = true;
            var newValueSet = new Dto.ParameterValueSet(Guid.NewGuid(), 2);

            iterationDto.Element.Add(def2Dto.Iid);
            def2Dto.Parameter.Add(parameterDto.Iid);
            parameterDto.ValueSet.Add(newValueSet.Iid);

            var returnedDto = new List <Dto.Thing>
            {
                iterationDto,
                def2Dto,
                parameterDto,
                newValueSet
            };

            var transactionContext = TransactionContextResolver.ResolveContext(this.iteration2);
            var context            = transactionContext.ContextRoute();

            var operationCreator = new ValueSetOperationCreator(this.session.Object);

            Assert.Throws <InvalidOperationException>(() => operationCreator.CreateValueSetsUpdateOperations(context, returnedDto, this.map));
        }
        public void VerifyCopyElementDefWorks()
        {
            var modelSetupService = new Mock <IEngineeringModelSetupService>();
            var modelSetup        = new EngineeringModelSetup(Guid.NewGuid(), 0);

            modelSetupService.Setup(x => x.GetEngineeringModelSetup(It.IsAny <NpgsqlTransaction>(), It.IsAny <Guid>())).Returns(modelSetup);

            this.copySourceDtos = new List <Thing>();

            var boolParamTypeId = Guid.NewGuid();
            var mrdl            = new ModelReferenceDataLibrary(Guid.NewGuid(), 1);

            mrdl.ParameterType.Add(boolParamTypeId);

            var sourceIteration   = new Iteration(Guid.NewGuid(), 1);
            var sourceElementDef1 = new ElementDefinition(Guid.NewGuid(), 1);
            var sourceElementDef2 = new ElementDefinition(Guid.NewGuid(), 1);
            var sourceUsage1      = new ElementUsage(Guid.NewGuid(), 1)
            {
                ElementDefinition = sourceElementDef2.Iid
            };

            sourceElementDef1.ContainedElement.Add(sourceUsage1.Iid);
            sourceIteration.Element.Add(sourceElementDef1.Iid);
            sourceIteration.Element.Add(sourceElementDef2.Iid);

            var parameter1 = new Parameter(Guid.NewGuid(), 1)
            {
                ParameterType = boolParamTypeId
            };
            var pvs1 = new ParameterValueSet(Guid.NewGuid(), 1)
            {
                Manual      = new ValueArray <string>(new[] { "true" }),
                Computed    = new ValueArray <string>(new[] { "-" }),
                Reference   = new ValueArray <string>(new[] { "-" }),
                Published   = new ValueArray <string>(new[] { "-" }),
                ValueSwitch = ParameterSwitchKind.MANUAL
            };

            var parameter2 = new Parameter(Guid.NewGuid(), 1)
            {
                ParameterType = boolParamTypeId
            };
            var pvs2 = new ParameterValueSet(Guid.NewGuid(), 1)
            {
                Manual      = new ValueArray <string>(new[] { "true" }),
                Computed    = new ValueArray <string>(new[] { "-" }),
                Reference   = new ValueArray <string>(new[] { "-" }),
                Published   = new ValueArray <string>(new[] { "-" }),
                ValueSwitch = ParameterSwitchKind.MANUAL
            };

            parameter1.ValueSet.Add(pvs1.Iid);
            sourceElementDef1.Parameter.Add(parameter1.Iid);
            parameter2.ValueSet.Add(pvs2.Iid);
            sourceElementDef2.Parameter.Add(parameter2.Iid);

            var override2 = new ParameterOverride(Guid.NewGuid(), 1);

            override2.Parameter = parameter2.Iid;
            var ovs = new ParameterOverrideValueSet(Guid.NewGuid(), 1)
            {
                ParameterValueSet = pvs2.Iid
            };

            override2.ValueSet.Add(ovs.Iid);
            sourceUsage1.ParameterOverride.Add(override2.Iid);

            this.copySourceDtos.Add(sourceIteration);
            this.copySourceDtos.Add(sourceElementDef1);
            this.copySourceDtos.Add(sourceElementDef2);
            this.copySourceDtos.Add(sourceUsage1);
            this.copySourceDtos.Add(parameter1);
            this.copySourceDtos.Add(pvs1);
            this.copySourceDtos.Add(parameter2);
            this.copySourceDtos.Add(pvs2);
            this.copySourceDtos.Add(override2);
            this.copySourceDtos.Add(ovs);

            var targetIteration = new Iteration(Guid.NewGuid(), 1);

            this.serviceProvider.Setup(x => x.MapToReadService(It.IsAny <string>())).Returns <string>(x => new TestSourceService(this.copySourceDtos, x));
            this.serviceProvider.Setup(x => x.MapToReadService(It.Is <string>(t => t == ClassKind.ModelReferenceDataLibrary.ToString())))
            .Returns <string>(x => new TestSourceService(new List <Thing> {
                mrdl
            }, x));

            this.serviceProvider.Setup(x => x.MapToReadService(It.Is <string>(t => t == ClassKind.Iteration.ToString())))
            .Returns <string>(x => new TestSourceService(new List <Thing> {
                sourceIteration, targetIteration
            }, x));

            var customOperationSideEffectProcessor = new Mock <IOperationSideEffectProcessor>();

            customOperationSideEffectProcessor.Setup(x => x.BeforeCreate(It.IsAny <Thing>(), It.IsAny <Thing>(), It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <ISecurityContext>())).
            Returns(true);

            var paramSubscriptionService = new ParameterSubscriptionService
            {
                ParameterSubscriptionDao = new Mock <IParameterSubscriptionDao>().Object,
                PermissionService        = this.permissionService.Object,
            };

            var parameterContextProvider = new OldParameterContextProvider
            {
                ParameterValueSetService = new TestSourceService(this.copySourceDtos, ClassKind.ParameterValueSet.ToString())
            };

            var paramGroupService = new ParameterGroupService
            {
                PermissionService = this.permissionService.Object,

                TransactionManager = this.transactionManager.Object,
                ParameterGroupDao  = new Mock <IParameterGroupDao>().Object
            };

            var valueSetService = new Mock <IParameterValueSetService>();

            valueSetService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <IEnumerable <Guid> >(), It.IsAny <ISecurityContext>()))
            .Returns <NpgsqlTransaction, string, IEnumerable <Guid>, ISecurityContext>((a, b, c, d) =>
            {
                var list = new List <ParameterValueSet>();
                foreach (var guid in c)
                {
                    var vs = new ParameterValueSet(guid, 1)
                    {
                        Manual    = new ValueArray <string>(new [] { "-" }),
                        Computed  = new ValueArray <string>(new [] { "-" }),
                        Reference = new ValueArray <string>(new [] { "-" }),
                        Published = new ValueArray <string>(new [] { "-" })
                    };

                    list.Add(vs);
                }

                return(list);
            });

            var overrideValueSetService = new Mock <IParameterOverrideValueSetService>();

            overrideValueSetService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <IEnumerable <Guid> >(), It.IsAny <ISecurityContext>()))
            .Returns <NpgsqlTransaction, string, IEnumerable <Guid>, ISecurityContext>((a, b, c, d) =>
            {
                var list = new List <ParameterOverrideValueSet>();
                foreach (var guid in c)
                {
                    var vs = new ParameterOverrideValueSet(guid, 1)
                    {
                        Manual    = new ValueArray <string>(new[] { "-" }),
                        Computed  = new ValueArray <string>(new[] { "-" }),
                        Reference = new ValueArray <string>(new[] { "-" }),
                        Published = new ValueArray <string>(new[] { "-" })
                    };

                    list.Add(vs);
                }

                return(list);
            });

            var paramDao     = new TestParameterDao();
            var paramService = new ParameterService
            {
                PermissionService            = this.permissionService.Object,
                ParameterDao                 = paramDao,
                OperationSideEffectProcessor = customOperationSideEffectProcessor.Object,
                TransactionManager           = this.transactionManager.Object,
                OldParameterContextProvider  = parameterContextProvider,
                ParameterSubscriptionService = paramSubscriptionService,
                ParameterValueSetService     = valueSetService.Object
            };

            var paramOverrideDao = new TestParameterOverrideDao();

            var paramOverrideService = new ParameterOverrideService
            {
                PermissionService = this.permissionService.Object,

                ParameterOverrideDao             = paramOverrideDao,
                TransactionManager               = this.transactionManager.Object,
                OperationSideEffectProcessor     = customOperationSideEffectProcessor.Object,
                ParameterSubscriptionService     = paramSubscriptionService,
                ParameterOverrideValueSetService = overrideValueSetService.Object
            };

            var usageDao     = new Mock <IElementUsageDao>();
            var usageService = new ElementUsageService
            {
                PermissionService = this.permissionService.Object,

                ParameterOverrideService     = paramOverrideService,
                ElementUsageDao              = usageDao.Object,
                TransactionManager           = this.transactionManager.Object,
                OperationSideEffectProcessor = customOperationSideEffectProcessor.Object
            };

            var edDao     = new TestElementDefinitionDao();
            var edService = new ElementDefinitionService
            {
                PermissionService = this.permissionService.Object,

                ElementDefinitionDao         = edDao,
                ElementUsageService          = usageService,
                ParameterService             = paramService,
                TransactionManager           = this.transactionManager.Object,
                OperationSideEffectProcessor = customOperationSideEffectProcessor.Object,
                ParameterGroupService        = paramGroupService
            };

            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ElementDefinition.ToString())).Returns(edService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ElementUsage.ToString())).Returns(usageService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.Parameter.ToString())).Returns(paramService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ParameterOverride.ToString())).Returns(paramOverrideService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ParameterSubscription.ToString())).Returns(paramSubscriptionService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ParameterGroup.ToString())).Returns(paramGroupService);

            var postOperation = new CdpPostOperation();
            var copyinfo      = new CopyInfo
            {
                ActiveOwner = Guid.NewGuid(),
                Options     = new CopyInfoOptions
                {
                    CopyKind   = CopyKind.Deep,
                    KeepOwner  = true,
                    KeepValues = true
                },
                Source = new CopySource
                {
                    IterationId = sourceIteration.Iid,
                    Thing       = new CopyReference
                    {
                        Iid       = sourceElementDef1.Iid,
                        ClassKind = ClassKind.ElementDefinition
                    },
                    TopContainer = new CopyReference
                    {
                        Iid       = Guid.NewGuid(),
                        ClassKind = ClassKind.EngineeringModel
                    }
                },
                Target = new CopyTarget
                {
                    IterationId = targetIteration.Iid,
                    Container   = new CopyReference
                    {
                        Iid       = targetIteration.Iid,
                        ClassKind = ClassKind.Iteration
                    },
                    TopContainer = new CopyReference
                    {
                        Iid       = Guid.NewGuid(),
                        ClassKind = ClassKind.EngineeringModel
                    }
                }
            };

            postOperation.Copy.Add(copyinfo);

            this.serviceProvider.Setup(x => x.MapToReadService(ClassKind.EngineeringModelSetup.ToString())).Returns(modelSetupService.Object);
            this.operationProcessor.Process(postOperation, null, $"Iteration_{targetIteration.Iid.ToString().Replace("-", "_")}", null);

            Assert.AreEqual(2, edDao.WrittenThingCount);
            Assert.AreEqual(2, paramDao.WrittenThingCount);
            Assert.AreEqual(1, paramOverrideDao.WrittenThingCount);
            usageDao.Verify(x => x.Write(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <ElementUsage>(), It.IsAny <Thing>()), Times.Once);
        }
Beispiel #11
0
        public void VerifyThatAfterUpdateUpdateTheOVerrideAndSubscription()
        {
            var valueset = new ParameterValueSet(Guid.NewGuid(), 0);

            valueset.Manual      = new ValueArray <string>(new[] { "set" });
            valueset.Published   = new ValueArray <string>(new[] { "set" });
            valueset.Computed    = new ValueArray <string>(new[] { "set" });
            valueset.ValueSwitch = ParameterSwitchKind.REFERENCE;

            this.parameter.ValueSet.Add(valueset.Iid);
            this.OldParameterContextProvider.Setup(x => x.GetsourceValueSet(null, It.IsAny <Guid?>())).Returns(valueset);

            var overrideValueSet = new ParameterOverrideValueSet(Guid.NewGuid(), 1);

            overrideValueSet.ParameterValueSet = valueset.Iid;
            overrideValueSet.Manual            = new ValueArray <string>(new[] { "override" });
            overrideValueSet.Published         = new ValueArray <string>(new[] { "override" });
            overrideValueSet.Computed          = new ValueArray <string>(new[] { "override" });
            overrideValueSet.ValueSwitch       = ParameterSwitchKind.REFERENCE;

            this.parameterOverride.ValueSet.Add(overrideValueSet.Iid);

            var subscription1 = new ParameterSubscription(Guid.NewGuid(), 1);
            var subscription2 = new ParameterSubscription(Guid.NewGuid(), 2);

            var subscription1ValueSet = new ParameterSubscriptionValueSet(Guid.NewGuid(), 1);

            subscription1ValueSet.Manual             = new ValueArray <string>(new [] { "sub1" });
            subscription1ValueSet.SubscribedValueSet = valueset.Iid;

            var subscription2ValueSet = new ParameterSubscriptionValueSet(Guid.NewGuid(), 1);

            subscription2ValueSet.Manual             = new ValueArray <string>(new[] { "sub2" });
            subscription2ValueSet.SubscribedValueSet = overrideValueSet.Iid;

            subscription1.ValueSet.Add(subscription1ValueSet.Iid);
            subscription2.ValueSet.Add(subscription2ValueSet.Iid);

            var originalThing = this.parameter.DeepClone <Thing>();

            this.parameterOverride.ParameterSubscription.Add(subscription2.Iid);
            this.parameter.ParameterSubscription.Add(subscription1.Iid);

            this.parameterOverrideService.Setup(
                x => x.GetShallow(this.npgsqlTransaction, "partition", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.parameterOverride
            });

            this.parameterSubscriptionService.Setup(x =>
                                                    x.GetShallow(this.npgsqlTransaction, "partition",
                                                                 It.Is <IEnumerable <Guid> >(g => g.Contains(subscription1.Iid) && g.Contains(subscription2.Iid)),
                                                                 this.securityContext.Object))
            .Returns(new List <Thing> {
                subscription1, subscription2
            });

            this.valueSetService.Setup(x => x.DeleteConcept(null, "partition", It.IsAny <ParameterValueSet>(), this.parameter))
            .Returns(true);

            this.parameterOverrideValueSetService
            .Setup(x => x.GetShallow(null, "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(overrideValueSet.Iid)), this.securityContext.Object))
            .Returns(new[] { overrideValueSet });

            this.parameterSubscriptionValueSetService
            .Setup(x => x.GetShallow(null, "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(subscription1ValueSet.Iid)), this.securityContext.Object))
            .Returns(new[] { subscription1ValueSet });

            this.parameterSubscriptionValueSetService
            .Setup(x => x.GetShallow(null, "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(subscription2ValueSet.Iid)), this.securityContext.Object))
            .Returns(new[] { subscription2ValueSet });

            this.parameter.ParameterType   = this.cptParameterType.Iid;
            this.parameter.StateDependence = null;

            var updatedParameter = new Parameter(this.parameter.Iid, 0)
            {
                StateDependence = this.actualList.Iid
            };

            updatedParameter.ValueSet.Add(valueset.Iid);
            updatedParameter.ParameterType = this.cptParameterType.Iid;
            updatedParameter.ParameterSubscription.Add(subscription1.Iid);

            this.sideEffect.AfterUpdate(updatedParameter, this.elementDefinition, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object);

            this.valueSetService.Verify(x => x.CreateConcept(this.npgsqlTransaction, "partition", It.Is <ParameterValueSet>(y => y.Manual.Contains("set")), updatedParameter, -1),
                                        Times.Exactly(2));

            this.parameterOverrideValueSetService.Verify(x => x.CreateConcept(this.npgsqlTransaction, "partition", It.Is <ParameterOverrideValueSet>(y => y.Manual.Contains("override")), this.parameterOverride, -1),
                                                         Times.Exactly(2));

            this.parameterSubscriptionValueSetService.Verify(x => x.CreateConcept(this.npgsqlTransaction, "partition", It.Is <ParameterSubscriptionValueSet>(y => y.Manual.Contains("sub1")), subscription1, -1),
                                                             Times.Exactly(2));

            this.parameterSubscriptionValueSetService.Verify(x => x.CreateConcept(this.npgsqlTransaction, "partition", It.Is <ParameterSubscriptionValueSet>(y => y.Manual.Contains("sub2")), subscription2, -1),
                                                             Times.Exactly(2));
        }
        /// <summary>
        /// Create a new <see cref="ParameterOverrideValueSet"/> from the old values
        /// </summary>
        /// <param name="oldValue">The old <see cref="ParameterOverrideValueSet"/></param>
        /// <param name="parameterValueSet">The <see cref="ParameterValueSet"/></param>
        /// <param name="container">The <see cref="ParameterOverride"/></param>
        /// <param name="transaction">The current transaction</param>
        /// <param name="partition">The current partition</param>
        /// <returns>The new <see cref="ParameterOverrideValueSet"/></returns>
        private ParameterOverrideValueSet CreateParameterOverrideValueSet(ParameterOverrideValueSet oldValue, ParameterValueSet parameterValueSet, ParameterOverride container, NpgsqlTransaction transaction, string partition)
        {
            var isOldValueNull = oldValue == null;
            var newValueSet    = new ParameterOverrideValueSet(Guid.NewGuid(), 1)
            {
                Manual            = new ValueArray <string>(isOldValueNull ? parameterValueSet.Manual : oldValue.Manual),
                Computed          = new ValueArray <string>(isOldValueNull ? parameterValueSet.Computed : oldValue.Computed),
                Reference         = new ValueArray <string>(isOldValueNull ? parameterValueSet.Reference : oldValue.Reference),
                Published         = new ValueArray <string>(isOldValueNull ? parameterValueSet.Published : oldValue.Published),
                Formula           = new ValueArray <string>(isOldValueNull ? parameterValueSet.Formula : oldValue.Formula),
                ParameterValueSet = parameterValueSet.Iid,
                ValueSwitch       = isOldValueNull ? CDP4Common.EngineeringModelData.ParameterSwitchKind.MANUAL : oldValue.ValueSwitch
            };

            this.ParameterOverrideValueSetService.CreateConcept(transaction, partition, newValueSet, container);
            return(newValueSet);
        }
Beispiel #13
0
        public async Task AssertThatRevisionsAreCachedCorrectly()
        {
            var assembler = new Assembler(this.uri);

            var parameterIid       = Guid.NewGuid();
            var parameterRevision1 = new Dto.Parameter(parameterIid, 1);  //The Parameter's 1st Revision
            var parameterRevision2 = new Dto.Parameter(parameterIid, 2);  //The Parameter's 2nd Revision
            var parameterRevision3 = new Dto.Parameter(parameterIid, 3);  //The Parameter's 3rd Revision

            var valueSet1 = new Dto.ParameterValueSet(Guid.NewGuid(), 1); //ValueSet that belongs to the parameter's 1st Revision
            var valueSet2 = new Dto.ParameterValueSet(Guid.NewGuid(), 1); //ValueSet that belongs to the parameter's 2nd Revision
            var valueSet3 = new Dto.ParameterValueSet(Guid.NewGuid(), 1); //ValueSet that belongs to the parameter's 3rd Revision

            parameterRevision1.ValueSet.Add(valueSet1.Iid);
            parameterRevision2.ValueSet.Add(valueSet2.Iid);
            parameterRevision3.ValueSet.Add(valueSet3.Iid);

            //******************************************************************************************************************
            // 1st call of Synchronize for Revision 2, which is the currently active revision
            //******************************************************************************************************************
            await assembler.Synchronize(new List <Dto.Thing> {
                parameterRevision2, valueSet2
            });

            //Cache should not be empty
            Assert.IsNotEmpty(assembler.Cache);

            //Cache should contain 2 items
            Assert.AreEqual(2, assembler.Cache.Count);

            //Get the cached version of the parameter
            var cachedParameter = assembler.Cache.First(x => x.Value.Value.Iid == parameterRevision2.Iid).Value.Value as Parameter;

            //Revision number should be 2 now
            Assert.AreEqual(parameterRevision2.RevisionNumber, cachedParameter.RevisionNumber);

            //Parameter should contain a ValueSet
            Assert.AreEqual(1, cachedParameter.ValueSet.Count);

            //Parameter should contain the correct ValueSet
            Assert.AreEqual(cachedParameter.ValueSet.First().Iid, valueSet2.Iid);

            //******************************************************************************************************************
            // 2st call of Synchronize which introduces a newer revision: Revision nr. 3.
            //******************************************************************************************************************
            await assembler.Synchronize(new List <Dto.Thing> {
                parameterRevision3, valueSet3
            });

            //Cache should still contain 2 things, because parameterRevision2 is removed from cache together with valueSet2
            //parameterRevision2 now is contained in the Revisions property of the cached version of the parameter
            Assert.AreEqual(2, assembler.Cache.Count);

            cachedParameter = assembler.Cache.First(x => x.Value.Value.Iid == parameterRevision3.Iid).Value.Value as Parameter;

            //Current cached parameter version is Revision 3
            Assert.AreEqual(parameterRevision3.RevisionNumber, cachedParameter.RevisionNumber);

            //cached parameter should contain a ValueSet
            Assert.AreEqual(1, cachedParameter.ValueSet.Count);

            //cached parameter should contain exactly 1 revision
            Assert.AreEqual(1, cachedParameter.Revisions.Count);

            //cached parameter should contain the correct ValueSet
            Assert.AreEqual(cachedParameter.ValueSet.First().Iid, valueSet3.Iid);

            //Revisions property of current cached item should contain the right revision number
            Assert.AreEqual(cachedParameter.Revisions.First().Value.RevisionNumber, parameterRevision2.RevisionNumber);

            //******************************************************************************************************************
            // 3rd call of Synchronize with older revision, that should be added as a revision to an existing cached poco
            //******************************************************************************************************************
            await assembler.Synchronize(new List <Dto.Thing> {
                parameterRevision1, valueSet1
            });

            //Cache should still contain 2 things, because parameterRevision1 is added to the Revisions property of the current cached parameter
            Assert.AreEqual(2, assembler.Cache.Count);

            cachedParameter = assembler.Cache.First(x => x.Value.Value.Iid == parameterRevision1.Iid).Value.Value as Parameter;

            //parameterRevision3 is still the current cached version
            Assert.AreEqual(parameterRevision3.RevisionNumber, cachedParameter.RevisionNumber);

            //cached parameter should contain a ValueSet
            Assert.AreEqual(1, cachedParameter.ValueSet.Count);

            //cached parameter should contain the correct ValueSet
            Assert.AreEqual(cachedParameter.ValueSet.First().Iid, valueSet3.Iid);

            //cached parameter should contain exactly 2 revisions
            Assert.AreEqual(2, cachedParameter.Revisions.Count);

            var revisionParameter1 = cachedParameter.Revisions.Single(x => x.Value.Iid == parameterRevision1.Iid && x.Value.RevisionNumber == parameterRevision1.RevisionNumber).Value as Parameter;
            var revisionParameter2 = cachedParameter.Revisions.Single(x => x.Value.Iid == parameterRevision2.Iid && x.Value.RevisionNumber == parameterRevision2.RevisionNumber).Value as Parameter;

            //Should be empty, because an older revision than the one currently in the cache was asked for
            //In that case the ValueSet belonging to the Parameter doens't get cloned (because it is unknown at that moment)
            Assert.AreEqual(0, revisionParameter1.ValueSet.Count);

            //Should be 1, because the ValueSet2 was cloned and added to the Parameter added to the Revisions property of the cached parameter
            //when revision 3 was added to the cache
            Assert.AreEqual(1, revisionParameter2.ValueSet.Count);
        }