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!!!!


Monday, August 14, 2006

Web Services and Microsoft SQL Server 2005

Microsoft SQL Server 2005 supports creating Web Services and storing data to be used in Web Services at a few different levels. With the addition of direct support in SQL Server for HTTP, we could think of SQL Server 2005 as a "Web Services server." This reduces the three-tier architecture usually required to support Web Services (database, middle tier, and client) to two-tier architecture, with stored procedures or XQuery/XSLT programs being used as a middle tier.

First of all create a stored procedure which will fetch some data from a table or a set of table. Assume the name of the stored procedure is usp_GetAllContacts() from a table called contacts.

The Stored procedure will be like this.
Create Procedure usp_GetAllContacts
AS
BEGIN
……Select Statement and business logic comes here.
END
Go

After creating this stored procedure next comes, exposing this as web service so that we can consume the same.

  • Syntax for creating Web service:
CREATE ENDPOINT endPointName [ AUTHORIZATION login ]
STATE = { STARTED | STOPPED | DISABLED }
AS { HTTP | TCP } (
<protocol_specific_arguments>
)
FOR { SOAP | TSQL | SERVICE_BROKER | DATABASE_MIRRORING } (
<language_specific_arguments>
)

<AS HTTP_protocol_specific_arguments> ::=
AS HTTP (
PATH = 'url'
, AUTHENTICATION =( { BASIC | DIGEST | INTEGRATED | NTLM | KERBEROS } [ ,...n ] )
, PORTS = ( { CLEAR | SSL} [ ,... n ] )
[ SITE = {'*' | '+' | 'webSite' },]
[, CLEAR_PORT = clearPort ]
[, SSL_PORT = SSLPort ]
[, AUTH_REALM = { 'realm' | NONE } ]
[, DEFAULT_LOGON_DOMAIN = { 'domain' | NONE } ]
[, COMPRESSION = { ENABLED | DISABLED } ]
)

<AS TCP_protocol_specific_arguments> ::=AS TCP (
LISTENER_PORT = listenerPort
[ , LISTENER_IP = ALL | (<4-part-ip> | <ip_address_v6> ) ]
)

<FOR SOAP_language_specific_arguments> ::=
FOR SOAP(
[ { WEBMETHOD [ 'namespace' .] 'method_alias'
( NAME = 'database.owner.name'
[ , SCHEMA = { NONE | STANDARD | DEFAULT } ]
[ , FORMAT = { ALL_RESULTS | ROWSETS_ONLY } ]
)
} [ ,...n ] ]
[ BATCHES = { ENABLED | DISABLED } ]
[ , WSDL = { NONE | DEFAULT | 'sp_name' } ]
[ , SESSIONS = { ENABLED | DISABLED } ]
[ , LOGIN_TYPE = { MIXED | WINDOWS } ]
[ , SESSION_TIMEOUT = timeoutInterval | NEVER ]
[ , DATABASE = { 'database_name' | DEFAULT }
[ , NAMESPACE = { 'namespace' | DEFAULT } ]
[ , SCHEMA = { NONE | STANDARD } ]
[ , CHARACTER_SET = { SQL | XML }]
[ , HEADER_LIMIT = int ]
)
<FOR SERVICE_BROKER_language_specific_arguments> ::=
FOR SERVICE_BROKER (
[ AUTHENTICATION = {
WINDOWS [ { NTLM | KERBEROS | NEGOTIATE } ]
| CERTIFICATE certificate_name
| WINDOWS [ { NTLM | KERBEROS | NEGOTIATE } ] CERTIFICATE certificate_name
| CERTIFICATE certificate_name WINDOWS [ { NTLM | KERBEROS | NEGOTIATE } ]
} ]
[ , ENCRYPTION = { DISABLED | SUPPORTED | REQUIRED }
[ ALGORITHM { RC4 | AES | AES RC4 | RC4 AES } ]
]
[ , MESSAGE_FORWARDING = { ENABLED | DISABLED* } ]
[ , MESSAGE_FORWARD_SIZE = forward_size ]
)

<FOR DATABASE_MIRRORING_language_specific_arguments> ::=
FOR DATABASE_MIRRORING (
[ AUTHENTICATION = {
WINDOWS [ { NTLM | KERBEROS | NEGOTIATE } ]
| CERTIFICATE certificate_name
} ]
[ [ , ] ENCRYPTION = { DISABLED |SUPPORTED | REQUIRED }
[ ALGORITHM { RC4 | AES | AES RC4 | RC4 AES } ]
]
[,] ROLE = { WITNESS | PARTNER | ALL }
)


Example:

CREATE ENDPOINT Contact
STATE = Started
AS HTTP
(
PATH = '/Contact',
PORTS = (CLEAR),
SITE = '*',
AUTHENTICATION = (INTEGRATED)
)
FOR SOAP
(
WEBMETHOD 'urn:autos'.'GetAllContacts'
(NAME = 'TempDB.dbo.GetAllContacts', SCHEMA=DEFAULT, FORMAT = ALL_RESULTS),
WSDL=DEFAULT,
SCHEMA=STANDARD,
DATABASE = 'TempDB’
NAMESPACE = 'urn:autos
)
GO


Through this way we can expose the stored procedure as Web service. This web service can be called by any application which got the feature of consuming web services. You can view the WSDL of this web service by giving the SQL Server URL and the web service name. In this scenario “http://VS2005/Contact?WSDL” will be the URL. You will get the WSDL detail of the web service, if you give this URL to your browser like Internet explorer or any web browser you are using. The ENDPOINT syntax got many features, which I believe you yourself will explore.

Consuming Microsoft SQL Server 2005 web service in a ASP .NET Application
Open the ASP .Net web application in Visual Studio 2005. Open the solution explorer and right click the project. There you can see Add Web reference. Just add the web reference menu and a dialog box will come. In that you type the URL of the web service, for e.g.:- “http://VS2005/Contact?WSDL”. You can see the web methods defined in the concerned web service. Click “Add reference” button and that’s all, you included the web service. It is a straight away method of consuming the web service in visual studio IDE.
Another method is using proxy classes which can be created by the command, wsdl in .net command prompt. The syntax is wsdl “<URL of the web service>”. This will create a class file. We can add the respective class file to our ASP .net web application. This class file will take care of the job for calling the web service. Web methods of the web service and its details like parameters, parameter type, port, authentication type etc are defined in this class file. If you don’t have IDE like visual studio, then this proxy class file can be used for consuming the web service.
In END POINT syntax, we should give much importance to the parameter FORMAT = ALL_RESULTS. By default, the parameter will be “rowset” and in return well get only datasets. If we want to get all the details like SQL message, row count etc then we should use ALL_RESULT. When parameter is ALL_RESULT, it will return array of objects. The T-SQL statement I used to fetch the values from database is something like that

“SELECT ID, FIRSTNAME, LASTNAME from CONTACTS for xml auto, ELEMENTS XSINIL, ROOT('Contacts')”

This will give us a result like this:
<Contacts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Contact>
<Id>5</Id>
<FirstName>Rama</FirstName>
<LastName>Krishnan</LastName>
</Contact>
</Contacts>

C# code to read this information is:-
XmlElement objXmlElement = null;
foreach (object result in objObject)
{
if (result is XmlElement)
{
objXmlElement = (XmlElement)result;
}
}

DataSet objDataSet = new DataSet();
Stream objXmlStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(objXmlElement.InnerXml));
objDataSet.ReadXml(objXmlStream, XmlReadMode.Auto);

After fetching the data into the dataset you can use this to directly bind it to a data grid or combo box
objDatagrid.DataSource = objDataSet;
objDataGrid.DataBind();


All values will be populated in the data grid.
  • Deleting Web Service in SQL Server
DROP ENDPOINT <Web Service Name>
  • Altering Web Service in SQL Server
ALTER ENDPOINT endPointName
[ AFFINITY = { NONE | <64bit_integer> | ADMIN } ]
[ STATE = { STARTED | STOPPED | DISABLED } ]
AS { TCP | HTTP } (
<protocol specific items>
)
FOR { SOAP | TSQL | SERVICE_BROKER | DATABASE_MIRRORING } (
<language specific items>
)

<AS HTTP_protocol_specific_arguments> ::=
AS HTTP (
PATH = 'url'
, PORTS = ( { CLEAR | SSL } [ ,...n ] )
[ SITE = { '*' | '+' | 'webSite' } , ]
[ , CLEAR_PORT = clearPort ]
[ , SSL_PORT = SSLPort ]
, AUTHENTICATION = ( { BASIC | DIGEST | NTLM | KERBEROS | INTEGRATED } [ ,...n ] )
[ , AUTH_REALM = { 'realm' | NONE } ]
[ , DEFAULT_LOGON_DOMAIN = { 'domain' | NONE } ]
[ , COMPRESSION = { ENABLED | DISABLED } ]
)

<AS TCP_protocol_specific_arguments> ::=
AS TCP (
LISTENER_PORT = listenerPort
[ , LISTENER_IP = ALL | (<4-part-ip> | <ip_address_v6> ) ]
)

<FOR SOAP_language_specific_arguments> ::=
(
[ { ADD WEBMETHOD [ 'namespace' .] 'method_alias'
( NAME = 'database.owner.name'
[ , SCHEMA = {NONE | STANDARD | DEFAULT } ]
[ , FORMAT = { ALL_RESULTS | ROWSETS_ONLY } ]
)
} [ ,...n ] ]
[ { ALTER WEBMETHOD [ 'namespace' .] 'method_alias'
( NAME = 'database.owner.name'
[ , SCHEMA = {NONE | STANDARD | DEFAULT} ]
[ , FORMAT = { ALL_RESULTS | ROWSETS_ONLY } ]
)
} [ ,...n] ]
[ { DROP WEBMETHOD [ 'namespace' .] 'method_alias' } [ ,...n ] ]
[ BATCHES = { ENABLED | DISABLED } ]
[ , WSDL = { NONE | DEFAULT | 'sp_name' } ]
[ , SESSIONS = { ENABLED | DISABLED } ]
[ , SESSION_TIMEOUT = int ]
[ , DATABASE = { 'database_name' | DEFAULT }
[ , NAMESPACE = { 'namespace' | DEFAULT } ]
[ , SCHEMA = { NONE | STANDARD } ]
[ , CHARACTER_SET = { SQL | XML } ]
)

<FOR SERVICE_BROKER_language_specific_arguments> ::=
FOR SERVICE_BROKER (
[ AUTHENTICATION = {
WINDOWS [ { NTLM | KERBEROS | NEGOTIATE } ]
| CERTIFICATE certificate_name
| WINDOWS [ { NTLM | KERBEROS | NEGOTIATE } ] CERTIFICATE certificate_name
| CERTIFICATE certificate_name WINDOWS [ { NTLM | KERBEROS | NEGOTIATE } ]
} ]
[ , ENCRYPTION = { DISABLED | SUPPORTED | REQUIRED }
[ ALGORITHM { RC4 | AES | AES RC4 | RC4 AES } ]
]

[ , MESSAGE_FORWARDING = ENABLED | DISABLED* ]
[ , MESSAGE_FORWARD_SIZE = forwardSize
)

<FOR DATABASE_MIRRORING_language_specific_arguments> ::=
FOR DATABASE_MIRRORING (
[ AUTHENTICATION = {
WINDOWS [ { NTLM | KERBEROS | NEGOTIATE } ]
| CERTIFICATE certificate_name
} ]
[ [ , ] ENCRYPTION = { DISABLED |SUPPORTED | REQUIRED }
[ ALGORITHM { RC4 | AES | AES RC4 | RC4 AES } ]
]
[ , ] ROLE = { WITNESS | PARTNER | ALL }
)


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!!!