Example #1
0
    private TurnError ActAnalyse(Ant ant, HexDirection direction)
    {
        if (direction == HexDirection.CENTER)
        {
            return(TurnError.ILLEGAL);
        }

        Vector2Int target = CoordConverter.MoveHex(ant.gameCoordinates, direction);

        TurnError tileError = CheckAnalyzability(target);

        if (tileError != TurnError.NONE)
        {
            return(tileError);
        }

        // Set all the fields of the response to 0
        TerrainType terrainType = TerrainType.NONE;
        AntType     antType     = AntType.NONE;
        bool        isAllied    = false;
        Value       foodValue   = Value.NONE;
        bool        egg         = false;

        if (terrain[target.x][target.y] == null || terrain[target.x][target.y].tile == null)
        {
        }                                                                                        // Leave everything like that
        else
        {
            terrainType = terrain[target.x][target.y].tile.Type;

            if (terrain[target.x][target.y].ant == null)
            {
            }                                                // Leave everything like that
            else
            {
                antType  = terrain[target.x][target.y].ant.Type;
                isAllied = terrain[target.x][target.y].ant.team.teamId == ant.team.teamId;

                terrain[target.x][target.y].ant.eventInputs.Add(new EventInputBump(CoordConverter.InvertDirection(direction)));
            }

            if (terrain[target.x][target.y].food == null)
            {
            }                                                 // Leave everything like that
            else
            {
                foodValue = ValueConverter.Convert(terrain[target.x][target.y].food.value, Const.FOOD_SIZE);
            }

            egg = terrain[target.x][target.y].egg != null;
            if (egg)
            {
                isAllied = terrain[target.x][target.y].egg.team.teamId == ant.team.teamId;
            }
        }

        ant.analyseReport = new AnalyseReport(terrainType, antType, egg, isAllied, foodValue, null);

        return(TurnError.NONE);
    }
Example #2
0
        public void DoConvertTest(object value, object expected, Type expectedType)
        {
            var    target = new ValueConverter();
            object actual = target.Convert(value, expectedType);

            actual.ShouldBe(expected);
        }
Example #3
0
        protected void SetTargetItemValue([NotNull] TTargetItem targetItem, [NotNull] TSourceItem sourceItem, [CanBeNull] TSourceItemValue sourceItemValue)
        {
            var valueConverterParameter = ValueConverter.ParameterAccessor.Get(sourceItem);
            var targetItemValue         = ValueConverter.Convert(sourceItemValue, typeof(TTargetItemValue), valueConverterParameter);

            SetTargetItemValue(targetItem, targetItemValue);
        }
        public void should_build()
        {
            ValueConverter converter = _aspNetObjectConversionFamily.Build(_registry, _property);

            converter.Convert(_context).ShouldEqual(_propertyValue);
            _context.VerifyAllExpectations();
        }
Example #5
0
 public void TestCustomValueConverters()
 {
     ValueConverter.AddValueConverter(new IPAddressConverter());
     Assert.Equal(IPAddress.Loopback, ValueConverter.Convert(typeof(IPAddress), "127.0.0.1"));
     Assert.Equal(IPAddress.IPv6Loopback, ValueConverter.Convert(typeof(IPAddress), "::1"));
     Assert.Equal(new IPAddress(new byte[] { 0, 0, 0, 0 }), ValueConverter.Convert(typeof(object), "0.0.0.0"));
     ValueConverter.ResetValueConverters();
 }
Example #6
0
        public void DoConvert_NullableNotNull_ConvertsToNull()
        {
            var      target = new ValueConverter();
            DateTime?value  = DateTime.Now;
            object   actual = target.Convert(value, typeof(DateTime?));

            actual.ShouldBe(value);
            actual.ShouldNotBeSameAs(value);
        }
        public override string Convert(string value, PrinterSettings settings)
        {
            if (settings.GetValue <bool>(enableOnKey))
            {
                return(sourceField.Convert(value, settings));
            }

            return(defaultValue);
        }
Example #8
0
        private object Convert(object value, BinarySerializationContext context)
        {
            if (ValueConverter == null)
            {
                return(value);
            }

            return(ValueConverter.Convert(value, ConverterParameter, context));
        }
Example #9
0
        /// <summary>
        /// Creates the dictionary.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns></returns>
        public object CreateDictionary(Document document)
        {
            if (document == null)
            {
                return(null);
            }

            return(document.ToDictionary(pair => (TKey)ValueConverter.Convert(pair.Key, typeof(TKey)), pair => (TValue)pair.Value));
        }
Example #10
0
 public void ConverterTest()
 {
     Assert.AreEqual(1, ValueConverter.Convert <int>("1"));
     Assert.IsInstanceOf <Color>(ValueConverter.Convert(typeof(Color), "(1,1,1)"));
     Assert.Throws <System.FormatException>(() => ValueConverter.Convert <bool>("1"));
     Assert.IsInstanceOf <int[]>(ValueConverter.Convert <int[]>("1#2#3"));
     ValueConverter.Register(i => Int32.Parse(i) * 2);
     Assert.AreEqual(4, ValueConverter.Convert <int>("2"));
     ValueConverter.Reset();
 }
Example #11
0
        public void DoConvert_NullableNull_ConvertsToNull(Type innerType)
        {
            var    target = new ValueConverter();
            Type   genericNullableType = typeof(Nullable <>);
            Type   concreteType        = genericNullableType.MakeGenericType(innerType);
            object value  = Activator.CreateInstance(concreteType);
            object actual = target.Convert(value, concreteType);

            actual.ShouldBe(null);
        }
Example #12
0
 public void TestBooleanValueConversion()
 {
     Assert.Equal(true, ValueConverter.Convert(typeof(bool), "true"));
     Assert.Equal(false, ValueConverter.Convert(typeof(bool), "false"));
     Assert.Equal(true, ValueConverter.Convert(typeof(bool), "on"));
     Assert.Equal(false, ValueConverter.Convert(typeof(bool), "off"));
     Assert.Equal(true, ValueConverter.Convert(typeof(bool), "yes"));
     Assert.Equal(false, ValueConverter.Convert(typeof(bool), "no"));
     Assert.Equal(true, ValueConverter.Convert(typeof(bool), "1"));
     Assert.Equal(false, ValueConverter.Convert(typeof(bool), "0"));
 }
        public override bool FromValue(string[] value)
        {
            IChromosome baseChromosome;

            if (!ValueConverter.Convert(out baseChromosome, value[0]))
            {
                return(false);
            }
            this.BaseChromosome = baseChromosome;
            return(true);
        }
Example #14
0
        public void build_passes_through()
        {
            var binder  = new PassthroughConverter <HttpPostedFileBase>();
            var context = MockRepository.GenerateMock <IPropertyContext>();

            context.Expect(c => c.PropertyValue).Return(new object());
            ValueConverter converter = binder.Build(MockRepository.GenerateStub <IValueConverterRegistry>(), property(x => x.File));

            converter.Convert(context);
            context.VerifyAllExpectations();
        }
Example #15
0
        /// <summary>
        /// Maps the given argument value.
        /// </summary>
        /// <param name="options">Options instance.</param>
        /// <param name="token">Value to map.</param>
        protected void AcceptArgumentValue(TOptions options, Token token)
        {
            // Convert
            var convertedValue = ValueConverter.Convert(_converter, Context, token.Value !);

            // Validate
            Validator.Validate(_validator, Context, convertedValue);

            // Map
            Mapper.MapValue(_mapper, Context, options, convertedValue);
        }
