/// <summary>
        /// Reads the data related to the provided <see cref="CDP4Common.EngineeringModelData.Iteration"/> from the data-source
        /// </summary>
        /// <param name="iteration">
        /// An instance of <see cref="CDP4Common.EngineeringModelData.Iteration"/> that needs to be read from the data-source
        /// </param>
        /// <param name="cancellationToken">
        /// The <see cref="CancellationToken"/>
        /// </param>
        /// <param name="attributes">
        /// An instance of <see cref="IQueryAttributes"/> to be used with the request
        /// </param>
        /// <returns>
        /// A list of <see cref="Thing"/> that are contained by the provided <see cref="CDP4Common.EngineeringModelData.EngineeringModel"/> including the Reference-Data.
        /// All the <see cref="Thing"/>s that have been updated since the last read will be returned.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// Thrown when the <see cref="Session"/> property has not been set
        /// </exception>
        public override async Task <IEnumerable <Thing> > Read(CDP4Common.DTO.Iteration iteration, CancellationToken cancellationToken, IQueryAttributes attributes = null)
        {
            if (this.Session == null)
            {
                throw new InvalidOperationException("The Session may not be null and must be set prior to reading an Iteration");
            }

            // Get the RequiredRdl to load
            var siteDirectory  = this.Session.Assembler.RetrieveSiteDirectory();
            var iterationSetup = siteDirectory.Model.SelectMany(mod => mod.IterationSetup).SingleOrDefault(it => it.IterationIid == iteration.Iid);

            if (iterationSetup == null)
            {
                throw new InvalidOperationException("The Iteration to open does not have any associated IterationSetup.");
            }

            var modelSetup = (EngineeringModelSetup)iterationSetup.Container;
            var modelReferenceDataLibrary = modelSetup.RequiredRdl.SingleOrDefault();

            if (modelReferenceDataLibrary == null)
            {
                throw new InvalidOperationException("The model to open does not have a Required Reference-Data-Library.");
            }

            var modelReferenceDataLibraryDto = modelReferenceDataLibrary.ToDto();

            var result        = new List <Thing>();
            var referenceData = await this.Read(modelReferenceDataLibraryDto, cancellationToken);

            result.AddRange(referenceData);
            var engineeringModelData = await this.Read((Thing)iteration, cancellationToken);

            result.AddRange(engineeringModelData);
            return(result);
        }
        /// <summary>
        /// Update a <see cref="Parameter"/> with new <see cref="ParameterValueSet"/>
        /// </summary>
        /// <param name="parameter">The <see cref="Parameter"/></param>
        /// <param name="iteration">The <see cref="Iteration"/></param>
        /// <param name="transaction">The current transaction</param>
        /// <param name="partition">The current partition</param>
        /// <param name="securityContext">The security context</param>
        /// <param name="newOldActualStateMap">The map that links the new to old <see cref="ActualFiniteState"/></param>
        /// <param name="newOldValueSetMap">The resulting map that links the new to old <see cref="ParameterValueSet"/></param>
        private void UpdateParameter(Parameter parameter, Iteration iteration, NpgsqlTransaction transaction, string partition, ISecurityContext securityContext, IReadOnlyDictionary <ActualFiniteState, ActualFiniteState> newOldActualStateMap, ref Dictionary <ParameterValueSet, ParameterValueSet> newOldValueSetMap)
        {
            var oldValueSets = this.ParameterValueSetService.GetShallow(transaction, partition, parameter.ValueSet, securityContext)
                               .Where(i => i is ParameterValueSet).Cast <ParameterValueSet>().ToList();

            if (parameter.IsOptionDependent)
            {
                foreach (var orderedItem in iteration.Option.OrderBy(x => x.K))
                {
                    var actualOption = Guid.Parse(orderedItem.V.ToString());
                    this.CreateParameterValueSets(parameter, actualOption, transaction, partition, securityContext, newOldActualStateMap, oldValueSets, ref newOldValueSetMap);
                }
            }
            else
            {
                this.CreateParameterValueSets(parameter, null, transaction, partition, securityContext, newOldActualStateMap, oldValueSets, ref newOldValueSetMap);
            }
        }
        public void VerifyThatMultipleIterationCanBeSynchronized()
        {
            var sitedir  = new Dto.SiteDirectory(Guid.NewGuid(), 0);
            var srdl1    = new Dto.SiteReferenceDataLibrary(Guid.NewGuid(), 0);
            var srdl2    = new Dto.SiteReferenceDataLibrary(Guid.NewGuid(), 0);
            var category = new Dto.Category(Guid.NewGuid(), 0);

            var modeldto      = new Dto.EngineeringModel(Guid.NewGuid(), 1);
            var iteration1dto = new Dto.Iteration(Guid.NewGuid(), 1);
            var iteration2dto = new Dto.Iteration(Guid.NewGuid(), 1);

            var element1dto = new Dto.ElementDefinition(Guid.NewGuid(), 1);

            element1dto.IterationContainerId = iteration1dto.Iid;
            element1dto.Category.Add(category.Iid);

            var element2dto = new Dto.ElementDefinition(element1dto.Iid, 1);

            element2dto.IterationContainerId = iteration2dto.Iid;
            element2dto.Category.Add(category.Iid);

            var usage1dto = new Dto.ElementUsage(Guid.NewGuid(), 1);

            usage1dto.IterationContainerId = iteration1dto.Iid;
            usage1dto.Category.Add(category.Iid);

            var usage2dto = new Dto.ElementUsage(usage1dto.Iid, 1);

            usage2dto.IterationContainerId = iteration2dto.Iid;
            usage2dto.Category.Add(category.Iid);

            sitedir.SiteReferenceDataLibrary.Add(srdl1.Iid);
            sitedir.SiteReferenceDataLibrary.Add(srdl2.Iid);
            srdl1.DefinedCategory.Add(category.Iid);

            modeldto.Iteration.Add(iteration1dto.Iid);
            modeldto.Iteration.Add(iteration2dto.Iid);

            iteration1dto.Element.Add(element1dto.Iid);
            iteration2dto.Element.Add(element2dto.Iid);

            element1dto.ContainedElement.Add(usage1dto.Iid);
            element2dto.ContainedElement.Add(usage2dto.Iid);

            var dtos = new List <Dto.Thing>
            {
                sitedir,
                srdl1,
                srdl2,
                category
            };

            var assembler = new Assembler(this.uri);

            assembler.Synchronize(dtos);

            dtos = new List <Dto.Thing>
            {
                modeldto,
                iteration1dto,
                iteration2dto,
                element1dto,
                element2dto,
                usage1dto,
                usage2dto
            };

            assembler.Synchronize(dtos);

            Assert.AreEqual(11, assembler.Cache.Count);
        }
 public IEnumerable <ReferenceDataLibrary> QueryReferenceDataLibrary(NpgsqlTransaction transaction, Iteration iteration)
 {
     return(this.dtos.OfType <ReferenceDataLibrary>());
 }
        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);
        }
