Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, April 17, 2012

Unit testing using LINQ in Visual Studio Team System

Definition for Unit Testing


In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual function or procedure. (Source: en.wikipedia.org/wiki/Unit_testing).

How to use LINQ in unit testing


OK, For a unit testing we require test data. In VSTS (Visual Studio Team System), test data can be acquired using following methods.

  1. Using a Database
  2. Using XML and LINQ

I am going to do a walk through on second part i.e. Using XML and LINQ. XML files are quite handy and always liked by developers due to its readability, flexibility etc. But mean time it comes with an additional over head of traversing XML file and use the data. Normally we need to use XML parser to read XML files, then traverse thorough elements, find it and then use it. Lot of additional coding, ha...

But LINQ made this step very easy. Let's see how it works. I will explain through some sample coding.

Before talking about that, if  you need to know how to create unit test class in your application, please refer MSDN http://msdn.microsoft.com/en-us/library/ms182532.aspx.

OK, Let back to our topic. I will explain in three steps.

Step 1: First use following namespace in your unit test class file.
using System.Linq;
using System.Xml;
using System.Xml.Linq;

Step 2:
Now we need to load the element from file. We can use XElement.Load(path) to load the XML data from file.Code sample which will fetch the complete XML data to this variable
          XElement testDataFromFile = XElement.Load(Path);

Step 3:
Below line of code will extract contents of specific elements to the varible. Here LINQ is so flexible and easy that you can query based on element name and you will get the data. So easy, is it? I love this.

     var RSAContracts = from r in testDataFromFile.Elements("RSAContract")
                              select r;
     foreach (var contract in RSAContracts)
     {
         if (contract.Element("TestType").Value == "SuccessPath")
          {
           //Extract the data and fill it to object for testing. ………..
           }
     }

Advantage of using XML files will be

  1. You can extend the test cases any point of time.
  2. Maintainability will be easy. If you are using Database, then you need to create tables, accessing them etc.


Happy programming!!!!


Wednesday, June 28, 2006

Creating windows Services using C#

After the introduction of .NET and C#, writing Windows services becomes an easy job. We have to keep something in mind before starting to write windows service.

Step 1
Create a new project in .NET by selecting windows service. Give relevant name to the service.


Microsoft .NET will generate required code for with these methods and the class will be inherited from “
System.ServiceProcess.ServiceBase” class. ServiceProcess is the base class for windows services. The windows services consist of the following method.

  1. OnStart
  2. OnStop
Step 2
After creating the project, we can write the relevant code on onStart method. There are different types of methodology to achieve the goal. Here I preferred threading, which we can handle easily. Inside the start thread you can have your functionality. We have to install the service for registering the service in windows machine. For this we have to inherit from installer base class. There will be two classes ie service installer and process installer. The two class should be inherited to achieve the relavant functionality.

Step 3 Configuration of the service comes the important part in window service development. Same name should be given inside the service installer class. This will recognise the service installer to install which service during installation. This can be set in property window of service installer control.

“Picture can represent things better than thousand words”

Like that simple code can explain things better. So I will give an example, which is written in C#.



using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Xml;
using System.Data.SqlClient;
using System.Web.Mail;
using System.Threading;


namespace NotificationEngine{
 public class EmailService : System.ServiceProcess.ServiceBase 
 { 
 private bool bStopValue; 
 private int nSleepTime;


public EmailService() { 
 bStopValue = false; 
 nSleepTime = 5000; //default time is 5000 milliseconds. 

// This call is required by the Windows.Forms Component Designer. 
 InitializeComponent();


// TODO: Add any initialization after the InitComponent call 
}


// The main entry point for the process 
 static void Main() 
 { 
 System.ServiceProcess.ServiceBase[] ServicesToRun; 
// More than one user Service may run within the same process. To add 
// another service to this process, change the following line to 
// create a second service object. For example, 
//// 
 ServicesToRun = new System.ServiceProcess.ServiceBase[] 
{
new Service1(), 
new MySecondUserService()
}; 
// ServicesToRun = new System.ServiceProcess.ServiceBase[] 

new EmailService() 
};


System.ServiceProcess.ServiceBase.Run(ServicesToRun); 
}


/// <summary> 
/// Required method for Designer support - do not modify 
 /// the contents of this method with the code editor. 
 /// </summary> 
 private void InitializeComponent() 
 { 
 this.ServiceName = "WindowsService";
}


/// <summary> 
/// Clean up any resources being used. 
/// </summary> 
protected override void Dispose( bool disposing ) 
{ 
if( disposing ) 
{
// if (components != null)
// {
// components.Dispose();
// } 
} 


base.Dispose( disposing ); 
}


/// <summary> 
/// Set things in motion so your service can do its work. 
/// </summary> 
protected override void OnStart(string[] args) 
 { 
 // TODO: Add code here to start your service. 
 bStopValue = false; 
Thread t = new Thread(new ThreadStart(ThreadFun)); 
t.Start(); 
}


private void ThreadFun() 
{ 
 if(AppReader.GetValue("TimerInterval") != null) 
 nSleepTime = int.Parse(AppReader.GetValue("TimerInterval")); 

while(!bStopValue) 
{ 
 bool bRetval = HandleNotification(); 
 System.Threading.Thread.Sleep(nSleepTime); 
 } 
}

/// <summary> 
 /// Stop this service. 
 /// </summary> 
 protected override void OnStop() { 
 // TODO: Add code here to perform any tear-down necessary to stop your service. 
 //For stopping the thread. 
 bStopValue = true; 
 }


private bool HandleNotification() 
 {
// TODO: The code for the required functionality 
 } 
}
}

Ok great, we finished the coding part. Now question arises how to install the process in windows machine!!!!! 

Lets do that.

Install Windows Service in Windows Machine

After writing the code, you will get an executable file which we have to install in the machine. The command is
InstallUtil /LogToConsole=true SaokEmailService.exe

The /LogToConsole is optional. If everything goes fine, you can see the new service will be installed. Click “Services” and you can see the newly installed service in the list. We can start and stop the service using the command net start <service name> and net stop <service name>. Even we can configure to start it automatically when windows start.

Debugging windows service

One of the toughest problems in programming is debugging windows service; But Microsoft Visual studio (any version) made programmers life very simple. Start the windows service. Open the windows service project using visual studio. In the project, select Debug(process. You can see all the process running on the local machine. Select the windows process and click attach. Before doing the above mentioned things, just remember to put a break point in the code. That’s all, now you can debug the program without much effort.





Happy programming!!!