Example #16
0
        public sealed override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (ValidationPipe != null)
            {
                // Pass if another validator has already reported an error.
                if (ValidationPipe.Error != null)
                {
                    return(ValidationResult.ValidResult);
                }

                // Checking this later might be a tiny bit faster.
                if (!IsEnforced.Value)
                {
                    return(ValidationResult.ValidResult);
                }

                var isValid = ValidateValue(ValueConverter != null
                    ? ValueConverter.Convert(value, typeof(object), null, cultureInfo)
                    : value, cultureInfo);

                if (!isValid)
                {
                    var error = ErrorProvider.GetErrorMessage(value);
                    if (StrictValidation)
                    {
                        // If we're going to stop propagation, we need to make sure
                        // that the pipe is clean for the next turn.
                        ValidationPipe.Error = null;
                        return(new ValidationResult(false, error));
                    }

                    ValidationPipe.Error = error;
                }

                return(ValidationResult.ValidResult);
            }
            else
            {
                if (!IsEnforced.Value)
                {
                    return(ValidationResult.ValidResult);
                }

                // When there's no pipe validation must return eagerly.
                // Properties will not be updated this way as validation will stop binding.
                var isValid = ValidateValue(ValueConverter != null
                    ? ValueConverter.Convert(value, typeof(object), null, cultureInfo)
                    : value, cultureInfo);

                return(isValid
                    ? ValidationResult.ValidResult
                    : new ValidationResult(false, ErrorProvider.GetErrorMessage(value)));
            }
        }
        /// <summary>
        ///   Sets the value on the specified instance.
        /// </summary>
        /// <param name = "instance">The instance.</param>
        /// <param name = "value">The value.</param>
        public virtual void SetValue(object instance, object value)
        {
            try
            {
                value = ValueConverter.Convert(value, MemberReturnType);
            }
            catch (MongoException exception)
            {
                throw new MongoException("Con not convert value on type " + instance.GetType(), exception);
            }

            _setter(instance, value);
        }
Example #18
0
        public void TestCollectionConversion()
        {
            Assert.Equal(new Color[] { Color.Red }, ValueConverter.Convert(typeof(Color[]), "Red"));
            Assert.Equal(new Color[] { Color.Red | Color.Blue }, ValueConverter.Convert(typeof(Color[]), "5"));
            Assert.Equal(new int[] { -255 }, ValueConverter.Convert(typeof(int[]), "-0xff"));

            Assert.Equal(new List <int> {
                1
            }, ValueConverter.Convert(typeof(List <int>), "1"));
            Assert.Equal(new List <object> {
                false
            }, ValueConverter.Convert(typeof(List <object>), "False"));
        }
Example #19
0
    private TurnError ActCommunicate(Ant ant, HexDirection direction, AntWord word)
    {
        if (direction == HexDirection.CENTER)
        {
            return(TurnError.ILLEGAL);
        }

        Vector2Int target = CoordConverter.MoveHex(ant.gameCoordinates, direction);

        TurnError tileError = CheckCommunicability(target, ant);

        if (tileError != TurnError.NONE)
        {
            if (tileError == TurnError.NOT_ALLY)
            {
                terrain[target.x][target.y].ant.eventInputs.Add(new EventInputBump(CoordConverter.InvertDirection(direction)));
            }
            return(tileError);
        }

        if (ant.CheckEnergy(Const.GIVE_COST))
        {
            ant.UpdateEnergy(-Const.GIVE_COST);
        }
        else
        {
            return(TurnError.NO_ENERGY);
        }

        Ant receptor = terrain[target.x][target.y].ant;

        // Gives the info to the emitter
        ant.communicateReport = new CommunicateReport(
            receptor.Type,
            receptor.mindset,
            ValueConverter.Convert(receptor.hp),
            ValueConverter.Convert(receptor.energy),
            ValueConverter.Convert(receptor.carriedFood),
            AntWord.NONE);

        // Gives the cmmunication to the receptor
        receptor.eventInputs.Add(new EventInputComunicate(CoordConverter.InvertDirection(direction), new CommunicateReport(
                                                              ant.Type,
                                                              ant.mindset,
                                                              ValueConverter.Convert(ant.hp),
                                                              ValueConverter.Convert(ant.energy),
                                                              ValueConverter.Convert(ant.carriedFood),
                                                              word)));

        return(TurnError.NONE);
    }
