Created
November 30, 2012 23:41
-
-
Save mikeobrien/4179548 to your computer and use it in GitHub Desktop.
Replace XML Serializer Fubu
This file contains hidden or 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
public class Conventions : FubuRegistry | |
{ | |
public Conventions() | |
{ | |
Policies.Add(x => x.ModifyBy(y => y.AddSymmetricFormatter<MyNewXmlFormatter>(), ConfigurationType.Attachment)); | |
} | |
} | |
public static class Extensions | |
{ | |
public static BehaviorChain AddSymmetricFormatter<T>(this BehaviorChain chain) where T : IFormatter | |
{ | |
if (chain.InputType() != null) chain.Input.AddFormatter<T>(); | |
if (chain.HasResourceType() && !chain.Output.Writers.Any(y => y is ViewNode)) | |
chain.Output.AddFormatter<T>(); | |
return chain; | |
} | |
} | |
[MimeType(new[] { "text/xml", "application/xml" })] | |
[Title("Xml Serialization")] | |
public class MyNewXmlFormatter : IFormatter | |
{ | |
public readonly static string[] MimeTypes = new [] { "text/xml", "application/xml" }; | |
private readonly IStreamingData _streaming; | |
private readonly IOutputWriter _writer; | |
public XmlFormatter(IStreamingData streaming, IOutputWriter writer) | |
{ | |
_streaming = streaming; | |
_writer = writer; | |
} | |
public IEnumerable<string> MatchingMimetypes { get { return MimeTypes; } } | |
public void Write<T>(T target, string mimeType) | |
{ | |
var serializer = new XmlSerializer(typeof(T)); | |
_writer.Write(mimeType, stream => serializer.Serialize( | |
new XmlTextWriter(stream, Encoding.Unicode) { Formatting = Formatting.None }, target)); | |
} | |
public T Read<T>() | |
{ | |
return (T)new XmlSerializer(typeof(T)).Deserialize(new StreamReader(_streaming.Input, true)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment