Fremus.co.za

Demistifying Life and Web Development

Daily Code – Day 3 – How do I understand “Unobtrusive JavaScript”

In my previous job I learnt the unfortunate bad habit of attaching onclick events to DOM elements, in other words I would take a div and add an onclick event to it. I realised at some point that this was a very bad habit and clearly nobody took the time to understand how it should work. Instead of doing the onclick thing you should be attaching “event listeners” to your elements so that when you click on them they are triggered. Still don’t understand what I mean? In the past I might have had this:

Instead you should do something like this:

Then you wire it up using jQuery’s Live event like this:

$(".mySillyClickableArea").live("click", function () { });

This has several obvious advantages:

  • Your markup is much cleaner
  • You dont have to add multiple onclicks for multiple elements. Instead apply an event to a class

If you did it like I did before, stop, and re-evaluate!

  • Share/Bookmark
Tags:
posted by fr3dr1k in jQuery and have No Comments

Daily Code – Day 2 – Use jQuery Data Templates

In yesterday’s blog post I illustrated how I can generate dynamic types, and return that dynamic type as JSON. Today I just want to show how I display the JSON data. To get the JSON data you have to make an AJAX call to the controller method, and you do this by using $.ajax like this:

    var restEndPoint = serviceURL + 'Home/GetOfferings';
    var templateId = '#offeringCheckTmpl';
    var data = '';
    var divToFill = '#offeringList';
    $.ajax({
        type: "POST",
        url: restEndPoint,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "json",
        data: data,
        success: function (msg) {
            var jsonObj = JSON.stringify(msg.Offerings);
            var temp = JSON.parse(jsonObj);
            if (templateId != null)
                $(templateId)
                    .tmpl(temp)
                    .appendTo(divToFill);
          }
    )};

The important bit is where I call the tmpl function and use a another script tag titled #offeringCheckTmpl which contains html and other bits. It looks like this:


Notice the ${OfferingId}, it matches up to the OfferingId field in your JSON object and basically maps it to the value and displays it. Using templates in this way makes it easy to create re-usable html without having to do string concatenations in your functions.

  • Share/Bookmark
Tags:
posted by fr3dr1k in jQuery and have No Comments

Daily Code – Day 1 – ASP.NET MVC: Using Json() to create dynamic types

Do you ever have to return more than one result set, or dataset for that matter to some UI? If for instance you have a piece of UI that allows users to create something new with by entering a value into a textbox AND by selecting a value from a dropdown list AND you are displaying existing (already added) data in a table below the dropdown and the textbox and they all appear on a modal dialog. Logic tells me that when I click to activate the dialogue the dropdownlist and the table with the data must be populated with data. It also tells me that its not feasible to make two jQuery ajax calls, one for the data in the table and another for the data in the dropdown. What to do? Return arrays of objects with one ajax call and bind it to the UI. How do you return arrays of objects in ASP.NET MVC? Well you can create dynamic objects like this:


        [HttpPost]
        public JsonResult GetOfferings()
        {
            offerings = new OfferingRepository();
            offerings.GetOfferings();
            offeringTypes = new OfferingTypeRepository();
            offeringTypes.GetOfferingTypes();
            return Json(
                new
                {
                    Offerings = offerings.Offerings.Select(t =>
                        new
                        {
                            OfferingName = t.OfferingName,
                            OfferingId = t.Id
                        }),
                    OfferingTypes = offeringTypes.OfferingTypes.Select(t =>
                        new {
                            OfferingTypeName = t.OfferingTypeName,
                            OfferingTypeId = t.Id
                        })
                });
        }
  • Share/Bookmark
posted by fr3dr1k in ASP.NET MVC and have No Comments

HOWTO: Check all items, and get all checked items

I often find myself re-using code, in the bad way (copying and pasting) without really remembering how it was done, and this is particularly true for JavaScript. I could easily say that I do most of my JavaScript with jQuery, so here is a function that enables all checkboxes with a given name:

var general = {
    selectAllEntities: function (chkBoxName, checked) {
        $('input[name=' + chkBoxName + ']').each(function () {
            $(this).attr("checked", checked);
        });
    },
    getAllCheckedEntities: function (chkBoxName) {
        var entityValues = [];
        $('input[name=' + chkBoxName + ']').each(function () {
            if ($(this).attr("checked")) {
                entityValues.push($(this).val());
            }
        });
        return entityValues;
    }
};

jQuery makes it easier with its $ selector, so if I had to write this without jQuery the code might be significantly longer.

  • Share/Bookmark
Tags:
posted by fr3dr1k in jQuery and have No Comments

Paging for ASP.NET MVC

I bought Steve Sanderson’s book Pro ASP.NET MVC about 6 months ago and I must admit its a real winner for the single reason that the code and explanations are clear and to the point, and he actually gives you code you can use easily. In chapter 4 he builds a paging helper class which is really cool and works well when you bind the model to your view but the way he implements it could be made better by creating a class that accepts a generic type and I also want to use this method for Ajax/jQuery. The code in his book for the PagingInfo class looks like this:

public class PagingInfo
{
	public int TotalItems { get; set; }
	public int ItemsPerPage { get; set; }
	public int CurrentPage { get; set; }
	public int TotalPages
	{
		get
		{
			return (int)Math.Ceiling(decimal)TotalItems / ItemsPerPage;
		};
	}
}

In the controller in his book he then creates a class called, ProductsListViewModel, which has two properties, IList Products and PagingInfo PagingInfo:

public class ProductsListViewModel
{
	public IList
 Products { get; set; }
	public PagingInfo PagingInfo { get; set; }
}

On a side note I must say I agree in part with Jeffrey Richter in his book C# via CLR that properties are a weird mix of a method and not a method and sometimes it does feel as if what you are doing in a property might work in a method also. But I digress. In his controller he has a action result that binds the ProductsListViewModel to the view:

public ViewResult List([DefaultValue(1)] int page)
{
	var productsToShow = productsRepository.Products;
	var viewModel = new ProductsListViewModel
	{
		Products = productsToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList();
		PagingInfo = new PagingInfo {
			CurrentPage = page,
			ItemsPerPage = PageSize,
			TotalItems = productsToShow.Count()
		}
	}
	return View(viewModel);
}

Before I continue there are a few things to note about the controller method and the first is that I have not shown the productsRepository and its implementation and the second thing to note is that PageSize is a public variable declared in the controller class.

The code works great, and I have used it now in several places and I really like it because it feels as if the PagingInfo class provides an abstraction that the entity you are paging does not know about. This makes it feel light and easy to implement. I do however think it might be useful to create a class that accepts a generic type instead. So what I have done is create a class called EntityViewModel, and it looks a bit like this:

public class EntityViewModel
{
	private List listOfEntities;
	private PagingInfo pagingInfo;

	public List ListOfEntities
	{
		get { return listOfEntities; }
		set { this.listOfEntities = value; }
	}
	public PagingInfo PagingInfo
	{
		get { return pagingInfo; }
		set { this.pagingInfo = value; }
	}
}

This will mean that when I create a controller method I can do this instead:

public ViewResult List([DefaultValue(1)] int page)
{
	var productsToShow = productsRepository.Products;
	var viewModel = new EntityViewModel
	{
		ListOfEntities = productsToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList();
		PagingInfo = new PagingInfo {
			CurrentPage = page,
			ItemsPerPage = PageSize,
			TotalItems = productsToShow.Count()
		}
	}
	return View(viewModel);
}

Which to me seems a bit more flexible. It doesnt end there though because I want to consume the controller method using jQuery and jQuery templates and for that I need to change the controller method slightly:

public JsonResult List([DefaultValue(1)] int page)
{
	var productsToShow = productsRepository.Products;
	var viewModel = new EntityViewModel
	{
		ListOfEntities = productsToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList();
		PagingInfo = new PagingInfo {
			CurrentPage = page,
			ItemsPerPage = PageSize,
			TotalItems = productsToShow.Count()
		}
	}
	return Json(viewModel);
}

Now I can get a JSON result, AND it has paging which is totally awesome!

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

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

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

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

AJAX form validation – LiveValidation

Here’s the thing right, I really want to create a nice contact form for my website, but I also want to make sure that the form accepts the right type of information. For this I need some JavaScript and of late I have been reading a lot about JavaScript libraries such as jquery, mootools and prototype. I have also worked a bit with ASP.NET Ajax, but I do find the .NET implementation does hide a lot of the inner workings of the JavaScript and does not force you to understand the core references as some of the other JavaScript libraries do. With .NET you can get some AJAX running without touching much JavaScript code at all.

So the contact form on my website should allow visitors to send an email with their name, email address and a message. All three fields are required and should not contain empty values. The validation will be done server side, so that the user can see what they are doing wrong immediately and take any necessary steps to correct the information they entered.

One thing that has been bugging me recently has been to find an easy way to validate forms, and I came across LiveValidation. It’s pretty easy to setup and use, and I will be using it to create the form described above.

I also downloaded Amaya, an free XHTML editor, since I am extremely keen on sticking to Web Standards and all.

The basic structure for the form can be seen here. The form requires all three fields and validates the email address field, and if the email address field is found to be valid a alert message box appears on the screen. The underlying JavaScript code is quite interesting to note:

var fld_name = new LiveValidation( 'fld_name', {onlyOnSubmit: true } );
fld_name.add(Validate.Presence);
var fld_email = new LiveValidation( 'fld_email', {onlyOnSubmit: true } );
fld_email.add(Validate.Email);
fld_email.add(Validate.Presence);
var fld_msg = new LiveValidation( 'fld_msg', {onlyOnSubmit: true } );
fld_msg.add(Validate.Presence);
var automaticOnSubmit = fld_email.form.onsubmit;
fld_email.form.onsubmit = function(){
    var valid = automaticOnSubmit();
    if(valid)alert('Thank you for submitting your message!');
    return false;
}
  • Share/Bookmark
posted by fr3dr1k in AJAX,Web Development,Web Technologies and have No Comments
Get Adobe Flash playerPlugin by wpburn.com wordpress themes