Esempio n. 1
0
        public static object StringToField(this IFieldInfoDescriptor fieldDescriptor, string value)
        {
            if (value == null)
            {
                return(null);
            }

            value = fieldDescriptor.StringTrim(value);

            if (string.Empty.Equals(value) && fieldDescriptor.Converter == null)
            {
                return(value);
            }

            if (fieldDescriptor.Converter == null && fieldDescriptor.Type == null)
            {
                return(value);
            }

            ConverterBase converterInstance =
                fieldDescriptor.Converter == null
                ? ConverterFactory.GetDefaultConverter(fieldDescriptor.Type, fieldDescriptor.ConverterFormat)
                : ConverterFactory.GetConverter(fieldDescriptor.Converter, fieldDescriptor.ConverterFormat);

            return(converterInstance == null
                ? value
                : converterInstance.StringToField(value));
        }
Esempio n. 2
0
 public RepositoryBase(VirtualWorkDatabaseContext mtfDatabase,
                       ConverterBase <TDtoType, TEntityType> converter,
                       DbSet <TEntityType> databaseTable) : base(databaseTable)
 {
     VirtualWorkDatabase = mtfDatabase;
     Converter           = converter;
 }
Esempio n. 3
0
 private static void AssertCanConvertEnglishNumbers(ConverterBase decimalConverter)
 {
     Assert.AreEqual(123.12,
                     decimalConverter.StringToField("123.12"),
                     "If no culture is specified, the decimal separator should be a dot");
     Assert.AreEqual(1234.12,
                     decimalConverter.StringToField("1,234.12"),
                     "If no culture is specified, the group separator should be a comma");
 }
Esempio n. 4
0
        static ConverterBase GetConverter(string msg)
        {
            ConverterBase converter = null;

            do
            {
                Console.Write(msg + " => ");
                var unit = Console.ReadLine();
                converter = ConverterFactory.GetInstance(unit);
            } while (converter == null);
            return(converter);
        }
Esempio n. 5
0
        static double GetDistance(ConverterBase from)
        {
            double?value = null;

            do
            {
                Console.Write($"変換したい距離(単位:{from.UnitName})を入力してください => ");
                var    line = Console.ReadLine();
                double temp;
                value = double.TryParse(line, out temp) ? (double?)temp : null;
            } while (value == null);
            return(value.Value);
        }
Esempio n. 6
0
        static double GetDistance(ConverterBase from)
        {
            double?value = null;

            do
            {
                Console.Write($"변환하려는 단위(단위:{from.UnitName})을(를) 입력하세요=> ");
                var    line = Console.ReadLine();
                double temp;
                value = double.TryParse(line, out temp) ? (double?)temp : null;
            } while (value == null);
            return(value.Value);
        }
Esempio n. 7
0
        /// <summary>
        /// 默认键值对列化工具
        /// </summary>
        public KeyValueFormatter()
        {
            var notSupported = new NotSupportedConverter();
            var converters   = this.GetConverters().Concat(new[] { notSupported });

            this.firstConverter = converters.First();

            converters.Aggregate((cur, next) =>
            {
                cur.Next      = next;
                cur.Formatter = this;
                return(next);
            }).Formatter = this;
        }
        private static string CreateFieldString(this IXmlFieldInfoDescriptor fieldDescriptor, object fieldValue)
        {
            if (fieldDescriptor.Converter == null)
            {
                if (fieldValue == null)
                {
                    return(string.Empty);
                }
                return(fieldValue.ToString());
            }

            ConverterBase converterInstance =
                ConverterFactory.GetConverter(fieldDescriptor.Converter, fieldDescriptor.ConverterFormat);

            return(converterInstance?.FieldToString(fieldValue) ?? string.Empty);
        }
        protected internal TType Set <TType>(TType value, string name)
        {
            var targetType = typeof(TType);
            var data       = _data.Value;

            if (data.TryGetValue(name, out var dataValue) && dataValue.TargetType == targetType)
            {
                dataValue.Value = value;
            }
            else
            {
                data[name] = new DataValue(value, ConverterBase.Find(targetType), targetType);
            }

            return(value);
        }