Example #20
0
    public float Apply(JSONObject jsonDictionary)
    {
        if (colorGradient == null)
        {
            return(valueConverter.Convert(jsonDictionary.GetField(metricName).n));
        }
        else
        {
            Vector3 col = colorGradient.GetValue(valueConverter.Convert(jsonDictionary.GetField(metricName).n));
            switch (buildingProperty)
            {
            case BuildingProperty.Red:
                return(col.x);

            case BuildingProperty.Green:
                return(col.y);

            case BuildingProperty.Blue:
                return(col.z);
            }
            return(0);
        }
    }
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            Contract.Assume(values != null);
            Contract.Assume(values.Length == 2);

            if (targetType == null)
            {
                targetType = typeof(object);
            }

            Bind(values[0], targetType);

            if (!hasValue)
            {
                return(DependencyProperty.UnsetValue);
            }
            else if (ValueConverter != null)
            {
                return(ValueConverter.Convert(currentValue, targetType, ValueConverterParameter ?? parameter, ValueConverterCulture ?? culture));
            }
            else if (currentValue == null)
            {
                return(null);
            }
            else if (targetType.IsAssignableFrom(currentValue.GetType()))
            {
                return(currentValue);
            }
            else
            {
                var converter = TypeDescriptor.GetConverter(currentValue);

                if (converter == null || !converter.CanConvertTo(targetType))
                {
                    Contract.Assume(PresentationTraceSources.DataBindingSource != null);

                    PresentationTraceSources.DataBindingSource.TraceEvent(
                        TraceEventType.Verbose,
                        0,
                        "Subscription: The value \"{0}\" cannot be converted to the specified type \"{1}\".",
                        currentValue.GetType(),
                        targetType);

                    return(DependencyProperty.UnsetValue);
                }

                return(converter.ConvertTo(null, ValueConverterCulture ?? culture, currentValue, targetType));
            }
        }
Example #22
0
        public void TestEnumerationValueConversion()
        {
            Assert.Equal(Color.Red, ValueConverter.Convert(typeof(Color), "Red"));
            Assert.Equal(Color.Green, ValueConverter.Convert(typeof(Color), "Green"));
            Assert.Equal(Color.Blue, ValueConverter.Convert(typeof(Color), "Blue"));
            Assert.Equal(Color.Red | Color.Blue, ValueConverter.Convert(typeof(Color), "5"));

            Assert.Equal(DayOfWeek.Monday, ValueConverter.Convert(typeof(DayOfWeek), "Monday"));
            Assert.Equal(DayOfWeek.Tuesday, ValueConverter.Convert(typeof(DayOfWeek), "Tuesday"));
            Assert.Equal(DayOfWeek.Wednesday, ValueConverter.Convert(typeof(DayOfWeek), "Wednesday"));
            Assert.Equal(DayOfWeek.Thursday, ValueConverter.Convert(typeof(DayOfWeek), "Thursday"));
            Assert.Equal(DayOfWeek.Friday, ValueConverter.Convert(typeof(DayOfWeek), "Friday"));
            Assert.Equal(DayOfWeek.Saturday, ValueConverter.Convert(typeof(DayOfWeek), "Saturday"));
            Assert.Equal(DayOfWeek.Sunday, ValueConverter.Convert(typeof(DayOfWeek), "Sunday"));
        }
Example #23
0
        private TreeValue ReadAndConvertData()
        {
            TreeValue root = (TreeValue)base.DataProvider.ProvideData(new object[] { _data, _fillParameters });

            // 从配置文件中获取是否进行数据转换
            if (FileHelper.GetIsUseConverter(Properties.Resources.FillRule, this.FillType))
            {
                // 获取数据转换器
                ValueConverter converter = this.DataProvider.GetConverter() as ValueConverter;
                converter.DataFilePath = string.IsNullOrEmpty(base.DataProvider.DataSourceFile) ? "" : System.IO.Directory.GetParent(base.DataProvider.DataSourceFile).FullName;
                string converterFile = FileHelper.GetConverterFile(this.FillType);
                root = converter.Convert(converterFile, this.FillType, root) as TreeValue;
            }
            return(root);
        }
Example #24
0
        public static async Task <List <RateItem> > GetExchangeRateAsync(DateTime date, DateTime?since = null)
        {
            if (since != null && since.Value.Date != date.Date)
            {
                throw new ArgumentException();
            }

            List <RateItem> items = new List <RateItem>();

            bool completed = false;
            int  page      = 1;

            while (!completed)
            {
                var data = await GetExchangeRateAsync(CURRENCY_ID_USDOLLAR, date.Date, date.Date, page ++);

                foreach (DataRow row in data.Data.Rows)
                {
                    var time = ValueConverter.Convert <DateTime>(row["发布时间"]);

                    if (time > DATE_VAL_MAX || time < DATE_VAL_MIN)
                    {
                        // ignore invalid row
                        continue;
                    }

                    if (since != null && time <= since.Value)
                    {
                        completed = true;
                        break;
                    }

                    items.Add(new RateItem
                    {
                        CurrencyId = CURRENCY_ID_USDOLLAR,
                        Rate       = ValueConverter.Convert <double>(row["现汇买入价"]) / 100,
                        Time       = time
                    });
                }

                if (page > data.PageNum)
                {
                    completed = true;
                }
            }

            return(items);
        }
        /// <summary>
        /// Creates the dictionary.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns></returns>
        public object CreateDictionary(Document document)
        {
            if (document == null)
            {
                return(null);
            }

            var list = new SortedList <TKey, TValue>();

            foreach (var pair in document)
            {
                list.Add((TKey)ValueConverter.Convert(pair.Key, typeof(TKey)), (TValue)pair.Value);
            }

            return(list);
        }
