Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CosmosJsonDotNetSerializer modified to allow migration of old schema
// Code removed for bravity
public sealed class CosmosJsonDotNetSerializer : CosmosSerializer
{
// Code removed for bravity
public override T FromStream<T>(Stream stream)
{
using (stream)
{
if (typeof(Stream).IsAssignableFrom(typeof(T)))
{
return (T)(object)stream;
}
using (var sr = new StreamReader(stream))
{
using (var jsonTextReader = new JsonTextReader(sr))
{
var jsonSerializer = GetSerializer();
return UpdateSchemaVersionToCurrent<T>(jsonSerializer.Deserialize<JObject>(jsonTextReader));
}
}
}
}
private T UpdateSchemaVersionToCurrent<T>(JObject jObject)
{
const int currentSchemaVersion = 3;
var schemaVersion = jObject["SchemaVersion"].Value<int>();
for (var i = schemaVersion; i < currentSchemaVersion; i++)
{
switch (i)
{
case 1:
jObject["Name"] = jObject["OrderName"];
jObject["OrderName"] = null;
break;
case 2:
var hasShipped = jObject["HasShipped"].Value<bool>();
if (hasShipped)
{
jObject["OrderStatus"] = (int)OrderStatus.Shipped;
}
else
{
jObject["OrderStatus"] = (int)OrderStatus.Processed;
}
break;
}
}
jObject["SchemaVersion"] = currentSchemaVersion;
return jObject.ToObject<T>();
}
// Code removed for bravity
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment