
I know what you’re thinking. Oh great, another article on AJAX! Okay, sure. You’re right. But seriously, when I was originally attempting to learn this stuff I found myself jumping through hoops just trying to get a simple example to work…
- How do I configure a web service to return JSON?
- What in the heck is JSON?
- Why not use XML?
- What is JQuery?
- How do I call a Web Service from JavaScript?
Yeah, there were articles. Lots of articles. But I found that no single article presented a complete example. Some would focus on the client. Some the server. Some would gloss over the “why” and emphasize the “how”. Others would pull in obscure technology that, while cool, would be completely at odds in a business environment.
So, here’s my own entry into wide assortment of AJAX articles – a simple Echo Service.
Why an Echo Service?
It’s a very simple way to demonstrate how to send/receive JSON objects between a client browser and a Web Service. This is common pattern that is used in modern websites. A simple example makes it easier to showcase a bunch of cool (yet essential) technologies such as…
ASP.NET | Microsoft’s web application framework. |
Javascript | The defacto standard for manipulating the HTML DOM. |
JQuery | An open-source Javascript Library for manipulating the HTML DOM. Endorsed by Microsoft and included with Visual Studio 2010. |
JSON | Like XML but with a (much) smaller footprint. JSON is Javascript. It can be serialized into a human-readable string or deserialized into a Javascript object that can be used programatically in Javascript code. |
Windows Communication Foundation (WCF) | Microsoft’s implementation of a SOA framework. We’ll use it to create a web service. |
The Echo Service
Overview
First, we’re going to create an EchoService Web Service using Microsoft’s Windows Communication Foundation (WCF). A Message class will be used to facilitate communication with the EchoService. The Message will be automatically converted to/from JSON by WCF.
Next, we’re going to create an ASP.NET EchoPage Web Form. A blank JSON representation of the Message class will be exposed to the EchoPage’s client-side. This JSON Message will be populated with some text and submitted to the EchoService using JQuery’s AJAX implementation.
Finally, we’re going to apply some enhancements to the EchoService and EchoPage to make them a little more robust – while eliminating unecessary code.
EchoService WCF Web Service
The EchoService exposes a single Echo() method that receives and returns a JSON object. Why a JSON object and not just a bunch of params? Because parameters are sloppy and difficult to manage. Also, it’s easier to deal with the same data object on both the server and the client.
The EchoService’s handling of JSON is declared in the attributes for the Echo() method. Notice the ResponseFormat and RequestFormat indicators. This tells WCF to implicitly convert between the Message class and JSON.
[OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] public Message Echo (Message message) { message.Text = string.Format("Echo {0}", message.Text); return message; }
EchoService.svc.cs
EchoPage ASP.NET Web Form
Client-Side (.aspx)
The client-side portion of the EchoPage uses JQuery’s AJAX implementation to submit (and receive) Messages to the EchoService. The “data” parameter specifies the data that you want to submit to the EchoService. The “dataType : json” instructs JQuery to expect a JSON result from the EchoService. JQuery will implicitly convert the EchoService’s response. The “success” function is called upon a successful transaction.
Be very careful when specifying your “data” parameter. It should be in the form of a JSON (name/value pair) object where the name corresponds to the parameter name on the EchoService’s Echo() method. The value is your actual data – serialized using the JSON.Stringify() function. Also, take special notice of the quotation marks. I’ve had problems before with single versus double-quotes.
$.ajax({ type: "POST", url: "EchoService.svc/Echo", data: '{ "message" : ' + JSON.stringify(jsonMessage) + '}', dataType: "json", contentType: "application/json; charset=utf-8", success: function(data, textStatus, httpRequest) { data = data.hasOwnProperty('d') ? data.d : data; $("#responseMessage").html(data.Text); }, error: function(httpRequest, status, errorThrown) { $("#responseMessage").addClass("error"); $("#responseMessage").html("There was a problem calling the Echo Service. Error : " + errorThrown + "!"); } });
EchoPage.svc.cs
What’s the deal with the .d in the AJAX success function?
Since ASP.NET 3.5 Microsoft’s WCF Service encapsulates all JSON responses in a “d” name-value pair for security reasons. You can read more about it here and here. A side-effect of this is that we need to handle the encapsulation in our client-side Javascript …
data = data.hasOwnProperty('d') ? data.d : data;
EchoPage.aspx
What’s the deal with the JSON.stringify() ?
When submitting a request to the EchoService using JQuery’s AJAX the data needs to be in the form of a string. JSON.stringify() serializes our Message (which is a JSON object) so that it can be submitted properly.
$.ajax({ type : "POST", url : "EchoService.svc/Echo", data : '{ "message" : ' + JSON.stringify(jsonMessage) + '}', ...
EchoPage.aspx
Server-Side (.aspx.cs)
The server-side portion of the EchoPage is relatively sparse. When we start optimizing our code later it will disappear entirely. For now, the server-side portion of the EchoPage creates a JSON representation of an empty Message.
protected string jsonMessage; protected void Page_Load(object sender, EventArgs e) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Message)); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, new Message()); jsonMessage = Encoding.Default.GetString(ms.ToArray()); // Viola! } }
EchoPage.aspx.cs
This JSON Message is exposed to the client-side Javascript as a var and is used in the JQuery AJAX submission to the EchoService.
var jsonMessage = <%= jsonMessage %>;
EchoPage.aspx
Okay, great. Is that it?
No, although the above code works there are a few issues that we should probably look into …
- ASP.NET’s JSON security is a nice touch. However, our handling of the “d” encapsulation on the client-side of the EchoPage is clunky.
- Our serialization of the Message object into JSON on the server-side of the EchoPage is very specific to a particular class.
- If an error occurs while the EchoService is processing a Message there is no way to properly notify the EchoPage so that it might handle the error gracefully.
Polishing the Echo Service
JQuery’s AJAX dataFilter
JQuery exposes a customizable “dataFilter” for it’s AJAX calls. Declaring a dataType instructed JQuery to implicitly handle the response from a Web Service. Declaring a dataFilter puts the responsibility solely on the developer.
We can leverage JQuery’s AJAX dataFilter when handling ASP.NET’s “d” security feature on the EchoPage. Notice that we need to programatically deserialize the EchoService’s response into a Javascript object using JSON.parse().
$.ajax({ type : "POST", url : "EchoService.svc/Echo", data : '{ "message" : ' + JSON.stringify(jsonMessage) + '}', /* dataType: "json", */ contentType : "application/json; charset=utf-8", dataFilter : function(data) { data = JSON.parse(data); return data.hasOwnProperty("d") ? data.d : data; }, success: function(data, textStatus, httpRequest) { /* data = data.hasOwnProperty('d') ? data.d : data; */ $("#responseMessage").html(data.Text); }, error: function(httpRequest, status, errorThrown) { $("#responseMessage").addClass("error"); $("#responseMessage").html("There was a problem calling the Echo Service. Error : " + errorThrown + "!"); } });
EchoPage.aspx
JSON Serialization Extension Method
NET 3.5 introduced Extension Methods. Extension Methods allow you to add new methods to an existing type. Adding an extension method to the .NET base object class exposes the method to all classes.
Currently the EchoPage can only serialize a Message into JSON. However, by moving the code into an Extension Method we can clean up the EchoPage and eliminate a lot of (potentially) redundant code. This is what the new .GetJsonString() Extension Method looks like …
/// <summary> /// Extension methods to .NET classes. /// </summary> public static class Extensions { /// <summary> /// Extends object to with a JSON serializer. /// </summary> /// The object as a serialized JSON string. public static string GetJsonString(this object obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); return Encoding.Default.GetString(ms.ToArray()); } } }
Extensions.cs
The EchoPage can now call .GetJsonString() directly from the Message data object.
var jsonMessage = <%= (new SimpleAJAXEchoService.Message()).GetJsonString() %>
EchoPage.aspx
As far as the server-side code for the EchoPage? Gone.
/// <summary> /// An Web Page that "talks" to the Echo Service using AJAX. /// </summary> public partial class EchoPage : System.Web.UI.Page { // The addition of the .GetJsonString() method eliminates all of this code. Furthermore, it can be called against any class derived from // object (which is pretty much anything). /* Gone! /// <summary> /// A serialized JSON representation of the Message class. Will be exposed to the EchoPage's Javascript and used to submit data to /// the EchoService. /// </summary> protected void Page_Load(object sender, EventArgs e) { // We'll need to submit an instance of the Message class to the EchoService from the EchoPage using Javascript. JSON is an ideal format to // work with. Let's serialize an instance of Message into a JSON string and expose it to the EchoPage's Javascript. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Message)); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, new Message()); jsonMessage = Encoding.Default.GetString(ms.ToArray()); // Viola! } } */ }
EchoPage.aspx.cs
Encapsulating the Response
By wrapping the response from the EchoService we can more effectively handle errors that it might throw on the EchoPage. We can wrap up the EchoService’s response Message in a new ClientResponse wrapper. In addition to a Payload (the Message) the ClientResponse exposes an IsSuccessful and ErrorMessage.
/// <summary> /// A generic client response wrapper. Wraps a web service response so that /// additional (troubleshooting) information can be returned alongside the payload. /// </summary> /// The payload type to encapsulate. [DataContract] public class ClientResponse { /// <summary> /// The data to return to the client. /// </summary> [DataMember] public T Payload { get; set; } /// <summary> /// True, if the data was retrieved sucessfully. /// </summary> [DataMember] public bool IsSuccessful { get; set; } /// <summary> /// The error message if the data was not retrieved sucessfully. /// </summary> [DataMember] public string ErrorMessage { get; set; } /// <summary> /// Constructor. /// </summary> public ClientResponse() { IsSuccessful = true; ErrorMessage = string.Empty; } /// <summary> /// Constructor. /// </summary> /// True, if the data was retrieved sucessfully. /// The data to return to the client. /// The error message if the data was not retrieved sucessfully. public ClientResponse(bool isSuccessful, T payload, string errorMessage) : this() { IsSuccessful = isSuccessful; Payload = payload; ErrorMessage = errorMessage; } }
ClientResponse.cs
We can leverage JQuery’s AJAX dataFilter to implictly handle the ClientResponse wrapper. Any errors incurred will now be passed onto JQuery’s AJAX error() function.
$.ajax({ type: "POST", url: "EchoService.svc/Echo", data: '{ "message" : ' + JSON.stringify(jsonMessage) + '}', /* dataType: "json", */ contentType: "application/json; charset=utf-8", dataFilter: function(data) { data = JSON.parse(data); data = data.hasOwnProperty("d") ? data.d : data; if (data.hasOwnProperty("IsSuccessful")) { if (data.IsSuccessful == true) { return data.Payload; } else { var errorMessage = "Error"; if (data.hasOwnProperty("ErrorMessage") && data.ErrorMessage !== null) { errorMessage = data.ErrorMessage; } throw errorMessage; } } return data; }, error: function(httpRequest, status, errorThrown) { $("#responseMessage").addClass("error"); $("#responseMessage").html("There was a problem calling the Echo Service. Error : " + errorThrown + "!"); } });
EchoPage.aspx
Conclusion
Okay, sure. The Echo Service was a simple example. But hey! It showcased a whole bunch of cool technologies in a nice little package. Now, next time someone asks you on the street, “Excuse me, but what is AJAX?” you can look them in the eyes and reply, “Let me tell you about a simple little Echo Service that I know…”.
The source code is available here. Please let me know if you have and questions or comments.
#.NET #WCF #JSON #Webservices #EchoService #ASP.NET #JQuery #Javascript #Programming #SoftwareDevelopment #SoftwareEngineer #DrawnAndCoded