by Njål

String replaceAll in Javascript

imageIn Javascript the string.replace(“target”, ”replacement”) function only replaces the first occurrence of the target…

Here’s how you can add a replaceAll() metod to all Strings (similar to Extension Methods in C#).

String.prototype.replaceAll = function (orig, replacement) {
    return this.split(orig).join(replacement);
}

 

You can then write (anywhere in your code):

"a a b c".replaceAll("a","X"); //==> "X X b c"
by Stian

Correct content type for JSON

When I Google around searching for any code snippets I might need for inspiration (or plain copy-paste), I see a lot of different use of MIME type for JSON in examples and existing code out there.

Examples of types found with a quick JSON google search:

application/json
application/x-javascript
text/javascript
text/x-javascript
text/x-json

You could of course argue that the reason for this is that the browsers do have a bit of history when it comes to supporting “standards”, but there is only one correct media type for JSON:

Content-Type: application/json

You can find this registered at IANA (Internet Assigned Numbers Authority), take a look here.

What about JSONP?

Since we are on the subject, you might also be wondering what the correct content type for JSONP is, because this is different. JSONP returns JavaScript and the correct usage would be

Content-Type: application/javascript

If you find this useful or in any way disagree, holla at me!

by Andreas

Converting JSON date string to javascript date object

JSON dates come in a format that isn’t directly convertable to Javascript date objects (e.g. /Date(1349301600000+0200)/ ). This can cause a bit of headache, but there is a very simple way to convert this to a native date object.

After stripping off the initial “/Date” part using substr, parseInt will return only the integers and ignore the trailing “/”. The result is an integer value that can be used in the native javascript Date constructor.

This is what goes on under the hood:

1. Original JSON date

/Date(1349301600000+0200)/

 

2. After substr(6)

1349301600000+0200)/

 

3. After parseInt()

1349301600000

 

Finally I am using DatePicker from the jQuery UI library to format the date to a custom JSON date:

// parse JSON formatted date to javascript date object
var date = new Date(parseInt(jsonDate.substr(6)));

// format display date (e.g. 04/10/2012)
var displayDate = $.datepicker.formatDate("mm/dd/yy", date);

 

On the server side I recommend using the Json.NET framework by James Newton-King (available as a NuGet). It contains several settings for handling dates depending on what you’re running client side. If you’re using KnockoutJS for instance, the ko.toJSON method will return your date object in UTC format (which means the date might suddenly be a day off, with an offset set to +2 hours my current timezone).

My quick-fix using DateTime.ToLocalTime() will work, but I am sure there is a more elegant way of getting your local time directly in the Json deserialization process:

// parse JSON
var timeRec = JsonConvert.DeserializeObject<JSONTimeRecord>(jsonString, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// convert date to local time
updatedRecord.Date = timeRec.Date.ToLocalTime();

 

At least that works fine – for now..

by Andreas

Jquery + JSON: IE8/IE9 treats response as downloadable file

We’ve recently been working with the pretty brilliant web based elFinder file manager. This component has a truckload of features, but for a very specific function (uploading files through the web browser) we came across a tricky problem. Upon receiving a JSON response from an HTTP handler (.asxh) Internet Explorer 8 triggered the following warning:

To Help Protect Your Security, Internet Explorer has blocked this website from displaying content with security certificate errors. Click here for options…

image

After opting for “Download file”, subsequent responses just triggered the “Save file” dialog box. The contents of this file was the perfectly fine JSON response, but this was not understood by Internet Explorer 8. In Internet Explorer 9 the warning was supressed and the response seemed to simply be ignored, leaving our jQuery component waiting for its JSON reply in vain. Chrome, Opera and Firefox had no issues, and processed the response as pure JSON.

After a fair bit of research trying to find the bug both server and client side, it turned out that Internet Explorer didn’t like that the Content-Type in the response header was "application/json”. Setting the Content-Type to “text/html” specifically for IE in the .asxh handler before returning the JSON response did the trick. It now works as expected across all browsers.

A simple method checks the browser and updates the content type if applicable (note: this is just an extract):

        private static string SetContentTypeBasedOnBrowserAndCommand(HttpContext context)
        {
            var contentType = "application/json"; // default
            // if browser is IE
            if (DegreeCore.Util.BrowserUtil.IsIE(context.Request.Browser))
            {
                // override response
                 contentType = "text/html";
            }

            return contentType;

        }

 

The non-reversible hair loss from occational problems like this has yet again been put on hold – for now.

Tags: ,
by thorhalvor

JSONP in ASP.NET MVC 3

When consuming a JSON REST API using AJAX the message is send as a XMLHttpRequest. Due to security reasons this is not allowed cross domain. Instead of returning the data as core JSON, JSONP is often used. The data will then not be parsed by the JSON parser but evaluated by the JavaScript interpreter.

Returning JSONP data does not come out of the box in ASP.NET MVC 3, but you can write a simple wrapper like this:

using System.Web.Mvc;
 
public class JsonpResult : JsonResult
{
    private const string CALLBACK_QUERYSTRING = "callback";
    private const string CALLBACK_CONTENTTYPE = "application/x-javascript";
 
    public override void ExecuteResult(ControllerContext controllerContext)
    {
        if (controllerContext != null)
        {
            var request = controllerContext.HttpContext.Request;
            object callback = request[CALLBACK_QUERYSTRING];
            if (callback == null)
            {
                controllerContext.RouteData.Values.TryGetValue(CALLBACK_QUERYSTRING, out callback);
            }
 
            var hasCallback = !string.IsNullOrWhiteSpace(callback ==null ? "" : callback as string);
 
            if (hasCallback)
            {
                SetContentTypeIfEmpty();
                var response = controllerContext.HttpContext.Response;
 
                response.Write(callback);
                response.Write("(");
                base.ExecuteResult(controllerContext);
                response.Write(")");
            }
            else
            {
                base.ExecuteResult(controllerContext);
            }
        }
    }
 
    private void SetContentTypeIfEmpty()
    {
        if (string.IsNullOrWhiteSpace(base.ContentType))
        {
            base.ContentType = CALLBACK_CONTENTTYPE;
        }
    }
}

 

It is now possible to just replace the jsonresult with jsonpresult in the code. If no callback is given it will work as normal.

        //return new JsonResult();
        return new JsonpResult();

 

When sending the request GET http://localhost/Website/Products/All?callback=myCallbackFunction the data will be wrapped like this: (same method used in last blogpost)

jsonp

by thorhalvor

Asp.NET MVC 3 and JSON

Creating a ASP.NET MVC 3 REST API returning JSON data is actually really simple.

If you have a MVC 3 Visual Studio project template and you add a Controller the default HomeController will be added:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

 

If you want this Index to return Json data the only thing needed is return JsonResult instead of a View.

        //return View();
        return new JsonResult();

 

To give an example I have created a ProductsController returning 3 products with the properties ProductId, Name and Price.

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult All()
{
    var data = GetProducts();
    return new JsonpResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Notice that you have to set JsonRequestBehavior.AllowGet. If forgotten you will get the self-explanatory errormessage:

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. 
To allow GET requests, set JsonRequestBehavior to AllowGet.

 

When sending the request GET http://localhost/Website/Products/All, the method will return my three products:

(using Chrome with the extension JSONView)

json

As simple as that Smile

by thorhalvor

My favorite Web Application Architecture

This is my first blogpost and I thought I should start writing about the web application architecture i normally choose these days, –if I am allowed by the client to refactor or start from scratch. Hopefully more blogposts will come out of this.

The first thing I do is splitting the Web Application in a html part and a JSON REST API part. Typically the Visual Studio folder structure looks like this:

  • WebApplication1.WebSite
  • WebApplication1.RestApi
HTML

I use the Razor viewengine in combination with Knockout.js to write the databinding and other than this the HTML is mostly consisting of a bunch of DIVs and script elements with jquery $.get or $.post’s. Normally I am that lucky in projects that I do not have to care about the “colors and stuff”, there is normally another guy taking care of the CSS. My main focus is therefore to get the databinding right and have a nice and clean architecture “downwards”.

REST API

I design the REST API service methods with the view in mind. So instead of having a super-generic method that works for “all web pages” I rather have several specific ones. I want to have as little logic in the client side as possible. I can then design my viewmodel-classes to consist of just the data needed, both translated and formated the way i want.

CQRS style: When working with the REST API I like to split the GET and POSTs as done in CQRS.

  • The GET-methods are fetching data from the database through a simple ORM like for example: EF, Dapper, Massive or Simple.Data. If working with a documentdatabase as for example RAVENDB the queries will go directly to its DocumentSession.
  • The POST-methods will have the business logic and sometimes be long running processes. A reliable service bus as nServiceBus is therefore to prefer. When working with long running and asynchronous processes special care must be taken when designing the UserInterface (HMTL pages). They can normally not be designed as done when working with request-response-based applications.
Environment:

If the team developers are writing tests and the application above is on GitHub using TeamCity with Continuous Deployment, then my day is perfect!