Scott Hanselman

Tiny Happy Features #2 - ASP.NET Web API in Visual Studio 2012

August 10, '12 Comments [15] Posted in ASP.NET | ASP.NET Web API | Javascript | Open Source | Tiny Happy Features | VS2012
Sponsored By

REST, POX, and WCF compared to RESTtafarians, a guy with a bag on his head and Darth Vader

(UPDATE: See other Tiny Happy Features)

At some point soon lots of people are going to start writing these epic blog posts about Visual Studio 2012. They will include LOTS of screenshots (some good and some bad), some small code samples and minimal context. I can't speak for other teams; I can only talk about what we worked on. The <AngleBrackets/> folks in Azure Platform and Tools (ASP.NET, IIS, WCF, EF, Azure much and more) have been putting a lot of work into what I sometimes call "Death by a Thousand Tiny Cuts." It's the little irritants that are as frustrating (or more so) as the big missing features.

Rather than a giant super post (although I'll do that at some point) I thought I'd showcase some Tiny Happy Features that the team worked on just because it made life better. Some are large some are small, but all are tiny happy features.

There's Enterprise Web Services that use SOAP and WS-*.* and they are great for many transactional or complex scenarios. Then there are lighter weight RESTful web services or "Web APIs" that use JSON, XML and respect all of the goodness and stability that is the HTTP specification.

WCF is alive and well and ASP.NET is alive and well and there are reasons to use each technology. As this article says very well, "The world of SOAP and the world of HTTP services are very different. SOAP allows us to place all the knowledge required by our service in the message itself" vs. "you can use [Web APIs] to create HTTP services that only use the standard HTTP concepts (URIs and verbs), and to to create services that use more advanced HTTP features – request/response headers, hypermedia concepts etc."

Kelly Sommers wrote what I consider the best explanation of REST out there in "Clarifying REST." Whether you want to write RESTful resource-focused HTTP services or just POX or POJ (Plain Old XML or Plain Old JSON) services, you can do both with ASP.NET Web API. It's all part of the ASP.NET open source web stack.

Rick Strahl says that ASP.NET Web API is different than other frameworks because "it was built from the ground up around the HTTP protocol and its messaging semantics. Unlike WCF REST or ASP.NET AJAX with ASMX, it’s a brand new platform rather than bolted on technology that is supposed to work in the context of an existing framework. The strength of the new ASP.NET Web API is that it combines the best features of the platforms that came before it, to provide a comprehensive and very usable HTTP platform."

I encourage you to check out Rick's excellent analysis. Here's the features of ASP.NET Web API Rick likes:

  • Strong Support for URL Routing to produce clean URLs using familiar MVC style routing semantics
  • Content Negotiation based on Accept headers for request and response serialization
  • Support for a host of supported output formats including JSON, XML, ATOM
  • Strong default support for REST semantics but they are optional
  • Easily extensible Formatter support to add new input/output types
  • Deep support for more advanced HTTP features via HttpResponseMessage and HttpRequestMessage
    classes and strongly typed Enums to describe many HTTP operations
  • Convention based design that drives you into doing the right thing for HTTP Services
  • Very extensible, based on MVC like extensibility model of Formatters and Filters
  • Self-hostable in non-Web applications 
  • Testable using testing concepts similar to MVC

ASP.NET Web API

There's some lovely new samples at this Git Repository. Just "git clone https://git01.codeplex.com/aspnet" or download the zip. You can also familiarize yourself with ASP.NET and the Web API at the new http://www.asp.net/webapi site.

By the way, I'll be publishing a bunch (13!) of new videos showcasing Web API plus a lot of other Tiny Happy Features next week on the 15th. Each video will only be 5 minutes long and will be a great way to get up to speed on all the new tech over lunch.

To use the samples, follow the instructions on Henrik's blog post announcing them.

Here's one nice little sample that will perhaps cause you to rethink what you can accomplish with ASP.NET web technologies. It's a console application that hosts ASP.NET Web API. To be clear, there's no IIS involved.

In the setup instructions we have to register a port and user with HTTP.sys so the Operating System knows it's OK for send our little self-hosted app HTTP traffic. If you're familiar with WCF you may have done this before.

Here's the server. It's a Console App, minus error handling for clarity.

class Program
{
static readonly Uri _baseAddress = new Uri("http://localhost:50231/");

static void Main(string[] args)
{
// Set up server configuration
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

// Create server
var server = new HttpSelfHostServer(config);

// Start listening
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + _baseAddress + " Hit ENTER to exit...");
Console.ReadLine();
server.CloseAsync().Wait();
}
}

