public static void PreLoad(Type type) { // Register soap actions for the methods in the type. foreach (MethodInfo method in type.GetMethods()) { RegisterSoapActionForMethodBase(method); } // Register XML tags for the type, if specified. SoapTypeAttribute tattr = (SoapTypeAttribute) InternalRemotingServices.GetCachedSoapAttribute(type); if (tattr.xmlElementWasSet) { RegisterInteropXmlElement (tattr.XmlElementName, tattr.XmlNamespace, type); } if (tattr.xmlTypeWasSet) { RegisterInteropXmlType (tattr.XmlTypeName, tattr.XmlTypeNamespace, type); } // Load and register the field mapping information. lock (typeof(SoapServices)) { if (fields == null) { fields = new Hashtable(); } TypeFieldInfo typeInfo = new TypeFieldInfo(); foreach (FieldInfo field in type.GetFields()) { SoapFieldAttribute fattr = (SoapFieldAttribute) InternalRemotingServices.GetCachedSoapAttribute (field); if (fattr.IsInteropXmlElement()) { if (fattr.UseAttribute) { typeInfo.StoreAttribute (XmlKey(fattr.XmlElementName, fattr.XmlNamespace), field.Name, field.FieldType); } else { typeInfo.StoreElement (XmlKey(fattr.XmlElementName, fattr.XmlNamespace), field.Name, field.FieldType); } } } if (typeInfo.IsPopulated) { fields[type] = typeInfo; } } }
/// /////////////////////////////////////////////////////////////////////// /// WriteObject /// public void WriteObject(T obj, List <string> row) { row.Clear(); for (int i = 0; i < m_IndexToInfo.Length; i++) { TypeFieldInfo tfi = m_IndexToInfo[i]; if (m_fileDescription.EnforceCsvColumnAttribute && (!tfi.hasColumnAttribute)) { continue; } // ---- Object objValue = null; if (tfi.memberInfo is PropertyInfo) { objValue = ((PropertyInfo)tfi.memberInfo).GetValue(obj, null); } else { objValue = ((FieldInfo)tfi.memberInfo).GetValue(obj); } // ------ string resultString = null; if (objValue != null) { var formattable = objValue as IFormattable; if ((formattable != null)) { resultString = formattable.ToString( tfi.outputFormat, m_fileDescription.FileCultureInfo); } else { resultString = objValue.ToString(); } } // ----- row.Add(resultString); } }
/// /////////////////////////////////////////////////////////////////////// /// WriteObject /// public void WriteObject(T obj, ref List <string> row) { row.Clear(); for (int i = 0; i < IndexToInfo.Length; i++) { TypeFieldInfo tfi = IndexToInfo[i]; if (FileDescription.EnforceCsvColumnAttribute && (!tfi.HasColumnAttribute)) { continue; } // ---- Object objValue = null; if (tfi.MemberInfo is PropertyInfo) { objValue = ((PropertyInfo)tfi.MemberInfo).GetValue(obj, null); } else { objValue = ((FieldInfo)tfi.MemberInfo).GetValue(obj); } // ------ string resultString = null; if (objValue != null) { if ((objValue is IFormattable)) { resultString = ((IFormattable)objValue).ToString( tfi.OutputFormat, FileDescription.FileCultureInfo); } else { resultString = objValue.ToString(); } } // ----- row.Add(resultString); } }
/// /////////////////////////////////////////////////////////////////////// /// ReadNames /// /// <summary> /// Assumes that the fields in parameter row are field names. /// Reads the names into the objects internal structure. /// </summary> /// <param name="row"></param> /// <param name="firstRow"></param> /// <returns></returns> /// public void ReadNames(IDataRow row) { // It is now the order of the field names that determines // the order of the elements in m_IndexToInfo, instead of // the FieldIndex fields. // If there are more names in the file then fields in the type, // and IgnoreUnknownColumns is set to `false` one of the names will // not be found, causing an exception. int currentNameIndex = 0; for (int i = 0; i < row.Count; i++) { if (!m_NameToInfo.ContainsKey(row[i].Value)) { //If we have to ignore this column if (m_fileDescription.IgnoreUnknownColumns) { continue; } // name not found throw new NameNotInTypeException(typeof(T).ToString(), row[i].Value, m_fileName); } // ---- //Map the column index in the CSV file with the column index of the business object. _mappingIndexes.Add(i, currentNameIndex); currentNameIndex++; } // Re-order m_IndexToInfo to match the field names for (int i = 0; i < row.Count; i++) { if (!_mappingIndexes.ContainsKey(i)) { continue; } TypeFieldInfo tfi = m_NameToInfo[row[i].Value]; m_IndexToInfo.Remove(tfi); m_IndexToInfo.Insert(_mappingIndexes[i], tfi); if (m_fileDescription.EnforceCsvColumnAttribute && !tfi.hasColumnAttribute) { // enforcing column attr, but this field/prop has no column attr. throw new MissingCsvColumnAttributeException(typeof(T).ToString(), row[i].Value, m_fileName); } } }
protected void AnalyzeType( Type type, bool allRequiredFieldsMustHaveFieldIndex, bool allCsvColumnFieldsMustHaveFieldIndex) { m_NameToInfo.Clear(); foreach (MemberInfo mi in type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if ((mi.MemberType == MemberTypes.Field) || (mi.MemberType == MemberTypes.Property)) { TypeFieldInfo tfi = AnalyzeTypeField( mi, allRequiredFieldsMustHaveFieldIndex, allCsvColumnFieldsMustHaveFieldIndex); m_NameToInfo[tfi.name] = tfi; } } int nbrTypeFields = m_NameToInfo.Keys.Count; m_IndexToInfo = new TypeFieldInfo[nbrTypeFields]; int i = 0; foreach (KeyValuePair <string, TypeFieldInfo> kvp in m_NameToInfo) { m_IndexToInfo[i++] = kvp.Value; } Array.Sort(m_IndexToInfo); int lastFieldIndex = Int32.MinValue; string lastName = ""; foreach (TypeFieldInfo tfi in m_IndexToInfo) { if ((tfi.index == lastFieldIndex) && (tfi.index != CsvColumnAttribute.mc_DefaultFieldIndex)) { throw new DuplicateFieldIndexException( typeof(T).ToString(), tfi.name, lastName, tfi.index); } lastFieldIndex = tfi.index; lastName = tfi.name; } }
public void TestLogRecord_FullFields() { FieldMapperReading <LogRecord> fm = new FieldMapperReading <LogRecord>(_fileDescriptionNamesUs, null, false); Assert.IsNotNull(fm); Assert.IsNotNull(fm.FieldIndexInfo); Assert.IsNotNull(fm.NameToInfo); Assert.AreEqual(fm.NameToInfo.Count, 27); Assert.IsNotNull(fm.NameToInfo["PCI"]); Assert.AreEqual(fm.NameToInfo["PCI"].HasColumnAttribute, true); List <int> charLengths = fm.GetCharLengths(); Assert.IsNull(charLengths); FileDataAccess dataAccess = new FileDataAccess(_testInput.GetStreamReader(), _fileDescriptionNamesUs); Assert.IsNotNull(dataAccess); RowReader <LogRecord> reader = dataAccess.ReadDataPreparation <LogRecord>(null); Assert.IsNotNull(reader); Assert.IsNotNull(dataAccess.Cs); dataAccess.Row = new DataRow(); Assert.IsTrue(dataAccess.Cs.ReadRow(dataAccess.Row)); bool readingResult = reader.ReadingOneFieldRow(fm, dataAccess.Row, true); Assert.IsFalse(readingResult); Assert.IsTrue(dataAccess.Cs.ReadRow(dataAccess.Row)); Assert.AreEqual(dataAccess.Row[0].Value, "0"); Assert.AreEqual(dataAccess.Row[1].Value, "13:58:08:359"); Assert.AreEqual(dataAccess.Row.Count, 18, "row count"); Assert.AreEqual(fm.FieldIndexInfo.IndexToInfo.Length, 27, "index to info"); Assert.AreEqual(fm.FieldIndexInfo.GetMaxRowCount(18), 18); TypeFieldInfo tfi = fm.FieldIndexInfo.QueryTypeFieldInfo(true, 1); Assert.IsNotNull(tfi); Assert.AreEqual(tfi.OutputFormat, "HH:mm:ss.fff"); string value = dataAccess.Row[1].Value; Assert.AreEqual(value, "13:58:08:359"); }
/// /////////////////////////////////////////////////////////////////////// /// WriteNames /// /// <summary> /// Writes the field names given in T to row. /// </summary> /// public void WriteNames(List <string> row) { row.Clear(); for (int i = 0; i < m_IndexToInfo.Length; i++) { TypeFieldInfo tfi = m_IndexToInfo[i]; if (m_fileDescription.EnforceCsvColumnAttribute && (!tfi.hasColumnAttribute)) { continue; } // ---- row.Add(tfi.name); } }
private TreeNode buildNode(object payload, string name = null) { var node = new TreeNode(); var type = payload.GetType(); if (!IsSimpleType(type)) { node.Text = null == name ? type.Name : name; var propFields = type.GetProperties().SelectMany(p => TypeFieldInfo.GetObjects(p, payload)); var fields = type.GetFields().Select(p => new TypeFieldInfo(p, payload)); foreach (var p in propFields.Concat(fields).Where(p => p != null)) { node.Nodes.Add(buildNode(p.Value, p.Name)); } } else { node.Text = string.Format("{0}:{1}", name, payload.ToString()); } return(node); }
// ----------------------------- // AnalyzeTypeField // private TypeFieldInfo AnalyzeTypeField( MemberInfo mi, bool allRequiredFieldsMustHaveFieldIndex, bool allCsvColumnFieldsMustHaveFieldIndex) { TypeFieldInfo tfi = new TypeFieldInfo(); tfi.memberInfo = mi; if (mi is PropertyInfo) { tfi.fieldType = ((PropertyInfo)mi).PropertyType; } else { tfi.fieldType = ((FieldInfo)mi).FieldType; } // parseNumberMethod will remain null if the property is not a numeric type. // This would be the case for DateTime, Boolean, String and custom types. // In those cases, just use a TypeConverter. // // DateTime and Boolean also have Parse methods, but they don't provide // functionality that TypeConverter doesn't give you. tfi.parseNumberMethod = tfi.fieldType.GetMethod("Parse", new Type[] { typeof(String), typeof(NumberStyles), typeof(IFormatProvider) }); if (tfi.parseNumberMethod == null) { if (m_fileDescription.UseOutputFormatForParsingCsvValue) { tfi.parseExactMethod = tfi.fieldType.GetMethod("ParseExact", new Type[] { typeof(string), typeof(string), typeof(IFormatProvider) }); } tfi.typeConverter = null; if (tfi.parseExactMethod == null) { foreach (Object attribute in mi.GetCustomAttributes(typeof(TypeConverterAttribute), true)) { var typeName = ((TypeConverterAttribute)attribute).ConverterTypeName; tfi.typeConverter = (TypeConverter)Activator.CreateInstance(Type.GetType(typeName)); break; } if (tfi.typeConverter == null) { tfi.typeConverter = TypeDescriptor.GetConverter(tfi.fieldType); } } } // ----- // Process the attributes tfi.index = CsvColumnAttribute.mc_DefaultFieldIndex; tfi.name = mi.Name; tfi.inputNumberStyle = NumberStyles.Any; tfi.outputFormat = ""; tfi.hasColumnAttribute = false; tfi.charLength = 0; foreach (Object attribute in mi.GetCustomAttributes(typeof(CsvColumnAttribute), true)) { CsvColumnAttribute cca = (CsvColumnAttribute)attribute; if (!string.IsNullOrEmpty(cca.Name)) { tfi.name = cca.Name; } tfi.index = cca.FieldIndex; tfi.hasColumnAttribute = true; tfi.canBeNull = cca.CanBeNull; tfi.outputFormat = cca.OutputFormat; tfi.inputNumberStyle = cca.NumberStyle; tfi.charLength = cca.CharLength; } // ----- if (allCsvColumnFieldsMustHaveFieldIndex && tfi.hasColumnAttribute && tfi.index == CsvColumnAttribute.mc_DefaultFieldIndex) { throw new ToBeWrittenButMissingFieldIndexException( typeof(T).ToString(), tfi.name); } if (allRequiredFieldsMustHaveFieldIndex && (!tfi.canBeNull) && (tfi.index == CsvColumnAttribute.mc_DefaultFieldIndex)) { throw new RequiredButMissingFieldIndexException( typeof(T).ToString(), tfi.name); } // ----- return(tfi); }
/// /////////////////////////////////////////////////////////////////////// /// ReadObject /// /// <summary> /// Creates an object of type T from the data in row and returns that object. /// /// </summary> /// <param name="row"></param> /// <param name="firstRow"></param> /// <returns></returns> public T ReadObject(IDataRow row, AggregatedException ae) { //If there are more columns than the required if (row.Count > m_IndexToInfo.Length) { //Are we ignoring unknown columns? if (!m_fileDescription.IgnoreUnknownColumns) { // Too many fields throw new TooManyDataFieldsException(typeof(T).ToString(), row[0].LineNbr, m_fileName); } } // ----- T obj = new T(); //If we will be using the mappings, we just iterate through all the cells in this row int maxRowCount = _mappingIndexes.Count > 0 ? row.Count : Math.Min(row.Count, m_IndexToInfo.Length); for (int i = 0; i < maxRowCount; i++) { TypeFieldInfo tfi; //If there is some index mapping generated and the IgnoreUnknownColums is `true` if (m_fileDescription.IgnoreUnknownColumns && _mappingIndexes.Count > 0) { if (!_mappingIndexes.ContainsKey(i)) { continue; } tfi = m_IndexToInfo[_mappingIndexes[i]]; } else { tfi = m_IndexToInfo[i]; } if (m_fileDescription.EnforceCsvColumnAttribute && (!tfi.hasColumnAttribute)) { // enforcing column attr, but this field/prop has no column attr. // So there are too many fields in this record. throw new TooManyNonCsvColumnDataFieldsException(typeof(T).ToString(), row[i].LineNbr, m_fileName); } // ----- if ((!m_fileDescription.FirstLineHasColumnNames) && (tfi.index == CsvColumnAttribute.mc_DefaultFieldIndex)) { // First line in the file does not have field names, so we're // depending on the FieldIndex of each field in the type // to ensure each value is placed in the correct field. // However, now hit a field where there is no FieldIndex. throw new MissingFieldIndexException(typeof(T).ToString(), row[i].LineNbr, m_fileName); } // ----- if (m_fileDescription.UseFieldIndexForReadingData && (!m_fileDescription.FirstLineHasColumnNames) && (tfi.index > row.Count)) { // First line in the file does not have field names, so we're // depending on the FieldIndex of each field in the type // to ensure each value is placed in the correct field. // However, now hit a field where the FieldIndex is bigger // than the total number of items in a row generated by the separatorChar throw new WrongFieldIndexException(typeof(T).ToString(), row[i].LineNbr, m_fileName); } int index = m_fileDescription.UseFieldIndexForReadingData ? tfi.index - 1 : i; // value to put in the object string value = row[index].Value; if (value == null) { if (!tfi.canBeNull) { ae.AddException( new MissingRequiredFieldException( typeof(T).ToString(), tfi.name, row[i].LineNbr, m_fileName)); } } else { try { Object objValue = null; // Normally, either tfi.typeConverter is not null, // or tfi.parseNumberMethod is not null. // if (tfi.typeConverter != null) { objValue = tfi.typeConverter.ConvertFromString( null, m_fileDescription.FileCultureInfo, value); } else if (tfi.parseExactMethod != null) { objValue = tfi.parseExactMethod.Invoke( tfi.fieldType, new Object[] { value, tfi.outputFormat, m_fileDescription.FileCultureInfo }); } else if (tfi.parseNumberMethod != null) { objValue = tfi.parseNumberMethod.Invoke( tfi.fieldType, new Object[] { value, tfi.inputNumberStyle, m_fileDescription.FileCultureInfo }); } else { // No TypeConverter and no Parse method available. // Try direct approach. objValue = value; } if (tfi.memberInfo is PropertyInfo) { ((PropertyInfo)tfi.memberInfo).SetValue(obj, objValue, null); } else { ((FieldInfo)tfi.memberInfo).SetValue(obj, objValue); } } catch (Exception e) { if (e is TargetInvocationException) { e = e.InnerException; } if (e is FormatException) { e = new WrongDataFormatException( typeof(T).ToString(), tfi.name, value, row[i].LineNbr, m_fileName, e); } ae.AddException(e); } } } // Visit any remaining fields in the type for which no value was given // in the data row, to see whether any of those was required. // If only looking at fields with CsvColumn attribute, do ignore // fields that don't have that attribute. for (int i = row.Count; i < m_IndexToInfo.Length; i++) { TypeFieldInfo tfi = m_IndexToInfo[i]; if (((!m_fileDescription.EnforceCsvColumnAttribute) || tfi.hasColumnAttribute) && (!tfi.canBeNull)) { ae.AddException( new MissingRequiredFieldException( typeof(T).ToString(), tfi.name, row[row.Count - 1].LineNbr, m_fileName)); } } return(obj); }
// ----------------------------- // AnalyzeType // protected void AnalyzeType( Type type, bool allRequiredFieldsMustHaveFieldIndex, bool allCsvColumnFieldsMustHaveFieldIndex) { m_NameToInfo.Clear(); // ------ // Initialize NameToInfo foreach (MemberInfo mi in type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { // Only process field and property members. if ((mi.MemberType == MemberTypes.Field) || (mi.MemberType == MemberTypes.Property)) { // Note that the compiler does not allow fields and/or properties // with the same name as some other field or property. TypeFieldInfo tfi = AnalyzeTypeField( mi, allRequiredFieldsMustHaveFieldIndex, allCsvColumnFieldsMustHaveFieldIndex); m_NameToInfo[tfi.name] = tfi; } } // ------- // Initialize IndexToInfo int nbrTypeFields = m_NameToInfo.Keys.Count; m_IndexToInfo = new TypeFieldInfo[nbrTypeFields]; _mappingIndexes = new Dictionary <int, int>(); int i = 0; foreach (KeyValuePair <string, TypeFieldInfo> kvp in m_NameToInfo) { m_IndexToInfo[i++] = kvp.Value; } // Sort by FieldIndex. Fields without FieldIndex will // be sorted towards the back, because their FieldIndex // is Int32.MaxValue. // // The sort order is important when reading a file that // doesn't have the field names in the first line, and when // writing a file. // // Note that for reading from a file with field names in the // first line, method ReadNames reworks IndexToInfo. Array.Sort(m_IndexToInfo); // ---------- // Make sure there are no duplicate FieldIndices. // However, allow gaps in the FieldIndex range, to make it easier to later insert // fields in the range. int lastFieldIndex = Int32.MinValue; string lastName = ""; foreach (TypeFieldInfo tfi in m_IndexToInfo) { if ((tfi.index == lastFieldIndex) && (tfi.index != CsvColumnAttribute.mc_DefaultFieldIndex)) { throw new DuplicateFieldIndexException( typeof(T).ToString(), tfi.name, lastName, tfi.index); } lastFieldIndex = tfi.index; lastName = tfi.name; } }
/// /////////////////////////////////////////////////////////////////////// /// ReadObject /// /// <summary> /// Creates an object of type T from the data in row and returns that object. /// /// </summary> /// <param name="row"></param> /// <param name="firstRow"></param> /// <returns></returns> public T ReadObject(List <DataRowItem> row, AggregatedException ae) { if (row.Count > m_IndexToInfo.Length) { // Too many fields throw new TooManyDataFieldsException(typeof(T).ToString(), row[0].LineNbr, m_fileName); } // ----- T obj = new T(); for (int i = 0; i < row.Count; i++) { TypeFieldInfo tfi = m_IndexToInfo[i]; if (m_fileDescription.EnforceDLColumnAttribute && (!tfi._bHasColumnAttribute)) { // enforcing column attr, but this field/prop has no column attr. // So there are too many fields in this record. throw new TooManyNonDLColumnDataFieldsException(typeof(T).ToString(), row[i].LineNbr, m_fileName); } // ----- if ((!m_fileDescription.FirstLineHasColumnNames) && (tfi._index == DLColumnAttribute._defaultFieldIndex)) { // First line in the file does not have field names, so we're // depending on the FieldIndex of each field in the type // to ensure each value is placed in the correct field. // However, now hit a field where there is no FieldIndex. throw new MissingFieldIndexException(typeof(T).ToString(), row[i].LineNbr, m_fileName); } // ----- // value to put in the object string value = row[i].Value; if (value == null) { if (!tfi._canBeNull) { ae.AddException( new MissingRequiredFieldException( typeof(T).ToString(), tfi._name, row[i].LineNbr, m_fileName)); } } else { try { Object objValue = null; // Normally, either tfi.typeConverter is not null, // or tfi.parseNumberMethod is not null. // if (tfi.typeConverter != null) { objValue = tfi.typeConverter.ConvertFromString( null, m_fileDescription.FileCultureInfo, value); } else if (tfi.parseNumberMethod != null) { objValue = tfi.parseNumberMethod.Invoke( tfi._fieldType, new Object[] { value, tfi._inputNumberStyle, m_fileDescription.FileCultureInfo }); } else { // No TypeConverter and no Parse method available. // Try direct approach. objValue = value; } if (tfi._memberInfo is PropertyInfo) { ((PropertyInfo)tfi._memberInfo).SetValue(obj, objValue, null); } else { ((FieldInfo)tfi._memberInfo).SetValue(obj, objValue); } } catch (Exception e) { if (e is TargetInvocationException) { e = e.InnerException; } if (e is FormatException) { e = new WrongDataFormatException( typeof(T).ToString(), tfi._name, value, row[i].LineNbr, m_fileName, e); } ae.AddException(e); } } } // Visit any remaining fields in the type for which no value was given // in the data row, to see whether any of those was required. // If only looking at fields with DLColumn attribute, do ignore // fields that don't have that attribute. for (int i = row.Count; i < m_IndexToInfo.Length; i++) { TypeFieldInfo tfi = m_IndexToInfo[i]; if (((!m_fileDescription.EnforceDLColumnAttribute) || tfi._bHasColumnAttribute) && (!tfi._canBeNull)) { ae.AddException( new MissingRequiredFieldException( typeof(T).ToString(), tfi._name, row[row.Count - 1].LineNbr, m_fileName)); } } return(obj); }
public static void PreLoad(Type type) { // Register soap actions for the methods in the type. foreach(MethodInfo method in type.GetMethods()) { RegisterSoapActionForMethodBase(method); } // Register XML tags for the type, if specified. SoapTypeAttribute tattr = (SoapTypeAttribute) InternalRemotingServices.GetCachedSoapAttribute(type); if(tattr.xmlElementWasSet) { RegisterInteropXmlElement (tattr.XmlElementName, tattr.XmlNamespace, type); } if(tattr.xmlTypeWasSet) { RegisterInteropXmlType (tattr.XmlTypeName, tattr.XmlTypeNamespace, type); } // Load and register the field mapping information. lock(typeof(SoapServices)) { if(fields == null) { fields = new Hashtable(); } TypeFieldInfo typeInfo = new TypeFieldInfo(); foreach(FieldInfo field in type.GetFields()) { SoapFieldAttribute fattr = (SoapFieldAttribute) InternalRemotingServices.GetCachedSoapAttribute (field); if(fattr.IsInteropXmlElement()) { if(fattr.UseAttribute) { typeInfo.StoreAttribute (XmlKey(fattr.XmlElementName, fattr.XmlNamespace), field.Name, field.FieldType); } else { typeInfo.StoreElement (XmlKey(fattr.XmlElementName, fattr.XmlNamespace), field.Name, field.FieldType); } } } if(typeInfo.IsPopulated) { fields[type] = typeInfo; } } }
private void FillList(TypeFieldInfo tfi, T obj) { ((PropertyInfo)tfi.memberInfo).SetValue(obj, obj.DynamicResourceList, null); }
private TypeFieldInfo AnalyzeTypeField( MemberInfo mi, bool allRequiredFieldsMustHaveFieldIndex, bool allCsvColumnFieldsMustHaveFieldIndex) { TypeFieldInfo tfi = new TypeFieldInfo(); tfi.memberInfo = mi; if (mi is PropertyInfo) { tfi.fieldType = ((PropertyInfo)mi).PropertyType; } else { tfi.fieldType = ((FieldInfo)mi).FieldType; } tfi.parseNumberMethod = tfi.fieldType.GetMethod("Parse", new Type[] { typeof(String), typeof(NumberStyles), typeof(IFormatProvider) }); tfi.typeConverter = null; if (tfi.parseNumberMethod == null) { tfi.typeConverter = TypeDescriptor.GetConverter(tfi.fieldType); } tfi.index = CsvColumnAttribute.mc_DefaultFieldIndex; tfi.name = mi.Name; tfi.inputNumberStyle = NumberStyles.Any; tfi.outputFormat = ""; tfi.hasColumnAttribute = false; foreach (Object attribute in mi.GetCustomAttributes(typeof(CsvColumnAttribute), true)) { CsvColumnAttribute cca = (CsvColumnAttribute)attribute; if (!string.IsNullOrEmpty(cca.Name)) { tfi.name = cca.Name; } tfi.index = cca.FieldIndex; tfi.hasColumnAttribute = true; tfi.canBeNull = cca.CanBeNull; tfi.outputFormat = cca.OutputFormat; tfi.inputNumberStyle = cca.NumberStyle; } if (allCsvColumnFieldsMustHaveFieldIndex && tfi.hasColumnAttribute && tfi.index == CsvColumnAttribute.mc_DefaultFieldIndex) { throw new ToBeWrittenButMissingFieldIndexException( typeof(T).ToString(), tfi.name); } if (allRequiredFieldsMustHaveFieldIndex && (!tfi.canBeNull) && (tfi.index == CsvColumnAttribute.mc_DefaultFieldIndex)) { throw new RequiredButMissingFieldIndexException( typeof(T).ToString(), tfi.name); } return(tfi); }
public T ReadObject(IDataRow row, AggregatedException ae) { T obj = new T(); obj.DynamicResourceList = new List <DynamicResource>(); List <TypeFieldInfo> list = m_IndexToInfo.ToList(); for (int i = 0; i < row.Count; i++) { TypeFieldInfo tfi = list.Where(tf => tf.name == rowName[i]).SingleOrDefault(); if (tfi != null) { if (m_fileDescription.EnforceCsvColumnAttribute && (!tfi.hasColumnAttribute)) { throw new TooManyNonCsvColumnDataFieldsException(typeof(T).ToString(), row[i].LineNbr, m_fileName); } if ((!m_fileDescription.FirstLineHasColumnNames) && (tfi.index == CsvColumnAttribute.mc_DefaultFieldIndex)) { throw new MissingFieldIndexException(typeof(T).ToString(), row[i].LineNbr, m_fileName); } string value = row[i].Value; if (value == null) { if (!tfi.canBeNull) { ae.AddException( new MissingRequiredFieldException( typeof(T).ToString(), tfi.name, row[i].LineNbr, m_fileName)); } } else { try { Object objValue = null; if (tfi.typeConverter != null) { objValue = tfi.typeConverter.ConvertFromString( null, m_fileDescription.FileCultureInfo, value); } else if (tfi.parseNumberMethod != null) { if (!string.IsNullOrWhiteSpace(value)) { value = value.Replace('.', ','); value = Math.Round(decimal.Parse(value.ToString()), 3).ToString(); } if (string.IsNullOrWhiteSpace(value)) { value = "0"; } if (value.Contains("E") || value.Contains("e")) { value = value.Replace('.', ','); value = Convert.ToDouble(value).ToString(); } objValue = tfi.parseNumberMethod.Invoke( tfi.fieldType, new Object[] { value, tfi.inputNumberStyle, m_fileDescription.FileCultureInfo }); } else { objValue = value; } if (tfi.memberInfo is PropertyInfo) { ((PropertyInfo)tfi.memberInfo).SetValue(obj, objValue, null); } else { ((FieldInfo)tfi.memberInfo).SetValue(obj, objValue); } } catch (Exception e) { if (e is TargetInvocationException) { e = e.InnerException; } if (e is FormatException) { e = new WrongDataFormatException( typeof(T).ToString(), tfi.name, value, row[i].LineNbr, m_fileName, e); } ae.AddException(e); } } } else { if (!string.IsNullOrWhiteSpace(row[i].Value)) { obj.DynamicResourceList.Add(new DynamicResource() { Key = rowName[i], Value = row[i].Value }); } } } for (int i = row.Count; i < m_IndexToInfo.Length; i++) { TypeFieldInfo tfi = m_IndexToInfo[i]; if (((!m_fileDescription.EnforceCsvColumnAttribute) || tfi.hasColumnAttribute) && (!tfi.canBeNull)) { ae.AddException( new MissingRequiredFieldException( typeof(T).ToString(), tfi.name, row[row.Count - 1].LineNbr, m_fileName)); } } return(obj); }