|
Avro C#
|
This namespace contains classes that implement Avro serialization and deserialization for plain C# objects. The classes use .net reflection to implement the serializers. The interface is similar to the Generic and Specific serialization classes.
The approach starts with the schema and iterates both the schema and the dotnet type together in a depth first manner per the specification. Serialization is the same as the Generic serializer except where the serializer encounters:
Basic serialization is performed as in the following example:
Deserialization proceeds in much the same fashion as serialization. When required objects are created. By default this is with:
however this can be overridden by setting the deserializer property RecordFactory.
You might want to do this if your class contains interfaces and/or if you use an IoC container.
See the section on Arrays. The ArrayHelper specifies the type of object created when an array is deserialized. The default is List<T>.
The type created for Map objects is specified by the Deserializer property MapType. This must be a two (or more) parameter generic type where the first type parameter is string and the second is undefined e.g. Dictionary<string,>.
By default the MapType is Dictionary<string,>
csharp Schema schema; // created previously
// using same writer and reader schema in this example. var avroReader = new ReflectReader<T>(schema, schema);
using (var stream = new MemoryStream(serialized)) { deserialized = avroReader.Read(null, new BinaryDecoder(stream)); }
csharp var cache = new ClassCache(); var writer = new ReflectWriter<MultiList>(schema, cache); var reader = new ReflectReader<MultiList>(schema, schema, cache);
csharp public class GenericFixedConverter : TypedFieldConverter<byte[],GenericFixed> { public override GenericFixed From(byte[] o, Schema s) { return new GenericFixed(s as FixedSchema, o); }
public override byte[] To(GenericFixed o, Schema s) { return o.Value; } }
csharp public class LogMessage {
[AvroField(typeof(DateTimeOffsetToLongConverter))]
public DateTimeOffset TimeStamp { get; set; }
}
csharp ClassCache.AddDefaultConverter<byte[], GenericFixed>((a,s)=>new GenericFixed(s as FixedSchema, a), (p,s)=>p.Value); var writer = new ReflectWriter<GenericFixedRec>(schema); var reader = new ReflectReader<GenericFixedRec>(schema, schema);
csharp public class LogMessage { [AvroField("message")] public string Message { get; set; }
[AvroField(typeof(DateTimeOffsetToLongConverter))] public DateTimeOffset TimeStamp { get; set; } }
csharp
public class ConcurrentQueueHelper<T> : ArrayHelper
{
public override int Count()
{
ConcurrentQueue<T> e = (ConcurrentQueue<T>)Enumerable;
return e.Count;
}
public override void Add(object o)
{
ConcurrentQueue<T> e = (ConcurrentQueue<T>)Enumerable;
e.Enqueue((T)o);
}
public override void Clear()
{
ConcurrentQueue<T> e = (ConcurrentQueue<T>)Enumerable;
#if NET461 while (e.TryDequeue(out _)) { } #else e.Clear(); #endif }
public override Type ArrayType { get => typeof(ConcurrentQueue<>); }
public ConcurrentQueueHelper(IEnumerable enumerable) : base(enumerable) { Enumerable = enumerable; } }
string recordList = " { ""type"": ""array"", ""helper"": ""recordListQueue"", ""items"": ""string"" }" // using the helper var schema = Schema.Parse(recordList); var fixedRecWrite = new ConcurrentQueue<string>(); var cache = new ClassCache(); cache.AddArrayHelper("recordListQueue", typeof(ConcurrentQueueHelper<string>)); var writer = new ReflectWriter<ConcurrentQueue<ConcurrentQueueRec>>(schema, cache); var reader = new ReflectReader<ConcurrentQueue<ConcurrentQueueRec>>(schema, schema, cache); @icode ## Unions All union constructs are supported however record types that are first defined in unions may need manual type registration. ### Automatic Type Registration Types associated with unions of this form can be automatically registered and no special handling is needed. @endicode json ["null", { "type": "record", "name": "X"}] @icode _Example_: @endicode csharp public class MyClass { public string A { get; set; } public double C { get; set; } } // ... var nullableSchema = @" [ ""null"", { ""type"" : ""record"", ""name"" : ""Dervied2"", ""fields"" : [ { ""name"" : ""A"", ""type"" : ""string""}, { ""name"" : ""C"", ""type"" : ""double""} ] },
] "; var schema = Schema.Parse(nullableSchema); var derived2write = new MyClass() { A = "derived2", C = 3.14 }; var writer = new ReflectWriter<MyClass>(schema); var reader = new ReflectReader<MyClass>(schema, schema); // etc. @icode ### Manual Registration Where a record type is defined inside a union and the union does not follow the "nullable construct" above, the CSharp type and schema need to be manually registered. Registration is done using the ClassCache method LoadClassCache. @endicode csharp cache.LoadClassCache(typeof(MyClass), recordSchema); @icode Note that the `recordSchema` used here is the schema corresponding to the `MyClass` type within the overall union schema. See the example below. @endicode csharp public class BaseClass { public string A { get; set; } } public class Derived1 : BaseClass { public int B { get; set; } } public class Derived2 : BaseClass { public double C { get; set; } } public void SerializeExample() { var baseClassSchema = @" [ { ""type"" : ""record"", ""name"" : ""Dervied1"", ""fields"" : [ { ""name"" : ""A"", ""type"" : ""string""}, { ""name"" : ""B"", ""type"" : ""int""} ] }, { ""type"" : ""record"", ""name"" : ""Dervied2"", ""fields"" : [ { ""name"" : ""A"", ""type"" : ""string""}, { ""name"" : ""C"", ""type"" : ""double""} ] },
] "; var schema = Schema.Parse(baseClassSchema); var derived1write = new Derived1() { A = "derived1", B = 7 }; var derived2write = new Derived2() { A = "derived2", C = 3.14 };
// union types (except for [null, type]) need to be manually registered var unionSchema = schema as UnionSchema; var cache = new ClassCache(); cache.LoadClassCache(typeof(Derived1), unionSchema[0]); cache.LoadClassCache(typeof(Derived2), unionSchema[1]); var x = schema as RecordSchema;
var writer = new ReflectWriter<BaseClass>(schema, cache); var reader = new ReflectReader<BaseClass>(schema, schema, cache);
using (var stream = new MemoryStream(256)) { var encoder = new BinaryEncoder(stream); writer.Write(derived1write, encoder); writer.Write(derived2write, encoder); stream.Seek(0, SeekOrigin.Begin);
var decoder = new BinaryDecoder(stream); var derived1read = (Derived1)reader.Read(decoder); var derived2read = (Derived2)reader.Read(decoder); } } ```