Пример #1
0
    public void SameCacheForUri()
    {
        var c1 = CustomConverters.Converter("foo");
        var c2 = CustomConverters.Converter("foo");

        Assert.Same(c1, c2);
    }
Пример #2
0
    public void GlobalConverters()
    {
        var c1 = CustomConverters.Converter("global");
        var c2 = CustomConverters.Global;

        Assert.Same(c1, c2);
    }
Пример #3
0
    public void CachePerUri()
    {
        var c1 = CustomConverters.Converter("foo");
        var c2 = CustomConverters.Converter("bar");

        Assert.NotSame(c1, c2);
    }
Пример #4
0
        public void Find_should_return_null_for_non_registered_type()
        {
            var customConverters = new CustomConverters();
            var conversion       = customConverters.Find(new ConversionKey(typeof(string), typeof(Foo)));

            Assert.IsNull(conversion);
        }
Пример #5
0
        private ODataAdapter(ISession session, string protocolVersion)
        {
            _session        = session;
            ProtocolVersion = protocolVersion;

            CustomConverters.RegisterTypeConverter(typeof(GeographyPoint), TypeConverters.CreateGeographyPoint);
            CustomConverters.RegisterTypeConverter(typeof(GeometryPoint), TypeConverters.CreateGeometryPoint);
        }
        private object GetPropertyValue(IEdmTypeReference propertyType, object value, ODataResource root)
        {
            if (value == null)
            {
                return(value);
            }

            switch (propertyType.TypeKind())
            {
            case EdmTypeKind.Complex:
                if (CustomConverters.HasObjectConverter(value.GetType()))
                {
                    return(CustomConverters.Convert(value, value.GetType()));
                }
                return(CreateODataEntry(propertyType.FullName(), value.ToDictionary(), root));

            case EdmTypeKind.Collection:
                var collection = propertyType.AsCollection();
                return(new ODataCollectionValue()
                {
                    TypeName = propertyType.FullName(),
                    Items = ((IEnumerable)value).Cast <object>().Select(x => GetPropertyValue(collection.ElementType(), x, root)),
                });

            case EdmTypeKind.Primitive:
                var mappedTypes = _typeMap.Where(x => x.Value == (propertyType.Definition as IEdmPrimitiveType).PrimitiveKind);
                if (mappedTypes.Any())
                {
                    foreach (var mappedType in mappedTypes)
                    {
                        if (Utils.TryConvert(value, mappedType.Key, out var result))
                        {
                            return(result);
                        }
                    }
                    throw new NotSupportedException($"Conversion is not supported from type {value.GetType()} to OData type {propertyType}");
                }
                return(value);

            case EdmTypeKind.Enum:
                return(new ODataEnumValue(value.ToString()));

            case EdmTypeKind.Untyped:
                return(new ODataUntypedValue {
                    RawValue = value.ToString()
                });

            case EdmTypeKind.None:
                if (CustomConverters.HasObjectConverter(value.GetType()))
                {
                    return(CustomConverters.Convert(value, value.GetType()));
                }
                throw new NotSupportedException($"Conversion is not supported from type {value.GetType()} to OData type {propertyType}");

            default:
                return(value);
            }
        }
Пример #7
0
        private string GetTheTimePanelColour()
        {
            _browsers[_c.CurrentUser].Driver.WaitUntilVisible(WaitingRoomPage.TimePanel);
            _browsers[_c.CurrentUser].ScrollTo(WaitingRoomPage.TimePanel);
            _browsers[_c.CurrentUser].Driver.WaitUntilVisible(WaitingRoomPage.TimePanel).Displayed.Should().BeTrue();
            var rgba = _browsers[_c.CurrentUser].Driver.WaitUntilElementExists(WaitingRoomPage.TimePanel).GetCssValue("background-color");

            return(CustomConverters.ConvertRgbToHex(rgba));
        }
Пример #8
0
        public ODataAdapter(ISession session, IODataModelAdapter modelAdapter)
        {
            _session        = session;
            ProtocolVersion = modelAdapter.ProtocolVersion;
            Model           = modelAdapter.Model as IEdmModel;

            CustomConverters.RegisterTypeConverter(typeof(GeographyPoint), TypeConverters.CreateGeographyPoint);
            CustomConverters.RegisterTypeConverter(typeof(GeometryPoint), TypeConverters.CreateGeometryPoint);
        }
