public void It_should_use_specified_format(string culture, object value, string formattedValue) { var attribute = new FormatAttribute("--{0}--"); var formattingService = new ValueFormattingServiceStub(new CultureInfo(culture)); Assert.That(attribute.FormatValue(value, formattingService), Is.EqualTo($"--{formattedValue}--")); }
public void It_should_use_specified_format() { var attribute = new FormatAttribute("--{0}--"); Assert.That(attribute.Format(CultureInfo.InvariantCulture, 55.5), Is.EqualTo("--55.5--")); Assert.That(attribute.Format(new CultureInfo("PL"), 55.5), Is.EqualTo("--55,5--")); }
/// <summary> /// This methods implements 'ToString' for the object <code>obj</code> using reflection. /// <code>Filter</code> allows you to filter properties or fields: which properties are visibles. /// </summary> /// <param name="obj">Object.</param> /// <param name="filter">Filter properties: which properties are visibles.</param> /// <returns>ToString.</returns> public static string ReflectionToString(object obj, Func <string, bool> filter) { StringBuilder buff = new StringBuilder(); Type type = obj.GetType(); foreach (MemberInfo memberInfo in GetBottomUpPropertiesAndFieldsFor(type)) { if (filter(memberInfo.Name)) { object value = Utils.GetValue(obj, memberInfo); FormatAttribute formatAttr = memberInfo.GetCustomAttribute <FormatAttribute>(); string format = (formatAttr != null) ? formatAttr.Format : ""; buff.AppendFormat("{0} = {1}", memberInfo.Name, ToString(value, format)); SymbolAttribute attr = memberInfo.GetCustomAttribute <SymbolAttribute>(); if (attr != null && attr.SymbolProperty != null) { object symbol = GetValue(obj, attr.SymbolProperty); if (symbol != null) { buff.AppendFormat(" {0}", ToString(symbol, "")); } } buff.AppendLine(); } } return(buff.ToString()); }
internal static string TrimValue([CanBeNull] string value, [CanBeNull] FormatAttribute formatter) { if (string.IsNullOrEmpty(value)) { return(value); } return(((formatter == null) || formatter.Trim) ? value.Trim() : value); }
public void Ctor_FormatIsCorrect() { var expected = "ssn"; var target = new FormatAttribute(expected); target.Format.Should().Be(expected); }
public void Example_CanBeEmpty() { var target = new FormatAttribute("ssn"); target.Example = ""; target.Example.Should().BeEmpty(); }
public void FormatAttributeTest() { FormatAttribute attr = new FormatAttribute("pre-{0}-post"); string actual = (string)attr.GetValue("input"); string expected = "pre-input-post"; Assert.AreEqual(expected, actual); }
public void Example_CanBeSet() { var expected = "xxx-xx-xxxx"; var target = new FormatAttribute("ssn"); target.Example = expected; target.Example.Should().Be(expected); }
/// <summary> /// Returns the full argument name and parameters. Example: "cull <face>" /// </summary> /// <param name="type"></param> /// <returns></returns> public static string GetFormat(Type type) { FormatAttribute attr = TokenHelper.GetFormatAttribute(type); if (attr.Parameters?.Any() == true) { string parameters = string.Join(" ", attr.Parameters.Select(s => $"<{s}>")); return($"{attr.Argument} {parameters}"); } else { return(attr.Argument); } }
private short GetFormatId(FormatAttribute formatAttribute) { if (formatAttribute == null) { return(0); } var formatId = HSSFDataFormat.GetBuiltinFormat(formatAttribute.FormatString); if (formatId != -1) { return(formatId); } return(_hssfWorkbook.CreateDataFormat().GetFormat(formatAttribute.FormatString)); }
public static string FormatString(PropertyRoute route) { PropertyRoute simpleRoute = route.SimplifyToProperty(); FormatAttribute format = simpleRoute.PropertyInfo.GetCustomAttribute <FormatAttribute>(); if (format != null) { return(format.Format); } var pp = Validator.TryGetPropertyValidator(simpleRoute); if (pp != null) { DateTimePrecissionValidatorAttribute datetimePrecission = pp.Validators.OfType <DateTimePrecissionValidatorAttribute>().SingleOrDefaultEx(); if (datetimePrecission != null) { return(datetimePrecission.FormatString); } TimeSpanPrecissionValidatorAttribute timeSpanPrecission = pp.Validators.OfType <TimeSpanPrecissionValidatorAttribute>().SingleOrDefaultEx(); if (timeSpanPrecission != null) { return(timeSpanPrecission.FormatString); } DecimalsValidatorAttribute decimals = pp.Validators.OfType <DecimalsValidatorAttribute>().SingleOrDefaultEx(); if (decimals != null) { return("N" + decimals.DecimalPlaces); } StringCaseValidatorAttribute stringCase = pp.Validators.OfType <StringCaseValidatorAttribute>().SingleOrDefaultEx(); if (stringCase != null) { return(stringCase.TextCase == StringCase.Lowercase ? "L" : "U"); } } if (route.IsId() && IsNumber(PrimaryKey.Type(route.RootType))) { return("D"); } return(FormatString(route.Type)); }
/// <summary> /// 格式检查 /// </summary> /// <param name="formatAttribute"></param> /// <param name="value"></param> /// <returns></returns> public bool CheckIsError(FormatAttribute formatAttribute, object value) { //正则表达式 string regex = null; switch (formatAttribute.FormatEnum) { case FormatEnum.Email: regex = "^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$"; break; case FormatEnum.Phone: regex = @"^(\d{3,4}-)?\d{6,8}$"; break; case FormatEnum.MobilePhone: regex = @"^[1]+[3,5,8]+\d{9}"; break; case FormatEnum.ID: regex = @"(^\d{18}$)|(^\d{15}$)"; break; } //如果用户配置了正则表达式,以用户配置为准 if (string.IsNullOrEmpty(formatAttribute.Regex) == false) { regex = formatAttribute.Regex; } //如果正则为空则跳出 if (regex == null) { return(false); } Regex r = new Regex(regex); //如果匹配不上则添加异常 if (r.IsMatch(value.ToString()) == false) { return(true); } return(false); }
private void AppendCustomerFileData(string filePath, IEnumerable <WellCareResultPdfLog> customerLog) { var sb = new StringBuilder(); var members = (typeof(WellCareResultPdfLog)).GetMembers(); var sanitizer = new CSVSanitizer(); foreach (var customer in customerLog) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(customer, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else if (obj.GetType() == typeof(List <string>)) { values.Add(sanitizer.EscapeString(string.Join(",", ((List <string>)obj).ToArray()))); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } sb.Append(string.Join(",", values.ToArray()) + Environment.NewLine); } File.AppendAllText(filePath, sb.ToString()); }
//Todo : Move this function in a generic class. private void WriteCsv(IEnumerable <CustomAppointmentsBookedModel> modelData, string fileName) { if (File.Exists(fileName)) { File.Delete(fileName); } var fileWriter = new StreamWriter(fileName); try { var members = (typeof(CustomAppointmentsBookedModel)).GetMembers(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } var propertyName = memberInfo.Name; var isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } fileWriter.WriteLine(string.Join(",", header.ToArray())); var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } if (propInfo.PropertyType == typeof(IEnumerable <RescheduleApplointmentModel>)) { if (model.RescheduleInfo != null && model.RescheduleInfo.Any()) { var rescheduleInfoString = string.Empty; foreach (var rescheduleInfo in model.RescheduleInfo) { rescheduleInfoString += "Rescheduled By: " + rescheduleInfo.RescheduledBy + "\n"; rescheduleInfoString += "Reason: " + rescheduleInfo.Reason + "\n"; if (!string.IsNullOrEmpty(rescheduleInfo.SubReason)) { rescheduleInfoString += "SubReason: " + rescheduleInfo.SubReason + "\n"; } if (!string.IsNullOrEmpty(rescheduleInfo.Notes)) { rescheduleInfoString += "Notes: " + rescheduleInfo.Notes + "\n"; } rescheduleInfoString += "---------------------------\n"; } values.Add(sanitizer.EscapeString(rescheduleInfoString)); } else { values.Add("N/A"); } continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } fileWriter.WriteLine(string.Join(",", values.ToArray())); } _logger.Info("CSV File Export was succesful!"); } catch (Exception ex) { _logger.Error((string.Format("File Write: \n Error {0} \n Trace: {1} \n\n\n", ex.Message, ex.StackTrace))); } finally { fileWriter.Close(); fileWriter.Dispose(); } }
private string WriteCsvHospitalPartnerEvent(string fileName, IEnumerable <HospitalPartnerEventViewModel> modelData) { var csvFilePath = _tempMediaLocation.PhysicalPath + fileName; // using (var streamWriter = new StreamWriter(csvFilePath, false)) //{ var csvStringBuilder = new StringBuilder(); var members = (typeof(HospitalPartnerEventViewModel)).GetMembers(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <NotesViewModel>)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } header.Add("Notes"); csvStringBuilder.Append(string.Join(",", header.ToArray()) + Environment.NewLine); var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <NotesViewModel>)) { continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } if (model.Notes != null && model.Notes.Count() > 0) { var notesString = string.Empty; foreach (var notesViewModel in model.Notes) { notesString += "Updated On: " + (notesViewModel.EnteredOn.HasValue ? notesViewModel.EnteredOn.Value.ToShortDateString() : string.Empty) + "\n"; notesString += "Updated By: " + notesViewModel.CreatedByUser + "\n"; notesString += "Notes: " + notesViewModel.Note + "\n\n"; } values.Add(sanitizer.EscapeString(notesString)); } else { values.Add(string.Empty); } csvStringBuilder.Append(string.Join(",", values.ToArray()) + Environment.NewLine); } // streamWriter.Close(); //} var request = new GenericReportRequest { CsvFilePath = csvFilePath, Model = csvStringBuilder.ToString() }; var isGenerated = GetResponse(request, RequestSubcriberChannelNames.GenerateHospitalPartnerEventReportQueue, RequestSubcriberChannelNames.GenerateHospitalPartnerEventReportChannel); if (!isGenerated) { return("CSV File Export failed!"); } DownloadZipFile(_tempMediaLocation, fileName); return("CSV File Export was succesful!"); }
//private string WriteCsv<T>(string fileName, CSVExporter<T> exporter, IEnumerable<T> modelData) //{ // var csvFilePath = _tempMediaLocation.PhysicalPath + fileName; // using (var streamWriter = new StreamWriter(csvFilePath, false)) // { // streamWriter.Write(exporter.Header + Environment.NewLine); // foreach (string line in exporter.ExportObjects(modelData)) // { // streamWriter.Write(line + Environment.NewLine); // } // streamWriter.Close(); // } // DownloadZipFile(_tempMediaLocation, fileName); // return "CSV File Export was succesful!"; //} private string WriteCsvHospitalPartnerCustomer(string fileName, IEnumerable <HospitalPartnerCustomerViewModel> modelData) { var csvFilePath = _tempMediaLocation.PhysicalPath + fileName; //using (var streamWriter = new StreamWriter(csvFilePath, false)) //{ var csvStringBuilder = new StringBuilder(); var members = (typeof(HospitalPartnerCustomerViewModel)).GetMembers(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <OrderedPair <long, string> >) || propInfo.PropertyType == typeof(IEnumerable <HospitalPartnerCustomerActivityViewModel>)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } var tests = _testRepository.GetRecordableTests(); header.AddRange(tests.Select(test => test.Name)); header.Add("Activity"); header.Add(HealthAssessmentQuestionLabel.PrimaryCare.GetDescription()); header.Add(HealthAssessmentQuestionLabel.MammogramProstateScreening.GetDescription()); header.Add(HealthAssessmentQuestionLabel.Colonoscopy.GetDescription()); header.Add(HealthAssessmentQuestionLabel.Cancer.GetDescription()); header.Add(HealthAssessmentQuestionLabel.WeightBariatric.GetDescription()); csvStringBuilder.Append(string.Join(",", header.ToArray()) + Environment.NewLine); var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <OrderedPair <long, string> >) || propInfo.PropertyType == typeof(IEnumerable <HospitalPartnerCustomerActivityViewModel>)) { continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } foreach (var test in tests) { if (model.TestSummary != null && model.TestSummary.Count() > 0) { var summaryFinding = model.TestSummary.Where(ts => ts.FirstValue == test.Id).Select(ts => ts.SecondValue). FirstOrDefault(); values.Add(summaryFinding); } else { values.Add(string.Empty); } } if (model.Activities != null && model.Activities.Count() > 0) { var activitySummary = string.Empty; foreach (var activity in model.Activities) { activitySummary += "Status: " + activity.Status + "\n"; activitySummary += "Outcome: " + activity.Outcome + "\n"; activitySummary += "Updated On: " + activity.UpdateOn.ToShortDateString() + "\n"; activitySummary += "Updated By: " + activity.UpdatedBy + "\n"; activitySummary += "Notes: " + activity.Notes + "\n\n"; } values.Add(sanitizer.EscapeString(activitySummary)); } else { values.Add(string.Empty); } values.Add(model.PrimaryCare); values.Add(model.MammogramProstateScreening); values.Add(model.Colonoscopy); values.Add(model.Cancer); values.Add(model.WeightBariatric); csvStringBuilder.Append(string.Join(",", values.ToArray()) + Environment.NewLine); } // streamWriter.Close(); //} var request = new GenericReportRequest { CsvFilePath = csvFilePath, Model = csvStringBuilder.ToString() }; var isGenerated = GetResponse(request, RequestSubcriberChannelNames.GenerateHospitalPartnerCustomerReportQueue, RequestSubcriberChannelNames.GenerateHospitalPartnerCustomerReportChannel); if (!isGenerated) { return("CSV File Export failed!"); } DownloadZipFile(_tempMediaLocation, fileName); return("CSV File Export was succesful!"); }
private void WriteCsv(IEnumerable <UniversalProviderViewModel> collection, string fileName) { var fs = new FileStream(fileName, FileMode.Append); var streamWriter = new StreamWriter(fs); try { var members = (typeof(UniversalProviderViewModel)).GetMembers(); foreach (var model in collection) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(obj.ToString());//EscapeString(obj.ToString()) } } streamWriter.Write(string.Join(Delimiter, values.ToArray()) + Environment.NewLine); } } catch (Exception ex) { _logger.Error("While creating CSV File : " + ex.Message + "\n\t" + ex.StackTrace + "\n\n"); } finally { streamWriter.Close(); streamWriter.Dispose(); fs.Close(); fs.Dispose(); } }
/// <summary> /// Applies attribute configurations to the map. /// </summary> /// <param name="memberMap">The member map.</param> protected virtual void ApplyAttributes(MemberMap memberMap) { var member = memberMap.Data.Member; //if( member.GetCustomAttribute( typeof( IndexAttribute ) ) is IndexAttribute indexAttribute ) IndexAttribute indexAttribute = member.GetCustomAttributes(typeof(IndexAttribute), false).FirstOrDefault() as IndexAttribute; if (indexAttribute != null) { memberMap.Data.Index = indexAttribute.Index; memberMap.Data.IndexEnd = indexAttribute.IndexEnd; memberMap.Data.IsIndexSet = true; } //if( member.GetCustomAttribute( typeof( NameAttribute ) ) is NameAttribute nameAttribute ) NameAttribute nameAttribute = member.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault() as NameAttribute; if (nameAttribute != null) { memberMap.Data.Names.Clear(); memberMap.Data.Names.AddRange(nameAttribute.Names); memberMap.Data.IsNameSet = true; } //if( member.GetCustomAttribute( typeof( NameIndexAttribute ) ) is NameIndexAttribute nameIndexAttribute ) NameIndexAttribute nameIndexAttribute = member.GetCustomAttributes(typeof(NameIndexAttribute), false).FirstOrDefault() as NameIndexAttribute; if (nameIndexAttribute != null) { memberMap.Data.NameIndex = nameIndexAttribute.NameIndex; } //if( member.GetCustomAttribute( typeof( IgnoreAttribute ) ) is IgnoreAttribute ignoreAttribute ) IgnoreAttribute ignoreAttribute = member.GetCustomAttributes(typeof(IgnoreAttribute), false).FirstOrDefault() as IgnoreAttribute; if (ignoreAttribute != null) { memberMap.Data.Ignore = true; } //if( member.GetCustomAttribute( typeof( DefaultAttribute ) ) is DefaultAttribute defaultAttribute ) DefaultAttribute defaultAttribute = member.GetCustomAttributes(typeof(DefaultAttribute), false).FirstOrDefault() as DefaultAttribute; if (defaultAttribute != null) { memberMap.Data.Default = defaultAttribute.Default; memberMap.Data.IsDefaultSet = true; } //if( member.GetCustomAttribute( typeof( ConstantAttribute ) ) is ConstantAttribute constantAttribute ) ConstantAttribute constantAttribute = member.GetCustomAttributes(typeof(ConstantAttribute), false).FirstOrDefault() as ConstantAttribute; if (constantAttribute != null) { memberMap.Data.Constant = constantAttribute.Constant; memberMap.Data.IsConstantSet = true; } //if( member.GetCustomAttribute( typeof( TypeConverterAttribute ) ) is TypeConverterAttribute typeConverterAttribute ) TypeConverterAttribute typeConverterAttribute = member.GetCustomAttributes(typeof(TypeConverterAttribute), false).FirstOrDefault() as TypeConverterAttribute; if (typeConverterAttribute != null) { memberMap.Data.TypeConverter = typeConverterAttribute.TypeConverter; } //if( member.GetCustomAttribute( typeof( CultureInfoAttribute ) ) is CultureInfoAttribute cultureInfoAttribute ) CultureInfoAttribute cultureInfoAttribute = member.GetCustomAttributes(typeof(CultureInfoAttribute), false).FirstOrDefault() as CultureInfoAttribute; if (cultureInfoAttribute != null) { memberMap.Data.TypeConverterOptions.CultureInfo = cultureInfoAttribute.CultureInfo; } //if( member.GetCustomAttribute( typeof( DateTimeStylesAttribute ) ) is DateTimeStylesAttribute dateTimeStylesAttribute ) DateTimeStylesAttribute dateTimeStylesAttribute = member.GetCustomAttributes(typeof(DateTimeStylesAttribute), false).FirstOrDefault() as DateTimeStylesAttribute; if (dateTimeStylesAttribute != null) { memberMap.Data.TypeConverterOptions.DateTimeStyle = dateTimeStylesAttribute.DateTimeStyles; } //if( member.GetCustomAttribute( typeof( NumberStylesAttribute ) ) is NumberStylesAttribute numberStylesAttribute ) NumberStylesAttribute numberStylesAttribute = member.GetCustomAttributes(typeof(NumberStylesAttribute), false).FirstOrDefault() as NumberStylesAttribute; if (numberStylesAttribute != null) { memberMap.Data.TypeConverterOptions.NumberStyle = numberStylesAttribute.NumberStyles; } FormatAttribute formatAttribute = member.GetCustomAttributes(typeof(FormatAttribute), false).FirstOrDefault() as FormatAttribute; if (formatAttribute != null) { memberMap.Data.TypeConverterOptions.Formats = formatAttribute.Formats; } BooleanTrueValuesAttribute booleanTrueValuesAttribute = member.GetCustomAttributes(typeof(BooleanTrueValuesAttribute), false).FirstOrDefault() as BooleanTrueValuesAttribute; if (booleanTrueValuesAttribute != null) { memberMap.Data.TypeConverterOptions.BooleanTrueValues.Clear(); memberMap.Data.TypeConverterOptions.BooleanTrueValues.AddRange(booleanTrueValuesAttribute.TrueValues); } BooleanFalseValuesAttribute booleanFalseValuesAttribute = member.GetCustomAttributes(typeof(BooleanFalseValuesAttribute), false).FirstOrDefault() as BooleanFalseValuesAttribute; if (booleanFalseValuesAttribute != null) { memberMap.Data.TypeConverterOptions.BooleanFalseValues.Clear(); memberMap.Data.TypeConverterOptions.BooleanFalseValues.AddRange(booleanFalseValuesAttribute.FalseValues); } NullValuesAttribute nullValuesAttribute = member.GetCustomAttributes(typeof(NullValuesAttribute), false).FirstOrDefault() as NullValuesAttribute; if (nullValuesAttribute != null) { memberMap.Data.TypeConverterOptions.NullValues.Clear(); memberMap.Data.TypeConverterOptions.NullValues.AddRange(nullValuesAttribute.NullValues); } }
private string WriteCsvForCustomerExport(string fileName, IEnumerable <CustomerExportModel> modelData, long userId) { var csvFilePath = ExportableMediaLocation.PhysicalPath + fileName; var csvStringBuilder = new StringBuilder(); var members = (typeof(CustomerExportModel)).GetMembers(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } csvStringBuilder.Append(string.Join(",", header.ToArray()) + Environment.NewLine); var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } if (propInfo.PropertyType == typeof(IEnumerable <OrderedPair <string, string> >)) { string additionalFieldsString; if (model.AdditionalFields == null || !model.AdditionalFields.Any()) { additionalFieldsString = "N/A"; } else { additionalFieldsString = model.AdditionalFields.Aggregate(string.Empty, (current, item) => current + item.FirstValue + ": " + item.SecondValue + "\n"); } values.Add(sanitizer.EscapeString(additionalFieldsString)); continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } csvStringBuilder.Append(string.Join(",", values.ToArray()) + Environment.NewLine); } var request = new GenericReportRequest { CsvFilePath = csvFilePath, Model = csvStringBuilder.ToString() }; var isGenerated = _baseReportService.GetResponse(request); if (!isGenerated) { return("CSV File Export failed!"); } return(_baseReportService.DownloadZipFile(ExportableMediaLocation, fileName, userId, Logger)); }
private string WriteCsvAppointmentBooked(string fileName, IEnumerable <AppointmentsBookedModel> modelData, long userId) { var csvFilePath = ExportableMediaLocation.PhysicalPath + fileName; var csvStringBuilder = new StringBuilder(); var members = (typeof(AppointmentsBookedModel)).GetMembers(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <OrderedPair <string, string> >)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } header.Add("Additional Fields"); csvStringBuilder.Append(string.Join(",", header.ToArray()) + Environment.NewLine); var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } if (propInfo.PropertyType == typeof(IEnumerable <string>)) { if (model.ShippingOptions != null && model.ShippingOptions.Count() > 0) { var shippingOptions = string.Join(", \n", model.ShippingOptions.ToArray()); values.Add(sanitizer.EscapeString(shippingOptions)); } else { values.Add(string.Empty); } continue; } if (propInfo.PropertyType == typeof(IEnumerable <RescheduleApplointmentModel>) || propInfo.PropertyType == typeof(IEnumerable <OrderedPair <string, string> >)) { if (model.RescheduleInfo != null && model.RescheduleInfo.Any()) { var rescheduleInfoString = string.Empty; foreach (var rescheduleInfo in model.RescheduleInfo) { rescheduleInfoString += "Rescheduled By: " + rescheduleInfo.RescheduledBy + "\n"; rescheduleInfoString += "Reason: " + rescheduleInfo.Reason + "\n"; if (!string.IsNullOrEmpty(rescheduleInfo.SubReason)) { rescheduleInfoString += "SubReason: " + rescheduleInfo.SubReason + "\n"; } if (!string.IsNullOrEmpty(rescheduleInfo.Notes)) { rescheduleInfoString += "Notes: " + rescheduleInfo.Notes + "\n"; } rescheduleInfoString += "---------------------------\n"; } values.Add(sanitizer.EscapeString(rescheduleInfoString)); } else { values.Add("N/A"); } continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (memberInfo.Name == "Zip") { values.Add("=" + sanitizer.EscapeString(obj.ToString())); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } if (model.AdditionalFields != null && model.AdditionalFields.Any()) { string additionFiledString = model.AdditionalFields.Aggregate(string.Empty, (current, item) => current + item.FirstValue + ": " + item.SecondValue + "\n"); values.Add(sanitizer.EscapeString(additionFiledString)); } else { values.Add(string.Empty); } csvStringBuilder.Append(string.Join(",", values.ToArray()) + Environment.NewLine); } var request = new GenericReportRequest { CsvFilePath = csvFilePath, Model = csvStringBuilder.ToString() }; var isGenerated = _baseReportService.GetResponse(request); if (!isGenerated) { return("CSV File Export failed!"); } return(_baseReportService.DownloadZipFile(ExportableMediaLocation, fileName, userId, Logger)); }
/// <summary> /// 验证 /// </summary> /// <param name="entity"></param> /// <returns></returns> public override List <ValidationResult> Validation(TEntity entity) { List <ValidationResult> result = new List <ValidationResult>(); List <string> disableAttributes = GetDisableAttributes(); Dictionary <string, BaseAttribute> enableAttributes = GetEnableAttributes(); //遍历属性 foreach (PropertyInfo prop in PropertyHelper.GetPropertys <TEntity>()) { //获取属性 FormatAttribute formatAttribute = prop.GetCustomAttribute <FormatAttribute>(); if (formatAttribute == null && enableAttributes != null) { //实体没有标识必填特性,且没有设置启用必填特性,则跳出 if (enableAttributes.Keys.Contains(prop.Name) == true) { formatAttribute = enableAttributes[prop.Name] as FormatAttribute; } } //为空则跳出 if (formatAttribute == null) { continue; } //如果是禁用特性则跳出 if (disableAttributes != null && disableAttributes.Contains(prop.Name)) { continue; } //获取属性值 object value = prop.GetValueExt(entity); if (value == null) { result.Add(new ValidationResult() { PropertyName = prop.Name, ErrorMessage = formatAttribute.ErrorMessage }); continue; } //正则表达式 string regex = null; switch (formatAttribute.FormatEnum) { case FormatEnum.Email: regex = "^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$"; break; case FormatEnum.Phone: regex = @"^(\d{3,4}-)?\d{6,8}$"; break; case FormatEnum.MobilePhone: regex = @"^[1]+[3,5,8]+\d{9}"; break; case FormatEnum.ID: regex = @"(^\d{18}$)|(^\d{15}$)"; break; } //如果用户配置了正则表达式,以用户配置为准 if (string.IsNullOrEmpty(formatAttribute.Regex) == false) { regex = formatAttribute.Regex; } //如果正则为空则跳出 if (regex == null) { continue; } Regex r = new Regex(regex); //如果匹配不上则添加异常 if (r.IsMatch(value.ToString()) == false) { result.Add(new ValidationResult() { PropertyName = prop.Name, ErrorMessage = formatAttribute.ErrorMessage }); } } return(result); }
public void Write <T>(IEnumerable <T> modelData, string folderLocation, string filePath) { var csvStringBuilder = new StringBuilder(); var members = (typeof(T)).GetMembers(); if (!File.Exists(folderLocation + "\\" + filePath)) { var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } csvStringBuilder.Append(string.Join("|", header.ToArray()) + Environment.NewLine); } foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo == null) { continue; } if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(obj.ToString()); } } csvStringBuilder.Append(string.Join("|", values.ToArray()) + Environment.NewLine); } SaveToFile(csvStringBuilder.ToString(), filePath, folderLocation); }
private void CreateCrossWalkFile(string csvFilePath, IEnumerable <AnthemPdfCrossWalkVeiwModel> modelData) { try { if (modelData.IsNullOrEmpty()) { _logger.Info("No Data found to generate crosswalk file "); return; } try { DirectoryOperationsHelper.DeleteFiles(csvFilePath, "CrosswalkFile_*.csv"); } catch (Exception exception) { _logger.Error(" While deleting old files"); _logger.Error("message: " + exception); _logger.Error("stack Trace: " + exception.StackTrace); } DirectoryOperationsHelper.CreateDirectoryIfNotExist(_crosswalkFilePath); DirectoryOperationsHelper.CreateDirectoryIfNotExist(csvFilePath); var filePath = Path.Combine(_crosswalkFilePath, "CrosswalkFile_" + _crosswalkFileYear + ".csv"); bool createHeaderRow = !DirectoryOperationsHelper.IsFileExist(filePath); _logger.Info("File Path: " + filePath); if (createHeaderRow) { _logger.Info("Header info being created"); } var csvFileName = Path.Combine(csvFilePath, "CrosswalkFile_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv"); using (var streamWriter = new StreamWriter(filePath, append: !createHeaderRow)) { var members = (typeof(AnthemPdfCrossWalkVeiwModel)).GetMembers(); if (createHeaderRow) { var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } streamWriter.Write(string.Join(",", header.ToArray()) + Environment.NewLine); } var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } streamWriter.Write(string.Join(",", values.ToArray()) + Environment.NewLine); } streamWriter.Close(); _logger.Info("crosswalk .csv has been created at following location: "); _logger.Info(filePath); if (DirectoryOperationsHelper.IsFileExist(filePath)) { DirectoryOperationsHelper.DeleteFileIfExist(csvFileName); DirectoryOperationsHelper.Copy(filePath, csvFileName); } } } catch (Exception ex) { _logger.Error("While Generating crosswalk file: message " + ex.Message + " stack trace: " + ex.StackTrace); } }
private void UpdateFailedRecords(string filePath, IEnumerable <BloodTestResultParserLog> failedCustomers) { var sb = new StringBuilder(); var members = (typeof(BloodTestResultParserLog)).GetMembers(); var sanitizer = new CSVSanitizer(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo == null) { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } sb.Append(string.Join(",", header.ToArray()) + Environment.NewLine); foreach (var customer in failedCustomers) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo == null) { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(customer, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } sb.Append(string.Join(",", values.ToArray()) + Environment.NewLine); } File.AppendAllText(filePath, sb.ToString()); }
private void WriteCsv(HouseCallHafResultExportModel model, string fileName) { var fs = new FileStream(fileName, FileMode.Append); var streamWriter = new StreamWriter(fs); try { var members = (typeof(HouseCallHafResultExportModel)).GetMembers(); var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <OrderedPair <long, string> >)) { foreach (var question in HouseCallHafResultExportHelper.Questions) { if (model.HealthAssesmentAnswer != null && model.HealthAssesmentAnswer.Any()) { var answer = model.HealthAssesmentAnswer.Where(a => a.FirstValue == question.FirstValue).FirstOrDefault(); values.Add(EscapeString(answer.SecondValue)); } else { values.Add(string.Empty); } } continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(EscapeString(formatter.ToString(obj))); } else { values.Add(EscapeString(obj.ToString())); } } streamWriter.Write(string.Join(HouseCallHafResultExportHelper.Delimiter, values.ToArray()) + Environment.NewLine); } catch (Exception ex) { _logger.Error("While creating CSV File : " + ex.Message + "\n\t" + ex.StackTrace + "\n\n"); } finally { streamWriter.Close(); streamWriter.Dispose(); fs.Close(); fs.Dispose(); } }
private bool GenerateOutreachCallReportCsv(IEnumerable <HourlyOutreachCallReportModel> modelData, string csvFilePath) { var csvStringBuilder = new StringBuilder(); var members = (typeof(HourlyOutreachCallReportModel)).GetMembers(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <CallCenterNotes>)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } header.Add("Disposition Notes"); csvStringBuilder.Append(string.Join(",", header.ToArray()) + Environment.NewLine); var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <CallCenterNotes>)) { continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } if (model.Notes != null && model.Notes.Count() > 0) { var notesString = model.Notes.Aggregate("", (current, note) => current + ("[ " + note.DateCreated.ToShortDateString() + " ] - Notes: " + note.Notes + "\n")); values.Add(sanitizer.EscapeString(notesString)); } else { values.Add("N/A"); } csvStringBuilder.Append(string.Join(",", values.ToArray()) + Environment.NewLine); } var request = new GenericReportRequest { CsvFilePath = csvFilePath, Model = csvStringBuilder.ToString() }; var isGenerated = _baseReportService.GetResponse(request); return(isGenerated); }
public static CSVExporter <TV> GetCsvExporter <TV>() where TV : ViewModelBase { var members = (typeof(TV)).GetMembers(); var exporter = new CSVExporter <TV>(); var check = new Func <string, FormatAttribute, Func <TV, string> >((propName, formatter) => ((c) => { var obj = c.GetType().GetProperty(propName).GetValue(c, null); if (obj == null) { return(string.Empty); } if (formatter != null) { return(formatter.ToString(obj)); } return(obj.ToString()); })); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } exporter.AddColumn(propertyName, check(memberInfo.Name, formatter)); } return(exporter); }
public AbstractMemberData(Logger logger, MemberInfo info) { this.logger = logger; this.fa = (FormatAttribute)info.GetCustomAttribute(typeof(FormatAttribute), false); }
private string WriteCsv(string csvFilePath, IEnumerable <CustomerInfo> modelData) { using (var streamWriter = new StreamWriter(csvFilePath, false)) { var members = (typeof(CustomerInfo)).GetMembers(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } streamWriter.Write(string.Join(",", header.ToArray()) + Environment.NewLine); var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } if (propInfo.PropertyType == typeof(IEnumerable <string>)) { values.Add(string.Empty); continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } streamWriter.Write(string.Join(",", values.ToArray()) + Environment.NewLine); } streamWriter.Close(); } return("CSV File Export was succesful!"); }
private void WriteCsv(IEnumerable <HealthPlanGiftCertificateReportViewModel> modelData, string fileName) { _logger.Info("Writing CSV file " + fileName); if (File.Exists(fileName)) { File.Delete(fileName); } var fileWriter = new StreamWriter(fileName); try { var members = (typeof(HealthPlanGiftCertificateReportViewModel)).GetMembers(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } var propertyName = memberInfo.Name; var isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } fileWriter.WriteLine(string.Join(",", header.ToArray())); var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel)) { continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } fileWriter.WriteLine(string.Join(",", values.ToArray())); } _logger.Info("CSV File Export was succesful!"); } catch (Exception ex) { _logger.Error((string.Format("File Write: \n Error {0} \n Trace: {1} \n\n\n", ex.Message, ex.StackTrace))); } finally { fileWriter.Close(); fileWriter.Dispose(); } }