Exemple #1
0
    private static void RegisterConverters(
        DefaultTypeConverter registry)
    {
        RegisterDateTimeConversions(registry);
        RegisterGuidConversions(registry);
        RegisterUriConversions(registry);
        RegisterBooleanConversions(registry);
        RegisterStringConversions(registry);
        RegisterNameStringConversions(registry);

        RegisterByteConversions(registry);
        RegisterSByteConversions(registry);

        RegisterUInt16Conversions(registry);
        RegisterUInt32Conversions(registry);
        RegisterUInt64Conversions(registry);

        RegisterInt16Conversions(registry);
        RegisterInt32Conversions(registry);
        RegisterInt64Conversions(registry);

        RegisterSingleConversions(registry);
        RegisterDoubleConversions(registry);
        RegisterDecimalConversions(registry);

        RegisterStringListConversions(registry);
    }
Exemple #2
0
    private static void RegisterDateTimeConversions(
        DefaultTypeConverter registry)
    {
        registry.Register <DateTimeOffset, DateTime>(from => from.UtcDateTime);
        registry.Register <DateTime, DateTimeOffset>(from => from);

        registry.Register <DateTimeOffset, long>(from => from.ToUnixTimeSeconds());
        registry.Register <long, DateTimeOffset>(DateTimeOffset.FromUnixTimeSeconds);

        registry.Register <DateTime, long>(
            from => ((DateTimeOffset)from).ToUnixTimeSeconds());
        registry.Register <long, DateTime>(
            from => DateTimeOffset.FromUnixTimeSeconds(from).UtcDateTime);

        registry.Register <DateTimeOffset, string>(
            from => from.ToString(from.Offset == TimeSpan.Zero
                ? _utcFormat
                : _localFormat, CultureInfo.InvariantCulture));
        registry.Register <DateTime, string>(
            from =>
        {
            var offset = new DateTimeOffset(from);
            return(offset.ToString(offset.Offset == TimeSpan.Zero
                    ? _utcFormat
                    : _localFormat, CultureInfo.InvariantCulture));
        });

#if NET6_0_OR_GREATER
        registry.Register <DateOnly, DateTimeOffset>(from => from.ToDateTime(default));
        public void DefaultTypeConverter_WithNullableBoolean_Convert_ReturnsBoolean(bool?source)
        {
            var converter = new DefaultTypeConverter <bool?>();

            var target = converter.Convert(source);

            target.ShouldBe(source);
        }
        public void DefaultTypeConverter_WithFloat_Convert_ReturnsFloat(float source)
        {
            var converter = new DefaultTypeConverter <float>();

            var target = converter.Convert(source);

            target.ShouldBe(source);
        }
        public void DefaultTypeConverter_WithDouble_Convert_ReturnsDouble(double source)
        {
            var converter = new DefaultTypeConverter <double>();

            var target = converter.Convert(source);

            target.ShouldBe(source);
        }
        public void DefaultTypeConverter_WithDecimal_Convert_ReturnsDecimal(decimal source)
        {
            var converter = new DefaultTypeConverter <decimal>();

            var target = converter.Convert(source);

            target.ShouldBe(source);
        }
        public void DefaultTypeConverter_WithLong_Convert_ReturnsLong(long source)
        {
            var converter = new DefaultTypeConverter <long>();

            var target = converter.Convert(source);

            target.ShouldBe(source);
        }
        public void DefaultTypeConverter_WithShort_Convert_ReturnsShort(short source)
        {
            var converter = new DefaultTypeConverter <short>();

            var target = converter.Convert(source);

            target.ShouldBe(source);
        }
        public void DefaultTypeConverter_WithInteger_Convert_ReturnsInteger(int source)
        {
            var converter = new DefaultTypeConverter <int>();

            var target = converter.Convert(source);

            target.ShouldBe(source);
        }
        public void ConvertToField_Int()
        {
            var propConverter = GetPropetyConverter("PInt");
            var converter     = new DefaultTypeConverter(propConverter);

            var fieldVal = converter.ConvertToField(1);

            Assert.AreEqual(1, fieldVal);
        }
        private GeneratorConfiguration()
        {
            // Defaults
            LibraryName    = "Flyingpie.Storm";
            LibraryVersion = GetType().Assembly.GetName().Version.ToString();

            RootNamespace = "Database";

            NameConverter = new DefaultNameConverter();
            TypeConverter = new DefaultTypeConverter();
        }
Exemple #12
0
        public void ConvertToString_ValueIsNull_ReturnsEmptyString()
        {
            var converter = new DefaultTypeConverter();

            var memberMapData = new MemberMapData(null)
            {
            };

            var value = converter.ConvertToString(null, null, memberMapData);

            Assert.Equal(string.Empty, value);
        }
        public void SourceBaseType()
        {
            var registry = DefaultTypeConverter.Create();

            var result1 = registry.ConvertTo <string>(TypeConversionContext.None, TestEnum.Value1);
            var result2 = registry.ConvertTo <string>(TypeConversionContext.None, TestEnum.Value2);
            var result3 = registry.ConvertTo <string>(TypeConversionContext.None, true);

            Assert.AreEqual("value1", result1);
            Assert.AreEqual("Value2", result2);
            Assert.AreEqual("true", result3);
        }
        public void ConvertFromField_String()
        {
            var propConverter = GetPropetyConverter("PString");
            var converter     = new DefaultTypeConverter(propConverter);

            var val = converter.ConvertFromField("abc");

            Assert.AreEqual("abc", val);

            val = converter.ConvertFromField(null);
            Assert.AreEqual("", val);
        }
Exemple #15
0
        public void ConvertToString_MultipleNullValues_UsesFirstValue()
        {
            var converter = new DefaultTypeConverter();

            var memberMapData = new MemberMapData(null)
            {
                TypeConverterOptions = { NullValues = { "Foo", "Bar" } },
            };

            var value = converter.ConvertToString(null, null, memberMapData);

            Assert.Equal("Foo", value);
        }
        public void ConvertToString_SingleNullValue_UsesValue()
        {
            var converter = new DefaultTypeConverter();

            var memberMapData = new MemberMapData(null)
            {
                TypeConverterOptions = { NullValues = { "Foo" } },
            };

            var value = converter.ConvertToString(null, null, memberMapData);

            Assert.AreEqual("Foo", value);
        }
        public void TryConvertTest()
        {
            DefaultTypeConverter target = new DefaultTypeConverter();  
            object value = "123";  
            Type targetType = typeof(int);  
            object convertedObject = null;  
            object convertedObjectExpected = 123;  
            bool expected = true;  
            bool actual;

            actual = target.TryConvert(value, targetType, ref convertedObject); 
            Assert.AreEqual(convertedObjectExpected, convertedObject);
            Assert.AreEqual(expected, actual); 
        }
        public void TargetBaseType()
        {
            var registry = DefaultTypeConverter.Create();

            var result1 = registry.ConvertTo <TestEnum>(TypeConversionContext.None, "value1");
            var result2 = registry.ConvertTo <TestEnum>(TypeConversionContext.None, "Value2");
            var result3 = registry.ConvertTo <bool>(TypeConversionContext.None, "true");
            var result4 = registry.ConvertTo <bool>(TypeConversionContext.None, "True");

            Assert.AreEqual(TestEnum.Value1, result1);
            Assert.AreEqual(TestEnum.Value2, result2);
            Assert.AreEqual(true, result3);
            Assert.AreEqual(true, result4);
        }
Exemple #19
0
        private static TResult TestGetFromDbConverter <TSource, TResult>(TSource value, bool compare = true)
        {
            var converter = new DefaultTypeConverter();
            var result    = (Func <TSource, TResult>)converter.GetFromDbConverter(typeof(TSource), typeof(TResult));

            Assert.NotNull(result);
            var convertedValue = result(value);

            if (compare)
            {
                CollectionAssert.AreEqual((IEnumerable)value, (IEnumerable)convertedValue, new LooseComparer());
            }
            return(convertedValue);
        }
        public void ConvertFromField_Int()
        {
            var propConverter = GetPropetyConverter("PInt");
            var converter     = new DefaultTypeConverter(propConverter);

            var val = converter.ConvertFromField("1");

            Assert.AreEqual(1, val);

            //val = converter.ConvertFromField(long.MaxValue.ToField());
            // => error
            //val = converter.ConvertFromField("");
            // => error
            //val = converter.ConvertFromField(null);
            // => error
        }
        public async Task ArgumentProvider()
        {
            var httpHandler     = new MockHttpHandler();
            var responseHandler = new MockResponseHandler <string>(x => x.Headers.Single(y => y.Name == "name").Values.Single());

            var endpoint = new HttpApiEndpoint(
                null,
                "path/to/api",
                HttpMethod.Get,
                new Dictionary <string, IHttpArgumentHandler>
            {
                { "name", new HttpHeaderArgumentHandler(DefaultTypeConverter.Create()) }
            },
                responseHandler,
                Enumerable.Empty <HttpHeader>());
            var response = await endpoint.Call(httpHandler, "http://localhost", new Dictionary <string, object> {
                ["name"] = "value"
            });

            Assert.AreEqual("value", response);
        }
 public void DefaultTypeConverterConstructorTest()
 {
     DefaultTypeConverter target = new DefaultTypeConverter();
     Assert.IsNotNull(target);
 }
Exemple #23
0
        /// <summary>
        /// Constructs a new engine instance and allows customizing options.
        /// </summary>
        /// <remarks>The provided engine instance in callback is not guaranteed to be fully configured</remarks>
        public Engine(Action <Engine, Options> options)
        {
            _executionContexts = new ExecutionContextStack(2);

            Global = GlobalObject.CreateGlobalObject(this);

            Object   = ObjectConstructor.CreateObjectConstructor(this);
            Function = FunctionConstructor.CreateFunctionConstructor(this);
            _callerCalleeArgumentsThrowerConfigurable    = new GetSetPropertyDescriptor.ThrowerPropertyDescriptor(this, PropertyFlag.Configurable | PropertyFlag.CustomJsValue, "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them");
            _callerCalleeArgumentsThrowerNonConfigurable = new GetSetPropertyDescriptor.ThrowerPropertyDescriptor(this, PropertyFlag.CustomJsValue, "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them");

            Symbol   = SymbolConstructor.CreateSymbolConstructor(this);
            Array    = ArrayConstructor.CreateArrayConstructor(this);
            Map      = MapConstructor.CreateMapConstructor(this);
            Set      = SetConstructor.CreateSetConstructor(this);
            Iterator = IteratorConstructor.CreateIteratorConstructor(this);
            String   = StringConstructor.CreateStringConstructor(this);
            RegExp   = RegExpConstructor.CreateRegExpConstructor(this);
            Number   = NumberConstructor.CreateNumberConstructor(this);
            Boolean  = BooleanConstructor.CreateBooleanConstructor(this);
            Date     = DateConstructor.CreateDateConstructor(this);
            Math     = MathInstance.CreateMathObject(this);
            Json     = JsonInstance.CreateJsonObject(this);
            Proxy    = ProxyConstructor.CreateProxyConstructor(this);
            Reflect  = ReflectInstance.CreateReflectObject(this);

            GlobalSymbolRegistry = new GlobalSymbolRegistry();

            // Because the properties might need some of the built-in object
            // their configuration is delayed to a later step

            // trigger initialization
            Global.GetProperty(JsString.Empty);

            // this is implementation dependent, and only to pass some unit tests
            Global._prototype = Object.PrototypeObject;
            Object._prototype = Function.PrototypeObject;

            // create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3
            GlobalEnvironment = LexicalEnvironment.NewGlobalEnvironment(this, Global);

            // create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1
            EnterExecutionContext(GlobalEnvironment, GlobalEnvironment);

            Eval = new EvalFunctionInstance(this);
            Global.SetProperty(CommonProperties.Eval, new PropertyDescriptor(Eval, PropertyFlag.Configurable | PropertyFlag.Writable));

            Options = new Options();

            options?.Invoke(this, Options);

            // gather some options as fields for faster checks
            _isDebugMode       = Options.IsDebugMode;
            _isStrict          = Options.IsStrict;
            _constraints       = Options._Constraints;
            _referenceResolver = Options.ReferenceResolver;

            _referencePool         = new ReferencePool();
            _argumentsInstancePool = new ArgumentsInstancePool(this);
            _jsValueArrayPool      = new JsValueArrayPool();

            if (Options._IsClrAllowed)
            {
                Global.SetProperty("System", new PropertyDescriptor(new NamespaceReference(this, "System"), PropertyFlag.AllForbidden));
                Global.SetProperty("importNamespace", new PropertyDescriptor(new ClrFunctionInstance(
                                                                                 this,
                                                                                 "importNamespace",
                                                                                 (thisObj, arguments) => new NamespaceReference(this, TypeConverter.ToString(arguments.At(0)))), PropertyFlag.AllForbidden));
            }

            ClrTypeConverter = new DefaultTypeConverter(this);
        }
Exemple #24
0
        public HttpApi(ITypeConverter typeConverter = null)
        {
            TypeConverter = TypeConverterAttribute.Combine(typeof(T), typeConverter ?? DefaultTypeConverter.Create());
            Headers       = HeaderAttribute.GetHeaders(typeof(T));

            // Create endpoints
            var endpoints = new Dictionary <MethodInfo, HttpApiEndpoint>();

            foreach (var method in typeof(T).GetMethods())
            {
                var httpMethod = method.GetHttpMethodAttribute();
                if (httpMethod != null)
                {
                    var endpoint = CreateEndpoint(method, httpMethod);
                    endpoints[method] = endpoint;
                }
            }
            Endpoints = endpoints;
        }