Sunday, January 29, 2012

Remote System Monitoring and Controlling via Web based Mobile or Desktop Application


The idea of remote system monitoring and controlling application is to do some of the actions like ex: Shutdown, Reboot, Hibernate of the users systems remotely. The user can also make use of this application to query additional details of the systems.
Consider a scenario where you have a set of systems (Computers) and you want to control them from your mobile or any other desktop anywhere from the world. So this started as initial requirement of how we can implement the same to control numerous systems remotely.
Consider another scenario of how you can retrieve the information of a particular system remotely from your handheld devices or through desktops. By retrieving information, one may be interested in knowing the following

1.       Machine Name
2.       CPU information
3.       Username
4.       Domain Name
5.       OS Version

Software Requirements Specification

1.       Aim: The aim of this project is to provide a facility for the end user to remotely control their systems through desktop or mobile based web application.
2.       Purpose: The purpose of this project is to implement a proof or concept of the same. And to show how easily it can be done with .NET technology
3.       Scope: The scope of this project is very limited to controlling the system with few actions like Shutdown, Reboot, Hibernate, Logoff, Force close all applications etc. The user registration is done only at the client application and the it should be always running in-order to control the system remotely.

4.       User Characteristics:  The Following things are taken into consideration with this software development
a.       Users can have multiple systems for controlling. There is absolutely no limit in the number of systems being controlled by the users.
b.      The user can either control her/his systems through mobile or desktop based web application.
c.       Each user can control his/her system only and don’t have access to control others systems.
d.      Right now there is only one type of user of this system i.e. the System Administrators who will be using this system to control or fetch additional information of the system on their own interest.

Software and Hardware Requirement

Software Requirements:
·       Operating system: Microsoft Windows XP / Win 7 / Vista
·       .NET framework 4.0
·       SQL Server 2008

Hardware Requirements:
·       Processor Pentium 4
·       RAM- 256Mb
·       HDD-10GB

Technologies Used
·       Visual Studio.NET
    • The Client Application is developed with .NET C# Winform technology
    • The Server side web application is developed with ASP.NET MVC3 technology.

·       Internet based / Cloud based Microsoft SQL Server 2008
    • This software is designed with Software as a Service model with a common single cloud database which stores all the users and their system information.

How does the software functions?
Client Application:

When you run the client application for the first time, you will have to register yourself with the username and password. The same has to be provided as log on information which will authenticate the user in client and server applications.

Once authenticated, the user has to click on the Start button for continuous monitoring of the system behind the scene. The system registers by itself by putting an entry in database (this happens only for the first usage of the client app) so that the user can control that particular machine.  When the user closes the client application, the entry in the database for that system will be deactivated.  For subsequent usable of the client application, the system will be activated for monitoring and controlling.

Server Application:

It is a web based application, on requesting the user will be authenticated. The use has to provide the same username and password he/she has provided at the time of user registration in client app.
On successful authentication, the list of active systems will be displayed in a screen. The user can select one and perform the actions like Shutdown, Reboot etc.

Database Entity Relationship Design Diagram

Snapshots of Client App

Snapshots of Server Application

Thursday, January 19, 2012

Dependency Injection

Dependency injection basically allows us to create loosely coupled, reusable, and testable objects in your software designs by removing dependencies.

We will take a look into the Object dependencies before digging in more.
Consider a scenario of fetching an employee details and show display in UI. Let us say create a Business logic layer class named EmployeeBAL and a data access layer class named EmployeeDAO

public class EmployeeDao
     //Some code

public class EmployeeBAL
      var employeeDAO = new EmployeeDao();
      //Some code

From the above code you will notice one thing that we are creating EmployeeDAO instance inside the Business logic layer class. So here comes the dependency

What is wrong if we have a dependency?

Think about whether your code is unit testable. We cannot fully unit test the EmployeeBAL as it has a dependency on Employee DAO. So we can say as long as the composition of the DAO exists within the BAL we cannot unit test the EmployeeBAL.

You will also notice one more thing here; with this type of implementation you will see a high coupling of BAL and DAL.

How to make it loose coupling?

The basic idea behind Dependency Injection is that you should isolate the implementation of an object from the construction of objects on which it depends

Coming to the example, we should be isolating the implementation of EmployeeBAL object and the construction of the dependent EmployeeDAO object.

We will see how we can make loosely coupled objects in detail
           Constructor based dependency injection
      We will have to modify the EmployeeBAL to accept an EmployeeDAO instance within its constructor.

public class EmployeeDao
     //Some code

public class EmployeeBAL
     EmployeeDao employeeDAO;

     public EmployeeBAL(EmployeeDAO employeeDao){
             this.employeeDAO  = employeeDao;
     //Some code

     Property based dependency injection

      With property based injection we will have a public getter and setter Property of type EmployeeDao so that the dependency can be externally set.

public class EmployeeBAL
             Public EmployeeDao EmployeeDataAccess{ get; set; }
var employeeBAL = new EmployeeBAL();
EmployeeBAL.EmployeeDataAccess = new EmployeeDao();


The above ones are just some techniques of injecting the dependency. We are still yet to discuss one more interesting thing Unit Testing.

Are you agreeing that we have removed the DAO creation from the Business Logic EmployeeBAL? Yes it is good but it still depends on the actual instance of EmployeeDao.  

Consider the below mentioned implementation of the same sample senarios

interface IDataAccess
     //Some code
class EmployeeDao : IDataAccess
     //Some code
public class EmployeeBAL
    private IDataAccess dataAccess;
    public BusinessFacade(IDataAccess dao)
        dataAccess = dao;
You can notice we are doing a constructor dependency injection but most important thing here 
is we are using Interface type than creating a strongly typed object. 

The advantage that we are getting here is we can have an In-memory data access object of
IDataAccess interface type and we can  easily inject the dependency to the EmployeeBAL. 
By this way we need not inject the concrete instance of the data access object.

Are you happy that we can unit test the BAL without the data access dependency? 

Advantages of Dependency Injection
The primary advantages of dependency injection are:
  • Loose coupling
  • Centralized configuration
  • Easily testable

Monday, January 16, 2012

3 Tier Architecture in .NET C#

3-Tier architecture generally contains User Interface (UI) or Presentation Layer, Business Access/Logic Layer (BAL) and Data Access Layer (DAL). 

Presentation Layer (UI) 

Presentation layer is responsible for displaying the views. Contains windows forms or ASP.NET pages, where data is presented to the user or input is taken from the user. We will consider a sample Windows form application which will show the Authors information and details in the UI.

Business Access Layer (BAL) or Business Logic Layer 

BAL contains business logic, validations or calculations related with the data

Business Entities

Business entities are reusable entities developed as per the application. We are making use of these entities in BAL and DAL. The data access layer fetches the data and converts the data say to a List of business entity. Ex: When we are retrieving a list of Authors details, the DAL will fetch all the authors and returns List<AuthorsBE> list of author’s business entities.

Data Access Layer (DAL) 

DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc). For this demo pubs sample application, the BAL makes a call to data access to get all the list of authors i.e GetAllAuthors(), to get all the list of author titles GetAuthorTitleDetails(string authorID)

Advantages of N-Tier Application

1.    Decoupling the logic: By loose coupling the logics of Presentation, Business and Data access suppose if there is a change in the UI layer, you will only have to worry about the modifications in the Presentation layer. Right now it is using SQL Server database , if in future you are changing your mind in is using other databases , we will only have to modify the logic within the Data access layer and nothing else is required.
2.    With layered architecture you can do the software development in Parallel. That means you can code each layers independently
3.    Easy to Test: The testability of the software increases by decoupling the logics into multiple layers. You can independently Unit Test the logics of different layers
4.    Re usability of components

How to run the sample
1)   Download pubs database sample from link
2)   Open SQL Management studio and execute the stored procedures with in the DataAccessLayer - > Scripts folder in Pubs database.
3)   Open PubsSamplePresentation.sln Solution from VS 2010 or VS2011
4)   Go to PubsSamplePresentation and open App.config
5)   Change the connection string (PubsConnectionString) value appropriately
6)   Run the Windows Form application (PubsSamplePresentation)

Class Diagram of Logger Library


A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
The signature of a single cast delegate is shown below:
delegate result-type identifier ([parameters]);
  • result-type: The result type, which matches the return type of the function.
  • identifier: The delegate name.
  • parameters: The Parameters that the function takes.
Delegates allow a clearer separation of specification and implementation. A delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification.

Multicast Delegate

With multicast delegate, it is just like a normal delegate but it can point to multiple functions so on invocation of such delegate it will invoke all the methods and functions associated with the same one after another sequentially.


Events are wrapper around the delegate. It sits on top of the delegate and provides only the necessary encapsulation so that the destination objects can subscribe to the Event and not have full control on the delegate object.
Events are declared using delegates. The delegate object encapsulates a method so that it can be called anonymously. An event is a way for a class to allow clients to give it delegates to methods that should be called when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked.
We will consider an example implementation of Logger application, which can be used to log messages in Console, File or Database etc.
We will declare a delegate named LogWriteDelegate which accepts one parameter named message.

public delegate void LogWriteDelegate(string message);

Next we will declare an Event of type LogWriteDelegate

public event LogWriteDelegate LogWriteEvent;

In our sample Logger the FileLogger and ConsoleLogger will subscribe or register to the above mentioned event so that when the Write method of logger is called the respective logic within the Write method of FileLogger and ConsolLogger will also gets invoked.

using (var logger = new Logger("testing", EntryType.Debug))
      logger.LogWriteEvent += new Logger.LogWriteDelegate(consoleLogger.Write);
      logger.LogWriteEvent += new Logger.LogWriteDelegate(fileLogger.Write);

You can notice here a multicast delegate; the LogWriteEvent is being registered with Console and File log write methods.
While firing an Event within the Logger object, it is always a good practice to check whether the event is registered or not.

public void Write()
       if (LogWriteEvent != null)

Here the LogWriteEvent holds the address of the methods console.Write and fileLogger.Write. When firing an event it will sequentially call the respective methods which are pre-registered to this Event.
Note: The Logger application is designed in the way that in future you can have multiple implementations of Loggers. Right now we have Console and File Logger; if you are interested in implementing a Database logger we can create a new Class named DatabaseLogger which will implement ILogger interface. Provide necessary Write method logic so that it will log messages to database.

Ones you have done with the DatabaseLogger implementation, you just have to create an instance and register the event as we have done for Console and File Loggers.

Aggregation, Composition and Association


“Association represents the static relationship shared among the objects of two classes. “So any relationship between object of two classes is called association.
An association says there is some kind of dependency between the objects. It can either be a weak or Strong dependency.
Consider an example of Teacher and Student classes. Multiple students can associate with single teacher and single student can associate with multiple teachers. This is a kind of a weak relationship because there is no ownership between the student and teacher and the life cycle are maintained by themselves.


Composition is specialized form of aggregation and we can call this as a “life and death” relationship. It is a strong type of aggregation. Child object does not have their life-cycle and if parent object deletes all child objects will also be deleted.
Consider an example of a set of classes Engine and Car. The object Engine is said to be composed with in the Car object as the Engine cannot leave without the Car object and the relationship is said to be whole because the Engine is a part of the Car object. Here the life cycle of Engine is managed by the Car object. If the Car gets destructed the associated composite object like Engine will also get destroyed.
Thus a composition relationship specifies that the lifetime of the part classifier is dependent on the lifetime of the whole classifier.

public class Engine
 . . .

public class Car
    Engine e = new Engine();

Yet another example for Composite relationship is, consider a set of classed Person, Leg and Hand. The objects Leg and Hand are composed within the Person object. The life cycle of Leg and Hand objects are maintained by Person object. Also you can see the Leg and Hand object cannot leave independently without the Person object. And note there is a strong relationship of Leg and Hand object with the Person.


The difference between aggregation and composition is the object which can exists independently uses aggregation and an object that has no meaning outside of the relationship uses composition
Let’s take an example of Department and teacher. A single teacher cannot belong to multiple departments, but if we delete the department, the teacher object will not destroy. We can think about “has-a” relationship.
Let us take another example of Company and Employee classes. The employee is said to be aggregated with the Company. The Employee is working for a company and has a relationship with the company.  The employee object can still survive even if say the Company object does not exists.


I will conclude here by taking a real world example which has aggregation and compositions.

Consider a scenario of a University which owns various departments (e.g., physics, chemistry) and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.