Esempio n. 10
0
        static async Task Main(string[] args)
        {
            // Initialize dependencies.
            var jsonSerializer = new JsonDocumentSerializer();
            var xmlSerializer  = new XmlDocumentSerializer();
            var converter      = new ConverterBase <Document>(new ISerializer <Document>[] { jsonSerializer, xmlSerializer, });

            var webStorage        = new WebStorage();
            var fileSystemStorage = new FileSystemStorage();
            var storageProvider   = new StorageProvider.Storage.StorageProvider(new IStorage[] { webStorage, fileSystemStorage, });

            var app = new Application(converter, storageProvider);

            // Run application.
            var fromUri = new Uri("https://gist.githubusercontent.com/daywee/155b9145f00967cffac2933869614d6c/raw/835a0feef86d671077a210b92e11f318abd0acb5/rwsDocument.json");

            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var    toUri         = new Uri(Path.Combine(documentsPath, "rwsHomework.xml"));

            await app.Convert(fromUri, toUri);
        }
Esempio n. 11
0
        private void CreateConverter(Type convType, object[] args)
        {
            if (typeof(ConverterBase).IsAssignableFrom(convType))
            {
                ConstructorInfo constructor;
                constructor = convType.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, null, ArgsToTypes(args), null);

                if (constructor == null)
                {
                    if (args.Length == 0)
                    {
                        throw new BadUsageException("Empty constructor for converter: " + convType.Name + " was not found. You must add a constructor without args (can be public or private)");
                    }
                    else
                    {
                        throw new BadUsageException("Constructor for converter: " + convType.Name + " with these arguments: (" + ArgsDesc(args) + ") was not found. You must add a constructor with this signature (can be public or private)");
                    }
                }

                try
                {
                    Converter = (ConverterBase)constructor.Invoke(args);
                }
                catch (TargetInvocationException ex)
                {
                    throw ex.InnerException;
                }
            }
#if !MINI
            else if (convType.IsEnum)
            {
                Converter = new EnumConverter(convType);
            }
#endif
            else
            {
                throw new BadUsageException("The custom converter must inherit from ConverterBase");
            }
        }
Esempio n. 12
0
        public static string CreateFieldString(this IFieldInfoDescriptor fieldBuilder, object fieldValue)
        {
            ConverterBase converterInstance = null;

            if (fieldBuilder.Type != null || fieldBuilder.Converter != null)
            {
                converterInstance = fieldBuilder.Converter == null
                ? ConverterFactory.GetDefaultConverter(fieldBuilder.Type, fieldBuilder.ConverterFormat)
                : ConverterFactory.GetConverter(fieldBuilder.Converter, fieldBuilder.ConverterFormat);
            }

            if (converterInstance == null)
            {
                if (fieldValue == null)
                {
                    return(string.Empty);
                }

                return(fieldValue.ToString());
            }

            return(converterInstance.FieldToString(fieldValue) ?? string.Empty);
        }
        private string IsConfigurationValid(ConverterBase converterBase)
        {
            NullGuard.NotNull(converterBase, nameof(converterBase));

            FieldInfo mapperFieldInfo = converterBase.GetType().GetField("Mapper", BindingFlags.Instance | BindingFlags.NonPublic);

            if (mapperFieldInfo == null)
            {
                throw new MissingFieldException($"Unable to find the field named 'Mapper' on '{converterBase.GetType().Name}'.", "Mapper");
            }

            Mapper mapper = (Mapper)mapperFieldInfo.GetValue(converterBase);

            try
            {
                mapper.ConfigurationProvider.AssertConfigurationIsValid();

                return(null);
            }
            catch (AutoMapperConfigurationException ex)
            {
                return(ex.Message);
            }
        }
Esempio n. 14
0
 public ArrayElement()
 {
     _converter = ConverterBase.Find(typeof(TType));
 }
Esempio n. 15
0
        public void WriteEnumerable(ref WriteStack state, Utf8JsonWriter writer)
        {
            Debug.Assert(ShouldSerialize);
            int originalDepth = writer.CurrentDepth;

            OnWriteEnumerable(ref state.Current, writer);

            if (originalDepth != writer.CurrentDepth)
            {
                ThrowHelper.ThrowJsonException_SerializationConverterWrite(state.PropertyPath(), ConverterBase.ToString());
            }
        }
