Ejemplo n.º 1
0
        /// <summary>
        /// Deletes a <see cref="BinaryRelationship" /> for the selected pair of thing
        /// </summary>
        /// <param name="direction">The direction of the relationship to delete</param>
        /// <returns>The task</returns>
        private Task DeleteRelationship(RelationshipDirectionKind direction)
        {
            if (!(this.SelectedCell is MatrixCellViewModel vm))
            {
                return(Task.FromResult(0));
            }

            var iterationClone = this.iteration.Clone(false);
            var context        = TransactionContextResolver.ResolveContext(iterationClone);
            var transaction    = new ThingTransaction(context, iterationClone);

            foreach (var binaryRelationship in vm.Relationships)
            {
                var clone = binaryRelationship.Clone(false);

                if (vm.RelationshipDirection != RelationshipDirectionKind.BiDirectional ||
                    direction == RelationshipDirectionKind.BiDirectional)
                {
                    // delete every relationship
                    transaction.Delete(clone);
                }
                else if (direction == RelationshipDirectionKind.RowThingToColumnThing &&
                         vm.SourceY.Iid == binaryRelationship.Source.Iid)
                {
                    transaction.Delete(clone);
                }
                else if (direction == RelationshipDirectionKind.ColumnThingToRowThing &&
                         vm.SourceX.Iid == binaryRelationship.Source.Iid)
                {
                    transaction.Delete(clone);
                }
            }

            return(this.session.Write(transaction.FinalizeTransaction()));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Removes the first found <see cref="Parameter"/> from the first found <see cref="ElementDefinition"/>
        /// </summary>
        private void RemoveParameter()
        {
            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 elementDefinition      = iteration.Element[0];
                var elementDefinitionClone = elementDefinition.Clone(false);
                var parameterClone         = elementDefinition.Parameter[0].Clone(false);

                var transaction = new ThingTransaction(
                    TransactionContextResolver.ResolveContext(elementDefinitionClone),
                    elementDefinitionClone);
                transaction.Delete(parameterClone, elementDefinitionClone);

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

                this.PrintCacheCount();

                this.PrintCommands();
            }
        }
        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}");
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Posts a predefined <see cref="Parameter"/>
        /// </summary>
        private void PostParameter()
        {
            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 elementDefinition      = iteration.Element[0];
                var elementDefinitionClone = elementDefinition.Clone(false);
                this.session.OpenIterations.TryGetValue(iteration, out var tuple);
                var domainOfExpertise = tuple.Item1;

                var parameter = new Parameter(Guid.NewGuid(), this.session.Assembler.Cache, this.uri);
                parameter.ParameterType = this.session.Assembler.Cache.Values.Select(x => x.Value)
                                          .OfType <ParameterType>().First();
                parameter.Owner = domainOfExpertise;

                var transaction = new ThingTransaction(
                    TransactionContextResolver.ResolveContext(elementDefinitionClone),
                    elementDefinitionClone);
                transaction.Create(parameter, elementDefinitionClone);

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

                this.PrintCacheCount();

                this.PrintCommands();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a <see cref="BinaryRelationship" /> for the selected cell
        /// </summary>
        /// <param name="direction">The direction fo the relationship to create</param>
        /// <returns>The task</returns>
        private Task CreateRelationship(RelationshipDirectionKind direction)
        {
            var vm = this.SelectedCell as MatrixCellViewModel;

            if (vm == null)
            {
                return(Task.FromResult(0));
            }

            var relationship = new BinaryRelationship(Guid.NewGuid(), null, null)
            {
                Owner = this.session.OpenIterations[this.iteration].Item1
            };

            relationship.Category.Add(vm.Rule.RelationshipCategory);

            relationship.Source =
                direction == RelationshipDirectionKind.RowThingToColumnThing ? vm.SourceY : vm.SourceX;

            relationship.Target =
                direction == RelationshipDirectionKind.RowThingToColumnThing ? vm.SourceX : vm.SourceY;

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

            iterationClone.Relationship.Add(relationship);

            var context     = TransactionContextResolver.ResolveContext(relationship);
            var transaction = new ThingTransaction(context, iterationClone);

            transaction.Create(relationship, iterationClone);

            return(this.session.Write(transaction.FinalizeTransaction()));
        }
        /// <summary>
        /// Updates multiple subscriptions in one batch operation
        /// </summary>
        /// <param name="session">
        /// The <see cref="ISession"/> that is used to communicate with the selected data source
        /// </param>
        /// <param name="iteration">
        /// The container <see cref="Iteration"/> in which the subscriptions are to be updated
        /// </param>
        /// <param name="isUncategorizedIncluded">
        /// A value indication whether <see cref="Parameter"/>s contained by <see cref="ElementDefinition"/>s that are
        /// not a member of a <see cref="Category"/> shall be included or not
        /// </param>
        /// <param name="categories">
        /// An <see cref="IEnumerable{Category}"/> that is a selection criteria to select the <see cref="Parameter"/>s to which
        /// <see cref="ParameterSubscription"/>s need to be updated
        /// </param>
        /// <param name="domainOfExpertises"></param>
        /// An <see cref="IEnumerable{DomainOfExpertise}"/> that is a selection criteria to select the <see cref="Parameter"/>s to which
        /// <see cref="ParameterSubscription"/>s need to be updated
        /// <param name="parameterTypes">
        /// An <see cref="IEnumerable{ParameterType}"/> that is a selection criteria to select the <see cref="Parameter"/>s to which
        /// <see cref="ParameterSubscription"/>s need to be updated
        /// </param>
        /// <param name="updateAction">
        /// An <see cref="Action{IThingTransaction, ParameterOrOverrideBase, ParameterSubscription}"/> that specified that update action to be performed
        /// </param>
        /// <returns>
        /// an awaitable <see cref="Task"/>
        /// </returns>
        private async Task Update(ISession session,
                                  Iteration iteration,
                                  bool isUncategorizedIncluded,
                                  IEnumerable <Category> categories,
                                  IEnumerable <DomainOfExpertise> domainOfExpertises,
                                  IEnumerable <ParameterType> parameterTypes,
                                  Action <IThingTransaction, ParameterOrOverrideBase, ParameterSubscription> updateAction,
                                  Func <IEnumerable <Parameter>, bool> confirmationCallBack = null)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session), $"The {nameof(session)} may not be null");
            }

            if (iteration == null)
            {
                throw new ArgumentNullException(nameof(iteration), $"The {nameof(iteration)} may not be null");
            }

            if (parameterTypes == null)
            {
                throw new ArgumentNullException(nameof(parameterTypes), $"The {nameof(parameterTypes)} may not be null");
            }

            if (categories == null)
            {
                throw new ArgumentNullException(nameof(categories), $"The {nameof(categories)} may not be null");
            }

            if (domainOfExpertises == null)
            {
                throw new ArgumentNullException(nameof(domainOfExpertises), $"The {nameof(domainOfExpertises)} may not be null");
            }

            var owner = session.QuerySelectedDomainOfExpertise(iteration);

            var parameters = this.QueryParameters(iteration, owner, isUncategorizedIncluded, categories, domainOfExpertises, parameterTypes);

            if (!parameters.Any())
            {
                return;
            }

            if (confirmationCallBack?.Invoke(parameters.Where(p => p.ParameterSubscription.Any(s => s.Owner == owner))) == false)
            {
                return;
            }

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

            this.UpdateTransactionWithParameterSubscriptions(transaction, owner, parameters, updateAction);

            var updateOperationContainer = transaction.FinalizeTransaction();


            await session.Write(updateOperationContainer);
        }
