Fremus.co.za

Demistifying Life and Web Development

Archive for the 'AJAX' Category

WCF, ASP.NET Webforms, ASP.NET MVC and jQuery

I haven’t written a technical article in a while but I thought I would write one that discusses AJAX calls with jQuery. Before I get into it I would like to reiterate some of my personal development objectives of late:

  1. Don’t do ANY UI manipulation in any of my server side API’s. The sole purpose of any API within the applications I build is to deal with business layer logic and the data related to it. Ideally speaking I would want my API to return structured data which is easily transformed into a format for the client application using the API (e.g. JSON). I have had experiences within another development team in the recent past where the API returned HTML with the data and to say that this is a mess is understating the obvious – if you think about it quickly then you can understand the impact of one style or layout change will have on this approach. It also blurs your application in terms of its concerns and makes testing a problem. So ideally I dont want any UI logic in any of my API’s.
  2. The second objective I have is that all my UI for web applications must be handled with client-side scripts. Client side includes both static HTML, CSS and JavaScript, and in this instance I specifically refer to JavaScript and the handling of my API’s data using JSON, for which I use jQuery. The REST (:D) of this article is dedicated to the AJAX options available in an ASP.NET application.

Dealing with AJAX in an ASP.NET Application

Developing ASP.NET applications gives you two “frameworks” or “architectures” to work with:

  1. ASP.NET Webforms
  2. ASP.NET MVC

Notice that each architecture or framework uses the ASP.NET runtime which in turn runs on the .NET framework, and part of the .NET framework is the Common Language Runtime (CLR). People often think ASP.NET automatically refers to webforms. The difference between the architectures lies both in how it was designed and who it was designed for. Webforms was designed for Windows Forms developers working within the Visual Studio drag-and-drop environment and aimed to provide an abstraction of Windows Forms for the web. With webforms you could simply drag and drop controls onto a design surface and assign properties to the controls. The problem with webforms was that it required state management and to deal with the state management viewstate was created. Basically state management refers to a controls ability to retain its “value state” across postbacks. So if I created a simple label and set its text to “hello world” viewstate is used to retain that text value throughout the life of the rendered page. Webforms also introduced the concept of the Page Life Cycle, which exposed certain events at certain points of the page’s rendering process. The problem with viewstate is that the viewstate is inserted into your HTML pages which causes the page to bloat – so there is no clean markup. Viewstate totally goes against the grain of how the web works – being stateless.

ASP.NET MVC addresses some of the issues associated with webforms by using a mature and well known architectural pattern – Model-View-Controller, as used in Ruby-On-Rails. ASP.NET MVC does not use the page lifecycle for a start and it embraces the web’s statelessness instead of fighting it. The result is that you have no ViewState and this means that there is no HTML bloat and you also have complete control over your HTML.

There are a couple of ways to consume AJAX requests in ASP.NET but they fall into two categories:

  1. SOAP
  2. REST

In my previous development role I worked with guys that used SOAP to do AJAX requests and although this approach was good enough it was specifically aimed at ASMX web services which meant adding web references to your project. Needless to say adding these reference is a pain in the ass, because if a new method was added to a service you had to first update your reference before you could see the method. REST, however, addresses this issue by allowing you to make calls to URL’s, and not by adding any references. It also means that if a new method is created its available immediately. The remainder of this article is about consuming REST-like services in an ASP.NET application.

With my latest development effort I started out by using Page Methods in an ASP.NET Webform application. Why ASP.NET webforms you may ask? Well I wanted to focus on the business value and I just started out with Webforms without concerning myself too much with the technical side of things. Page methods implement a REST-like architecture and simply requires that you add a WebMethod attribute in your code-behind’s CS file like this:

    [WebMethod]
    public static Dictionary> GetLastSixMonthReport()

You could then access the web method through jQuery like this (notice the Default.aspx/GetImportsLastSixMonths):

    $.ajax({
        type: "POST",
        url: "Default.aspx/GetImportsLastSixMonths",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var dict = msg.d;
            var html = '';
            $("#importsData").empty();
            html += dict;
            $("#importsData").append(html);
        }
    });

The main issue I have with this approach was that if I wanted to create a new web project I had to re-create the web methods – which is not ideal. So if I wanted to move this project over to a new MVC app I would have to recreate the methods. Based on this I decided to create a separate WCF project that could host all my methods and deliver them in a REST-JSON way. To get WCF to deliver JSON in a REST fashion you need to do two important things:

  • Configure it
  • Add the appropriate Interface attributes

Configuring a WCF service for JSON requires that you add an endpoint address to the service itself like this:


You also need to add an endPointBehavior like this:

				
					
				
			

In your service behaviours you need to set httpGetEnabled to true as well. I added this in my service class:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

In service contract I added the WebInvoke attribute to each method, like this:

    [OperationContract]
    [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    ProductCollectionView[] GetProductCollectionViews();

Once I set this up I could access the JSON-enabled endpoint: http://localhost/LRB2CServiceLayer_v1/LRB2c.svc/ajaxEndpoint/GetProductCollectionViews and I would see the JSON. Notice that the JSON comes with a MethodNameResult as opposed to the “d” from the page methods. Consuming it uses a similar approach to the jQuery for page methods, except that you use a GET (which is a little dodgy):

    $.ajax({
        type: "GET",
        url: "http://localhost/LRB2CServiceLayer_v1/LRB2c.svc/ajaxEndpoint/GetProductCollectionViews",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var dict = msg["GetProductCollectionViewsResult"];
            var html = '';
            $("#importsData").empty();
            html += dict;
            $("#importsData").append(html);
        }
    });

I decided to convert the WCF service to a class library (DLL) instead because I had all kinds of issues with XSS because I ran the WCF service as a separate web application. The idea was that a WCF service was easily shared between web apps. I basically combined the class library with a MVC web app instead. A class library can just as easily be shared among multiple projects or web sites. The JSON that MVC returns is different to WCF and Webforms – it just returns the object, no indexer/key such as “d”. Getting MVC to return JSON is pretty straight forward:

        [HttpPost]
        public JsonResult GetGetProductCollectionViews()
        {
        }

Of the three methods/technologies I described I like the ASP.NET MVC approach because:

  • Its RESTful
  • The JSON result only contains the object(s)
  • Share/Bookmark
posted by fr3dr1k in AJAX,ASP.NET,ASP.NET MVC,Web Development,Web Technologies and have No Comments

Ajax in the .NET environment…

Ajax is not new, its not revolutionary, but it has changed the way I view web development. Javascript no longer comes as a might-have, instead it comes as a critical part of any website application. These days I use JavaScript as the UI scripting tool of choice, and I try to steer away from doing to much UI lifting in my server side code. jQuery makes dealing with UI quite pleasant.

I have also, in the last year and a half or so, been coding without MS Ajax. I have let go of things like the UpdatePanel and the Script Manager and have instead come to do direct Ajax calls to .ashx, default.aspx and web services. It feels that when you follow this approach that you have much tighter control over the quality of the UI. So what are your options for making Ajax calls in a .NET environment? I would like to think that there are a few options that stand out:

  • Direct page ajax calls – you can use jQuery’s ajax function to call .ashx and .aspx pages. I have recently started using the [WebMethod] attribute in my .aspx files to make calls, and what I like about it is that you can tell the page to output JSON, which automatically serializes the method’s return type. I have also used ashx files to do ajax calls and this worked well
  • SOAP-based web services – an approach I learned last year was to use a javascript soap parser to parse soap-based web services. These were mainly .asmx services. You can configure .asmx services to return JSON as well
  • WCF-services can be configured for SOAP or JSON but also use a REST-like approach

What other options are there for .NET developers when making Ajax calls?

  • Share/Bookmark
Tags: ,
posted by fr3dr1k in AJAX,C#,Web Technologies and have No Comments

Getting POST values with an ASHX file

Today I had this scenario where I wanted to post items from multiple HTML input elements to a generic handler (.ashx) file without using the action attribute of the form. Specifying the action meant that that you are navigated away from the page where the action is happening, which means re-creating UI logic. How did I achieve this? By using an XMLHttpRequest and using a POST method. GET places everything inside a querystring, which is ok, but I just wondered what would happen if the content was too long for the querystring. I guess the same can be said for POST, but it just seems POST uses a different way to transfer the data. So lets say you had this JavaScript:

    getXMLHTTPPostObject: function(url, elementName, parameters) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            alert("Your browser does not support XMLHTTP!");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                document.getElementById(elementName).innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST", url, true);
        xmlhttp.send(parameters);
    }

I use this function to create an XMLHttpRequest object by passing it:

  • the URL for the AJAX call
  • an elementName to put the result of request in
  • A parameter list

I then have a function like this:

    addPost: function() {
        objXMLHTTP.getXMLHTTPPostObject("url to handler", "categoryTemp", "postTitle=" + document.getElementById("txtPostTitle").value + "&blogpost=" + document.getElementById("txtBlogPost").value);
    }

The function gets the values of two HTML input elements and passes it as parameters. The parameters are then used in the POST HTTPMethod. My next challenge was to get the data in the generic handler (.ashx) so that I can process it. I also wanted to return the data from the ASHX file to see that its processed successfully. So in my handler I created this code:

        context.Response.ContentType = "text/plain";
        System.IO.Stream body = context.Request.InputStream;
        System.Text.Encoding encoding = context.Request.ContentEncoding;
        System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
        //if (context.Request.ContentType != null)
        //{
        //    context.Response.Write("Client data content type " + context.Request.ContentType);
        //}
        string s = reader.ReadToEnd();
        string[] content = s.Split('&');
        for (int i = 0; i < content.Length; i++)
        {
            string[] fields = content[i].Split('=');
            context.Response.Write("
" + fields[0] + "
"); context.Response.Write("
" + fields[1] + "
"); } //context.Response.Write(s); body.Close(); reader.Close();

I first create a class of type Stream that is instantiated through the Response.InputStream property, after which I set the content encoding for the response object. I then create a StreamReader instance and call its ReadToEnd method. After this I do some string manipulation and return the text back to the XMLHttpRequest object, which then writes the content to an HTML Element.

  • Share/Bookmark
posted by fr3dr1k in AJAX,C#,Web Development,Web Technologies and have Comment (1)

JavaScript alphabetical sorting (A is less than a)

So A < a, which means if you use the sort() function and your array contains elements starting with upper and lowercase then the uppercase will appear first, i.e.:

Art, ASP.NET, LawDeed, LINQ will appear as:
ASP.NET
Art
LawDeed
LINQ

To get this working correctly you need the following function:

    charOrdA: function(a, b) {
        a = a.toLowerCase(); b = b.toLowerCase();
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
    }

This function will make sure your alphabetical sortorder is correct so that the list appears like this:
Art
ASP.NET
LawDeed
LINQ

You have to pass the function name to the sort function like this:


arrCategories.sort(charOrdA);

Note that there are no parenthesis.

  • Share/Bookmark
posted by fr3dr1k in AJAX,Web Development,Web Technologies and have No Comments

Getting to understand JavaScripts prototypal nature

One of the things that are quite weird to get use to, from a C# developer’s perspective, is JavaScript’s prototypical nature. Check out this basic example:


var objXMLHTTP =
{
    getXMLHTTPObject: function(url,elementName) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            alert("Your browser does not support XMLHTTP!");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                document.getElementById(elementName).innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
};
objXMLHTTP.getXMLHTTPObject("http://localhost/YieldTester/Handler.ashx", "testDiv");

The code above creates a simple XMLHTTPRequest object, but you do not create an instance of the object, you call it directly. Note objXMLHTTP.getXMLHTTPObject. In C# you might have created an object and then you instantiate it through an instance of that object. I have taken the code as is given on W3Schools and modified it a little.

  • Share/Bookmark
posted by fr3dr1k in AJAX,Web Technologies and have No Comments

Understanding JavaScript from a C# developer’s perspective

So during the week I did a lot of JavaScript and the thing that I found most, what shall I say, mindshiftable, is that you cannot think in the classical OOP way with JavaScript, as you do with C#. JavaScript does everything in functions, and everything within JavaScript is prototypical. Inheritance is prototypical, everything is prototypical. You dont create instances of objects but rather use the objects themselves. So its kinda like a static class, where you invoke members directly.

I started this week by looking at a SOAP client written in JavaScript that makes calls to web services. What the SOAP client basically does is cache the WSDL with all the functions in it, from a web service (in this case an asmx file), and then it sends SOAP requests, processes the request and if there is a callback it does the callback function. The code for the SOAP client is based on this code.

  • Share/Bookmark
Tags: ,
posted by fr3dr1k in AJAX,C#,Web Technologies and have No Comments

Unobtrusive JavaScript and a Session-less shopping cart

What is the idea behind unobtrusive JavaScript? What makes JavaScript unobtrusive? Does it mean removing any onlclick events in your markup and handling those click events with an approach as provided with jQuery? With jQuery its very (extremely) easy to traverse between DOM elements and its even easier associating events to elements and executing them.

I havent been doing a lot of JavaScript recently but you cannot really avoid it, but you can also not build an entire website with JavaScript and HTTPRequests alone (not search engine friendly), but you can also not rely entirely on server side code to do all the magic for you.

The other issue that has been bugging me of late is the idea of creating a session-less shopping basket, a shopping basket that uses a combination of web services and traditional classes. Within the .NET environment the only reason you might need to use sessions is to store DataTables or DataSets, but the question is how expensive is that on server resources. Would I be able to create the same session-based application with web services and traditional classes? After all you are adding web references to your web applications, and those web references all contain class declarations.

  • Share/Bookmark
posted by fr3dr1k in AJAX,ASP.NET and have No Comments

Demystifying some .NET Issues

What seemed a little odd to me today was that SQL Server Express 2005 is download-able from two places. Both shows different file sizes.

Another issues that needs clarity is ASP.NET and .NET framework versions. .NET 3.5 is an ‘extension’ of .NET 2.0 and replaces .NET 3.0. .NET 3.5 covers AJAX (Asynchronous JavaScript and XML) and LINQ (Language Integrated Query)

  • Share/Bookmark
Tags: ,
posted by fr3dr1k in AJAX,ASP.NET,Web Technologies and have No Comments

jQuery and Microsoft

I susbscribe to The Code Project’s newsletter and today I got some great news, jQuery will be supported in Visual Studio 2008. Now this is some awesome news. Makes one wonder if the Microsoft AJAX library will become redundant.

You can read the full article on Scott Gu’s website.

  • Share/Bookmark
posted by fr3dr1k in AJAX,ASP.NET,Web 2.0,Web Development and have No Comments

Light up the Web – Mix Essentials 2008 Review

I attended the Mix Essentials 2008 event at Canal Walk (Cape Town, South Africa) today and there were quite a few things that interested me. There were five speakers at the event:

  1. David Ives – Developer and Platform Strategy Group for Microsoft in South Africa – Microsoft
  2. Brad Abrams – Group Program Manager for the UI Framework and Services Team – Microsoft
  3. Michael Koester – Designer Marketing Manager for Middle East and Africa and Central and Eastern Europe – Microsoft
  4. Julian Harris – Conchango
  5. David Pugh-Jones – Microsoft

The event was split into two tracks, a developer track and a designer track, but it generally focussed on Silverlight, and more specifically on two software packages, Visual Studio 2008 and Expression Studio, and even more specifically it introduced XAML as a common way for these packages to share content between them. XAML, Extensible Application Markup Language is an XML-like language that defines graphic elements in a human readable form that can be used in vector-imaging programs as well as Visual Studio 2008. This gives designers the flexibility to design interfaces without having to worry about programmers not being able to replicate their designs in a programming environment. Julian Harris demonstrated that you can export files from Adobe Illustrator into XAML format and import that XAML into Visual Studio 2008. XAML is also used in the Expression Studio range of products which includes amongst other two interesting products:

  • Expression Blend
  • Expression Design

Expression Blend is, almost like Adobe’s Flash Studio, which is an IDE that allows you to create WPF (Windows Presentation Foundation) and Silverlight applications. WPF is a technology that allows developers (and designers) to create applications that give users a better user experience (UX). Contemporary windows applications generally use square (often mundane) windows, whereas WPF applications allow designers to implement creative graphics into the interface. Rounded corners and transparent backgrounds for instance are used, and because Expression Blend can read and understand XAML, none of a designer’s creative flair is lost. The developer no longer has any excuses to develop interfaces that do not exactly meet the designer’s design.

  • Share/Bookmark
posted by fr3dr1k in AJAX,ASP.NET,Web 2.0,Web Design,Web Development,Web Technologies and have No Comments
Get Adobe Flash playerPlugin by wpburn.com wordpress themes