Пример #9
0
        public void IsRegisteredFor_should_return_true_for_registered_type()
        {
            var customConverters = new CustomConverters();

            customConverters.Register <string, Foo>(x => new Foo(Int32.Parse(x)));
            Conversion conversion = customConverters.Find(new ConversionKey(typeof(string), typeof(Foo)));

            Assert.IsNotNull(conversion);
        }
Пример #10
0
        private static object ToObject(this IDictionary <string, object> source, ITypeCache typeCache, Type type, string dynamicPropertiesContainerName, bool dynamicObject)
        {
            if (typeCache == null)
            {
                throw new ArgumentNullException(nameof(typeCache));
            }

            if (source == null)
            {
                return(null);
            }

            if (typeof(IDictionary <string, object>).IsTypeAssignableFrom(type))
            {
                return(source);
            }

            if (type == typeof(ODataEntry))
            {
                return(CreateODataEntry(source, typeCache, dynamicObject));
            }

            // TODO: Should be a method on TypeCache
            if (CustomConverters.HasDictionaryConverter(type))
            {
                return(CustomConverters.Convert(source, type));
            }

            var instance = CreateInstance(type);

            IDictionary <string, object> dynamicProperties = null;

            if (!string.IsNullOrEmpty(dynamicPropertiesContainerName))
            {
                dynamicProperties = CreateDynamicPropertiesContainer(type, typeCache, instance, dynamicPropertiesContainerName);
            }

            foreach (var item in source)
            {
                var property = FindMatchingProperty(type, typeCache, item);

                if (property != null && property.CanWrite)
                {
                    if (item.Value != null)
                    {
                        property.SetValue(instance, ConvertValue(property.PropertyType, typeCache, item.Value), null);
                    }
                }
                else
                {
                    dynamicProperties?.Add(item.Key, item.Value);
                }
            }

            return(instance);
        }
Пример #11
0
        public void Converts()
        {
            var customConverters = new CustomConverters();

            customConverters.Register <string, Foo>(x => new Foo(Int32.Parse(x)));
            Conversion conversion = customConverters.Find(new ConversionKey(typeof(string), typeof(Foo)));
            var        actualFoo  = (Foo)conversion("123");

            Assert.AreEqual(123, actualFoo.Value);
        }
Пример #12
0
        public void Register_and_unregister_ok()
        {
            var customConverters = new CustomConverters();

            customConverters.Register <string, Foo>(x => new Foo(Int32.Parse(x)));
            customConverters.Unregister <string, Foo>();
            var comversion = customConverters.Find(new ConversionKey(typeof(string), typeof(Foo)));

            Assert.IsNull(comversion);
        }
Пример #13
0
        private void ConvertDoc(string inputDoc, string rootOutputDirectory)
        {
            var outputDir     = GetOutputDirectory(inputDoc, rootOutputDirectory);
            var outputFile    = Path.Combine(outputDir, GetOuputFilename(inputDoc));
            var inputFileInfo = new FileInfo(inputDoc);

            if (!Directory.Exists(outputDir))
            {
                Console.WriteLine("Output Directory Doesn't Exist: '" + outputDir + "'");
                return;
            }
            if (!inputFileInfo.Exists)
            {
                Console.WriteLine("Input File Doesn't Exist: '" + inputDoc + "'");
                return;
            }

            var ns = ExtractNamespaceFromFile(outputFile);

            // we might need to convert this namespace to an explicit value
            if (PackageNamespaceToStandalone.TryGetValue(ns, out var standaloneNs))
            {
                ns = standaloneNs;
            }

            // get the MD converter for the namespace
            var converter = _defaultConverter;

            if (CustomConverters.TryGetValue(ns, out var customConverter))
            {
                converter = customConverter;
            }

            var markdown = converter.ConvertFile(inputDoc);

            if (JavaDocFormatters.CustomReplacers.TryGetValue(ns, out var replacers))
            {
                foreach (var r in replacers)
                {
                    markdown = r.Replace(markdown);
                }
            }

            var doc = new ConvertedDocument(inputFileInfo, new FileInfo(outputFile), ns, markdown);

            if (JavaDocFormatters.CustomProcessors.TryGetValue(ns, out var processor))
            {
                processor(doc);
            }
            markdown = doc.Markdown; // it may have changed

            var fileContent = AppendYamlHeader(ns, markdown);

            File.WriteAllText(outputFile, fileContent, Encoding.UTF8);
        }
Пример #14
0
        public static object ToObject(this IDictionary <string, object> source, Type type)
        {
            var ctor = type.GetDefaultConstructor();

            if (ctor == null && !CustomConverters.HasConverter(type))
            {
                throw new InvalidOperationException(
                          string.Format("Unable to create an instance of type {0} that does not have a default constructor.", type.Name));
            }

            return(ToObject(source, type, () => ctor.Invoke(new object[] { }), false));
        }
Пример #15
0
        static ScriptObjectBuilder()
        {
            CustomConverters.Add(typeof(Color), delegate(object value) { return(ColorTranslator.ToHtml((Color)value)); });
            Converter <object, string> dateTimeConverter = delegate(object value)
            {
                DateTime?date = (DateTime?)value;
                return((date != null) ? date.Value.ToUniversalTime().ToString("r") : null);
            };

            CustomConverters.Add(typeof(DateTime), dateTimeConverter);
            CustomConverters.Add(typeof(DateTime?), dateTimeConverter);
        }
        public void ToObjectSpatialV4()
        {
            CustomConverters.RegisterTypeConverter(typeof(SpatialV4.GeographyPoint), V4.Adapter.TypeConverters.CreateGeographyPoint);
            var dict = new Dictionary <string, object>()
            {
                { "PointV4", SpatialV4.GeographyPoint.Create(SpatialV4.CoordinateSystem.Geography(100), 1, 2, null, null) },
            };

            var value = dict.ToObject <ClassType>();

            Assert.Equal(100, value.PointV4.CoordinateSystem.EpsgId);
            Assert.Equal(1d, value.PointV4.Latitude);
            Assert.Equal(2d, value.PointV4.Longitude);
        }
Пример #17
0
        private static object ToObject(this IDictionary <string, object> source, Type type, Func <object> instanceFactory,
                                       string dynamicPropertiesContainerName, bool dynamicObject)
        {
            if (source == null)
            {
                return(null);
            }
            if (typeof(IDictionary <string, object>).IsTypeAssignableFrom(type))
            {
                return(source);
            }
            if (type == typeof(ODataEntry))
            {
                return(CreateODataEntry(source, dynamicObject));
            }

            if (CustomConverters.HasDictionaryConverter(type))
            {
                return(CustomConverters.Convert(source, type));
            }

            var instance = instanceFactory();

            IDictionary <string, object> dynamicProperties = null;

            if (!string.IsNullOrEmpty(dynamicPropertiesContainerName))
            {
                dynamicProperties = CreateDynamicPropertiesContainer(type, instance, dynamicPropertiesContainerName);
            }

            foreach (var item in source)
            {
                var property = FindMatchingProperty(type, item);

                if (property != null && property.CanWrite && !property.IsNotMapped())
                {
                    if (item.Value != null)
                    {
                        property.SetValue(instance, ConvertValue(property.PropertyType, item.Value), null);
                    }
                }
                else if (dynamicProperties != null)
                {
                    dynamicProperties.Add(item.Key, item.Value);
                }
            }

            return(instance);
        }
Пример #18
0
 public void Registers_with_null_conversion_should_throw_exception()
 {
     var customConverters = new CustomConverters();
     customConverters.Register(typeof(string), typeof(Foo), null);
 }
Пример #19
0
 public void Registers_with_null_target_type_should_throw_exception()
 {
     var customConverters = new CustomConverters();
     customConverters.Register(typeof(string), null, x => null);
 }
Пример #20
0
        public void Registers_with_null_target_type_should_throw_exception()
        {
            var customConverters = new CustomConverters();

            customConverters.Register(typeof(string), null, x => null);
        }
Пример #21
0
 public void Generic_Registers_with_null_converter_should_throw_exception()
 {
     var customConverters = new CustomConverters();
     customConverters.Register<string, Foo>(null);
 }