Ejemplo n.º 7
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;
            }
        }
Ejemplo n.º 8
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);
            }
        }
        /// <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);
            }
        }
Ejemplo n.º 10
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();
            }
        }
        /// <summary>
        /// Create and write the copy operation
        /// </summary>
        /// <param name="thingToCopy">The <see cref="Thing"/> to copy</param>
        /// <param name="targetContainer">The target container</param>
        /// <param name="keyStates">The <see cref="DragDropKeyStates"/> used in the drag-and-drop operation</param>
        private async Task WriteCopyOperation(Thing thingToCopy, Thing targetContainer, OperationKind operationKind)
        {
            var clone          = thingToCopy.Clone(false);
            var containerClone = targetContainer.Clone(false);

            var transactionContext = TransactionContextResolver.ResolveContext(targetContainer);
            var transaction        = new ThingTransaction(transactionContext, containerClone);

            transaction.Copy(clone, containerClone, operationKind);

            await this.session.Write(transaction.FinalizeTransaction());
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Write the inline operations to the Data-access-layer
 /// </summary>
 /// <param name="transaction">The <see cref="ThingTransaction"/> that contains the operations</param>
 /// <param name="showConfirmation">A value indicating whether a confirmation should be displayed</param>
 protected async Task DalWrite(ThingTransaction transaction, bool showConfirmation = false)
 {
     try
     {
         var operationContainer = transaction.FinalizeTransaction();
         await this.Session.Write(operationContainer);
     }
     catch (Exception ex)
     {
         logger.Error("The inline update operation failed: {0}", ex.Message);
         this.ErrorMsg = ex.Message;
     }
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Write the inline operations to the Data-access-layer
 /// </summary>
 /// <param name="transaction">The <see cref="ThingTransaction"/> that contains the operations</param>
 protected async Task DalWrite(ThingTransaction transaction)
 {
     try
     {
         var operationContainer = transaction.FinalizeTransaction();
         await this.Session.Write(operationContainer);
     }
     catch (Exception exception)
     {
         logger.Error(exception, "The inline update operation failed");
         this.Feedback = exception.Message;
     }
 }
Ejemplo n.º 14
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);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Create a new <see cref="ElementUsage"/>
        /// </summary>
        /// <param name="container">
        /// The container <see cref="ElementDefinition"/> of the <see cref="ElementUsage"/> that is to be created.
        /// </param>
        /// <param name="referencedDefinition">
        /// The referenced <see cref="ElementDefinition"/> of the <see cref="ElementUsage"/> that is to be created.
        /// </param>
        /// <param name="owner">
        /// The <see cref="DomainOfExpertise"/> that is the owner of the <see cref="ElementUsage"/> that is to be created.
        /// </param>
        /// <param name="session">
        /// The <see cref="ISession"/> in which the current <see cref="Parameter"/> is to be added
        /// </param>
        public async Task CreateElementUsage(ElementDefinition container, ElementDefinition referencedDefinition, DomainOfExpertise owner, ISession session)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container", "The container must not be null");
            }

            if (referencedDefinition == null)
            {
                throw new ArgumentNullException("referencedDefinition", "The referencedDefinition must not be null");
            }

            if (owner == null)
            {
                throw new ArgumentNullException("owner", "The owner must not be null");
            }

            if (session == null)
            {
                throw new ArgumentNullException("session", "The session may not be null");
            }

            var clone = container.Clone(false);
            var usage = new ElementUsage
            {
                Name              = referencedDefinition.Name,
                ShortName         = referencedDefinition.ShortName,
                Category          = referencedDefinition.Category,
                Owner             = owner,
                ElementDefinition = referencedDefinition
            };

            clone.ContainedElement.Add(usage);

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

            transaction.Create(usage);

            try
            {
                var operationContainer = transaction.FinalizeTransaction();
                await session.Write(operationContainer);
            }
            catch (Exception ex)
            {
                logger.Error("The ElementUsage could not be created", ex);
                throw ex;
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Create a new <see cref="Parameter"/>
        /// </summary>
        /// <param name="elementDefinition">
        /// The container <see cref="ElementDefinition"/> of the <see cref="Parameter"/> that is to be created.
        /// </param>
        /// <param name="group">
        /// The <see cref="ParameterGroup"/> that the <see cref="Parameter"/> is to be grouped in.
        /// </param>
        /// <param name="parameterType">
        /// The <see cref="ParameterType"/> that the new <see cref="Parameter"/> references
        /// </param>
        /// <param name="measurementScale">
        /// The <see cref="MeasurementScale"/> that the <see cref="Parameter"/> references in case the <see cref="ParameterType"/> is a <see cref="QuantityKind"/>
        /// </param>
        /// <param name="owner">
        /// The <see cref="DomainOfExpertise"/> that is the owner of the <see cref="Parameter"/> that is to be created.
        /// </param>
        /// <param name="session">
        /// The <see cref="ISession"/> in which the current <see cref="Parameter"/> is to be added
        /// </param>
        public async Task CreateParameter(ElementDefinition elementDefinition, ParameterGroup group, ParameterType parameterType, MeasurementScale measurementScale, DomainOfExpertise owner, ISession session)
        {
            if (elementDefinition == null)
            {
                throw new ArgumentNullException(nameof(elementDefinition), "The container ElementDefinition may not be null");
            }

            if (parameterType == null)
            {
                throw new ArgumentNullException(nameof(parameterType), "The ParameterType may not be null");
            }

            if (owner == null)
            {
                throw new ArgumentNullException(nameof(owner), "The owner DomainOfExpertise may not be null");
            }

            if (session == null)
            {
                throw new ArgumentNullException(nameof(session), "The session may not be null");
            }

            var parameter = new Parameter(Guid.NewGuid(), null, null)
            {
                Owner         = owner,
                ParameterType = parameterType,
                Scale         = measurementScale,
                Group         = group
            };

            var clone = elementDefinition.Clone(false);

            clone.Parameter.Add(parameter);

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

            transaction.Create(parameter);

            try
            {
                var operationContainer = transaction.FinalizeTransaction();
                await session.Write(operationContainer);
            }
            catch (Exception ex)
            {
                logger.Error("The parameter could not be created", ex);
                throw ex;
            }
        }
        /// <summary>
        /// Updates multiple <see cref="Parameter"/>s with <see cref="ActualFiniteStateList"/> application in one batch operation
        /// </summary>
        /// <param name="session">
        /// The <see cref="ISession"/> that is used to communicate with the selected data source
        /// </param>
        /// <param name="iteration">
        /// The container <see cref="Iteration"/> in which the parameteres are to be updated
        /// </param>
        /// <param name="actualFiniteStateList">
        /// The <see cref="ActualFiniteStateList"/> that needs to be applied to the <see cref="Parameter"/>s
        /// </param>
        /// <param name="isUncategorizedIncluded">
        /// A value indication whether <see cref="Parameter"/>s contained by <see cref="ElementDefinition"/>s that are
        /// not a member of a <see cref="Category"/> shall be included or not
        /// </param>
        /// <param name="categories">
        /// An <see cref="IEnumerable{Category}"/> that is a selection criteria to select the <see cref="Parameter"/>s that need
        /// to be updated with the <see cref="ActualFiniteStateList"/>
        /// </param>
        /// <param name="domainOfExpertises"></param>
        /// An <see cref="IEnumerable{DomainOfExpertise}"/> that is a selection criteria to select the <see cref="Parameter"/>s that need
        /// to be updated with the <see cref="ActualFiniteStateList"/>
        /// <param name="parameterTypes">
        /// An <see cref="IEnumerable{ParameterType}"/> that is a selection criteria to select the <see cref="Parameter"/>s that need
        /// to be updated with the <see cref="ActualFiniteStateList"/>
        /// </param>
        /// <returns>
        /// an awaitable <see cref="Task"/>
        /// </returns>
        public async Task Update(ISession session, Iteration iteration, ActualFiniteStateList actualFiniteStateList, bool isUncategorizedIncluded, IEnumerable <Category> categories, IEnumerable <DomainOfExpertise> domainOfExpertises, IEnumerable <ParameterType> parameterTypes)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session), $"The {nameof(session)} may not be null");
            }

            if (iteration == null)
            {
                throw new ArgumentNullException(nameof(iteration), $"The {nameof(iteration)} may not be null");
            }

            if (actualFiniteStateList == null)
            {
                throw new ArgumentNullException(nameof(actualFiniteStateList), $"The {nameof(actualFiniteStateList)} may not be null");
            }

            if (categories == null)
            {
                throw new ArgumentNullException(nameof(categories), $"The {nameof(categories)} may not be null");
            }

            if (domainOfExpertises == null)
            {
                throw new ArgumentNullException(nameof(domainOfExpertises), $"The {nameof(domainOfExpertises)} may not be null");
            }

            if (parameterTypes == null)
            {
                throw new ArgumentNullException(nameof(parameterTypes), $"The {nameof(parameterTypes)} may not be null");
            }

            var parameters = this.QueryParameters(session, iteration, actualFiniteStateList, isUncategorizedIncluded, categories, domainOfExpertises, parameterTypes);

            if (!parameters.Any())
            {
                return;
            }

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

            this.UpdateTransactionWithUpdatedParameters(transaction, actualFiniteStateList, parameters);

            var updateOperationContainer = transaction.FinalizeTransaction();
            await session.Write(updateOperationContainer);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Posts a predefined <see cref="PossibleFiniteStateList"/>
        /// </summary>
        private void PostPossibleFiniteStateList()
        {
            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 pfs1           = new PossibleFiniteState(Guid.NewGuid(), this.session.Assembler.Cache, this.uri)
                {
                    Name = "state1", ShortName = "s1"
                };

                var pfs2 = new PossibleFiniteState(Guid.NewGuid(), this.session.Assembler.Cache, this.uri)
                {
                    Name = "state2", ShortName = "s2"
                };

                var pfsList = new PossibleFiniteStateList(Guid.NewGuid(), this.session.Assembler.Cache, this.uri)
                {
                    Name = "PossibleFiniteStateList1", ShortName = "PFSL1"
                };

                this.session.OpenIterations.TryGetValue(iteration, out var tuple);
                var domainOfExpertise = tuple.Item1;
                pfsList.Owner = domainOfExpertise;

                var transaction = new ThingTransaction(
                    TransactionContextResolver.ResolveContext(iterationClone),
                    iterationClone);
                transaction.Create(pfsList, iterationClone);
                transaction.Create(pfs1, pfsList);
                transaction.Create(pfs2, pfsList);

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

                this.PrintCacheCount();

                this.PrintCommands();
            }
        }
Ejemplo n.º 19
0
        public void Verify_that_OperationContainerFileVerification_throws_no_exception_when_data_is_complete()
        {
            var siteDirectory         = new CDP4Common.SiteDirectoryData.SiteDirectory(Guid.NewGuid(), null, null);
            var engineeringModelSetup = new CDP4Common.SiteDirectoryData.EngineeringModelSetup(Guid.NewGuid(), null, null);
            var iterationSetup        = new CDP4Common.SiteDirectoryData.IterationSetup(Guid.NewGuid(), null, null);

            siteDirectory.Model.Add(engineeringModelSetup);
            engineeringModelSetup.IterationSetup.Add(iterationSetup);

            var engineeringModel = new CDP4Common.EngineeringModelData.EngineeringModel(Guid.NewGuid(), null, null);

            engineeringModel.EngineeringModelSetup = engineeringModelSetup;

            var iteration = new CDP4Common.EngineeringModelData.Iteration(Guid.NewGuid(), null, null);

            iteration.IterationSetup = iterationSetup;

            var commonFileStore = new CDP4Common.EngineeringModelData.CommonFileStore(Guid.NewGuid(), null, null);

            engineeringModel.Iteration.Add(iteration);
            engineeringModel.CommonFileStore.Add(commonFileStore);

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

            var commonFileStoreClone = commonFileStore.Clone(false);

            var file         = new CDP4Common.EngineeringModelData.File(Guid.NewGuid(), null, null);
            var fileRevision = new CDP4Common.EngineeringModelData.FileRevision(Guid.NewGuid(), null, null);

            fileRevision.ContentHash = "1B686ADFA2CAE870A96E5885087337C032781BE6";

            transaction.Create(file, commonFileStoreClone);
            transaction.Create(fileRevision, file);

            var operationContainer = transaction.FinalizeTransaction();

            var files = new List <string> {
                this.filePath
            };

            var testDal = new TestDal(this.credentials);

            Assert.DoesNotThrow(() => testDal.TestOperationContainerFileVerification(operationContainer, files));
        }
        /// <summary>
        /// Updates the Executed On property of the <paramref name="ruleVerification"/> in the data-source
        /// </summary>
        /// <param name="session">
        /// The <see cref="ISession"/> instance used to update the contained <see cref="RuleVerification"/> instances on the data-source.
        /// </param>
        /// <param name="ruleVerification">
        /// The <see cref="RuleVerification"/> that is to be updated.
        /// </param>
        /// <returns>An awaitable <see cref="Task"/></returns>
        private async Task UpdateExecutedOn(ISession session, RuleVerification ruleVerification)
        {
            try
            {
                var clone = ruleVerification.Clone(false);

                var transactionContext = TransactionContextResolver.ResolveContext(ruleVerification);
                var transaction        = new ThingTransaction(transactionContext, clone);
                clone.ExecutedOn = DateTime.UtcNow;

                var operationContainer = transaction.FinalizeTransaction();
                await session.Write(operationContainer);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Create a new <see cref="UserRuleVerification"/>
        /// </summary>
        /// <param name="ruleVerificationList">
        /// The container <see cref="RuleVerificationList"/> of the <see cref="UserRuleVerification"/> that is to be created.
        /// </param>
        /// <param name="rule">
        /// The <see cref="Rule"/> that the new <see cref="UserRuleVerification"/> references.
        /// </param>
        /// <param name="session">
        /// The <see cref="ISession"/> in which the new <see cref="UserRuleVerification"/> is to be added
        /// </param>
        public async Task CreateUserRuleVerification(RuleVerificationList ruleVerificationList, Rule rule, ISession session)
        {
            if (ruleVerificationList == null)
            {
                throw new ArgumentNullException("ruleVerificationList", "The ruleVerificationList must not be null");
            }

            if (rule == null)
            {
                throw new ArgumentNullException("rule", "The rule must not be null");
            }

            if (session == null)
            {
                throw new ArgumentNullException("session", "The session may not be null");
            }

            var userRuleVerification = new UserRuleVerification(Guid.NewGuid(), null, null)
            {
                Rule     = rule,
                IsActive = false,
                Status   = RuleVerificationStatusKind.NONE
            };

            var clone = ruleVerificationList.Clone(false);

            clone.RuleVerification.Add(userRuleVerification);

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

            transaction.Create(userRuleVerification);

            try
            {
                var operationContainer = transaction.FinalizeTransaction();
                await session.Write(operationContainer);
            }
            catch (Exception ex)
            {
                logger.Error("The UserRuleVerification could not be created", ex);
                throw ex;
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Create a new <see cref="BuiltInRuleVerification"/>
        /// </summary>
        /// <param name="ruleVerificationList">
        /// The container <see cref="RuleVerificationList"/> of the <see cref="BuiltInRuleVerification"/> that is to be created.
        /// </param>
        /// <param name="name">
        /// The name for the <see cref="BuiltInRuleVerification"/>
        /// </param>
        /// <param name="session">
        /// The <see cref="ISession"/> in which the new <see cref="UserRuleVerification"/> is to be added
        /// </param>
        public async Task CreateBuiltInRuleVerification(RuleVerificationList ruleVerificationList, string name, ISession session)
        {
            if (ruleVerificationList == null)
            {
                throw new ArgumentNullException(nameof(ruleVerificationList), "The ruleVerificationList must not be null");
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("The name may not be null or empty");
            }

            if (session == null)
            {
                throw new ArgumentNullException(nameof(session), "The session may not be null");
            }

            var builtInRuleVerification = new BuiltInRuleVerification(Guid.NewGuid(), null, null)
            {
                Name     = name,
                IsActive = false,
                Status   = RuleVerificationStatusKind.NONE
            };

            var clone = ruleVerificationList.Clone(false);

            clone.RuleVerification.Add(builtInRuleVerification);

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

            transaction.Create(builtInRuleVerification);

            try
            {
                var operationContainer = transaction.FinalizeTransaction();
                await session.Write(operationContainer);
            }
            catch (Exception ex)
            {
                logger.Error("The BuiltInRuleVerification could not be created", ex);
                throw ex;
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Posts a predefined <see cref="Person"/>
        /// </summary>
        private void PostPerson()
        {
            if (this.IsSiteDirectoryUnavailable())
            {
                Console.WriteLine("At first a connection should be opened.");
                return;
            }

            // Create person object
            var person = new Person(Guid.NewGuid(), this.session.Assembler.Cache, this.uri)
            {
                IsActive = true, ShortName = "M" + DateTime.Now, Surname = "Mouse", GivenName = "Mike",
                Password = "******"
            };
            var email1 = new EmailAddress(Guid.NewGuid(), this.session.Assembler.Cache, this.uri)
            {
                Value = "*****@*****.**", VcardType = VcardEmailAddressKind.HOME
            };

            person.DefaultEmailAddress = email1;

            var email2 = new EmailAddress(Guid.NewGuid(), this.session.Assembler.Cache, this.uri)
            {
                Value = "*****@*****.**", VcardType = VcardEmailAddressKind.WORK
            };

            var modifiedSiteDirectory = this.session.Assembler.RetrieveSiteDirectory().Clone(true);

            var transaction = new ThingTransaction(
                TransactionContextResolver.ResolveContext(modifiedSiteDirectory), modifiedSiteDirectory);

            transaction.Create(person, modifiedSiteDirectory);
            transaction.Create(email1, person);
            transaction.Create(email2, person);

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

            this.PrintCacheCount();

            this.PrintCommands();
        }
        /// <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;
            }
        }
        /// <summary>
        /// Perform the copy operation of an <see cref="ElementDefinition"/>
        /// </summary>
        /// <param name="elementDefinition">The <see cref="ElementDefinition"/> to copy</param>
        /// <param name="targetIteration">The target container</param>
        public async Task Copy(ElementDefinition elementDefinition, bool areUsagesCopied)
        {
            var iterationClone     = (Iteration)elementDefinition.Container.Clone(false);
            var transactionContext = TransactionContextResolver.ResolveContext(iterationClone);
            var transaction        = new ThingTransaction(transactionContext, iterationClone);

            var clone = elementDefinition.Clone(true);

            clone.Iid   = Guid.NewGuid();
            clone.Name += CopyAffix;

            if (!areUsagesCopied)
            {
                clone.ContainedElement.Clear();
            }

            this.ResolveReferences(elementDefinition, clone);
            iterationClone.Element.Add(clone);

            transaction.CopyDeep(clone);
            await this.session.Write(transaction.FinalizeTransaction());
        }
Ejemplo n.º 26
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;
            }
        }
        /// <summary>
        /// Update the ownnership of ultiple <see cref="IOwnedThing"/>s
        /// </summary>
        /// <param name="session">
        /// The <see cref="ISession"/> that is used to communicate with the selected data source
        /// </param>
        /// <param name="root">
        /// An <see cref="Thing"/> of which the ownership needs to be changed to the <paramref name="owner"/> or the ownership of contained items
        /// </param>
        /// <param name="owner">
        /// the <see cref="DomainOfExpertise"/> that is to be the new owner of the <paramref name="ownedThings"/>
        /// </param>
        /// <param name="updateContainedItems">
        /// a value indicating whether the owner of the contained <see cref="IOwnedThing"/> needs to be updated as well
        /// </param>
        /// <param name="classKinds">
        /// An <see cref="IEnumerable{ClassKind}"/> that specifies in case the <paramref name="updateContainedItems"/> is true, what kind of
        /// contianed items are to be taken into account. The <paramref name="root"/> is always taken into account.
        /// </param>
        /// <returns>
        /// an awaitable <see cref="Task"/>
        /// </returns>
        public async Task Update(ISession session, Thing root, DomainOfExpertise owner, bool updateContainedItems, IEnumerable <ClassKind> classKinds)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session), $"The {nameof(session)} may not be null");
            }

            if (root == null)
            {
                throw new ArgumentNullException(nameof(root), $"The {nameof(root)} may not be null");
            }

            if (owner == null)
            {
                throw new ArgumentNullException(nameof(owner), $"The {nameof(owner)} may not be null");
            }

            if (classKinds == null)
            {
                throw new ArgumentNullException(nameof(classKinds), $"The {nameof(classKinds)} may not be null");
            }

            var ownedThings = this.QueryOwnedThings(root, updateContainedItems, classKinds);

            if (!ownedThings.Any())
            {
                return;
            }

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

            this.UpdateTransactionWithUpdatedOwners(transaction, ownedThings, owner);
            var updateOperationContainer = transaction.FinalizeTransaction();

            await session.Write(updateOperationContainer);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Execute the <see cref="DeprecateCommand"/>
        /// </summary>
        protected virtual async void ExecuteDeprecateCommand()
        {
            if (!(this.SelectedThing.Thing is IDeprecatableThing))
            {
                return;
            }

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

            var isDeprecatedPropertyInfo = clone.GetType().GetProperty("IsDeprecated");

            if (isDeprecatedPropertyInfo == null)
            {
                return;
            }

            var oldValue = ((IDeprecatableThing)this.SelectedThing.Thing).IsDeprecated;

            isDeprecatedPropertyInfo.SetValue(clone, !oldValue);

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

            var transaction = new ThingTransaction(context);

            transaction.CreateOrUpdate(clone);

            try
            {
                await this.Session.Write(transaction.FinalizeTransaction());
            }
            catch (Exception ex)
            {
                logger.Error("An error was produced when (un)deprecating {0}: {1}", thing.ClassKind, ex.Message);
                this.Feedback = ex.Message;
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Execute the <see cref="DeleteCommand"/>
        /// </summary>
        /// <param name="thing">
        /// The thing to delete.
        /// </param>
        protected virtual async void ExecuteDeleteCommand(Thing thing)
        {
            if (thing == null)
            {
                return;
            }

            var confirmation = new ConfirmationDialogViewModel(thing);
            var dialogResult = this.dialogNavigationService.NavigateModal(confirmation);

            if (dialogResult == null || !dialogResult.Result.HasValue || !dialogResult.Result.Value)
            {
                return;
            }

            this.IsBusy = true;

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

            var transaction = new ThingTransaction(context);

            transaction.Delete(thing.Clone(false));

            try
            {
                await this.Session.Write(transaction.FinalizeTransaction());
            }
            catch (Exception ex)
            {
                logger.Error("An error was produced when deleting the {0}: {1}", thing.ClassKind, ex.Message);
                this.Feedback = ex.Message;
            }
            finally
            {
                this.IsBusy = false;
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Execute the <see cref="CreateRelationshipCommand"/>
        /// </summary>
        private async Task ExecuteCreateRelationshipCommand()
        {
            var relationship = this.SelectedRelationshipCreator.CreateRelationshipObject();

            relationship.Owner = this.session.OpenIterations[this.iteration].Item1;

            var transaction    = new ThingTransaction(TransactionContextResolver.ResolveContext(this.iteration));
            var iterationClone = this.iteration.Clone(false);

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

            try
            {
                await this.session.Write(transaction.FinalizeTransaction());

                this.SelectedRelationshipCreator.ReInitializeControl();
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
            }
        }