Archive

Posts Tagged ‘JSON’

jQuery File Upload: IE9 and ASP.Net Web API File Uploading

June 2nd, 2016
No comments

    The blueimp jQuery File Upload plugin uses the XMLHttpRequest to pass the file data to a server (only IE10+). If browser doesn’t support Ajax file uploading, the plugin makes a workaround by dynamically creating IFrame and sending the data on behalf of it through the traditional form POST. The JavaScript responsible for the workaround resides in jquery.iframe-transport.js, which accompanies the basic jquery.fileupload.js. The following TypeScript code could be used to initialize the plugin and submit file data (the code is intentionally kept as simple as possible – no progress bars, validations and so on):

//...
private fileData: any = {};
//...
$(".filePicker").fileupload({
	autoUpload: false, // will be submitted once button is clicked
	method: "PUT",
	dataType: "json", 
	url: "api/someController/someMethod", // Web Api method to receive and process the file
	formData: () => { // additional parameters accompanying the file data
		return [{
			name: "bookName",
			value: $("#bookName").val()
		},
		{
			name: "bookGenre",
			value: $("#bookGenre").val()
		},
		{
			name: "bookAuthor",
			value: $("#bookAuthor").val()
		}];
	},
	add: (e: JQueryEventObject, data: any) => { // event handlers
		this.fileData = data;
		//...
	},
	done: (e: JQueryEventObject, data: any) => {
		//...
	},
	fail: (e: JQueryEventObject, data: any) => {		
		//...
	},
	always: (e: JQueryEventObject, data: any) => {
		//...
	}
});
//...
$("#loadBook").on('click', function () { // the button to initiate the file sending
	if (this.fileData && this.fileData.hasOwnProperty("process")) {

		// file data validation: size, extension, whatever else...
		
		this.fileData.process().done(() => { // file sending
			this.fileData.submit();
		});
	}
});

On the server side the following code receives and processes the file data:

using System;
using System.Text;
using System·Web;
using System·Web.Http;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Linq;
...
namespace DotNetFollower.Web.Controllers.Api
{
    [RoutePrefix("api/someController")]
	public class someController : ApiController
	{        
        public someController()
		{
            //...
		}
		
        [Route("someMethod")]
        [HttpPut]
        [HttpPost] // this attribute allows processing traditional form POST
        public ServiceResult<BookOutput> someMethod()
        {
            try
            { 
			    //...
			    var request = HttpContext.Current.Request;
			    var files   = request.Files;

			    if (files.Count == 0) 
				    throw new Exception("Couldn't find a book to load!");

			    // read accompanying parameters
			    var bookName   = request.Form.Get("bookName");
			    var bookGenre  = request.Form.Get("bookGenre");
			    var bookAuthor = request.Form.Get("bookAuthor");
			
			    var file = new HttpPostedFileWrapper(files[0]);
			
			    // parsing file.InputStream ...
			
			    // processing the parsed file data ...
			
			    file.InputStream.Close();
			    //...
			
			    return new ServiceResult<BookOutput>() 
				    { 
					    Data = new BookOutput() 
						    { 
							    Name   = bookName, 
							    Genre  = bookGenre, 
							    Author = bookAuthor 
						    } 
				    };
            }
            catch(Exception ex)
            {
                return new ServiceResult<BookOutput>(ex);
            }
        }
	}
}

// Where ServiceResult and BookOutput are defined as follows

public class ServiceResult<T>
{
	public bool   Success      { get; set; }
	public string ErrorMessage { get; set; }	
	public T      Data         { get; set; }

	public ServiceResult()
	{
		Success = true;
	}

	public ServiceResult(string errorMessage)
	{   
		ErrorMessage = errorMessage;
	}

	public ServiceResult(Exception exception)
	{
		ErrorMessage = exception.Message;	
	}
}

public class BookOutput
{
	public string Name   { get; set; }
	public string Genre  { get; set; }
	public string Author { get; set; }
}

Unfortunately, the code doesn’t works as expected in Internet Explorer 9 (thankfully, the lower versions are not supposed to be supported by the project, so I don’t care about them). If IE9 sends an Ajax request to the Web Api method, it interprets the JSON response correctly. However, when uploading a file, the jQuery File Upload plugin sends traditional non-Ajax form POST. So, having received the JSON result, IE9 prompts for a JSON file download.

Download Json File Prompt

To bypass such IE9 behaviour the server response should contain the content-type header “text/html” rather than the “application/json” returned by the Web Api method by default. To avoid writing some IE9 specific logic on both server and client sides, I’ve introduced the following Web Api method-adapter:

[Route("someMethodAdapted")]
[HttpPut]
[HttpPost] // this attribute allows processing traditional form POST
public HttpResponseMessage someMethodAdapted()
{
	var res = someMethod(); // call the original method

	const string JsonContentType = "application/json";
	const string HtmlContentType = "text/html";

	var response = Request.CreateResponse(HttpStatusCode.OK); // return 200 OK
	var context  = HttpContext.Current;
	response.Content = new StringContent(ToJson(res), // serialize result object into JSON
	  Encoding.UTF8, 
	  // check if the JSON content-type is accepted 
	  // (it's not accepted in case of form POST coming from IE9)
	  context.Request.AcceptTypes.Contains(JsonContentType, StringComparer.OrdinalIgnoreCase) ?
	     JsonContentType : HtmlContentType); // return suitable content-type

	return response;
}

// the ToJson method is defined as follows

private static string ToJson<T>(T obj) where T : class
{
	if (obj == null)
		return string.Empty;

	DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
	using (MemoryStream stream = new MemoryStream())
	{
		serializer.WriteObject(stream, obj);
		return Encoding.Default.GetString(stream.ToArray());
	}
}

The someMethodAdapted is supposed to be used instead of someMethod everywhere on the client side. So, repoint the url to the method-adapter

...
$(".filePicker").fileupload({
	...
	// Web Api method-adapter to receive and process the file
	url: "api/someController/someMethodAdapted",
	...
});
...

The someMethodAdapted makes a content-type trick and perfectly serves IE9 and higher. The use of HttpResponseMessage gives a control over the response headers. The HttpContext.Current.Request.AcceptTypes is a list of client-supported content types (aka MIME types). If the “application/json” is not in the list, the “text/html” is the right choice. Below are the AcceptTypes of Ajax and non-Ajax requests made by IE9:

// IE9 Ajax request to a Web Api method (true for higher browser versions too)
HttpContext.Current.Request.AcceptTypes	{string[3]}	string[]
[0]	"application/json"	string
[1]	"text/javascript"	string
[2]	"*/*; q=0.01"	string

// IE9 non-Ajax form POST
HttpContext.Current.Request.AcceptTypes	{string[3]}	string[]
[0]	"text/html"	string
[1]	"application/xhtml+xml"	string
[2]	"*/*"	string

WebLoading Library: Downloading data from RESTful sources

July 23rd, 2012
No comments

    I often run into necessity to load data from sources published in the Internet. In most cases the sources are RESTful web-services, thus the data they emit is in xml or json formats. More and more web-services providers prefer spreading their data in an easier-to-use REST formats as a simpler alternative to SOAP and WSDL based web-services.

WebLoading Library Overview

For downloading data via the Http protocol I implemented a set of generic classes, let’s call it WebLoading Library. Almost every class in the library is a loader, which operates at a certain level of abstraction. The library allows to easily derive a new class from one of the exposed loaders, defining a type of the data to be loaded and the type of the ready-to-use data to be returned out of the loader. See the class diagram below.

Class Diagram of WebLoading Library

I single out such basic steps of getting data as raw data loading, verification and conversion into a ready-to-use view. All loaders exposes the LoadData method aimed at performing these steps.The listing below demonstrates the LoadData‘s base implementation in the BaseLoader class. BaseLoader is a root base class for all loaders in the WebLoading Library hierarchy.

BaseLoader abstracts the loading from any source. Unlike BaseLoader, its direct descendant, HttpLoader, implies loading from a source supporting the Http protocol. See the listing of the HttpLoader class below.

The next level in the hierarchy comprises such loaders as ImageLoader, XmlLoader and JsonLoader. I’ll dwell upon the last two a bit later. As regards the first one, ImageLoader is a quite simple class derived from HttpLoader that downloads an image from a specified source via Http. Being initially intended for dealing with REST formats, the loaders family can be easily extended to any data formats. So, the ImageLoader is a good example to that. The class is shown below:

WebLoading Library Overview: XmlLoader

XmlLoader is an abstract class derived from HttpLoader and intended for xml data downloading. The downloaded raw xml is presented as a XDocument object. Create a descendent of the XmlLoader class to verify and turn the XDocument into any another desired view-object. The XmlLoader looks as follows:

As a simple example, below is a class-descendent demonstrating how to get the expected maximum temperatures for the next 7 days. The data source is http://graphical.weather.gov, which provides with xml data like the following:

The GraphicalWeatherLoader class accepts a zip code of the region you need to get forecast for. See the next listing:

WebLoading Library Overview: JsonLoader

Like XmlLoader, the JsonLoader class is abstract and derived from HttpLoader too. It’s dedicated for downloading json data. The downloaded json is processed by the JsonParser borrowed from the fastJSON project by Mehdi Gholam. Undoubtedly it’s the fastest json parser I’ve ever met. So, many thanks to Mehdi. The parsed json data is presented as a Dictionary<string, object>, which, besides simple objects, may contain arrays and other dictionaries nested on different levels. To have an ability to verify and transform the dictionary into something different, just create a descendent of the JsonLoader. Below is the listing of the JsonLoader:

Pay attention to the SelectObjects methods that obtain an specified object(s) from a tree of arrays and dictionaries using a xpath-like path (for example, “set/items/item”).

Let’s take a look at yet another example, this time it’s a descendent of JsonLoader. The derived class is quite pointless and just gets names of some capital-cities. The http://api.geonames.org service returns the json data in the following form:

The next listing is the GeoNamesCitiesLoader class:

The source code and examples are available to download here.

Categories: C#, JSON, XML Tags: , ,