/// <summary>
        /// Moves a <see cref="File"/> to another <see cref="Folder"/> or <see cref="FileStore"/>
        /// A <see cref="File"/>'s parent folder is its latest <see cref="FileRevision"/>'s <see cref="FileRevision.ContainingFolder"/>.
        /// When <see cref="FileRevision.ContainingFolder"/> is null, that means that the <see cref="File"/> is located
        /// Moving a file means that a new <see cref="FileRevision"/> has to be created that has the destination parent folder set as its <see cref="FileRevision.ContainingFolder"/>.
        /// </summary>
        /// <param name="file"><The <see cref="File"/></param>
        /// <param name="destinationFolder">The destination <see cref="Folder"/></param>
        /// <param name="creator">The <see cref="Participant"/> that executes the move action</param>
        /// <param name="session">The <see cref="ISession"/></param>
        public static async Task MoveFile(this File file, Folder destinationFolder, Participant creator, ISession session)
        {
            var transactionContext   = TransactionContextResolver.ResolveContext(file);
            var containerClone       = file.TopContainer.Clone(false);
            var containerTransaction = new ThingTransaction(transactionContext, containerClone);

            var fileClone = file.Clone(false);

            var newFileRevision = file.CurrentFileRevision.CopyToNew(creator);

            fileClone.FileRevision.Add(newFileRevision);

            newFileRevision.ContainingFolder = destinationFolder;
            containerTransaction.CreateOrUpdate(fileClone);
            containerTransaction.CreateOrUpdate(newFileRevision);

            try
            {
                var operationContainer = containerTransaction.FinalizeTransaction();
                await session.Write(operationContainer);
            }
            catch (Exception ex)
            {
                throw new Exception($"Moving file failed: {ex.Message}");
            }
        }
Пример #2
0
        /// <summary>
        /// Performs the drop operation for a <see cref="RequirementsGroup"/> payload
        /// </summary>
        /// <param name="requirementGroupPayload">
        /// The <see cref="RequirementsGroup"/> that was dropped into this <see cref="RequirementsSpecification"/>
        /// </param>
        private async Task OnRequirementGroupDrop(RequirementsGroup requirementGroupPayload)
        {
            var context                 = TransactionContextResolver.ResolveContext(this.Thing);
            var transaction             = new ThingTransaction(context);
            var previousRequirementSpec = requirementGroupPayload.GetContainerOfType <RequirementsSpecification>();

            // Add the RequirementGroup to the RequirementsSpecification represented by this RowViewModel
            var requirementsSpecificationClone = this.Thing.Clone(false);

            requirementsSpecificationClone.Group.Add(requirementGroupPayload);
            transaction.CreateOrUpdate(requirementsSpecificationClone);

            if (previousRequirementSpec != this.Thing)
            {
                // Update the requirements that were inside any of the groups that have been dropped
                var previousRequirementSpecRow = ((RequirementsBrowserViewModel)this.ContainerViewModel).ReqSpecificationRows.Single(x => x.Thing == previousRequirementSpec);
                var droppedRequirementGroups   = requirementGroupPayload.ContainedGroup().ToList();
                droppedRequirementGroups.Add(requirementGroupPayload);
                foreach (var keyValuePair in previousRequirementSpecRow.requirementContainerGroupCache)
                {
                    if (!droppedRequirementGroups.Contains(keyValuePair.Value))
                    {
                        continue;
                    }

                    var requirementClone = keyValuePair.Key.Clone(false);
                    requirementClone.Group = null;
                    transaction.CreateOrUpdate(requirementClone);
                }
            }

            await this.DalWrite(transaction);
        }
Пример #3
0
        /// <summary>
        /// Toggles the favorite status of a thing.
        /// </summary>
        /// <typeparam name="T">The type on which to base the save.</typeparam>
        /// <param name="thing">The thing to persist/remove from persistence</param>
        /// <param name="session">The session in which to persist.</param>
        /// <returns>The empty task.</returns>
        public async Task ToggleFavorite <T>(ISession session, T thing) where T : Thing
        {
            var transaction = new ThingTransaction(TransactionContextResolver.ResolveContext(session.ActivePerson));

            var preferenceShortname = this.GetPreferenceShortname(typeof(T));
            var preference          = this.GetFavoritePreference(session, preferenceShortname);

            var userClone = session.ActivePerson.Clone(false);

            HashSet <Guid> valueSet;

            if (preference == null)
            {
                // if property not there, create it and add
                valueSet = new HashSet <Guid>
                {
                    thing.Iid
                };

                preference = new UserPreference(Guid.NewGuid(), null, null)
                {
                    ShortName = preferenceShortname
                };

                userClone.UserPreference.Add(preference);
                transaction.CreateOrUpdate(userClone);
            }
            else
            {
                // if property is there, see if thing is in the array, true => remove, false => append
                valueSet = this.GetIidsFromUserPreference(preference);

                if (valueSet.Contains(thing.Iid))
                {
                    valueSet.Remove(thing.Iid);
                }
                else
                {
                    valueSet.Add(thing.Iid);
                }

                preference = preference.Clone(false);
            }

            preference.Value = string.Join(",", valueSet);
            transaction.CreateOrUpdate(preference);

            try
            {
                var operationContainer = transaction.FinalizeTransaction();
                await session.Write(operationContainer);
            }
            catch (Exception ex)
            {
                logger.Error("The inline update operation failed: {0}", ex.Message);
            }
        }
Пример #4
0
        /// <summary>
        /// Performs the drop operation for a <see cref="RequirementsGroup"/> payload
        /// </summary>
        /// <param name="requirementGroup">
        /// The <see cref="RequirementsGroup"/> that was dropped into this <see cref="RequirementsGroup"/>
        /// </param>
        /// <param name="dropInfo">The <see cref="IDropInfo"/></param>
        private async Task OnRequirementGroupDrop(RequirementsGroup requirementGroup, IDropInfo dropInfo)
        {
            if (dropInfo.KeyStates == (DragDropKeyStates.LeftMouseButton | DragDropKeyStates.ControlKey))
            {
                // ordered-move
                var model   = (EngineeringModel)this.Thing.TopContainer;
                var orderPt = OrderHandlerService.GetOrderParameterType(model);

                if (orderPt == null)
                {
                    return;
                }

                var orderService = new RequirementsGroupOrderHandlerService(this.Session, orderPt);
                var transaction  = orderService.Insert(requirementGroup, this.Thing,
                                                       dropInfo.IsDroppedAfter ? InsertKind.InsertAfter : InsertKind.InsertBefore);
                await this.Session.Write(transaction.FinalizeTransaction());
            }
            else
            {
                var context                 = TransactionContextResolver.ResolveContext(this.Thing);
                var transaction             = new ThingTransaction(context);
                var previousRequirementSpec = requirementGroup.GetContainerOfType <RequirementsSpecification>();
                var currentRequirementSpec  = this.Thing.GetContainerOfType <RequirementsSpecification>();

                // Add this RequirementGroup to the RequirementGroup represented by this RowViewModel
                var requirementGroupClone          = requirementGroup.Clone(false);
                var containerRequirementGroupClone = this.Thing.Clone(false);
                containerRequirementGroupClone.Group.Add(requirementGroupClone);
                transaction.CreateOrUpdate(containerRequirementGroupClone);

                if (previousRequirementSpec != currentRequirementSpec)
                {
                    // Update the requirements that were inside any of the groups that have been dropped
                    var previousRequirementSpecRow =
                        (RequirementsSpecificationRowViewModel)
                        ((RequirementsBrowserViewModel)this.TopParentRow.ContainerViewModel).ReqSpecificationRows
                        .Single(x => x.Thing == previousRequirementSpec);
                    var droppedRequirementGroups = requirementGroup.ContainedGroup().ToList();
                    droppedRequirementGroups.Add(requirementGroup);
                    foreach (var keyValuePair in previousRequirementSpecRow.requirementContainerGroupCache)
                    {
                        if (!droppedRequirementGroups.Contains(keyValuePair.Value))
                        {
                            continue;
                        }

                        var requirementClone = keyValuePair.Key.Clone(false);
                        requirementClone.Group = null;
                        transaction.CreateOrUpdate(requirementClone);
                    }
                }

                await this.DalWrite(transaction);
            }
        }
Пример #5
0
        /// <summary>
        /// Performs the drop operation for a <see cref="RequirementsGroup"/> payload
        /// </summary>
        /// <param name="requirementGroupPayload">
        /// The <see cref="RequirementsGroup"/> that was dropped into this <see cref="RequirementsSpecification"/>
        /// </param>
        private async Task OnRequirementGroupDrop(RequirementsGroup requirementGroupPayload)
        {
            var firstRow = this.ContainedRows.OfType <RequirementsGroupRowViewModel>().FirstOrDefault();

            if (firstRow == null)
            {
                var context                 = TransactionContextResolver.ResolveContext(this.Thing);
                var transaction             = new ThingTransaction(context);
                var previousRequirementSpec = requirementGroupPayload.GetContainerOfType <RequirementsSpecification>();

                // Add the RequirementGroup to the RequirementsSpecification represented by this RowViewModel
                var requirementsSpecificationClone = this.Thing.Clone(false);
                requirementsSpecificationClone.Group.Add(requirementGroupPayload);
                transaction.CreateOrUpdate(requirementsSpecificationClone);

                if (previousRequirementSpec != this.Thing)
                {
                    // Update the requirements that were inside any of the groups that have been dropped
                    var previousRequirementSpecRow =
                        (RequirementsSpecificationRowViewModel)((RequirementsBrowserViewModel)this.ContainerViewModel)
                        .ReqSpecificationRows.Single(x => x.Thing == previousRequirementSpec);
                    var droppedRequirementGroups = requirementGroupPayload.ContainedGroup().ToList();
                    droppedRequirementGroups.Add(requirementGroupPayload);
                    foreach (var keyValuePair in previousRequirementSpecRow.requirementContainerGroupCache)
                    {
                        if (!droppedRequirementGroups.Contains(keyValuePair.Value))
                        {
                            continue;
                        }

                        var requirementClone = keyValuePair.Key.Clone(false);
                        requirementClone.Group = null;
                        transaction.CreateOrUpdate(requirementClone);
                    }
                }

                await this.DalWrite(transaction);
            }
            else
            {
                // insert before first
                var model   = (EngineeringModel)this.Thing.TopContainer;
                var orderPt = OrderHandlerService.GetOrderParameterType(model);

                if (orderPt == null)
                {
                    return;
                }

                var orderService = new RequirementsGroupOrderHandlerService(this.Session, orderPt);
                var transaction  = orderService.Insert(requirementGroupPayload, firstRow.Thing, InsertKind.InsertBefore);
                await this.Session.Write(transaction.FinalizeTransaction());
            }
        }
        /// <summary>
        /// Performs the drop operation
        /// </summary>
        /// <param name="dropInfo">
        /// Information about the drop operation.
        /// </param>
        public async Task Drop(IDropInfo dropInfo)
        {
            var termPayload = dropInfo.Payload as Term;

            if (termPayload == null)
            {
                return;
            }

            if (dropInfo.Effects == DragDropEffects.Move)
            {
                var termClone       = termPayload.Clone(false);
                var currentGlossary = (Glossary)this.Thing.Container.Clone(false);
                currentGlossary.Term.Add(termClone);

                var context     = TransactionContextResolver.ResolveContext(this.Thing);
                var transaction = new ThingTransaction(context);

                transaction.CreateOrUpdate(currentGlossary);
                await this.DalWrite(transaction);
            }
            else if (dropInfo.Effects == DragDropEffects.Copy)
            {
                throw new NotImplementedException("drag and drop on a different data-source is not implemented yet.");
            }
        }
Пример #7
0
        /// <summary>
        /// Executes the <see cref="CreateSubscriptionCommand"/>
        /// </summary>
        private async Task ExecuteCreateSubscriptionCommand()
        {
            if (this.SelectedThing == null)
            {
                return;
            }

            var parameterOrOverrideRow = this.SelectedThing as ParameterOrOverrideBaseRowViewModel;

            if (parameterOrOverrideRow == null)
            {
                return;
            }

            Tuple <DomainOfExpertise, Participant> tuple;

            this.Session.OpenIterations.TryGetValue(this.Thing.GetContainerOfType <Iteration>(), out tuple);

            var subscription = new ParameterSubscription
            {
                Owner = tuple.Item1
            };

            var transactionContext = TransactionContextResolver.ResolveContext(this.Thing);
            var transaction        = new ThingTransaction(transactionContext);

            var clone = parameterOrOverrideRow.Thing.Clone(false);

            transaction.Create(subscription);
            transaction.CreateOrUpdate(clone);
            clone.ParameterSubscription.Add(subscription);

            await this.DalWrite(transaction);
        }
        private async Task WriteParametersValueSets(Parameter parameter, int elementIndex)
        {
            var valueConfigPair =
                StressGeneratorConfiguration.ParamValueConfig.FirstOrDefault(pvc =>
                                                                             pvc.Key == parameter.ParameterType.ShortName);
            var parameterSwitchKind =
                elementIndex % 2 == 0 ? ParameterSwitchKind.MANUAL : ParameterSwitchKind.REFERENCE;
            var parameterValue = (valueConfigPair.Value + elementIndex).ToString(CultureInfo.InvariantCulture);
            var valueSetClone  = ParameterGenerator.UpdateValueSets(parameter.ValueSets,
                                                                    parameterSwitchKind, parameterValue);

            try
            {
                var transactionContext = TransactionContextResolver.ResolveContext(valueSetClone);
                var transaction        = new ThingTransaction(transactionContext);
                transaction.CreateOrUpdate(valueSetClone);
                var operationContainer = transaction.FinalizeTransaction();
                await this.configuration.Session.Write(operationContainer);

                this.NotifyMessage($"Successfully generated ValueSet (Published value: {parameterValue}) for parameter {parameter.ParameterType.Name} ({parameter.ParameterType.ShortName}).");
            }
            catch (Exception ex)
            {
                this.NotifyMessage($"Cannot update ValueSet (Published value: {parameterValue}) for parameter {parameter.ParameterType.Name} ({parameter.ParameterType.ShortName}). Exception: {ex.Message}");
            }
        }
Пример #9
0
        public void VerifyThatAnUnkownLanguageCodeCanBeLoaded()
        {
            var languageCode = "F6F40215-560D-4104-93E1-6452769FDACC";
            var content      = "content in an unknown language";

            var definition = new Definition()
            {
                LanguageCode = languageCode, Content = content
            };

            var requirement = new Requirement();
            var clone       = requirement.Clone(false);

            clone.Definition.Add(definition);

            var transactionContext = TransactionContextResolver.ResolveContext(this.siteDirectory);
            var transaction        = new ThingTransaction(transactionContext, null);

            transaction.CreateOrUpdate(clone);

            var vm = new DefinitionDialogViewModel(definition, transaction, this.session.Object, true, ThingDialogKind.Create, null, clone, null);

            Assert.AreEqual(vm.SelectedLanguageCode.Name, languageCode);
            Assert.AreEqual(vm.Content, content);
        }
Пример #10
0
        /// <summary>
        /// Method for creating a <see cref="BinaryRelationship"/> for requirement verification between a <see cref="ParameterOrOverrideBase"/> and a <see cref="RelationalExpression"/>.
        /// </summary>
        /// <param name="session">The <see cref="Session"/> for which the <see cref="BinaryRelationship"/> will be created</param>
        /// <param name="iteration">The <see cref="Iteration"/> for which the  <see cref="BinaryRelationship"/> will be created</param>
        /// <param name="parameter">The <see cref="ParameterOrOverrideBase"/> that acts as the source of the <see cref="BinaryRelationship"/></param>
        /// <param name="relationalExpression">The <see cref="RelationalExpression"/> that acts as the target of the <see cref="BinaryRelationship"/></param>
        /// <returns>An awaitable <see cref="Task"/></returns>
        public async Task CreateBinaryRelationshipForRequirementVerification(ISession session, Iteration iteration, ParameterOrOverrideBase parameter, RelationalExpression relationalExpression)
        {
            session.OpenIterations.TryGetValue(iteration, out var tuple);

            var binaryRelationship = new BinaryRelationship(Guid.NewGuid(), null, null)
            {
                Owner = tuple?.Item1
            };

            var transaction = new ThingTransaction(TransactionContextResolver.ResolveContext(relationalExpression));

            binaryRelationship.Container = iteration;
            binaryRelationship.Source    = parameter;
            binaryRelationship.Target    = relationalExpression;

            var iterationClone = iteration.Clone(false);

            iterationClone.Relationship.Add(binaryRelationship);
            transaction.CreateOrUpdate(iterationClone);
            transaction.Create(binaryRelationship);

            try
            {
                var operationContainer = transaction.FinalizeTransaction();
                await session.Write(operationContainer);
            }
            catch (Exception ex)
            {
                LogManager.GetLogger(typeof(Iteration).FullName).Error("The inline update operation failed: {0}", ex.Message);
            }
        }
        /// <summary>
        /// Move the value of reference value to manual value on value sets of parameters of specified element definition.
        /// The move is only done if the manual value = default value = "-"
        /// </summary>
        public void MoveReferenceValuesToManualValues()
        {
            foreach (var parameter in this.sessionService.Iteration.Element.Where(e => this.filterService.IsFilteredIn(e))
                     .SelectMany(e => e.Parameter).OrderBy(x => x.ParameterType.ShortName))
            {
                if (parameter.ParameterType is ScalarParameterType && this.filterService.IsParameterSpecifiedOrAny(parameter))
                {
                    var valueSet    = parameter.ValueSet.FirstOrDefault();
                    var refValue    = valueSet?.Reference;
                    var manualValue = valueSet?.Manual;

                    if (valueSet?.ValueSwitch == ParameterSwitchKind.REFERENCE && manualValue[0] == "-")
                    {
                        var valueSetClone = valueSet.Clone(true);
                        var transaction   = new ThingTransaction(TransactionContextResolver.ResolveContext(valueSetClone), valueSetClone);
                        valueSetClone.Manual[0]    = refValue[0];
                        valueSetClone.ValueSwitch  = ParameterSwitchKind.MANUAL;
                        valueSetClone.Reference[0] = "-";
                        transaction.CreateOrUpdate(valueSetClone);
                        this.sessionService.Transactions.Add(transaction);

                        Console.WriteLine($"Moved {parameter.UserFriendlyShortName} = {refValue[0]} ref value to manual value and changed switch to MANUAL");
                    }
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Create a <see cref="ThingTransaction"/> object from the <see cref="RequirementsSpecification"/>
        /// </summary>
        /// <returns>The <see cref="ThingTransaction"/></returns>
        private ThingTransaction CreateTransaction()
        {
            var transactionContext = TransactionContextResolver.ResolveContext(this.IterationClone);
            var transaction        = new ThingTransaction(transactionContext, this.IterationClone);

            foreach (var externalIdentifierMap in this.IterationClone.ExternalIdentifierMap)
            {
                transaction.CreateOrUpdate(externalIdentifierMap);
            }

            foreach (var specMap in this.thingFactory.SpecificationMap)
            {
                transaction.CreateDeep(specMap.Value);
            }

            foreach (var relationshipMap in this.thingFactory.SpecRelationMap)
            {
                transaction.CreateDeep(relationshipMap.Value);
            }

            foreach (var relationshipMap in this.thingFactory.RelationGroupMap)
            {
                transaction.CreateDeep(relationshipMap.Value);
            }

            return(transaction);
        }
Пример #13
0
        /// <summary>
        /// Execute the publication.
        /// </summary>
        public async void ExecutePublishCommand()
        {
            // get the list of parameters or overrides to publish
            var parametersOrOverrides = this.GetListOfParametersOrOverridesToPublish().ToList();

            // there must be some parameters selected. An empty publication is not possible.
            if (parametersOrOverrides.Count == 0)
            {
                MessageBox.Show(
                    "Please select at least one Parameter or Parameter Override to be published.",
                    "Publication",
                    MessageBoxButton.OK,
                    MessageBoxImage.Warning);

                return;
            }

            // fire off the publication
            var publication = new Publication(Guid.NewGuid(), null, null);
            var iteration   = this.Thing.Clone(false);

            iteration.Publication.Add(publication);

            publication.Container = iteration;

            publication.PublishedParameter = parametersOrOverrides;

            this.IsBusy = true;

            var transactionContext   = TransactionContextResolver.ResolveContext(this.Thing);
            var containerTransaction = new ThingTransaction(transactionContext, iteration);

            containerTransaction.CreateOrUpdate(publication);

            try
            {
                var operationContainer = containerTransaction.FinalizeTransaction();
                await this.Session.Write(operationContainer);

                // Unselecect the domain rows
                foreach (var domain in this.Domains)
                {
                    domain.ToBePublished = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("Publication failed: {0}", ex.Message),
                    "Publication Failed",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
            finally
            {
                this.IsBusy = false;
            }
        }
        /// <summary>
        /// Creates an new <see cref="ElementDefinition"/> on the connected data-source and updates and valuesests of created contained parameters
        /// </summary>
        /// <param name="session">
        /// The active <see cref="ISession"/> used to write to the data-source
        /// </param>
        /// <param name="iteration">
        /// The <see cref="Iteration"/> that the template <see cref="ElementDefinition"/> is to be added to
        /// </param>
        /// <param name="elementDefinition">
        /// the template <see cref="ElementDefinition"/> that is to be created.
        /// </param>
        /// <returns>
        /// an awaitable task
        /// </returns>
        public static async Task CreateElementDefinitionFromTemplate(ISession session, Iteration iteration, ElementDefinition elementDefinition)
        {
            var owner = session.QuerySelectedDomainOfExpertise(iteration);

            if (owner == null)
            {
                return;
            }

            elementDefinition.Owner = owner;
            foreach (var parameter in elementDefinition.Parameter)
            {
                parameter.Owner = owner;
            }

            var clonedParameters = new List <Parameter>();

            foreach (var parameter in elementDefinition.Parameter)
            {
                clonedParameters.Add(parameter.Clone(true));

                parameter.ValueSet.Clear();
            }

            var transactionContext = TransactionContextResolver.ResolveContext(iteration);
            var iterationClone     = iteration.Clone(false);

            var createTransaction = new ThingTransaction(transactionContext);

            createTransaction.CreateDeep(elementDefinition, iterationClone);
            var createOperationContainer = createTransaction.FinalizeTransaction();
            await session.Write(createOperationContainer);

            var createdElementDefinition = iteration.Element.SingleOrDefault(x => x.Iid == elementDefinition.Iid);

            if (createdElementDefinition != null)
            {
                var updateTransaction = new ThingTransaction(transactionContext);

                foreach (var parameter in createdElementDefinition.Parameter)
                {
                    var clonedParameter =
                        clonedParameters.SingleOrDefault(x => x.ParameterType.Iid == parameter.ParameterType.Iid);
                    if (clonedParameter != null)
                    {
                        var parameterValueSet        = parameter.ValueSet[0];
                        var clonedParameterValuesSet = parameterValueSet.Clone(false);
                        clonedParameterValuesSet.Manual = clonedParameter.ValueSet[0].Manual;

                        updateTransaction.CreateOrUpdate(clonedParameterValuesSet);
                    }
                }

                var updateOperationContainer = updateTransaction.FinalizeTransaction();
                await session.Write(updateOperationContainer);
            }
        }
Пример #15
0
        /// <summary>
        /// Update the value switch and create a transaction to persist the change
        /// </summary>
        /// <param name="parameterSubscriptionValueSet">the value set on to change the value switch</param>
        private void UpdateValueSwitch(ParameterSubscriptionValueSet parameterSubscriptionValueSet)
        {
            var thingClone  = parameterSubscriptionValueSet.Clone(true);
            var transaction = new ThingTransaction(TransactionContextResolver.ResolveContext(thingClone), thingClone);

            thingClone.ValueSwitch = this.commandArguments.ParameterSwitchKind.Value;
            transaction.CreateOrUpdate(thingClone);
            this.sessionService.Transactions.Add(transaction);
        }
Пример #16
0
        /// <summary>
        /// Performs the drop operation for a <see cref="Requirement"/> payload
        /// </summary>
        /// <param name="requirement">
        /// The <see cref="Requirement"/> that was dropped into this <see cref="RequirementsGroup"/>
        /// </param>
        private async Task OnRequirementDrop(Requirement requirement)
        {
            var context                  = TransactionContextResolver.ResolveContext(this.Thing);
            var transaction              = new ThingTransaction(context);
            var requirementClone         = requirement.Clone(false);
            var requirementSpecification = this.Thing.GetContainerOfType <RequirementsSpecification>();

            requirementClone.Group = this.Thing;
            transaction.CreateOrUpdate(requirementClone);
            if (requirement.Container != requirementSpecification)
            {
                var requirementSpecificationClone = requirementSpecification.Clone(false);
                requirementSpecificationClone.Requirement.Add(requirementClone);
                transaction.CreateOrUpdate(requirementSpecificationClone);
            }

            await this.DalWrite(transaction);
        }
 /// <summary>
 /// Move the parameter to the given parameter group.
 /// </summary>
 /// <param name="parameter">The <see cref="Parameter" /> whose group will change</param>
 /// <param name="group">The <see cref="ParameterGroup" /></param>
 /// <param name="transaction">the <see cref="ThingTransaction" /> holding the changes to persist</param>
 private void MoveParameterToGroup(ParameterBase parameter, ParameterGroup group, ThingTransaction transaction)
 {
     if (parameter != null && group != null && parameter.Group != group)
     {
         parameter.Group = group;
         transaction.CreateOrUpdate(parameter);
         Console.WriteLine($"Moved parameter {parameter.ParameterType.ShortName} to group {group.Name}");
     }
 }
Пример #18
0
        /// <summary>
        /// Performs the drop operation for a <see cref="Requirement"/> payload
        /// </summary>
        /// <param name="requirement">
        /// The <see cref="Requirement"/> that was dropped into this <see cref="RequirementsSpecification"/>
        /// </param>
        private async Task OnRequirementDrop(Requirement requirement)
        {
            var context     = TransactionContextResolver.ResolveContext(this.Thing);
            var transaction = new ThingTransaction(context);

            var requirementClone = requirement.Clone(false);

            requirementClone.Group = null;
            transaction.CreateOrUpdate(requirementClone);

            if (requirement.Container != this.Thing)
            {
                // Add the requirement to the RequirementSpecification represented by this RowViewModel
                var requirementSpecificationClone = this.Thing.Clone(false);
                requirementSpecificationClone.Requirement.Add(requirement);
                transaction.CreateOrUpdate(requirementSpecificationClone);
            }

            await this.DalWrite(transaction);
        }
Пример #19
0
        /// <summary>
        /// Change the container of the <paramref name="reqContainerToInsert"/> to insert
        /// </summary>
        /// <param name="transaction">The current transaction</param>
        /// <param name="reqContainerToInsert">The <see cref="RequirementsContainer"/> to insert</param>
        /// <param name="referenceGroup">The <see cref="RequirementsContainer"/> to insert before or after</param>
        protected override void ChangeContainer(ThingTransaction transaction, RequirementsContainer reqContainerToInsert, RequirementsContainer referenceGroup)
        {
            // create a clone if there is none
            var reqToInsertClone = (RequirementsGroup)transaction.UpdatedThing.SingleOrDefault(x => x.Key.Iid == reqContainerToInsert.Iid).Value;

            if (reqToInsertClone == null)
            {
                reqToInsertClone = (RequirementsGroup)reqContainerToInsert.Clone(false);
                transaction.CreateOrUpdate(reqToInsertClone);
            }

            // change container if necessary
            if (reqContainerToInsert.Container != referenceGroup.Container)
            {
                var reqContainerClone = (RequirementsContainer)referenceGroup.Container.Clone(false);

                reqContainerClone.Group.Add(reqToInsertClone);
                transaction.CreateOrUpdate(reqContainerClone);
            }
        }
Пример #20
0
        /// <summary>
        /// Posts a reorder of elements in <see cref="PossibleFiniteStateList"/>
        /// </summary>
        private void PostPossibleFiniteStateListReorder()
        {
            if (this.session.OpenIterations.Count == 0)
            {
                Console.WriteLine("At first an iteration should be opened");
                return;
            }

            var iteration = this.session.OpenIterations.Keys.First();

            if (iteration != null)
            {
                var iterationClone = iteration.Clone(false);
                var pfsl           = iteration.PossibleFiniteStateList.First(x => x.Name.Equals("PossibleFiniteStateList1"));

                if (pfsl == null)
                {
                    Console.WriteLine("There is not a predefined PossibleFiniteStateList. Execute post_pfsl");
                    return;
                }

                var pfslClone = pfsl.Clone(true);

                // make sure keys are preserved
                var itemsMap = new Dictionary <object, long>();
                pfsl.PossibleState.ToDtoOrderedItemList()
                .ToList().ForEach(x => itemsMap.Add(x.V, x.K));
                var orderedItems = new List <OrderedItem>();
                pfslClone.PossibleState.SortedItems.Values.ToList().ForEach(x =>
                {
                    itemsMap.TryGetValue(x.Iid, out var value);
                    var orderedItem = new OrderedItem {
                        K = value, V = x
                    };
                    orderedItems.Add(orderedItem);
                });

                pfslClone.PossibleState.Clear();
                pfslClone.PossibleState.AddOrderedItems(orderedItems);
                pfslClone.ModifiedOn = DateTime.Now;

                pfslClone.PossibleState.Move(1, 0);
                var transaction = new ThingTransaction(
                    TransactionContextResolver.ResolveContext(iterationClone),
                    iterationClone);
                transaction.CreateOrUpdate(pfslClone);

                this.session.Write(transaction.FinalizeTransaction()).GetAwaiter().GetResult();

                this.PrintCacheCount();

                this.PrintCommands();
            }
        }
Пример #21
0
        /// <summary>
        /// given actual finite state list as state dependence from selected parameters and overrides
        /// </summary>
        /// <param name="isStateDependencyToBeRemoved">the value whether the state dependency is to be removed</param>
        public void ApplyOrRemoveStateDependency(bool isStateDependencyToBeRemoved)
        {
            if (!this.commandArguments.SelectedParameters.Any())
            {
                Console.WriteLine("No --parameters given. Apply state dependence skipped.");
                return;
            }

            var actualFiniteStateList = this.sessionService.Iteration.ActualFiniteStateList.SingleOrDefault(x => x.ShortName == this.commandArguments.StateListName);

            if (actualFiniteStateList == null)
            {
                Console.WriteLine($"Cannot find Actual Finite State List \"{this.commandArguments.StateListName}\". Apply state dependence skipped.");
                return;
            }

            Console.WriteLine($"{(isStateDependencyToBeRemoved ? "Removing" : "Applying")} state dependency \"{this.commandArguments.StateListName}\"");

            foreach (var elementDefinition in this.sessionService.Iteration.Element.OrderBy(x => x.ShortName))
            {
                if (!this.filterService.IsFilteredIn(elementDefinition))
                {
                    continue;
                }

                // Visit all parameters in the element definitions and make the selected ones dependent on the given state if not already
                foreach (var parameter in elementDefinition.Parameter.Where(p => this.commandArguments.SelectedParameters.Contains(p.ParameterType.ShortName)).OrderBy(x => x.ParameterType.ShortName))
                {
                    //  if there is no dependency yet or another one than the one specified and the state dependency was set to be added
                    //OR
                    //  there is a state dependency set already and it is the same state as the one specified and the state dependency was set to removed
                    if ((parameter.StateDependence == null || parameter.StateDependence.Iid != actualFiniteStateList.Iid) &&
                        !isStateDependencyToBeRemoved ||
                        parameter.StateDependence != null && parameter.StateDependence.Iid == actualFiniteStateList.Iid &&
                        isStateDependencyToBeRemoved)
                    {
                        var parameterClone = parameter.Clone(true);
                        var transaction    = new ThingTransaction(TransactionContextResolver.ResolveContext(parameterClone), parameterClone);
                        parameterClone.StateDependence = isStateDependencyToBeRemoved ? null : actualFiniteStateList;
                        transaction.CreateOrUpdate(parameterClone);
                        this.sessionService.Transactions.Add(transaction);

                        Console.WriteLine(
                            isStateDependencyToBeRemoved
                                ? $"State {this.commandArguments.StateListName} removed from Parameter {parameter.UserFriendlyShortName}, changed from {parameter.StateDependence.ShortName}"
                                : $"State {this.commandArguments.StateListName} applied to Parameter {parameter.UserFriendlyShortName}");
                    }
                    else
                    {
                        Console.WriteLine($"State {this.commandArguments.StateListName} was already {(isStateDependencyToBeRemoved ? "removed" : "applied")} to Parameter {parameter.UserFriendlyShortName}");
                    }
                }
            }
        }
        /// <summary>
        /// Saves the <see cref="T"/> as a value for a specific key
        /// </summary>
        /// <param name="session">The session in which to persist.</param>
        /// <param name="userPreferenceKey">The key for which we want to store <see cref="UserPreference.Value"/></param>
        /// <param name="userPreferenceValue">The <see cref="T"/></param>
        /// <returns>An awaitable task.</returns>
        public async Task SaveUserPreference <T>(ISession session, string userPreferenceKey, T userPreferenceValue) where T : class
        {
            var transaction = new ThingTransaction(TransactionContextResolver.ResolveContext(session.ActivePerson));

            var preference = this.GetUserPreference(session, userPreferenceKey);

            var userClone = session.ActivePerson.Clone(false);

            if (preference == null)
            {
                // if property not there, create it and add
                preference = new UserPreference(Guid.NewGuid(), null, null)
                {
                    ShortName = userPreferenceKey
                };

                userClone.UserPreference.Add(preference);
                transaction.CreateOrUpdate(userClone);
            }
            else
            {
                preference = preference.Clone(false);
            }

            var values = JsonConvert.SerializeObject(userPreferenceValue);

            preference.Value = values;
            transaction.CreateOrUpdate(preference);

            try
            {
                var operationContainer = transaction.FinalizeTransaction();
                await session.Write(operationContainer);
            }
            catch (Exception ex)
            {
                logger.Error("The inline update operation failed: {0}", ex.Message);
                throw;
            }
        }
Пример #23
0
        /// <summary>
        /// Creates a <see cref="MultiRelationship"/>
        /// </summary>
        /// <param name="relatableThings">The list of <see cref="Thing"/> that this relationship will apply to.</param>
        /// <param name="rule">The <see cref="MultiRelationshipRule"/> that defines this relationship.</param>
        private async void CreateMultiRelationship(IEnumerable <Thing> relatableThings, MultiRelationshipRule rule)
        {
            // send off the relationship
            Tuple <DomainOfExpertise, Participant> tuple;

            this.Session.OpenIterations.TryGetValue(this.Thing, out tuple);
            var multiRelationship = new MultiRelationship(Guid.NewGuid(), null, null)
            {
                Owner = tuple.Item1
            };

            if (rule != null)
            {
                multiRelationship.Category.Add(rule.RelationshipCategory);
            }

            var iteration = this.Thing.Clone(false);

            iteration.Relationship.Add(multiRelationship);

            multiRelationship.Container = iteration;

            multiRelationship.RelatedThing = relatableThings.ToList();

            var transactionContext = TransactionContextResolver.ResolveContext(this.Thing);

            var containerTransaction = new ThingTransaction(transactionContext, iteration);

            containerTransaction.CreateOrUpdate(multiRelationship);

            try
            {
                var operationContainer = containerTransaction.FinalizeTransaction();
                await this.Session.Write(operationContainer);

                // at this point relationship has gone through.
                var returedRelationship =
                    this.Thing.Relationship.FirstOrDefault(r => r.Iid == multiRelationship.Iid) as MultiRelationship;

                if (returedRelationship != null)
                {
                    this.CreateMultiRelationshipDiagramConnector(returedRelationship);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Creation of Binary Relationship failed: {0}", ex.Message),
                                "Binary Relationship Failed",
                                MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #24
0
        /// <summary>
        /// Execute the <see cref="CreateCommand"/>
        /// </summary>
        private async Task ExecuteCreateParameterOverride()
        {
            if (this.SelectedThing == null)
            {
                return;
            }

            var elementUsage = this.SelectedThing.ContainerViewModel.Thing as ElementUsage;

            if (elementUsage == null)
            {
                return;
            }

            var parameter = this.SelectedThing.Thing as Parameter;

            if (parameter == null)
            {
                return;
            }

            Tuple <DomainOfExpertise, Participant> tuple;

            this.Session.OpenIterations.TryGetValue(this.Thing.GetContainerOfType <Iteration>(), out tuple);

            var parameterOverride = new ParameterOverride
            {
                Parameter = parameter,
                Owner     = tuple.Item1
            };


            var transactionContext = TransactionContextResolver.ResolveContext(elementUsage);
            var transaction        = new ThingTransaction(transactionContext);

            transaction.Create(parameterOverride);

            var clone = elementUsage.Clone(false);

            transaction.CreateOrUpdate(clone);
            clone.ParameterOverride.Add(parameterOverride);

            await this.DalWrite(transaction);
        }
Пример #25
0
        /// <summary>
        /// Handles the drop action of a <see cref="Tuple{ParameterType, MeasurementScale}"/>
        /// </summary>
        /// <param name="tuple">The <see cref="Tuple{ParameterType, MeasurementScale}"/></param>
        private async Task Drop(Tuple <ParameterType, MeasurementScale> tuple)
        {
            var clone = this.Thing.Clone(false);

            var parameterValue = new SimpleParameterValue();

            parameterValue.ParameterType = tuple.Item1;
            parameterValue.Scale         = tuple.Item2;
            parameterValue.Value         = new ValueArray <string>(new [] { "-" });

            clone.ParameterValue.Add(parameterValue);

            var transaction = new ThingTransaction(TransactionContextResolver.ResolveContext(this.Thing));

            transaction.Create(parameterValue);
            transaction.CreateOrUpdate(clone);

            await this.DalWrite(transaction);
        }
Пример #26
0
        public void VerifyThatDialogViewModelCanLoadIfLanguageCodeIsNull()
        {
            var definition = new Definition()
            {
                LanguageCode = null, Content = null
            };

            var requirement = new Requirement();
            var clone       = requirement.Clone(false);

            clone.Definition.Add(definition);

            var transactionContext = TransactionContextResolver.ResolveContext(this.siteDirectory);
            var transaction        = new ThingTransaction(transactionContext, null);

            transaction.CreateOrUpdate(clone);

            Assert.DoesNotThrow(() => new DefinitionDialogViewModel(definition, transaction, this.session.Object, true, ThingDialogKind.Create, null, clone, null));
        }
Пример #27
0
        /// <summary>
        /// Send the update operation for this <see cref="ElementUsage"/> related to its excluded <see cref="Option"/>
        /// </summary>
        private void SendUpdateExcludedOptionOperation()
        {
            if (this.ExcludedOptions.OrderBy(x => x.ShortName).SequenceEqual(this.Thing.ExcludeOption.OrderBy(x => x.ShortName)))
            {
                return;
            }


            var clone = this.Thing.Clone(false);

            clone.ExcludeOption = new List <Option>(this.ExcludedOptions);

            var transactionContext = TransactionContextResolver.ResolveContext(this.Thing);
            var transaction        = new ThingTransaction(transactionContext);

            transaction.CreateOrUpdate(clone);

            this.DalWrite(transaction);
        }
Пример #28
0
        /// <summary>
        /// Execute the <see cref="CreateCommand"/>
        /// </summary>
        private async Task ExecuteCreateParameterOverride()
        {
            if (this.SelectedThing == null)
            {
                return;
            }

            var elementUsage = this.SelectedThing.ContainerViewModel.Thing as ElementUsage;

            if (elementUsage == null)
            {
                return;
            }

            var parameter = this.SelectedThing.Thing as Parameter;

            if (parameter == null)
            {
                return;
            }

            this.Session.OpenIterations.TryGetValue(this.Thing, out var tuple);

            if (tuple != null)
            {
                var parameterOverride = new ParameterOverride
                {
                    Parameter = parameter,
                    Owner     = tuple.Item1
                };

                var transactionContext = TransactionContextResolver.ResolveContext(elementUsage);
                var transaction        = new ThingTransaction(transactionContext);

                transaction.Create(parameterOverride);

                var elementUsageClone = elementUsage.Clone(false);
                transaction.CreateOrUpdate(elementUsageClone);
                elementUsageClone.ParameterOverride.Add(parameterOverride);

                await this.DalWrite(transaction);
            }
        }
Пример #29
0
        /// <summary>
        /// Execute the <see cref="SetDefaultCommand"/> command
        /// </summary>
        private async Task ExecuteSetDefaultCommand()
        {
            var possibleStateRow = this.SelectedThing as PossibleFiniteStateRowViewModel;

            if (possibleStateRow == null)
            {
                return;
            }

            var list = (PossibleFiniteStateList)possibleStateRow.Thing.Container;

            var transactionContext = TransactionContextResolver.ResolveContext(this.Thing);
            var transaction        = new ThingTransaction(transactionContext);
            var clone = list.Clone(false);

            clone.DefaultState = possibleStateRow.Thing.Clone(false);

            transaction.CreateOrUpdate(clone);
            await this.DalWrite(transaction);
        }
Пример #30
0
        /// <summary>
        /// removes the <see cref="Category"/> from the selected <see cref="ICategorizableThing"/>
        /// </summary>
        /// <param name="category">
        /// The <see cref="Category"/> that is to be removed,
        /// </param>
        private async void RemoveCategoryFromSelectedThing(Thing category)
        {
            if (!(category is Category categoryToRemove))
            {
                return;
            }

            if (!(this.SelectedThing.Thing is ICategorizableThing))
            {
                return;
            }

            var clone = this.SelectedThing.Thing.Clone(false);
            var categorizableClone = clone as ICategorizableThing;

            categorizableClone.Category.Remove(categoryToRemove);

            var transactionContext = TransactionContextResolver.ResolveContext(this.Thing);
            var transaction        = new ThingTransaction(transactionContext, clone);

            transaction.CreateOrUpdate(clone);

            try
            {
                this.IsBusy = true;
                await this.Session.Write(transaction.FinalizeTransaction());

                logger.Info("Category {0} removed from from {1}", categoryToRemove.ShortName, this.SelectedThing.Thing.ClassKind);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "An error was produced when removing Category {0} from {1}", categoryToRemove.ShortName, this.SelectedThing.Thing.ClassKind);
                this.Feedback = ex.Message;
            }
            finally
            {
                this.IsBusy = false;
            }
        }