Monday 12 December 2011

We are also contributing to road accidents

Advancement in technology is a good thing. It improves our standards of living. Take for example the mobile-phone and the internet. Now you can call anyone anywhere as long there is coverage. With the internet, well you can now get information instantly, share your thoughts with the world and so on …

But are we responsible when we use all these goodies that we have? I once had a discussion as to what is the major contributor to road accidents in South Africa. And we couldn’t pin point the exact reason because all most all the points we came up with contributed. Apparently our innovations and creations in web and mobile development contributed, for instance, twitter; whats app; mix-it; Facebook and so on …

Yes these applications have helped us in one way or the other, but they are also destroying us. I am sure there is more or less the same debate when it comes to the use of guns. The manufacturer is not to blame, because he/she isn’t pulling the trigger. It is all up to the end user as to when and how to use these products.

Well I think as developers we need to take action and try to educate users on the dangers of texting, twitting or being on Facebook while you drive. It only takes a split second and before you know it you are either in a hospital or worse caused someone to die. I am urging all those who will be driving during this festive season or any other time, to be careful. DO NOT USE YOUR CELL PHONE WHILE YOU ARE DRIVING. Let’s embrace technology and use it to improve our lives not the other way round.  

Tuesday 29 November 2011

Is Facebook necessary?

Have you ever wondered what it was like before Facebook? Or what will happen if Facebook is to be no more? For me it is not going to change anything, it's not like it will be the end of the world. But one thing for sure we have to give Mark Zuckerberg the respect he deserves for being innovative.

Before Facebook, i was not in touch with people i knew when i was doing my primary education or even with my relatives that are abroad. It all changed when i joined FB, i was amazed with how easy it was to be linked to  people, from relatives to friends and friends of friends ... So i was in touch but only for a short while. To be honest, i joined FB so that i can check on people i knew ... what are they doing ... who is married ... who has kids .... and so on ...

It was also a platform for engaging in meaningful debates ... be it sports, politics, relationships ... i could share my thoughts with a lot of people. But for some reason i just stopped using FB. If i want to be in touch with my brother or sister, i either call or send an email. If i want to talk about sports or politics i visit my friends. And guess what, i am still not in touch with people i knew when i was in primary ... I am sure they were more curious to know how i was doing than to get in touch with me again ... which i am also guilty of ...

So after FB, everything is still the same. Nothing has been added or removed in my life. And i just came to one conclusion ... for me it is not necessary. I do not know about you, maybe it is great ... you use it to remind you of people who are having birthdays ... to stoke someone ... to check progress on others ... to stay in touch with relatives and friends ... and so on ... I would, however, like to know what you think about FB ... till next time ...

Friday 4 November 2011

Should We Support Old Browsers?

A lot has happened over the past 10 years. Browsers have evolved to adapt to new web technologies. From a user’s perspective, they are now faster, simple and easy to upgrade. On the other hand, from a developer’s view, it is now easy and faster to develop the look and feel of web applications.

For instance, let us look at one of CSS 3 new feature, box-shadow. The box-shadow, as the name implies, creates a shadow, for instance, on a rectangular div. Now in previous versions you would have to add an image to do that. This feature is supported in IE-9, Firefox 4+ and Chrome 3+ (and other browsers I did not mention).
Another example I can add is Html 5 which again has new elements and features that are supported in newer versions of browsers. Let us look at the input element as an example. You can now specify a text-input as an email. I am referring to it as a text-input because in older browser like IE-6, it will be rendered as a text-box. Now with this there is no need to add validation on the control to check if the value is a valid email. This is all taken care of for you.
These are just a few simple examples that I can point out, but there are a lot more benefits we can reap from using new browsers. Now as a developer you will be tempted to develop web applications or static sites that can only be rendered nicely in these new browsers. You would be impressed with what you would have accomplished in a short period of time and this will only last up to until you get a phone call from a client telling you that the design is not good or that validation is not working. Only to realise that you did not cater for old browsers.
Let us look at the box-shadow again as an example. Now as a fall-back plan you would put a background image that would show the shadow. With the email you would add a JavaScript validation to make sure that the value entered is a valid email. All this could be avoided. How? From the word go, develop bearing in mind there are people still using old browsers. Or simply ask your client to upgrade to new browsers which I would advocate for.
I think it is time we start to educate our clients the benefits of upgrading to new browsers. Not only does it cut development time, but it will also give them a good user experience. This is a win-win situation for all of us. I would also like to hear your thoughts on this.

Friday 28 October 2011

KnockoutJs

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically, KO can help you implement it more simply and maintainably.

Read here for more information on KnockoutJs.

Implementation:

Now in this post, assuming you have read about KO, I want to show you how you can populate a dropdown list from the server and change text when a value is selected.


Please take note, I did this using . Net MVC 3. Now, i have two ActionResult function that return a Json object. The "studentObj" is an anonymous object that has two properties, student and rankings. Student is the student object with a ranking of  "Average". The rankings, is a list of Ranking that can be awarded to a student.

This is how we are going to display the information on the client side:





These are the results, when page loads for the first time:

And when student is ranked:


I am sure you can agree that this is a cleaner way of changing text depending with the action or event. Try to do this the normal way you were used to doing it and compare, i am sure you will be amazed.

Friday 21 October 2011

Creational Design Pattern - The Singleton Pattern

A singleton is a class which only allows a single instance of itself to be created, and usually give simple access to that instance, hence the name single-ton. Singletons don’t allow any parameters to be specified when creating the instance because a second request for an instance but with a different parameter could cause problems. If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.

There are different ways of implementing the singleton pattern in any language, however for this post; I am going to show you how to implement it in JavaScript. With JavaScript, singletons serve as a namespace provider, which isolate implementation code from the global namespace so as to provide single point of access for functions.
The singleton doesn’t provide a way for code that doesn’t know about a previous reference to the singleton to easily retrieve it – it is not the object or class that is returned by a singleton, it is a structure. For instance, closured variables are not actually closures but the function scope that provides the closure is the closure.
In its simplest form, a singleton in JS can be an object literal grouped together with its related methods and properties as follows:
var mySingleton  = {

Name:”Tendai”,
Surname:”Bepete”,
getFullname:function(){
      return this.Name + “ “ + this.Surname;
}

};

You can extend this further by adding private members and methods to the singleton by encapsulating variable and function declarations inside a closure:
var mySingleton = function(){
          var privateAge = 18; //something private like your age or salary
          function showPrivateAge(){
               console.log(privateAge);
          }     
return{
         showAge:function(){ // you can now make it public knowledge
             showPrivateAge();
         },
         Name:”Tendai”, //this the public can see
         Surname:”Bepete”,
         getFullname:function(){
            return this.Name + “ “ + this.Surname;
        }
} ;

};

var single = mySingleton();
single.showAge(); // logs something private - age;
console.log(single.Name); // logs Name;
Now let us consider a situation where the singleton is instantiated when it is needed.


























Calling public methods is easy as follows: mySingleton.getInstance().getFullname();

How can the singleton pattern be useful? It is useful when exactly one object is needed to coordinate patterns across the system. Here is an example:

























var singletonTest = SingletonTester.getInstance({pointX:20});
console.log(singletonTest.PointX); // outputs 20

Hope this has been helpful. Welcome to comments and suggestion.

Monday 17 October 2011

Creational Design Pattern - Factory Pattern

To understand further about design patterns, let us look at what design is and what pattern is. Design is a blue print or sketch of something so it can be referred to as a creation of something in mind. Pattern, on the other hand, is a guideline or something that repeats. Now combining this, design patterns becomes creating something in mind that repeats or in other words capturing design ideas as a "pattern" to the problems.  


Now in this post I will look at one of the categories of design patterns and an example. Creational patterns define the best possible way in which an object can be instantiated. This describes the best way to create object instances. There are different types of Creational patterns and in this post we are going to look at the Factory pattern.

Factory Pattern

Factory of what? Of classes. In simple words, if we have a base class and a  number of sub-classes, and based on the data provided, we have to return the object of one of the sub-classes, we use a factory pattern. Here is an example:

In  this example, we use an abstract class as the base. The Ford, Toyota and BMW classes derive from the abstract class Vehicle.

abstract class Vehicle
{   
   abstract string Make {get;}
}

public class Ford : Vehicle 
{
      public override string Make
     {
        get
        {
           return "Ford";
        }
     }
}

public class Toyota: Vehicle 
{
      public override string Make
     {
        get
        {
           return "Toyota";
        }
     }
}

public class BMW: Vehicle 
{
      public override string Make
     {
        get
        {
           return "BMW";
        }
     }
}

static class Factory
{
    public static Make Get(int id)
    {
        switch(id)
        {
           case 0:
              return new Ford();
           case 1:
           case 2:
             return new Toyota();
           case 3:
           default:
             return new BMW();
       }
 }

static void Main()
{
    for(int i = 0; i <=3; i++)
    {
       var vehicle= Factory.Get(i);
       Console.WriteLine("Where id  = {0}, position = {1} ", i , vehicle.Make);
     }
}

Here is the Output 

Where id = 0, position = Ford
Where id = 1, position = Toyota
Where id = 2, position = Toyota
Where id = 3, position = BMW

The factory design pattern is found in the Factory class. The point of the Get method is to take a value and instantiate a class based on that value. It translate integers to objects with a switch statement. Because Ford, Toyota and BMW all derive from the same abstract class, the return type Make can be used. An implicit cast automatically casts the Ford, Toyota and BMW to Make references.

The Main method serves to demonstrate the Factory class in action. We use as part of the demonstration the integers 0, 1, 2 and 3. We user Get method with each of these values. Then, we show that the appropriate type of class was instantiated for each integer.

In short, the Factory patterns can be used in the following cases:

a) When a class does not know which class of objects it must create.
b) A class specifies its sub-class to specify which objects to create.
c) In programmer's language, you can use factory pattern where you have to create an object of any one sub-classes depending on the data provided.





Saturday 15 October 2011

Design Patterns

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Design patterns are represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. To illustrate a design pattern, consider the Adapter pattern. Adapter provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are incompatible. To implement an Adapter, you create a custom class that honours the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.

Why Design Patterns

Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns.

Often, people only understand how to apply certain software design techniques to certain problems. These techniques are difficult to apply to a broader range of problems. Design patterns provide general solutions, documented in a format that doesn’t require specifics tied to a particular problem.

In addition, patterns allow developers to communicate using well-known, well understood names for software interactions. Common design patterns can be improved over time, making them more robust than ad-hoc designs.

There are three basic classifications of patterns Creational, Structural and Behavioural patterns.

Creational Patterns
Creational design patterns are design patterns that deal with object creation mechanism, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Some examples of creational design patterns include:

Abstract factory pattern: centralize decision of what factory to instantiate

Factory method pattern: centralize creation of an object of a specific type choosing one of several implementations

Builder pattern: separate the construction of a complex object from its representation so that the same construction process can create different representations

Lazy initialization pattern: tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it in needed

Object pool pattern: avoid expensive acquisition and release of resources by recycling objects that are no longer in use

Prototype pattern: used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects

Singleton pattern: restrict instantiation of a class to one object

Structural pattern
Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationship between entities.
Examples of Structural Patterns include:
Adapter pattern: adapts one interface for a class into one that a client expects
Composite pattern: a tree structure of objects where every object has the same interface
Aggregate pattern: a version of the Composite pattern with the methods for aggregation of children
Decorator pattern: add additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes
Façade pattern: create a simplified interface of an existing interface to ease usage for common tasks.

Behavioural pattern
Behavioural design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
Examples of this type of design pattern include:
Command pattern: command objects encapsulate an action and its parameters
Interpreter pattern: implement a specialized computer language to rapidly solve a specific set of problems
Iterator pattern: iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation



Thursday 29 September 2011

Extension methods

What are Extension Methods?

Extension methods allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performace and compile-time validation of strongly-typed languages. This is a cool feature of C# 3.0

Extension Method Example:

Lets say you want to check if a variable string is a valid telephone number. In this example, our valid telephone number must start with a zero and followed by 9 more digits or start with a zero followed by two digits a space three digits a space and four digits (0787845122 or 078 784 5122). You would normally implement this by calling a separate class (most likely a static method) to check to see whether the string is valid, for instance:

string telephone = txtTelephone.Text;

if ( MyValidator.IsValidTelephone(telephone) ) {

}

Now using extension method, i can add a useful IsValidTelephone() method onto the string itself, which returns whether the string instance is a valid string or not. I can then re-write the above code to be cleaner and more informative like:






















Note that the static method above has a "this" keyword before the first parameter argument of type string. This tells the compiler that this particular Extension method should be added to objects of type "string". Within the IsValidTelephone() method implementation i can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid telephone or not.
Hope you enjoyed this post, will add some example in the next post.

Thursday 15 September 2011

Linq equivalent to SQL Select Count and Group by

In this post i want to show you how you can do a select count and group by using LINQ that is equivalent to SQL's.
















We have our object Student and we are going to create a list of Students. Now we want to return a list of Students who are in a certain Class and the number of Students in that Class. To do that we are going to use the GroupBy method and use a lambda expression to return the group of Students in a Class as a list. From the list we can then select the Class name and the Count. Take note that I used an anonymous type in the Select method.




Now if we want to group by more than one field, for instance, Subject in this case here is how we can do it:


Results:



Hope you found this post useful. Like to hear from you for suggestions or questions.

What are lambda expressions

In this post i want to talk about lambda expressions. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as "goes to". In other words, lambda expression can be broken down into parameters followed by execution code:

Parameter => executioncode.

The  left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block. The lambda expression x=> x * x  is read " x goes to x times x". In other words we want to square any given number and to do this we are going to assign to a delegate type as follows:



 







Result: The square of 5 is 25.

The => operator has the same precedence as assignment (=) and is right-associative.

Lambdas can be used in method-based LINQ queries as arguments to standard query operator methods such as Where. Let us look at the following pratical example:




























I have my object Person that i can model into a list of anything that represents a person, for instance, in this case i have modeled it to give me a list of Students. Now that we have our Students, we can go ahead and filter the Students by their Age, in this example i want to return teenagers or independents.

Both "getTeenagers()" and "getIndependents()" uses a lambda expression as a predicate to compare each Student's Age and return a  new collection of Students in their respective Age group.

For more on Lambda expressions you can read this article.

Thursday 1 September 2011

How to get a SharePoint list using SharePoint object model

In this post i want to discuss how you can get a SharePoint list using SharePoint object model. To do this make  sure you have SharePoint installed on your PC. Now create a new console project in Visual Studio 2010. Make sure that the platform target for your project is 64 bit and that you added the SharePoint dll as a reference.

Now, i have already added a custom list to my site and it is called My List. It has two columns, Name and Surname. So this is just a small list of random Names and Surnames.

 
 If you are done with your list, lets get the same list and display it from the Console application.

 If you run the code you will get the list you just created from SharePoint.


So this how you can simply get a SharePoint list using SharePoint object model. 










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







Monday 20 June 2011

Removing Special Characters

Lets say you have a database that have names of people and that some names have special characters, for instance, Zeélie,Wentzël,Oösthüizen or Oosthuÿsen. For some reason you have a third party application that you send through the names you have in your database, for example, a payroll system. But this system validates names and does't accept names with special characters. Therefore, you want to send through names without the special characters to this application, here is how you can do it in SQL:

We start by creating a table that will hold the special characters and the equivalent text character, for instance, é is equivalent to e.

CREATE TABLE dbo.tblSpecialCharacters (SeqId int identity(1,1),SpecialCharacter nvarchar(50),TextCharacter nvarchar(50))

INSERT INTO dbo.tblSpecialCharacters (SpecialCharacter,TextCharacter)
VALUES ('é','e')

INSERT INTO dbo.tblSpecialCharacters (SpecialCharacter,TextCharacter)
VALUES ('ë','e')

INSERT INTO dbo.tblSpecialCharacters (SpecialCharacter,TextCharacter)
VALUES ('ö','o')

INSERT INTO dbo.tblSpecialCharacters (SpecialCharacter,TextCharacter)
VALUES ('ü','u')

-- Create a Tally table that we are going to use to loop through the names with special characters. 
-- For this exmaple we are just going to end at 200, you can however, go as far as 20000 or more
-- depending on your needs.
SELECT TOP 100 IDENTITY(INT,1,1) AS N INTO dbo.tblTally FROM Master.dbo.SysColumns sc1,Master.dbo.SysColumns sc2

--- Add a Primary Key to maximize performance
  ALTER TABLE dbo.Tally
    ADD CONSTRAINT PK_Tally_N 
        PRIMARY KEY CLUSTERED (N) WITH FILLFACTOR = 100

Now create a function that will be removing the special characters:

CREATE FUNCTION [dbo].[RemoveCharacter]  
(  
@name nvarchar(200)  
)  
RETURNS nvarchar(200)
AS  
BEGIN  

declare @numCharacters int
-- Get the number of characters that the name has
set @numCharacters = (select count(s.SpecialCharacter)
FROM SpecialCharacters s,Tally t 
WHERE t.n <= len(@name) 
and s.SpecialCharacter=substring(@name,t.n,1))

declare @count int 
-- Set counter to 1
set @count = 1

-- Loop through the number of characters that needs to be 
-- replaced 
while @count<=@numCharacters
begin
-- Replace the character with the equivalent text.
-- Make sure you select only one character at a time. This way the subquery does't return more than
-- one record set.
set @name = replace(@name,(SELECT TOP 1(s.SpecialCharacter) FROM SpecialCharacters s,Tally t WHERE t.n <= len(@name) and s.SpecialCharacter=substring(@name,t.n,1)),
(SELECT TOP 1(s.TextCharacter) FROM SpecialCharacters s,Tally t WHERE t.n <= len(@name) and s.SpecialCharacter=substring(@name,t.n,1)))

set @count = @count + 1
end 
RETURN  
-- return the name without the characters.
@name
END  

Now lets say you have a table of people, in this example we will use a temporary table of employees who have special characters as follows:

CREATE TABLE #tblEmployees (SeqId int identity(1,1), Firstname nvarchar(200), Surname nvarchar(200))

INSERT INTO #tblEmployees (Firstname,Surname)
VALUES ('Tinashe','Zeélie')

INSERT INTO #tblEmployees (Firstname,Surname)
VALUES ('Takura','Wentzël')

INSERT INTO #tblEmployees (Firstname,Surname)
VALUES ('Tafadzwa','Oösthüizen')

INSERT INTO #tblEmployees (Firstname,Surname)
VALUES ('Peter','Oosthuÿsen')

SELECT FIRSTNAME,
dbo.RemoveCharacter(SURNAME) AS SURNAME
FROM #tblEmployees

DROP TABLE #tblEmployees

Results:

FirstnameSurname
TinasheZeelie
TakuraWentzel
TafadzwaOosthuizen
PeterOosthuysen
From the results, the characters are removed. This is just a small record set. You can test to see how the function fares, when lets say you have to pass through more than 10000 records of employees. Or that you have to do an inner join with another table, for instance the salary table.

This is just one of the ways you can remove special characters in SQL, I am sure there are other ways this can be achieved. If you have any additions, subtractions or suggestions please do let me know. Hope this helps someone.