/// <summary> /// Initializes. /// </summary> public XmlRpcServer() { TypeSerializerFactory = new TypeSerializerFactory(); TypeConverterFactory = new TypeConverterFactory(); XmlRpcServerConfig config = new XmlRpcServerConfig(); //config.EnabledForExtensions = true; Config = config; }
/// <summary> /// Writes the field to the CSV file /// using the given <see cref="T:CsvHelper.TypeConversion.ITypeConverter" />. /// When all fields are written for a record, /// <see cref="M:CsvHelper.ICsvWriter.NextRecord" /> must be called /// to complete writing of the current record. /// </summary> /// <typeparam name="T">The type of the field.</typeparam> /// <typeparam name="TConverter">The type of the converter.</typeparam> /// <param name="field">The field to write.</param> public virtual void WriteField <T, TConverter>(T field) { CheckDisposed(); WriteField(field, TypeConverterFactory.GetConverter <TConverter>()); }
/// <summary> /// Writes the field to the CSV file /// using the given <see cref="ITypeConverter"/>. /// When all fields are written for a record, /// <see cref="ICsvWriter.NextRecord" /> must be called /// to complete writing of the current record. /// </summary> /// <typeparam name="T">The type of the field.</typeparam> /// <typeparam name="TConverter">The type of the converter.</typeparam> /// <param name="field">The field to write.</param> public virtual void WriteField <T, TConverter>(T field) { var converter = TypeConverterFactory.GetConverter <TConverter>(); WriteField(field, converter); }
/// <summary> /// Auto maps the given map and checks for circular references as it goes. /// </summary> /// <param name="map">The map to auto map.</param> /// <param name="ignoreReferences">A value indicating if references should be ignored when auto mapping. /// True to ignore references, otherwise false.</param> /// <param name="prefixReferenceHeaders">A value indicating if headers of reference properties should /// get prefixed by the parent property name. /// True to prefix, otherwise false.</param> /// <param name="mapParents">The list of parents for the map.</param> internal static void AutoMapInternal(CsvClassMap map, bool ignoreReferences, bool prefixReferenceHeaders, LinkedList <Type> mapParents, int indexStart = 0) { var type = map.GetType().GetTypeInfo().BaseType.GetGenericArguments()[0]; if (typeof(IEnumerable).IsAssignableFrom(type)) { throw new CsvConfigurationException("Types that inherit IEnumerable cannot be auto mapped. " + "Did you accidentally call GetRecord or WriteRecord which " + "acts on a single record instead of calling GetRecords or " + "WriteRecords which acts on a list of records?"); } var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var property in properties) { var typeConverterType = TypeConverterFactory.GetConverter(property.PropertyType).GetType(); if (typeConverterType == typeof(EnumerableConverter)) { // The IEnumerable converter just throws an exception so skip it. continue; } var isDefaultConverter = typeConverterType == typeof(DefaultTypeConverter); var hasDefaultConstructor = property.PropertyType.GetConstructor(new Type[0]) != null; if (isDefaultConverter && hasDefaultConstructor) { if (ignoreReferences) { continue; } // If the type is not one covered by our type converters // and it has a parameterless constructor, create a // reference map for it. if (CheckForCircularReference(property.PropertyType, mapParents)) { continue; } mapParents.AddLast(type); var refMapType = typeof(DefaultCsvClassMap <>).MakeGenericType(property.PropertyType); var refMap = (CsvClassMap)ReflectionHelper.CreateInstance(refMapType); AutoMapInternal(refMap, false, prefixReferenceHeaders, mapParents, map.GetMaxIndex() + 1); if (refMap.PropertyMaps.Count > 0 || refMap.ReferenceMaps.Count > 0) { var referenceMap = new CsvPropertyReferenceMap(property, refMap); if (prefixReferenceHeaders) { referenceMap.Prefix(); } map.ReferenceMaps.Add(referenceMap); } } else { var propertyMap = new CsvPropertyMap(property); propertyMap.Data.Index = map.GetMaxIndex() + 1; if (propertyMap.Data.TypeConverter.CanConvertFrom(typeof(string)) || propertyMap.Data.TypeConverter.CanConvertTo(typeof(string)) && !isDefaultConverter) { // Only add the property map if it can be converted later on. // If the property will use the default converter, don't add it because // we don't want the .ToString() value to be used when auto mapping. map.PropertyMaps.Add(propertyMap); } } } map.ReIndex(indexStart); }
public void GetConverterForFloatTest() { var converter = TypeConverterFactory.GetConverter(typeof(float)); Assert.IsInstanceOfType(converter, typeof(SingleConverter)); }
public void GetConverterForDecimalTest() { var converter = TypeConverterFactory.GetConverter(typeof(decimal)); Assert.IsInstanceOfType(converter, typeof(DecimalConverter)); }
public void GetConverterForByteTest() { var converter = TypeConverterFactory.GetConverter(typeof(byte)); Assert.IsInstanceOfType(converter, typeof(ByteConverter)); }
public void GetConverterForUnknownTypeTest() { var converter = TypeConverterFactory.GetConverter(typeof(TestUnknownClass)); Assert.IsInstanceOfType(converter, typeof(DefaultTypeConverter)); }
protected virtual ISettings LoadSettingCore(Type settingType, int storeId = 0) { var allSettings = GetAllCachedSettings(); var instance = (ISettings)Activator.CreateInstance(settingType); var prefix = settingType.Name; foreach (var fastProp in FastProperty.GetProperties(settingType).Values) { var prop = fastProp.Property; // Get properties we can read and write to if (!prop.CanWrite) { continue; } string key = prefix + "." + prop.Name; if (!allSettings.TryGetValue(CreateCacheKey(key, storeId), out var cachedSetting) && storeId > 0) { // Fallback to shared (storeId = 0) allSettings.TryGetValue(CreateCacheKey(key, 0), out cachedSetting); } string setting = cachedSetting?.Value; if (setting == null) { if (fastProp.IsSequenceType) { if ((fastProp.GetValue(instance) as IEnumerable) != null) { // Instance of IEnumerable<> was already created, most likely in the constructor of the settings concrete class. // In this case we shouldn't let the EnumerableConverter create a new instance but keep this one. continue; } } else { continue; } } var converter = TypeConverterFactory.GetConverter(prop.PropertyType); if (converter == null || !converter.CanConvertFrom(typeof(string))) { continue; } try { object value = converter.ConvertFrom(setting); // Set property fastProp.SetValue(instance, value); } catch (Exception ex) { var msg = "Could not convert setting '{0}' to type '{1}'".FormatInvariant(key, prop.PropertyType.Name); Logger.Error(ex, msg); } } return(instance); }
private static IEnumerable <IDbDataParameter> BindingModelPropertyToParameter( TModel model, IDictionary <string, IDbModelPropertyStrategy> modelPropertyBindings, IEnumerable <IDbDataParameter> dbParams) { var parameters = new List <IDbDataParameter>(dbParams); var converterFactory = TypeConverterFactory.GetTypeConverterFactory(); foreach (var parameter in parameters) { var propBindingQuery = modelPropertyBindings.Where(c => c.Key == parameter.ParameterName).ToList(); if (!propBindingQuery.Any()) { continue; } var propertyBindingInfo = propBindingQuery.First(); var modelProperty = propertyBindingInfo.Value.GetPropertyInfo(); var value = modelProperty.GetValue(model, null); if (value != null) { var converter = converterFactory.GetConvertType(modelProperty.PropertyType); if (converter != null) { if (converter is EnumConverter) { parameter.Value = (converter as EnumConverter).Convert(modelProperty.PropertyType, value); } else { parameter.Value = converter.Convert(value); } } else { parameter.Value = value; } } else { if (propertyBindingInfo.Value.IsAllowNull()) { parameter.Value = DBNull.Value; } else { if (propertyBindingInfo.Value.GetPropertyInfo().PropertyType.IsValueType) { parameter.Value = Activator.CreateInstance( propertyBindingInfo.Value.GetPropertyInfo().PropertyType); } else { parameter.Value = string.Empty; } } } } return(parameters); }
/// <summary> /// Auto maps the given map and checks for circular references as it goes. /// </summary> /// <param name="map">The map to auto map.</param> /// <param name="options">Options for auto mapping.</param> /// <param name="mapParents">The list of parents for the map.</param> /// <param name="indexStart">The index starting point.</param> internal static void AutoMapInternal(CsvClassMap map, AutoMapOptions options, LinkedList <Type> mapParents, int indexStart = 0) { var type = map.GetType().GetTypeInfo().BaseType.GetGenericArguments()[0]; if (typeof(IEnumerable).IsAssignableFrom(type)) { throw new CsvConfigurationException("Types that inherit IEnumerable cannot be auto mapped. " + "Did you accidentally call GetRecord or WriteRecord which " + "acts on a single record instead of calling GetRecords or " + "WriteRecords which acts on a list of records?"); } var flags = BindingFlags.Instance | BindingFlags.Public; if (options.IncludePrivateProperties) { flags = flags | BindingFlags.NonPublic; } var members = new List <MemberInfo>(); if ((options.MemberTypes & MemberTypes.Properties) == MemberTypes.Properties) { var properties = type.GetProperties(flags); members.AddRange(properties); } if ((options.MemberTypes & MemberTypes.Fields) == MemberTypes.Fields) { var fields = new List <MemberInfo>(); foreach (var field in type.GetFields(flags)) { if (!field.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any()) { fields.Add(field); } } members.AddRange(fields); } foreach (var member in members) { var typeConverterType = TypeConverterFactory.GetConverter(member.MemberType()).GetType(); if (typeConverterType == typeof(EnumerableConverter)) { // The IEnumerable converter just throws an exception so skip it. continue; } var isDefaultConverter = typeConverterType == typeof(DefaultTypeConverter); var hasDefaultConstructor = member.MemberType().GetConstructor(new Type[0]) != null; if (isDefaultConverter && hasDefaultConstructor) { if (options.IgnoreReferences) { continue; } // If the type is not one covered by our type converters // and it has a parameterless constructor, create a // reference map for it. if (CheckForCircularReference(member.MemberType(), mapParents)) { continue; } mapParents.AddLast(type); var refMapType = typeof(DefaultCsvClassMap <>).MakeGenericType(member.MemberType()); var refMap = (CsvClassMap)ReflectionHelper.CreateInstance(refMapType); var refOptions = options.Copy(); refOptions.IgnoreReferences = false; AutoMapInternal(refMap, options, mapParents, map.GetMaxIndex() + 1); if (refMap.PropertyMaps.Count > 0 || refMap.ReferenceMaps.Count > 0) { var referenceMap = new CsvPropertyReferenceMap(member, refMap); if (options.PrefixReferenceHeaders) { referenceMap.Prefix(); } map.ReferenceMaps.Add(referenceMap); } } else { var propertyMap = new CsvPropertyMap(member); // Use global values as the starting point. propertyMap.Data.TypeConverterOptions = TypeConverterOptions.Merge(options.TypeConverterOptionsFactory.GetOptions(member.MemberType())); propertyMap.Data.Index = map.GetMaxIndex() + 1; if (!isDefaultConverter) { // Only add the property/field map if it can be converted later on. // If the property/field will use the default converter, don't add it because // we don't want the .ToString() value to be used when auto mapping. map.PropertyMaps.Add(propertyMap); } } } map.ReIndex(indexStart); }
static WriteToCSVHelper() { TypeConverterFactory.AddConverter <string[]>(new EnumerableConverter <string>()); }
public AbstractReflectiveHandlerMapping() { TypeConverterFactory = new TypeConverterFactory(); //TargetProviderFactory = new StatelessTargetProviderFactory(); }
public void GetConverterForInt64() { var converter = TypeConverterFactory.CreateTypeConverter(typeof(long)); Assert.IsInstanceOfType(converter, typeof(Int64Converter)); }
public void GetConverterForInt16() { var converter = TypeConverterFactory.CreateTypeConverter(typeof(short)); Assert.IsInstanceOfType(converter, typeof(Int16Converter)); }
public void GetConverterForDateTime() { var converter = TypeConverterFactory.CreateTypeConverter(typeof(DateTime)); Assert.IsInstanceOfType(converter, typeof(DateTimeConverter)); }
public void GetConverterForEnumTest() { var converter = TypeConverterFactory.GetConverter(typeof(TestEnum)); Assert.IsInstanceOfType(converter, typeof(EnumConverter)); }
/// <summary> /// Generates a <see cref="CsvClassMap"/> for the type. /// This internal method is used to pass extra information /// along so circular references can be checked, and /// property maps can be auto indexed. /// </summary> /// <param name="type">The type to generate for the map.</param> /// <param name="indexStart">The index that is started from.</param> /// <param name="mapParents">The list of parents for the map.</param> /// <returns></returns> internal virtual CsvClassMap AutoMapInternal(Type type, int indexStart, LinkedList <Type> mapParents) { if (typeof(IEnumerable).IsAssignableFrom(type)) { throw new CsvConfigurationException("Types that inhererit IEnumerable cannot be auto mapped. " + "Did you accidentally call GetRecord or WriteRecord which " + "acts on a single record instead of calling GetRecords or " + "WriteRecords which acts on a list of records?"); } if (maps[type] != null) { // If the map already exists, use it. return(maps[type]); } #if WINRT_4_5 var properties = type.GetProperties(); #else var properties = type.GetProperties(propertyBindingFlags); #endif var mapType = typeof(DefaultCsvClassMap <>).MakeGenericType(type); var map = (CsvClassMap)ReflectionHelper.CreateInstance(mapType); map.IndexStart = indexStart; foreach (var property in properties) { var isDefaultConverter = TypeConverterFactory.GetConverter(property.PropertyType).GetType() == typeof(DefaultTypeConverter); #if WINRT_4_5 var hasDefaultConstructor = property.PropertyType.GetTypeInfo().DeclaredConstructors.Any(c => !c.GetParameters().Any()); #else var hasDefaultConstructor = property.PropertyType.GetConstructor(Type.EmptyTypes) != null; #endif if (isDefaultConverter && hasDefaultConstructor) { // If the type is not one covered by our type converters // and it has a parameterless constructor, create a // reference map for it. if (CheckForCircularReference(property.PropertyType, mapParents)) { continue; } mapParents.AddLast(type); var refMap = AutoMapInternal(property.PropertyType, map.GetMaxIndex(), mapParents); if (refMap.PropertyMaps.Count > 0 || refMap.ReferenceMaps.Count > 0) { map.ReferenceMaps.Add(new CsvPropertyReferenceMap(property, refMap)); } } else { var propertyMap = new CsvPropertyMap(property); propertyMap.Data.Index = map.GetMaxIndex() + 1; if (propertyMap.Data.TypeConverter.CanConvertFrom(typeof(string)) || propertyMap.Data.TypeConverter.CanConvertTo(typeof(string)) && !isDefaultConverter) { // Only add the property map if it can be converted later on. // If the property will use the default converter, don't add it because // we don't want the .ToString() value to be used when auto mapping. map.PropertyMaps.Add(propertyMap); } } } return(map); }
public void RemoveConverterForUnknownTypeTest() { TypeConverterFactory.RemoveConverter <TestUnknownClass>(); TypeConverterFactory.RemoveConverter(typeof(TestUnknownClass)); }
/// <summary> /// Registers CsvHelper type converters that can allow serialization of complex types. /// </summary> public static void RegisterAnalysisProgramsTypeConverters() { // This is a manually maintained method TypeConverterFactory.AddConverter <ISet <Point> >(new CsvSetPointConverter()); }
public void GetConverterForCharTest() { var converter = TypeConverterFactory.GetConverter(typeof(char)); Assert.IsInstanceOfType(converter, typeof(CharConverter)); }
/// Load settings /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="storeId">Store identifier for which settigns should be loaded</param> public virtual T LoadSetting <T>(int storeId = 0) where T : ISettings, new() { if (typeof(T).HasAttribute <JsonPersistAttribute>(true)) { return(LoadSettingsJson <T>(storeId)); } var settings = Activator.CreateInstance <T>(); foreach (var fastProp in FastProperty.GetProperties(typeof(T)).Values) { var prop = fastProp.Property; // get properties we can read and write to if (!prop.CanWrite) { continue; } var key = typeof(T).Name + "." + prop.Name; // load by store string setting = GetSettingByKey <string>(key, storeId: storeId, loadSharedValueIfNotFound: true); if (setting == null) { if (fastProp.IsSequenceType) { if ((fastProp.GetValue(settings) as IEnumerable) != null) { // Instance of IEnumerable<> was already created, most likely in the constructor of the settings concrete class. // In this case we shouldn't let the EnumerableConverter create a new instance but keep this one. continue; } } else { #region Obsolete ('EnumerableConverter' can handle this case now) //if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>)) //{ // // convenience: don't return null for simple list types // var listArg = prop.PropertyType.GetGenericArguments()[0]; // object list = null; // if (listArg == typeof(int)) // list = new List<int>(); // else if (listArg == typeof(decimal)) // list = new List<decimal>(); // else if (listArg == typeof(string)) // list = new List<string>(); // if (list != null) // { // fastProp.SetValue(settings, list); // } //} #endregion continue; } } var converter = TypeConverterFactory.GetConverter(prop.PropertyType); if (converter == null || !converter.CanConvertFrom(typeof(string))) { continue; } object value = converter.ConvertFrom(setting); //set property fastProp.SetValue(settings, value); } return(settings); }
public void GetConverterForDoubleTest() { var converter = TypeConverterFactory.GetConverter(typeof(double)); Assert.IsInstanceOfType(converter, typeof(DoubleConverter)); }
public void GetConverterForInt32Test() { var converter = TypeConverterFactory.GetConverter(typeof(int)); Assert.IsInstanceOfType(converter, typeof(Int32Converter)); }
public void GetConverterForGuidTest() { var converter = TypeConverterFactory.GetConverter(typeof(Guid)); Assert.IsInstanceOfType(converter, typeof(GuidConverter)); }
public void GetConverterForNullableTest() { var converter = TypeConverterFactory.GetConverter(typeof(int?)); Assert.IsInstanceOfType(converter, typeof(NullableConverter)); }
protected virtual ISettings LoadSettingCore(Type settingType, int storeId = 0) { var allSettings = GetAllCachedSettings(); var instance = (ISettings)Activator.CreateInstance(settingType); var prefix = settingType.Name; foreach (var fastProp in FastProperty.GetProperties(settingType).Values) { var prop = fastProp.Property; // Get properties we can read and write to if (!prop.CanWrite) { continue; } string key = prefix + "." + prop.Name; if (!allSettings.TryGetValue(CreateCacheKey(key, storeId), out var cachedSetting) && storeId > 0) { // // Fallback to shared (storeId = 0) allSettings.TryGetValue(CreateCacheKey(key, 0), out cachedSetting); } string setting = cachedSetting?.Value; if (setting == null) { if (fastProp.IsSequenceType) { if ((fastProp.GetValue(instance) as IEnumerable) != null) { // Instance of IEnumerable<> was already created, most likely in the constructor of the settings concrete class. // In this case we shouldn't let the EnumerableConverter create a new instance but keep this one. continue; } } else { #region Obsolete ('EnumerableConverter' can handle this case now) //if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>)) //{ // // convenience: don't return null for simple list types // var listArg = prop.PropertyType.GetGenericArguments()[0]; // object list = null; // if (listArg == typeof(int)) // list = new List<int>(); // else if (listArg == typeof(decimal)) // list = new List<decimal>(); // else if (listArg == typeof(string)) // list = new List<string>(); // if (list != null) // { // fastProp.SetValue(settings, list); // } //} #endregion continue; } } var converter = TypeConverterFactory.GetConverter(prop.PropertyType); if (converter == null || !converter.CanConvertFrom(typeof(string))) { continue; } try { object value = converter.ConvertFrom(setting); // Set property fastProp.SetValue(instance, value); } catch (Exception ex) { var msg = "Could not convert setting '{0}' to type '{1}'".FormatInvariant(key, prop.PropertyType.Name); Logger.Error(ex, msg); } } return(instance); }
public void GetConverterForStringTest() { var converter = TypeConverterFactory.GetConverter(typeof(string)); Assert.IsInstanceOfType(converter, typeof(StringConverter)); }
private EnumReader(IColumnReader valueReader, IColumnReader rowIndexReader) { _valueReader = valueReader; _rowIndexReader = rowIndexReader; _rowIndexToIntConverter = TypeConverterFactory.GetConverter(typeof(byte), typeof(int)); }
public void GetConverterForUInt16Test() { var converter = TypeConverterFactory.GetConverter(typeof(ushort)); Assert.IsInstanceOfType(converter, typeof(UInt16Converter)); }
/// <summary> /// Writes a cell to the Excel file. /// </summary> /// <typeparam name="T">The type of the field.</typeparam> /// <param name="row">Row to write the field to.</param> /// <param name="col">Column to write the field to.</param> /// <param name="field">The field to write.</param> /// <param name="numberFormat">Optional number formatting string for the cell</param> /// <param name="dateFormat">Optional DateTime formatting string for the cell</param> /// <param name="fontStyle">Optional font style for the cell</param> /// <param name="fontSize">Optional font size for the cell</param> /// <param name="fontName">Optional font name for the cell</param> public void WriteCell <T>( int row, int col, T field, string numberFormat = null, string dateFormat = null, FontStyle?fontStyle = null, float?fontSize = null, string fontName = null) { // Find the type conversion options var type = typeof(T); var converter = TypeConverterFactory.GetConverter(type); var options = TypeConverterOptions.Merge(TypeConverterOptionsFactory.GetOptions(type, _configuration.CultureInfo)); // Set the formatting options to override the defaults var format = numberFormat ?? dateFormat; if (converter.AcceptsNativeType) { // Convert the options to Excel format if (format != null) { format = XLStyle.FormatDotNetToXL(format, converter.ConvertedType, options.CultureInfo); } else { // If no formatting is provided, see if the native type requires it (mostly for DateTime) format = converter.ExcelFormatString(options); } } else { // Override the formatting for the formatter, and do not format the Excel cell if (numberFormat != null) { options.NumberFormat = format; } else if (dateFormat != null) { options.DateFormat = format; } format = null; } // Find the default style to use for this cell based on the row and column styles var cellStyle = _sheet.Rows[row].Style ?? _sheet.Columns[col].Style; // Clone the style so it does not modify the entire row or column cellStyle = cellStyle?.Clone(); // Set up cell formatting for this cell UpdateStyle(ref cellStyle, format, fontStyle, fontSize, fontName); // Apply the style to this cell if defined if (cellStyle != null) { _sheet[row, col].Style = cellStyle; } // Now write the cell contents object value; if (converter.AcceptsNativeType) { value = field; } else { value = converter.ConvertToExcel(options, field); } var s = value as string; if (s != null && s.StartsWith("=")) { // Write as a formula if it starts with an equals sign _sheet[row, col].Value = ""; _sheet[row, col].Formula = s; } else { _sheet[row, col].Value = value; } }
public void GetConverterForUInt64Test() { var converter = TypeConverterFactory.GetConverter(typeof(ulong)); Assert.IsInstanceOfType(converter, typeof(UInt64Converter)); }