That code sets up a route, starts the self-hosting process, and waits. Here's a controller at http://localhost:50231/Contact that will ECHO whatever contact you HTTP POST to it as content-type JSON. Note that Contact is a C# type as a parameter to Post().

public class ContactController : ApiController
{
public Contact Post(Contact contact)
{
return contact;
}
}

If I want, I can do a POST from another command line using curl and send some JSON into the server.

POSTing JSON from CURL to ASP.NET Web API

Here's the actual command line. The JSON is echo'ed back.

C:\>curl -X POST -H "Content-Type: application/json" -d "{ Name: 'Scott Guthrie', Age: 67}" http://localhost:50231/api/Contact

That's from the command line but I can also use System.Net.Http.HttpClient to make a call from .NET if I like:

HttpClient client = new HttpClient();

Contact contact = new Contact {
Name = "Henrik",
Age = 100
};

// Post contact
Uri address = new Uri(_baseAddress, "/api/contact");
HttpResponseMessage response = await client.PostAsJsonAsync(address.ToString(), contact);

// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();

// Read result as Contact
Contact result = await response.Content.ReadAsAsync<Contact>();

Console.WriteLine("Result: Name: {0} Age: {1}", result.Name, result.Age);

See how the C# Contact object moves back and forth between the JSON world and C# world easily? That's the JSON.NET open source library making that happen.

JSON and JavaScript is really dynamic, though, and often it's a hassle to try to "deserialize" really dynamic JSON objects into strongly-typed .NET structures. JSON.NET and ASP.NET Web API's model binding offer a happy medium - a middle ground - called JToken.

public class ContactController : ApiController
{
public JToken Post(JToken contact)
{
return contact;
}
}

Check out the watch window as the JSON comes in:

Using JToken to catch a JSON payload

Using JToken gives me a dynamic container but also a DOM-like navigation model. But if that's not dynamic enough for me, why can't my method's parameter just take a "dynamic."

C# is statically typed, sure, but that doesn't mean I can't statically type something dynamic. ;)

Again, note the watch window.

Using dynamic to catch JSON post payloads

See how JSON is moving around the system without any impedance mismatch. The power of C# isn't slowing down the flexibility of JavaScript and JSON.

It makes me happy when things work as they should.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

ASP.NET for Mobile, One ASP.NET and Realtime ASP.NET with Signalr - Video of Scott Hanselman's talks in Russia

June 5, '12 Comments [24] Posted in ASP.NET | ASP.NET MVC | Javascript | SignalR | Speaking
Sponsored By

Hey that says Scott Hanselman in Russian!I was outside Moscow last week speaking at Microsoft DevCon 12 in Russia. They did a great job with the event and not only filmed everything but did picture in picture as well as real-time translation into Russian. It was also live streamed at the team and later edited for download. Very cool. Big thanks to the team for putting the videos up so fast!

The English versions of my three talks (plus one open Q&A sesssion) are now all up for your viewing pleasure. If it seems I'm speaking ever so slightly slower than usual, that was at the request of the translators, and is a good practice when speaking English to non-native speakers.

You can also download and view the Russian versions if you like as well.

ASP.NET for Mobile Phones and Tablets

The ASP.NET for Mobile Phones and Tablets video

Download links:

SignalR and the Realtime Web

The SignalR and the Realtime Web video

Many problems, many solutions: One ASP.NET

The Many problems, many solutions: One ASP.NET keynote video

Open question and answer session – Ask Scott Hanselman

The Open question and answer session – Ask Scott Hanselman video

Hope you enjoy them!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Visual Studio 11 Express for Web for Front End Development - JavaScript/HTML5/CSS3

April 14, '12 Comments [24] Posted in HTML5 | Javascript | Open Source
Sponsored By

I wanted to work through a new tutorial by former Microsoftie, now Googler Pete LePage along with Chris Wilson. They have a great lab called "WReader" that uses Ember, HTML5 Boilerplate, Moment.js, Bootstrap CSS and LawnChair.js that builds a single page JavaScript application over 12 exercises.

