Ejemplo n.º 1
0
        /// <summary>
        /// Modifies the public fields values, of a target instance, with the values of another instance of the same type.
        /// Allows to indicate (true) whether the values must be compared in order to apply the change if them are different,
        /// else (false) the change will be forced for all.
        /// Returns whether any change -forced or not- was applied.
        /// </summary>
        public static bool AlterInstanceFields <TType>(ref TType Target, TType Source, bool ComparePriorToChange)
        {
            bool   ChangeWasApplied = false;
            object TargetValue, SourceValue;

            if (ComparePriorToChange)
            {
                foreach (FieldInfo FieldData in typeof(TType).GetFields())
                {
                    TargetValue = FieldData.GetValue(Target);
                    SourceValue = FieldData.GetValue(Source);

                    if ((TargetValue != null && SourceValue != null && !TargetValue.Equals(SourceValue)) ||
                        (TargetValue == null && SourceValue != null) || (TargetValue != null && SourceValue == null))
                    {
                        FieldData.SetValue(Target, SourceValue);
                        ChangeWasApplied = true;
                    }
                }
            }
            else
            {
                foreach (FieldInfo FieldData in typeof(TType).GetFields())
                {
                    FieldData.SetValue(Target, FieldData.GetValue(Source));
                }

                ChangeWasApplied = true;
            }

            return(ChangeWasApplied);
        }
Ejemplo n.º 2
0
 protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
 {
     base.OnPropertyChanged(e);
     if (e.Property == TargetProperty && e.NewValue != null)
     {
         SetAttachedHelper(Target, this);
         SetBinding(Attached.Slider.ValueStringFormatProperty, new Binding {
             Source = e.NewValue, Path = new PropertyPath(Attached.Slider.ValueStringFormatProperty), Mode = BindingMode.OneWay
         });
         SetBinding(TargetValueProperty, new Binding {
             Source = e.NewValue, Path = new PropertyPath(Slider.ValueProperty), Mode = BindingMode.OneWay
         });
     }
     if (e.Property == Attached.Slider.ValueStringFormatProperty || e.Property == TargetValueProperty)
     {
         if (!String.IsNullOrEmpty(targetValueFormatString))
         {
             FormattedValue = String.Format(targetValueFormatString, TargetValue);
         }
         else
         {
             FormattedValue = TargetValue.ToString();
         }
     }
 }
Ejemplo n.º 3
0
        public async Task <ActionResult <TargetValue> > PostTargetValue(TargetValue targetValue)
        {
            _context.TargetValue.Add(targetValue);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetTargetValue", new { id = targetValue.Id }, targetValue));
        }
Ejemplo n.º 4
0
 protected override void Initialize()
 {
     if (mapping == null)
     {
         mapping = new Dictionary <AnimatorControllerParameterType, ParameterType>();
         foreach (string name in Enum.GetNames(typeof(AnimatorControllerParameterType)))
         {
             var acpt = (AnimatorControllerParameterType)Enum.Parse(typeof(AnimatorControllerParameterType), name, true);
             var pt   = (ParameterType)Enum.Parse(typeof(ParameterType), name, true);
             mapping[acpt] = pt;
         }
     }
     if (memberType.IsA <string>())
     {
         _value = new StringValue(member);
     }
     else if (memberType.IsA <int>())
     {
         _value = new HashValue(member);
     }
     else //Assuming it is a AnimatorControllerParameter
     {
         _value = new ACPValue(member);
     }
     _mask = attribute.Filter;
     FetchVariables();
 }
Ejemplo n.º 5
0
 /// <summary>
 /// 保存客户经理的指标目标值
 /// </summary>
 /// <param name="vals"></param>
 public void SaveManagerTargetValue(TargetVals vals)
 {
     if (vals != null && vals.TargetValues.Length > 0)
     {
         var valList = JSON.EncodeToEntity <List <TargetValueModel> >(vals.TargetValues);
         if (valList != null && valList.Count > 0)
         {
             foreach (var val in valList)
             {
                 var tv = _TargetValueCase.FirstOrDefault(p => p.YearMonth == vals.Month &&
                                                          p.TargetId == val.TargetId &&
                                                          p.DistrictId == vals.DistrictId &&
                                                          p.TargetTagId == vals.TargetTagId &&
                                                          p.ManagerNo == val.ManagerNo);
                 if (tv != null)
                 {
                     tv.TValue = val.TValue;
                 }
                 else
                 {
                     tv = new TargetValue {
                         YearMonth   = vals.Month,
                         TargetTagId = vals.TargetTagId,
                         DistrictId  = vals.DistrictId,
                         ManagerNo   = val.ManagerNo,
                         ManagerName = val.ManagerName,
                         TargetId    = val.TargetId,
                         TValue      = val.TValue,
                     };
                 }
                 _TargetValueCase.InsertOrUpdateAsync(tv);
             }
         }
     }
 }
Ejemplo n.º 6
0
        public override CCodeExpression destroy_value(TargetValue value, bool is_macro_definition = false)
        {
            var type = value.value_type;

            if (type is ArrayType)
            {
                var array_type = (ArrayType)type;

                if (!array_type.fixed_length)
                {
                    return(base.destroy_value(value, is_macro_definition));
                }

                requires_array_free = true;

                var ccall = new CCodeFunctionCall(get_destroy_func_expression(type));

                ccall = new CCodeFunctionCall(new CCodeIdentifier("_vala_array_destroy"));
                ccall.add_argument(get_cvalue_(value));
                ccall.add_argument(get_ccodenode(array_type.length));
                ccall.add_argument(new CCodeCastExpression(get_destroy_func_expression(array_type.element_type), "GDestroyNotify"));

                return(ccall);
            }
            else
            {
                return(base.destroy_value(value, is_macro_definition));
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// This takes the name of another field in the model and that fields expected value.
 /// If the dependentProperty equals the targetValue then return valid.
 /// </summary>
 /// <param name="dependentProperty">The name of the field to check</param>
 /// <param name="targetValue">The expected value of the passed in field</param>
 public RequiredIfAttribute(object dependentProperty, object targetValue)
 {
     _innerAttribute        = new RequiredAttribute();
     this.DependentProperty = dependentProperty;
     this.TargetValue       = targetValue;
     //If we have just a string then add it to an array. Otherwise if our object is already
     //an array then cast the object as an array
     if (DependentProperty.GetType().IsArray)
     {
         DependentPropertyArray = ((IEnumerable)DependentProperty).Cast <object>().Select(x => x.ToString()).ToArray();
     }
     else if (DependentProperty.GetType().ToString() == "System.String")
     {
         String DependentPropertyString = (String)DependentProperty;
         DependentPropertyArray = new String[1] {
             DependentPropertyString
         };
     }
     if (TargetValue.GetType().IsArray)
     {
         TargetValueArray = ((IEnumerable)TargetValue).Cast <object>().Select(x => x.ToString()).ToArray();
     }
     else
     {
         TargetValueArray = new object[1] {
             TargetValue
         };
     }
 }
Ejemplo n.º 8
0
        public override CCodeExpression get_array_length_cvalue(TargetValue value, int dim = -1)
        {
            var array_type = value.value_type as ArrayType;

            if (array_type != null && array_type.fixed_length)
            {
                return(get_ccodenode(array_type.length));
            }

            // dim == -1 => total size over all dimensions
            if (dim == -1)
            {
                if (array_type != null && array_type.rank > 1)
                {
                    CCodeExpression cexpr = get_array_length_cvalue(value, 1);
                    for (dim = 2; dim <= array_type.rank; dim++)
                    {
                        cexpr = new CCodeBinaryExpression(CCodeBinaryOperator.MUL, cexpr, get_array_length_cvalue(value, dim));
                    }
                    return(cexpr);
                }
                else
                {
                    dim = 1;
                }
            }

            List <CCodeExpression> size = ((GLibValue)value).array_length_cvalues;

            Debug.Assert(size != null && size.Count >= dim);
            return(size[dim - 1]);
        }
Ejemplo n.º 9
0
        public override TargetValue copy_value(TargetValue value, CodeNode node)
        {
            var type  = value.value_type;
            var cexpr = get_cvalue_(value);

            if (type is ArrayType)
            {
                var array_type = (ArrayType)type;

                if (!array_type.fixed_length)
                {
                    return(base.copy_value(value, node));
                }

                var temp_value = create_temp_value(type, false, node);

                var copy_call = new CCodeFunctionCall(new CCodeIdentifier(generate_array_copy_wrapper(array_type)));
                copy_call.add_argument(cexpr);
                copy_call.add_argument(get_cvalue_(temp_value));
                ccode.add_expression(copy_call);

                return(temp_value);
            }
            else
            {
                return(base.copy_value(value, node));
            }
        }
Ejemplo n.º 10
0
        private void SetTypeAndVersion(string targetValue)
        {
            if (targetValue.StartsWith(TargetValuePrefix.Core, true, CultureInfo.InvariantCulture))
            {
                Type    = TargetType.Core;
                Version = targetValue.Substring(TargetValuePrefix.Core.Length);
                return;
            }

            if (targetValue.StartsWith(TargetValuePrefix.Standard, true, CultureInfo.InvariantCulture))
            {
                Type    = TargetType.Standard;
                Version = targetValue.Substring(TargetValuePrefix.Standard.Length);
                return;
            }

            if (targetValue.StartsWith(TargetValuePrefix.FrameworkNew, true, CultureInfo.InvariantCulture))
            {
                Type    = TargetType.Framework;
                Version = VersionNumberFormatter.Format(TargetValue.Substring(TargetValuePrefix.FrameworkNew.Length));
                return;
            }

            if (targetValue.StartsWith(TargetValuePrefix.FrameworkOld, true, CultureInfo.InvariantCulture))
            {
                Type    = TargetType.Framework;
                Version = targetValue.Substring(TargetValuePrefix.FrameworkOld.Length);
                return;
            }

            throw new InvalidDotNetProjectException($"Could not determine {nameof(Type)} from '{targetValue}'.");
        }
Ejemplo n.º 11
0
        /// <inheritdoc/>
        public string ToDelimitedString()
        {
            CultureInfo culture = CultureInfo.CurrentCulture;

            return(string.Format(
                       culture,
                       StringHelper.StringFormatSequence(0, 23, Configuration.FieldSeparator),
                       Id,
                       SubstanceIdentifier?.ToDelimitedString(),
                       SubstanceStatus != null ? string.Join(Configuration.FieldRepeatSeparator, SubstanceStatus.Select(x => x.ToDelimitedString())) : null,
                       SubstanceType?.ToDelimitedString(),
                       InventoryContainerIdentifier?.ToDelimitedString(),
                       ContainerCarrierIdentifier?.ToDelimitedString(),
                       PositionOnCarrier?.ToDelimitedString(),
                       InitialQuantity.HasValue ? InitialQuantity.Value.ToString(Consts.NumericFormat, culture) : null,
                       CurrentQuantity.HasValue ? CurrentQuantity.Value.ToString(Consts.NumericFormat, culture) : null,
                       AvailableQuantity.HasValue ? AvailableQuantity.Value.ToString(Consts.NumericFormat, culture) : null,
                       ConsumptionQuantity.HasValue ? ConsumptionQuantity.Value.ToString(Consts.NumericFormat, culture) : null,
                       QuantityUnits?.ToDelimitedString(),
                       ExpirationDateTime.HasValue ? ExpirationDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       FirstUsedDateTime.HasValue ? FirstUsedDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       OnBoardStabilityDuration,
                       TestFluidIdentifiers != null ? string.Join(Configuration.FieldRepeatSeparator, TestFluidIdentifiers.Select(x => x.ToDelimitedString())) : null,
                       ManufacturerLotNumber,
                       ManufacturerIdentifier?.ToDelimitedString(),
                       SupplierIdentifier?.ToDelimitedString(),
                       OnBoardStabilityTime?.ToDelimitedString(),
                       TargetValue?.ToDelimitedString(),
                       EquipmentStateIndicatorTypeCode?.ToDelimitedString(),
                       EquipmentStateIndicatorValue?.ToDelimitedString()
                       ).TrimEnd(Configuration.FieldSeparator.ToCharArray()));
        }
Ejemplo n.º 12
0
        public override Expression BuildExpression(ParameterExpression pe, int indexPosition)
        {
            if (TargetValue.Count > 1)
            {
                var oexp1 = Expression.OrElse(
                    Expression.Equal(
                        Expression.ArrayIndex(pe, Expression.Constant(indexPosition)),
                        Expression.Constant(TargetValue[0])),
                    Expression.Equal(
                        Expression.ArrayIndex(pe, Expression.Constant(indexPosition)),
                        Expression.Constant(TargetValue[1])));

                for (var c1 = 2; c1 < TargetValue.Count; c1++)
                {
                    oexp1 = Expression.OrElse(oexp1,
                                              Expression.Equal(
                                                  Expression.ArrayIndex(pe, Expression.Constant(indexPosition)),
                                                  Expression.Constant(TargetValue[c1])));
                }

                return(Expression.Not(oexp1));
            }

            return(Expression.Not(Expression.Equal(
                                      Expression.ArrayIndex(pe, Expression.Constant(indexPosition)),
                                      Expression.Constant(TargetValue.First())
                                      )));
        }
Ejemplo n.º 13
0
        /// <inheritdoc/>
        public override string ModelSummary()
        {
            using (StringWriter htmlWriter = new StringWriter())
            {
                htmlWriter.Write("\r\n<div class=\"activityentry\">");
                htmlWriter.Write(CLEMModel.DisplaySummaryValueSnippet(Metric, "Metric not set"));
                if (TargetValue > 0)
                {
                    htmlWriter.Write("<span class=\"setvalue\">");
                    htmlWriter.Write(TargetValue.ToString("#,##0.##"));
                }
                else
                {
                    htmlWriter.Write("<span class=\"errorlink\">VALUE NOT SET");
                }

                htmlWriter.Write("</span> units per AE per day</div>");

                if (OtherSourcesValue > 0)
                {
                    htmlWriter.Write("\r\n<div class=\"activityentry\">");
                    htmlWriter.Write("<span class=\"setvalue\">" + OtherSourcesValue.ToString("#,##0.##") + "</span> is provided from sources outside the human food store</div>");
                }
                return(htmlWriter.ToString());
            }
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> PutTargetValue(int id, TargetValue targetValue)
        {
            if (id != targetValue.Id)
            {
                return(BadRequest());
            }

            _context.Entry(targetValue).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TargetValueExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Ejemplo n.º 15
0
		public override void store_local(LocalVariable local, TargetValue value, bool initializer, SourceReference source_reference = null) {
			if (!initializer && requires_destroy(local.variable_type)) {
				/* unref old value */
				ccode.add_expression(destroy_local(local));
			}

			store_value(get_local_cvalue(local), value, source_reference);
		}
Ejemplo n.º 16
0
        public void ReCalcSendCost()
        {
            switch (this.CostSets)
            {
            case ArCostSets.Fate:
            {
                var nFCv = new ObservableCollection <BindableValue <int> >();
                for (var i = 0; i < 5; i++)
                {
                    nFCv.Add(new BindableValue <int>(0));
                }
                nFCv[(int)ArResource.Fate].Value = -this.FateCost;

                this.SendingCost.ClearAllEvents();
                this.SendingCost = new ArCost()
                {
                    CostGroup = "Fate使用",
                    CostName  = FateType.Text(),
                    Items     = nFCv
                };
                break;
            }

            case ArCostSets.Damage:
            {
                var nDCv = new ObservableCollection <BindableValue <int> >();
                for (var i = 0; i < 5; i++)
                {
                    nDCv.Add(new BindableValue <int>(0));
                }
                nDCv[(int)TargetValue].Value = this.DamageCorrected;

                var nCostName = this.DamageBase.ToString("0;-0")
                                + this.DefPoint.ToString("-0;+0;#")
                                + this.DamageCorrect1.ToString("+0;-0;#")
                                + this.DamageCorrect2.ToString("+0;-0;#");
                //+ "="
                //+ ((this.DamageType == ArDamageType.Heal) ? this.DamageCorrected.ToString("0;-0;0") : this.DamageCorrected.ToString("-0;0;0"));

                this.SendingCost.ClearAllEvents();
                this.SendingCost = new ArCost()
                {
                    CostGroup = (DamageType == ArDamageType.Heal ? TargetValue.ResourceName() : "") + DamageType.Text(),
                    CostName  = nCostName,
                    Items     = nDCv
                };
                break;
            }

            case ArCostSets.SkillCost:
            {
                this.SendingCost = new ArCost(this.SelectedItem);
                break;
            }
            }
            this.SendingText = this.SendingCost.ToString();
            this.CostChanged?.Invoke(this, null);
        }
Ejemplo n.º 17
0
        public void SetsProperties()
        {
            var propInfo = typeof (SomeClass).GetProperties().First();

            var testee = new TargetValue<SomeClass>(propInfo);

            Assert.AreEqual("A", testee.PropertyName);
            Assert.AreEqual(typeof(string), testee.ValueType);
        }
 private void lst_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     if (TargetValue != null && TargetValue.Trim().Length > 0)
     {
         txt.Text       = TargetValue;
         IsDropDownOpen = false;
     }
     FocusTextBox();
 }
Ejemplo n.º 19
0
        public void SetsProperties()
        {
            var propInfo = typeof(SomeClass).GetProperties().First();

            var testee = new TargetValue <SomeClass>(propInfo);

            Assert.AreEqual("A", testee.PropertyName);
            Assert.AreEqual(typeof(string), testee.ValueType);
        }
Ejemplo n.º 20
0
        public static void BeginAnimation(IAnimatable Item, DependencyProperty dp, AnimationTimeline ATL, object FromValue, object ToValue, Action OnCompleted, SetExtentAnimationTimelineDelegate SetExtentValue)
        {
            if (ToValue == null)
            {
                return;
            }

            if (Item != null && Item is DependencyObject)
            {
                ATL.FillBehavior = FillBehavior.HoldEnd;

                if (SetExtentValue != null)
                {
                    SetExtentValue(ATL);
                }

                FillBehavior StatusValue = ATL.FillBehavior;
                ATL.FillBehavior = FillBehavior.Stop;

                DependencyObject ConvertItem = Item as DependencyObject;
                object           TargetValue = null;
                if (StatusValue == FillBehavior.Stop || ATL.AutoReverse)
                {
                    if (FromValue == null)
                    {
                        TargetValue = ConvertItem.GetValue(dp);
                    }
                    else
                    {
                        TargetValue = FromValue;
                    }
                }
                else
                {
                    TargetValue = ToValue;
                }

                ATL.Completed += new EventHandler(
                    delegate(object sender, EventArgs e)
                {
                    ConvertItem.SetValue(dp, TargetValue);
                    object CurValue = ConvertItem.GetValue(dp);
                    if (TargetValue != null && !TargetValue.Equals(CurValue))
                    {
                        return;
                    }

                    if (OnCompleted != null)
                    {
                        OnCompleted();
                    }
                });
                Item.BeginAnimation(dp, ATL, HandoffBehavior.SnapshotAndReplace);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Step the motor and return the resulting current value.
        /// </summary>
        /// <param name="timeStep"> The current timestep of the scene </param>
        public virtual Vector3 Step(float timeStep)
        {
            Vector3 errorValue, correctionValue;
            float   decayFactor;

            // If the motor is not enabled, we assume that we
            // have reached the target value, so simply just
            // return the target value that we have
            if (!Enabled)
            {
                return(TargetValue);
            }

            // Calculate the difference in the current and target values
            errorValue = TargetValue - CurrentValue;

            correctionValue = Vector3.Zero;

            // If the calculated error value is not zero
            if (!ErrorIsZero(errorValue))
            {
                // Calculate the error correction value
                // and add it to the current value
                correctionValue = StepError(timeStep, errorValue);
                CurrentValue   += correctionValue;

                // The desired value reduces to zero which also reduces the
                // difference with current
                // If the decay timescale is not infinite, we decay
                if (TargetValueDecayTimeScale != PxMotor.Infinite)
                {
                    decayFactor  = (1.0f / TargetValueDecayTimeScale) * timeStep;
                    TargetValue *= (1f - decayFactor);
                }
            }
            else
            {
                // Difference between what we have and target is small, Motor
                // is done
                if (TargetValue.ApproxEquals(Vector3.Zero, ErrorZeroThreshold))
                {
                    // The target can step down to nearly zero but not get
                    // there If close to zero it is really zero
                    TargetValue = Vector3.Zero;
                }

                // If the motor is done, set the current value to the target value
                CurrentValue = TargetValue;
            }

            // Update the last error as the most recently calculated error
            LastError = errorValue;

            return(correctionValue);
        }
Ejemplo n.º 22
0
		public override void store_field(Field field, TargetValue instance, TargetValue value, SourceReference source_reference = null) {
			var lvalue = get_field_cvalue(field, instance);
			var type = lvalue.value_type;
			if (lvalue.actual_value_type != null) {
				type = lvalue.actual_value_type;
			}
			if (requires_destroy(type)) {
				/* unref old value */
				ccode.add_expression(destroy_field(field, instance));
			}

			store_value(lvalue, value, source_reference);
		}
Ejemplo n.º 23
0
        // Compute the next step and return the new current value.
        // Returns the correction needed to move 'current' to 'target'.
        public virtual Vector3 Step(float timeStep)
        {
            if (!Enabled)
            {
                return(TargetValue);
            }

            Vector3 origTarget  = TargetValue;      // DEBUG
            Vector3 origCurrVal = CurrentValue;     // DEBUG

            Vector3 correction = Vector3.Zero;
            Vector3 error      = TargetValue - CurrentValue;

            if (!ErrorIsZero(error))
            {
                correction = StepError(timeStep, error);

                CurrentValue += correction;

                // The desired value reduces to zero which also reduces the difference with current.
                // If the decay time is infinite, don't decay at all.
                float decayFactor = 0f;
                if (TargetValueDecayTimeScale != BSMotor.Infinite)
                {
                    decayFactor  = (1.0f / TargetValueDecayTimeScale) * timeStep;
                    TargetValue *= (1f - decayFactor);
                }

                MDetailLog("{0},  BSVMotor.Step,nonZero,{1},origCurr={2},origTarget={3},timeStep={4},err={5},corr={6}",
                           BSScene.DetailLogZero, UseName, origCurrVal, origTarget,
                           timeStep, error, correction);
                MDetailLog("{0},  BSVMotor.Step,nonZero,{1},tgtDecayTS={2},decayFact={3},tgt={4},curr={5}",
                           BSScene.DetailLogZero, UseName, TargetValueDecayTimeScale, decayFactor, TargetValue, CurrentValue);
            }
            else
            {
                // Difference between what we have and target is small. Motor is done.
                if (TargetValue.ApproxEquals(Vector3.Zero, ErrorZeroThreshold))
                {
                    // The target can step down to nearly zero but not get there.  If close to zero
                    //     it is really zero.
                    TargetValue = Vector3.Zero;
                }
                CurrentValue = TargetValue;
                MDetailLog("{0},  BSVMotor.Step,zero,{1},origTgt={2},origCurr={3},currTgt={4},currCurr={5}",
                           BSScene.DetailLogZero, UseName, origCurrVal, origTarget, TargetValue, CurrentValue);
            }
            LastError = error;

            return(correction);
        }
Ejemplo n.º 24
0
            public void AddValidation(ClientModelValidationContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

                CheckForLocalizer(context);
                var errorMessage = GetErrorMessage(context.ModelMetadata.GetDisplayName());

                MergeAttribute(context.Attributes, "data-val", "true");
                MergeAttribute(context.Attributes, "data-val-requiredwhen", errorMessage);
                MergeAttribute(context.Attributes, "data-val-other", "#" + DependentProperty);
                MergeAttribute(context.Attributes, "data-val-otherval", TargetValue.ToString());
            }
Ejemplo n.º 25
0
 public override RandomValue GetRandomValue(int randomCount)
 {
     if (HasTargetValue())
     {
         if (HasRangeValue())
         {
             return(new RandomValueFromDoubleRangeWithTarget(ValueFrom.GetValueOrDefault(), ValueTo.GetValueOrDefault(), ValueDecimals, TargetValue.GetValueOrDefault(), TargetValueMinPercent.GetValueOrDefault(), randomCount));
         }
         return(new RandomValueFromListWithTarget <double>(ValueList, TargetValue.GetValueOrDefault(), TargetValueMinPercent.GetValueOrDefault(), randomCount));
     }
     if (HasRangeValue())
     {
         return(new RandomValueFromDoubleRange(ValueFrom.GetValueOrDefault(), ValueTo.GetValueOrDefault(), ValueDecimals));
     }
     return(new RandomValueFromList <double>(ValueList));
 }
Ejemplo n.º 26
0
        public void CreatesSetterExpression()
        {
            var propInfo = typeof(SomeClass).GetProperties().First();

            var testee = new TargetValue <SomeClass>(propInfo);

            Expression <Func <SomeSourceClass, string> > getter = x => x.X;

            var expr = testee.CreateSetter(getter);

            var sourceInstance = new SomeSourceClass();
            var targetInstance = new SomeClass();

            (expr as Expression <Func <SomeClass, SomeSourceClass, SomeClass> >).Compile()(targetInstance, sourceInstance);

            Assert.AreEqual("a value", targetInstance.A);
        }
Ejemplo n.º 27
0
        public void CreatesSetterExpression()
        {
            var propInfo = typeof(SomeClass).GetProperties().First();

            var testee = new TargetValue<SomeClass>(propInfo);

            Expression<Func<SomeSourceClass, string>> getter = x => x.X;

            var expr = testee.CreateSetter(getter);

            var sourceInstance = new SomeSourceClass();
            var targetInstance = new SomeClass();

            (expr as Expression<Func<SomeClass, SomeSourceClass, SomeClass>>).Compile()(targetInstance, sourceInstance);

            Assert.AreEqual("a value", targetInstance.A);
        }
        public override string GetCommandLineArguments()
        {
            ArgumentFormatter argFormatter = new ArgumentFormatter();
            StringBuilder     arguments    = new StringBuilder();

            arguments.Append(" " + argFormatter.GetFormattedArgument(Responses));
            arguments.Append(" " + argFormatter.GetFormattedArgument(ResponseTransformation, false));

            arguments.Append(" " + argFormatter.GetFormattedArgument(TargetValue.ToString(), false));

            arguments.Append(" " + argFormatter.GetFormattedArgument(ConfidenceInterval));
            arguments.Append(" " + argFormatter.GetFormattedArgument(NormalPlot));

            arguments.Append(" " + argFormatter.GetFormattedArgument(Significance, false));

            return(arguments.ToString().Trim());
        }
Ejemplo n.º 29
0
        /// <summary>
        ///     Parse the target value(s), this also depends on the type of the value so it should be called no matter which
        ///     changes
        /// </summary>
        private void ParseTargetValues()
        {
            _parsedTargetValues.Clear();

            if (string.IsNullOrEmpty(TargetValue))
            {
                return;
            }
            var parsedValues =
                from targetValue in TargetValue.Split(',')
                where !string.IsNullOrWhiteSpace(targetValue)
                select targetValue.Trim();

            foreach (var parsedValue in parsedValues)
            {
                _parsedTargetValues.Add(parsedValue);
            }
        }
        private void SetDescription()
        {
            switch (Type)
            {
            case TargetType.Framework:
                Description = _isOldStyleFormat ?
                              $".NET Framework {TargetValue.Substring(TargetValuePrefix.FrameworkOld.Length)}" :
                              $".NET Framework {VersionNumberFormatter.Format(TargetValue.Substring(TargetValuePrefix.FrameworkNew.Length))}";
                break;

            case TargetType.Core:
                Description = $".NET Core {TargetValue.Substring(TargetValuePrefix.Core.Length)}";
                break;

            case TargetType.Standard:
                Description = $".NET Standard {TargetValue.Substring(TargetValuePrefix.Standard.Length)}";
                break;

            default:
                throw new InvalidOperationException($"Unhandled {nameof(TargetType)}: {Type}.");
            }
        }
Ejemplo n.º 31
0
        void SetTargetValueEdit(TargetValueEdit targetValueEdit, TargetValue targetValue)
        {
            double multiplier = 1;

            if (targetValueEdit.Units == "%")
            {
                multiplier = 100.0;
            }
            targetValueEdit.Value = (targetValue.value * multiplier).ToString();
            if (targetValue.absoluteVariance != 0)
            {
                targetValueEdit.Variance = targetValue.absoluteVariance.ToString();
            }
            else
            {
                targetValueEdit.Variance = (100 * targetValue.relativeVariance).ToString() + "%";
            }
            targetValueEdit.Binding = targetValue.targetBinding.ToString();
            targetValueEdit.Drift   = targetValue.drift.ToString();
            targetValueEdit.Min     = targetValue.min.ToString();
            targetValueEdit.Max     = targetValue.max.ToString();
        }
Ejemplo n.º 32
0
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                // get a reference to the property this validation depends upon
                var containerType = validationContext.ObjectInstance.GetType();
                var field         = containerType.GetProperty(DependentProperty);


                if (field != null)
                {
                    // get the value of the dependent property
                    var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
                    // trim spaces of dependent value
                    if (dependentValue != null && dependentValue is string)
                    {
                        dependentValue = (dependentValue as string).Trim();

                        if (!AllowEmptyStrings && (dependentValue as string).Length == 0)
                        {
                            dependentValue = null;
                        }
                    }

                    // compare the value against the target value
                    if ((dependentValue == null && TargetValue == null) ||
                        (dependentValue != null && (TargetValue.Equals("*") || dependentValue.Equals(TargetValue))))
                    {
                        // match => means we should try validating this field
                        if (!_innerAttribute.IsValid(value))
                        {
                            // validation failed - return an error
                            return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName }));
                        }
                    }
                }

                return(ValidationResult.Success);
            }
Ejemplo n.º 33
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Finds the target.
		/// </summary>
		/// <param name="buildFile">The build file.</param>
		/// <param name="projectName">Name of the project.</param>
		/// <param name="fwroot">The fwroot.</param>
		/// <param name="projectPath">The project path.</param>
		/// ------------------------------------------------------------------------------------
		private void FindTarget(ref string buildFile, ref string projectName, string fwroot,
			string projectPath)
		{
			lock(m_Targets)
			{
				string originalProjectName = projectName;
				bool fTargetExists = true;
				if (m_Targets.Contains(originalProjectName))
				{
					TargetValue val = (TargetValue)m_Targets[originalProjectName];
					if (val == null)
						fTargetExists = false;
					else
					{
						projectName = val.projectName;
						buildFile = val.buildfile;
					}
				}
				else
				{
					// If the target exists in the build file, we compile that.
					// If it doesn't exist, we look for a file '*.build' in the project's
					// directory and build with that.
					// If even that doesn't exist, we quit and let Visual Studio do the compile.
					// If the buildFile is the same as what we had before, we speed up things
					// and don't perform the check
					if ((buildFile == m_buildFile && Path.GetExtension(projectPath) == ".csproj")
						|| TargetExists(buildFile, projectName, fwroot))
					{
						// we already have the correct build file
					}
					else
					{
						if (projectPath != null && projectPath.Length > 0)
						{
							DirectoryInfo dirInfo = new DirectoryInfo(Path.GetDirectoryName(projectPath));
							FileInfo[] buildfiles = dirInfo.GetFiles("*.build");
							string tmpBuildfile = string.Empty;
							if (buildfiles != null)
							{
								if (buildfiles.Length == 1)
								{	// there is exactly one *.build file
									tmpBuildfile = buildfiles[0].FullName;
								}
								else if (buildfiles.Length > 1)
								{
									foreach (FileInfo fileInfo in buildfiles)
									{
										if (fileInfo.Name == "build.build")
											tmpBuildfile = fileInfo.FullName;
									}
								}
							}
							if (tmpBuildfile != string.Empty)
							{
								OutputBuild.WriteLine(string.Format("Target \"{2}\" not found in {0}, using {1} instead",
									buildFile, tmpBuildfile, projectName));

								fwroot = Path.GetDirectoryName(Path.GetFullPath(projectPath));
								if (!TargetExists(tmpBuildfile, projectName, fwroot))
									projectName = "all";
								buildFile = tmpBuildfile;
								// projectName = string.Format("{0} -D:fwroot=\"{1}\"", projectName, fwroot);
							}
							else
							{
								fTargetExists = false;
							}
						}
						else
						{
							fTargetExists = false;
						}
					}
				}

				if (fTargetExists)
				{
					m_Targets[originalProjectName] = new TargetValue(buildFile, projectName);
				}
				else
				{
					m_Targets[originalProjectName] = null;
					System.Diagnostics.Debug.WriteLine("Target doesn't exist");
					OutputBuild.WriteLine(string.Format("Target \"{1}\" not found in {0}, performing VS build",
						buildFile, projectName));
					throw new TargetException("Target doesn't exist");
				}
			}
		}