Where did that JSON field go? Serializing IHtmlString to JSON.

TL;DR If your brain consumes Stack Overflow questions better than blog posts, go see “How do I serialize IHtmlString to JSON with Json.NET?” over there. IHtmlString doesn’t play nicely with JSON serialization If you have an IHtmlString in your JSON (regardless of arguments against putting raw HTML in JSON), you will probably need to customize the serialization to get the HTML out of that variable. In fact, the serialization will probably be invalid compared to what you expect; it does make sense if you think about how the serialization process works. Fortunately, putting together a quick Json.NET JsonConverter will make the issue go away. What you might expect from some object containing an IHtmlString variable named x: { x = “some <span>text</span>” } What default .NET JavaScript serialization and default Json.NET serialization will give you for said object: { x = { } } How to fix it with Json.NET: public class IHtmlStringConverter : Newtonsoft.Json.JsonConverter { public override bool CanConvert(Type objectType) { return typeof(IHtmlString).IsAssignableFrom(objectType); } … public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { IHtmlString source = value as IHtmlString; if (source == null) { return; } writer.WriteValue(source.ToString()); } } Background While working on some random API, we… Continue reading

Performance Stub: getting all subtype items from a list

Performance Stubs These blog posts are simply times I wanted to identify the fastest method for accomplishing a particular goal. As I write the code, I like to make some light notes of alternatives while driving forward with the first implementation that makes it from my brain to my fingers. When I get the chance, I can go back and flesh out the two versions and drop them into some basic Stopwatch timing to determine which is better in terms of raw speed. Factoring those results with clarity of code, I have a method I will likely choose the next time I need the same feature. Goal Given a particular IEnumerable, find all the elements that are of a particular type (subclass, in this case). Method 1: Select As, Where Not Null The as operator with convert between two types with one nice tweak. If the cast cannot happen, it results in null. In this version, we massage the list by hitting all items with an as cast and then filter out the ones that didn’t cast successfully. public static IEnumerable<SubSomething> SelectAsWhereNotNull(IEnumerable<Something> source) { return source.Select(item => item as SubSomething).Where(item => item != null); } Method 2: Where Is, Cast… Continue reading

Getting dynamic ExpandoObject to serialize to JSON as expected

Serializing ExpandoObjects I am currently creating a JSON API for a handful of upcoming Sierra Trading Post projects. When I found myself generating JSON for a stripped-down representation of a number of domain classes, all wrapped with some metadata, I turned to dynamic and things have been going quite well. Unfortunately, there was a hurdle to getting the JSON to look the way I wanted. If you start playing around with serializing ExpandoObject to JSON, you will probably start finding a number of options. The easiest solution to find is the one that comes with .NET, JavaScriptSerializer under System.Web.Script.Serialization. It will happily serialize an ExpandoObject for you, but it probably won’t look the way you expect. Your searches will probably vary, but I found Newtonsoft’s JSON.NET, which handled ExpandoObject right out of the NuGet box. Then I stumbled on ServiceStack.Text (also “NuGettable”). While it does even weirder things than the .NET serializer with ExpandoObjects, it supposedly does them very fast. Test code dynamic test = new ExpandoObject(); test.x = “xvalue”; test.y = DateTime.Now; BCL JavaScriptSerializer (using System.Web.Script.Serialization;) JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string jsonOfTest = javaScriptSerializer.Serialize(test); // [{“Key”:”x”,”Value”:”xvalue”},{“Key”:”y”,”Value”:”\/Date(1314108923000)\/”}] Not quite what I was looking for but it makes sense if… Continue reading

Subtleties with using Url.RouteUrl to get fully-qualified URLs

At some point I missed the Url.RouteUrl overload that took a protocol and returned an absolute URL based on the current context. It is quite handy when you are sending URLs out into the world (e.g., RSS feed link). I ended up using the less-handy overload that took an explicit host (same as the current, in this case) and passing it in. When someone pointed out the simpler overload, I did the obvious and deleted the host from the call. That didn’t quite work. For those looking for a way to get a fully-qualified URL through the route system, the less-than-obvious answer is to call the overload for Url.RouteUrl that gets a URL with a different protocol (Url.RouteUrl(string, object, string)), passing in Request.Url.Scheme for the current protocol. Url.RouteUrl(“Default”, new { action = “Index”, controller = “Department”, id = 1 }, Request.Url.Scheme); // https://www.currentdomain.com/department/index/1 Say you want to send someone to a different subdomain in your app while using the same routes. There’s an overload for that: Url.RouteUrl(string, RouteValueDictionary, string, string). Combined with the above example, here’s how these all play out if you are currently handling a www.currentdomain.com request and your route table includes the fallback default ({controller}/{action}/{id}). Url.RouteUrl(“Default”, new… Continue reading

Handling case-insensitive enum action method parameters in ASP.NET MVC

Skip to solution Using enums as action method parameters Say you have a enum, a sorting enum in this case. public enum SortType { NewestFirst, OldestFirst, HighestRated, MostReviews } ASP.NET will gladly let you use that enum as an action method parameter; you can even make it an optional parameter. To make it optional by routing, you need to make it nullable for the action method function parameter in your controller and add some guarding logic (!sort.HasValue or the like). routes.MapRoute( “DepartmentProducts”, “Department/Products/{sort}”, new { controller = “Department”, action = “Products”, sort = UrlParameter.Optional } ); public ActionResult Products(SortType? sort) { SortType requestedSort = sort ?? SortType.NewestFirst; … } To make the parameter optional by function parameter, just give the parameter a default value. routes.MapRoute( “DepartmentProducts”, “Department/Products/{sort}”, new { controller = “Department”, action = “Products” } ); public ActionResult Products(SortType sort = SortType.NewestFirst) { … } Both work just fine, though I lean toward the function parameter default. Regardless of implementation, you can call the method by a number of different URLs: https://www.somedomain.com/department/products/ (sort == null or SortType.NewestFirst, respectively) https://www.somedomain.com/department/products/OldestFirst/ https://www.somedomain.com/department/products/HighestRated/ https://www.somedomain.com/department/products/?sort=MostReviews Unfortunately, it requires the route value to be an exact match for the enum name, proper case included…. Continue reading