A few weeks ago a non-Microsoft developer saw a post I did on some new HTML5, CSS3 and JavaScript features in VS11 and mentioned he might want to use it over Dreamweaver. I thought that was cool because some client-side developers think VS is all server-side and too "industrial strength."

I wanted to see if VS11 Express Web (the free version) would work well for "front end" web development. This lab that Pete made is all client-side. It doesn't use ASP.NET or anything server-side that Visual Studio is typically built for. However, a lot of work has been done in Visual Studio lately to make web development easier and I wanted to see if it stood up, even when doing all client-side HTML/CSS/JS.

I downloaded Pete's Lab, opened Visual Studio and when Open Web Site and opened the first Exercise's folder.

Opening a folder as a web site

I right-clicked on Index.html and set it as the Startup Page for my project. You can set any page you like a the startup page and they Ctrl-F5 (or a button in the toolbar) will launch the browser without server-side debugging.

At the end of Exercise 2 you will have dynamically created feed items and bound them with a client-side template. Here's a screenshot of what that looks like.

Excercise Two completed and I've got a list of 10 RSS feeds in a list.

While I was typing up this exercise there were a few nice things about VS that made the experience pleasant. The JavaScript editor in VS11 is greatly improved and is actually running the JavaScript in the background as you are running it, so the intellisense autocomplete help is very useful, especially for a JavaScript newbie. It doesn't get everything, but it's VERY smart.

Nice JavaScript intellisense improvements in VS11

There are times when you're working in a JavaScript file that needs to know about objects in another file but the editor can't figure it out. You can add a "hint" or reference so Visual Studio can be smarter for you.

For example, I was using this Ember.js object and wasn't getting any help so intellisense just added all the info that it had.

Ember in VS without intellisense

You can drag a file from the Solution Explorer into your JavaScript file to make a comment that acts as a reference/hint to Visual Studio like this: /// <reference path="libs/ember-0.9.5.js" />. You can see the results below.

Ember in VS with intellisense

If adding that line bugs you, you can put all your references in a _references.js file and never look at it.

This was helpful to me when I got to adding moment.js as I could see what methods my Date had available:

Intellisense available on dates with VS11 and moment.js

Later in Exercise 2 I make a client-side JavaScript template like this with "mustache/handlebar style" expressions like {{ }}:

<section class="mainContent">
  <section class="summaries">
      <script type="text/x-handlebars">
      {{#each WReader.dataController}}
          {{#view WReader.SummaryListView contentBinding="this"}}
              {{content.title}} from {{content.pub_name}} on {{content.pub_date}}
          {{/view}}
      {{/each}}
      </script>
  </section>
</section>

However, Visual Studio syntax highlighting didn't look useful/pretty to me. This seemed like an opportunity to make it better.

A mustache template without syntax highlighting

I mentioned in an earlier post that we have the ability now to update the web editors (HTML, CSS, and JS) easier and more often now as the editors bits are implemented as extensions themselves. I asked the owner Mads Kristensen to prototype what "mustache" template syntax highlighting could/might/would look like if we did it. We'd want all the general templating libraries to work, like Mustache, HandleBars, JsRender, and others, even if templating as a concept changes or disappears.

Here's some of the prototype work he did tonight. This would make my client-side experience just a little nicer. These are screenshots of the private build he is messing with and he's trying different colors.

An example mustache template with highlighting

I like this one the best. I'm not digging the yellow. I like this more subtle approach.

A nice subtle mustache template

I was testing this lab on multiple browsers and switching back and forth between the Chrome Developer Tools and the Internet Explorer Developers Tools (F12). There's a nice feature in Visual Studio 11 that lets you quickly run your project in different browsers with this dropdown:

All your installed browsers in a list

But sometimes you want to run multiple browsers at the same time. There's a little known feature (I'm working with the team on making this more discoverable) where you can right-click on an HTML file and click Browse With, then "Ctrl-Select" multiple browsers:

browsewith

If you click Set as Default while there are multiple browsers selected it will change your toolbar and menu to say "Multiple Browsers." CTRL-F5 will then launch more than one browser at the same time.

Multiple Browsers selected in the toolbar

The UI is a little rough now but it's being improved. It's a really nice little feature and a time saver!

Later in the tutorial Pete includes the Twitter Bootstrap CSS and I wanted to change some of the default colors. You can click a color in the CSS editor and edit it interactively like this. It even does opacity.

The VS11 Color Picker for CSS Colors

I encourage you to go check out Pete's tutorial if you're interested in learning more about JavaScript, HTML5, Ember.js (and frameworks like it) and this emerging style of web development.

Related Links

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

The Big Glossary of Open Source JavaScript and Web Frameworks with Cool Names

April 13, '12 Comments [38] Posted in ASP.NET | Javascript | Open Source
Sponsored By

Photo via Dmitry Baranovskiy and used under Creative Commons - http://flic.kr/p/4CdjpjIt's getting to the point where there are so many cool open source projects that I can't keep up. When you add in the currently battle royale of JavaScript projects that are basically just hip sounding words with ".js" added to the end, it's a little overwhelming. Seriously, just pick a word out of the dictionary at random and that's the name of an up and coming JavaScript library.

JavaScript MVC Frameworks and Libraries

This is an area that is very interesting but also very not-yet-baked. In the DOM manipulation and CSS selector space, jQuery won. That fight is over. The next big question is client side MVC frameworks. It seems everyone wants to make the next "Rails" framework on JavaScript and while there are some contenders, there's still lots of room for someone to "win."

DOM manipulation libraries like jQuery are important, but it's clear that making large and rich web applications requires more than just jQuery. More and more applications want smart asynchrony and dynamic loading.

(Reminder: All this IS overwhelming. That doesn't mean you need to know all these frameworks or feel bad that you don't know them all. Just accept that you DON'T know them all. Be OK with that.)

Here's the major players and ones you might want to be familiar with. Remember, these are client side libraries and while they often mention server-side frameworks like node or rails, these are things written in JavaScript that anyone can use.

  • Ember.js - Attempts to remove tedious boilerplate code. Includes a templating engine (no one will agree on just one), encourages an architecture where the browser does most of the work, supports state-management out of the box. Focus on computed properties, and templates that update themselves.
  • Underscore .js - A library of more than 60 functions to make JavaScript more fun and easier to use. Provides a layer that will use a modern browser's native implementation of a method while still supporting older browsers. Has iterators like each, map, reduce, etc. In a way, it's like LINQ for JavaScript.
  • JavaScriptMVC - A jQuery-friendly framework that adds functional testing, MVC plugins, documentation generation, dependancy management and build tools.
  • Spine.js - Seems like less than a Backbone (these libraries all play with each other's names). Introduces models and controllers, but for views, requires you use your own template engine. Intends to be super lightweight.
  • Backbone.js - Everyone loves Backbone. It's the one you'll hear about the most. There's a large community supporting it. Folks have said that large applications can get a little hairy and difficult to manage, though. Lots of great docs and examples.
  • Knockout.js - MVVM on the client rather than MVC. Lots of interesting client-side data-bind expressions. Rich documentation.
    • And, wait for it, Knockback.js, a library that bridges the gaps between Knockout and Backbone and encourages you to use both effectively.
  • Sammy.js - A very small core library that brings in other adapters and plugins to give you just the parts you need. Focused on developer happiness. Works well with apps that are sitting on top of RESTful JSON server sides.
  • Angular.js - Includes templates, two-way data-binding and MVC, again, all on the client. Very small and starting to make a splash.
  • SproutCore - SproutCore seems to be very complete and more prescriptive than other frameworks. It also has a focus on making apps on tablets and other devices. The NPR for Chrome app used them.
  • Cappuccino - If you like and think in Objective-C, you'll like Cappuccino and Objective-J. Cappuccino is kinda of Cocoa (Mac APIs) for the web.
  • Google Closure - Almost doesn't belong in the list as it's a very complete toolkit with a whole worldview, rich library, templates, and lots of extras. You can choose how much you want to embrace, though.
  • ExtJS4 - This is a Sencha product and now on its fourth major release. It includes not only a framework and architecture but also widgets and charts.
  • PureMVC - Another MVC on the client side implementation, but this one was ported from ActionScript. It was originally used on Adobe Air and the like.
  • Batman.js - Bonus points for the best name. Explicitly embraces CoffeeScript as well as JavaScript. Only 2000 lines and very few extras. Very Rails friendly, prescriptive without being oppressive.
  • Require.js - A JavaScript file and module loader.
  • PrefixFree.js - A nice library that expands all your CSS to use the explosion of vendor prefixes correctly.
  • Lawnchair.js - Client-side storage and persistence. Less than a couch, but smaller and outside.
  • Mustache - Templates for views, explicitly without logic.
var view = {
title: "Joe",
calc: function () {
return 2 + 4;
}
};

var output = Mustache.render("{{title}} spends {{calc}}", view);
  • Handlebars.js - An superset of the Mustache template concept with extra features. A fancier mustache. Ahem, "Handlebar Mustache."

Also checkout Gordon Hempton's excellent "consumer reports" table on his blog that covers which JavaScript frameworks support which features.

ASP.NET Libraries, Frameworks and Open Source Projects

You may have heard that ASP.NET MVC 4, ASP.NET Web API and ASP.NET Web Pages v2 (Razor) are all now open source with contributions. They are up on CodePlex using Git. I thought I'd mention some interesting ASP.NET/CLR server side libraries here also as that's the area I work in.  There are thousands of Open Source projects in the .NET space, but I wanted to take a moment and feature these as they are all related and all emerging.

Just like the JavaScript projects above, these .NET projects are all trying to innovate...trying to make something new and modern and compelling without sacrificing the good things about the past.

  • OWIN - This is the "open web interface for .net." It represents the "spec" of the web app function signature. It serves the same purpose as Rack spec on Ruby or WSGI on Python. "The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools."
  • Gate - An OWIN Reference implementation of utilities, host handlers, and web framework adapters for OWIN. This is essentially glue code, with things like Gate.Hosts.Kayak.dll on one hand, and Gate.Adapters.Nancy.dll on the other, to fit together your stack, e.g. "Kayak->Owin->Nancy"
  • Nancy - A "Sinatra" inspired framework. "Nancy is a lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono. The goal of the framework is to stay out of the way as much as possible and provide a super-duper-happy-path to all interactions."
  • Kayak - A 100% C# HTTP Server assembly that can be embedded in your project. "Kayak is an asynchronous HTTP server written in C#. It has been designed to be easy to embed into a variety of applications. Kayak natively supports the OWIN 1.0 Draft specification."
  • Firefly - Another 100% C# HTTP server assembly.
  • Manos - A 100% C# HTTP server in an assembly that is a part of a larger Manos web server + web framework bundle.
    (web frameworks with owin adapters:)
  • AspNetWebApi - A framework optimized for HTTP APIs and services. Part of the open source ASP.NET Web Stack.
  • SignalR -  A socket.io-like message bus that supports realtime communication over Web Sockets, long polling, forever frame, or server sent events. JavaScript and Server-side components.
  • Fubu - A MVC-inspired framework with the beginnings of some OWIN support.
  • OpenRasta - A development framework for building web-based applications and services. Focused on being RESTful.

There is no question that I've missed some. Leave them in the comments and I'll keep this post updated. Projects for this list should be of some renown and be pushing the envelope in some notable way.

Big thanks to Louis DeJardin for his help and bootstrapping the list.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

On the nightmare that is JSON Dates. Plus, JSON.NET and ASP.NET Web API

March 6, '12 Comments [69] Posted in ASP.NET | Javascript | Open Source
Sponsored By

Ints are easy. Strings are mostly easy. Dates? A nightmare. They always will be. There's different calendars, different formats. Did you know it's 2004 in the Ethiopian Calendar? Yakatit 26, 2004, in fact. I spoke to a German friend once about how much 9/11 affected me and he said, "yes, November 9th was an amazing day in Germany, also."

Dates are hard.

If I take a simple model:

public class Post
{
public int ID { get; set; }

[StringLength(60)][Required]
public string Title { get; set; }

[StringLength(500)]
[DataType(DataType.MultilineText)]
[AllowHtml]
public string Text { get; set; }

public DateTime PublishedAt { get; set; }
}

And I make a quick ASP.NET Web API controller from VS11 Beta (snipped some stuff for simplicity):

public class PostAPIController : ApiController
{
private BlogContext db = new BlogContext();

// GET /api/post
public IEnumerable<Post> Get()
{
return db.Posts.ToList();
}

// GET /api/post/5
public Post Get(int id)
{
return db.Posts.Where(p => p.ID == id).Single();
}
...snip...
}

And hit /api/post with this Knockout View Model and jQuery.

$(function () {
$("#getPosts").click(function () {
// We're using a Knockout model. This clears out the existing posts.
viewModel.posts([]);

$.get('/api/PostAPI', function (data) {
// Update the Knockout model (and thus the UI)
// with the posts received back
// from the Web API call.
viewModel.posts(data);
});
});

viewModel = {
posts: ko.observableArray([])
};

ko.applyBindings(viewModel);
});

And this super basic template:

<li class="comment">
<header>
<div class="info">
<strong><span data-bind="text: Title"></span></strong>
</div>
</header>
<div class="body">
<p data-bind="date: PublishedAt"></p>
<p data-bind="text: Text"></p>
</div>
</li>

I am saddened as the date binding doesn't work, because the date was serialized by default like this. Here's the JSON on the wire.

[{
"ID": 1,
"PublishedAt": "\/Date(1330848000000-0800)\/",
"Text": "Best blog post ever",
"Title": "Magical Title"
}, {
"ID": 2,
"PublishedAt": "\/Date(1320825600000-0800)\/",
"Text": "No, really",
"Title": "You rock"
}]

Eek! My eyes! That's milliseconds since the beginning of the Unix Epoch WITH a TimeZone. So, converting in PowerShell looks like:

PS C:\> (new-object DateTime(1970,1,1,0,0,0,0)).AddMilliseconds(1330848000000).AddHours(-8)

Sunday, March 04, 2012 12:00:00 AM

Yuck. Regardless,  it doesn't bind with KnockoutJS either. I could add a bindingHandler for dates like this:

ko.bindingHandlers.date = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var jsonDate = valueAccessor();
var value = new Date(parseInt(jsonDate.substr(6)));
var ret = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
element.innerHTML = ret;
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
}
};

That works, but it's horrible and I hate myself. It's lousy parsing and it doesn't even take the TimeZone into consideration. This is a silly format for a date to be in on the wire.

Example of Knockout binding

I was talking to some folks on Twitter in the last few days and said that all this is silly and JSON dates should be ISO 8601, and we should all move on. James Newton-King the author of JSON.NET answered by making ISO 8601 the default in his library. We on the web team will be including JSON.NET as the default JSON Serializer in Web API when it releases, so that'll be nice.

I mentioned this to Raffi from Twitter a few weeks back and he agreeds. He tweeted back to me

He also added "please don't do what the @twitterAPI does (ruby strings)." What does that look like? Well, see for yourself: https://www.twitter.com/statuses/public_timeline.json in a random public timeline tweet...snipped out the boring stuff...

{
"id_str": "176815815037952000",
"user": {
"id": 455349633,
...snip...
"time_zone": null
},
"id": 176815815037952000,
"created_at": "Mon Mar 05 23:45:50 +0000 2012"
}

Yes, so DON'T do it that way. Let's just do it the JavaScript 1.8.5/ECMASCript 5th way and stop talking about it. Here's Firefox, Chrome and IE.

All the browsers support toJSON()

We're going to do this by default in ASP.NET Web API when it releases. (We aren't doing this now in Beta) You can see how to swap out the serializer to JSON.NET on Henrik's blog. You can also check out the Thinktecture.Web.Http convenience methods that bundles some useful methods for ASP.NET Web API.

Today with the Beta, I just need to update my global.asax and swap out the JSON Formatter like this (see Henrik's blog for the full code):

// Create Json.Net formatter serializing DateTime using the ISO 8601 format
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
GlobalConfiguration.Configuration.Formatters[0] = new JsonNetFormatter(serializerSettings);

When we ship, none of this will be needed as it should be the default which is much nicer. JSON.NET will be the default serializer AND Web API will use ISO 8601 on the wire as the default date format for JSON APIs.

ISO Dates in Fiddler

Hope this helps.


Sponsor: Big thanks to DevExpress for sponsoring this last week's feed. There is no better time to discover DevExpress. Visual Studio 11 beta is here and DevExpress tools are ready! Experience next generation tools, today.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb
Previous Page Page 5 of 23 in the Javascript category Next Page

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.