public void Scribe_Write_List_Of_Classes_With_Attributes_Writes_Values() { var expected = "54321 John Smith 8765309 Jenny Smith "; var fieldFormatter = new FieldFormatter(); var merchantA = new Merchant() { MerchantFirstName = "John", MerchantLastName = "Smith", MerchantId = "54321" }; var merchantB = new Merchant() { MerchantFirstName = "Jenny", MerchantLastName = "Smith", MerchantId = "8765309" }; IList <Merchant> merchants = new List <Merchant>() { merchantA, merchantB }; using (var writer = new StringWriter()) { IScribe scribe = new Scribe(writer, fieldFormatter); scribe.Write(merchants); var actual = writer.ToString(); Assert.Equal(expected, actual); } }
public void Scribe_Write_Uses_FixedLengthFileAttribute_To_Add_Line_Endings() { var expected = "12345000000000000000" + Environment.NewLine + "BusinessName " + Environment.NewLine + "5555555555 " + Environment.NewLine + "45678900000000000000" + Environment.NewLine + "00000000000000010000" + Environment.NewLine; var fieldFormatter = new FieldFormatter(); var business = new SimpleBusinessWithFixedLengthFileAttribute() { BusinessId = 12345, BusinessName = "BusinessName", BusinessTelephoneNumber = "5555555555", TaxId = "456789", CashOnHand = "10000" }; using (var writer = new StringWriter()) { IScribe scribe = new Scribe(writer, fieldFormatter); scribe.Write(business); var actual = writer.ToString(); Assert.Equal(expected, actual); } }
public void Scribe_Write_NULL_Values_On_Properties_Resolves_To_Empty_String() { var expected = string.Empty.PadLeft(80); var fieldFormatter = new FieldFormatter(); var merchantA = new Merchant() { MerchantFirstName = null, MerchantLastName = null, MerchantId = null }; var merchantB = new Merchant() { MerchantFirstName = null, MerchantLastName = null, MerchantId = null }; IList <Merchant> merchants = new List <Merchant>() { merchantA, merchantB }; using (var writer = new StringWriter()) { IScribe scribe = new Scribe(writer, fieldFormatter); scribe.Write(merchants); var actual = writer.ToString(); Assert.Equal(expected, actual); } }
private static (List <IFormatter> fieldFormatters, List <IFormatter> tagFormatters) CreateFormatters(Type type, DiagnosticListenerOptions options) { var fieldFormatters = new List <IFormatter>(); var tagFormatters = new List <IFormatter>(); foreach (var property in type.GetProperties().Where(p => p.CanRead)) { if (CheckCustomFormatters(options.CustomFieldFormatters, options.CustomTagFormatters, property, fieldFormatters, tagFormatters)) { continue; } if (FieldFormatter.IsFieldType(property.PropertyType)) { var formatter = FieldFormatter.TryCreate(property, options.FieldNameFormatter ?? NameFixer.Identity); if (formatter != null) { fieldFormatters.Add(formatter); } } else if (TagFormatter.IsTagType(property.PropertyType)) { var tagFormatter = TagFormatter.TryCreate(property, options.TagNameFormatter ?? NameFixer.Identity); if (tagFormatter != null) { tagFormatters.Add(tagFormatter); } } } return(fieldFormatters, tagFormatters); }
public void Scribe_Write_Performance_Test() { var business = new SimpleBusiness() { BusinessId = 12345, BusinessName = "BusinessName", BusinessTelephoneNumber = "5555555555", TaxId = "456789", CashOnHand = "10000" }; var businessList = new List <SimpleBusiness>(); for (int i = 0; i < 1000000000; i++) { businessList.Add(business); } using (var writer = new StringWriter()) { var stopwatch = new Stopwatch(); IFieldFormatter fieldFormatter = new FieldFormatter(); IScribe scribe = new Scribe(writer, fieldFormatter); stopwatch.Start(); scribe.Write(businessList); stopwatch.Stop(); var timeToRun = stopwatch.Elapsed.TotalSeconds; Assert.True(timeToRun <= 15); } }
private static (List <IFormatter> fieldFormatters, List <IFormatter> tagFormatters) CreateFormatters(Type type, CustomDict customFieldFormatters, CustomDict customTagFormatters) { var fieldFormatters = new List <IFormatter>(); var tagFormatters = new List <IFormatter>(); foreach (var property in type.GetProperties().Where(p => p.CanRead)) { if (CheckCustomFormatters(customFieldFormatters, customTagFormatters, property, fieldFormatters, tagFormatters)) { continue; } if (FieldFormatter.IsFieldType(property.PropertyType)) { var formatter = FieldFormatter.TryCreate(property); if (formatter != null) { fieldFormatters.Add(formatter); } } else if (TagFormatter.IsTagType(property.PropertyType)) { var tagFormatter = TagFormatter.TryCreate(property); if (tagFormatter != null) { tagFormatters.Add(tagFormatter); } } } return(fieldFormatters, tagFormatters); }
public void FormatTest() { FieldInfo fieldInfo = default; string actual = FieldFormatter.Format(fieldInfo); string expected = default; Assert.That(actual, Is.EqualTo(expected)); Assert.Fail("autogenerated"); }
public void FormatsDecimalCorrectly() { var args = new { foo = 42m }; var formatter = FieldFormatter.TryCreate(args.GetType().GetProperty("foo"), NameFixer.Identity); var buffer = new byte[64]; Assert.True(formatter.TryWrite(args, buffer.AsSpan(), false, out int written)); Assert.Equal(6, written); var text = Encoding.UTF8.GetString(buffer, 0, written); Assert.Equal("foo=42", text); }
public void FormatsUInt32(Func <string, string> formatter) { var obj = new { foo = 42u }; var property = obj.GetType().GetProperty("foo"); var target = FieldFormatter.TryCreate(property, formatter); var bytes = new byte[7]; var span = bytes.AsSpan(); Assert.True(target.TryWrite(obj, span, false, out int bytesWritten)); Assert.Equal(7, bytesWritten); Assert.Equal(Encoding.UTF8.GetBytes($"{formatter("foo")}=42i"), bytes); }
public static string Serialize(InfluxPoint point) { var tags = point.Tags; var fields = point.Fields; var allTags = string.Join(",", TagsFormatter.Format(tags)); var allFields = string.Join(",", FieldFormatter.Format(fields)); var tagsPart = allTags.Length > 0 ? $",{allTags}" : allTags; var measurement = KeyFormatter.Format(point.Measurement); return($"{measurement}{tagsPart} {allFields} {FieldValueFormatter.FormatTimestamp(point.UtcTimestamp)}".Trim()); }
public void AddField() { FieldFormatterCollection fieldFormatters = new FieldFormatterCollection(); fieldFormatters.Added += new FieldFormatterAddedEventHandler( OnFieldFormattersAdded); _removedEventArgs = null; fieldFormatters.Removed += new FieldFormatterRemovedEventHandler( OnFieldFormattersRemoved); // Add field formatters. for (int i = _fieldFormatters.Length - 1; i >= 0; i--) { _addedEventArgs = null; fieldFormatters.Add(( FieldFormatter)(_fieldFormatters[i])); Assert.IsNull(_removedEventArgs); Assert.IsNotNull(_addedEventArgs); Assert.IsTrue(_addedEventArgs.FieldFormatter == ( FieldFormatter)(_fieldFormatters[i])); } // Check valid field formatters. for (int i = 0; i < _exists.Length; i++) { Assert.IsNotNull(fieldFormatters[_exists[i]]); Assert.IsTrue(fieldFormatters.Contains(_exists[i])); } // Check invalid field formatters. for (int i = 0; i < _notExists.Length; i++) { Assert.IsNull(fieldFormatters[_notExists[i]]); Assert.IsFalse(fieldFormatters.Contains(_notExists[i])); } Assert.IsTrue(fieldFormatters.MaximumFieldFormatterNumber == 64); Assert.IsTrue(fieldFormatters.Count == _fieldFormatters.Length); // Substitute one field formatter. FieldFormatter toReplace = fieldFormatters[_exists[0]]; FieldFormatter toAdd = new StringFieldFormatter(_exists[0], new FixedLengthManager(20), StringEncoder.GetInstance()); _addedEventArgs = null; fieldFormatters.Add(toAdd); Assert.IsNotNull(_removedEventArgs); Assert.IsNotNull(_addedEventArgs); Assert.IsTrue(_addedEventArgs.FieldFormatter == toAdd); Assert.IsTrue(_removedEventArgs.FieldFormatter == toReplace); }
public void RemoveOne() { FieldFormatterCollection fieldFormatters = new FieldFormatterCollection(); fieldFormatters.Removed += new FieldFormatterRemovedEventHandler( OnFieldFormattersRemoved); // Add field formatters. for (int i = _fieldFormatters.Length - 1; i >= 0; i--) { fieldFormatters.Add(( FieldFormatter)(_fieldFormatters[i])); } // Remove. for (int i = 0; i < _exists.Length; i++) { Assert.IsNotNull(fieldFormatters[_exists[i]]); Assert.IsTrue(fieldFormatters.Contains(_exists[i])); Assert.IsNull(fieldFormatters[_notExists[i]]); Assert.IsFalse(fieldFormatters.Contains(_notExists[i])); _removedEventArgs = null; FieldFormatter fieldFormatter = fieldFormatters[_exists[i]]; fieldFormatters.Remove(_exists[i]); Assert.IsNotNull(_removedEventArgs); Assert.IsTrue(_removedEventArgs.FieldFormatter == fieldFormatter); _removedEventArgs = null; fieldFormatters.Remove(_notExists[i]); Assert.IsNull(_removedEventArgs); Assert.IsNull(fieldFormatters[_exists[i]]); Assert.IsFalse(fieldFormatters.Contains(_exists[i])); Assert.IsNull(fieldFormatters[_notExists[i]]); Assert.IsFalse(fieldFormatters.Contains(_notExists[i])); if (i < _maximum.Length) { Assert.IsTrue(fieldFormatters.MaximumFieldFormatterNumber == _maximum[i]); } else { try { int max = fieldFormatters.MaximumFieldFormatterNumber; Assert.Fail(); } catch (ApplicationException) { } } } }
/// <summary> /// Specifies that a field's value should be converted to a string from its source type using the provided conversion function. /// </summary> /// <typeparam name="TProperty">The type of the source property.</typeparam> /// <param name="formatter">A lambda function converting to a string.</param> public IDelimitedFieldSettingsBuilder WithConversionToString <TProperty>(FieldFormatter <TProperty> formatter) { if (_converter == null) { _converter = new DelegatingConverter <TProperty>(); } if (_converter is DelegatingConverter <TProperty> delegatingConverter) { delegatingConverter.FormatValue = formatter; } else { throw new InvalidOperationException("A converter has already been explicitly set."); } return(this); }
public void Scibe_Write_Property_With_Custom_Padding_No_Char_Supplied_Writes_Values() { var expected = "ZZZ "; var fieldFormatter = new FieldFormatter(); var business = new BusinessWithPropertyThatUsesCustomerPaddingNoPaddingChar() { BusinessDBA = "ZZZ" }; using (var writer = new StringWriter()) { IScribe scribe = new Scribe(writer, fieldFormatter); scribe.Write(business); var actual = writer.ToString(); Assert.Equal(expected, actual); } }
public void Scibe_Write_Property_With_Custom_Char_Writes() { var expected = "ZZZZZXXXXX"; var fieldFormatter = new FieldFormatter(); var business = new BusinessWithPropertyThatUsesCustomPadding() { BusinessName = "ZZZZZ" }; using (var writer = new StringWriter()) { IScribe scribe = new Scribe(writer, fieldFormatter); scribe.Write(business); var actual = writer.ToString(); Assert.Equal(expected, actual); } }
/// <summary> /// It initializes a new instance of the class. /// </summary> /// <param name="fieldNumber"> /// It's the number of the field this formatter formats/parse. /// </param> /// <param name="expression"> /// It's the expression to evaluate, based in the result <paramref name="trueFormatter"/> /// or <paramref name="falseFormatter" /> are used in the formatting/parsing of a message. /// </param> /// <param name="trueFormatter"> /// It's the formatter to be used when <paramref name="expression"/> is true. /// </param> /// <param name="falseFormatter"> /// It's the formatter to be used when <paramref name="expression"/> is false. /// </param> /// <param name="description"> /// It's the description of the field formatter. /// </param> public ConditionalFieldFormatter(int fieldNumber, string expression, FieldFormatter trueFormatter, FieldFormatter falseFormatter, string description) : base(fieldNumber, description) { if (trueFormatter == null) { throw new ArgumentNullException("trueFormatter"); } if (falseFormatter == null) { throw new ArgumentNullException("falseFormatter"); } _expression = expression; _trueFormatter = trueFormatter; _falseFormatter = falseFormatter; Tokenizer tokenizer = new Tokenizer( new StringReader(_expression)); SemanticParser sp = new SemanticParser(); object result = null; try { result = sp.yyparse(tokenizer); } catch (Exception ex) { throw new ExpressionCompileException(ex.Message, tokenizer.LastParsedTokenIndex); } _compiledExpression = result as IBooleanExpression; if (_compiledExpression == null) { throw new ApplicationException("Unknown result from expression."); } _evaluator = this; }
public void Scribe_Write_Only_Writes_Public_Properties_Of_Classes() { var expected = "12345000000000000000BusinessName 5555555555 45678900000000000000"; var fieldFormatter = new FieldFormatter(); var business = new BusinessWithPrivateProperty() { BusinessId = 12345, BusinessName = "BusinessName", BusinessTelephoneNumber = "5555555555", TaxId = "456789", }; using (var writer = new StringWriter()) { IScribe scribe = new Scribe(writer, fieldFormatter); scribe.Write(business); var actual = writer.ToString(); Assert.Equal(expected, actual); } }
public void Scribe_Write_Class_Writes_Properties_To_String_Value() { var expected = "12345000000000000000BusinessName 5555555555 4567890000000000000000000000000000010000"; var fieldFormatter = new FieldFormatter(); var business = new SimpleBusiness() { BusinessId = 12345, BusinessName = "BusinessName", BusinessTelephoneNumber = "5555555555", TaxId = "456789", CashOnHand = "10000" }; using (var writer = new StringWriter()) { IScribe scribe = new Scribe(writer, fieldFormatter); scribe.Write(business); var actual = writer.ToString(); Assert.Equal(expected, actual); } }
public void Scribe_Write_Class_With_One_Property_Without_Attribute_Writes_Values_With_Attributes_Only() { var expected = "12345000000000000000BusinessName 5555555555 45678900000000000000"; var fieldFormatter = new FieldFormatter(); var business = new BusinessWithOneFieldWithoutAttribute() { BusinessId = 12345, BusinessName = "BusinessName", BusinessTelephoneNumber = "5555555555", TaxId = "456789", Something = "something" }; using (var writer = new StringWriter()) { IScribe scribe = new Scribe(writer, fieldFormatter); scribe.Write(business); var actual = writer.ToString(); Assert.Equal(expected, actual); Assert.DoesNotContain(actual, business.Something); } }
/// <summary> /// It initializes a new instance of the class. /// </summary> /// <param name="fieldNumber"> /// It's the number of the field this formatter formats/parse. /// </param> /// <param name="evaluator"> /// It's the evaluator which decides which field formatter must be used between /// <paramref name="trueFormatter"/> and <paramref name="falseFormatter" />, /// in the formatting/parsing of a message. /// </param> /// <param name="trueFormatter"> /// It's the formatter to be used when <paramref name="expression"/> is true. /// </param> /// <param name="falseFormatter"> /// It's the formatter to be used when <paramref name="expression"/> is false. /// </param> /// <param name="description"> /// It's the description of the field formatter. /// </param> public ConditionalFieldFormatter(int fieldNumber, IConditionalFieldEvaluator evaluator, FieldFormatter trueFormatter, FieldFormatter falseFormatter, string description) : base(fieldNumber, description) { if (evaluator == null) { throw new ArgumentNullException("evaluator"); } if (trueFormatter == null) { throw new ArgumentNullException("trueFormatter"); } if (falseFormatter == null) { throw new ArgumentNullException("falseFormatter"); } _evaluator = evaluator; _trueFormatter = trueFormatter; _falseFormatter = falseFormatter; }
public void test_formatter_throws_exception_with_fields_with_whitespace() { var formatter = new FieldFormatter(FieldFormatterType.INHERITED); formatter.Invoking(frm => frm.Format("Hola don pepito")).Should().Throw <ArgumentException>(); }
public void test_formatter_format_correctly_to_upper_underscore_from_upper_camel() { var formatter = new FieldFormatter("UppER_UNDERSCORE"); formatter.Format("HolaDonPepito").Should().BeEquivalentTo("HOLA_DON_PEPITO"); }
public void test_formatter_format_correctly_to_upper_camel_from_lower_camel() { var formatter = new FieldFormatter(FieldFormatterType.UPPER_CAMEL); formatter.Format("holaDonPepito").Should().BeEquivalentTo("HolaDonPepito"); }
public void test_formatter_format_correctly_to_upper_camel_from_all_upper() { var formatter = new FieldFormatter(FieldFormatterType.UPPER_CAMEL); formatter.Format("HOLADONPEPITO").Should().BeEquivalentTo("HOLADONPEPITO"); }
public void test_formatter_format_correctly_to_lower_underscore_from_upper_camel() { var formatter = new FieldFormatter("lower_underscore"); formatter.Format("HolaDonPepito").Should().BeEquivalentTo("hola_don_pepito"); }
private void AddDirectory() { DirectoryType dir = null; List <FieldFormatter> ffs = new List <FieldFormatter>(); if (rblDirectoryType.SelectedValue == "LDAP") { dir = InitLdapDirectory(); foreach (ListItem lil in lbLdapFieldFormatters.Items) { FieldFormatter ffl = new FieldFormatter(); ffl.fieldName = lil.Text; string[] values = lil.Value.Split('#'); ffl.value = values[0]; ffl.fieldType = GetFieldType(values[1]); ffs.Add(ffl); } ((LdapDatasourceType)dir.Item).fieldFormatters = ffs.ToArray(); ((LdapDatasourceType)dir.Item).ipphonefilter = new CiscoIPPhoneFilterType(); ((LdapDatasourceType)dir.Item).ipphonefilter.firstnamemap = tbLdapFirstNameFilterMap.Text; ((LdapDatasourceType)dir.Item).ipphonefilter.lastnamemap = tbLdapLastNameFilterMap.Text; ((LdapDatasourceType)dir.Item).ipphonefilter.telephonenumbermap = tbLdapTelephoneNumberFilterMap.Text; } else if (rblDirectoryType.SelectedValue == "SQL") { dir = InitSqlDirectory(); foreach (ListItem lis in lbSQLFieldFormatters.Items) { FieldFormatter ffsql = new FieldFormatter(); ffsql.fieldName = lis.Text; string[] values = lis.Value.Split('#'); ffsql.value = values[0]; ffsql.fieldType = GetFieldType(values[1]); ffs.Add(ffsql); } ((SqlDatasourceType)dir.Item).fieldFormatters = ffs.ToArray(); ((SqlDatasourceType)dir.Item).ipphonefilter = new CiscoIPPhoneFilterType(); ((SqlDatasourceType)dir.Item).ipphonefilter.firstnamemap = tbSQLFirstNameFilterMap.Text; ((SqlDatasourceType)dir.Item).ipphonefilter.lastnamemap = tbSQLLastNameFilterMap.Text; ((SqlDatasourceType)dir.Item).ipphonefilter.telephonenumbermap = tbSQLTelephoneNumberFilterMap.Text; } else if (rblDirectoryType.SelectedValue == "CISCO") { dir = InitCiscoDirectory(); foreach (ListItem lis in lbCiscoFieldFormatters.Items) { FieldFormatter ffcisco = new FieldFormatter(); ffcisco.fieldName = lis.Text; string[] values = lis.Value.Split('#'); ffcisco.value = values[0]; ffcisco.fieldType = GetFieldType(values[1]); ffs.Add(ffcisco); } ((CiscoDatasourceType)dir.Item).fieldFormatters = ffs.ToArray(); ((CiscoDatasourceType)dir.Item).ipphonefilter = new CiscoIPPhoneFilterType(); ((CiscoDatasourceType)dir.Item).ipphonefilter.firstnamemap = tbFirstNameFilterMap.Text; ((CiscoDatasourceType)dir.Item).ipphonefilter.lastnamemap = tbLastNameFilterMap.Text; ((CiscoDatasourceType)dir.Item).ipphonefilter.telephonenumbermap = tbTelephoneNumberFilterMap.Text; } Global.AddDirectory(dir); }
public void test_formatter_format_correctly_to_lower_hyphen_from_mixed_string() { var formatter = new FieldFormatter(FieldFormatterType.LOWER_HYPHEN); formatter.Format("Hola_don-Pepito").Should().BeEquivalentTo("hola-don-pepito"); }
/** * Write this entry to the given Writer, with the given FieldFormatter. * @param write True if this is a write, false if it is a display. The write will * not include non-writeable fields if it is a write, otherwise non-displayable fields * will be ignored. Refer to GUIGlobals for isWriteableField(String) and * isDisplayableField(String). */ public void write(TextWriter writer, FieldFormatter ff, bool write) { // Write header with type and bibtex-key. writer.Write("@"+_type.getName().ToUpper(/*TODO:Locale.US*/)+"{"); String str = Util.shaveString(getField(BibtexFields.KEY_FIELD)); writer.Write(((str == null) ? "" : str)+","+Globals.NEWLINE); Dictionary<String, String> written = new Dictionary<String, String>(); written.Add(BibtexFields.KEY_FIELD, null); bool hasWritten = false; // Write required fields first. String[] s = getRequiredFields(); if (s != null) for (int i=0; i<s.Length; i++) { hasWritten = hasWritten | writeField(s[i], writer, ff, hasWritten); written.Add(s[i], null); } // Then optional fields. s = getOptionalFields(); if (s != null) for (int i=0; i<s.Length; i++) { if (!written.ContainsKey(s[i])) { // If field appears both in req. and opt. don't repeat. //writeField(s[i], writer, ff); hasWritten = hasWritten | writeField(s[i], writer, ff, hasWritten); written.Add(s[i], null); } } // Then Write remaining fields in alphabetic order. var remainingFields = new Dictionary<String, bool>(); foreach (var key in _fields.Keys) { bool writeIt = (write ? BibtexFields.isWriteableField(key) : BibtexFields.isDisplayableField(key)); if (!written.ContainsKey(key) && writeIt) remainingFields.Add(key, true); } foreach (var field in remainingFields.Keys) hasWritten = hasWritten | writeField(field, writer, ff, hasWritten); // Finally, end the entry. writer.Write((hasWritten ? Globals.NEWLINE : "")+"}"+Globals.NEWLINE); }
private void UpdateDirectory() { DirectoryType dir = null; List<FieldFormatter> ffs = new List<FieldFormatter>(); if (rblDirectoryType.SelectedValue == "LDAP") { dir = InitLdapDirectory(); foreach (ListItem lil in lbLdapFieldFormatters.Items) { FieldFormatter ffl = new FieldFormatter(); ffl.fieldName = lil.Text; string[] values = lil.Value.Split('#'); ffl.value = values[0]; ffl.fieldType = GetFieldType(values[1]); ffs.Add(ffl); } ((LdapDatasourceType)dir.Item).fieldFormatters = ffs.ToArray(); ((LdapDatasourceType)dir.Item).ipphonefilter = new CiscoIPPhoneFilterType(); ((LdapDatasourceType)dir.Item).ipphonefilter.firstnamemap = tbLdapFirstNameFilterMap.Text; ((LdapDatasourceType)dir.Item).ipphonefilter.lastnamemap = tbLdapLastNameFilterMap.Text; ((LdapDatasourceType)dir.Item).ipphonefilter.telephonenumbermap = tbLdapTelephoneNumberFilterMap.Text; } else if (rblDirectoryType.SelectedValue == "SQL") { dir = InitSqlDirectory(); foreach (ListItem lis in lbSQLFieldFormatters.Items) { FieldFormatter ffsql = new FieldFormatter(); ffsql.fieldName = lis.Text; string[] values = lis.Value.Split('#'); ffsql.value = values[0]; ffsql.fieldType = GetFieldType(values[1]); ffs.Add(ffsql); } ((SqlDatasourceType)dir.Item).fieldFormatters = ffs.ToArray(); ((SqlDatasourceType)dir.Item).ipphonefilter = new CiscoIPPhoneFilterType(); ((SqlDatasourceType)dir.Item).ipphonefilter.firstnamemap = tbSQLFirstNameFilterMap.Text; ((SqlDatasourceType)dir.Item).ipphonefilter.lastnamemap = tbSQLLastNameFilterMap.Text; ((SqlDatasourceType)dir.Item).ipphonefilter.telephonenumbermap = tbSQLTelephoneNumberFilterMap.Text; } else if (rblDirectoryType.SelectedValue == "CISCO") { dir = InitCiscoDirectory(); foreach (ListItem lis in lbCiscoFieldFormatters.Items) { FieldFormatter ffcisco = new FieldFormatter(); ffcisco.fieldName = lis.Text; string[] values = lis.Value.Split('#'); ffcisco.value = values[0]; ffcisco.fieldType = GetFieldType(values[1]); ffs.Add(ffcisco); } ((CiscoDatasourceType)dir.Item).fieldFormatters = ffs.ToArray(); ((CiscoDatasourceType)dir.Item).ipphonefilter = new CiscoIPPhoneFilterType(); ((CiscoDatasourceType)dir.Item).ipphonefilter.firstnamemap = tbFirstNameFilterMap.Text; ((CiscoDatasourceType)dir.Item).ipphonefilter.lastnamemap = tbLastNameFilterMap.Text; ((CiscoDatasourceType)dir.Item).ipphonefilter.telephonenumbermap = tbTelephoneNumberFilterMap.Text; } Global.UpdateDirectory(dir); }
/// <summary> /// 将list的数据导出到指定路径的Excel文件中,同时将执行过程中产生的警告信息保存到字段warningMsg /// 每个字段为一列按顺序导出 /// 可指定不需要导出的字段名称,可通过编写委托函数设置指定名称字段的导出格式 /// 失败:抛出异常 /// </summary> /// auto: tac /// created date: 2016/01/25 PM /// <exception cref="CommonException"></exception> /// <typeparam name="T"></typeparam> /// <param name="list">要导出的数据</param> /// <param name="templatePath">模版文件路径</param> /// <param name="path">文件导出路径</param> /// <param name="unexportFiledList">不需要导出的字段列表(区分大小写)</param> /// <param name="formatter">调用者用于格式化指定名称字段的委托函数</param> /// <returns></returns> public void Export <T>(IEnumerable <T> list, string templatePath, string path, List <string> unexportFiledList = null, FieldFormatter formatter = null) { if (!list.Any()) { throw new CommonException("无任何要导出的数据"); } try { File.Copy(templatePath, path, true); using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { IWorkbook workbook = null; ISheet sheet = null; Regex xls = new Regex("\\.xls$", RegexOptions.IgnoreCase); Regex xlsx = new Regex("\\.xlsx$", RegexOptions.IgnoreCase); if (xls.Match(path).Length > 0) { // 2003版本 workbook = new HSSFWorkbook(fs); } else if (xlsx.Match(path).Length > 0) { // 2007版本 workbook = new XSSFWorkbook(fs); } else { throw new CommonException("文件格式错误"); } //创建属性的集合 List <PropertyInfo> pList = new List <PropertyInfo>(); //获得反射的入口 Type type = typeof(T); //把所有的public属性加入到集合 Array.ForEach <PropertyInfo>(type.GetProperties(), p => pList.Add(p)); sheet = (ISheet)workbook.GetSheetAt(0); int rowIndex = 1; foreach (var item in list) { IRow dataRow = (IRow)sheet.CreateRow(rowIndex); var col = 0; for (int i = 0; i < pList.Count; i++) { //如果是不需要导出的字段,则continue if (unexportFiledList != null && unexportFiledList.Contains(pList[i].Name)) { continue; } var fieldType = pList[i].PropertyType.Name; var fieldValue = pList[i].GetValue(item); string txt = ""; //需要格式化特定字段 if (formatter != null) { txt = formatter(pList[i].Name, fieldValue); } else { txt = fieldValue == null ? "" : fieldValue.ToString(); } dataRow.CreateCell(col).SetCellValue(txt); col++; } rowIndex++; } //写入文件 using (FileStream stm = File.OpenWrite(path)) { workbook.Write(stm); } fs.Close(); } } catch (CommonException) { throw; } catch (Exception) { throw; } }
public void test_formatter_format_correctly_to_lower_hyphen_from_upper_camel() { var formatter = new FieldFormatter("LOWER_HYPHEN"); formatter.Format("HolaDonPepito").Should().BeEquivalentTo("hola-don-pepito"); }
/** * Write a single field, if it has any content. * @param name The field name * @param out The Writer to send it to * @param ff A formatter to filter field contents before writing * @param isFirst Indicates whether this is the first field written for * this entry - if not, start by writing a comma and newline * @return true if this field was written, false if it was skipped because * it was not set * @throws IOException In case of an IO error */ private bool writeField(String name, TextWriter writer, FieldFormatter ff, bool isFirst) { String o = getField(name); if (o != null) { if (isFirst) writer.Write(","+Globals.NEWLINE); writer.Write(" "+name+" = "); try { writer.Write(ff.format(o.ToString(), name)); } catch (Exception ex) { throw new IOException (Globals.lang("Error in field")+" '"+name+"': "+ex.Message); } return true; } else return false; }
public void test_formatter_format_correctly_to_lower_underscore_from_mixed_string() { var formatter = new FieldFormatter(FieldFormatterType.LOWER_UNDERSCORE); formatter.Format("Hola_don-Pepito").Should().BeEquivalentTo("hola_don_pepito"); }