/// <summary> /// Create the default scale update subscription /// </summary> private void CreateDefaultScaleUpdateSubscription() { var quantityKind = this.Thing as QuantityKind; if (quantityKind == null) { return; } if (this.defaultScaleObject != null && quantityKind.DefaultScale == this.defaultScaleObject) { return; } if (this.defaultScaleSubscription != null) { this.defaultScaleSubscription.Dispose(); } this.defaultScaleObject = quantityKind.DefaultScale; this.defaultScaleSubscription = CDPMessageBus.Current.Listen <ObjectChangedEvent>(this.defaultScaleObject) .Where(objectChange => objectChange.EventKind == EventKind.Updated) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => { this.DefaultScale = this.defaultScaleObject.ShortName; }); this.DefaultScale = this.defaultScaleObject.ShortName; }
/// <summary> /// Assign measurement scale to given parameters. /// </summary> public void AssignMeasurementScale() { MeasurementScale measurementScale = null; if (!string.IsNullOrWhiteSpace(this.commandArguments.Scale)) { measurementScale = this.sessionService.SiteDirectory.SiteReferenceDataLibrary.SelectMany(r => r.Scale).SingleOrDefault(x => x.ShortName == this.commandArguments.Scale); } if (measurementScale == null) { Console.WriteLine("Invalid action \"set-scale\": short name of a valid scale must be given in --scale."); return; } if (!this.commandArguments.SelectedParameters.Any()) { Console.WriteLine("No --parameters given. Action set-scale skipped."); return; } foreach (var elementDefinition in this.sessionService.Iteration.Element.Where(e => this.filterService.IsFilteredIn(e)).OrderBy(x => x.ShortName)) { foreach (var parameter in elementDefinition.Parameter.Where(this.filterService.IsParameterSpecifiedOrAny).OrderBy(x => x.ParameterType.ShortName)) { if (!(parameter.ParameterType is QuantityKind quantityKind)) { continue; } var allPossibleScale = quantityKind.AllPossibleScale; if (parameter.Scale == null) { Console.WriteLine( $"No measurement scale assigned to parameter {parameter.UserFriendlyShortName}: should be one of " + $"{string.Join(", ", allPossibleScale.Select(x => x.ShortName).OrderBy(x => x))}"); } else if (!allPossibleScale.Contains(parameter.Scale)) { Console.WriteLine( $"Invalid measurement scale {parameter.Scale.ShortName} assigned to parameter {parameter.UserFriendlyShortName}: should be one of" + $" {string.Join(", ", allPossibleScale.Select(x => x.ShortName).OrderBy(x => x))}"); } if (this.commandArguments.SelectedParameters.Contains(parameter.ParameterType.ShortName) && allPossibleScale.Contains(measurementScale) && parameter.Scale != measurementScale) { var parameterClone = parameter.Clone(true); this.sessionService.Transactions.Add(new ThingTransaction(TransactionContextResolver.ResolveContext(parameterClone), parameterClone)); parameterClone.Scale = measurementScale; this.sessionService.Transactions.Last().CreateOrUpdate(parameterClone); Console.WriteLine($"Assigned scale \"{measurementScale.ShortName}\" to parameter {parameter.UserFriendlyShortName}"); } } } }
/// <summary> /// Removes a <see cref="MeasurementScaleRowViewModel"/> from the view model /// </summary> /// <param name="scale"> /// The <see cref="MeasurementScale"/> for which the row view model has to be removed /// </param> private void RemoveMeasurementScaleRowViewModel(MeasurementScale scale) { var row = this.MeasurementScales.SingleOrDefault(rowViewModel => rowViewModel.Thing == scale); if (row != null) { this.MeasurementScales.RemoveAndDispose(row); } }
public void Setup() { RxApp.MainThreadScheduler = Scheduler.CurrentThread; this.permissionService = new Mock <IPermissionService>(); this.cache = new ConcurrentDictionary <CacheKey, Lazy <Thing> >(); this.session = new Mock <ISession>(); var person = new Person(Guid.NewGuid(), null, null) { Container = this.siteDir }; this.session.Setup(x => x.ActivePerson).Returns(person); this.siteDir = new SiteDirectory(Guid.NewGuid(), this.cache, null); this.siteDir.Person.Add(person); this.srdl = new SiteReferenceDataLibrary(Guid.NewGuid(), this.cache, null) { Name = "testRDL", ShortName = "test" }; this.compoundPt = new CompoundParameterType { Name = "parameterType", ShortName = "cat" }; this.cat = new Category(Guid.NewGuid(), this.cache, null) { Name = "category1", ShortName = "cat1" }; this.cat.PermissibleClass.Add(ClassKind.CompoundParameterType); this.srdl.DefinedCategory.Add(cat); this.siteDir.SiteReferenceDataLibrary.Add(this.srdl); this.session.Setup(x => x.RetrieveSiteDirectory()).Returns(this.siteDir); this.session.Setup(x => x.OpenReferenceDataLibraries).Returns(new HashSet <ReferenceDataLibrary>(this.siteDir.SiteReferenceDataLibrary)); this.bpt = new BooleanParameterType(Guid.NewGuid(), this.cache, null); this.cpt = new CompoundParameterType(Guid.NewGuid(), this.cache, null); this.srdl.ParameterType.Add(this.bpt); this.srdl.ParameterType.Add(this.cpt); this.qt = new SimpleQuantityKind(Guid.NewGuid(), this.cache, null); this.srdl.ParameterType.Add(this.qt); this.scale = new OrdinalScale(Guid.NewGuid(), this.cache, null); this.srdl.Scale.Add(this.scale); this.qt.PossibleScale.Add(this.scale); this.cache.TryAdd(new CacheKey(this.srdl.Iid, null), new Lazy <Thing>(() => this.srdl)); this.permissionService.Setup(x => x.CanWrite(It.IsAny <ClassKind>(), It.IsAny <Thing>())).Returns(true); this.permissionService.Setup(x => x.CanWrite(It.IsAny <Thing>())).Returns(true); this.session.Setup(x => x.PermissionService).Returns(this.permissionService.Object); var dal = new Mock <IDal>(); this.session.Setup(x => x.DalVersion).Returns(new Version(1, 1, 0)); this.session.Setup(x => x.Dal).Returns(dal.Object); dal.Setup(x => x.MetaDataProvider).Returns(new MetaDataProvider()); this.parameterType = new ParameterTypeComponent(); }
/// <summary> /// Computes the extra mass contributions /// </summary> /// <param name="budgetConfig">The current <see cref="BudgetConfig"/></param> /// <param name="element">The current <see cref="ElementDefinition"/> to compute the budget for</param> /// <param name="option">The current <see cref="Option"/></param> /// <param name="currentDomain">The current <see cref="DomainOfExpertise"/></param> /// <returns>The list of <see cref="ExtraContribution"/></returns> public IReadOnlyList <ExtraContribution> GetExtraMassContributions(BudgetConfig budgetConfig, ElementDefinition element, Option option, DomainOfExpertise currentDomain) { var config = (MassBudgetParameterConfig)budgetConfig.BudgetParameterConfig; var extraMassContributorUsages = new Dictionary <ExtraMassContributionConfiguration, List <ElementUsage> >(); foreach (var extraConfig in config.ExtraMassContributionConfigurations) { extraMassContributorUsages.Add(extraConfig, new List <ElementUsage>()); } this.WalkProductTree(element, option, eu => this.FindExtraMassContributors(eu, config, extraMassContributorUsages)); MeasurementScale scale = null; var results = new List <ExtraContribution>(); foreach (var extraMassContributorUsage in extraMassContributorUsages) { var total = 0f; var totalWithMargin = 0f; foreach (var elementUsage in extraMassContributorUsage.Value) { var floatValue = elementUsage.GetFloatActualValue(extraMassContributorUsage.Key.MassParameterType, null, option, currentDomain); var marginValue = extraMassContributorUsage.Key.MarginParameterType != null ? elementUsage.GetFloatActualValue(extraMassContributorUsage.Key.MarginParameterType, null, option, currentDomain) : 0f; var ptScale = elementUsage.GetScale(extraMassContributorUsage.Key.MassParameterType); if (scale == null && ptScale != null) { scale = ptScale; } else if (ptScale != null && scale.Iid != ptScale.Iid) { throw new BudgetComputationException($"Different scales used in the element-usage {elementUsage.Name}.{extraMassContributorUsage.Key.MassParameterType.ShortName}"); } if (floatValue.HasValue) { total += floatValue.Value; if (marginValue.HasValue) { totalWithMargin += floatValue.Value * (1 + marginValue.Value / 100f); } else { totalWithMargin += floatValue.Value; } } } results.Add(new ExtraContribution(extraMassContributorUsage.Key.ContributionCategories, total, totalWithMargin, extraMassContributorUsage.Key.MassParameterType, scale)); } return(results); }
/// <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 Task CreateParameter( ElementDefinition elementDefinition, ParameterGroup @group, ParameterType parameterType, MeasurementScale measurementScale, DomainOfExpertise owner, ISession session) { throw new Exception("The parameter could not be created"); }
/// <summary> /// Validates the new value of a <see cref="ParameterValueSetBase"/> or <see cref="ParameterSubscriptionValueSet"/> and return an error if any /// </summary> /// <param name="newValue">The new value to validate</param> /// <param name="parameterType">The associated <see cref="ParameterType"/></param> /// <param name="scale">An optional <see cref="MeasurementScale"/> if the <paramref name="parameterType"/> is a <see cref="QuantityKind"/></param> /// <returns>An error message if any</returns> public static string Validate(object newValue, ParameterType parameterType, MeasurementScale scale = null) { if (parameterType == null) { logger.Error("The parameter type is null."); return("Error: The parameter type is null."); } var stringValue = newValue.ToValueSetString(parameterType); var result = parameterType.Validate(stringValue, scale); return((result.ResultKind == ValidationResultKind.Valid) ? null : result.Message); }
/// <summary> /// Check that the values of this row are valid /// </summary> /// <param name="scale">The <see cref="MeasurementScale"/></param> public override void CheckValues(MeasurementScale scale) { if (this.ContainedRows.Count == 0) { this.RaisePropertyChanged(ManualPropertyName); this.RaisePropertyChanged(ReferencePropertyName); return; } foreach (IDialogValueSetRow row in this.ContainedRows) { row.CheckValues(scale); } }
/// <summary> /// Validates the to check whether it is a <see cref="ScalarParameterType"/> /// </summary> /// <param name="quantityKind"> /// A <see cref="QuantityKind"/> /// </param> /// <param name="scale"> /// The <see cref="MeasurementScale"/> /// </param> /// <param name="value"> /// the string representation of a <see cref="ScalarParameterType"/> value /// </param> /// <returns> /// a <see cref="ValidationResult"/> that carries the <see cref="ValidationResultKind"/> and an optional message. /// </returns> public static ValidationResult Validate(this QuantityKind quantityKind, MeasurementScale scale, string value) { ValidationResult result; if (value == DefaultValue) { result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); } result = scale.Validate(value); return(result); }
public void Setup() { RxApp.MainThreadScheduler = Scheduler.CurrentThread; this.iteration = new Iteration(Guid.NewGuid(), null, null); this.elementDefinition = new ElementDefinition(Guid.NewGuid(), null, null) { ShortName = "ED" }; this.iteration.Element.Add(this.elementDefinition); this.elementUsage = new ElementUsage(Guid.NewGuid(), null, null) { ElementDefinition = this.elementDefinition, ShortName = "EU" }; this.elementDefinition.ContainedElement.Add(this.elementUsage); this.simpleQuantityKind = new SimpleQuantityKind(Guid.NewGuid(), null, null) { ShortName = "SQ" }; this.scale = new RatioScale(Guid.NewGuid(), null, null) { ShortName = "SC" }; this.parameter = new Parameter(Guid.NewGuid(), null, null) { ParameterType = this.simpleQuantityKind, Scale = this.scale, Container = this.elementDefinition }; this.parameterOverride = new ParameterOverride(Guid.NewGuid(), null, null) { Parameter = this.parameter, Container = this.elementUsage }; this.iterationTrackParameterForParameter = new IterationTrackParameter(this.parameter); this.iterationTrackParameterForParameterOverride = new IterationTrackParameter(this.parameterOverride); }
/// <summary> /// Validates the to check whether it is a <see cref="ScalarParameterType"/> /// </summary> /// <param name="quantityKind"> /// A <see cref="QuantityKind"/> /// </param> /// <param name="scale"> /// The <see cref="MeasurementScale"/> /// </param> /// <param name="value"> /// The value that is to be validated. /// </param> /// <param name="provider"> /// The <see cref="IFormatProvider"/> used to validate, if set to null <see cref="CultureInfo.CurrentCulture"/> will be used. /// </param> /// <returns> /// a <see cref="ValidationResult"/> that carries the <see cref="ValidationResultKind"/> and an optional message. /// </returns> public static ValidationResult Validate(this QuantityKind quantityKind, MeasurementScale scale, object value, IFormatProvider provider = null) { ValidationResult result; if (scale == null) { Logger.Error("The scale is null with a quantity kind as the parameter type."); result.ResultKind = ValidationResultKind.Invalid; result.Message = "The scale is null with a quantity kind as the parameter type."; return(result); } var stringValue = value as string; if (stringValue != null && stringValue == DefaultValue) { result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); } result = scale.Validate(value, provider); return(result); }
public DataAttribute CreateDataAttribute(string shortName, string name, string description, bool isMultiValue, bool isBuiltIn, string scope, MeasurementScale measurementScale, DataContainerType containerType, string entitySelectionPredicate, DataType dataType, Unit unit, Methodology methodology, Classifier classifier, ICollection <AggregateFunction> functions, ICollection <GlobalizationInfo> globalizationInfos, ICollection <Constraint> constraints, ICollection <ExtendedProperty> extendedProperies ) { Contract.Requires(!string.IsNullOrWhiteSpace(shortName)); Contract.Requires(dataType != null && dataType.Id >= 0); Contract.Requires(unit != null && unit.Id >= 0); Contract.Ensures(Contract.Result <DataAttribute>() != null && Contract.Result <DataAttribute>().Id >= 0); DataAttribute e = new DataAttribute() { ShortName = shortName, Name = name, Description = description, IsMultiValue = isMultiValue, IsBuiltIn = isBuiltIn, Scope = scope, MeasurementScale = measurementScale, ContainerType = containerType, EntitySelectionPredicate = entitySelectionPredicate, DataType = dataType, Unit = unit, Methodology = methodology, AggregateFunctions = functions, GlobalizationInfos = globalizationInfos, Constraints = constraints, ExtendedProperties = extendedProperies, }; if (classifier != null && classifier.Id > 0) { e.Classification = classifier; } using (IUnitOfWork uow = this.GetUnitOfWork()) { IRepository <DataAttribute> repo = uow.GetRepository <DataAttribute>(); repo.Put(e); uow.Commit(); } return(e); }
/// <summary> /// Validates the to check whether the <paramref name="value"/> is valid with respect to the <paramref name="parameterType"/> /// </summary> /// <param name="parameterType"> /// A <see cref="BooleanParameterType"/> /// </param> /// <param name="value"> /// The value that is to be validated /// </param> /// <param name="measurementScale"> /// The measurement Scale. /// </param> /// <param name="provider"> /// The <see cref="IFormatProvider"/> used to validate, if set to null <see cref="CultureInfo.CurrentCulture"/> will be used. /// </param> /// <returns> /// a <see cref="ValidationResult"/> that carries the <see cref="ValidationResultKind"/> and an optional message. /// </returns> public static ValidationResult Validate(this ParameterType parameterType, object value, MeasurementScale measurementScale = null, IFormatProvider provider = null) { ValidationResult result; var stringValue = value as string; if (stringValue != null && stringValue == DefaultValue) { result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); } var booleanParameter = parameterType as BooleanParameterType; if (booleanParameter != null) { return(booleanParameter.Validate(value)); } var dateParameterType = parameterType as DateParameterType; if (dateParameterType != null) { return(dateParameterType.Validate(value)); } var dateTimeParameterType = parameterType as DateTimeParameterType; if (dateTimeParameterType != null) { return(dateTimeParameterType.Validate(value)); } var enumerationParameterType = parameterType as EnumerationParameterType; if (enumerationParameterType != null) { return(enumerationParameterType.Validate(value)); } var quantityKind = parameterType as QuantityKind; if (quantityKind != null) { return(quantityKind.Validate(measurementScale, value, provider)); } var textParameterType = parameterType as TextParameterType; if (textParameterType != null) { return(textParameterType.Validate(value)); } var timeOfDayParameterType = parameterType as TimeOfDayParameterType; if (timeOfDayParameterType != null) { return(timeOfDayParameterType.Validate(value)); } throw new NotSupportedException($"The Validate method is not suported for parameterType: {parameterType}"); }
/// <summary> /// Validates whether the provided value is valid with respect to the <see cref="MeasurementScale"/> /// </summary> /// <param name="measurementScale"> /// The <see cref="MeasurementScale"/> /// </param> /// <param name="value"> /// The value that is to be validated /// </param> /// <param name="provider"> /// The <see cref="IFormatProvider"/> used to validate, if set to null <see cref="CultureInfo.CurrentCulture"/> will be used. /// </param> /// <returns> /// a <see cref="ValidationResult"/> that carries the <see cref="ValidationResultKind"/> and an optional message. /// </returns> public static ValidationResult Validate(this MeasurementScale measurementScale, object value, IFormatProvider provider = null) { ValidationResult result; bool isMaximumPermissibleValue; bool isMinimumPermissibleValue; var stringValue = value as string; switch (measurementScale.NumberSet) { case NumberSetKind.INTEGER_NUMBER_SET: bool isInteger = false; int integer = 0; if (value is int) { isInteger = true; integer = (int)value; } // the value parameter may be passed as a double, provided it has no digits after // the decimal separator, we consider it may be a integer number if (value is double) { var d = (double)value; if (d % 1 == 0) { isInteger = true; integer = (int)d; } } if (stringValue != null) { isInteger = int.TryParse(stringValue, NumberStyles.Integer, null, out integer); } if (!isInteger) { result.ResultKind = ValidationResultKind.Invalid; result.Message = $"{value.GetType().Name}:\"{value}\" is not a member of the INTEGER NUMBER SET"; return(result); } if (!string.IsNullOrWhiteSpace(measurementScale.MaximumPermissibleValue)) { int intMaximumPermissibleValue; isMaximumPermissibleValue = int.TryParse(measurementScale.MaximumPermissibleValue, NumberStyles.Integer, null, out intMaximumPermissibleValue); if (isMaximumPermissibleValue) { if (measurementScale.IsMaximumInclusive && integer > intMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{integer}\" is greater than the maximium permissible value of \"{intMaximumPermissibleValue}\""; return(result); } if (!measurementScale.IsMaximumInclusive && integer >= intMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{integer}\" is greater than or equal to the maximium permissible value of \"{intMaximumPermissibleValue}\""; return(result); } } else { Logger.Warn("The MaximumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MaximumPermissibleValue, measurementScale.Iid); } } if (!string.IsNullOrWhiteSpace(measurementScale.MinimumPermissibleValue)) { int intMinimumPermissibleValue; isMinimumPermissibleValue = int.TryParse(measurementScale.MinimumPermissibleValue, NumberStyles.Integer, null, out intMinimumPermissibleValue); if (isMinimumPermissibleValue) { if (measurementScale.IsMinimumInclusive && integer < intMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{integer}\" is smaller than the minimum permissible value of \"{intMinimumPermissibleValue}\""; return(result); } if (!measurementScale.IsMinimumInclusive && integer <= intMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{integer}\" is smaller than or equal to the minimum permissible value of \"{intMinimumPermissibleValue}\""; return(result); } } else { Logger.Warn("The MinimumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MinimumPermissibleValue, measurementScale.Iid); } } result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); case NumberSetKind.NATURAL_NUMBER_SET: int natural = 0; bool isNatural = false; if (value is int) { isNatural = true; natural = (int)value; } // the value parameter may be passed as a double, provided it has no digits after // the decimal separator, we consider it may be a natural number if (value is double) { var d = (double)value; if (d % 1 == 0) { isNatural = true; natural = (int)d; } } if (stringValue != null) { isNatural = int.TryParse(stringValue, NumberStyles.Integer, null, out natural); } if (!isNatural) { result.ResultKind = ValidationResultKind.Invalid; result.Message = $"{value.GetType().Name}:\"{value}\" is not a member of the NATURAL NUMBER SET"; return(result); } if (natural < 0) { result.ResultKind = ValidationResultKind.Invalid; result.Message = $"\"{value}\" is not a member of the NATURAL NUMBER SET"; return(result); } if (!string.IsNullOrWhiteSpace(measurementScale.MaximumPermissibleValue)) { int naturalMaximumPermissibleValue; isMaximumPermissibleValue = int.TryParse(measurementScale.MaximumPermissibleValue, NumberStyles.Integer, null, out naturalMaximumPermissibleValue); if (isMaximumPermissibleValue) { if (measurementScale.IsMaximumInclusive && natural > naturalMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{natural}\" is greater than the maximium permissible value of \"{naturalMaximumPermissibleValue}\""; return(result); } if (!measurementScale.IsMaximumInclusive && natural >= naturalMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{natural}\" is greater than or equal to the maximium permissible value of \"{naturalMaximumPermissibleValue}\""; return(result); } } else { Logger.Warn("The MaximumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MaximumPermissibleValue, measurementScale.Iid); } } if (!string.IsNullOrWhiteSpace(measurementScale.MinimumPermissibleValue)) { int naturalMinimumPermissibleValue; isMinimumPermissibleValue = int.TryParse(measurementScale.MinimumPermissibleValue, NumberStyles.Integer, null, out naturalMinimumPermissibleValue); if (isMinimumPermissibleValue) { if (measurementScale.IsMinimumInclusive && natural < naturalMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{natural}\" is smaller than the minimum permissible value of \"{naturalMinimumPermissibleValue}\""; return(result); } if (!measurementScale.IsMinimumInclusive && natural <= naturalMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{natural}\" is smaller than or equal to the minimum permissible value of \"{naturalMinimumPermissibleValue}\""; return(result); } } else { Logger.Warn("The MinimumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MinimumPermissibleValue, measurementScale.Iid); } } result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); case NumberSetKind.RATIONAL_NUMBER_SET: Logger.Warn("RATIONAL NUMBER SET currently not validated and always returns ValidationResultKind.Valid"); result.ResultKind = ValidationResultKind.Valid; result.Message = "RATIONAL NUMBER SET are not validated"; return(result); case NumberSetKind.REAL_NUMBER_SET: if (provider == null) { provider = CultureInfo.InvariantCulture; } double real = 0; bool isReal = false; // the real numbers include all the integers if (value is int) { isReal = true; real = Convert.ToDouble(value); } if (value is double) { isReal = true; real = (double)value; } if (stringValue != null) { isReal = double.TryParse(stringValue, NumberStyles.Float, provider, out real); } if (!isReal) { result.ResultKind = ValidationResultKind.Invalid; result.Message = $"{value.GetType().Name}:\"{value}\" is not a member of the REAL NUMBER SET"; return(result); } if (!string.IsNullOrWhiteSpace(measurementScale.MaximumPermissibleValue)) { double realMaximumPermissibleValue; isMaximumPermissibleValue = double.TryParse(measurementScale.MaximumPermissibleValue, NumberStyles.Float, null, out realMaximumPermissibleValue); if (isMaximumPermissibleValue) { if (measurementScale.IsMaximumInclusive && real > realMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{real}\" is greater than the maximium permissible value of \"{realMaximumPermissibleValue}\""; return(result); } if (!measurementScale.IsMaximumInclusive && real >= realMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{real}\" is greater than or equal to the maximium permissible value of \"{realMaximumPermissibleValue}\""; return(result); } } else { Logger.Warn("The MaximumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MaximumPermissibleValue, measurementScale.Iid); } } if (!string.IsNullOrWhiteSpace(measurementScale.MinimumPermissibleValue)) { double realMinimumPermissibleValue; isMinimumPermissibleValue = double.TryParse(measurementScale.MinimumPermissibleValue, NumberStyles.Integer, null, out realMinimumPermissibleValue); if (isMinimumPermissibleValue) { if (measurementScale.IsMinimumInclusive && real < realMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{real}\" is smaller than the minimum permissible value of \"{realMinimumPermissibleValue}\""; return(result); } if (!measurementScale.IsMinimumInclusive && real <= realMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = $"The value \"{real}\" is smaller than or equal to the minimum permissible value of \"{realMinimumPermissibleValue}\""; return(result); } } else { Logger.Warn("The MinimumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MinimumPermissibleValue, measurementScale.Iid); } } result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); default: throw new Exception("Invalid NumberSetKind"); } }
public void Setup() { this.domain = new DomainOfExpertise(); this.modelReferenceDataLibrary = new ModelReferenceDataLibrary(); this.iteration = new Iteration() { Element = { new ElementDefinition() { Owner = this.domain } }, Option = { new Option() }, Container = new EngineeringModel() { EngineeringModelSetup = new EngineeringModelSetup() { RequiredRdl = { this.modelReferenceDataLibrary }, Container = new SiteReferenceDataLibrary() { Container = new SiteDirectory() } } } }; this.hubController = new Mock <IHubController>(); this.hubController.Setup(x => x.OpenIteration).Returns(this.iteration); this.hubController.Setup(x => x.CurrentDomainOfExpertise).Returns(this.domain); this.hubController.Setup(x => x.GetSiteDirectory()).Returns(new SiteDirectory()); this.dstController = new Mock <IDstController>(); this.dstController.Setup(x => x.Map(It.IsAny <List <VariableRowViewModel> >())); this.variableRowViewModels = new List <VariableRowViewModel> { new VariableRowViewModel( (new ReferenceDescription() { NodeId = new ExpandedNodeId(Guid.NewGuid()), DisplayName = new LocalizedText("", "el.DummyVariable0") }, new DataValue() { Value = .2 })), new VariableRowViewModel( (new ReferenceDescription() { NodeId = new ExpandedNodeId(Guid.NewGuid()), DisplayName = new LocalizedText("", "res0.DummyVariable1") }, new DataValue())), new VariableRowViewModel( (new ReferenceDescription() { NodeId = new ExpandedNodeId(Guid.NewGuid()), DisplayName = new LocalizedText("", "trans0.Gain.DummyVariable2") }, new DataValue())) }; this.scale = new RatioScale() { Name = "scale", NumberSet = NumberSetKind.REAL_NUMBER_SET }; this.parameterType = new SampledFunctionParameterType() { Name = "TextXQuantity", IndependentParameterType = { new IndependentParameterTypeAssignment() { ParameterType = new TextParameterType() { Name = "IndependentText" } } }, DependentParameterType = { new DependentParameterTypeAssignment() { ParameterType = new SimpleQuantityKind() { Name = "DependentQuantityKing", DefaultScale = this.scale, PossibleScale ={ this.scale } } } } }; var invalidParameterType = new SampledFunctionParameterType() { Name = "TextXQuantity", IndependentParameterType = { new IndependentParameterTypeAssignment() { ParameterType = new CompoundParameterType() { Name = "IndependentText" } } }, DependentParameterType = { new DependentParameterTypeAssignment() { ParameterType = new SimpleQuantityKind() { Name = "DependentQuantityKing" } } } }; this.quantityKindParameterType = new SimpleQuantityKind() { DefaultScale = this.scale, PossibleScale = { this.scale }, Name = "SimpleQuantityKind" }; this.modelReferenceDataLibrary.ParameterType.Add(this.parameterType); this.modelReferenceDataLibrary.ParameterType.Add(invalidParameterType); this.statusBar = new Mock <IStatusBarControlViewModel>(); this.navigationService = new Mock <INavigationService>(); this.viewModel = new DstMappingConfigurationDialogViewModel( this.hubController.Object, this.dstController.Object, this.statusBar.Object, this.navigationService.Object); this.viewModel.Initialize(); this.viewModel.Variables.AddRange(this.variableRowViewModels); this.closeBehavior = new Mock <ICloseWindowBehavior>(); this.closeBehavior.Setup(x => x.Close()); }
/// <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> /// Process the <see cref="ParameterSubscriptionValueSet"/> . /// </summary> /// <param name="parameterSubscriptionValueSet"> /// The <see cref="ParameterSubscriptionValueSet"/> to be processed. /// </param> /// <param name="componentIndex"> /// The index of the <see cref="ParameterTypeComponent"/>. /// </param> /// <param name="currentRow"> /// The row in the Parameter sheet that contains the <see cref="ParameterValueSet"/>. /// </param> /// <param name="manualValue"> /// The manual value of the <see cref="ParameterValueSet"/>. /// </param> /// <param name="switchValue"> /// The string value of the <see cref="ParameterSwitchKind"/> of the <see cref="ParameterSubscriptionValueSet"/> /// </param> /// <param name="valuesets"> /// A <see cref="Dictionary{Guid,ProcessedValueSet}"/> of <see cref="ProcessedValueSet"/>s that capture the updated <see cref="Thing"/>s with its value validation result /// </param> /// <param name="provider"> /// The <see cref="IFormatProvider"/> used to validate. /// </param> /// <returns> /// The <see cref="ValidationResultKind"/> for the <see cref="ParameterSubscriptionValueSet"/> /// </returns> private void ProcessValueSet(ParameterSubscriptionValueSet parameterSubscriptionValueSet, int componentIndex, int currentRow, object manualValue, string switchValue, ref Dictionary <Guid, ProcessedValueSet> valuesets, IFormatProvider provider) { var validationResult = ValidationResultKind.InConclusive; var switchKind = ParameterSwitchKind.MANUAL; ParameterType parameterType = null; MeasurementScale measurementScale = null; ParameterSheetUtilities.QueryParameterTypeAndScale(parameterSubscriptionValueSet, componentIndex, out parameterType, out measurementScale); ValidationResult validSwitch; var isValidSwitchKind = Enum.IsDefined(typeof(ParameterSwitchKind), switchValue); if (isValidSwitchKind) { switchKind = (ParameterSwitchKind)Enum.Parse(typeof(ParameterSwitchKind), switchValue); validSwitch = new ValidationResult { ResultKind = ValidationResultKind.Valid, Message = string.Empty }; } else { switchKind = ParameterSwitchKind.MANUAL; validSwitch = new ValidationResult { ResultKind = ValidationResultKind.Invalid, Message = string.Format("{0} is not a valid Parameter Switch Kind", switchValue) }; } if (validSwitch.ResultKind > validationResult) { validationResult = validSwitch.ResultKind; } var validManualValue = new ValidationResult { ResultKind = ValidationResultKind.InConclusive, Message = string.Empty }; if (parameterType != null) { if (parameterType is TimeOfDayParameterType) { ParameterSheetUtilities.ConvertDoubleToDateTimeObject(ref manualValue, parameterType); } validManualValue = parameterType.Validate(manualValue, measurementScale, provider); if (validManualValue.ResultKind > validationResult) { validationResult = validManualValue.ResultKind; } } ParameterSheetUtilities.Decorate(validManualValue, this.parameterSheet, currentRow, ParameterSheetConstants.ManualColumn); ProcessedValueSet processedValueSet; var valueSetExists = valuesets.TryGetValue(parameterSubscriptionValueSet.Iid, out processedValueSet); if (!valueSetExists) { processedValueSet = new ProcessedValueSet(parameterSubscriptionValueSet, validationResult); } ValueSetValues valueSetValues; if (processedValueSet.IsDirty(componentIndex, parameterType, switchKind, manualValue, null, null, null, out valueSetValues)) { processedValueSet.UpdateClone(valueSetValues); if (!valueSetExists) { valuesets.Add(parameterSubscriptionValueSet.Iid, processedValueSet); } } }
/// <summary> /// Add an Scale row view model to the list of <see cref="MeasurementScale"/> /// </summary> /// <param name="scale"> /// The <see cref="Scale"/> that is to be added /// </param> private IMeasurementScaleRowViewModel <MeasurementScale> AddScaleRowViewModel(MeasurementScale scale) { var cyclicRatioScale = scale as CyclicRatioScale; if (cyclicRatioScale != null) { return(new CyclicRatioScaleRowViewModel(cyclicRatioScale, this.Session, this)); } var ordinalScale = scale as OrdinalScale; if (ordinalScale != null) { return(new OrdinalScaleRowViewModel(ordinalScale, this.Session, this)); } var ratioScale = scale as RatioScale; if (ratioScale != null) { return(new RatioScaleRowViewModel(ratioScale, this.Session, this)); } var intervalScale = scale as IntervalScale; if (intervalScale != null) { return(new IntervalScaleRowViewModel(intervalScale, this.Session, this)); } var logarithmicScale = scale as LogarithmicScale; if (logarithmicScale != null) { return(new LogarithmicScaleRowViewModel(logarithmicScale, this.Session, this)); } throw new Exception("No MeasurementScale to return"); }
public DataAttribute CreateDataAttribute(string shortName, string name, string description, bool isMultiValue, bool isBuiltIn, string scope, MeasurementScale measurementScale, DataContainerType containerType, string entitySelectionPredicate, DataType dataType, Unit unit, Methodology methodology, Classifier classifier, ICollection<AggregateFunction> functions, ICollection<GlobalizationInfo> globalizationInfos, ICollection<Constraint> constraints, ICollection<ExtendedProperty> extendedProperies ) { Contract.Requires(!string.IsNullOrWhiteSpace(shortName)); Contract.Requires(dataType != null && dataType.Id >= 0); Contract.Requires(unit != null && unit.Id >= 0); Contract.Ensures(Contract.Result<DataAttribute>() != null && Contract.Result<DataAttribute>().Id >= 0); DataAttribute e = new DataAttribute() { ShortName = shortName, Name = name, Description = description, IsMultiValue = isMultiValue, IsBuiltIn = isBuiltIn, Scope = scope, MeasurementScale = measurementScale, ContainerType = containerType, EntitySelectionPredicate = entitySelectionPredicate, DataType = dataType, Unit = unit, Methodology = methodology, AggregateFunctions = functions, GlobalizationInfos = globalizationInfos, Constraints = constraints, ExtendedProperties = extendedProperies, }; if (classifier != null && classifier.Id > 0) e.Classification = classifier; using (IUnitOfWork uow = this.GetUnitOfWork()) { IRepository<DataAttribute> repo = uow.GetRepository<DataAttribute>(); repo.Put(e); uow.Commit(); } return (e); }
public void Setup() { this.scaleValueDefinition = new ScaleValueDefinition(Guid.NewGuid(), 0); this.containerMeasurementScale = new OrdinalScale(Guid.NewGuid(), 0) { ValueDefinition = { this.scaleValueDefinition.Iid } }; this.rootMappingToReferenceScale = new MappingToReferenceScale(Guid.NewGuid(), 0) { ReferenceScaleValue = this.scaleValueDefinition.Iid, DependentScaleValue = this.scaleValueDefinition.Iid }; this.rootMeasurementScale = new OrdinalScale(Guid.NewGuid(), 0) { MappingToReferenceScale = { this.rootMappingToReferenceScale.Iid } }; // RDL chain: mrdl -> srdl this.srdl = new SiteReferenceDataLibrary(Guid.NewGuid(), 0); this.mrdl = new ModelReferenceDataLibrary(Guid.NewGuid(), 0) { Scale = { this.rootMeasurementScale.Iid, this.containerMeasurementScale.Iid, }, RequiredRdl = this.srdl.Iid }; // setup services this.npgsqlTransaction = null; this.securityContext = new Mock <ISecurityContext>(); this.siteReferenceDataLibraryService = new Mock <ISiteReferenceDataLibraryService>(); this.siteReferenceDataLibraryService .Setup(x => x.Get( this.npgsqlTransaction, It.IsAny <string>(), null, It.IsAny <ISecurityContext>())) .Returns(new List <ReferenceDataLibrary> { this.srdl }); this.mappingToReferenceScaleService = new Mock <IMappingToReferenceScaleService>(); this.mappingToReferenceScaleService .Setup(x => x.Get( this.npgsqlTransaction, It.IsAny <string>(), It.IsAny <IEnumerable <Guid> >(), It.IsAny <ISecurityContext>())) .Returns <NpgsqlTransaction, string, IEnumerable <Guid>, ISecurityContext>( (transaction, partition, iids, context) => { iids = iids.ToList(); return(new List <Thing> { this.rootMappingToReferenceScale }.Where(qk => iids.Contains(qk.Iid))); }); this.scaleValueDefinitionService = new Mock <IScaleValueDefinitionService>(); this.scaleValueDefinitionService .Setup(x => x.Get( this.npgsqlTransaction, It.IsAny <string>(), It.IsAny <IEnumerable <Guid> >(), It.IsAny <ISecurityContext>())) .Returns <NpgsqlTransaction, string, IEnumerable <Guid>, ISecurityContext>( (transaction, partition, iids, context) => { iids = iids.ToList(); return(new List <Thing> { this.scaleValueDefinition }.Where(qk => iids.Contains(qk.Iid))); }); this.measurementScaleService = new Mock <IMeasurementScaleService>(); this.measurementScaleService .Setup(x => x.Get( this.npgsqlTransaction, It.IsAny <string>(), null, It.IsAny <ISecurityContext>())) .Returns(new List <MeasurementScale> { this.rootMeasurementScale, this.containerMeasurementScale }); this.sideEffect = new MeasurementScaleSideEffect { SiteReferenceDataLibraryService = this.siteReferenceDataLibraryService.Object, MappingToReferenceScaleService = this.mappingToReferenceScaleService.Object, ScaleValueDefinitionService = this.scaleValueDefinitionService.Object, MeasurementScaleService = this.measurementScaleService.Object }; }
/// <summary> /// Verify that the <paramref name="parameterType"/> is compatible with this dst adapter /// </summary> /// <param name="parameterType">The <see cref="SampledFunctionParameterType"/></param> /// <param name="value">The <see cref="object"/> value</param> /// <param name="scale">The <see cref="MeasurementScale"/></param> /// <returns>A value indicating if the <paramref name="parameterType"/> is compliant</returns> public static bool Validate(this SampledFunctionParameterType parameterType, object value, MeasurementScale scale = null) { if (!parameterType.HasTheRightNumberOfParameterType(out var independantParameterType, out var dependantParameterType)) { return(false); } var independentValidation = independantParameterType.IsQuantityKindOrText(); var measurementScale = scale ?? (dependantParameterType as QuantityKind)?.DefaultScale; var validate = dependantParameterType.Validate(value, measurementScale); var dependentValidation = validate.ResultKind == ValidationResultKind.Valid; return(independentValidation && dependentValidation); }
/// <summary> /// Adds a <see cref="MeasurementScaleRowViewModel"/> /// </summary> /// <param name="scale"> /// The associated <see cref="MeasurementScale"/> for which the row is to be added. /// </param> private void AddMeasurementScaleRowViewModel(MeasurementScale scale) { var row = new MeasurementScaleRowViewModel(scale, this.Session, this); this.MeasurementScales.Add(row); }
/// <summary> /// Initializes a new instance of the <see cref="ParameterTypeColumn"/> class. /// </summary> /// <param name="parameterType"> /// The <see cref="CDP4Common.SiteDirectoryData.ParameterType"/> of the <see cref="ParameterTypeColumn"/> /// </param> /// <param name="measurementScale"> /// The <see cref="CDP4Common.SiteDirectoryData.MeasurementScale"/> of the <see cref="ParameterTypeColumn"/> /// </param> /// <param name="column"> /// the column number of the <see cref="ParameterTypeColumn"/> /// </param> public ParameterTypeColumn(ParameterType parameterType, MeasurementScale measurementScale, int column) { this.ParameterType = parameterType; this.MeasurementScale = measurementScale; this.Column = column; }
/// <summary> /// Returns the <see cref="AttributeValue"/> representation of the value of a <see cref="SimpleParameterValue"/> /// </summary> /// <param name="parameterType">The <see cref="ParameterType"/></param> /// <param name="attributeDefinition">The associated <see cref="AttributeDefinition"/></param> /// <param name="valuearray">The <see cref="ValueArray{String}"/> containing the values</param> /// <param name="scale">The scale used</param> /// <returns>The <see cref="AttributeValue"/></returns> private AttributeValue ToReqIfAttributeValue(ParameterType parameterType, AttributeDefinition attributeDefinition, ValueArray <string> valuearray, MeasurementScale scale = null) { if (parameterType == null) { throw new ArgumentNullException("parameterType"); } if (parameterType is EnumerationParameterType) { var enumParameterType = (EnumerationParameterType)parameterType; var concatEnumValue = valuearray.Single(); var enumValues = concatEnumValue.Split(parameterEnumSeparator).Select(x => x.Trim()); // retrieve the list of litteral var valueDefinitions = enumParameterType.ValueDefinition.Where(x => enumValues.Contains(x.ShortName)).ToList(); // Assuming the model is not wrong the values in the SimpleParameterValue references the ValueDefinition by its ShortName var attributeValue = new AttributeValueEnumeration { Definition = (AttributeDefinitionEnumeration)attributeDefinition }; var reqIfEnumValues = ((DatatypeDefinitionEnumeration)attributeDefinition.DatatypeDefinition).SpecifiedValues; attributeValue.Values.AddRange(valueDefinitions.Select(x => reqIfEnumValues.Single(e => e.Properties.OtherContent == x.ShortName))); return(attributeValue); } if (parameterType is DateParameterType || parameterType is DateTimeParameterType || parameterType is TimeOfDayParameterType) { var value = valuearray.SingleOrDefault(); DateTime date; if (!DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out date)) { throw new InvalidOperationException(string.Format("The string {0} cannot be parsed to a DateTime", value)); } return(new AttributeValueDate { TheValue = date, Definition = (AttributeDefinitionDate)attributeDefinition }); } if (parameterType is TextParameterType) { var value = valuearray.Single(); return(new AttributeValueString { TheValue = value, Definition = (AttributeDefinitionString)attributeDefinition }); } if (parameterType is BooleanParameterType) { var value = valuearray.Single(); var boolean = Boolean.Parse(value); return(new AttributeValueBoolean { TheValue = boolean, Definition = (AttributeDefinitionBoolean)attributeDefinition }); } if (parameterType is QuantityKind) { var value = valuearray.Single(); return(new AttributeValueString { TheValue = string.Format("{0} [{1}]", value, scale != null ? scale.ShortName : "-"), Definition = (AttributeDefinitionString)attributeDefinition }); } // CompoundParameterType var compoundType = (CompoundParameterType)parameterType; var theValue = "Error: The value could not be parsed."; if (valuearray.Count() == compoundType.Component.Count) { var values = new List <string>(); for (var i = 0; i < valuearray.Count(); i++) { var component = compoundType.Component[i].Scale != null ? compoundType.Component[i].Scale.ShortName : "-"; values.Add(string.Format("{0}: {1} [{2}]", compoundType.Component[i].ShortName, valuearray[i], component)); } theValue = string.Format("{{ {0} }}", string.Join(", ", values)); } return(new AttributeValueString { TheValue = theValue, Definition = (AttributeDefinitionString)attributeDefinition }); }
/// <summary> /// Initializes a new instance of the <see cref="ExtraContribution"/> structure /// </summary> /// <param name="categories">The categories</param> /// <param name="total">The total</param> /// <param name="totalWithMargin">Thetotal with margin</param> /// <param name="quantityKind">The quantityKind</param> /// <param name="scale">The measurement-scale for this extra-contribution</param> public ExtraContribution(IReadOnlyList <Category> categories, float total, float totalWithMargin, QuantityKind quantityKind, MeasurementScale scale) { this.Categories = categories; this.TotalContribution = total; this.TotalWithMargin = totalWithMargin; this.QuantityKind = quantityKind; this.Scale = scale; }
/// <summary> /// Returns the excel format string based on a <see cref="ParameterType"/> /// </summary> /// <param name="parameterType"> /// an instance of <see cref="ParameterType"/> that is used to determine the format string /// </param> /// <param name="measurementScale"> /// The optional <see cref="MeasurementScale"/> in case the <see cref="ParameterType"/> is a <see cref="QuantityKind"/> /// </param> /// <returns> /// an excel format string, the default value is "@" /// </returns> public static string Format(ParameterType parameterType, MeasurementScale measurementScale = null) { var booleanParameterType = parameterType as BooleanParameterType; if (booleanParameterType != null) { return("@"); } var compoundParameterType = parameterType as CompoundParameterType; if (compoundParameterType != null) { return("@"); } var dateParameterType = parameterType as DateParameterType; if (dateParameterType != null) { return("yyyy-mm-dd"); } var dateTimeParameterType = parameterType as DateTimeParameterType; if (dateTimeParameterType != null) { return("yyyy-mm-dd hh:mm:ss"); } var enumerationParameterType = parameterType as EnumerationParameterType; if (enumerationParameterType != null) { return("@"); } var quantityKind = parameterType as QuantityKind; if (quantityKind != null) { if (measurementScale != null) { return(measurementScale.NumberSet == NumberSetKind.INTEGER_NUMBER_SET ? "0" : "general"); } return("@"); } var textParameterType = parameterType as TextParameterType; if (textParameterType != null) { return("@"); } var timeOfDayParameterType = parameterType as TimeOfDayParameterType; if (timeOfDayParameterType != null) { return("hh:mm:ss"); } return("@"); }
/// <summary> /// Validates whether the provided value is valid with respect to the <see cref="MeasurementScale"/> /// </summary> /// <param name="measurementScale"> /// The <see cref="MeasurementScale"/> /// </param> /// <param name="value"> /// The value that is to be validated /// </param> /// <returns> /// a <see cref="ValidationResult"/> that carries the <see cref="ValidationResultKind"/> and an optional message. /// </returns> public static ValidationResult Validate(this MeasurementScale measurementScale, string value) { ValidationResult result; bool isMaximumPermissibleValue; bool isMinimumPermissibleValue; switch (measurementScale.NumberSet) { case NumberSetKind.INTEGER_NUMBER_SET: int integer; var isInteger = int.TryParse(value, NumberStyles.Integer, null, out integer); if (!isInteger) { result.ResultKind = ValidationResultKind.Invalid; result.Message = string.Format("\"{0}\" is not a member of the INTEGER NUMBER SET", value); return(result); } if (!string.IsNullOrWhiteSpace(measurementScale.MaximumPermissibleValue)) { int intMaximumPermissibleValue; isMaximumPermissibleValue = int.TryParse(measurementScale.MaximumPermissibleValue, NumberStyles.Integer, null, out intMaximumPermissibleValue); if (isMaximumPermissibleValue) { if (measurementScale.IsMaximumInclusive && integer > intMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is greater than the maximium permissible value of \"{1}\"", integer, intMaximumPermissibleValue); return(result); } if (!measurementScale.IsMaximumInclusive && integer >= intMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is greater than or equal to the maximium permissible value of \"{1}\"", integer, intMaximumPermissibleValue); return(result); } } else { Logger.Warn("The MaximumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MaximumPermissibleValue, measurementScale.Iid); } } if (!string.IsNullOrWhiteSpace(measurementScale.MinimumPermissibleValue)) { int intMinimumPermissibleValue; isMinimumPermissibleValue = int.TryParse(measurementScale.MinimumPermissibleValue, NumberStyles.Integer, null, out intMinimumPermissibleValue); if (isMinimumPermissibleValue) { if (measurementScale.IsMinimumInclusive && integer < intMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is smaller than the minimum permissible value of \"{1}\"", integer, intMinimumPermissibleValue); return(result); } if (!measurementScale.IsMinimumInclusive && integer <= intMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is smaller than or equal to the minimum permissible value of \"{1}\"", integer, intMinimumPermissibleValue); return(result); } } else { Logger.Warn("The MinimumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MinimumPermissibleValue, measurementScale.Iid); } } result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); case NumberSetKind.NATURAL_NUMBER_SET: int natural; var isNatural = int.TryParse(value, NumberStyles.Integer, null, out natural); if (!isNatural) { result.ResultKind = ValidationResultKind.Invalid; result.Message = string.Format("\"{0}\" is not a member of the NATURAL NUMBER SET", value); return(result); } if (natural < 0) { result.ResultKind = ValidationResultKind.Invalid; result.Message = string.Format("\"{0}\" is not a member of the NATURAL NUMBER SET", value); return(result); } if (!string.IsNullOrWhiteSpace(measurementScale.MaximumPermissibleValue)) { int naturalMaximumPermissibleValue; isMaximumPermissibleValue = int.TryParse(measurementScale.MaximumPermissibleValue, NumberStyles.Integer, null, out naturalMaximumPermissibleValue); if (isMaximumPermissibleValue) { if (measurementScale.IsMaximumInclusive && natural > naturalMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is greater than the maximium permissible value of \"{1}\"", natural, naturalMaximumPermissibleValue); return(result); } if (!measurementScale.IsMaximumInclusive && natural >= naturalMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is greater than or equal to the maximium permissible value of \"{1}\"", natural, naturalMaximumPermissibleValue); return(result); } } else { Logger.Warn("The MaximumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MaximumPermissibleValue, measurementScale.Iid); } } if (!string.IsNullOrWhiteSpace(measurementScale.MinimumPermissibleValue)) { int naturalMinimumPermissibleValue; isMinimumPermissibleValue = int.TryParse(measurementScale.MinimumPermissibleValue, NumberStyles.Integer, null, out naturalMinimumPermissibleValue); if (isMinimumPermissibleValue) { if (measurementScale.IsMinimumInclusive && natural < naturalMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is smaller than the minimum permissible value of \"{1}\"", natural, naturalMinimumPermissibleValue); return(result); } if (!measurementScale.IsMinimumInclusive && natural <= naturalMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is smaller than or equal to the minimum permissible value of \"{1}\"", natural, naturalMinimumPermissibleValue); return(result); } } else { Logger.Warn("The MinimumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MinimumPermissibleValue, measurementScale.Iid); } } result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); case NumberSetKind.RATIONAL_NUMBER_SET: Logger.Warn("RATIONAL NUMBER SET currently not validated and always returns ValidationResultKind.Valid"); result.ResultKind = ValidationResultKind.Valid; result.Message = "RATIONAL NUMBER SET are not validated"; return(result); case NumberSetKind.REAL_NUMBER_SET: double real; var isReal = double.TryParse(value, NumberStyles.Float, null, out real); if (!isReal) { result.ResultKind = ValidationResultKind.Invalid; result.Message = string.Format("\"{0}\" is not a member of the REAL NUMBER SET", value); return(result); } if (!string.IsNullOrWhiteSpace(measurementScale.MaximumPermissibleValue)) { double realMaximumPermissibleValue; isMaximumPermissibleValue = double.TryParse(measurementScale.MaximumPermissibleValue, NumberStyles.Float, null, out realMaximumPermissibleValue); if (isMaximumPermissibleValue) { if (measurementScale.IsMaximumInclusive && real > realMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is greater than the maximium permissible value of \"{1}\"", real, realMaximumPermissibleValue); return(result); } if (!measurementScale.IsMaximumInclusive && real >= realMaximumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is greater than or equal to the maximium permissible value of \"{1}\"", real, realMaximumPermissibleValue); return(result); } } else { Logger.Warn("The MaximumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MaximumPermissibleValue, measurementScale.Iid); } } if (!string.IsNullOrWhiteSpace(measurementScale.MinimumPermissibleValue)) { double realMinimumPermissibleValue; isMinimumPermissibleValue = double.TryParse(measurementScale.MinimumPermissibleValue, NumberStyles.Integer, null, out realMinimumPermissibleValue); if (isMinimumPermissibleValue) { if (measurementScale.IsMinimumInclusive && real < realMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is smaller than the minimum permissible value of \"{1}\"", real, realMinimumPermissibleValue); return(result); } if (!measurementScale.IsMinimumInclusive && real <= realMinimumPermissibleValue) { result.ResultKind = ValidationResultKind.OutOfBounds; result.Message = string.Format("The value \"{0}\" is smaller than or equal to the minimum permissible value of \"{1}\"", real, realMinimumPermissibleValue); return(result); } } else { Logger.Warn("The MinimumPermissibleValue \"{0}\" of MeasurementScale \"{1}\" is not a member of the INTEGER NUMBER SET", measurementScale.MinimumPermissibleValue, measurementScale.Iid); } } result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); default: throw new Exception("Invalid NumberSetKind"); } }
/// <summary> /// Convert a parameter value and scale. /// </summary> /// <param name="elementDefinitionShortName"> The element definition user friendly short name </param> /// <param name="parameterClone"> The parameter clone </param> /// <param name="oldScale"> The old scale. </param> /// <param name="newScale"> The new scale. </param> /// <param name="conversionFactor">the conversion factor in <see cref="double" /></param> private void ConvertParameterValueAndScale(string elementDefinitionShortName, Parameter parameterClone, string oldScale, MeasurementScale newScale, double conversionFactor) { var ownerShortName = parameterClone.Owner.ShortName; var errorCount = 0; foreach (var thingClone in parameterClone.ValueSet.Select(p => p.Clone(true))) { this.sessionService.Transactions.Add(new ThingTransaction(TransactionContextResolver.ResolveContext(thingClone), thingClone)); if (thingClone.Computed.Count == 1 && errorCount == 0) { var oldValue = thingClone.Computed[0]; thingClone.Computed[0] = this.ConvertNumericValue(oldValue, conversionFactor, ref errorCount); this.OutputReport(elementDefinitionShortName, parameterClone.UserFriendlyShortName, oldScale, newScale, ownerShortName, oldValue, thingClone.Computed[0], errorCount == 0); } if (thingClone.Manual.Count == 1 && errorCount == 0) { var oldValue = thingClone.Manual[0]; thingClone.Manual[0] = this.ConvertNumericValue(oldValue, conversionFactor, ref errorCount); this.OutputReport(elementDefinitionShortName, parameterClone.UserFriendlyShortName, oldScale, newScale, ownerShortName, oldValue, thingClone.Manual[0], errorCount == 0); } if (thingClone.Reference.Count == 1 && errorCount == 0) { var oldValue = thingClone.Reference[0]; thingClone.Reference[0] = this.ConvertNumericValue(oldValue, conversionFactor, ref errorCount); this.OutputReport(elementDefinitionShortName, parameterClone.UserFriendlyShortName, oldScale, newScale, ownerShortName, oldValue, thingClone.Reference[0], errorCount == 0); } this.sessionService.Transactions.Last().CreateOrUpdate(thingClone); } foreach (var thingClone in parameterClone.ParameterSubscription.SelectMany(p => p.ValueSet.Select(v => v.Clone(true)))) { var subscriber = (thingClone.Container as ParameterSubscription)?.Owner.ShortName; this.sessionService.Transactions.Add(new ThingTransaction(TransactionContextResolver.ResolveContext(thingClone), thingClone)); if (thingClone.Computed.Count == 1 && errorCount == 0) { var oldValue = thingClone.Computed[0]; thingClone.Computed[0] = this.ConvertNumericValue(oldValue, conversionFactor, ref errorCount); this.OutputReport(elementDefinitionShortName, parameterClone.UserFriendlyShortName, oldScale, newScale, subscriber, oldValue, thingClone.Computed[0], errorCount == 0, true); } if (thingClone.Manual.Count == 1 && errorCount == 0) { var oldValue = thingClone.Manual[0]; thingClone.Manual[0] = this.ConvertNumericValue(oldValue, conversionFactor, ref errorCount); this.OutputReport(elementDefinitionShortName, parameterClone.UserFriendlyShortName, oldScale, newScale, subscriber, oldValue, thingClone.Manual[0], errorCount == 0, true); } if (thingClone.Reference.Count == 1 && errorCount == 0) { var oldValue = thingClone.Reference[0]; thingClone.Reference[0] = this.ConvertNumericValue(oldValue, conversionFactor, ref errorCount); this.OutputReport(elementDefinitionShortName, parameterClone.UserFriendlyShortName, oldScale, newScale, subscriber, oldValue, thingClone.Reference[0], errorCount == 0, true); } this.sessionService.Transactions.Last().CreateOrUpdate(thingClone); } if (errorCount == 0) { var transaction = new ThingTransaction(TransactionContextResolver.ResolveContext(parameterClone), parameterClone); parameterClone.Scale = newScale; transaction.CreateOrUpdate(parameterClone); this.sessionService.Transactions.Add(transaction); } }
/// <summary> /// Queries the container of the <see cref="ParameterValueSet"/> for the <see cref="ParameterType"/> and <see cref="MeasurementScale"/> /// </summary> /// <param name="parameterSubscriptionValueSet"> /// The subject <see cref="ParameterSubscriptionValueSet"/> /// </param> /// <param name="componentIndex"> /// The index of the <see cref="ParameterTypeComponent"/>. /// </param> /// <param name="parameterType"> /// The resulting <see cref="ParameterType"/> /// </param> /// <param name="measurementScale"> /// The resulting <see cref="MeasurementScale"/>, this may be null if the <see cref="ParameterType"/> is not a <see cref="QuantityKind"/> /// </param> public static void QueryParameterTypeAndScale(ParameterSubscriptionValueSet parameterSubscriptionValueSet, int componentIndex, out ParameterType parameterType, out MeasurementScale measurementScale) { var parameterSubscription = (ParameterSubscription)parameterSubscriptionValueSet.Container; var scalarParameterType = parameterSubscription.ParameterType as ScalarParameterType; if (scalarParameterType != null) { parameterType = scalarParameterType; measurementScale = parameterSubscription.Scale; return; } var compoundParameterType = parameterSubscription.ParameterType as CompoundParameterType; if (compoundParameterType != null) { var component = compoundParameterType.Component[componentIndex]; parameterType = component.ParameterType; measurementScale = component.Scale; return; } logger.Debug("The ParameterType and MeasurementScale of ParameterSubscriptionValueSet {0} could not be queried", parameterSubscriptionValueSet.Iid); parameterType = null; measurementScale = null; }
/// <summary> /// Validates the to check whether the <paramref name="value"/> is valid with respect to the <paramref name="parameterType"/> /// </summary> /// <param name="parameterType"> /// A <see cref="BooleanParameterType"/> /// </param> /// <param name="value"> /// The string value that is to be validated /// </param> /// <param name="measurementScale"> /// The measurement Scale. /// </param> /// <returns> /// a <see cref="ValidationResult"/> that carries the <see cref="ValidationResultKind"/> and an optional message. /// </returns> public static ValidationResult Validate(this ParameterType parameterType, string value, MeasurementScale measurementScale = null) { ValidationResult result; if (value == DefaultValue) { result.ResultKind = ValidationResultKind.Valid; result.Message = string.Empty; return(result); } switch (parameterType.ClassKind) { case ClassKind.BooleanParameterType: var booleanParameter = (BooleanParameterType)parameterType; return(booleanParameter.Validate(value)); case ClassKind.DateParameterType: var dateParameterType = (DateParameterType)parameterType; return(dateParameterType.Validate(value)); case ClassKind.DateTimeParameterType: var dateTimeParameterType = (DateTimeParameterType)parameterType; return(dateTimeParameterType.Validate(value)); case ClassKind.EnumerationParameterType: var enumerationParameterType = (EnumerationParameterType)parameterType; return(enumerationParameterType.Validate(value)); case ClassKind.QuantityKind: case ClassKind.SimpleQuantityKind: case ClassKind.DerivedQuantityKind: case ClassKind.SpecializedQuantityKind: var quantityKind = (QuantityKind)parameterType; return(quantityKind.Validate(measurementScale, value)); case ClassKind.TextParameterType: var textParameterType = (TextParameterType)parameterType; return(textParameterType.Validate(value)); case ClassKind.TimeOfDayParameterType: var timeOfDayParameterType = (TimeOfDayParameterType)parameterType; return(timeOfDayParameterType.Validate(value)); default: throw new NotSupportedException(string.Format("The Validate method is not suported for parameterType: {0}", parameterType)); } }