public static void DoMemberLevelValidation(this object rec, string fn, ChoRecordFieldConfiguration fieldConfig, ChoObjectValidationMode vm) { if (!((vm & ChoObjectValidationMode.MemberLevel) == ChoObjectValidationMode.MemberLevel)) { return; } if (rec is IDictionary <string, object> ) { ((IDictionary <string, object>)rec).DoMemberLevelValidation(fn, fieldConfig, vm); } else { if (fieldConfig.PI != null) { if (fieldConfig.Validators.IsNullOrEmpty()) { ChoValidator.ValidateFor(rec, fieldConfig.PI); } else { ChoValidator.ValidateFor(ChoType.GetPropertyValue(rec, fieldConfig.PI), fn, fieldConfig.Validators); } } } }
public static void DoObjectLevelValidation(this object recObject, ChoRecordConfiguration configuration, IEnumerable <ChoRecordFieldConfiguration> fieldConfigurations) { if ((configuration.ObjectValidationMode & ChoObjectValidationMode.ObjectLevel) == ChoObjectValidationMode.ObjectLevel) { if (configuration.HasConfigValidators) { IDictionary <string, Object> dict = null; if (recObject is ExpandoObject) { dict = recObject as IDictionary <string, Object>; } else { dict = new Dictionary <string, object>(); foreach (var pd in configuration.PIDict.Values) { dict.Add(pd.Name, ChoType.GetPropertyValue(recObject, pd)); } } ChoValidator.Validate(dict, configuration.ValDict); } else { if (!configuration.IsDynamicObject) { ChoValidator.Validate(recObject); } } } }
public virtual void Validate() { string propName = null; object propValue = null; string propValueText = null; var results = new List <ValidationResult>(); foreach (PropertyInfo pi in ChoType.GetProperties(GetType())) { propName = pi.Name; results.Clear(); try { propValue = ChoType.GetPropertyValue(this, pi); } catch (Exception ex) { throw new ChoHL7Exception("Failed to validate '{0}' member.".FormatString(pi.FullName()), ex); } try { propValueText = propValue.ToNString(); } catch (Exception ex) { throw new ChoHL7Exception("Failed to validate '{0}' member.".FormatString(pi.FullName()), ex); } pi.CheckRequired(propValue); if (Field != null && Field.Configuration != null && !Field.Configuration.DisableEnumChecks) { pi.CheckForValidEnumValue(propValueText); } var context = new ValidationContext(propValueText, null, null); context.MemberName = pi.Name; Validator.TryValidateValue(propValueText, context, results, ChoTypeDescriptor.GetPropetyAttributes <ValidationAttribute>(ChoTypeDescriptor.GetProperty <ValidationAttribute>(GetType(), pi.Name))); if (results.Count > 0) { throw new ChoHL7Exception("Failed to validate '{0}' member. {2}{1}".FormatString(pi.FullName(), ChoHL7Helper.ToString(results), Environment.NewLine)); } try { if (propValue is ChoHL7AbstractField) { ((ChoHL7AbstractField)propValue).Validate(); } } catch (Exception ex) { throw new ChoHL7Exception("Failed to validate '{0}' member.".FormatString(pi.FullName()), ex); } } }
public static object ConvertToObject(this object source, Type type) { if (source == null) { return(source); } if (source is IDictionary <string, object> ) { return(((IDictionary <string, object>)source).ToObject(type)); } else { if (source is IDictionary) { var dict = ((IDictionary)source).ToDictionary(); return(dict.ToObject(type)); } else { Type sourceType = source.GetType(); object target = ChoActivator.CreateInstance(type); string key = null; object value = null; foreach (var p in ChoType.GetProperties(type)) { if (p.GetCustomAttribute <ChoIgnoreMemberAttribute>() != null) { continue; } key = p.Name; var attr = p.GetCustomAttribute <ChoPropertyAttribute>(); if (attr != null && !attr.Name.IsNullOrWhiteSpace()) { key = attr.Name.NTrim(); } if (!ChoType.HasProperty(sourceType, key)) { continue; } value = ChoType.GetPropertyValue(source, key); p.SetValue(target, value.CastObjectTo(p.PropertyType)); } return(target); } } }
public static Dictionary <string, object> ToDictionary(this object target) { ChoGuard.ArgumentNotNull(target, "Target"); Dictionary <string, object> dict = new Dictionary <string, object>(); foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(target).AsTypedEnumerable <PropertyDescriptor>().Where(pd => !pd.Attributes.OfType <ChoIgnoreMemberAttribute>().Any())) { dict.Add(pd.Name, ChoType.GetPropertyValue(target, pd.Name)); } return(dict); }
public static void DoObjectLevelValidation(this object recObject, ChoRecordConfiguration configuration, IEnumerable <ChoRecordFieldConfiguration> fieldConfigurations) { if (recObject == null) { return; } if ((configuration.ObjectValidationMode & ChoObjectValidationMode.ObjectLevel) == ChoObjectValidationMode.ObjectLevel) { if (configuration.Validator == null) { if (configuration.HasConfigValidators) { IDictionary <string, Object> dict = null; if (recObject is IDictionary <string, object> ) { dict = recObject as IDictionary <string, Object>; } else { dict = new Dictionary <string, object>(); foreach (var pd in configuration.PIDict.Values) { dict.Add(pd.Name, ChoType.GetPropertyValue(recObject, pd)); } } ChoValidator.Validate(dict, configuration.ValDict); } else { if (!configuration.IsDynamicObject) { ChoValidator.Validate(recObject); } } } else { if (recObject != null && configuration.Validator(recObject)) { throw new ValidationException("Failed to validate '{0}' object. {1}".FormatString(recObject.GetType().FullName, Environment.NewLine)); } } } }
protected virtual object Serialize(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { IList result = ChoActivator.CreateInstance(typeof(IList <>).MakeGenericType(targetType)) as IList; if (value != null && !value.GetType().IsCollectionType()) { if (targetType == typeof(object) || targetType.IsSimple()) { foreach (var p in ChoTypeDescriptor.GetProperties(value.GetType()).Where(pd => ChoTypeDescriptor.GetPropetyAttribute <ChoIgnoreMemberAttribute>(pd) == null)) { result.Add(ChoConvert.ConvertTo(ChoType.GetPropertyValue(value, p.Name), targetType, culture)); } } } return(result.OfType <object>().ToArray()); }
public static Dictionary <string, object> ToDictionary(this object target) { ChoGuard.ArgumentNotNull(target, "Target"); if (target is IDictionary <string, object> ) { return((Dictionary <string, object>)target); } Dictionary <string, object> dict = new Dictionary <string, object>(); foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(target.GetType())) { dict.Add(pd.Name, ChoType.GetPropertyValue(target, pd.Name)); } return(dict); }
public static T MemberwiseClone <T>(this T target) where T : new() { T obj = Activator.CreateInstance <T>(); if (target != null) { foreach (PropertyInfo info in ChoType.GetProperties(typeof(T))) { if (ChoType.GetAttribute <ChoIgnorePropertyAttribute>(info, false) == null) { ChoType.SetPropertyValue(obj, info, ChoType.GetPropertyValue(target, info)); } } } return(obj); }
public static void GetValues <T>(this IChoCSVLiteWriter parser, T rec, IList <string> cols) { if (rec is IDictionary <string, object> ) { foreach (var col in ((IDictionary <string, object>)rec).Values) { cols.Add(col.ToNString()); } } else { PropertyInfo[] props = GetPropertyInfos <T>(); foreach (var prop in props) { cols.Add(ChoType.GetPropertyValue(rec, prop).ToNString()); } } }
public static object GetNestedPropertyValue(this object target, string propName) { object parent = null; string memberName = null; if (GetNestedMember(target, propName, ref parent, ref memberName)) { if (parent is IDictionary) { IDictionary dict = parent as IDictionary; if (dict.Contains(memberName)) { return(dict[memberName]); } else { return(null); } } else if (parent is IDictionary <string, object> ) { IDictionary <string, object> dict = parent as IDictionary <string, object>; if (dict.ContainsKey(memberName)) { return(dict[memberName]); } else { return(null); } } else { return(ChoType.GetPropertyValue(parent, memberName)); } } else { return(null); } }
public object GetPropertyValue(object target, PropertyInfo propertyInfo, ChoBSONRecordFieldConfiguration fieldConfig) { if (typeof(IList).IsAssignableFrom(target.GetType())) { if (fieldConfig.ArrayIndex != null) { var item = ((IList)target).OfType <object>().Skip(fieldConfig.ArrayIndex.Value).FirstOrDefault(); if (item != null) { return(ChoType.GetPropertyValue(item, propertyInfo)); } } return(null); } else { var item = ChoType.GetPropertyValue(target, propertyInfo); if (item != null && typeof(IList).IsAssignableFrom(item.GetType())) { if (fieldConfig.ArrayIndex != null) { return(((IList)item).OfType <object>().Skip(fieldConfig.ArrayIndex.Value).FirstOrDefault()); } return(item); } else if (item != null && typeof(IDictionary <string, object>).IsAssignableFrom(item.GetType())) { if (fieldConfig.DictKey != null && ((IDictionary)item).Contains(fieldConfig.DictKey)) { return(((IDictionary)item)[fieldConfig.DictKey]); } return(item); } else { return(item); } } }
public static Dictionary <string, object> ToDictionary(this object target) { ChoGuard.ArgumentNotNull(target, "Target"); if (target is IDictionary <string, object> ) { return((Dictionary <string, object>)target); } if (target is IDictionary) { Dictionary <string, object> dict1 = new Dictionary <string, object>(); foreach (var kvp in ((IDictionary)target).Keys) { dict1.Add(kvp.ToNString(), ((IDictionary)target)[kvp]); } return(dict1); } if (target is IEnumerable <KeyValuePair <string, object> > ) { return(new List <KeyValuePair <string, object> >(target as IEnumerable <KeyValuePair <string, object> >).ToDictionary(x => x.Key, x => x.Value)); } if (target is IEnumerable <Tuple <string, object> > ) { return(new List <Tuple <string, object> >(target as IEnumerable <Tuple <string, object> >).ToDictionary(x => x.Item1, x => x.Item2)); } if (target is IList) { return(((IList)(target)).OfType <object>().Select((item, index) => new KeyValuePair <string, object>("Column_{0}".FormatString(index), item)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value)); } Dictionary <string, object> dict = new Dictionary <string, object>(); foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(target.GetType())) { dict.Add(pd.Name, ChoType.GetPropertyValue(target, pd.Name)); } return(dict); }
public static object MemberwiseClone <T>(this object target) where T : new() { if (target == null) { object obj = Activator.CreateInstance(target.GetType()); foreach (PropertyInfo info in ChoType.GetProperties(target.GetType())) { if (ChoType.GetAttribute <ChoIgnorePropertyAttribute>(info, false) == null) { ChoType.SetPropertyValue(obj, info, ChoType.GetPropertyValue(target, info)); } } return(obj); } else { return(null); } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { return; } Type objectType = value.GetType(); var dict = new Dictionary <string, string>(); if (typeof(IChoKeyValueType).IsAssignableFrom(objectType)) { IChoKeyValueType kvp = value as IChoKeyValueType; var propName = kvp.Key.ToNString(); var propValue = kvp.Value.ToNString(); if (!propName.IsNullOrWhiteSpace()) { dict.Add(propName, propValue); } } else { var kP = ChoTypeDescriptor.GetProperties <ChoKeyAttribute>(objectType).FirstOrDefault(); var vP = ChoTypeDescriptor.GetProperties <ChoValueAttribute>(objectType).FirstOrDefault(); var propName = ChoType.GetPropertyValue(value, kP.Name).ToNString(); var propValue = ChoType.GetPropertyValue(value, vP.Name).ToNString(); if (!propName.IsNullOrWhiteSpace()) { dict.Add(propName, propValue); } } serializer.Serialize(writer, dict); }
private bool ToText(long index, object rec, out string recText) { if (typeof(IChoScalarObject).IsAssignableFrom(Configuration.RecordType)) { rec = ChoActivator.CreateInstance(Configuration.RecordType, rec); } recText = null; StringBuilder msg = new StringBuilder(); object fieldValue = null; string fieldText = null; ChoFixedLengthRecordFieldConfiguration fieldConfig = null; if (Configuration.ColumnCountStrict) { CheckColumnsStrict(rec); } //bool firstColumn = true; PropertyInfo pi = null; object rootRec = rec; IDictionary <string, Object> dict = null; foreach (KeyValuePair <string, ChoFixedLengthRecordFieldConfiguration> kvp in Configuration.RecordFieldConfigurationsDict) { fieldConfig = kvp.Value; fieldValue = null; fieldText = String.Empty; if (Configuration.PIDict != null) { Configuration.PIDict.TryGetValue(kvp.Key, out pi); } rec = GetDeclaringRecord(kvp.Value.DeclaringMember, rootRec); dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (Configuration.IsDynamicObject) { dict = dict.Flatten().ToDictionary(); } if (Configuration.ThrowAndStopOnMissingField) { if (Configuration.IsDynamicObject) { if (!dict.ContainsKey(kvp.Key)) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' FixedLength column.".FormatString(fieldConfig.FieldName)); } } else { if (pi == null) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' FixedLength column.".FormatString(fieldConfig.FieldName)); } } } try { if (Configuration.IsDynamicObject) { fieldValue = dict[kvp.Key]; // dict.GetValue(kvp.Key, Configuration.FileHeaderConfiguration.IgnoreCase, Configuration.Culture); if (kvp.Value.FieldType == null) { if (fieldValue == null) { kvp.Value.FieldType = typeof(string); } else { kvp.Value.FieldType = fieldValue.GetType(); } } } else { if (pi != null) { fieldValue = ChoType.GetPropertyValue(rec, pi); if (kvp.Value.FieldType == null) { kvp.Value.FieldType = pi.PropertyType; } } else { kvp.Value.FieldType = typeof(string); } } //Discover default value, use it if null if (fieldValue == null) { if (fieldConfig.IsDefaultValueSpecified) { fieldValue = fieldConfig.DefaultValue; } } if (!RaiseBeforeRecordFieldWrite(rec, index, kvp.Key, ref fieldValue)) { return(false); } if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(fieldValue); } else { rec.GetNConvertMemberValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue); } if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.ObjectLevel) == ChoObjectValidationMode.MemberLevel) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } if (!RaiseAfterRecordFieldWrite(rec, index, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ref ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (Configuration.IsDynamicObject) { if (dict.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else if (dict.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } else if (pi != null) { if (rec.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (rec.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldWriteError(rec, index, kvp.Key, fieldText, ex)) { throw new ChoWriterException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } } else { throw new ChoWriterException("Failed to use '{0}' fallback value for '{1}' member.".FormatString(fieldValue, kvp.Key), innerEx); } } } if (fieldValue == null) { fieldText = String.Empty; } else { fieldText = fieldValue.ToString(); } msg.Append(NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification, kvp.Value.FieldType), GetFillChar(kvp.Value.FillChar, kvp.Value.FieldType), false, kvp.Value.NullValue, kvp.Value.GetFieldValueTrimOption(kvp.Value.FieldType))); } recText = msg.ToString(); return(true); }
private bool ToText(long index, object rec, out string recText) { if (typeof(IChoScalarObject).IsAssignableFrom(Configuration.RecordType)) { rec = ChoActivator.CreateInstance(Configuration.RecordType, rec); } recText = null; msg.Clear(); if (Configuration.ColumnCountStrict) { CheckColumnCountStrict(rec); } if (Configuration.ColumnOrderStrict) { CheckColumnOrderStrict(rec); } bool firstColumn = true; PropertyInfo pi = null; object rootRec = rec; foreach (KeyValuePair <string, ChoCSVRecordFieldConfiguration> kvp in Configuration.RecordFieldConfigurationsDict) { if (Configuration.IsDynamicObject) { if (Configuration.IgnoredFields.Contains(kvp.Key)) { continue; } } fieldConfig = kvp.Value; fieldValue = null; fieldText = String.Empty; if (Configuration.PIDict != null) { Configuration.PIDict.TryGetValue(kvp.Key, out pi); } rec = GetDeclaringRecord(kvp.Value.DeclaringMember, rootRec); dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (Configuration.IsDynamicObject && Configuration.UseNestedKeyFormat) { dict = dict.Flatten(Configuration.NestedColumnSeparator).ToDictionary(); } if (Configuration.ThrowAndStopOnMissingField) { if (Configuration.IsDynamicObject) { if (!dict.ContainsKey(kvp.Key)) { if (fieldConfig.FieldPosition > dict.Count) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' CSV column.".FormatString(fieldConfig.FieldName)); } } } else { if (pi == null) { pi = Configuration.PIDict.Where(kvp1 => kvp.Value.FieldPosition == kvp.Value.FieldPosition).FirstOrDefault().Value; } if (pi == null) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' CSV column.".FormatString(fieldConfig.FieldName)); } } } try { if (Configuration.IsDynamicObject) { fieldValue = dict.ContainsKey(kvp.Key) ? dict[kvp.Key] : dict[dict.Keys.ElementAt(fieldConfig.FieldPosition - 1)]; // dict.GetValue(kvp.Key, Configuration.FileHeaderConfiguration.IgnoreCase, Configuration.Culture); if (rec is ChoDynamicObject) { var dobj = rec as ChoDynamicObject; kvp.Value.FieldType = dobj.GetMemberType(kvp.Key); } if (kvp.Value.FieldType == null) { if (fieldValue == null) { kvp.Value.FieldType = typeof(string); } else { kvp.Value.FieldType = fieldValue.GetType(); } } } else { if (pi != null) { fieldValue = ChoType.GetPropertyValue(rec, pi); if (kvp.Value.FieldType == null) { kvp.Value.FieldType = pi.PropertyType; } } else { kvp.Value.FieldType = typeof(string); } } //Discover default value, use it if null if (fieldValue == null) { if (fieldConfig.IsDefaultValueSpecified) { fieldValue = fieldConfig.DefaultValue; } } if (!RaiseBeforeRecordFieldWrite(rec, index, kvp.Key, ref fieldValue)) { return(false); } if (fieldConfig.ValueSelector == null) { if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(fieldValue); } else { rec.GetNConvertMemberValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue); } } else { fieldValue = fieldConfig.ValueSelector(rec); } if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.ObjectLevel) == ChoObjectValidationMode.MemberLevel) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } if (!RaiseAfterRecordFieldWrite(rec, index, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ref ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (Configuration.IsDynamicObject) { if (dict.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else if (dict.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } else if (pi != null) { if (rec.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (rec.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldWriteError(rec, index, kvp.Key, fieldText, ex)) { throw new ChoWriterException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } } else { throw new ChoWriterException("Failed to use '{0}' fallback value for '{1}' member.".FormatString(fieldValue, kvp.Key), innerEx); } } } if (fieldValue == null) { fieldText = String.Empty; } else { if (fieldValue is IList) { StringBuilder sb = new StringBuilder(); bool first = true; foreach (var item in (IList)fieldValue) { if (first) { sb.Append(NormalizeFieldValue(kvp.Key, item.ToNString(), null, false, null, ChoFieldValueJustification.None, GetFillChar(kvp.Value.FillChar))); first = false; } else { sb.AppendFormat("{0}{1}", Configuration.Delimiter, NormalizeFieldValue(kvp.Key, item.ToNString(), null, false, null, ChoFieldValueJustification.None, GetFillChar(kvp.Value.FillChar))); } } fieldText = sb.ToString(); } else { fieldText = fieldValue.ToString(); } } if (firstColumn) { msg.Append(NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification), GetFillChar(kvp.Value.FillChar), false, kvp.Value.NullValue, kvp.Value.GetFieldValueTrimOption(kvp.Value.FieldType, Configuration.FieldValueTrimOption), fieldConfig)); firstColumn = false; } else { msg.AppendFormat("{0}{1}", Configuration.Delimiter, NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification), GetFillChar(kvp.Value.FillChar), false, kvp.Value.NullValue, kvp.Value.GetFieldValueTrimOption(kvp.Value.FieldType, Configuration.FieldValueTrimOption), fieldConfig)); } } recText = msg.ToString(); return(true); }
public static bool GetNestedMember(this object target, string propName, ref object parent, ref string memberName) { if (target == null) { return(false); } if (propName.IsNullOrWhiteSpace()) { return(false); } if (!propName.Contains(".")) { parent = target; memberName = propName; return(true); } else { int pos = propName.IndexOf("."); if (pos < 0) { return(false); } string spropName = propName.Substring(0, pos); if (spropName.IsNullOrWhiteSpace()) { return(false); } if (pos + 1 >= propName.Length) { return(false); } string remPropName = propName.Substring(pos + 1); if (target is IDictionary) { IDictionary dict = target as IDictionary; if (dict.Contains(spropName)) { return(GetNestedMember(dict[spropName], remPropName, ref parent, ref memberName)); } else { return(false); } } else if (target is IDictionary <string, object> ) { IDictionary <string, object> dict = target as IDictionary <string, object>; if (dict.ContainsKey(spropName)) { return(GetNestedMember(dict[spropName], remPropName, ref parent, ref memberName)); } else { return(false); } } else if (target is IList) { int index = 0; IList list = (IList)target; if (int.TryParse(spropName, out index)) { if (index < list.Count) { return(GetNestedMember(list[index], remPropName, ref parent, ref memberName)); } else { return(false); } } else { return(false); } } else { return(GetNestedMember(ChoType.GetPropertyValue(target, spropName), remPropName, ref parent, ref memberName)); } } }
private bool ToText(long index, object rec, out string recText) { recText = null; StringBuilder msg = new StringBuilder(); object fieldValue = null; string fieldText = null; ChoXmlRecordFieldConfiguration fieldConfig = null; if (Configuration.ColumnCountStrict) { CheckColumnsStrict(rec); } //bool firstColumn = true; PropertyInfo pi = null; bool isElementClosed = false; msg.AppendFormat("{1}<{0}", Configuration.NodeName, Configuration.Indent); foreach (KeyValuePair <string, ChoXmlRecordFieldConfiguration> kvp in Configuration.RecordFieldConfigurationsDict) { fieldConfig = kvp.Value; fieldValue = null; fieldText = String.Empty; if (Configuration.PIDict != null) { Configuration.PIDict.TryGetValue(kvp.Key, out pi); } if (Configuration.ThrowAndStopOnMissingField) { if (Configuration.IsDynamicObject) { var dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (!dict.ContainsKey(kvp.Key)) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' Xml node.".FormatString(fieldConfig.FieldName)); } } else { if (pi == null) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' Xml node.".FormatString(fieldConfig.FieldName)); } } } try { if (Configuration.IsDynamicObject) { IDictionary <string, Object> dict = rec.ToDynamicObject() as IDictionary <string, Object>; fieldValue = dict[kvp.Key]; // dict.GetValue(kvp.Key, Configuration.FileHeaderConfiguration.IgnoreCase, Configuration.Culture); if (kvp.Value.FieldType == null) { if (fieldValue == null) { kvp.Value.FieldType = typeof(string); } else { kvp.Value.FieldType = fieldValue.GetType(); } } } else { if (pi != null) { fieldValue = ChoType.GetPropertyValue(rec, pi); if (kvp.Value.FieldType == null) { kvp.Value.FieldType = pi.PropertyType; } } else { kvp.Value.FieldType = typeof(string); } } //Discover default value, use it if null if (fieldValue == null) { if (fieldConfig.IsDefaultValueSpecified) { fieldValue = fieldConfig.DefaultValue; } } if (!RaiseBeforeRecordFieldWrite(rec, index, kvp.Key, ref fieldValue)) { return(false); } rec.GetNConvertMemberValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue); if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.ObjectLevel) == ChoObjectValidationMode.MemberLevel) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } if (!RaiseAfterRecordFieldWrite(rec, index, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (Configuration.IsDynamicObject) { var dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (dict.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else if (dict.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { throw new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); } } else if (pi != null) { if (rec.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (rec.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { throw new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); } } else { throw new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldWriteError(rec, index, kvp.Key, fieldText, ex)) { throw new ChoWriterException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } } else { throw new ChoWriterException("Failed to use '{0}' fallback value for '{1}' member.".FormatString(fieldValue, kvp.Key), innerEx); } } } if (fieldValue == null) { fieldText = String.Empty; } else { fieldText = fieldValue.ToString(); } if (fieldConfig.IsXmlAttribute) { msg.Append(@" {0}=""{1}""".FormatString(fieldConfig.FieldName, NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification, kvp.Value.FieldType), GetFillChar(kvp.Value.FillChar, kvp.Value.FieldType), false))); } else { if (!isElementClosed) { msg.AppendFormat(">{0}", Configuration.EOLDelimiter); isElementClosed = true; } msg.Append("{2}{2}<{0}>{1}</{0}>{3}".FormatString(fieldConfig.FieldName, NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification, kvp.Value.FieldType), GetFillChar(kvp.Value.FillChar, kvp.Value.FieldType), false), Configuration.Indent, Configuration.EOLDelimiter)); } } if (!isElementClosed) { msg.AppendFormat(">{0}", Configuration.EOLDelimiter); isElementClosed = true; } msg.AppendFormat("{1}</{0}>", Configuration.NodeName, Configuration.Indent); recText = msg.ToString(); return(true); }
private static void ZipToDictionary(object target, Dictionary <string, object> dict, Action <Dictionary <string, object>, string, object> collisionResolver = null) { if (target == null) { return; } else if (target.GetType().GetUnderlyingType().IsSimple()) { return; } else if (target.GetType().GetUnderlyingType().IsSimpleSpecial()) { return; } if (target is IDictionary) { foreach (var kvp in ((IDictionary)target).Keys) { if (!dict.ContainsKey(kvp.ToNString())) { dict.Add(kvp.ToNString(), ((IDictionary)target)[kvp]); } else if (collisionResolver != null) { collisionResolver(dict, kvp.ToNString(), ((IDictionary)target)[kvp]); } } } if (target is IEnumerable <KeyValuePair <string, object> > ) { foreach (var kvp in (IEnumerable <KeyValuePair <string, object> >)target) { if (!dict.ContainsKey(kvp.Key)) { dict.Add(kvp.Key, kvp.Value); } else if (collisionResolver != null) { collisionResolver(dict, kvp.Key, kvp.Value); } } } if (target is IEnumerable <Tuple <string, object> > ) { foreach (var kvp in (IEnumerable <Tuple <string, object> >)target) { if (!dict.ContainsKey(kvp.Item1)) { dict.Add(kvp.Item1, kvp.Item2); } else if (collisionResolver != null) { collisionResolver(dict, kvp.Item1, kvp.Item2); } } } if (target is IList) { foreach (var kvp in ((IList)(target)).OfType <object>().Select((item, index) => { return(new KeyValuePair <string, object>($"{ChoETLSettings.ValueNamePrefix}{index + ChoETLSettings.ValueNameStartIndex}", item)); }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToDictionaryInternal(kvp.Key))) { if (!dict.ContainsKey(kvp.Key)) { dict.Add(kvp.Key, kvp.Value); } else if (collisionResolver != null) { collisionResolver(dict, kvp.Key, kvp.Value); } } } string propNamex = null; foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(target.GetType())) { propNamex = pd.GetDisplayName(pd.Name); var value = ChoType.GetPropertyValue(target, pd.Name); if (!dict.ContainsKey(propNamex)) { dict.Add(propNamex, value); } else if (collisionResolver != null) { collisionResolver(dict, propNamex, value); } } }
public static bool GetNestedMember(this object target, string propName, ref object parent, ref string memberName, bool createSubKeysIfNotExists = false, Func <object> factory = null) { if (target == null) { return(false); } if (propName.IsNullOrWhiteSpace()) { return(false); } parent = target; if (!propName.Contains(".")) { memberName = propName; return(true); } else { int pos = propName.IndexOf("."); if (pos < 0) { return(false); } string spropName = propName.Substring(0, pos); if (spropName.IsNullOrWhiteSpace()) { return(false); } if (pos + 1 >= propName.Length) { return(false); } string remPropName = propName.Substring(pos + 1); if (target is IDictionary) { IDictionary dict = target as IDictionary; if (dict.Contains(spropName)) { return(GetNestedMember(dict[spropName], remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory)); } else { if (!createSubKeysIfNotExists) { return(false); } else { memberName = spropName; var child = factory != null?factory() : null; if (child == null) { return(false); } dict.Add(spropName, child); return(GetNestedMember(dict[spropName], remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory)); } } } else if (target is IDictionary <string, object> ) { IDictionary <string, object> dict = target as IDictionary <string, object>; if (dict.ContainsKey(spropName)) { return(GetNestedMember(dict[spropName], remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory)); } else { return(false); } } else if (target is IList) { int index = 0; IList list = (IList)target; if (int.TryParse(spropName, out index)) { if (index < list.Count) { return(GetNestedMember(list[index], remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory)); } else { return(false); } } else { return(false); } } else { return(GetNestedMember(ChoType.GetPropertyValue(target, spropName), remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory)); } } }
public static Dictionary <string, object> ToSimpleDictionary(this object target) { if (target == null) { return(null); } //ChoGuard.ArgumentNotNull(target, "Target"); if (target is IDictionary <string, object> ) { return((Dictionary <string, object>)target); } if (target is IDictionary) { Dictionary <string, object> dict1 = new Dictionary <string, object>(); foreach (var kvp in ((IDictionary)target).Keys) { dict1.Add(kvp.ToNString(), ((IDictionary)target)[kvp]); } return(dict1); } if (target is IEnumerable <KeyValuePair <string, object> > ) { return(new List <KeyValuePair <string, object> >(target as IEnumerable <KeyValuePair <string, object> >).ToDictionary(x => x.Key, x => x.Value)); } if (target is IEnumerable <Tuple <string, object> > ) { return(new List <Tuple <string, object> >(target as IEnumerable <Tuple <string, object> >).ToDictionary(x => x.Item1, x => x.Item2)); } if (target is IList) { return(((IList)(target)).OfType <object>().Select((item, index) => { return new KeyValuePair <string, object>($"{ChoETLSettings.ValueNamePrefix}{index + ChoETLSettings.ValueNameStartIndex}", item); }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value)); } string propNamex = null; Dictionary <string, object> dict = new Dictionary <string, object>(); foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(target.GetType())) { propNamex = pd.GetDisplayName(pd.Name); var value = ChoType.GetPropertyValue(target, pd.Name); if (value == null) { dict.Add(propNamex, value); } else if (value.GetType().GetUnderlyingType().IsSimple()) { dict.Add(propNamex, value); } else if (value.GetType().GetUnderlyingType().IsSimpleSpecial()) { dict.Add(propNamex, value.ToNString()); } else { dict.Add(propNamex, value); } } return(dict); }
public static void ConvertNSetMemberValue(this object rec, string fn, ChoRecordFieldConfiguration fieldConfig, ref object fieldValue, CultureInfo culture) { if (fieldConfig.PI == null) { return; } if (fieldValue is ChoDynamicObject) { ((ChoDynamicObject)fieldValue).DynamicObjectName = fn; } if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(fieldValue); } else { if (fieldValue != null && fieldConfig.PI.PropertyType != null && fieldConfig.PI.PropertyType.IsAssignableFrom(fieldValue.GetType())) { } else if (fieldConfig.PI.PropertyType.IsGenericType && fieldConfig.PI.PropertyType.GetGenericTypeDefinition() == typeof(Dictionary <,>) /*&& typeof(string) == fieldConfig.PI.PropertyType.GetGenericArguments()[0]*/) { IDictionary dict = ChoType.GetPropertyValue(rec, fieldConfig.PI) as IDictionary; if (dict == null) { dict = (IDictionary)Activator.CreateInstance(fieldConfig.FieldType); ChoType.SetPropertyValue(rec, fieldConfig.PI, dict); } if (fieldConfig is ChoFileRecordFieldConfiguration && !((ChoFileRecordFieldConfiguration)fieldConfig).DictKey.IsNullOrWhiteSpace()) { if (!dict.Contains(fn)) { var valueType = fieldConfig.PI.PropertyType.GetGenericArguments()[1]; object[] fcParams = GetPropertyConvertersParams(fieldConfig); if (fieldConfig.ValueConverters.IsNullOrEmpty()) { fieldValue = ChoConvert.ConvertFrom(fieldValue, valueType, null, null, fcParams, culture); } else { fieldValue = ChoConvert.ConvertFrom(fieldValue, valueType, null, fieldConfig.ValueConverters.ToArray(), fcParams, culture); } dict.Add(fn, fieldValue); } } else { object[] fcParams = GetPropertyConvertersParams(fieldConfig); if (fieldConfig.Converters.IsNullOrEmpty()) { if (fieldConfig.PropConverters.IsNullOrEmpty()) { var keyType = fieldConfig.PI.PropertyType.GetGenericArguments()[0]; var valueType = fieldConfig.PI.PropertyType.GetGenericArguments()[1]; char itemSeparator = ';'; char keyValueSeparator = '='; if (fieldConfig is ChoCSVRecordFieldConfiguration) { var fc = fieldConfig as ChoCSVRecordFieldConfiguration; if (!fc.ItemSeparator.IsNull()) { itemSeparator = fc.ItemSeparator; } if (!fc.KeyValueSeparator.IsNull()) { keyValueSeparator = fc.KeyValueSeparator; } } object key = null; object value = null; foreach (var kvp in ((string)fieldValue).ToKeyValuePairs(itemSeparator, keyValueSeparator)) { key = null; value = null; if (fieldConfig.KeyConverters.IsNullOrEmpty()) { key = ChoConvert.ConvertFrom(kvp.Key, keyType, null, null, fcParams, culture); } else { key = ChoConvert.ConvertFrom(kvp.Key, keyType, null, fieldConfig.KeyConverters.ToArray(), fcParams, culture); } if (fieldConfig.ValueConverters.IsNullOrEmpty()) { value = ChoConvert.ConvertFrom(kvp.Value, valueType, null, null, fcParams, culture); } else { value = ChoConvert.ConvertFrom(kvp.Value, valueType, null, fieldConfig.ValueConverters.ToArray(), fcParams, culture); } if (key != null) { dict.Add(key, value); } } } else { fieldValue = ChoConvert.ConvertFrom(fieldValue, fieldConfig.PI.PropertyType, null, fieldConfig.PropConverters, fcParams, culture); } } else { fieldValue = ChoConvert.ConvertFrom(fieldValue, fieldConfig.PI.PropertyType, null, fieldConfig.Converters.ToArray(), fcParams, culture); } } return; } else if (typeof(IList).IsAssignableFrom(fieldConfig.PI.PropertyType)) { var itemType = fieldConfig.PI.PropertyType.GetItemType(); IList list = ChoType.GetPropertyValue(rec, fieldConfig.PI) as IList; if (list == null && !fieldConfig.FieldType.IsArray) { list = (IList)Activator.CreateInstance(fieldConfig.FieldType); ChoType.SetPropertyValue(rec, fieldConfig.PI, list); } if (((ChoFileRecordFieldConfiguration)fieldConfig).ArrayIndex != null) { if (list != null) { if (itemType != null) { object[] fcParams = GetPropertyConvertersParams(fieldConfig); if (fieldConfig.ItemConverters.IsNullOrEmpty()) { fieldValue = ChoConvert.ConvertFrom(fieldValue, itemType, null, null, fcParams, culture); } else { fieldValue = ChoConvert.ConvertFrom(fieldValue, itemType, null, fieldConfig.ItemConverters.ToArray(), fcParams, culture); } } if (list.IsFixedSize) { int ai = fieldConfig is ChoFileRecordFieldConfiguration ? ((ChoFileRecordFieldConfiguration)fieldConfig).ArrayIndex != null ? ((ChoFileRecordFieldConfiguration)fieldConfig).ArrayIndex.Value : -1 : -1; if (ai >= 0 && ai < ((Array)list).Length) { ((Array)list).SetValue(fieldValue, ai); } } else { list.Add(fieldValue); } } return; } else { object[] fcParams = GetPropertyConvertersParams(fieldConfig); if (fieldConfig.Converters.IsNullOrEmpty()) { if (fieldConfig.PropConverters.IsNullOrEmpty() && fieldValue is string) { List <object> result = new List <object>(); if (itemType != null) { char itemSeparator = ';'; if (fieldConfig is ChoCSVRecordFieldConfiguration) { var fc = fieldConfig as ChoCSVRecordFieldConfiguration; if (!fc.ItemSeparator.IsNull()) { itemSeparator = fc.ItemSeparator; } } foreach (var item in ((string)fieldValue).SplitNTrim(itemSeparator)) { if (fieldConfig.ItemConverters.IsNullOrEmpty()) { result.Add(ChoConvert.ConvertFrom(item, itemType, null, null, fcParams, culture)); } else { result.Add(ChoConvert.ConvertFrom(item, itemType, null, fieldConfig.ItemConverters.ToArray(), fcParams, culture)); } } } if (fieldConfig.PI.PropertyType.IsArray) { fieldValue = result.ToArray(); } else { fieldValue = result; } } else { fieldValue = ChoConvert.ConvertFrom(fieldValue, fieldConfig.PI.PropertyType, null, fieldConfig.PropConverters, fcParams, culture); } } else { fieldValue = ChoConvert.ConvertFrom(fieldValue, fieldConfig.PI.PropertyType, null, fieldConfig.Converters.ToArray(), fcParams, culture); } } } else { object[] fcParams = GetPropertyConvertersParams(fieldConfig); if (fieldConfig.Converters.IsNullOrEmpty()) { fieldValue = ChoConvert.ConvertFrom(fieldValue, fieldConfig.PI.PropertyType, null, fieldConfig.PropConverters, fcParams, culture); } else { fieldValue = ChoConvert.ConvertFrom(fieldValue, fieldConfig.PI.PropertyType, null, fieldConfig.Converters.ToArray(), fcParams, culture); } } } ChoType.SetPropertyValue(rec, fieldConfig.PI, fieldValue); }
public static Dictionary <string, object> ToDictionary(this object target, string propName = null) { if (target == null) { return(null); } //ChoGuard.ArgumentNotNull(target, "Target"); if (target is IDictionary <string, object> ) { return((Dictionary <string, object>)target); } if (target is IDictionary) { Dictionary <string, object> dict1 = new Dictionary <string, object>(); foreach (var kvp in ((IDictionary)target).Keys) { dict1.Add(kvp.ToNString(), ((IDictionary)target)[kvp]); } return(dict1); } if (target is IEnumerable <KeyValuePair <string, object> > ) { return(new List <KeyValuePair <string, object> >(target as IEnumerable <KeyValuePair <string, object> >).ToDictionary(x => x.Key, x => x.Value.ToDictionaryInternal())); } if (target is IEnumerable <Tuple <string, object> > ) { return(new List <Tuple <string, object> >(target as IEnumerable <Tuple <string, object> >).ToDictionary(x => x.Item1, x => x.Item2.ToDictionaryInternal())); } if (target is IList) { return(((IList)(target)).OfType <object>().Select((item, index) => { return new KeyValuePair <string, object>("{0}".FormatString(index), item); }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToDictionaryInternal())); } Dictionary <string, object> dict = new Dictionary <string, object>(); foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(target.GetType())) { var value = ChoType.GetPropertyValue(target, pd.Name); if (value == null) { dict.Add(pd.Name, value); } else if (value.GetType().IsSimpleSpecial()) { dict.Add(pd.Name, value.ToNString()); } else if (value.GetType().IsSimple()) { dict.Add(pd.Name, value); } else { dict.Add(pd.Name, value.ToDictionary(pd.Name)); } } return(dict); }
private bool ToText(int index, object rec, out string recText) { recText = null; StringBuilder msg = new StringBuilder(); object fieldValue = null; string fieldText = null; ChoCSVRecordFieldConfiguration fieldConfig = null; if (Configuration.ColumnCountStrict) { CheckColumnsStrict(rec); } bool firstColumn = true; foreach (KeyValuePair <string, ChoCSVRecordFieldConfiguration> kvp in Configuration.RecordFieldConfigurationsDict) { fieldConfig = kvp.Value; fieldValue = null; fieldText = String.Empty; if (Configuration.ThrowAndStopOnMissingField) { if (rec is ExpandoObject) { var dict = rec as IDictionary <string, Object>; if (!dict.Keys.Contains(kvp.Key, Configuration.FileHeaderConfiguration.StringComparer)) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' CSV column.".FormatString(fieldConfig.FieldName)); } } else { if (!ChoType.HasProperty(rec.GetType(), kvp.Key)) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' CSV column.".FormatString(fieldConfig.FieldName)); } } } try { if (rec is ExpandoObject) { IDictionary <string, Object> dict = rec as IDictionary <string, Object>; fieldValue = dict.GetValue(kvp.Key, Configuration.FileHeaderConfiguration.IgnoreCase, Configuration.Culture); } else { if (ChoType.HasProperty(rec.GetType(), kvp.Key)) { fieldValue = ChoType.GetPropertyValue(rec, kvp.Key); } } //Discover default value, use it if null if (fieldValue == null) { fieldValue = rec.GetDefaultValue(kvp.Key, fieldConfig); } if (!RaiseBeforeRecordFieldWrite(rec, index, kvp.Key, ref fieldValue)) { return(false); } fieldValue = rec.GetNConvertMemberValue(kvp.Key, kvp.Value, Configuration.Culture, fieldValue); rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); if (!RaiseAfterRecordFieldWrite(rec, index, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (rec is ExpandoObject) { var dict = rec as IDictionary <string, Object>; if (dict.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { throw new ChoParserException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } else if (ChoType.HasProperty(rec.GetType(), kvp.Key) && rec.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { throw new ChoParserException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldWriteError(rec, index, kvp.Key, fieldText, ex)) { throw new ChoParserException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } } else { throw new ChoParserException("Failed to use '{0}' fallback value for '{1}' member.".FormatString(fieldValue, kvp.Key), innerEx); } } } if (fieldValue == null) { fieldText = String.Empty; } else { fieldText = fieldValue.ToString(); } if (firstColumn) { msg.Append(NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification), GetFillChar(kvp.Value.FillChar), false)); firstColumn = false; } else { msg.AppendFormat("{0}{1}", Configuration.Delimiter, NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification), GetFillChar(kvp.Value.FillChar), false)); } } recText = msg.ToString(); return(true); }
private bool ToText(long index, object rec, out string recText) { if (typeof(IChoScalarObject).IsAssignableFrom(Configuration.RecordType)) { rec = ChoActivator.CreateInstance(Configuration.RecordType, rec); } if (!Configuration.IsDynamicObject) { if (rec.ToTextIfCustomSerialization(out recText)) { return(true); } //Check if KVP object if (rec.GetType().IsKeyValueType()) { recText = SerializeObject(rec); return(true); } } recText = null; if (Configuration.UseYamlSerialization) { recText = new Serializer().Serialize(rec, rec.GetType()); return(true); } StringBuilder msg = new StringBuilder(); object fieldValue = null; string fieldText = null; ChoYamlRecordFieldConfiguration fieldConfig = null; string fieldName = null; if (Configuration.ColumnCountStrict) { CheckColumnsStrict(rec); } //bool firstColumn = true; PropertyInfo pi = null; bool isFirst = true; object rootRec = rec; Dictionary <string, object> output = new Dictionary <string, object>(); foreach (KeyValuePair <string, ChoYamlRecordFieldConfiguration> kvp in Configuration.RecordFieldConfigurationsDict.OrderBy(kvp => kvp.Value.Order)) { //if (Configuration.IsDynamicObject) //{ if (Configuration.IgnoredFields.Contains(kvp.Key)) { continue; } //} fieldConfig = kvp.Value; fieldName = fieldConfig.FieldName; fieldValue = null; fieldText = String.Empty; if (Configuration.PIDict != null) { Configuration.PIDict.TryGetValue(kvp.Key, out pi); } rec = GetDeclaringRecord(kvp.Value.DeclaringMember, rootRec); if (Configuration.ThrowAndStopOnMissingField) { if (Configuration.IsDynamicObject) { var dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (!dict.ContainsKey(kvp.Key)) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' Yaml node.".FormatString(fieldConfig.FieldName)); } } else { if (pi == null) { if (!RecordType.IsSimple()) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' Yaml node.".FormatString(fieldConfig.FieldName)); } } } } try { if (Configuration.IsDynamicObject) { IDictionary <string, Object> dict = rec.ToDynamicObject() as IDictionary <string, Object>; fieldValue = dict[kvp.Key]; // dict.GetValue(kvp.Key, Configuration.FileHeaderConfiguration.IgnoreCase, Configuration.Culture); if (rec is ChoDynamicObject) { } if (kvp.Value.FieldType == null) { if (rec is ChoDynamicObject) { var dobj = rec as ChoDynamicObject; kvp.Value.FieldType = dobj.GetMemberType(kvp.Key); } if (kvp.Value.FieldType == null) { if (ElementType == null) { kvp.Value.FieldType = typeof(object); } else { kvp.Value.FieldType = ElementType; } } } } else { if (pi != null) { fieldValue = ChoType.GetPropertyValue(rec, pi); if (kvp.Value.FieldType == null) { kvp.Value.FieldType = pi.PropertyType; } } else { kvp.Value.FieldType = typeof(string); } } //Discover default value, use it if null //if (fieldValue == null) //{ // if (fieldConfig.IsDefaultValueSpecified) // fieldValue = fieldConfig.DefaultValue; //} bool ignoreFieldValue = fieldValue.IgnoreFieldValue(fieldConfig.IgnoreFieldValueMode); if (ignoreFieldValue) { fieldValue = fieldConfig.IsDefaultValueSpecified ? fieldConfig.DefaultValue : null; } if (!RaiseBeforeRecordFieldWrite(rec, index, kvp.Key, ref fieldValue)) { return(false); } if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(fieldValue); } else if (RecordType.IsSimple()) { fieldValue = new List <object> { rec } } ; else { rec.GetNConvertMemberValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue, true); } if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.ObjectLevel) == ChoObjectValidationMode.MemberLevel) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } if (!RaiseAfterRecordFieldWrite(rec, index, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ref ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (Configuration.IsDynamicObject) { var dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (dict.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else if (dict.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } else if (pi != null) { if (rec.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (rec.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldWriteError(rec, index, kvp.Key, ref fieldValue, ex)) { throw new ChoWriterException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } } else { throw new ChoWriterException("Failed to use '{0}' fallback value for '{1}' member.".FormatString(fieldValue, kvp.Key), innerEx); } } } bool isSimple = true; if (fieldConfig.CustomSerializer != null) { fieldText = fieldConfig.CustomSerializer(fieldValue) as string; } else if (RaiseRecordFieldSerialize(rec, index, kvp.Key, ref fieldValue)) { fieldText = fieldValue as string; } else if (fieldConfig.PropCustomSerializer != null) { fieldText = ChoCustomSerializer.Serialize(fieldValue, typeof(string), fieldConfig.PropCustomSerializer, fieldConfig.PropCustomSerializerParams, Configuration.Culture, fieldConfig.Name) as string; } else { Type ft = fieldValue == null ? typeof(object) : fieldValue.GetType(); //if (fieldConfig.IgnoreFieldValue(fieldValue)) // fieldText = null; bool ignoreFieldValue = fieldValue.IgnoreFieldValue(fieldConfig.IgnoreFieldValueMode); if (ignoreFieldValue) { fieldText = null; } else if (fieldValue == null) { //if (fieldConfig.FieldType == null || fieldConfig.FieldType == typeof(object)) //{ // if (fieldConfig.NullValue == null) // fieldText = !fieldConfig.IsArray ? "null" : "[]"; // else // fieldText = fieldConfig.NullValue; //} if (Configuration.NullValueHandling == ChoNullValueHandling.Ignore) { fieldText = null; } else if (Configuration.NullValueHandling == ChoNullValueHandling.Default) { fieldText = ChoActivator.CreateInstance(fieldConfig.FieldType).ToNString(); } else if (Configuration.NullValueHandling == ChoNullValueHandling.Empty && fieldConfig.FieldType == typeof(string)) { fieldText = String.Empty; } else { if (fieldConfig.NullValue == null) { } else { fieldText = fieldConfig.NullValue; } } } else if (ft == typeof(string) || ft == typeof(char)) { fieldText = NormalizeFieldValue(kvp.Key, fieldValue.ToString(), kvp.Value.Size, kvp.Value.Truncate, false, GetFieldValueJustification(kvp.Value.FieldValueJustification, kvp.Value.FieldType), GetFillChar(kvp.Value.FillChar, kvp.Value.FieldType), false, kvp.Value.GetFieldValueTrimOption(kvp.Value.FieldType, Configuration.FieldValueTrimOption)); } else if (ft == typeof(DateTime) || ft == typeof(TimeSpan)) { fieldText = ChoConvert.ConvertTo(fieldValue, typeof(String), Configuration.Culture) as string; } else if (ft.IsEnum) { fieldText = ChoConvert.ConvertTo(fieldValue, typeof(String), Configuration.Culture) as string; } else if (ft == typeof(ChoCurrency)) { fieldText = fieldValue.ToString(); } else if (ft == typeof(bool)) { fieldText = ChoConvert.ConvertTo(fieldValue, typeof(String), Configuration.Culture) as string; } else if (ft.IsNumeric()) { fieldText = ChoConvert.ConvertTo(fieldValue, typeof(String), Configuration.Culture) as string; } else { isSimple = false; } } object objValue = null; if (isSimple) { objValue = fieldText; } else { Writer.ContractResolverState = new ChoContractResolverState { Name = kvp.Key, Index = index, Record = rec, FieldConfig = kvp.Value }; var json = JsonConvert.SerializeObject(fieldValue, Configuration.JsonSerializerSettings); if (RecordType.IsSimple()) { objValue = JsonConvert.DeserializeObject <IList <object> >(json); } else { objValue = JsonConvert.DeserializeObject <IDictionary <string, object> >(json); } } if (!RecordType.IsSimple()) { output.Add(fieldName, objValue); } else { fieldValue = objValue; } } if (!RecordType.IsSimple()) { recText = Configuration.YamlSerializer.Serialize(output, output.GetType()); } else { recText = Configuration.YamlSerializer.Serialize(fieldValue, fieldValue.GetType()); } return(true); }
private bool ToText(long index, object rec, out string recText) { if (typeof(IChoScalarObject).IsAssignableFrom(Configuration.RecordType)) { rec = Activator.CreateInstance(Configuration.RecordType, rec); } if (!Configuration.IsDynamicObject) { if (rec.ToTextIfCustomSerialization(out recText)) { return(true); } //Check if KVP object if (rec.GetType().IsKeyValueType()) { recText = SerializeObject(rec); return(true); } } recText = null; if (rec == null) { if (Configuration.NullValueHandling == ChoNullValueHandling.Ignore) { return(false); } else if (Configuration.NullValueHandling == ChoNullValueHandling.Default) { rec = Activator.CreateInstance(Configuration.RecordType); } else { recText = "{{{0}}}".FormatString(Configuration.Formatting == Formatting.Indented ? Configuration.EOLDelimiter : String.Empty); return(true); } } StringBuilder msg = new StringBuilder(); object fieldValue = null; string fieldText = null; ChoJSONRecordFieldConfiguration fieldConfig = null; if (Configuration.ColumnCountStrict) { CheckColumnsStrict(rec); } //bool firstColumn = true; PropertyInfo pi = null; bool isFirst = true; object rootRec = rec; msg.AppendFormat("{{{0}", Configuration.Formatting == Formatting.Indented ? Configuration.EOLDelimiter : String.Empty); foreach (KeyValuePair <string, ChoJSONRecordFieldConfiguration> kvp in Configuration.RecordFieldConfigurationsDict) { fieldConfig = kvp.Value; fieldValue = null; fieldText = String.Empty; if (Configuration.PIDict != null) { Configuration.PIDict.TryGetValue(kvp.Key, out pi); } rec = GetDeclaringRecord(kvp.Value.DeclaringMember, rootRec); if (Configuration.ThrowAndStopOnMissingField) { if (Configuration.IsDynamicObject) { var dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (!dict.ContainsKey(kvp.Key)) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' JSON node.".FormatString(fieldConfig.FieldName)); } } else { if (pi == null) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' JSON node.".FormatString(fieldConfig.FieldName)); } } } try { if (Configuration.IsDynamicObject) { IDictionary <string, Object> dict = rec.ToDynamicObject() as IDictionary <string, Object>; fieldValue = dict[kvp.Key]; // dict.GetValue(kvp.Key, Configuration.FileHeaderConfiguration.IgnoreCase, Configuration.Culture); if (kvp.Value.FieldType == null) { if (fieldValue == null) { kvp.Value.FieldType = typeof(string); } else { kvp.Value.FieldType = fieldValue.GetType(); } } } else { if (pi != null) { fieldValue = ChoType.GetPropertyValue(rec, pi); if (kvp.Value.FieldType == null) { kvp.Value.FieldType = pi.PropertyType; } } else { kvp.Value.FieldType = typeof(string); } } //Discover default value, use it if null if (fieldValue == null) { if (fieldConfig.IsDefaultValueSpecified) { fieldValue = fieldConfig.DefaultValue; } } if (!RaiseBeforeRecordFieldWrite(rec, index, kvp.Key, ref fieldValue)) { return(false); } if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(fieldValue); } else { rec.GetNConvertMemberValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue, true); } if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.ObjectLevel) == ChoObjectValidationMode.MemberLevel) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } if (!RaiseAfterRecordFieldWrite(rec, index, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ref ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (Configuration.IsDynamicObject) { var dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (dict.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else if (dict.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } else if (pi != null) { if (rec.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (rec.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } else { var ex1 = new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); fieldValue = null; throw ex1; } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldWriteError(rec, index, kvp.Key, fieldText, ex)) { throw new ChoWriterException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } } else { throw new ChoWriterException("Failed to use '{0}' fallback value for '{1}' member.".FormatString(fieldValue, kvp.Key), innerEx); } } } bool isSimple = true; if (RaiseRecordFieldSerialize(rec, index, kvp.Key, ref fieldValue)) { if (isFirst) { msg.AppendFormat("{1}{0}", fieldValue.ToNString(), Configuration.Formatting == Formatting.Indented ? " " : String.Empty); } else { msg.AppendFormat(",{1}{2}{0}", fieldValue.ToNString(), Configuration.Formatting == Formatting.Indented ? Configuration.EOLDelimiter : String.Empty, Configuration.Formatting == Formatting.Indented ? " " : String.Empty); } } else { Type ft = fieldValue == null ? typeof(object) : fieldValue.GetType(); if (fieldValue == null) { fieldText = "null"; } else if (ft == typeof(string) || ft == typeof(char)) { fieldText = JsonConvert.SerializeObject(NormalizeFieldValue(kvp.Key, fieldValue.ToString(), kvp.Value.Size, kvp.Value.Truncate, false, GetFieldValueJustification(kvp.Value.FieldValueJustification, kvp.Value.FieldType), GetFillChar(kvp.Value.FillChar, kvp.Value.FieldType), false)); } else if (ft == typeof(DateTime)) { fieldText = JsonConvert.SerializeObject(fieldValue); } else if (ft.IsEnum) { fieldText = JsonConvert.SerializeObject(fieldValue); } else if (ft == typeof(ChoCurrency)) { fieldText = "\"{0}\"".FormatString(fieldValue.ToString()); } else if (ft == typeof(bool)) { fieldText = JsonConvert.SerializeObject(fieldValue); } else if (ft.IsNumeric()) { fieldText = fieldValue.ToString(); } else { isSimple = false; } if (isFirst) { msg.AppendFormat("{2}\"{0}\":{1}", fieldConfig.FieldName, isSimple ? " {0}".FormatString(fieldText) : Configuration.Formatting == Formatting.Indented ? SerializeObject(fieldValue, fieldConfig.UseJSONSerialization).Indent(1, " ") : SerializeObject(fieldValue, fieldConfig.UseJSONSerialization), Configuration.Formatting == Formatting.Indented ? " " : String.Empty); } else { msg.AppendFormat(",{2}{3}\"{0}\":{1}", fieldConfig.FieldName, isSimple ? " {0}".FormatString(fieldText) : Configuration.Formatting == Formatting.Indented ? SerializeObject(fieldValue, fieldConfig.UseJSONSerialization).Indent(1, " ") : SerializeObject(fieldValue, fieldConfig.UseJSONSerialization), Configuration.Formatting == Formatting.Indented ? Configuration.EOLDelimiter : String.Empty, Configuration.Formatting == Formatting.Indented ? " " : String.Empty); } } isFirst = false; } msg.AppendFormat("{0}}}", Configuration.Formatting == Formatting.Indented ? Configuration.EOLDelimiter : String.Empty); recText = msg.ToString(); return(true); }
private bool ToText(long index, object rec, out string recText) { if (typeof(IChoScalarObject).IsAssignableFrom(Configuration.RecordType)) { rec = Activator.CreateInstance(Configuration.RecordType, rec); } recText = null; if (rec == null) { if (Configuration.NullValueHandling == ChoNullValueHandling.Ignore) { return(false); } else if (Configuration.NullValueHandling == ChoNullValueHandling.Default) { rec = Activator.CreateInstance(Configuration.RecordType); } else { recText = @"<{0} xsi:nil=""true"" />".FormatString(Configuration.NodeName ).Indent(Configuration.Indent * 1, Configuration.IndentChar.ToString()); return(true); } } StringBuilder msg = new StringBuilder(); object fieldValue = null; string fieldText = null; ChoXmlRecordFieldConfiguration fieldConfig = null; if (Configuration.ColumnCountStrict) { CheckColumnsStrict(rec); } //bool firstColumn = true; PropertyInfo pi = null; bool isElementClosed = false; bool isElementStart = false; foreach (KeyValuePair <string, ChoXmlRecordFieldConfiguration> kvp in GetOrderedKVP()) { fieldConfig = kvp.Value; fieldValue = null; fieldText = String.Empty; if (Configuration.PIDict != null) { Configuration.PIDict.TryGetValue(kvp.Key, out pi); } if (Configuration.ThrowAndStopOnMissingField) { if (Configuration.IsDynamicObject) { var dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (!dict.ContainsKey(kvp.Key)) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' Xml node.".FormatString(fieldConfig.FieldName)); } } else { if (pi == null) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' Xml node.".FormatString(fieldConfig.FieldName)); } } } try { if (Configuration.IsDynamicObject) { IDictionary <string, Object> dict = rec.ToDynamicObject() as IDictionary <string, Object>; fieldValue = dict[kvp.Key]; // dict.GetValue(kvp.Key, Configuration.FileHeaderConfiguration.IgnoreCase, Configuration.Culture); if (kvp.Value.FieldType == null) { if (fieldValue == null) { kvp.Value.FieldType = typeof(string); } else { kvp.Value.FieldType = fieldValue.GetType(); } } } else { if (pi != null) { fieldValue = ChoType.GetPropertyValue(rec, pi); if (kvp.Value.FieldType == null) { kvp.Value.FieldType = pi.PropertyType; } } else { kvp.Value.FieldType = typeof(string); } } //Discover default value, use it if null if (fieldValue == null) { if (fieldConfig.IsDefaultValueSpecified) { fieldValue = fieldConfig.DefaultValue; } } if (!RaiseBeforeRecordFieldWrite(rec, index, kvp.Key, ref fieldValue)) { return(false); } if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(fieldValue); } else { rec.GetNConvertMemberValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue, true); } if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.ObjectLevel) == ChoObjectValidationMode.MemberLevel) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } if (!RaiseAfterRecordFieldWrite(rec, index, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (Configuration.IsDynamicObject) { var dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (dict.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else if (dict.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { throw new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); } } else if (pi != null) { if (rec.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (rec.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { throw new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); } } else { throw new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldWriteError(rec, index, kvp.Key, fieldText, ex)) { throw new ChoWriterException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } } else { throw new ChoWriterException("Failed to use '{0}' fallback value for '{1}' member.".FormatString(fieldValue, kvp.Key), innerEx); } } } if (fieldValue == null) { if (!fieldConfig.IsXmlAttribute && fieldConfig.IsNullable) { if (Configuration.RecordType == typeof(ChoScalarObject)) { if (!isElementStart) { msg.Append(@"<{0} xsi:nil=""true""".FormatString(Configuration.NodeName).Indent(Configuration.Indent, Configuration.IndentChar.ToString())); isElementStart = true; } if (!isElementClosed) { msg.AppendFormat(">{0}", Configuration.EOLDelimiter); isElementClosed = true; } } else { if (!isElementStart) { msg.Append("<{0}".FormatString(Configuration.NodeName).Indent(Configuration.Indent, Configuration.IndentChar.ToString())); isElementStart = true; } if (!isElementClosed) { msg.AppendFormat(">{0}", Configuration.EOLDelimiter); isElementClosed = true; } msg.Append(@"<{0} xsi:nil=""true"" />{1}".FormatString(fieldConfig.FieldName, Configuration.EOLDelimiter).Indent(Configuration.Indent * 2, Configuration.IndentChar.ToString())); } } else { if (Configuration.RecordType != typeof(ChoScalarObject)) { if (!isElementStart) { msg.Append("<{0}".FormatString(Configuration.NodeName).Indent(Configuration.Indent, Configuration.IndentChar.ToString())); isElementStart = true; } } //isElementClosed = true; fieldText = String.Empty; } } else { if (!isElementStart) { msg.Append("<{0}".FormatString(Configuration.NodeName).Indent(Configuration.Indent, Configuration.IndentChar.ToString())); isElementStart = true; } if (fieldValue.GetType().IsSimple()) { fieldText = fieldValue.ToString(); if (Configuration.RecordType == typeof(ChoScalarObject)) { if (fieldConfig.IsXmlAttribute) { msg.Append(@" {0}=""{1}""".FormatString(fieldConfig.FieldName, NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification, kvp.Value.FieldType), GetFillChar(kvp.Value.FillChar, kvp.Value.FieldType), false))); } else { if (!isElementClosed) { msg.AppendFormat(">{0}", Configuration.EOLDelimiter); isElementClosed = true; } msg.Append("{0}{1}".FormatString( NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification, kvp.Value.FieldType), GetFillChar(kvp.Value.FillChar, kvp.Value.FieldType), false), Configuration.EOLDelimiter).Indent(Configuration.Indent * 2, Configuration.IndentChar.ToString())); } } else if (fieldConfig.IsXmlAttribute) { msg.Append(@" {0}=""{1}""".FormatString(fieldConfig.FieldName, NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification, kvp.Value.FieldType), GetFillChar(kvp.Value.FillChar, kvp.Value.FieldType), false))); } else { if (!isElementClosed) { msg.AppendFormat(">{0}", Configuration.EOLDelimiter); isElementClosed = true; } msg.Append("<{0}>{1}</{0}>{2}".FormatString(fieldConfig.FieldName, NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification, kvp.Value.FieldType), GetFillChar(kvp.Value.FillChar, kvp.Value.FieldType), false), Configuration.EOLDelimiter).Indent(Configuration.Indent * 2, Configuration.IndentChar.ToString())); } } else { fieldText = ChoUtility.XmlSerialize(fieldValue); fieldText = _beginTagRegex.Replace(fieldText, delegate(Match thisMatch) { return("<{0}>".FormatString(fieldConfig.FieldName)); }); fieldText = _endTagRegex.Replace(fieldText, delegate(Match thisMatch) { return("</{0}>".FormatString(fieldConfig.FieldName)); }); if (!isElementClosed) { msg.AppendFormat(">{0}", Configuration.EOLDelimiter); isElementClosed = true; } msg.Append("{0}{1}".FormatString(fieldText, Configuration.EOLDelimiter).Indent(Configuration.Indent * 2, Configuration.IndentChar.ToString())); } } } if (!isElementClosed && msg.Length > 0) { msg.AppendFormat(">{0}", Configuration.EOLDelimiter); isElementClosed = true; } if (isElementStart) { msg.Append("</{0}>".FormatString(Configuration.NodeName).Indent(Configuration.Indent, Configuration.IndentChar.ToString())); isElementStart = false; } recText = msg.ToString(); return(true); }
private bool ToText(long index, object rec, out string recText) { recText = null; msg.Clear(); if (Configuration.ColumnCountStrict) { CheckColumnsStrict(rec); } bool firstColumn = true; PropertyInfo pi = null; foreach (KeyValuePair <string, ChoCSVRecordFieldConfiguration> kvp in Configuration.RecordFieldConfigurationsDict) { fieldConfig = kvp.Value; fieldValue = null; fieldText = String.Empty; if (Configuration.PIDict != null) { Configuration.PIDict.TryGetValue(kvp.Key, out pi); } dict = rec.ToDynamicObject() as IDictionary <string, Object>; if (Configuration.ThrowAndStopOnMissingField) { if (Configuration.IsDynamicObject) { if (!dict.ContainsKey(kvp.Key)) { if (fieldConfig.FieldPosition > dict.Count) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' CSV column.".FormatString(fieldConfig.FieldName)); } } } else { if (pi == null) { pi = Configuration.PIDict.Where(kvp1 => kvp.Value.FieldPosition == kvp.Value.FieldPosition).FirstOrDefault().Value; } if (pi == null) { throw new ChoMissingRecordFieldException("No matching property found in the object for '{0}' CSV column.".FormatString(fieldConfig.FieldName)); } } } try { if (Configuration.IsDynamicObject) { fieldValue = dict.ContainsKey(kvp.Key) ? dict[kvp.Key] : dict[dict.Keys.ElementAt(fieldConfig.FieldPosition - 1)]; // dict.GetValue(kvp.Key, Configuration.FileHeaderConfiguration.IgnoreCase, Configuration.Culture); if (kvp.Value.FieldType == null) { if (fieldValue == null) { kvp.Value.FieldType = typeof(string); } else { kvp.Value.FieldType = fieldValue.GetType(); } } } else { if (pi != null) { fieldValue = ChoType.GetPropertyValue(rec, pi); if (kvp.Value.FieldType == null) { kvp.Value.FieldType = pi.PropertyType; } } else { kvp.Value.FieldType = typeof(string); } } //Discover default value, use it if null if (fieldValue == null) { if (fieldConfig.IsDefaultValueSpecified) { fieldValue = fieldConfig.DefaultValue; } } if (!RaiseBeforeRecordFieldWrite(rec, index, kvp.Key, ref fieldValue)) { return(false); } rec.GetNConvertMemberValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue); if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.ObjectLevel) == ChoObjectValidationMode.MemberLevel) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } if (!RaiseAfterRecordFieldWrite(rec, index, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (Configuration.IsDynamicObject) { if (dict.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else if (dict.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { throw new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); } } else if (pi != null) { if (rec.GetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (rec.GetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode, fieldValue); } else { throw new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); } } else { throw new ChoWriterException($"Failed to write '{fieldValue}' value for '{fieldConfig.FieldName}' member.", ex); } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldWriteError(rec, index, kvp.Key, fieldText, ex)) { throw new ChoWriterException($"Failed to write '{fieldValue}' value of '{kvp.Key}' member.", ex); } } } else { throw new ChoWriterException("Failed to use '{0}' fallback value for '{1}' member.".FormatString(fieldValue, kvp.Key), innerEx); } } } if (fieldValue == null) { fieldText = String.Empty; } else { fieldText = fieldValue.ToString(); } if (firstColumn) { msg.Append(NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification), GetFillChar(kvp.Value.FillChar), false)); firstColumn = false; } else { msg.AppendFormat("{0}{1}", Configuration.Delimiter, NormalizeFieldValue(kvp.Key, fieldText, kvp.Value.Size, kvp.Value.Truncate, kvp.Value.QuoteField, GetFieldValueJustification(kvp.Value.FieldValueJustification), GetFillChar(kvp.Value.FillChar), false)); } } recText = msg.ToString(); return(true); }
public virtual void Validate() { string propName = null; object propValue = null; string propValueText = null; var results = new List <ValidationResult>(); foreach (PropertyInfo pi in ChoType.GetProperties(GetType())) { propName = pi.Name; results.Clear(); try { propValue = ChoType.GetPropertyValue(this, pi); } catch (Exception ex) { throw new ChoHL7Exception("Failed to validate '{0}' member.".FormatString(pi.FullName()), ex); } if (propValue is Array) { Array arr = (Array)propValue; if (arr.Length == 0 && ChoTypeDescriptor.GetPropetyAttributes <RequiredAttribute>(ChoTypeDescriptor.GetProperty <RequiredAttribute>(GetType(), pi.Name)).Any()) { throw new ChoHL7Exception("'{0}' member is required.".FormatString(pi.FullName())); } var maxCountAttr = ChoTypeDescriptor.GetPropetyAttributes <ChoHL7MaxCountAttribute>(ChoTypeDescriptor.GetProperty <ChoHL7MaxCountAttribute>(GetType(), pi.Name)).FirstOrDefault(); if (maxCountAttr != null) { if (arr.Length > maxCountAttr.Count) { throw new ChoHL7Exception("Incorrect number of elements found in '{0}' member. [Expected: {1}, Found: {2}]".FormatString(pi.FullName(), maxCountAttr.Count, arr.Length)); } } foreach (ChoHL7AbstractField arrValue in arr) { try { propValueText = arrValue.ToNString(); } catch (Exception ex) { throw new ChoHL7Exception("Failed to validate '{0}' member.".FormatString(pi.FullName()), ex); } pi.CheckRequired(propValueText); if (Configuration != null && !Configuration.DisableEnumChecks) { pi.CheckForValidEnumValue(propValueText); } var context = new ValidationContext(propValueText, null, null); context.MemberName = pi.Name; Validator.TryValidateValue(propValueText, context, results, ChoTypeDescriptor.GetPropetyAttributes <ValidationAttribute>(ChoTypeDescriptor.GetProperty <ValidationAttribute>(GetType(), pi.Name))); if (results.Count > 0) { throw new ChoHL7Exception("Failed to validate '{0}' member. {2}{1}".FormatString(pi.FullName(), ChoHL7Helper.ToString(results), Environment.NewLine)); } try { if (arrValue is ChoHL7AbstractField) { ((ChoHL7AbstractField)arrValue).Validate(); } } catch (Exception ex) { throw new ChoHL7Exception("Failed to validate '{0}' member.".FormatString(pi.FullName()), ex); } } } else { try { propValueText = propValue.ToNString(); } catch (Exception ex) { throw new ChoHL7Exception("Failed to validate '{0}' member.".FormatString(pi.FullName()), ex); } pi.CheckRequired(propValueText); if (Configuration != null && !Configuration.DisableEnumChecks) { pi.CheckForValidEnumValue(propValueText); } var context = new ValidationContext(propValueText, null, null); context.MemberName = pi.Name; Validator.TryValidateValue(propValueText, context, results, ChoTypeDescriptor.GetPropetyAttributes <ValidationAttribute>(ChoTypeDescriptor.GetProperty <ValidationAttribute>(GetType(), pi.Name))); if (results.Count > 0) { if (Configuration.DisableValueInErrorMessage) { throw new ChoHL7Exception("Failed to validate '{0}' member. {2}{1}".FormatString(pi.FullName(), ChoHL7Helper.ToString(results), Environment.NewLine)); } else { throw new ChoHL7Exception("Failed to validate '{0}' member [Value: {3}]. {2}{1}".FormatString(pi.FullName(), ChoHL7Helper.ToString(results), Environment.NewLine, propValueText)); } } try { if (propValue is ChoHL7AbstractField) { ((ChoHL7AbstractField)propValue).Validate(); } } catch (Exception ex) { throw new ChoHL7Exception("Failed to validate '{0}' member.".FormatString(pi.FullName()), ex); } } } }