Пример #6
0
        public void Setup()
        {
            this.securityContext = new Mock <ISecurityContext>();
            this.optionService   = new Mock <IOptionService>();
            this.actualFiniteStateListService = new Mock <IActualFiniteStateListService>();
            this.parameterService             = new Mock <ICompoundParameterTypeService>();
            this.valueSetService  = new Mock <IParameterValueSetService>();
            this.iterationService = new Mock <IIterationService>();
            this.parameterOverrideValueSetService     = new Mock <IParameterOverrideValueSetService>();
            this.parameterSubscriptionValueSetService = new Mock <IParameterSubscriptionValueSetService>();
            this.parameterSubscriptionService         = new Mock <IParameterSubscriptionService>();
            this.parameterOverrideService             = new Mock <IParameterOverrideService>();
            this.parameterTypeComponentService        = new Mock <IParameterTypeComponentService>();
            this.parameterTypeService        = new Mock <IParameterTypeService>();
            this.elementUsageService         = new Mock <IElementUsageService>();
            this.defaultValueArrayFactory    = new Mock <IDefaultValueArrayFactory>();
            this.OldParameterContextProvider = new Mock <IOldParameterContextProvider>();

            this.npgsqlTransaction = null;

            this.iteration = new Iteration(Guid.NewGuid(), 1);
            this.option1   = new Option(Guid.NewGuid(), 1);
            this.option2   = new Option(Guid.NewGuid(), 1);

            this.iteration.Option.Add(new OrderedItem {
                K = 1, V = this.option1.Iid
            });
            this.iteration.Option.Add(new OrderedItem {
                K = 2, V = this.option2.Iid
            });

            this.actualList   = new ActualFiniteStateList(Guid.NewGuid(), 1);
            this.actualState1 = new ActualFiniteState(Guid.NewGuid(), 1);
            this.actualState2 = new ActualFiniteState(Guid.NewGuid(), 1);

            this.actualList.ActualState.Add(this.actualState1.Iid);
            this.actualList.ActualState.Add(this.actualState2.Iid);

            this.parameter = new Parameter(Guid.NewGuid(), 1);

            this.cptParameterType = new CompoundParameterType(Guid.NewGuid(), 1);
            this.boolPt           = new BooleanParameterType(Guid.NewGuid(), 1);
            this.cpt1             = new ParameterTypeComponent(Guid.NewGuid(), 1)
            {
                ParameterType = this.boolPt.Iid
            };
            this.cpt2 = new ParameterTypeComponent(Guid.NewGuid(), 1)
            {
                ParameterType = this.boolPt.Iid
            };

            this.cptParameterType.Component.Add(new OrderedItem {
                K = 1, V = this.cpt1.Iid.ToString()
            });
            this.cptParameterType.Component.Add(new OrderedItem {
                K = 2, V = this.cpt2.Iid.ToString()
            });

            this.sideEffect = new ParameterSideEffect
            {
                IterationService                     = this.iterationService.Object,
                ActualFiniteStateListService         = this.actualFiniteStateListService.Object,
                ParameterValueSetService             = this.valueSetService.Object,
                ParameterOverrideValueSetService     = this.parameterOverrideValueSetService.Object,
                ParameterSubscriptionValueSetService = this.parameterSubscriptionValueSetService.Object,
                ParameterOverrideService             = this.parameterOverrideService.Object,
                ParameterSubscriptionService         = this.parameterSubscriptionService.Object,
                ParameterTypeService                 = this.parameterTypeService.Object,
                ElementUsageService                  = this.elementUsageService.Object,
                ParameterTypeComponentService        = this.parameterTypeComponentService.Object,
                OptionService                        = this.optionService.Object,
                DefaultValueArrayFactory             = this.defaultValueArrayFactory.Object,
                ParameterValueSetFactory             = new ParameterValueSetFactory(),
                ParameterOverrideValueSetFactory     = new ParameterOverrideValueSetFactory(),
                ParameterSubscriptionValueSetFactory = new ParameterSubscriptionValueSetFactory(),
                OldParameterContextProvider          = this.OldParameterContextProvider.Object
            };

            // prepare mock data
            this.elementDefinition = new ElementDefinition(Guid.NewGuid(), 1);
            this.elementDefinition.Parameter.Add(this.parameter.Iid);
            this.parameterOverride = new ParameterOverride(Guid.NewGuid(), 1)
            {
                Parameter = this.parameter.Iid,
            };
            this.elementUsage = new ElementUsage(Guid.NewGuid(), 1)
            {
                ElementDefinition = this.elementDefinition.Iid, ParameterOverride = { this.parameterOverride.Iid }
            };

            this.parameterService.Setup(x => x.Get(It.IsAny <NpgsqlTransaction>(), "SiteDirectory", It.Is <IEnumerable <Guid> >(y => y.Contains(this.cptParameterType.Iid)), this.securityContext.Object))
            .Returns(new List <Thing> {
                this.cptParameterType
            });

            this.iterationService.Setup(x => x.GetActiveIteration(null, "partition", this.securityContext.Object))
            .Returns(this.iteration);

            this.actualFiniteStateListService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(this.actualList.Iid)), this.securityContext.Object))
            .Returns(new List <Thing> {
                this.actualList
            });

            this.parameterTypeService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.boolPt, this.cptParameterType
            });

            this.parameterTypeService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", new List <Guid> {
                this.existingNotQuantityKindParameterTypeGuid
            }, this.securityContext.Object))
            .Returns(new List <Thing> {
                new BooleanParameterType(this.existingNotQuantityKindParameterTypeGuid, 1)
            });

            this.parameterTypeService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", new List <Guid> {
                this.existingQuantityKindParameterTypeGuid
            }, this.securityContext.Object))
            .Returns(new List <Thing> {
                new SimpleQuantityKind(this.existingQuantityKindParameterTypeGuid, 1)
            });

            this.parameterTypeService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", new List <Guid> {
                this.notExistingParameterTypeGuid
            }, this.securityContext.Object))
            .Returns(new List <Thing>());

            this.parameterTypeComponentService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.cpt1, this.cpt2
            });

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

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

            this.scalarDefaultValueArray = new ValueArray <string>(new List <string>()
            {
                "-"
            });
            this.compoundDefaultValueArray = new ValueArray <string>(new List <string>()
            {
                "-", "-"
            });

            this.defaultValueArrayFactory.Setup(x => x.CreateDefaultValueArray(this.cptParameterType.Iid))
            .Returns(this.compoundDefaultValueArray);

            this.defaultValueArrayFactory.Setup(x => x.CreateDefaultValueArray(this.boolPt.Iid))
            .Returns(this.scalarDefaultValueArray);

            this.OldParameterContextProvider.Setup(x => x.GetsourceValueSet(It.IsAny <Guid?>(), It.IsAny <Guid?>())).Returns((ParameterValueSet)null);
        }
        public void Setup()
        {
            this.securityContext = new Mock <ISecurityContext>();
            this.optionService   = new Mock <IOptionService>();
            this.actualFiniteStateListService = new Mock <IActualFiniteStateListService>();
            this.valueSetService  = new Mock <IParameterValueSetService>();
            this.iterationService = new Mock <IIterationService>();
            this.parameterOverrideValueSetService     = new Mock <IParameterOverrideValueSetService>();
            this.parameterSubscriptionValueSetService = new Mock <IParameterSubscriptionValueSetService>();
            this.parameterSubscriptionService         = new Mock <IParameterSubscriptionService>();
            this.parameterOverrideService             = new Mock <IParameterOverrideService>();
            this.elementUsageService         = new Mock <IElementUsageService>();
            this.defaultValueArrayFactory    = new Mock <IDefaultValueArrayFactory>();
            this.OldParameterContextProvider = new Mock <IOldParameterContextProvider>();
            this.cachedReferenceDataService  = new Mock <ICachedReferenceDataService>();

            this.organizationalParticipationResolverService = new Mock <IOrganizationalParticipationResolverService>();
            this.organizationalParticipationResolverService.Setup(x => x.ValidateCreateOrganizationalParticipation(It.IsAny <Thing>(), It.IsAny <Thing>(), It.IsAny <ISecurityContext>(), this.npgsqlTransaction, It.IsAny <string>()));

            this.npgsqlTransaction = null;

            this.iteration = new Iteration(Guid.NewGuid(), 1);
            this.option1   = new Option(Guid.NewGuid(), 1);
            this.option2   = new Option(Guid.NewGuid(), 1);

            this.iteration.Option.Add(new OrderedItem {
                K = 1, V = this.option1.Iid
            });
            this.iteration.Option.Add(new OrderedItem {
                K = 2, V = this.option2.Iid
            });

            this.actualList   = new ActualFiniteStateList(Guid.NewGuid(), 1);
            this.actualState1 = new ActualFiniteState(Guid.NewGuid(), 1);
            this.actualState2 = new ActualFiniteState(Guid.NewGuid(), 1);

            this.actualList.ActualState.Add(this.actualState1.Iid);
            this.actualList.ActualState.Add(this.actualState2.Iid);

            this.parameter = new Parameter(Guid.NewGuid(), 1);

            this.cptParameterType = new CompoundParameterType(Guid.NewGuid(), 1);
            this.boolPt           = new BooleanParameterType(Guid.NewGuid(), 1);
            this.cpt1             = new ParameterTypeComponent(Guid.NewGuid(), 1)
            {
                ParameterType = this.boolPt.Iid
            };
            this.cpt2 = new ParameterTypeComponent(Guid.NewGuid(), 1)
            {
                ParameterType = this.boolPt.Iid
            };

            this.cptParameterType.Component.Add(new OrderedItem {
                K = 1, V = this.cpt1.Iid.ToString()
            });
            this.cptParameterType.Component.Add(new OrderedItem {
                K = 2, V = this.cpt2.Iid.ToString()
            });

            this.sideEffect = new ParameterSideEffect
            {
                IterationService                     = this.iterationService.Object,
                ActualFiniteStateListService         = this.actualFiniteStateListService.Object,
                ParameterValueSetService             = this.valueSetService.Object,
                ParameterOverrideValueSetService     = this.parameterOverrideValueSetService.Object,
                ParameterSubscriptionValueSetService = this.parameterSubscriptionValueSetService.Object,
                ParameterOverrideService             = this.parameterOverrideService.Object,
                ParameterSubscriptionService         = this.parameterSubscriptionService.Object,
                ElementUsageService                  = this.elementUsageService.Object,
                OptionService                              = this.optionService.Object,
                DefaultValueArrayFactory                   = this.defaultValueArrayFactory.Object,
                ParameterValueSetFactory                   = new ParameterValueSetFactory(),
                ParameterOverrideValueSetFactory           = new ParameterOverrideValueSetFactory(),
                ParameterSubscriptionValueSetFactory       = new ParameterSubscriptionValueSetFactory(),
                OldParameterContextProvider                = this.OldParameterContextProvider.Object,
                OrganizationalParticipationResolverService = this.organizationalParticipationResolverService.Object,
                CachedReferenceDataService                 = this.cachedReferenceDataService.Object
            };

            // prepare mock data
            this.elementDefinition = new ElementDefinition(Guid.NewGuid(), 1);
            this.elementDefinition.Parameter.Add(this.parameter.Iid);

            this.parameterOverride = new ParameterOverride(Guid.NewGuid(), 1)
            {
                Parameter = this.parameter.Iid
            };

            this.elementUsage = new ElementUsage(Guid.NewGuid(), 1)
            {
                ElementDefinition = this.elementDefinition.Iid, ParameterOverride = { this.parameterOverride.Iid }
            };

            this.iterationService.Setup(x => x.GetActiveIteration(null, "partition", this.securityContext.Object))
            .Returns(this.iteration);

            this.actualFiniteStateListService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(this.actualList.Iid)), this.securityContext.Object))
            .Returns(new List <Thing> {
                this.actualList
            });

            var parameterTypeDictionary = new Dictionary <Guid, ParameterType>();

            parameterTypeDictionary.Add(this.cptParameterType.Iid, this.cptParameterType);
            parameterTypeDictionary.Add(this.boolPt.Iid, this.boolPt);

            this.cachedReferenceDataService.Setup(x => x.QueryParameterTypes(this.npgsqlTransaction, this.securityContext.Object))
            .Returns(parameterTypeDictionary);

            var parameterTypeComponentDictionary = new Dictionary <Guid, ParameterTypeComponent>();

            parameterTypeComponentDictionary.Add(this.cpt1.Iid, this.cpt1);
            parameterTypeComponentDictionary.Add(this.cpt2.Iid, this.cpt2);

            this.cachedReferenceDataService.Setup(x => x.QueryParameterTypeComponents(this.npgsqlTransaction, this.securityContext.Object))
            .Returns(parameterTypeComponentDictionary);

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

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

            this.scalarDefaultValueArray = new ValueArray <string>(new List <string> {
                "-"
            });
            this.compoundDefaultValueArray = new ValueArray <string>(new List <string> {
                "-", "-"
            });

            this.defaultValueArrayFactory.Setup(x => x.CreateDefaultValueArray(this.cptParameterType.Iid))
            .Returns(this.compoundDefaultValueArray);

            this.defaultValueArrayFactory.Setup(x => x.CreateDefaultValueArray(this.boolPt.Iid))
            .Returns(this.scalarDefaultValueArray);

            this.OldParameterContextProvider.Setup(x => x.GetsourceValueSet(It.IsAny <Guid?>(), It.IsAny <Guid?>())).Returns((ParameterValueSet)null);
        }
        /// <summary>
        /// Update all the relevant <see cref="CDP4Common.DTO.ParameterBase"/>
        /// </summary>
        /// <param name="actualFiniteStateList">The updated <see cref="CDP4Common.DTO.ActualFiniteStateList"/></param>
        /// <param name="iteration">The <see cref="CDP4Common.DTO.Iteration"/></param>
        /// <param name="transaction">The current transaction</param>
        /// <param name="partition">The current partition</param>
        /// <param name="securityContext">The security context</param>
        /// <param name="newOldActualStateMap">The map that links the new to old <see cref="CDP4Common.DTO.ActualFiniteState"/></param>
        public void UpdateAllStateDependentParameters(ActualFiniteStateList actualFiniteStateList, Iteration iteration, NpgsqlTransaction transaction, string partition, ISecurityContext securityContext, IReadOnlyDictionary <ActualFiniteState, ActualFiniteState> newOldActualStateMap)
        {
            if (iteration == null)
            {
                throw new ArgumentNullException("iteration");
            }

            var parameters = this.ParameterService.GetShallow(transaction, partition, null, securityContext).Where(i => i is Parameter).Cast <Parameter>()
                             .Where(x => x.StateDependence == actualFiniteStateList.Iid).ToList();
            var parameterOverrides = this.ParameterOverrideService.GetShallow(transaction, partition, null, securityContext).Where(i => i is ParameterOverride).Cast <ParameterOverride>()
                                     .Where(x => parameters.Select(p => p.Iid).Contains(x.Parameter)).ToList();

            // update the parameters with the new actual states
            var newOldParameterValueSetMap = new Dictionary <Parameter, IDictionary <ParameterValueSet, ParameterValueSet> >();

            foreach (var parameter in parameters)
            {
                var tmpMap = new Dictionary <ParameterValueSet, ParameterValueSet>();
                this.UpdateParameter(parameter, iteration, transaction, partition, securityContext, newOldActualStateMap, ref tmpMap);
                newOldParameterValueSetMap.Add(parameter, tmpMap);
            }

            // update the parameter override from the updated parameters
            var parameterOrOVerrideValueSetMap = new Dictionary <ParameterOrOverrideBase, IReadOnlyDictionary <ParameterValueSetBase, ParameterValueSetBase> >();

            foreach (var pair in newOldParameterValueSetMap)
            {
                parameterOrOVerrideValueSetMap.Add(pair.Key, pair.Value.ToDictionary(newSet => (ParameterValueSetBase)newSet.Key, oldSet => (ParameterValueSetBase)oldSet.Value));
            }

            foreach (var parameterOverride in parameterOverrides)
            {
                var tmpMap             = new Dictionary <ParameterValueSetBase, ParameterValueSetBase>();
                var overridenParameter = parameters.Single(x => x.Iid == parameterOverride.Parameter);
                this.UpdateParameterOverride(parameterOverride, transaction, partition, securityContext, newOldParameterValueSetMap[overridenParameter], ref tmpMap);
                parameterOrOVerrideValueSetMap.Add(parameterOverride, tmpMap);
            }

            // update the parameter subscription from the updated parameter/overide value sets
            var parameterOrOverrides   = parameters.Cast <ParameterOrOverrideBase>().Union(parameterOverrides).ToList();
            var parameterSubscriptions = this.ParameterSubscriptionService.GetShallow(transaction, partition, null, securityContext).Where(i => i is ParameterSubscription).Cast <ParameterSubscription>()
                                         .Where(x => parameterOrOverrides.SelectMany(p => p.ParameterSubscription).Contains(x.Iid));

            foreach (var parameterSubscription in parameterSubscriptions)
            {
                var subscribedParameterOrOverride = parameterOrOverrides.Single(x => x.ParameterSubscription.Contains(parameterSubscription.Iid));
                this.UpdateParameterSubscription(parameterSubscription, transaction, partition, securityContext, parameterOrOVerrideValueSetMap[subscribedParameterOrOverride]);
            }
        }