Created
September 3, 2012 08:36
-
-
Save chgeuer/3607916 to your computer and use it in GitHub Desktop.
This sample illustrates how we can simply bring more complex data types into Azure Mobile Services.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Sample | |
{ | |
using System; | |
using System.Runtime.Serialization; | |
using System.Xml.Linq; | |
using Windows.Data.Json; | |
using Microsoft.WindowsAzure.MobileServices; | |
/// <summary> | |
/// This sample illustrates how we can simply bring more complex data types into Azure Mobile Services. | |
/// <seealso href="http://blogs.msdn.com/b/carlosfigueira/archive/2012/08/30/supporting-arbitrary-types-in-azure-mobile-services-managed-client-simple-types.aspx"/> | |
/// </summary> | |
public class CustomConvertedData | |
{ | |
public int Id { get; set; } | |
[DataMember(Name = "xml")] | |
[DataMemberJsonConverter(ConverterType = typeof(XElementConverter))] | |
public XElement SerializedXml { get; set; } | |
[DataMember(Name = "octetstream")] | |
[DataMemberJsonConverter(ConverterType = typeof(ByteArrayConverter))] | |
public byte[] Octets { get; set; } | |
} | |
public class ByteArrayConverter : DataMemberJsonConverterBase<byte[]> | |
{ | |
protected override byte[] tFromString(string s) { return Convert.FromBase64String(s); } | |
protected override string stringFromT(byte[] t) { return Convert.ToBase64String(t); } | |
} | |
public class XElementConverter : DataMemberJsonConverterBase<XElement> | |
{ | |
protected override XElement tFromString(string s) { return XElement.Parse(s); } | |
protected override string stringFromT(XElement t) { return t.ToString(); } | |
} | |
public abstract class DataMemberJsonConverterBase<T> : IDataMemberJsonConverter | |
{ | |
private static readonly IJsonValue NullJson = JsonValue.Parse("null"); | |
protected abstract T tFromString(string s); | |
protected abstract string stringFromT(T t); | |
public object ConvertFromJson(IJsonValue value) | |
{ | |
T t = default(T); | |
if (value != null && value.ValueType == JsonValueType.String) | |
{ | |
t = tFromString(value.GetString()); | |
} | |
return t; | |
} | |
public IJsonValue ConvertToJson(object instance) | |
{ | |
if (instance is T) | |
{ | |
T t = (T)instance; | |
return JsonValue.CreateStringValue(stringFromT(t)); | |
} | |
else | |
{ | |
return NullJson; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment