Fremus.co.za

Demistifying Life and Web Development

Archive for the 'Web Development' Category

Dealing with Circular References in EF4/JSON

I like the many-to-many mapping EF4 provides you simply because it allows such great navigation between entities and its easy to shape the query from one side to other and vice verse. The only issue is that it causes issues with JSON serialization, because the serializer does not know how to handle circular references, it can only serialize one way. Initially I dealt with this issue by creating “view classes” but it seemed rather tedious and pointless, so instead I started using the enumerable Select() method. It provides a very easy way to construct “anonymous objects”. So in my controller I would have a JSON Result and I would do something like this:

Json(courses.Courses.Select(t => new { CourseTitle = t.CourseTitle, CourseCode = t.CourseCode, CourseId = t.Id }));

Pretty damn neat, considering that Courses is a EF4 entity and I dont have to go and change or adapt it to play nicely with the JSON serializer.

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

Product Navigation Design

As I mentioned in my previous blogpost I am busy working on a website at the moment and a part of the website display dynamic product-related content. I believe that the product navigation is not perfect yet and I think it might be a good idea to take a look at some examples and draw a few conclusions from it. The first example I looked at this morning was Hi Fi Corporation (I was looking at some LCD tv’s) and immediately I started looking at the way the product navigation was done, and here are some of my thoughts:

Products are divided into categories and each category is displayed in two areas, the horizontal menu at the top and a vertical-collapsible menu to the right. Each category links to its own individual page, e.g. prods/audio for Audio products. When you click through to a category page the category bar remains to the left, with another “product filter” bar that appears below it.

On the category page for audio, here, there is a product comparison box and a paging component. Notice that the pages aren’t individual pages but javascripty/ajaxy items. Each product however has its own dedicated permalink. Isn’t it equally important to link to pages? Or is that not that important due to the nature of the data?

If you go to another website, Take 2 (my favourite online retailer for DVD’s and books), you will notice that if you click through to electronics (which is a category much like the Hi Fi Corporation example) you get to a page with sub categories to the left, which when clicked on (e.g. Mp3 Players) produces a paged result page. The difference from the Hi Fi Corporation example is that the pages are not ajaxy and you could probably access an individual page with a link – whereas the Hi Fi Corporation example you couldn’t. I’m not saying its a bad thing, just stating the difference. How would you design a product pager? Make it URL accessible? If you take a look at this Amazon.com page you will see that the paging is ajaxy. The Amazon.com page I just linked to is also bound by category, software architecture, as was the Take 2 and Hi Fi Corporation example. Would it be wrong to surmise that categories are permalinks and the products/items on them are page-able and that the individual pages are not permalinks? I can understand why a page within a category would not make sense as a permalink – simply because the data might change and move around. If 20 new books on software architecture were added today that would affect the pages. You could also argue that a page could give you the top 10 new items which might make sense in a MVC architecture where you could apply action filters.

What would the ideal product navigation design be? Well the ideal product navigation design would take the functional aspects into consideration and produce an effective solution.

  • Share/Bookmark
posted by fr3dr1k in Web Design and have No Comments

A Quick Look at some website design / functionality

I have been working on a new website recently and its far from perfect – in fact I see it being refactored several times before I think it will reach an optimum phase or place. That being said business people don’t buy-in or the see the value in refactoring, so its something only the developer is aware or should be aware of. I digress.

Parts of the design I have been working on seems to have been using scrollable areas a lot and personally I see that as a fatal design flaw for two major reasons:

  • You are forcing design onto the natural flow of information on a web page. Surely the design should work with the flow and nature of a website and not against it. Content is the most important asset on your website and should ideally have a natural flow to it. Personally if you are using too many scrollable areas, you should re-look your design.
  • Not many websites use scrollable areas. Its ok to be different, not indifferent.

In case you are wondering what I mean by scrollable areas, it refers to applying the height property to an area and setting the overflow: auto. The effect is that you have a scrollable area. I cannot find many sites that use this technique actually.

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

Calling all Young African (Web) Designers

Africhic and Quirk eMarketing have devised a way to give Web Design hopefuls a shot at a year’s paid internship at Africa’s largest full service digital agency and the chance to shine by designing the winning new skin for the online shop, Africhic.com. You’ll find the full brief here.

Africhic was the winner of the Africa Fashion Awards Retailer of the Year 2010, a worthy honour as Africhic.com does far more for aspirant young African designers than flog their fashion on the Internet. Rather it gives South African fashion designers and increasingly, designers from the rest of the continent a platform to showcase their work, philosophy and passion for African design to a global market.
Quirk eMarketing and Africhic are offering students in the creative fields an opportunity to showcase their own take on African creativity by redesigning the look and feel of the Africhic website. Fashion legend, Robyn Cooke will be on the panel of judges. Robyn is a long time player in the local fashion scene and is respected as a stylist, as the editor of Styleguide Cape Town and as Fashion Editor for O Magazine.

Submissions close 30 September 2010 and the winner will be announced shortly thereafter and will see their artwork come to life on the new Africhic website, as well as R5000 in online credit for their shopping pleasure on Africhic.com.The winner will also be able to pursue a career in the digital creative arts, kick started by a coveted internship at Quirk eMarketing. 

Quirk has a passion for creativity in Africa and is promoting this competition with Africhic by offering the winner a Web design internship. The Quirk internship programme is a year’s paid apprenticeship under the watch of some of the best minds in marketing and technology in South Africa. Quirk is a leading digital agency with branches in London, Cape Town and Johannesburg, and Quirk’s interns have the unrivalled opportunity to glean the latest knowledge in the new media and digital fields, and to contribute their minds and talents to the development and implementation of exciting digital campaigns for clients such as DStv, Distell, Sun International and SA Tourism.

The Ethical Fashion Movement
Fashionistas of the world are currently spending in the region of US$1trilion every year on clothes, while ethical fashion is a growing trend with 27 percent of British consumers surveyed saying they are willing to pay a premium for fashion, footwear and accessories produced in a socially and environmentally sustainable way.

Clothing and textiles represent seven percent of the world’s exports, and in light of the current demand for sustainable sourcing, innovation in skills, recycling, and organic fabrics, all practices that African designers have been promoting for years, there is a bright opportunity for African fashion businesses to successfully compete in the international market for fashion.

“Quirk instantly took a liking to Africhic because of the evident pride the website takes in African innovation, a passion Quirk shares,” says Emma Carpenter, Creative Director at Quirk eMarketing.

“Africhic’s advocacy on behalf of local, aspirant talent and promotion of ethical fashion are values Quirk can stand by. The skin design competition we are supporting should work to further strengthen the image of South Africa as a source of creative talent, including digital talent, and to make people aware of the wealth of creativity Africa has to offer,” says Carpenter.

To Enter:
Submissions should reflect high fashion with a global appeal, while remaining true to the spirit of Africa, both urban and ethnic. The winning submission will add a new and fresh layer of meaning to outdated and over-used notions of African fashion and culture. Think Shack chic, modern versions of Africa and let the creative juices flow. The deliverables on this project are in the brief.

About Africhic:
Africhic.com is an online luxury fashion retailer for African designer fashion. It boasts a virtual catwalk on which local designers Suzaan Heyns, Undacova, Stiaan Louw, Lunar, Michelle Ludek, Kenyan designer, Lalesso and others showcase their talent, giving fashionistas all over the world the chance to buy unique designer fashion that is 100 percent African and 100 percent ethically sourced. Our vision and goal is to increase our stable of designers to 50 by the end 2010 and to advance the local industry and African fashion more generally through increased exposure and access to these products.

What the Quirk?
Quirk eMarketing is strategy-led full service digital agency with branches in London, Cape Town and Johannesburg. Quirk was born in March 1999 with the sole purpose of providing innovative digital services to the global business community. Known for being smart and creative, we have a passion for digital and are constantly updating our skills and services in the belief that enough is never enough. Using our unique knowledge and abilities, we apply the fusion of marketing and technology for the benefit of your business. Today, Quirk is an ever-growing agency with a loyal client base that includes brands like Capitec Bank, DStv, MWEB, Distell, Sun International, The Financial Times and Warner Bros.

  • Share/Bookmark
posted by fr3dr1k in Web Design and have Comment (1)

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

Choosing a JavaScript library/strategy

JQuery, prototype, scriptalicious, moo tools and Microsoft Ajax are all JavaScript libraries that encapsulate common functionality, or rather commonly repeated tasks, into a re-usable form. One such example is accessing DOM elements. Usually you would type document.getElementById to get to a div element for example, which also implies for each element you access you have to type document.getElementById. Most JavaScript libraries provide an easy way to access elements, usually through a dollar($). In jQuery you simply type $(‘elementID’) and in Microsoft Ajax you type $get(‘elementID’) to get to the object. So basically the library has encapsulated the document.getElementById in some JavaScript function, and that function simply returns the object. Most JavaScript libraries also provide built-in AJAX functionality, which means that the library makes it easy to create XMLHTTPRequests. The libraries also make it easy to do all kinds of special effects such as animations and modal popups.

So which one do you use? What determines which one you use? Well personally I would take a pragmatic approach and say that no matter which library you choose, you still have to learn the basic concepts such as how HTTP requests work and how things are executed. Once these things are understood you can pick a library and make sure you learn it. Whether you pick jQuery or Microsoft Ajax is irrelevant, because with both you will have to spend time learning how the API works. I often find myself in a situation where I want to jump between libraries because I feel that there is a wow feature in the one and not the other. I also find myself creating my own JavaScript at times because I just don’t need the entire library. The most important thing to know though is that you have to commit your time and energy to learning JavaScript with or without the use of a library.

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

Deciding on a web-based user login system

This article aims to discuss some of the web-based user login systems that are available to .NET developers, and aims to provide some clarity. In my view there are three approaches that can be followed to developing a web-based user login system for .NET:

  1. Write a custom solution
  2. Use existing ASP.NET Membership and Roles
  3. Use OpenID


Writing a custom solution

I think its easy thinking I can write my own custom login system, right? I mean what are the things I must consider for writing my own custom login system. I must consider that users will each have an unique login and that users will be grouped into roles. Thats as far as basic structure goes. But how do you maintain a user’s login session for example, or when do you consider the session over? I have also seen systems that store user passwords in clear text, which means your system MUST use some sort of hashing or encrypting of passwords. There is a lot involved in writing a custom user login system, a lot more than meets the eye.

Use existing ASP.NET Membership and Roles

The ASP.NET Membership and Roles ships with .NET 2.0, and is implemented as an API in code.

Use OpenID

Stackoverflow uses it!

  • Share/Bookmark
Tags:
posted by fr3dr1k in General,Web Development and have No Comments
Get Adobe Flash playerPlugin by wpburn.com wordpress themes