Пример #22
0
        private static object ToObject(this IDictionary <string, object> source, Type type, Func <object> instanceFactory, bool dynamicObject)
        {
            if (source == null)
            {
                return(null);
            }
            if (typeof(IDictionary <string, object>).IsTypeAssignableFrom(type))
            {
                return(source);
            }
            if (type == typeof(ODataEntry))
            {
                return(CreateODataEntry(source, dynamicObject));
            }

            if (CustomConverters.HasConverter(type))
            {
                return(CustomConverters.Convert(source, type));
            }

            var instance = instanceFactory();

            Func <Type, bool> IsCompoundType = fieldOrPropertyType =>
                                               !fieldOrPropertyType.IsValue() && !fieldOrPropertyType.IsArray && fieldOrPropertyType != typeof(string);

            Func <Type, object, bool> IsCollectionType = (fieldOrPropertyType, itemValue) =>
                                                         (fieldOrPropertyType.IsArray ||
                                                          fieldOrPropertyType.IsGeneric() &&
                                                          typeof(System.Collections.IEnumerable).IsTypeAssignableFrom(fieldOrPropertyType)) &&
                                                         (itemValue as System.Collections.IEnumerable) != null;

            Func <Type, object, object> ConvertEnum = (fieldOrPropertyType, itemValue) =>
            {
                if (itemValue == null)
                {
                    return(null);
                }
                var stringValue = itemValue.ToString();
                int intValue;
                if (int.TryParse(stringValue, out intValue))
                {
                    object result;
                    Utils.TryConvert(intValue, fieldOrPropertyType, out result);
                    return(result);
                }
                else
                {
                    return(Enum.Parse(fieldOrPropertyType, stringValue, false));
                }
            };

            Func <Type, object, object> ConvertSingle = (fieldOrPropertyType, itemValue) =>
                                                        IsCompoundType(fieldOrPropertyType)
                ? itemValue.ToDictionary().ToObject(fieldOrPropertyType)
                : fieldOrPropertyType.IsEnumType()
                    ? ConvertEnum(fieldOrPropertyType, itemValue)
                    : itemValue;

            Func <Type, object, object> ConvertCollection = (fieldOrPropertyType, itemValue) =>
            {
                var elementType = fieldOrPropertyType.IsArray
                    ? fieldOrPropertyType.GetElementType()
                    : fieldOrPropertyType.IsGeneric() && fieldOrPropertyType.GetGenericTypeArguments().Length == 1
                        ? fieldOrPropertyType.GetGenericTypeArguments()[0]
                        : null;
                if (elementType == null)
                {
                    return(null);
                }

                var count      = (itemValue as System.Collections.IEnumerable).Cast <object>().Count();
                var arrayValue = Array.CreateInstance(elementType, count);

                count = 0;
                foreach (var item in (itemValue as System.Collections.IEnumerable))
                {
                    (arrayValue as Array).SetValue(ConvertSingle(elementType, item), count++);
                }

                if (fieldOrPropertyType.IsArray || fieldOrPropertyType.IsTypeAssignableFrom(arrayValue.GetType()))
                {
                    return(arrayValue);
                }
                else
                {
                    var typedef        = typeof(IEnumerable <>);
                    var enumerableType = typedef.MakeGenericType(elementType);
                    var ctor           = fieldOrPropertyType.GetDeclaredConstructors().FirstOrDefault(
                        x => x.GetParameters().Length == 1 && x.GetParameters().First().ParameterType == enumerableType);
                    return(ctor != null
                        ? ctor.Invoke(new object[] { arrayValue })
                        : null);
                }
            };

            Func <Type, object, object> ConvertValue = (fieldOrPropertyType, itemValue) =>
                                                       IsCollectionType(fieldOrPropertyType, itemValue)
                ? ConvertCollection(fieldOrPropertyType, itemValue)
                : ConvertSingle(fieldOrPropertyType, itemValue);

            foreach (var item in source)
            {
                if (item.Value != null)
                {
                    var property = type.GetAnyProperty(item.Key) ??
                                   type.GetAllProperties().FirstOrDefault(x => x.GetMappedName() == item.Key);

                    if (property != null && property.CanWrite && !property.IsNotMapped())
                    {
                        property.SetValue(instance, ConvertValue(property.PropertyType, item.Value), null);
                    }
                }
            }

            return(instance);
        }
Пример #23
0
 public void Find_should_return_null_for_non_registered_type()
 {
     var customConverters = new CustomConverters();
     var conversion = customConverters.Find(new ConversionKey(typeof(string), typeof(Foo)));
     Assert.IsNull(conversion);
 }
Пример #24
0
 public void IsRegisteredFor_should_return_true_for_registered_type()
 {
     var customConverters = new CustomConverters();
     customConverters.Register<string, Foo>(x => new Foo(Int32.Parse(x)));
     Conversion conversion = customConverters.Find(new ConversionKey(typeof(string), typeof(Foo)));
     Assert.IsNotNull(conversion);
 }
Пример #25
0
        public void Registers_with_null_conversion_should_throw_exception()
        {
            var customConverters = new CustomConverters();

            customConverters.Register(typeof(string), typeof(Foo), null);
        }
Пример #26
0
        public void Registers_with_null_source_type_should_throw_exception()
        {
            var customConverters = new CustomConverters();

            customConverters.Register(null, typeof(Foo), x => null);
        }
Пример #27
0
 public void Registers_with_null_source_type_should_throw_exception()
 {
     var customConverters = new CustomConverters();
     customConverters.Register(null, typeof(Foo), x => null);
 }
Пример #28
0
 internal static ITypeCache TypeCache(string uri, INameMatchResolver nameMatchResolver)
 {
     return(_typeCaches.GetOrAdd(uri, new TypeCache(CustomConverters.Converter(uri), nameMatchResolver)));
 }
Пример #29
0
        public void Generic_Registers_with_null_converter_should_throw_exception()
        {
            var customConverters = new CustomConverters();

            customConverters.Register <string, Foo>(null);
        }
Пример #30
0
 public void Register_and_unregister_ok()
 {
     var customConverters = new CustomConverters();
     customConverters.Register<string, Foo>(x => new Foo(Int32.Parse(x)));
     customConverters.Unregister<string, Foo>();
     var comversion = customConverters.Find(new ConversionKey(typeof(string), typeof(Foo)));
     Assert.IsNull(comversion);
 }
Пример #31
0
        private object GetPropertyValue(IEdmTypeReference propertyType, object value)
        {
            if (value == null)
            {
                return(value);
            }

            switch (propertyType.TypeKind())
            {
            case EdmTypeKind.Complex:
                if (CustomConverters.HasObjectConverter(value.GetType()))
                {
                    return(CustomConverters.Convert(value, value.GetType()));
                }
                var complexTypeProperties = propertyType.AsComplex().StructuralProperties();
                return(new ODataComplexValue
                {
                    TypeName = propertyType.FullName(),
                    Properties = value.ToDictionary()
                                 .Where(val => complexTypeProperties.Any(p => p.Name == val.Key))
                                 .Select(x => new ODataProperty
                    {
                        Name = x.Key,
                        Value = GetPropertyValue(complexTypeProperties, x.Key, x.Value),
                    })
                });

            case EdmTypeKind.Collection:
                var collection = propertyType.AsCollection();
                return(new ODataCollectionValue()
                {
                    TypeName = propertyType.FullName(),
                    Items = ((IEnumerable)value).Cast <object>().Select(x => GetPropertyValue(collection.ElementType(), x)),
                });

            case EdmTypeKind.Primitive:
                var mappedTypes = _typeMap.Where(x => x.Value == (propertyType.Definition as IEdmPrimitiveType).PrimitiveKind);
                if (mappedTypes.Any())
                {
                    foreach (var mappedType in mappedTypes)
                    {
                        object result;
                        if (Utils.TryConvert(value, mappedType.Key, out result))
                        {
                            return(result);
                        }
                    }
                    throw new NotSupportedException(string.Format("Conversion is not supported from type {0} to OData type {1}", value.GetType(), propertyType));
                }
                return(value);

            case EdmTypeKind.Enum:
                return(value.ToString());

            case EdmTypeKind.None:
                if (CustomConverters.HasObjectConverter(value.GetType()))
                {
                    return(CustomConverters.Convert(value, value.GetType()));
                }
                throw new NotSupportedException(string.Format("Conversion is not supported from type {0} to OData type {1}", value.GetType(), propertyType));

            default:
                return(value);
            }
        }
Пример #32
0
 public void Converts()
 {
     var customConverters = new CustomConverters();
     customConverters.Register<string, Foo>(x => new Foo(Int32.Parse(x)));
     Conversion conversion = customConverters.Find(new ConversionKey(typeof(string), typeof(Foo)));
     var actualFoo = (Foo)conversion("123");
     Assert.AreEqual(123, actualFoo.Value);
 }