What a difference a framework can make…
Rick Strahl, C# MVP extraordinaire, has released a very cool app at codepaste.net. Go and check it out, it’s quite cool.
One of the things Rick is doing is publishing a POD API that uses xml and json. And he posted on an unrelated entry an implementation of POD using MVC. For reference, here’s his snippet.
AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)]
public ActionResult PostNewCodeSnippetObject()
{
StreamReader sr = new StreamReader(Request.InputStream);
string data = sr.ReadToEnd();
sr.Close();
Snippet inputSnippet = null;
if (Request.ContentType == "text/javascript" || Request.ContentType == "application/json")
{
JSONSerializer ser = new JSONSerializer(SupportedJsonParserTypes.WestWindJsonSerializer);
inputSnippet = ser.Deserialize(data, typeof(Snippet)) as Snippet;
}
else if (Request.ContentType == "text/xml")
{
inputSnippet = SerializationUtils.DeSerializeObject(data, typeof(Snippet)) as Snippet;
}
else
return ExceptionResult("Unsuppported data input format. Please provide input content-type as text/javascript, application/json or text/xml.");
busCodeSnippet codeSnippet = new busCodeSnippet();
codeSnippet.NewEntity();
DataUtils.CopyObjectData(inputSnippet, codeSnippet.Entity, "Id", BindingFlags.Public | BindingFlags.Instance);
if (!codeSnippet.Validate())
return this.ExceptionResult("Code snippet validation failed: " + codeSnippet.ValidationErrors.ToString());
if (!codeSnippet.Save())
return this.ExceptionResult("Couldn't save new code snippet: " + codeSnippet.ValidationErrors.ToString());
return ApiResult(codeSnippet.Entity);
}
Ouch. Lot of fluff if I may say so. Let’s see what the equivalent implementation would be using OpenRasta.
The configuration:
using (OpenRastaConfiguration.Manual)
{
ResourceSpace.Has.ResourcesOfType<Snippet>().AtUri("/snippets")
.HandledBy<SnippetHandler>()
.AsJsonDataContract().And.AsXmlDataContract();
}
The handler:
public OperationResult Post(Snippet newSnippet)
{
var codeSnippet = new busCodeSnippet();
codeSnippet.NewEntity();
DataUtils.CopyObjectData(inputSnippet, codeSnippet.Entity, "Id", BindingFlags.Public | BindingFlags.Instance);
if (!codeSnippet.Validate())
return new OperationResult.BadRequest("Code snippet validation failed", codeSnippet.ValidationErrors.ToString());
if (!codeSnippet.Save())
return new OperationResult.InternalServerError("Couldn't save new code snippet", codeSnippet.ValidationErrors.ToString());
return new OperationResult.OK(codeSnippet.Entity);
}
I much prefer the latter. Don’t you?