Archive

Posts Tagged ‘JavaScript’

Are you writing JavaScript or JQuery?

November 22nd, 2009 1 comment

I’ve noticed that more and more, when I search for infromation for JavaScript I search for JQuery not JavaScript. Have I reached the point that I consider developing JavaScript code to be JQuery development? It is of sort natural, as JQuery close to eliminates alot of the work required for multi-browser support, it is better to have a JQuery backed solution.

I can only speak for myself, but it would seem that a lot of people are doing the same thing.

A library that acctually positions itself above the language it is written in? Accepted by both Google and Microsoft? The impact of JQuery on the web-development community is truly facinating,

RemoteX Localization Editor final touches

November 19th, 2009 1 comment

I’ve been working on a JavaScript client for our REST-service. So far it’s an editor for Localization and pick list options. But I was on a roll!

imageSo we charge by the amount of users each installation, lets add an easy way to calculate the amount of users. Download the list of users, and just count them. Pretty easy when then REST server is already in place.  To the right here you can see the end result of the view of the users. I did a similar one to calculate what we call resources.

While I was on that I figured I could add some graphs. I have a small thing for visual data. I found the JQuery Flot plugin, which suited my needs quite well.

I combined the flot plugin with our REST based search API and created some graphs. All cooked together I could produce a statistics view like this:

image

To finish things up I added the style used on RemoteX website, to get a consistent feel. This took some sweat, as the style sheet is generated HTML and CSS from dotNetNuke, and not exactly the same as my carefully handcrafted HTML. In the end I got it in and here is the end result.

image

RemoteX Applications Localization Editor next step

November 17th, 2009 No comments

In a previous post I mentioned that I started working on a localization editor for RemoteX Applications. This last week I started change a few things on the server side.

In RemoteX Applications there are certain combobox’es where you can change the content to customer specific lists. Previously they have been stored as XML files on the server, but this caused long process round trips for changing them. It also added cost to our Operations department at RemoteX. Currently were trying to reduce process costs and delays for our Operations to free up resources for tasks with higher value.

The list configurations are now stored in the database of the system, and is accessible through the REST service. Allowing me to create yet another web based editor.

This one was very similar to the first. Pick a list to edit, add or remove some keyword; then save.

image

The work was straight forward as it was so similar to the precious editor. The separation of concerns between the classes allowed me to just implement a few classes to get a first prototype up and running. The whole solution was completed in a couple of hours.

I added both editors to the same page, and quickly noticed one thing. If you changed editor you needed to enter your password and username again. This couldn’t do.

So I used the technique outlined in my other post about AJAX and Basic Auth, to add a single login dialog forcing the user to login when the page loads.

image

With some JQuery UI I got the above login dialog. Now the login state is available the entire duration of the “visit”.

Testing JQuery AJAX communication code

November 15th, 2009 No comments

I developed a JQuery Application using TDD these last couple of days. During the testing I used a new technique for testing my AJAX calls, so I thought I’d blog about how I test AJAX calls done by JQuery.

First of you have to see that there are several things to test in just a simple $.ajax call. There is not only all the combinations of the options, there is the behaviour of what to do when the call fails, or is successfull, or times out. There is a boundary between the JavaScript code and the server, will you pass it? Will you test the communication with a server, or even a mocked server using an XML file?

I’ve been testing $.ajax get operations using XML files as a mocked server backend for a while, but recently I mocked it instead.

Mocking $.Ajax requests is quite easy. Before you execute the code that will make the AJAX call, you exchange the ajax function.

$.ajax() = function(options) { options.fail(); };

The above line of codes forces the following ajax calls to automatically execute their fail callbacks. The function can easily be changed to simulate different behaviour of the AJAX requests.

Using this technique there is a risk, that the tests your writing become whitebox testing. The ajax mocking code becomes twins of the code your testing, resulting in a verification that the code is written as is, but not testing that it does what it should do.

JQuery: keeping your site-state in the addressbar

June 9th, 2009 No comments

More and more sites are doing it. Keeping their state in the address bar of the browser, enabling AJAX driven dynamic html pages to use the back and forward buttons between javascript driven views.  The most common website that uses this functionality, that I know of, is GMail. If you look at the address bar in GMail when in an message you can see that they added a bookmark hash (#) specifying which message to show. The updated address bar allows the application to keep state in the browser history.

I started working on a solution for this on my own, at the time I couldn’t find any JQuery plug-ins with the desired functionality. Now however there are several. In order to reduce the amount of specific code in my own application I tried out three.

JQuery History, JQuery hashchange and JQuery address .

JQuery address

After looking at JQuery address I can honestly say that it has the best fail-safe of the three I looked at. It uses full page post backs as a fallback. I haven’t been able to get it to work without reloading the entire page. So for that reason I cannot use the plug-in myself.

JQuery hashchange

This is my favourite. I has a nice and clean interface and does only what you tell it to do. However I couldn’t get it to work on Internet explorer 6. Which is also one of the reasons why I’m looking at the plug-ins to begin with.

JQuery History

JQuery history is actually the plug-in that led me to the others. I came in contact with another Mor.ph user who used it on his site. As far as I can tell from the usage of this it needs to interact with the link’s on the page in order to work properly. Catching the click events on the links. This is also a problem for me. I’d prefer just to update the bookmark hash.

Now while I couldn’t use any of these plug-ins I just wanted to give a shout out to people looking for them. They are there. A few things to think about, that I found out. Is that your page needs to be designed for this type of behaviour. If you use any of the plug-ins then your page will most likely be couple to that design. It’s also much easier to add this type of behaviour for the page in the beginning than appending it to already existing Ajax pages. These are my experiences with it.

I also lack a word for the technique of keeping your state in the address-bar.

IETester

May 27th, 2009 No comments

I found a new tool for testing web-applications in IE today. It’s called IETester, and it allows me to test IE versions 5.5 to 8 in the same application. Which is great, since my Vista machine only runs 8 normally.

I use it to verify my Grails application in IE6. Tonight I managed to create a unit test capturing the issue I was experiencing in IE6, using IETester and QUnit, so now I know where to take off tomorrow.

However it isn’t that stable, I’m running it on a 64-bit machine which might add some extra strain on the application. But for me it needed to be re-started or crashed a few times while I was isolating the bug I am working on.

Grails: Jetty and Character-encoding

April 20th, 2009 No comments

Im doing something not supported. I’m serving html files through my Grails web-app running Jetty. Simply I have some static pages that will not change. I want them served uncompiled. I use the resources-first plugin to help out with serving these html files.

The files are documentation, responses if you wish, for the user. I load them using Ajax to provide standard responses for some actions. The problem is that the responses are in Swedish. Jetty only serves them in ISO-8859-1, which is its standard configuration. According to this.

The issue I have is that I can’t change it. I can’t set a system variable to change the default encoding to UTF-8, not without having to do some programming. As  a result, the easiest way for me to handle this issue is to change my HTML files to GSP files. This forces me to serve them through the Grails stack and thus demands somewhat more resources from my poor server.

I tried to see if I could configure the Jetty-server to use UTF-8 as a default encoding, but alas according to this documentation I can only change it for the URI and not the content, and the URI is already set to UTF-8.

If anyone finds out how to serve HTML through the same server as Grails but with the correct encoding let me know. Right now I have a work around that will work for the next 6 months.

Update: Apparently, hosting just HTML files with utf-8 encoding set on the file, works in the production environment. Thank you Mor.ph.

Grails: UI-Performance plugin – issue with encodings

April 13th, 2009 1 comment

After getting the UI-performance plugin to work, I started to address an issue I got with charsets and my js files.

I have some Swedish messages in some of my JavaScript files, and as such they have Swedish characters. While I was branching them I managed to change the charset of the files somehow, so they weren’t UTF-8. Easy enough to fix. However, after fixing them the error still occurred in the production environment.

After some tracking it turns out that the bundling process of the UI-performance plugin works with the system default character encoding in some parts of the files, and with a specified encoding in another. Non-bundled files are OK. The missing code is in the ResourceVersionHelper.groovy file on line 357 to 364.

private void concatenate(List files, String name, String subdir, String ext, File stagingDir) {
    new File(stagingDir, "$subdir/${name}.$ext").withWriter { writer ->
        files.each { file ->
            writer.write new File(stagingDir, "$subdir/${file}.$ext").text
            writer.write '\n'
        }
    }
}

Fixing it could be like this, but adding the charset as a parameter will allow for better configuration.

private void concatenate(List files, String name, String subdir, String ext, File stagingDir) {
    new File(stagingDir, "$subdir/${name}.$ext").withWriter( "utf-8", { writer ->
        files.each { file ->
            writer.write new File(stagingDir, "$subdir/${file}.$ext").getText('utf-8')
            writer.write '\n'
        }
    })
}

Still nice work Burt.

Jira ticket: http://jira.codehaus.org/browse/GRAILSPLUGINS-1079

Update: This is resolved in version: 1.1.1 of the UI-Performance plugin

Grails: UI-performance plugin

April 12th, 2009 2 comments

I installed the UI-performance plugin last night. Configured it to bundle my javascript code into a single compressed file. Did the same with my CSS files.

With everything bundled and compressed the size of the the page download is reduced from 485 Kb to 187 Kb.

I only had some minor configuration problems but those were just related to my own typos. Apart from that it all now works perfectly.

The plugin saves me the time it would take me to produce a build step to produce the same output, and it even does more than the initial idea for my own build step. Thank you Burt Beckwith for a job well done!

Grails: Ajax Login using Basic Auth

April 7th, 2009 No comments

So I have my Grails environment setup. The point is to build a REST-service that will work as a back end to a highly dynamic JavaScript page. I chose Grails, since it builds on Hibernate and Spring.

Two frameworks Id like to examine for the purpose of seeing the differences between Castle and nHibernate in the .Net world.

Building domain-classes and having the represented as XML is straight forward in Grails, but I need to take care of the login scenario. If you’d like to know more about building REST web services with Grails, I recommend reading the Mastering Grails: RESTful Grails article. Login seems like a good place to start, to ensure that my domain-controllers can dictate login as I develop the domain.

Now Grails.org has a list of tutorials, one of them, focusing on Login. It’s a good beginners tutorial showing how to use interceptors to execute user verification before showing the actual view requested. For my scenario however it has a few problems. Lets use the tutorial as a start of point.

The problems I have with the solution is with the following code:

def checkUser() {
  if(!session.user) {
    // i.e. user not logged in
    redirect(controller:'user',action:'login')
    return false
  }
}

For my scenario this has one problem, in two places. Its stateful. First of it always directs the user to the same place, of course it can be different per controller. I need it to simple say access denied.

def checkUser() {
  if(!session.user) {
    // i.e. user not logged in
    response.sendError(401)
    return false
  }
}

The above code is changed to instead of redirecting the user, it simply sets the response code to Access Denied. Now there’s just one issue left, the session code.

I don’t want to use session, as it requires my server to remember each session, preferably I want the client to remember the state.

Another issue is that I want to use Mor.ph AppSpace, if I pay for the most basic of subscriptions at Mor.ph I get two Cube, i.e. two servers with a load balancers in front. As a result I can’t be sure that the same server will service the same client all the time.

If we instead choose to check for the logged in user using the authorization header. The state is always provided by the client, instead of keeping the state on the server.

def checkUser() {
  if(!UserController.checkAuthorization(request, response)) {
    // i.e. user not logged in
    response.sendError(401)
    return false
  }
  return true
}

I let the UserController do the checking of the user, using a static method. This will let me keep the authorization code in the same place I handle users to begin with. It also allows me to change the authorization method later by changing the code in the checkAuthorization method. We could use Dependency Injection here to inject a real instance of the UserController, or even better an object with the sole responsibility to check user access. However DI is out of scope for this post.

You can implement any way of checking the user login you want. If you want a simple solution and stick with the HTTP standard you could use Basic auth. Here is a good explaination of how to implement Basic auth for Grails. Another way is too use a cookie to hold authorization information.

For this example were just sending username:password in the authorization header. My final implementation will be Basic Auth with the password hashed to a checksum. The point of the hash is to never send plain-text password across the net.

Here is the checkAuthorization method in the UserController for this example.

static boolean checkAuthorization(HttpServletRequest request, HttpServletResponse response) {
  def authString = request.getHeader('Authorization')

  if (!authString) {
    return false;
  }

  def credentials = authString.split(':')
  if( credentials.length != 2 || credentials[0] == null || credentials[0] == "" || credentials[1] == "" || credentials[1] == null)
    return false;

  def user = User.findByEmailAndPassword(credentials[0], credentials[1])

  if (user) {
    return true;
  }
  return false;
}

Now we can create some JQuery based JavaScript code to handle login.

function RestClient() {
    var self = this;
    var auth;

    function ShowLoginUI(afterLoginCallback) {
        var dialog = document.createElement('div');
        $(dialog).html("<table><tr><td>Email</td><td><input id='email' type='text'/></td></tr><tr><td>Password</td><td><input id='pass' type='password'/></td></tr></table>");
        $(dialog).dialog({ buttons: {"Login": function() {
            auth = $(this).find("#email").val() + ":" + $(this).find("#pass").val();
            afterLoginCallback();
            $(this).dialog("close");
        }, "Cancel":function() {
            $(this).dialog("close");
        }}, modal:true});
    }

    this.Get = function(url) {
        var data = null;

        data = $.ajax({
            url : url,
            method : 'GET',
            beforeSend : function(req) {
                req.setRequestHeader('Authorization', auth);
            }, cache : true,
            error: function(request, textStatus, error) {
                if (request.status == 401) {
                    ShowLoginUI(function() {
                        data = self.Get(url);
                    });
                }
            }});

        return data;
    };
}

The above code does Ajax Get-calls to the specified address. If the call failed due to Access Denied, it shows a login form and tries to execute the Ajax request again. The class remembers the authorization string, so as long as the user uses the same RestClient-object the state is maintained at the client side.
Ill leave instructions on how to wire up Grails with JQuery to someone else.

Here is a simple usage example:

var a = new RestClient();
$("#test").click(function() {
  var data = a.Get("plant/create");
  $(document).append(data);
});

Good luck writing scalable login scenarios using Ajax instead of page reloads.