Sunday, August 31, 2014

Providers that make your life easy (Part I)

Chapter – VI
Providers that make your life easy (Part I)

In the previous post I've shown you how you can implement business logics in your controllers and use them in different parts of your application just by calling them. But as we all know too much code in one place is never a good idea. And it is considered to be a good habit not to write a whole amount of business logics in a controller cause you may have to use those same logics again in another controller. So doing the same thing over and over again is an overkill and also error prone.

So in this chapter I’m going to show you how Angular.js providers can make your coding life cycle easier by separating these business logics from your controllers and prevent from injecting bugs in your application.

Ok sounds fine, but there is a catch! Before I make your head spin with those topics of Angular, let’s take a step back to some object oriented JavaScript. You may ask yourself why? The answer is be patient my friend!

So let’s start by creating a simple object in JavaScript. There are many ways of creating an object in JavaScript but I’m going to show you the easiest and most granted way. And that is known as creating an object by object literals. First of all I want to create an arnoldSchwarzenegger (A Hollywood Actor) object. The object will have a property for holding the first name of the actor, a property for the last name, a property for the catch phrase and last of all a property which will make a string with all of those previous properties and show it to the application users.

Creating an object literal is as easy as pie. It is just some key value pair. All you have to do is to define a key [a string representing the property name] and a value associated with it. So from that concept our Arnold Schwarzenegger object literal will look like this,

var arnoldSchwarzenegger = {
            firstName: "Arnold",
            lastName: "Schwarzenegger",
            catchPhrase: "Hasta la vista, baby",
            sayCatchPhrase: function () {
                return this.firstName + " " + this.lastName + " says " + this.catchPhrase;
            }
};

Now if you call the sayCatchPhrase property like this

arnoldSchwarzenegger.sayCatchPhrase();

You will get the string given below

"Arnold Schwarzenegger says Hasta la vista, baby"

Remember to add those first brackets when you call sayCatchPhrase. Since JavaScript don’t have methods for an object, you can bypass this rule by encapsulating a function within a property.

Now it’s time to create the clintEastwood object. All is same as before.

var clintEastwood = {
            firstName: "Clint",
            lastName: "Eastwood",
            catchPhrase: "Go ahead. Make my day",
            sayCatchPhrase: function () {
                return this.firstName + " " + this.lastName + " says " + this.catchPhrase;
            }
};

clintEastwood.sayCatchPhrase();

"Clint Eastwood says Go ahead. Make my day”

Now let’s create another one. Wait a sec!!! You may ask yourself why am I doing the same thing over and over again. Why don’t I just define a class and declare those properties in that class. Then when the time comes I just instantiate an object of that class and use those properties. Well you are right about the fact that we are doing the same thing over and over again but to our utter luck we don’t have the concept of class in JavaScript.

But don’t worry because where there is a will there is a way. Functions are like the first class citizen in JavaScript language. We can do almost anything with functions. And we can also create an object within a function and return that object. Functions like these are called factory functions.
So creating and returning an actor object with a factory function looks like this,

var actor = function (firstName, lastName, catchPhrase) {
            return {
                firstName: firstName,
                lastName: lastName,
                catchPhrase: catchPhrase,
                sayCatchPhrase: function () {
                    return this.firstName + " " + this.lastName + " says " + this.catchPhrase;
                }
            };
};

var clint = actor("Client", "Eastwood", "Go ahead. Make my day");

clint.sayCatchPhrase();

"Clint Eastwood says Go ahead. Make my day”

As you can see I've declared a function with some parameters. In that function we set the passed in parameters in an object literal and then return that to hold the reference into actor variable. Then all we did is called the actor function with some parameters.

I hope you likethe way I create an object with factory function to restrict myself from doing the same thing again and again. There is another way by which we can create an object. But that will be discussed in the next part. 

Thursday, August 28, 2014

Alarming Delegates (Advanced)

Alarming Delegates (Advanced)

Creating an alarm system using delegates


So here goes a post about c# delegates, which is considered to be one of the hardest concept in c#. So I decided to show you a simple example which I guess will clear the concept of delegates for you.

Delegates are like function pointers in C++ and callback functions in JavaScript. Functions can be encapsulated using delegates. As you already know that c# is an event based programming language, you will be happy to know that behind the scene all events are basically delegates. So sooner or later you will find yourself learning delegates.

‘Nuff said! Let’s talk about the example which we are going to build. Our example is very simple one. All we are going to build is a simple console app, which will work like a clock. It will only count the seconds, so you can call it a second’s clock. In this simple app you will have to set an alarm for an upcoming second. The app will continuously check the current second against the second set at compile time and will show an alarming message if the condition is matched.

Now let’s talk about how we are going to build it using delegates. For simplicity let’s create a Clock class first. For now the class only contains a single DateTime property named Alarm.

public class Clock
{
public DateTime Alarm { get; set; }
}

We will use this auto property to set an alarm time in seconds in near future.


We all know that Class and Struct are some ways of creating user defined types. Likewise delegates can be used to define a type which can only encapsulate functions. Signature of a delegate type is more like a function declaration. To declare a delegate, you simply have to follow the signature given below,

access_modifier delegate_keyword reurn_type delegate_name(type parameter1,……);

So, let’s go and create our own delegate as

public delegate void ClockAlarm(Clock clock, string name);

As you can see our newly created delegate, ClockAlarm can take a Clock object and a string as parameters and can return a void type. Everything is set.

So I successfully declared a delegate but there is no use of it. Let’s go to our Main method in  Program class and write some magical code. Let’s start by creating an instance of our Clock class and assign a seconds value of a near future for the Alarm property.

var clock = new Clock();
clock.Alarm =  DateTime.Now.AddSeconds(5);

Now it’s time to encapsulate a function with our ClockAlarm delegate. You may be thinking now that ok so I have a delegate to which I can attach a function. But what will be the signature and definition of the attaching function? I know you are geek enough and figured out the attaching functions’ signature. Yes you are right!!! its signature is same as our  ClockAlarm delegate. If we try to attach a function whose signature mismatches with our  ClockAlarm delegate signature, it will give you a compile time error.

Next let’s create our attaching or subscribing function with definition as below

private static void Wakeup(Clock clock)
{
while (true)
       {
       Thread.Sleep(1000);
              DateTime currentTime = DateTime.Now;
             
if (currentTime.Second == clock.Alarm.Second)
              {
                     Console.WriteLine("Please wake up!!!!");
                     break;
              }
             
Console.WriteLine("Clock is ticking!!!");
}
}

The code is very simple all we did is created a while loop which will first send the system to sleep for one second and wake it up. After that it will assign the current DateTime value to the currentTime variable. After that the if clause checks if the current second matches the Alarm property value which was passed in the function object. If the clause is true then it prints the message "Please wake up!!!!" and breaks out of the loop otherwise it will continuously prints "Clock is ticking!!!" message. 

Now its time to create an instance of our delegate and then attach the subscribing function to it.

ClockAlarm clockAlarm;
clockAlarm = Wakeup;
  
Last of all we will have to invoke the delegate with the required parameters. To do that we will simply have to write

clockAlarm(clock,"Fiyaz");

So I guess you got the point. With the help of a delegate we are making a function subscribing to an event which is basically for now is simply an alarm notification. Now if you run the program you’ll something like this,



We can attach more than one subscribing functions to our delegate which is a process of multicasting delegates. More about delegate multicasting in the next post.


Tuesday, August 19, 2014

Make Your Code Modular Buddy! (Modules)

Chapter – V
Make Your Code Modular Buddy! (Modules)

Unlike the Hello World Program, in real life an enterprise level application gets bigger and bigger day by day as the client’s requirements flown in from here and there. Managing these kind of applications are easy when some heavyweight enterprise languages like C#, Java etc. are there for you. These heavyweight languages provides some features, where a client side language like JavaScript often lakes these features. Features like Class and Namespace are absent in JavaScript. But since every problem has a solution, with the help of JavaScript functions we can have both of those features. The simplest way to create a namespace in JavaScript is to use a self-invocating anonymous function. Likewise we can use a factory function which works as a constructor function that returns a singleton object. But enough of these advance features. Let’s see what Angular provides us to implement the concept of Namespaces and Class. Angular has a feature called module by which we can introduce Namespaces in our code. By using modules we can keep the global namespace [Global Scope] clean. This makes testing our code easier and also sharing of code between applications easier [You can make your own modules and use it in different applications]. For an example let’s create a simple module and encapsulate some basic functionalities into the module.
Since separating the scripts from the HTML files is a good practice. A simple Anguler module can be written as follows in the app.js file:

var app = angular.module('app', []);

app.controller('messageController', function($scope) {
    $scope.data = {
        message: "Fiyaz Hasan"
    };
});


app.controller('mathController',function($scope) {
    $scope.data = {
        number: 9,
        squareRoot: function () {
            return Math.sqrt(this.number);
        }
    };
});

The important part here is that we declared an app Namespace with the help of angular.module('app', []); Here the first parameter represents the Namespace identifier and the empty [] third braces means that we can inject dependencies into the module.[More about dependencies will be discussed later]. Except that nothing is so special here. All I did is I created two app specific controllers that can only be accessed when a DOM references the module.

The controllers serve the same functionality as the previous post’s controllers serve. Now goes the HTML layout,

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <title>Angular Module</title>
</head>
<body>
    <div ng-controller="messageController">
        <input type="text" ng-model="data.message" />
        <h1>{{data.message}}</h1>
    </div>

    <div ng-controller="mathController">
        <input type="text" ng-model="data.number" />
        <h1>{{data.squareRoot()}}</h1>
    </div>

    <script src="scripts/angular.js"></script>
    <script src="scripts/App/app.js"></script>
</body>
</html>
  
As you can see all are as before except at the top I have referenced the app module into the ng-app directive. And we are done. Now our HTML document will only responds to the different functionality described in the app module.

Now let’s talk about how we have kept our global namespace clean by using module. To show an example I've created another Angular module called app2 and the script is as follows,

var app2 = angular.module('app2', []);

app2.controller('messageController', function ($scope) {
    $scope.data = {
        message: "Circle circumference"
    };
});


app2.controller('mathController', function ($scope) {
    $scope.data = {
        radius: 3,
        circumference: function () {
            return 2 * Math.PI * this.radius;
        }
    };
});

Up in the script again I've two controllers whose names are as same as app modules controller but in app2 module they serve different purposes. As you can see the first one [messageController] is identical to the previous [messageController] one in the app module where the second controller [mathController] returns the circumference of a circle with a given radius.

Again I've created another HTML file called index2.html and the layout is like this,

<!DOCTYPE html>
<html lang="en" ng-app="app2">
<head>
    <title>Angular Module</title>
</head>
<body>
    <div ng-controller="messageController">
        <input type="text" ng-model="data.message" />
        <h1>{{data.message}}</h1>
    </div>

    <div ng-controller="mathController">
        <input type="text" ng-model="data.radius" />
        <h1>{{data.circumference()}}</h1>
    </div>

    <script src="scripts/angular.js"></script>
    <script src="scripts/App/app.js"></script>
</body>
</html>

From the script shown above I guess you've already figured out the rest. In app2 module we have those two controllers with the same name again as we have in the app module but I kept the controller name same. As we can see that identical controllers didn't come in each other’s way because they are attached to different modules. Since two HTML documents reference two different modules the behavior that the app gets depend on the different module functionalities. The outputs are shown below.

OUTPUT: