Fremus.co.za

Demistifying Life and Web Development

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

What do I know about ASP.NET? Part 1

I started using ASP.NET around 2003/2004 for the first time and at the time I had no real clue as to what it really was and how it worked. I think we often do things in a haphazard way and mature in our method(s) of doing things. The same goes for learning ASP.NET and I honestly feel that learning ASP.NET means that you are willing to learn about the rest of the .NET framework, not just the web development framework.

The reason I am writing this blog post is because I started watching some videos on Tekpub and in particular Rob Conery and Steve Sanderson’s video series and I asked myself where my current knowledge of ASP.NET is at. Notice that I am not referring to classic ASP – something I have not really bothered to learn since ASP.NET could do everything classic ASP could and more. Its strange that some people seem to still revert to classic ASP in some instances.

The first thing that comes to mind when I think about ASP.NET is that it is a Microsoft product and runs mostly on one of the many Microsoft Windows operating systems. ASP.NET is a web development framework that also runs on IIS (internet information services), which is a web server built by Microsoft and included with most Windows versions. ASP.NET also runs on the .NET framework which is built on top of the CLR (Common Language Runtime) which in turn allows developers to target the .NET framework with any programming language that can target the framework.
In its most basic form an HTTP server handles request and sends responses to a client, and with IIS and ASP.NET it is no different. Its important to note that ASP.NET is not automatically enabled for IIS and often requires that you run aspnet_regiis which you can find in your WINDOWS directory under Microsoft.NET > Framework > Vx.x (where x can be a framework number). You are essentially attaching the ASP.NET runtime to IIS, which in turn is a process that runs in Windows. IIS sometimes makes me think of the SQL Server tool that allows you to attach jobs to it, because SQL Server is also a long running process in Windows you can attach processes or components to it.

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

My opinion on webforms and such

Today someone asked me what my opinion on webforms are or were, and sometimes I feel like the proverbial deer that gets caught with the light in his eyes. It probably seemed like I knew nothing about web forms, which is not entirely true. I mean I did a lot of my first ASP.NET programming with web forms, and its a really great platform for several reasons. Firstly you can develop a working demo of something in really short order, you don’t have to really go out and code a user control from scratch, because the controls that are already there are pretty good. I mean the Gridview/Datagrid control is pretty cool and it is pretty customizable. Secondly ASP.NET does a good job of taking HTTP from the stateless protocol it is, to a model that maintains state quite well. I coded a lot with ASP.NET Webforms and its not a bad technology or platform to work with.

In the same breath, however, I have been working with SOAP calls and web services for the last 8 to 9 months and what I like the most about this approach is the freedom to totally control the markup that is rendered in the browser. With web forms you had to deal with something called ViewState which could in some scenarios make a mess of your code. I like clean HTML. What the SOAP/Webservice model also kinda reinforces is that HTTP is stateless and should be treated as such.

I have also been doing some ASP.NET MVC and I personally like it, a lot, and will continue developing a bit more with it. There is a clean and clear separation between your presentation logic and your business logic and there is no viewstate.

Maybe I need to do some more webforms for a bit to get to grips with it again, maybe not. I do prefer spending time learning C# language features actually.

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

On that Session-less shopping cart issue

In my post yesterday I mentioned that I would like to develop a session-less shopping cart through the use of web services and classes. Well, I changed my mind a bit because I am not sure if AJAX can maintain state. Can it? How will AJAX retain state? I’m not sure yet, so sessions it is.

There are some important reading bits that need to be covered before you can get stuck into sessions, and its always better to try and understand something as far as possible before you simply jump in and implement it. The first article that proves invaluable (and very important) is the ASP.NET Page Lifecycle where after I can recommend you read the State Management Overview Article to understand the difference between Client side and Server side state management and what each offers. Why is state management such an issue? Well firstly because HTTP is stateless, after you make a request to a web server for a web page there is no further communication between you and that server. So to create a state, you use a state management technique, which can either be client or server side. With either technique you have several options and each option has some advantages and disadvantages.

My fear with session state management was the performance hit my server might take, but I have not really tested it enough to make that assertion.

  • Share/Bookmark
Tags:
posted by fr3dr1k in ASP.NET,Web Development,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

ASP.NET, handlers and IHTTPHandler

I have never used handlers (.ashx) files in any of my .NET web development projects, but this all changed in the last two days. The way I understand a handler is that it acts as a ‘process’ handler and does not write any output to the browser. Where would you use this? Well I used it for a shopping cart (but in hindsight I will change this) by using a handler to process the items added to the cart. The handler took a querystring and created a datatable of none existed or added the data to a datatable if that datatable already existed and stored the datatable in a session variable, which could then be accessed throughout the application. Accessing querystring variables in a handler file requires that you implement the IHTTPHandler interface, i.e. you cannot simply type Request.Querystring in the handler.

  • Share/Bookmark
Tags: ,
posted by fr3dr1k in ASP.NET,C# and have No Comments

Panel and its DefaultButton property

ASP.NET has a server control called a panel, which allows you to display other server controls or HTML elements inside it, and one of its properties is DefaultButton. By setting the DefaultButton to the ID of a button within the panel you basically set its default keyboard event that will fire the click event associated with that button. The other alternative to this would be to add the property to the TextBox in your CodeBehind.

  • Share/Bookmark
Tags:
posted by fr3dr1k in ASP.NET,C# and have No Comments

So, is everything event driven?

I am busy with a Silverlight video player at the moment, and what is interesting to note and understand is that Silverlight is heavily event-driven, as is ASP.NET and a lot of the .NET framework. You can attach event handlers to almost any object, from mouse event handlers to click event handlers.

Having asked that question I took a look at the ASP.NET page life cycle and just realised how intrinsic events are in the .NET framework. There are eight basic stages in the ASP.NET page lifecycle:

  1. Page Request
  2. Start
  3. Page Initialization
  4. Load
  5. Validation
  6. Postback Event Handling
  7. Rendering
  8. Unload

Within the page lifecycle there are events raised, which allows you to write code that initialises controls that are dynamically created.

  • Share/Bookmark
posted by fr3dr1k in ASP.NET,Silverlight and have Comment (1)

Nobody seems to know about Silverlight, for now

I would be the first to admit that not a lot of people have heard or know about Silverlight, which is Microsoft’s rich internet plugin, which is an alternative to Adobe’s Flash. It is true that Flash has been around for a long time and that Silverlight will not dislodge Flash’s entrenched following and use. But maybe, just maybe Silverlight was not designed for that purpose and that if people respond to Silverlight in certain ways it means they are taking some notice at least. The response clearly does not take into account the opportunities Silverlight offers a .NET developer. As a .NET developer I can use my C# skills to develop rich internet applications. I do not have to learn Action Script. Those same skills that I use to develop Silverlight applications can be used to develop WPF applications, ASP.NET applications and Windows applications.

  • Share/Bookmark
posted by fr3dr1k in ASP.NET,C#,Silverlight 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
Get Adobe Flash playerPlugin by wpburn.com wordpress themes