To JSON or not to JSON?
I want to introduce some performance testing about DataContractJsonSerializer against DataContractSerializer.
But first, I want to explain what is JSON and DataContractJsonSerializer?
What is JSON?
JSON (JavaScript Object Notation) is a lightweight syntax for representing data that enabling fast exchanges of small amount of data between client browsers and AJAX-enabled Web services.
JSON encodes data using subset of the JavaScript object literals, and it easier to "parse" for JavaScript client code, and used as alternative to XML in AJAX applications.
The following sample illustrates how easy you can parse JSON in JavaScript, using 'eval' method:
var jsonText = “someVar = { 'color' : 'blue' }”;
eval( ‘(‘ + jsonText + ‘)’ );
alert(someVar.color);
DataContractJsonSerializer
With DataContractJsonSerializer introduced with WCF 3.5 you can serialize instance of .NET type into a JSON document, and de-serialize JSON document into an instance of a .NET type.
.NET Framework 3.5 include reach support of JSON in WCF. You can specify for each method if it accept/return JSON format or XML.
The DataContractJsonSerializer can be plugged by using WebScriptEnablingBehavior or by using WebHttpBehavior.
For WebScriptEnablingBehavior see the following post about WCF and ASP.NET AJAX Integration.
JsonReaderWriterFactory
WCF processes JSON messages using mapping between JSON data and the XML info-set. For that WCF use the XmlDictionaryReader and XmlDictionaryWriter produced by the JsonReaderWriterFactory, which provide an XML API over JSON.
The following JSON object:
{ “product” : “pencil”, “price” : 12 }
Translates into the following XML info-set:
<root type=“object”>
<product type=“string”>pencil</product>
<price type=“number”>12</price>
</root>
The Performance Test
I'm including two tests:
1) One customer with simple data.
| |
JSON |
XML |
JSON / XML |
| CustomerList Length |
275 |
471 |
0.5838 |
| Serialization Time |
0.18 |
0.02 |
9 |
| Deserialization Time |
0.3 |
0.1 |
3 |
2) List of 13 Customers, each contains 20 sales orders, each contains 75 sales order items.
| |
JSON |
XML |
JSON / XML |
| CustomerList Length |
1587031 |
3007061 |
0.5277 |
| Serialization Time |
294.3 |
181.4 |
1.6223 |
| Deserialization Time |
416 |
323 |
1.2879 |
Conclusion
It seems that DataContractJsonSerializer doesn't implemented in a way that adhere to the JSON as a lightweight syntax advantages over XML. But, the test should be completed, and with the end-to-end results, by parsing the data also at the browser side (JavaScript), the final results should be different.
Technorati Tags:
WCF 3.5,
AJAX,
JSON
REST Friendly URLs
Lest say you have an articles site, which have:
- Category: credit-card
- Sub Category: student
- Article Id: students-heed-parents-on-credit-card-advice
The following two samples describes the difference between friendly URLs and Dirty URLs:
Dirty URLs
http://.../article/Article.aspx?categoryId=credit-card&subCategoryId=student&articleId=student-article
http://.../Category.aspx?categoryId=credit-card
http://.../SubCategory.aspx?categoryId=credit-card&subCategoryId=student
Friendly URLs
http://.../article/credit-card/student/student-article
http://.../category/credit-card
http://.../category/credit-card/student
Why Does URL Rewriting Matter?
There are some reasons why me matter about rewriting URLs to get a clean version of them:
- Bookmaking - The URLs are part of your API in REST world, and such, client may bookmarks them or have some client programs that works with your API links. Your goal is to stay with the same URL no matter if you changing tomorrow your technology.
- Usability - Friendly URLs are easy to remember and provides cues to the user about the resource itself.
- Hide implementation details - The main reason is abstraction. The user doesn't require to know how I implemented it.
- Security - The query string which follow the question mark (?) is often modified by hackers.
- Logical URLs - If you have a site with 400,000 pages, it is not easy to maintain all of them, for example, you need to add some script for all pages..., using logical you can use only few physical pages to serve all the pages Logical URLs means that any URL in your site represents resource which is not physical but logical.
- Search Engine Optimization (SEO) - When search engine gets URL which imply that the underlying site is dynamic, and use query parameters, it treats to him different than he gets a friendly URL.
URL Rewriting with IIS 7.0
Intercepting request with IIS 7.0 is very easy:
- Implement HttpModule
- Configure it in Web.Config
The following sample is show how to remove '.svc' extension from WCF service hosted in IIS:
public void Init(HttpApplication app)
{
app.BeginRequest += delegate
{
HttpContext ctx = HttpContext.Current;
String path = ctx.Request.AppRelativeCurrentExtensionFilePath;
// …
ctx.RewritePath(path + “.svc”, …);
}
}
URL Rewriting with UrlRewriter.NET
<section
name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter"/>
</configSections>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/>
</httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule"/>
</modules>
<rewriter>
<rewrite
url="~/article/(.+)/(.+)/(.+)"
to="~/Article.aspx?categoryId=$1&subCategoryId=$2&articleId=$3"/>
<rewrite
url="~/category/(.+)/(.+)"
to="~/SubCategory.aspx?categoryId=$1&subCategoryId=$2"/>
<rewrite
url="~/category/(.+)"
to="~/Category.aspx?categoryId=$1"/>
</rewriter>
</configuration>
- The source code for Article.aspx.cs is show in the following sample:
protected void Page_Load(object sender, EventArgs e)
{
ASP.article_aspx page = sender as ASP.article_aspx;
if (page == null)
{
return;
}
String categoryId = page.ApplicationInstance.Request.Params["categoryId"];
String subCategoryId = page.ApplicationInstance.Request.Params["subCategoryId"];
String articleId = page.ApplicationInstance.Request.Params["articleId"];
Conclusion
Friendly URLs are simple to implements, and have a big rewards on this few additional lines of code. I show here two methods to use it, there are few more (ISAPI filters on IIS 6.0, HttpContext.RewritePath() in ASP.NET), but I wanted to concentrate on the better approaches.
With Friendly URLs your site links (and API) are clean, easy to remember, SEO friendly, and has abstraction level.
Presentation Tips
After my first presentation in user groups: WCF 3.5 REST Presentation I put some tips and lessons I had, so new presenters can used.
- Projector verification - If you can, verify a week before the presentation that your laptop works with the projector, or at least check if your laptop brand have problems with the specific projector.
-
Internet verification - If your presentation requires Internet, verify that you can access the internet, usually it required special request some days before.
-
Portable demos - Put all your demos also in a flash disk, so in case of problems you can move them quickly to another computer.
-
Interoperable demos - All your demos should be able to run in minimal environment, which means avoid database usage if you can.
-
Know your audience needs - Prepare the content for the audience needs.
-
Short slides - Each slide should contain no more than 3-4 lines.
-
Prepare hidden slides - Or additional notes (do not read from them!!) since when you look on a slide with 3 lines, you may forget some additional issues you want to talk about.
-
Manage your time wisely - Prepare by talking about each issue and measure the time each issue take, so you promise you have enough to talk. It is ok to finish before time, just be aware to it.
-
Practice at home - Before the real presentation, you should practice your speech in front of some friends at home, prefer those with appropriate background so they can ask questions, write the question, and prepare to them. If they haven't appropriate background, it is still better than nothing.
-
Review your presentation - Send your presentation to friends for review, it can help to see thinks you didn't see. Also you should spend time to review the presentation design and flow.
-
Time to arrive - Arrive at least one hour before the presentation to setup the projector and internet, and verify all the demos works appropriately.
-
Master your presentation - Prepare to any question.
-
Presentation prepared - Finish the presentation and demos some days before the date, so you can practice speech.
-
Listen to the audience - Be aware when they don't understand something, boring, etc.
Do you have something to share from your experience?