Esempio n. 16
0
        public void Write(ref WriteStack state, Utf8JsonWriter writer)
        {
            Debug.Assert(ShouldSerialize);

            if (state.Current.CollectionEnumerator != null)
            {
                // Forward the setter to the value-based JsonPropertyInfo.
                JsonPropertyInfo propertyInfo = ElementClassInfo.PolicyProperty;
                propertyInfo.WriteEnumerable(ref state, writer);
            }
            else
            {
                int originalDepth = writer.CurrentDepth;

                OnWrite(ref state.Current, writer);

                if (originalDepth != writer.CurrentDepth)
                {
                    ThrowHelper.ThrowJsonException_SerializationConverterWrite(state.PropertyPath(), ConverterBase.ToString());
                }
            }
        }
Esempio n. 17
0
        private void VerifyRead(JsonTokenType tokenType, int depth, long bytesConsumed, ref ReadStack state, ref Utf8JsonReader reader)
        {
            switch (tokenType)
            {
            case JsonTokenType.StartArray:
                if (reader.TokenType != JsonTokenType.EndArray)
                {
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath(), ConverterBase.ToString());
                }
                else if (depth != reader.CurrentDepth)
                {
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath(), ConverterBase.ToString());
                }

                // Should not be possible to have not read anything.
                Debug.Assert(bytesConsumed < reader.BytesConsumed);
                break;

            case JsonTokenType.StartObject:
                if (reader.TokenType != JsonTokenType.EndObject)
                {
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath(), ConverterBase.ToString());
                }
                else if (depth != reader.CurrentDepth)
                {
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath(), ConverterBase.ToString());
                }

                // Should not be possible to have not read anything.
                Debug.Assert(bytesConsumed < reader.BytesConsumed);
                break;

            default:
                // Reading a single property value.
                if (reader.BytesConsumed != bytesConsumed)
                {
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath(), ConverterBase.ToString());
                }

                // Should not be possible to change token type.
                Debug.Assert(reader.TokenType == tokenType);

                break;
            }
        }
Esempio n. 18
0
        private void VerifyRead(JsonTokenType originalTokenType, int originalDepth, long bytesConsumed, ref ReadStack state, ref Utf8JsonReader reader)
        {
            switch (originalTokenType)
            {
            case JsonTokenType.StartArray:
                if (reader.TokenType != JsonTokenType.EndArray)
                {
                    // todo issue #38550 blocking this: originalDepth != reader.CurrentDepth + 1
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath, ConverterBase.ToString());
                }
                break;

            case JsonTokenType.StartObject:
                if (reader.TokenType != JsonTokenType.EndObject)
                {
                    // todo issue #38550 blocking this: originalDepth != reader.CurrentDepth + 1
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath, ConverterBase.ToString());
                }
                break;

            default:
                // Reading a single property value.
                if (reader.TokenType != originalTokenType || reader.BytesConsumed != bytesConsumed)
                {
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath, ConverterBase.ToString());
                }

                break;
            }
        }
Esempio n. 19
0
 public ConvertedType Convert <ConvertedType>()
 {
     return((ConvertedType)ConverterBase.GetConverter <ConvertedType>().Convert(Value ?? ""));
 }
Esempio n. 20
0
 public ConvertedType Convert <ConvertedType>(string specialName)
 {
     return((ConvertedType)ConverterBase.GetConverter(specialName).Convert(Value ?? ""));
 }
Esempio n. 21
0
 private void VerifyWrite(int originalDepth, ref WriteStack state, ref Utf8JsonWriter writer)
 {
     // todo issue #38550 blocking this: originalDepth != reader.CurrentDepth
     if (originalDepth != writer.CurrentDepth)
     {
         ThrowHelper.ThrowJsonException_SerializationConverterWrite(state.PropertyPath, ConverterBase.ToString());
     }
 }
Esempio n. 22
0
        private void VerifyRead(JsonTokenType originalTokenType, int originalDepth, ref ReadStack state, ref Utf8JsonReader reader)
        {
            // We don't have a single call to ThrowHelper since the line number captured during throw may be useful for diagnostics.
            switch (originalTokenType)
            {
            case JsonTokenType.StartArray:
                if (reader.TokenType != JsonTokenType.EndArray)
                {
                    // todo issue #38550 blocking this: originalDepth != reader.CurrentDepth + 1
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath, ConverterBase.ToString());
                }
                break;

            case JsonTokenType.StartObject:
                if (reader.TokenType != JsonTokenType.EndObject)
                {
                    // todo issue #38550 blocking this: originalDepth != reader.CurrentDepth + 1
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath, ConverterBase.ToString());
                }
                break;

            default:
                // Reading a single property value.
                if (reader.TokenType != originalTokenType)
                {
                    // todo issue #38550 blocking this: originalDepth != reader.CurrentDepth + 1
                    ThrowHelper.ThrowJsonException_SerializationConverterRead(reader, state.JsonPath, ConverterBase.ToString());
                }

                break;
            }
        }
 public DataValue(object?value, ConverterBase converter, Type targetType)
 {
     Value      = value;
     TargetType = targetType;
     Converter  = converter;
 }
Esempio n. 24
0
 private static void AssertCanConvertFrenchNumbers(ConverterBase decimalConverterWithoutCulture)
 {
     Assert.AreEqual(1.23, decimalConverterWithoutCulture.StringToField("1,23"), "If a culture is specified, the decimal separator should be the specified culture decimal separator");
     Assert.AreEqual(1234.12, decimalConverterWithoutCulture.StringToField("1 234,12"), "If a culture is specified, the group separator should be the specified culture group separator");
     Assert.Catch(() => { decimalConverterWithoutCulture.StringToField("1.23"); }, "The dot is not a valid french separator");
 }
            public DataValue(BinaryReader reader)
            {
                TargetType = Type.GetType(reader.ReadString());
                Converter  = ConverterBase.Find(TargetType);
                if (reader.ReadBoolean())
                {
                    Value = null;
                    return;
                }

                // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault
                switch ((TypeCode)reader.ReadInt32())
                {
                case TypeCode.Boolean:
                    Value = reader.ReadBoolean();
                    break;

                case TypeCode.Byte:
                    Value = reader.ReadByte();
                    break;

                case TypeCode.Char:
                    Value = reader.ReadChar();
                    break;

                case TypeCode.DateTime:
                    Value = DateTime.FromBinary(reader.ReadInt64());
                    break;

                case TypeCode.Decimal:
                    Value = reader.ReadDecimal();
                    break;

                case TypeCode.Double:
                    Value = reader.ReadDouble();
                    break;

                case TypeCode.Int16:
                    Value = reader.ReadInt16();
                    break;

                case TypeCode.Int32:
                    Value = reader.ReadInt32();
                    break;

                case TypeCode.Int64:
                    Value = reader.ReadInt64();
                    break;

                case TypeCode.SByte:
                    Value = reader.ReadSByte();
                    break;

                case TypeCode.Single:
                    Value = reader.ReadSingle();
                    break;

                case TypeCode.String:
                    Value = reader.ReadString();
                    break;

                case TypeCode.UInt16:
                    Value = reader.ReadUInt16();
                    break;

                case TypeCode.UInt32:
                    Value = reader.ReadUInt32();
                    break;

                case TypeCode.UInt64:
                    Value = reader.ReadUInt64();
                    break;

                case TypeCode.Object:
                    if (TargetType == typeof(AkkaType))
                    {
                        Value = new AkkaType(reader.ReadString());
                    }
                    else if (TargetType.IsEnum)
                    {
                        Value = Enum.Parse(TargetType, reader.ReadString());
                    }
                    else if (typeof(ConfigurationElement).IsAssignableFrom(TargetType))
                    {
                        var ele = Activator.CreateInstance(Type.GetType(reader.ReadString()));
                        ((IBinarySerializable)ele).Read(reader);
                        Value = ele;
                    }
                    else
                    {
                        var converter = TypeDescriptor.GetConverter(TargetType);
                        if (converter == null)
                        {
                            throw new FormatException("Binary Data not Supportet Format");
                        }

                        Value = converter.ConvertFromString(reader.ReadString());
                    }

                    break;

                default:
                    throw new FormatException("Binary Data not Supportet Format");
                }
            }