Bundle: redb-route / redb.Route.DataFormats.Csv (redb.Route.DataFormats.Csv.txt), 5 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.DataFormats.Csv/CsvDataFormat.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.DataFormats.Csv/CsvDataFormat.cs
----
using System.Collections;
using CsvHelper;
using CsvHelper.Configuration;
using redb.Route.Abstractions;
namespace redb.Route.DataFormats.Csv;
///
/// CSV (CsvHelper). Marshals POCO collections (header from property
/// names), dictionaries (header from keys), raw rows (string[] / object[] , no header) or a
/// single POCO; unmarshals to List<T> / T[] / IEnumerable<T> , to
/// List<Dictionary<string,string>> (with header) or List<string[]> (without),
/// or to a single T . Errors name the format.
///
public sealed class CsvDataFormat : IMessageSerializer
{
/// Content type the format is registered under.
public const string DefaultContentType = "text/csv";
/// The name the format answers to in markup, <marshal format="csv"/> , as Apache Camel names it; AddCsvDataFormat() registers it.
public const string Name = "csv";
private readonly CsvDataFormatOptions _options;
/// Creates the format with the given options (defaults when null ).
public CsvDataFormat(CsvDataFormatOptions? options = null) => _options = options ?? new CsvDataFormatOptions();
/// The options in effect.
public CsvDataFormatOptions Options => _options;
///
public string ContentType => DefaultContentType;
///
public IReadOnlyCollection MediaTypes => [DefaultContentType, "application/csv"];
private CsvConfiguration Configuration(bool forWriting)
{
var configuration = new CsvConfiguration(_options.Culture)
{
Delimiter = _options.Delimiter,
HasHeaderRecord = _options.HasHeaderRecord,
Quote = _options.Quote,
TrimOptions = _options.TrimFields ? TrimOptions.Trim : TrimOptions.None,
MissingFieldFound = null,
HeaderValidated = null,
};
// NewLine is a writer setting: when set on a reader CsvHelper stops auto-detecting \r\n / \n / \r.
if (forWriting)
configuration.NewLine = _options.NewLine;
return configuration;
}
// ── Marshal ───────────────────────────────────────────────────────────────
///
public byte[] Serialize(T value)
{
switch (value)
{
case null: return [];
case byte[] bytes: return bytes;
case string text: return _options.Encoding.GetBytes(text);
}
try
{
using var writer = new StringWriter(_options.Culture);
using (var csv = new CsvWriter(writer, Configuration(forWriting: true), leaveOpen: true))
{
switch (value)
{
case IEnumerable maps: WriteMaps(csv, maps); break;
case IEnumerable rows: WriteRows(csv, rows); break;
case IEnumerable rows: WriteRows(csv, rows); break;
case IEnumerable records: csv.WriteRecords(records); break;
default: csv.WriteRecords(new[] { value }); break;
}
}
return _options.Encoding.GetBytes(writer.ToString());
}
catch (Exception ex) when (ex is CsvHelperException or InvalidOperationException or ArgumentException)
{
throw new InvalidOperationException($"CSV data format: cannot marshal {value.GetType().Name} ({ex.Message}).", ex);
}
}
private void WriteMaps(CsvWriter csv, IEnumerable maps)
{
// The header is the union of every row's keys in first-seen order: a column that only a later
// row carries must not be dropped because the first row happened not to have it.
var rows = maps.ToList();
var header = new List();
var seen = new HashSet(StringComparer.Ordinal);
foreach (var map in rows)
foreach (var key in map.Keys)
{
var name = key?.ToString() ?? string.Empty;
if (seen.Add(name)) header.Add(name);
}
if (_options.HasHeaderRecord)
{
foreach (var name in header) csv.WriteField(name);
csv.NextRecord();
}
foreach (var map in rows)
{
foreach (var name in header)
csv.WriteField(map.Contains(name) ? map[name] : null);
csv.NextRecord();
}
}
private static void WriteRows(CsvWriter csv, IEnumerable> rows)
{
foreach (var row in rows)
{
foreach (var cell in row) csv.WriteField(cell);
csv.NextRecord();
}
}
// ── Unmarshal ─────────────────────────────────────────────────────────────
///
public T? Deserialize(byte[] data) => (T?)Deserialize(data, typeof(T));
///
public object? Deserialize(byte[] data, Type type)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(type);
var text = _options.Encoding.GetString(data);
if (type == typeof(string)) return text;
try
{
using var reader = new StringReader(text);
using var csv = new CsvReader(reader, Configuration(forWriting: false));
var element = CollectionElement(type);
if (element is null)
return ReadSingle(csv, type);
var items = ReadMany(csv, element);
return ToCollection(type, element, items);
}
catch (Exception ex) when (ex is CsvHelperException or FormatException or InvalidOperationException or ArgumentException)
{
throw new InvalidOperationException($"CSV data format: cannot unmarshal to {type.Name} ({ex.Message}).", ex);
}
}
private object? ReadSingle(CsvReader csv, Type type)
{
if (type == typeof(object) || IsMapType(type))
return ReadMany(csv, type).FirstOrDefault();
if (type == typeof(string[]))
return ReadMany(csv, type).FirstOrDefault();
return csv.GetRecords(type).Cast().FirstOrDefault();
}
private List ReadMany(CsvReader csv, Type element)
{
if (element == typeof(string[]))
return ReadRows(csv, skipHeader: _options.HasHeaderRecord);
if (element == typeof(object) || IsMapType(element))
return _options.HasHeaderRecord ? ReadMaps(csv, element) : ReadRows(csv, skipHeader: false);
return csv.GetRecords(element).Cast().ToList();
}
/// Raw rows; with a header record configured, the header line is data for nobody and is skipped.
private static List ReadRows(CsvReader csv, bool skipHeader)
{
var rows = new List();
if (skipHeader && !csv.Read()) return rows;
while (csv.Read())
rows.Add(csv.Parser.Record?.ToArray() ?? []);
return rows;
}
private static List ReadMaps(CsvReader csv, Type element)
{
var rows = new List();
if (!csv.Read()) return rows;
csv.ReadHeader();
var header = csv.HeaderRecord ?? [];
var objectValues = element == typeof(object) || (element.IsGenericType && element.GetGenericArguments()[1] == typeof(object));
while (csv.Read())
{
if (objectValues)
{
var map = new Dictionary(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < header.Length; i++) map[header[i]] = csv.GetField(i);
rows.Add(map);
}
else
{
var map = new Dictionary(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < header.Length; i++) map[header[i]] = csv.GetField(i) ?? string.Empty;
rows.Add(map);
}
}
return rows;
}
/// Element type when is a supported collection shape; otherwise null (single record).
private static Type? CollectionElement(Type type)
{
if (type == typeof(string[])) return null; // one raw row
if (type.IsArray) return type.GetElementType();
if (!type.IsGenericType) return type == typeof(IEnumerable) ? typeof(object) : null;
var definition = type.GetGenericTypeDefinition();
if (definition == typeof(List<>) || definition == typeof(IList<>) || definition == typeof(IEnumerable<>)
|| definition == typeof(ICollection<>) || definition == typeof(IReadOnlyList<>) || definition == typeof(IReadOnlyCollection<>))
return type.GetGenericArguments()[0];
return null;
}
private static bool IsMapType(Type type)
{
if (!type.IsGenericType) return false;
var definition = type.GetGenericTypeDefinition();
return (definition == typeof(Dictionary<,>) || definition == typeof(IDictionary<,>) || definition == typeof(IReadOnlyDictionary<,>))
&& type.GetGenericArguments()[0] == typeof(string);
}
private static object ToCollection(Type collectionType, Type element, List items)
{
if (collectionType.IsArray)
{
var array = Array.CreateInstance(element, items.Count);
for (var i = 0; i < items.Count; i++) array.SetValue(items[i], i);
return array;
}
var listType = typeof(List<>).MakeGenericType(element == typeof(object) && items.Count > 0 && items[0] is IDictionary ? typeof(object) : element);
var list = (IList)Activator.CreateInstance(listType)!;
foreach (var item in items) list.Add(item);
return list;
}
}
Path: redb-route/redb.Route.DataFormats.Csv/CsvDataFormatOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.DataFormats.Csv/CsvDataFormatOptions.cs
----
using System.Globalization;
using System.Text;
namespace redb.Route.DataFormats.Csv;
/// Options of one instance (per node or per registration).
public sealed class CsvDataFormatOptions
{
/// Field delimiter. Default , .
public string Delimiter { get; set; } = ",";
/// Whether the first record is a header (written on marshal, read on unmarshal). Default true .
public bool HasHeaderRecord { get; set; } = true;
/// Quote character. Default " .
public char Quote { get; set; } = '"';
/// Culture for number and date conversion. Default invariant.
public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture;
/// Trim whitespace around fields on read. Default false .
public bool TrimFields { get; set; }
/// Record terminator written on marshal. Default \r\n (RFC 4180).
public string NewLine { get; set; } = "\r\n";
/// Text encoding. Default UTF-8 without BOM.
public Encoding Encoding { get; set; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
}
Path: redb-route/redb.Route.DataFormats.Csv/CsvRouteDefinitionExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.DataFormats.Csv/CsvRouteDefinitionExtensions.cs
----
using redb.Route.Abstractions;
using redb.Route.Extensions;
namespace redb.Route.DataFormats.Csv;
/// DSL and registration sugar for .
public static class CsvRouteDefinitionExtensions
{
/// Marshals the body to CSV with per-node options.
public static IRouteDefinition MarshalCsv(this IRouteDefinition route, Action? configure = null)
=> route.Marshal(new CsvDataFormat(Build(configure)));
/// Unmarshals CSV to (List<Row> , Row[] , List<Dictionary<string,string>> , List<string[]> ) with per-node options.
public static IRouteDefinition UnmarshalCsv(this IRouteDefinition route, Action? configure = null)
=> route.Unmarshal(new CsvDataFormat(Build(configure)));
/// Registers CSV as text/csv on the context, for Marshal("text/csv") , Unmarshal<T>("text/csv") and content-type-driven Unmarshal<T>() .
public static IRouteContext AddCsvDataFormat(this IRouteContext context, Action? configure = null)
=> context.AddDataFormat(new CsvDataFormat(Build(configure)), CsvDataFormat.Name);
/// DI form of .
public static RedbRouteBuilder AddCsvDataFormat(this RedbRouteBuilder builder, Action? configure = null)
=> builder.AddDataFormat(new CsvDataFormat(Build(configure)), CsvDataFormat.Name);
private static CsvDataFormatOptions Build(Action? configure)
{
var options = new CsvDataFormatOptions();
configure?.Invoke(options);
return options;
}
}
Path: redb-route/redb.Route.DataFormats.Csv/README.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.DataFormats.Csv/README.md
----
# redb.Route.DataFormats.Csv
> Documentation and articles:
CSV as a redb.Route data format, on [CsvHelper](https://joshclose.github.io/CsvHelper/).
```csharp
// per-node options
.UnmarshalCsv>(o => { o.Delimiter = ";"; o.HasHeaderRecord = true; })
.MarshalCsv()
// or by content type, after registering once
context.AddCsvDataFormat(); // builder.AddCsvDataFormat() with DI
.Marshal("text/csv")
.Unmarshal>("text/csv")
.Unmarshal>() // driven by the message ContentType (text/csv)
```
| Direction | Body in | Body out |
|---|---|---|
| Marshal | `IEnumerable` of POCOs (header from property names), `IEnumerable` (header from keys), `IEnumerable` / `object[]` rows (no header), a single POCO, a ready CSV `string` | `byte[]`, `ContentType = text/csv` |
| Unmarshal | `byte[]`, `string`, `Stream` | `List` / `T[]` / `IEnumerable` of POCOs; `List>` (with header) or `List` (without); a single `T`; `string` |
Options: `Delimiter` (`,`), `HasHeaderRecord` (`true`), `Quote` (`"`), `Culture` (invariant), `TrimFields`,
`NewLine` (`\r\n`), `Encoding` (UTF-8 without BOM). Quotes, embedded newlines and empty fields follow RFC 4180.
XML form: ` `, ` `.
Path: redb-route/redb.Route.DataFormats.Csv/redb.Route.DataFormats.Csv.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.DataFormats.Csv/redb.Route.DataFormats.Csv.csproj
----
redb.Route.DataFormats.Csv
CSV data format for redb.Route (CsvHelper): Marshal/Unmarshal of POCO collections, dictionaries and raw rows; delimiter, header, quote and culture options; registered as text/csv.
esb;messaging;csv;dataformat;redb
README.md