Example #26
0
 object IBindingBridgeInternal.GetValueFromSource(object sourceObject)
 {
     if (ValueConverter != null)
     {
         return(ValueConverter.Convert(
                    SourcePropertyInfo.GetValue(sourceObject, null),
                    TargetPropertyChain.Last().PropertyType,
                    ConverterParameter,
                    ConverterCulture ?? CultureInfo.CurrentUICulture
                    ));
     }
     else
     {
         return(SourcePropertyInfo.GetValue(sourceObject, null));
     }
 }
        public static Configurator <Contract, ContractRow> ConfigureValueFilters(this Configurator <Contract, ContractRow> conf)
        {
            conf.Table();
            conf.Column(c => c.Id).DataOnly();

            // Simple server filtering
            conf.Column(c => c.Title).FilterValue(c => c.Title);

            // Server configuration in order to continue configure filter
            // in cshtml
            conf.Column(c => c.Supplier).FilterValueNoUi(c => c.Supplier);

            // Value filter overriden by filtering delegate
            conf.Column(c => c.Price).FilterValueNoUi(c => c.Price)
            .By((q, v) => q.Where(x => x.Price < v));

            // Exactly the same as above
            conf.Column(c => c.Price).FilterValueNoUiBy((q, v) => q.Where(x => x.Price < v));

            // Overriden value extractor
            conf.Column(c => c.Tax)
            .FilterValueBy((q, v) => q.Where(x => x.Tax > v))
            .Value(q =>
            {
                if (!q.Filterings.ContainsKey("Tax"))
                {
                    return(FilterTuple.None <double?>());
                }
                var f = q.Filterings["Tax"];
                if (string.IsNullOrEmpty(f))
                {
                    return(FilterTuple.None <double?>());
                }
                var d = ValueConverter.Convert <double>(f);
                if (d > 10)
                {
                    d = d / 100;
                }
                return(((double?)d).ToFilterTuple());
            });

            // Automatic datepickers demo
            conf.Column(c => c.StartDate).FilterValue(c => c.StartDate).CompareOnlyDates();
            conf.Column(c => c.EndDate).FilterValueNoUi(c => c.StartDate).CompareOnlyDates();

            return(conf);
        }
        protected object ParseValue(Type t, object valueToParse, Type converterType = null)
        {
            t = Nullable.GetUnderlyingType(t) ?? t;
            if (converterType != null)
            {
                ValueConverter c = (ValueConverter)Activator.CreateInstance(converterType);
                return(c.Convert(valueToParse, t));
            }
            else
            {
                if (t.IsPrimitive || t == typeof(string))
                {
                    ValueConverter converter = new ValueConverter();
                    return(converter.Convert(valueToParse, t));
                }
                if (t.IsEnum)
                {
                    EnumConverter converter = new EnumConverter();
                    return(converter.Convert(valueToParse, t));
                }
                if (t.IsSubclassOfRawGeneric(typeof(List <>)))
                {
                    Type listType = t.GetGenericArguments()[0];
                    var  list     = (IList)t.GetConstructor(Type.EmptyTypes).Invoke(null);

                    if (valueToParse is IEnumerable enumerable)
                    {
                        foreach (object rawValue in enumerable)
                        {
                            object parsedValue = ParseValue(listType, rawValue);
                            list.Add(parsedValue);
                        }
                        return(list);
                    }
                    else
                    {
                        throw new ArgumentException("Value must implement the IEnumerable interface if the type is a collection.", nameof(valueToParse));
                    }
                }
                if (t.IsClass)
                {
                    return(ParseObject(t, (TDataContainer)valueToParse));
                }
                return(null);
            }
        }
Example #29
0
 public void TestFloatValueConversion()
 {
     Assert.Equal(1.0f, ValueConverter.Convert(typeof(float), "1"));
     Assert.Equal(0.123d, ValueConverter.Convert(typeof(double), ".123"));
     Assert.Equal(1234567m, ValueConverter.Convert(typeof(decimal), "1,234,567"));
     Assert.Equal(123L, ValueConverter.Convert(typeof(object), "123"));
     Assert.Equal(12.3f, ValueConverter.Convert(typeof(float), "1,2.3"));
     Assert.Equal(123.456d, ValueConverter.Convert(typeof(double), "123.456"));
     Assert.Equal(1.00001m, ValueConverter.Convert(typeof(decimal), "00001.00001"));
     Assert.Equal(0.123m, ValueConverter.Convert(typeof(object), ".123"));
     Assert.Equal(1234567.89f, ValueConverter.Convert(typeof(float), "1,234,567.89"));
     Assert.Equal(123456789.0d, ValueConverter.Convert(typeof(double), "1,2,3,4,5,6,7,8,9"));
     Assert.Equal(0.0m, ValueConverter.Convert(typeof(decimal), "00000"));
     Assert.Equal(1234L, ValueConverter.Convert(typeof(object), "1,234"));
     Assert.Equal(12000.0f, ValueConverter.Convert(typeof(float), "12e3"));
     Assert.Equal(0.01d, ValueConverter.Convert(typeof(double), "10e-3"));
     Assert.Equal(10000000000000000.0m, ValueConverter.Convert(typeof(decimal), "10E+15"));
     Assert.Equal(0.00035m, ValueConverter.Convert(typeof(object), "3.5E-4"));
 }
Example #30
0
        public static T[] FromStringArray <T>(string[] strValues)
        {
            if (strValues == null)
            {
                return(null);
            }

            var values = new List <T>(strValues.Length);

            foreach (var field in strValues)
            {
                T value;
                if (ValueConverter.Convert(out value, field))
                {
                    values.Add(value);
                }
            }
            return(values.ToArray());
        }