Fremus.co.za

Demistifying Life and Web Development

Archive for the 'ASP.NET' 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

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

Mimicking AJAX behaviour with Generic Handler (.ashx) file uploader

Earlier today I posted a blog about using a generic handler (.ashx) to upload a file to a web server, and in the back of my head I wanted to use it somewhere neat and special, and I also want to find the most reliable and working version. And I also want to learn what the approaches are to doing so, and why not to do it a certain way, etc.

So back to the topic of the post and the first thing that needs to be understood is that you CANNOT upload files with AJAX/JavaScript. This is because of you cannot retrieve the contents of a file off a local system, and if this was so it would cause major security headaches. So what I ended up doing is following the IFRAME approach, by which you make it look as if the upload is happening all AJAX-like when in actual fact its not. So what I did was create an IFRAME:

Notice that I added a div called divTimerValue, which I use to display some progress indicator, in my case it will be busy that will grow and subside with dots. In the source file (where the IFRAME points to) I create a form:

Notice that it has the ReturnValue.ashx action and that I have added an onclick function to the submit button, which looks like this:

        function dotsAnimate() {
            parent.document.getElementById("divFrame").style.display = 'none';
            var dotspan = parent.document.getElementById("divTimerValue");
            dotspan.style.display = '';
            setInterval(function() {
                if (dotspan.innerHTML == 'busy...') {
                    dotspan.innerHTML = 'busy.';
                }
                else {
                    dotspan.innerHTML += '.';
                }
            }, 1000);
        };

The dotsAnimate function uses the setTimeout function to create the animation. The generic handler then returns some HTML that contains a javascript function that clears the timeout and prints a message in the divTimerValue div:

        context.Response.Write(@"");
        context.Response.Write(savedFileName);

And this code produces the desired result.

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

Uploading files with a generic handler (.ashx)

In recent times, the last year or so, I have come to move away from web forms and move more towards an architecture that involves plain html combined with web services or in some cases generic handlers. I like this approach because it allows me to perfectly control the quality of the HTML that is rendered, which in turn is good for a few reasons, one being search engines and the other being true to web standards (or at least trying to). Its relatively easy to combine an asynchronous call with an ASHX file. ASHX files are lighter in terms of processing than their ASPX counterparts. With that in mind I decided to write or create a generic handler based on Scott Hanselman’s example here. And it works! Thats the key thing.

First create an HTML file and add code for a form like this:

Then you create the code in the ASHX file like this:

        string savedFileName = "";

        foreach(string file in context.Request.Files)
        {
            HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile;
            if (hpf.ContentLength == 0)
                continue;
            savedFileName = context.Server.MapPath(Path.GetFileName(hpf.FileName));
            hpf.SaveAs(savedFileName);
        }
        context.Response.Write(savedFileName);
  • Share/Bookmark
Tags:
posted by fr3dr1k in ASP.NET,C# and have No Comments

Sites that use Silverlight, updated

Last year July I wrote a blog post that listed some sites that use Silverlight to power rich application content. Twelve months later and I have found a few more cool ones, although the Hardrock Memorabilia site still remains my favourite.

ShineDraw still remains a great site for checking out the same things done in either Flash or Silverlight. And its updated regularly, which is always great.

In the meantime though I have found two other cool examples of Silverlight:

  • Share/Bookmark
posted by fr3dr1k in Silverlight 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

using System.Web.UI.DataVisualization.Charting;

Ok so I recently got a request to do a project that uses all kinds of pretty charts, and initially the development team wanted to use Open Flash Charts, but the developer I was working with on the project was on leave for two days and in that time I decided to check out New ASP.NET Charting Control: . First thing you need to do is download the free Microsoft Chart Controls and install that on your machine. Note that once installed it creates a folder under Program Files called Microsoft Chart Controls, with another folder called Assemblies under that, which contains DLL’s for both web and application. Once you have installed Microsoft Chart Controls you can choose to add the VS 2008 add-on if you are going to be doing web-forms development, but if like me you use a lot of web services and AJAX, you may not need it. So how do you get to use it then otherwise? By adding these two lines in your web.config file:



You then have access to a range of classes by typing the fully qualified namespace like this:

System.Web.UI.DataVisualization

Once you have access to the classes you can do all sorts of interesting things. You get to choose from 35 different chart types, that you can format with colours, 3D effects. And you can also use data with it very easily with a datareader, which impressed me. You can also save your charts as images.

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

My Top 5 .NET Resources

I use Google a lot for .NET resources, but I do have a few places I read a lot, and not just to get solutions but also to read about other people’s solutions. Reading about other people’s solutions is a key to learning, and learning is important to any developer’s success. Here are my top resources for .NET related topics:

  • ASP.NET Forums: Ever noted that a lot of the Google search results for ASP.NET point to posts on this forum. Do yourself a favour and register, and try to visit as regularly as possible, try and answer a few questions, or just read the solutions that are posted there. You will learn something. The posts are very fresh and is updated by the minute, so the content grows, so no chance of stagnant content.
  • Scott Guthrie’s blog: This blog has all the latest stuff on it, from ASP.NET MVC to Silverlight. If you want to know whats new make sure you read this blog.
  • Shine Draw: Looking to do something in Silverlight that you have seen done in Flash? Take a look here and maybe you can draw some inspiration.
  • 4 Guys from Rolla: Scott Mitchell has written a lot about .NET, and I read his article about URL Rewriting in ASP.NET on MSDN, so the articles on 4 Guys From Rolla really cover relevant and good topics. I also found that they write the articles in relatively easy to understand language.
  • Codeplex: Is Microsoft’s Open Source project hosting site and contains a lots of .NET projects
  • Share/Bookmark
Tags:
posted by fr3dr1k in ASP.NET,C# 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
Get Adobe Flash playerPlugin by wpburn.com wordpress themes