Skip to content

Instantly share code, notes, and snippets.

@darrelmiller
Created April 26, 2012 23:17
Show Gist options
  • Save darrelmiller/2504054 to your computer and use it in GitHub Desktop.
Save darrelmiller/2504054 to your computer and use it in GitHub Desktop.
SimpleFormatter<T>
public class SimpleFormatter<T> : MediaTypeFormatter
{
private readonly Action<T,Stream> _write;
private readonly Func<Stream,T> _read;
public SimpleFormatter(MediaTypeHeaderValue mediatype, Func<Stream,T> read, Action<T,Stream> write)
{
_write = write;
_read = read;
SupportedMediaTypes.Add(mediatype);
}
protected override bool CanReadType(Type type)
{
return _read != null && type == typeof (T);
}
protected override bool CanWriteType(Type type)
{
return _write != null && type == typeof (T);
}
protected override System.Threading.Tasks.Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
{
return new TaskFactory<object>().StartNew(() =>_read(stream));
}
protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
{
return new TaskFactory().StartNew(() => _write((T) value, stream));
}
public static MediaTypeFormatter CreateXmlDocumentFormatter()
{
return new SimpleFormatter<XmlDocument>(new MediaTypeHeaderValue("application/xml"),
(s) =>
{
var x = new XmlDocument();
x.Load(s);
return x;
},
(x, s) => x.Save(s));
}
public static MediaTypeFormatter CreateXDocumentFormatter()
{
return new SimpleFormatter<XDocument>(new MediaTypeHeaderValue("application/xml"),
XDocument.Load,
(x, s) => x.Save(s));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment