Thursday, September 16, 2010

Yet another reason to live...


DARE TO SHARE?
Yet another gift from heaven, yet another reason to live, yet another spirit to fight with all odds in the universe.

He came to my world on 15th September 2010 at 4.45 pm BDT. I just wish I can leave a better world for him. A world without war, hunger and global worming, and a world with piece and comfort for every living being.

May God bless us all.

Conditional use of ScriptManager in Aspx pages


DARE TO SHARE?
The <Asp:ScriptManager> is a "Must include" element for using Asp.net Ajax. Now, guess what heppens with the following piece of code:

<div>
<%
bool includeScript = false;
if (includeScript)
{
%>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<% 
}
%>
</div> 

Easy. The ScriptManager is not going to be included here, right?

Well, no. Despite the fact that, includeScript is set to "false", the ScriptManager actually gets included and the built-in scripts are emitted in the HTML page output. If you run the page and see page source, you will see the followoing scripts references are added:

<script src="/WebSite2/WebResource.axd?d=Q6DK_w2gdQLulMt..."></script>
<script src="/WebSite2/ScriptResource.axd?d=cPZd..."></script>
<script src="/WebSite2/ScriptResource.axd?d=cPZdb-Sve..."></script>

Well, this is surprising. There is no way the ScriptManager should be included (And executed) by the Asp.net run time according to the code as the conditional block executes to false. To verify that, add a Label control with the ScriptManager control as follows:

<div>
<%
bool includeScript = false;
if (includeScript)
{
%>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<% 
}
%>
</div>

If you view the page output in the browser, the Label control's output will not be shown in the browser. But, if you set bool includeScript = true, the Label control's output will be shown in the browser.

So, how to include the ScriptManager conditionally? How to ensure that you are including the ScriptManager only when certain condition is met.

The solution is, you have to do this in CodeBehind. Here goes the solution:

1. Include a PlaceHolder control in the aspx:

<asp:placeholder id="ViewPlaceholder" runat="server"></asp:placeholder>

2. Put the conditional code in the CodeBehind (In the Page_Init) so that, the ScriptManager is added to the PlaceHolder control only if the condition is met:
protected void Page_Init(object sender, EventArgs e)
{
        bool includeScript = false;
        if (includeScript)
        {
            ScriptManager script = new ScriptManager();
            script.ID = "ScriptManager1";
            ViewPlaceholder.Controls.Add(script);
        }
}

Wednesday, September 8, 2010

Interface vs Abstract class. The classic confusion


DARE TO SHARE?

One of the mostly asked question in OOP is about choosing between an Interface and an Abstract class.  These two look pretty similar and it appears as if one could be used instead of another. So, which one should be most appropriate to use to lay out class designs?

These two things are similar, and both talk about abstraction, rather than concrete implementation. Both concepts are interpreted and inherited from the real world. But, there is a small difference in their purpose.

Interface talks about "What" functionality a particular kind of object should have, and, it doesn't care about exactly "How" these functionality should be implemented by the actual objects of those kind.

For example, let us consider a Vehicle object. A vehicle could be of any brand in the world. But, what are the core functionality of a vehicle? What would you expect from a vehicle while you try to purchase one? The very basic things you would expect would be:

It must start
It must run
It must break
It must accelerate
It must stop

So, how would you identify these "very basic" features for any vehicle in the OOP?

You already know it. You create an interface and put these functionality as some method signatures without definition. That is:

interface IVehicle
{
     void Start();
     void Run();
     void Accelerate();
     void Break();
     void Stop();
}

So, this basically describes what are the basic functionality that a vehicle (Any vehicle made by any manufacturer) should have. Now, how these functionality are going to be implemented? Well, It completely depends on the manufacturers. One particular kind of vehicle might start using a Remote control, and another might start with a Key. One might accelerate via an auto gear and another might accelerate via a manual gear. In OOP, these particular implementations are defined by the classes which implements the interface. The interface knows nothing about these concrete implementation and it is quite happy about that.

On the other hand, an "Abstract class" also talks about "What" functionality a particular kind of object should have, but, it may also talk about "How" a particular functionality is implemented.

Need an example? Here you go

Toyota makes cars and of course all of its cars have the very basic functionality that a vehicle should have. So, each car obviously implements the IVehicle interface. For now, let us assume Toyota makes cars based upon only two models, the Camry and the XCorolla. So, while laying out the Camry and XCorolla classes, they implement the IVehicle classes as follows:

class Camry : IVehicle
{
    public void Start()
    {
         //Starts with a Remote control
    }

    public void Run()
    {
         //Runs via a 2000CC Toyota engine
    }

    public void Accelerate()
    {
         //Accelerates via an Auto gear
    }

    public void Break()
    {
         //Breaks via an hydrolic break
    }

    public void Stop()
    {
         //Stops with a key, or a remote control
    }
}

class XCorolla: IVehicle
{
    public void Start()
    {
         //Starts with a Key

    }

    public void Run()
    {
         //Runs via a 1500CC Toyota engine

    }

    public void Accelerate()
    {
         //Accelerates via an Auto gear

    }

    public void Break()
    {
         //Breaks via an hydrolic break

    }

    public void Stop()
    {
         //Stops with a key

    }

}


Looks pretty good, but, wait a minute. The Camry and the XCorolla class both seem to be having a same implementation for Accelerate() and Break(), though, these two classes implement the other three functionality Start(), Run() and Stop() in different ways. So, as these two classes have a same implementation for the Accelerate() and Break() functionality, why shouldn't these be re-used?


The IVehicle interface could of-course be used in this case, but, it is not allowing to re-use the same functionality Accelerate() and Break(). So, how about using an Abstract class?

Let us help Toyota to improve their programs a bit, by creating an abstract class Car, that contains the common functional implementation for Accelerate and Break.

abstract class Car : IVehicle
{
    public abstract void Start();
    public abstract void Run();
    public abstract void Stop();
    
    public void Accelerate()
    {
         //Accelerates via an Auto gear
    }
    public void Break()
    {
         //Breaks via an hydrolic break
    }
}

As you see, the abstract class Car contains concrete implementations of Accelerate() and Break() function (They have method definition), but, abstract implementation of Start(), Run() and Stop() (They don't have method definition). Why two concrete implementations? Because, these two functions are the same for both Camry and the XCorolla classes. Why two abstract implementations? Because, these two function's concrete implementation are not same for Camry and XCorolla classes.

So now, the Camry and the XCorolla classes would be re-defined as follows:

class Camry : Car
{
     public void Start()
    {
         //Starts with a Remote control
    }
     public void Run()
    {
         //Runs via a 2000CC Toyota engine
    }
    public void Stop()
    {
         //Stops with a key, or a remote control
    }
}

class XCorolla: Car
{
     public void Start()
    {
         //Starts with a Key

    }
     public void Run()
    {
         //Runs via a 1500CC Toyota engine

    }
    public void Stop()
    {
         //Stops with a key

    }
}

This time, the Camry and the XCorolla classes don't include the definition of  Break() and Accelerate(), because, they inherit those from the abstract Car class.

To summarize, the purpose of abstract classes is not only to define abstraction between classes, but also to define concrete definition of functions which are common across the concrete implementation classes. Interfaces allow us to identify (Not implement) the functionality a particular kind of object where Abstract classes allows to both identify and implement the functionality across the objects, that increases re-usability and code manageability and allows to build better systems.

However, it doesn't mean that, all interfaces should be replaced with Abstract classes. Try to use Abstract classes wherever possible and wherever applicable, where use of Abstract classes allows you to increase code manageability and reuse.


Enjoy abstraction.

Monday, September 6, 2010

How to automatically log onto a web application from a windows application in a secured way?


DARE TO SHARE?
This is an interesting requirement. Sometimes, there could be a single database which is accessed by a web application and a windows/desktop application. If a user is logged onto the windows application, he/she might want to navigate to the web application by clicking some link on the windows forms and want to be able to access to authenticated pages in the browser(Pages which are accessible onto to the logged in use) without having to re-login at the web application.

One obvious option is to open the web application's URL with the username and password of the user who is currently logged onto the windows application. But, this is insecure. If someone intercepts the requests he will easily get the user credentials and can gain un-authorized access to the system. Another option could be to encrypt the credentials using an encryption algorithm and using the same algorithm at the web application to decrypt the credentials. But, this requires managing an extra encryption-decryption hassle along with running the risk of making the URL request a long one.

Here is a proposed cleaner approach to solve this issue:

When you log onto your system from the windows application, you can generate a token (Say, A GUID), store it into the database along with the user ID, and keep it in a variable inside the windows application. You need to remove the token from the database user logs out. So, the token is valid as long as user is logged onto the system from the windows application.

Now, when you click the Web application's URL from the windows application, you send the Token with the QueryString. Within the web application, you get the token from the QueryString and query the database to retrieve the associated user. Also, you invoke the necessary method with the retrieved user's username and password that logs in a user into the web application.

Please note, there is a security issue with this approach. As long as the token is available in the database, if any one intercepts the Request and gets the Token and hits the web application's URL with that particular token, he or she will be able to access the web application.

To prevent that, you just need to make sure that you are deleting the token from the database as soon as you get the Token in the Request URL, match with the existing Token in the database and log onto the web application. In that case, hacker won't be able to access the system with the Token that he/she just intercepted.