Thursday 25 August 2011

How you can log errors Part 1

In this post, which is in two parts, i would like to discuss about ways you can handle and log errors. It is really important to think about the strategy you are going to use to handle errors at an early stage. Why? Let us take a look at a simple example:


This is a simple try catch statement whereby the error is shown in a message box. If the application start to grow and there has't been a proper infrastucture layed out on how to cater for errors, there is going to be a lot of try catch statements as the one above, hence there will be a lot of duplication. You are going to need help with the project, and you are going to employ other developers to help. There are higher chances that the developers are going to employ their own ways of handling the errors and hence there is going to be inconsistency as far as handling errors is concerned.

From the above example, there is an important piece of information that is missing, the stack trace. It is not advisable to show the whole error to the user, but there should be a way of logging the error details so that it will be easy to trace the error, maybe to log to a file or send an email. Hence if you don't plan ahead there can be information loss concerning bugs that can occurr within the application. It is, therefore, important to plan on how you are going to handle errors at an early stage of development due to the facts i mentioned and others that you might have come across.

How can i handle errors?

There are different ways you can handle errors depending with the development environment you are in. But as you plan on how you are going to do it, one thing you must bear in mind is that it must be easy for maintenance, to use and to configure. Here are some of the tools you can use depending with your needs:


  • Trace.axd
  • Log4net - logging.apache.org/log4net/index.html
  • ELMAH - code.google.com/p/elmah/
  • PostSharp - www.postsharp.org
Apart, from these tools, you can create your own custom error handling tool or library. I personally have used Log4net. It is easy to configure and there is support for it from the community, though it is now looking like there aren't any upgrades being done. However, despite that fact, you have a wide range of tools to choose from that you can use to handle you errors.

Therefore, as you plan your architecture, you might want to consider which tool you can use that can complement with what you want to achieve. For instance, apart from, showing friendly errors to users, you might want to receive emails concerning critical operations that might have failed to execute, and that they would need your immediate attention. In this case, i would go for Log4net as an example.

If you have used any one of the tools that i have mentioned, i would like to hear about your experience. Or if you have used another tool apart from these ones, please do share. In the next part, i will go ahead and show you how you can address the problems that i mentioned earlier on if you don't plan on handling errors.



























Tuesday 16 August 2011

How do JavaScript Closurers Work

Closure

A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after that function has returned. A closure is a special kind of object that combines two things:
  • ·         A function
  • ·         A local variable that is in scope at the time that the closure was created.
In other words a closure is the local variables for a function kept alive after the function has returned or a closure is a stack-frame which is not deallocated when the function returns. 

For instance:

function  myFullName(){
                var firstname = “Tendai”;
                function getName(){     
                                alert(firstname);
}
getName();
}
myFullName();

The function myFullName() creates a local variable called firstname, and then defines a function called getName(). Function getName() is an inner function – it is defined inside myFullName, and is only available within the body of that function. As you can see, the function getName() has no local variables of its own, but reuses the name variable declared in the outer function, myFullName().

If you run the code, you are going to notice that it is going to show ‘Tendai’. This is an example of functional scoping, whereby the scope variable is defined by its location within the source code, and the nested functions have access to variables declared in their outer scope.

Let us look at another example:

function myFullName(){
                var firstname =”Tendai”;
                function getName(){
                                alert(firstname);
}

return getName;
}
var myName = myFullName();
myName();

This code will have the same result as before. The difference here is that, getName() is an inner function that was returned from the outer function before being executed. Under normal circumstances the local variables within a function only exist for the duration of that function’s execution. Once myFullName() has finished executing, it is reasonable to expect that the firstname variable will no longer be necessary, which is not the case here. 

The reason behind this is that myName has become a closure. Remember that a closure combines two things:
myName is a closure that incorporates both the getName function and  the local variable, string “Tendai”,  that was in scope at the time the closure was created.

Now the complete example:

function myFullName(firstname){
                return function(surname){
                                return firstname + surname;
};
}
var myFullNameTendai =myFullName(‘Tendai’);
var myFullNamePeter =myFullName(‘Peter’);
print(myFullNameTendai (‘Bepete’)); // Tendai Bepete
print(myFullNamePeter (‘Jacobs’));// Peter Jacobs

Here, the function myFullName(firstname) takes a single argument firstname and returns a new function. The function it returns takes a single argument surname, and returns a concatenation of firstname and surname.

Both myFullNameTendai and myFullNamePeter are closures. They share the same function body definition, but store different environments. In myFullNameTendai’s environment, firstname is Tendai and that in myFullNamePeter it is Peter.
Hope after reading this you had a better understanding on what closurers are and how they work. For further reading you can read this article.


Wednesday 10 August 2011

How to do an Ajax post with client side validation using JQuery

In this post I want to explain how to do an Ajax post with client side validation using JQuery. The idea here is to have an object that can validate itself and once it is valid the data is sent through to the server.

JQuery Syntax for Ajax Post

The syntax for doing an Ajax post is fairly easy to understand and it is as follows:

$.post(url,data,success,dataType)
  • The url is the URL to which the request is sent.
  • Data is the information that is sent to the server with the request.
  • Success is a callback function that is executed if the request succeeds.
  • DataType is the type of data expected from the server and it can be either xml, json, script or html.
For more information you can read this article.

Issue to be resolved


Now assuming that you want to register a person and you only have three fields, Name; SecondName and Surname. And that the only required fields are Name and Surname. The expected outcome is as follows:

If not valid:












If valid:














Html:

<div id="result">

</div>
<form id="frmAdd" class="frmAdd" action="">
    <div>
    <label id="lblName">Name</label><br />
    <input type="text" id="Name" class="data required" /></div>
    <div>
    <label id="lblSecondName">SecondName</label><br />
    <input type="text" id="SecondName" class="data" /></div>
    <div>
    <label id="lblSurname">Surname</label><br />
    <input type="text" id="Surname" class="data required" /></div>
    <input type="button" id="btnAddPerson" value="Add Person" />
</form>

Now take note that for the inputs, i have two classes, data and required. Data is to get the data that needs to be sent through and required is to mark the fields that need to be filled in.

Data object


The first part of my data object is the data itself that is going to be sent through and its properties. Take note that the names of the properties are identical to the input fields id that have class data.


        var myObject = {

            // data to be sent
            data: {
                Name: "",
                SecondName: "",
                Surname: ""
            },

The second part of the object is to reset if there were any errors that were flagged


            // removes any errors
            reset: function () {
                $(".error").remove();
            },



The third part is to assign the data's properties with values from the input fields will the class data.


            assign: function ($element) {
                //get the element id
                var id = $element.attr("id");
                // match the property with the element
                for (var prop in myObject.data) {
                    if (myObject.data.hasOwnProperty(prop) && prop === id) {
                        // get the value and assign it to the property
                        myObject.data[prop] = $element.val();
                        return false;
                    }
                }
            },


The last part is the validation. Take note that the first call is to reset, that is, remove any errors that were flagged so that if there errors persist they can be shown else there are no errors to flag.



            valid: function () {

                myObject.reset();

                var valid = true;
                // validate
                if ($("input.required").length) {
                    $(".required").each(function (index, obj) {
                        if ($(this).val() === "") {
                            $(this).parent().append("<span style='color:red;' class='error'>This is a required field</span>");
                            valid = false;
                        }
                    });
                }
                // assign
                if ($("input.data").length) {
                    $(".data").each(function (index, obj) {
                        myObject.assign($(this));
                    });
                }
                return valid;
            }
        };

Now the last part is the event itself when a user clicks the button AddPerson.


        $("#btnAddPerson").click(function (e) {
            e.preventDefault();
            if (myObject.valid()) {
                $.post(
                    "ajax-calls.aspx", url
                    myObject.data, data
                     function (data) { success                    
                         if (data.success) {
                             $("#result").append("<span style='color:green;' class='error'>Person added successfully</span>");
                         } else {
                             $("#result").append("<span style='color:red;' class='error'>Person wasn't added successfully</span>");
                         }
                     },'json' dataType
                     );
            };
        });

Take note that i have highlighted the parts that makes up the syntax used to do an Ajax post, that we discussed in the first part of this article, in red. Therefore, before we do the Ajax post, the data must be valid first and if it is valid then the data is sent through.

One thing that i like about this method is that, if for instance the username or password are fields that need to be added and are also required fields, all you have to do is modify the html and add the username and passwords to the data as properties and you are done. And you can also go ahead and add more functionality to validate if the data sent is of the right type on the client side.

I hope this will be useful to those who enjoy playing around with jquery. Any comments and suggestions are welcomed.




What is Ajax and how does it work

In this post I want to give a brief explain on what is Ajax and how it works.

What is AJAX 


AJAX stands for Asynchronous JavaScript and XML. What this means, is that you can update a part of a web page without reloading the whole page. Hence, you are updating a single part of a web page asynchronously by exchanging small amounts of data with the server behind the scenes.  


How does Ajax Work?

When a user requests a page, the server will send the full HTML and CSS code at once. After the user enters his/her details in a form and submits it, the server processes the information and rebuilds the page. It then sends the full page back to the client. And so on.

When using AJAX, the page is loaded entirely only once, the first time it is requested. Besides the HTML and CSS code that make up the page, some JavaScript files are also downloaded: the AJAX engine. All requests for data to the sever will then be sent as JavaScript calls to this engine. The AJAX engine then requests information from the web server asynchronously. Thus, only small page bits are requested and sent to the browser, as they are needed by the user. The engine then displays the information without reloading the entire page. This leads to a much more responsive interface, because only the necessary information is passed between the client and server, not the whole page. This produces the feeling that information is displayed immediately, which brings web applications closer to their desktop relatives.

To demonstrate the communication between the client (browser) and the remote server, as well as the differences between the classic and the AJAX-powered applications, take a look at the diagram below:


At the heart of the AJAX method of communicating with the server lays the AJAX engine. This is nothing more than some JavaScript code that instantiates and uses the XMLHttpRequest object. This is a JavaScript object that allows sending, receiving and processing HTTP requests to and from the server without refreshing the entire page.

In AJAX-powered applications, HTTP requests for data can be made completely in the background, without the user experiencing any interruptions. This means the user can continue working and using the application, while the necessary page sections are received from the server. The XMLHttpRequest object was implemented as an ActiveX object in Internet Explorer, and has later become a native JavaScript object in most modern browsers (FireFox, Safari).

Although adding an extra layer to any kind of model should add to the response time, this is an exception. Through the use of this new layer – the AJAX engine – response time shortens and the user interface seems much more connected to the application logic. Moreover, the user no longer has to wait around for the page to load.

For further reading you can visit the following links:
Stackoverflow
Exforsys
Interaktonline