Friday, December 26, 2008

How to List Installed Softwares on a machine using VBScript?

Here is a handy code to list down all the installed softwares on a machine with their installation information:

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile("D:\Test\softwares.tsv", True)

strComputer = "."
Set objWMIService = GetObject("winmgmts:"_
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colSoftware = objWMIService.ExecQuery("Select * from Win32_Product")

objTextFile.WriteLine "Caption" & vbtab & _
"Description" & vbtab & "Identifying Number" & vbtab & _
"Install Date" & vbtab & "Install Location" & vbtab & _
"Install State" & vbtab & "Name" & vbtab & _
"Package Cache" & vbtab & "SKU Number" & vbtab & "Vendor" & vbtab _
& "Version"

For Each ObjSoftware in colSoftware
objTextFile.WriteLine objSoftware.Caption & vbtab & _
objSoftware.Description & vbtab & _
objSoftware.IdentifyingNumber & vbtab & _
objSoftware.InstallDate2 & vbtab & _
objSoftware.InstallLocation & vbtab & _
objSoftware.InstallState & vbtab & _
objSoftware.Name & vbtab & _
objSoftware.PackageCache & vbtab & _
objSoftware.SKUNumber & vbtab & _
objSoftware.Vendor & vbtab & _


Hope this helps :)

StyleSheet for Floating Div Tag in HTML

Here is the StyleSheet for displaying a floating DIV tag in HTML. This is often required to display status, Tooltips etc.

border-right: #0067a2 3px solid;
padding-right: 3px;
border-top: #0067a2 3px solid;
padding-left: 3px;
z-index: 1;
left: 18%;
float: none;
visibility: visible;
padding-bottom: 3px;
margin: 2px;
border-left: #0067a2 3px solid;
padding-top: 3px;
border-bottom: #0067a2 3px solid;
position: absolute;
top: 27%;
background-color: #6095b3;
width: 600px;
height: 220px;

Include the above class in your stylesheet and use ash shown below:

<div class="floatingDiv" id="Test_1"> </div>

Hope this helps you!

How to dynamically add Update Panel to page?

Here is a simple code to dynamically add update panel to page:

UpdatePanel upannel = new UpdatePanel();
upannel.ChildrenAsTriggers = true;
upannel.UpdateMode = UpdatePanelUpdateMode.Conditional;
upannel.ID = "updatePannel_1";

Hope this helps you :)

How to parse mails in Microsoft Outlook using C#?

We often get hundreds of mails in our Outlook Inbox and want to do some processing with these mails. This scenario arises mainly with the customer support people who wanted to act depending on the mail subject line. Here is a simple code to parse the Microsoft Outlook Inbox:

static void ReadMail()
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.MailItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;

app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);

inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
// subFolder = inboxFolder.Folders["Inbox"]; //folder.Folders[1]; also works
Console.WriteLine("Folder Name: {0}, EntryId: {1}", inboxFolder.Name, inboxFolder.EntryID);
Console.WriteLine("Num Items: {0}", inboxFolder.Items.Count.ToString());

System.IO.StreamWriter strm = new System.IO.StreamWriter(@"d:\Test\Inbox.txt");
for (int counter = 1; counter <= inboxFolder.Items.Count; counter++)
item = (Microsoft.Office.Interop.Outlook.MailItem)inboxFolder.Items[counter];
Console.WriteLine("Item: {0}", counter.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
Console.WriteLine("Sendername: {0}", item.SenderName);
strm.WriteLine(counter.ToString() + "," + item.Subject + "," + item.SentOn.ToShortDateString() + "," + item.SenderName);
catch (System.Runtime.InteropServices.COMException comException)
ns = null;
app = null;
inboxFolder = null;

Hope this helps you :)

How to determine the control that caused PostBack in an ASP.NET Page?

I have faced this issue a lot of time, where I want to know what control caused the page to postback. If you study carefully, you will find that ALL the server side controls are rendered as simple HTML to the client browser. When a postback occurs some event at the server side is triggered such as Button_Click, SelectedIndexChanged, Page_Load etc. Now let's go in some more details.. The rendered page is nothing but a plain HTML. Now when the page causes a postback, the engine needs to know what has cused the postback. Depending on this, the engine will trigger particular event on the server side. How does the engine know what control has caused postback???

If you view the source of the rendered page you would find some hidden text fields such as __EVENTTARGET, __EVENTARGUMENT, __VIEWSTATE. These fields act as information storage for the HTML page. They convey the postback infromation to the engine, which can then trigger appropriate event.

When you change the index of dropdown control or any other control, a javascript function name "__doPostBack" is invoked. This function is responsible for saving the control information along with control arguments i.e. called as EventTarget and EventArguments. The __EVENTTARGET field stores the name of the control that caused postback. Hence by simply querying this hidden field we can get the name of the control that caused postback as shown below:

string controlName = page.Request.Params.Get("__EVENTTARGET");
if (controlName != null && controlName != string.Empty)
return this.Page.FindControl(controlName );

This will work absolutely fine with TextBox, DropDown, LinkButton control, but it won't work with Button control. Since the Button control is rendered as <input type="Submit" />. The __doPostBack function is not called in this case, hence the hidden field __EVENTTARGET is not set. Now in such case how to find the control name that caused postback?

An IMPORTANT point to note is a Submit button i.e. <input type="Submit" /> is not added to the Form until it causes a postback. This means that if their are 3 buttons on the page names B1, B2 and B3. And B2 caused a postback then B1 and B3 will not be added to the form. Thus if the Button causes a postback we can definitely search it in page.Request.Form as shown below:

Control control = null;
foreach (string formControl in page.Request.Form)
Control ctrl = page.FindControl(formControl );
if (ctrl is System.Web.UI.WebControls.Button)
control = ctrl;

Thus the final method to get the postback control will look like:

 public Control GetPostBackControl(Page CurrentPage)
Control control = null;
string controlName = page.Request.Params.Get("__EVENTTARGET");
if (controlName != null && controlName != string.Empty)
control this.Page.FindControl(controlName );

foreach (string formControl in page.Request.Form)
Control ctrl = page.FindControl(formControl );
if (ctrl is System.Web.UI.WebControls.Button)
control = ctrl;
return control;

In this way we can find out the control that caused postback in

Hope this helps :)

Agile/Scrum Methodology for Software Projects!

Here is a classic presentation from Ken Schwaber on Agile/Scrum methodology for software project development.

Click here to view the presentation on youtube.

Download Month Calendar User Control!

We get many advance Calendar controls on the internet and in controls library, but I was struggling to find the Month Calendar control. A control that will only display months in a year with a hyperlink(event). Finally here is one that I have developed.


Code in ASPX Page:

<%@ Register Src="~/UserControls/MonthSelectControl.ascx" TagName="MonthSelectControl" TagPrefix="uc1" %>


<uc1:MonthSelectControl ID="TestControl" runat="server" />


Code in .aspx.cs (CodeBehind) Class:

In Page_Load event register the Month Calendar control DateChanged event as shown below:

TestControl.DateChanged += new EventHandler(Control_DateChanged);

Code for the DateChanged Event:

void DateChanged(object sender, EventArgs e)


MonthCalendarControlEventArgs arg = (MonthCalendar.MonthCalendarControlEventArgs) e;

string month = arg.Month;

string year = arg.Year;


Download the control here.

Your comments are welcome :)

Why I cannot access classes in .aspx codebehind from the classes in app_code in

This is a fantastic problem that I faced. I was having a user control in my application as MSDD.ascx. I wanted to dynamically display this user control from the code written in the Dynamic.cs file in app_code folder of my applicaiton. But at this movement, I was unable to access the MSDD class written in codebehind file from my class in app_code. How can we proceed now???


The best solution is to write an Interface. Place this interface in the app_code folder of you application. The aspx codebehind class should implment this particular interface. Now via interface you can access the codebehind class from you class in app_code folder. See the scenario below:

I have following files:

ASPX: A user control/class named MSDD.

app_code: A call named Dynamic, in which I want to access the above user control class MSDD.

Now write an interface IMSDD and make the codebehind class MSDD to implement this IMSDD interface. So you MSDD class will look like:

public class MSDD : IMSDD


// Code here...


And your Dynamic class which uses the Interface will look like:

public class Dynamic


IMSDDctrl = (IMSDD) Page.LoadControl("../MSDD.ascx");

// Now using this interface you can invoke any method/property of the MSDD class this is exposed via the interface.



Hope this helps you...

How to Create a Process on Remote Computer using VBScript WMI?

Here is a sample code to start the notepad.exe on a remote computer. This code works well with all the Windows operating system except for the advance OS like Windows XP the notepad opens in an invisible mode. In the code below you need to replace "server" with the name of the computer where you want to start the process.

strComputer = "server"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
Error = objWMIService.Create("notepad.exe", null, null, intProcessID)
If Error = 0 Then
Wscript.Echo "Notepad was started with a process ID of " & intProcessID & "."
Wscript.Echo "Notepad could not be started due to error" & Error & "."
End If

Hope this helps!

How to prevent sending an email without subject from Microsoft Outlook?

We often feel horrible when we send email messages to our bosses without any subject line. Here is a simple way to avoid such mistakes...

Steps: -
1. Open your Outlook,
2. Press Alt+F11. This opens the Visual Basic Editor and then Press Ctrl+R which in turn open Project-Project 1 (left side)
3. On the Left Pane, one can see "Microsoft Outlook Objects" or "Project1", expand this. Now one can see the "ThisOutLookSession".
4. Double click on "ThisOutLookSession". It will open up a Code Pane on the right hand side.
5. Copy and Paste the following code in the right pane (Code Pane) and save it

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim strSubject As String
strSubject = Item.Subject
If Len(Trim(strSubject)) = 0 Then
Prompt$ = "Subject is Empty. Are you sure you want to send the Mail?"
If MsgBox(Prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check for Subject") = vbNo Then
Cancel = True
End If
End If
End Sub
6. Save the Project and exit.

Now whenever you try to send a mail without subject, a pop-up is raised to remind you of the blank subject.

How to Bulk Insert records to T-SQL Table from a DataTable in C#?

This article will tell you two method of inserting bulk records into a T-SQL table from a DataTable in C#:

1. Bulk insert using the SqlBulkCopy class

2. Bulk insert by passing XML data table to the stored procedure

The first method is used ONLY to insert the data to the database and is simple as compared to the second method. The second method can be used to do some complex processing while inserting/updating the data in the SQL table.

In the first method we will make use of the SqlBulkCopy class provided in .NET. Following code illustrates the use of the SqlBulkCopy class for bulk insert:

#region references
using System.Data;
using System.Data.SqlClient;
#endregion references

namespace SQLBulkInsert
class Program
static void Main(string[] args)
// T-SQL Connection
string connection = "Data source=.; Initial Catalog= MyDatabase; SSPI=true";
DataTable dtData = new DataTable();

// Get the data into the DataTable
//dtData = GetData(...);

// Create an object of SqlBulkCopy
SqlBulkCopy objSBC = new SqlBulkCopy(connection);
// Specify the destination table
objSBC.DestinationTableName = "Table_Name";
// Write the data to the SQL Server

You can find the implementation of the second method in my article on

Hope this helps you!

How to convert int Month to String Month Name in C#?

Often we get month as integer from external source and want to display it as "Oct" or "October" i.e. string. Following is a code to convert the int month to string month :)

/// <summary>
/// Converts the given month int to month name
/// </summary>
/// <param name="month">month int </param>
/// <param name="abbrev">return abbreviated or not</param>
/// <returns>Short or long month name as string </returns>
private static string GetMonthName(int month, bool abbrev)
DateTime date = new DateTime(2000, month, 1);
if (abbrev) return date.ToString("MMM");
return date.ToString("MMMM");
Hope this helps :)

How to assign a static IP address using VBScript?

This type of scripts are always in demand by the network proffessionals. Here is a handy script that assigns a static IP address to a machine:

strComputer = "."
Set objWMIService = GetObject ("winmgmts:" & "{impersonationLevel = impersonate}!\\" & strComputer & "\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")
strIPAddress = Array("")
strSubnetMask= Array("")
strGateway = Array("")
strGatewayMetric = Array(1)
For Each objNetAdapter in colNetAdapters
errorEnable = objNetAdapter.EnableStatic(strIPAddress,strSubnetMask)
errorGateway= objNetAdapter.SetGateways(strGateway, strGatewayMetric)
If errorEnable = 0 Then
WScript.Echo "The IP Address has been changed successfully!!"
WScript.Echo "Their was an error, the IP Address could not be changed!"
End If
Hope this helps :)

How to Start, Stop and Pause a Web Server on IIS using VBScript?

Here is a VBScript code to start, stop and pause a web server running in IIS:

Start a Web Server

strComp = "LocalHost"
Set objIIS = GetObject("IIS://" & strComp & "/W3SVC/2142295254")

Stop a Web Server

strComp = "LocalHost"
Set objIIS = GetObject("IIS://" & strComp & "/W3SVC/2142295254")

Pause a Web Server

strComp = "LocalHost"
Set objIIS = GetObject("IIS://" & strComp & "/W3SVC/2142295254")

Hope this helps :)

Friday, October 31, 2008

How to list domain information using VBScript - WMI?

Here is a handy VBScript code to list domain information. This code will list down the domain information for all the domains found on that machine.

on Error Resume Next
strComputer = "."
Set objWMISvc = GetObject ("winmdmts:"_
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMISvc.ExecQuery("Select * from Win32_NTDomain")
For Each objItem in colItems
Wscript.Echo "Client Site Name: " & objItem.ClientSiteName
Wscript.Echo "DC Site Name: " & objItem.DCSiteName
Wscript.Echo "Descriptopn: " & objItem.Description
Wscript.Echo "DNS Forest Name: " & objItem.DnsForestName
Wscript.Echo "Domain Controller Address: " & objItem.DomainControllerAddress
Wscript.Echo "Domain Controller Address Type: " & objItem.DomainControllerAddressType
Wscript.Echo "Domain Controller Name: " & objItem.DomainControllerName
Wscript.Echo "Domain GUID: " & objItem.DomainGuid
Wscript.Echo "Domain Name: " & objItem.DomainName
Wscript.Echo "Primary Owner Contact: " & objItem.PrimaryOwnerContact

Hope this Helps!

This blog will be closed in near future, please refer the same article at :

Sunday, September 7, 2008

What is Active and Passive FTP?

What is FTP?
File Transfer Protocol (FTP) is a network protocol used to transfer data from one computer to another through a network, such as the Internet. FTP is a file transfer protocol for exchanging and manipulating files over any TCP-based computer network. A FTP client may connect to a FTP server to manipulate files on that server. As there are many FTP client and server programs available for different operating systems, FTP is a popular choice for exchanging files independent of the operating systems involved.

What is Active and Passive FTP?
The Basics
FTP is a TCP based service exclusively. There is no UDP component to FTP. FTP is an unusual service in that it utilizes two ports, a 'data' port and a 'command' port (also known as the control port). Traditionally these are port 21 for the command port and port 20 for the data port. The confusion begins however, when we find that depending on the mode, the data port is not always on port 20.

Active FTP
In active mode FTP the client connects from a random unprivileged port (N > 1023) to the FTP server's command port, port 21. Then, the client starts listening to port N+1 and sends the FTP command PORT N+1 to the FTP server. The server will then connect back to the client's specified data port from its local data port, which is port 20.
From the server-side firewall's standpoint, to support active mode FTP the following communication channels need to be opened:

  • FTP server's port 21 from anywhere (Client initiates connection)
  • FTP server's port 21 to ports > 1023 (Server responds to client's control port)
  • FTP server's port 20 to ports > 1023 (Server initiates data connection to client's data port)
  • FTP server's port 20 from ports > 1023 (Client sends ACKs to server's data port)

When drawn out, the connection appears as follows:

In step 1, the client's command port contacts the server's command port and sends the command PORT 1027. The server then sends an ACK back to the client's command port in step 2. In step 3 the server initiates a connection on its local data port to the data port the client specified earlier. Finally, the client sends an ACK back as shown in step 4.
The main problem with active mode FTP actually falls on the client side. The FTP client doesn't make the actual connection to the data port of the server--it simply tells the server what port it is listening on and the server connects back to the specified port on the client. From the client side firewall this appears to be an outside system initiating a connection to an internal client--something that is usually blocked.

Passive FTP
In order to resolve the issue of the server initiating the connection to the client a different method for FTP connections was developed. This was known as passive mode, or PASV, after the command used by the client to tell the server it is in passive mode.
In passive mode FTP the client initiates both connections to the server, solving the problem of firewalls filtering the incoming data port connection to the client from the server. When opening an FTP connection, the client opens two random unprivileged ports locally (N > 1023 and N+1). The first port contacts the server on port 21, but instead of then issuing a PORT command and allowing the server to connect back to its data port, the client will issue the PASV command. The result of this is that the server then opens a random unprivileged port (P > 1023) and sends the PORT P command back to the client. The client then initiates the connection from port N+1 to port P on the server to transfer data.
From the server-side firewall's standpoint, to support passive mode FTP the following communication channels need to be opened:

  • FTP server's port 21 from anywhere (Client initiates connection)
  • FTP server's port 21 to ports > 1023 (Server responds to client's control port)
  • FTP server's ports > 1023 from anywhere (Client initiates data connection to random port specified by server)
  • FTP server's ports > 1023 to remote ports > 1023 (Server sends ACKs (and data) to client's data port)

When drawn, a passive mode FTP connection looks like this:

In step 1, the client contacts the server on the command port and issues the PASV command. The server then replies in step 2 with PORT 2024, telling the client which port it is listening to for the data connection. In step 3 the client then initiates the data connection from its data port to the specified server data port. Finally, the server sends back an ACK in step 4 to the client's data port.
While passive mode FTP solves many of the problems from the client side, it opens up a whole range of problems on the server side. The biggest issue is the need to allow any remote connection to high numbered ports on the server. Fortunately, many FTP daemons, including the popular WU-FTPD allow the administrator to specify a range of ports which the FTP server will use. The second issue involves supporting and troubleshooting clients which do (or do not) support passive mode. As an example, the command line FTP utility provided with Solaris does not support passive mode, necessitating a third-party FTP client, such as ncftp.

Thursday, September 4, 2008

All new Google Chrome!!!

Google enters into a new era of competition in IE Browsers. Google has launched its new “Google Chrome” browser and claims to be one of the fastest internet browser. This browser has many advance functions including the unique one – incognito window. The data (such as cookies etc)entered into the incognito window will not be saved in the browser history. Chrome has a capability to show "Most Visited" pages, Recent Bookmarks and even search box is provided on the IE. Unlike other browsers, Chrome gives a larger client area (client area is the area where the web page is displayed).

Explore more and have a happy browsing !

Wednesday, September 3, 2008

Magic with Windows!!!

See the magic that happens in Windows (except Vista) :)

Nobody can create a FOLDER anywhere on the computer which can be named as “CON“. Try it!!!

This one is awesome. Try it yourself…
Open Microsoft Word and type
=rand (200, 99)
and then press ENTER

Do the following:
1. Open an emty notepad file
2. Type “bush hid the facts” ( without the quotes )
3. Save it as whatever you want.
4. Close it, and re-open it.
See what has happened….
You can try the same thing above with another sentence “this app can break”.

There are logical reasons behind these magic... try to find them!

Wednesday, August 27, 2008

How to implement Threading in C#.NET?

What is Threading?

A Thread is an independent execution path for a code that can run concurrently with other execution paths i.e. other threads. All threads within a single application are logically contained within a Process – the operating system unit in which an application runs.. Application performance can be improved by executing multiple code paths simultaneously i.e. executing multiple threads simultaneously. This phenomenon of executing multiple threads simultaneously is called as Multi-threading. Multi-threading is often used in applications to enhance the application performance. Usually multiple threads that are executed are independent of each other to enhance the performance by reducing dependencies.

C# supports multi-threading of applications. A C# programs (let’s consider a console application) starts in a single thread created by the CLR and the OS i.e. the “main” thread. Then user can invoke multiple threads from this main thread to create a multi-threaded application. Let’s consider the example given below:

C# Threading Example:

using System;
using System.Threading;

namespace ThreadingSamples
class Program
static void Main(string[] args)

Program pg = new Program();
Thread thread = new Thread(new ThreadStart(pg.Fun));
thread.Name = "Thread_1";

Thread.CurrentThread.Name = "Main_Thread";


public void Fun()


In the above given sample C# code, the main thread is invoked (also called as spawned) by the CLR. In the main thread we have created another thread called “Thread_1” and invoked the thread using the thread.Start() method. Note that we need to include the System and System.Threading namespaces for implementation of threading in C#. A separate copy of the variables in the “Fun” method is created for each thread (which resides on each threads memory stack). We have created an object of “ThreadStart”. Basically ThreadStart is a delegate that invokes the method supplied to it. In this example we have invoked a method “Fun” that does not accept any arguments. But if we want to call a function that accepts arguments then we have to use ParameterizedThreadStart instead of ThreadStart. The threads can be named, as we have named the thread “Main_Thread” and “Thread_1”.

How Threading Works in C#?

Multithreading is managed internally by a thread scheduler, a function the CLR typically delegates to the operating system. A thread scheduler ensures all active threads are allocated appropriate execution time, and that threads that are waiting or blocked such as on an exclusive lock, or for user input do not consume CPU time. Usually time-slicing mechanism is used to schedule the thread execution.

What is a Thread Safe Function?

A method/function that can ONLY be executed by a Single thread at a time is called as a Thread Safe function. The function “Fun” that we have seen in the above code sample is not thread safe, since any number of threads can access/execute this function simultaneously. When we talk about a thread safe function, the question arises- Why do we require a thread safe function? A thread safe function is required usually when we share variables across threads such as static variables or when we want that an object should be manipulated by a single thread at a time to maintain the data integrity. Let’s see an example of Thread Safe function…

C# Thread Safe Function:

class Program
static void Main(string[] args)

Program pg = new Program();
Thread thread = new Thread(new ThreadStart(pg.Fun));
thread.Name = "Thread_1";
thread.Priority = ThreadPriority.Normal;

Thread.CurrentThread.Name = "Main_Thread";


public void Fun()
// The C# “lock” statement will lock the execution of the thread

In the above sample code, the C# “lock” statement is used to lock the execution of the block when one thread is executing it. This means that ONLY one thread at a time can enter this Lock block for execution. Any other thread trying to enter will have to wait until the first thread completes its execution. Thus in this way we can make a function as a thread safe function. This can even be achieved by using Semaphores, Mutex etc. We do set priorities for threads in execution. Various values for thread priority are AboveNormal, BelowNormal, Normal, Highest, and Lowest.

Hope this helps you! Your comments are always welcome !

What is Cohesion and Coupling?

Cohesion of a single component is the affinity between different units of the module. High cohesion is expected during designing application architecture.

Coupling between components is their degree of mutual interdependence. Low coupling is expected during design application architecture. Low coupling makes components behave as plug-n-play devices.

  • size: Number of connections between routines
  • intimacy: The directness of the connection between routines
  • visibility: The prominence of the connection between routines
  • flexibility: The ease of changing the connections between routines

Following are the types of Cohesion observed during the design phase:

  • Coincidental Cohesion: (Worst) Module elements are unrelated.
  • Logical Cohesion: Elements perform similar activities as selected from outside module.
  • Temporal Cohesion: Operations related only by general time performed (i.e. initialization() or FatalErrorShutdown()).
  • Procedural Cohesion: Elements involved in different but sequential activities, each on different data. This can be divided into several functions as required.
  • Communicational Cohesion : Unrelated operations except need same data or input.
  • Sequential Cohesion : operations on same data in significant order; output from one function is input to next (pipeline).
  • Informational Cohesion: a module performs a number of actions, each with its own entry point, with independent code for each action, all performed on the same data structure.
  • Functional Cohesion: all elements contribute to a single, well-defined task, i.e. a function that performs exactly one operation.

Following are the types of Coupling observed during design phase:

  • Content/Pathological Coupling: (worst) When a module uses/alters data in another .
  • Control Coupling: 2 modules communicating with a control flag (first tells second what to do via flag).
  • Common/Global-data Coupling: 2 modules communicating via global data.
  • Stamp/Data-structure Coupling: Communicating via a data structure passed as a parameter. The data structure holds more information than the recipient needs.
  • Data Coupling: (best) Communicating via parameter passing. The parameters passed are only those that the recipient needs.
  • No data coupling: independent modules.

More information at:

Monday, August 18, 2008

How to program Read,Write parallel port in C#?


The Parallel Port is the most commonly used port for interfacing homemade projects. Parallel ports are easy to program and faster compared to the serial ports. But main disadvantage is it needs more number of transmission lines. Because of this reason parallel ports are not used in long distance communications. This port allows the input of up to 9 bits or the output of 12 bits at any one given time, thus requiring minimal external circuitry to implement many simpler tasks. The port is composed of 4 control lines, 5 status lines and 8 data lines. It's found commonly on the back of your PC as a D-Type 25 Pin female connector.

What is a parallel port?
A port contains a set of signal lines that the CPU sends or receives data with other components. We use ports to communicate via modem, printer, keyboard, mouse and other such devices. In signaling, open signals are "1" and close signals are "0" so it is like binary system. A parallel port sends 8 bits and receives 5 bits at a time.

The parallel port comprises of 3 different ports the Data Port, the Status Port and the Control Port. These ports are distributed among the 25 PIN of the port. The data port ranges from PIN 2 to PIN 9 i.e. 8 PIN indicating a byte. The Status port ranges from PIN 10 to PIN 13 and the PIN 15 is also a part of the status port. The Control port comprises of PINs 1, 14, 16 and 17. The detail of these PINs and their functions is given below:
* Pins with * symbol in this table are hardware inverted. That means, If a pin has a 'low' ie. 0V, Corresponding bit in the register will have value 1.
Signals with prefix 'n' are active low. Normally these pins will have low value. When it needs to send some indication, it will become high. For example, normally nStrobe will be high, when the data is placed in the port, computer makes that pin low.
Normally, data, control and status registers will have following addresses. We need these addresses in programming later.

By default, data port is output port. To enable the bidirectional property of the port, we need to set the bit 5 of control register.
To know the details of parallel ports available in your computer, follow this procedure:
1. Right click on My Computer, go to "Properties".
2. Select the tab Hardware, Click Device manager.
3. You will get a tree structure of devices; in that Expand "Ports (Com1 &LPT)".
4. Double Click on the ECP Printer Port (LPT1) or any other LPT port if available.
5. You will get details of LPT port. Make sure that "Use this Port (enable)" is selected.
6. Select tab recourses. In that you will get the address range of port.

Parallel Port Interface Projects
1. Running LED lights.
2. Controlling a remote Car using the computer.
3. Controlling home appliances such as lights, fan, TV etc.
4. Any other gadget that you want to control.

Programming Parallel Port in C#
Till today we use to control the Parallel port using the “Turbo C”, which is easy to code and at the same time powerful to control the parallel port. C lacks the fancy user interface that most of the users are attracted towards. Even in this article we will be using the Console application, you can use the code and create a Windows Forms application for a fancy UI.

I have used an assembly inpout32.dll for interfacing with parallel port. This assembly provides easy access to the interfacing API’s. You can download the assembly from here.

If you are coding in Turbo C, you will end up using the functions outportb() and inportb() from the Stdio.h and IO.h library files.

Create a Console application project using Visual Studio. Add a file PortAccessAPI.cs and add the following code to this file:
// References
using System;
using System.Runtime.InteropServices;

/// <summary>
/// Class to access the Port API's from the inpout32.dll.
/// </summary>
public class PortAccessAPI
/// <summary>
/// This method will be used to send the data out to the parallel port.
/// </summary>
/// <param name="adress">Address of the port to which the data needs to be sent.</param>
/// <param name="value">Data that need to send out.</param>
[DllImport("inpout32.dll", EntryPoint="Out32")]
public static extern void Output(int address, int value);

/// <summary>
/// This method will be used to receive any data from the parallel port.
/// </summary>
/// <param name="address">Address of the port from which the data should be received.</param>
/// <returns>Returns Integer read from the given port.</returns>
[DllImport("inpout32.dll", EntryPoint = "Inp32")]
public static extern int Input(int address);
The Output function used in the above class will send the data out to the required port. The first parameter i.e. address, indicates the address of the port on which the data needs to be sent. The second parameter i.e. value, indicated the value (as integer) that needs to be sent to the port. In actual the value will be sent as binary on the port and hence an equivalent integer value needs to be computed before invoking this method.

Now in the Program.cs which is the entry point for the Console application, the following code will go in the Main method:

int address = 888;
int value = 24;
PortAccessAPI.Output(adress, value);

Here the address 888 as int is actually 0x378 as Hex, which is the data port of the parallel port.
To reset the data that is sent on the data port, you need to invoke the Output method with a value 0x00 i.e.0 as shown below:

int address = 888;
PortAccessAPI.Output(adress, 0);

This was all about writing data to the parallel port; now let’s see how we can read data from the parallel port. In the file PortAccessAPI.cs we have declared a function “Input”, this will be used to read the parallel port. This function takes a parameter “address”, this is the address of the parallel port that we want to read. This method will return an integer as the data that is read from the requested port. The code will look like:

int address = 888;
int value;
value = PortAccessAPI.Input(adress);

The variable “value” will contain the data that is read from the parallel port 0x378.

1. How Inpout32.dll works?
2. Inpout32.dll for Windows 98/NT/2000/XP.

Using this simple technique of read/write we can create innovative gadgets that can be controlled using the computer...

Hope this helps you !
Your comments are always welcome!

Sunday, August 17, 2008

How to Read an Excel in C#?

This article will help you understand reading an excel file in C#. This is often required when developing applications. Create an excel file named "Test.xls" in the C Drive. The sample excel file will look like:
For interacting with an excel file you will have to include the following COM assemblies:

  • Microsoft Excel 12.0 Object Library
  • Microsoft Office 12.0 Object Library

Following code will be used to read the excel file and display the values in a Console application:

// Add Reference
using System;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;

namespace ReadExcel
/// <summary>
/// This class will be used to read the excel and
/// display it in a console.
/// </summary>
class ReadExcelApplication
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
// Path for the test excel application
string Path = @"c:\test.xls";
// Initialize the Excel Application class
Excel.ApplicationClass app = new ApplicationClass();
// Create the workbook object by opening the excel file.
Excel.Workbook workBook = app.Workbooks.Open(Path,
// Get the active worksheet using sheet name or active sheet
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;

// This row,column index should be changed as per your need.
// i.e. which cell in the excel you are interesting to read.
int index = 1;
object rowIndex = 1;
object colIndex1 = 1;
object colIndex2 = 2;

while (((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2 != null)
// Read the Cells to get the required value.
string firstName = ((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2.ToString();
string lastName = ((Excel.Range)workSheet.Cells[rowIndex, colIndex2]).Value2.ToString();
Console.WriteLine("Name : {0},{1} ", firstName, lastName);
rowIndex = index;
catch (Exception ex)
// Log the exception and quit...


Hope this helps! Your comments are always welcome!

Wednesday, August 13, 2008

App_Offline.htm - How to Redirect user to "Down for Maintenance" page in ASP.NET ?

Usually there arises a scenario when we want to upgrade our production site to a new release, and want the users to be redirected to the “Down for Maintenance” page.

The best way to implement this is using the app_offline.htm file. ASP.NET 2.0 has provided a fantastic functionality using which the users will automatically be redirected to the “Down for Maintenence” page. Just add a HTML file named “app_offline.htm” to the root directory of your web site. Adding this file will clear the server cache. When ASP.NET sees the app_offline.htm file, it will shut-down the app-domain for the application (and not restart it for requests) and instead send back the contents of the app_offline.htm file in response to all new dynamic requests for the application.

Please take a note that the size of the file should be more that 512 bytes to be displayed. If the size of the file is less that 512 bytes, then manually IE Browser settings need to be changed. The "Show Friendly Http Errors" check box from the Tools->Internet Options->Advanced tab within IE needs to be unchecked. If this check-box is not unchecked and the app_offline.htm file size is less that 512 bytes, then the IE “Page cannot be displayed” message will be shown.

To start the web site again, just remove this file from the root folder of your web site. This will trigger the engine to cache all the page contents and display the pages. This has really made life simple :)

Hope this helps! Your comments are always welcome!

Saturday, August 9, 2008

What is Obsessive-Compulsive Disorder (OCD)?

Obsessive-Compulsive Disorder (OCD), is an anxiety disorder characterised by unwanted or intrusive thoughts(obsessions) which leads to repetitive behaviors or mental acts (compulsions)that the person feels driven to perform in response to an obsession to get relieved from anxiety.

For example:
If people are obsessed with germs or dirt, they may develop a compulsion to wash their hands over and over again repeatedly upto the level of distress.
Many people have doubt that the door is locked or not; they may develop a compulsion to check repeatedly if it is locked or not.

These are some situations encounterd by normal people also but the difference is that people with OCD perform their rituals several times even though doing so interferes with daily life till they feel the repetition distressing.

Friday, August 8, 2008

What is Delusion?

A delusion is a belief that is clearly false (non bizarre) ;due to abnormality in the affected person's content of thought. The false belief is not due to person’s cultural or religious background or his or her level of intelligence. It is the degree to which the person is convinced that the belief is true. A person with a delusion will hold firmly to the belief regardless of contrary evidence. Some delusions are:

Delusion of control: This is a false belief that another person, group of people, or external force controls one's thoughts, feelings, impulses, or behavior. A person may describe, for instance, the experience that aliens actually make him or her move in certain ways and that the person affected has no control over the bodily movements.

Delusional jealousy: A person with this delusion falsely believes that his or her spouse or lover is having an affair. This delusion stems from pathological jealousy and the person often gathers "evidence" and confronts the spouse about the nonexistent affair.

Delusion of guilt or sin: This is a false feeling of remorse or guilt of delusional intensity. A person may, for example, believe that he or she has committed some horrible crime and should be punished severely. Another example is a person who is convinced that he or she is responsible for some disaster (such as fire, flood, or earthquake) with which there can be no possible connection.

Delusion of mind being read: This is a false belief that other people can know one's thoughts. This is different from thought broadcasting in that the person does not believe that his or her thoughts are heard aloud.

There is a subtle difference between illusion and delusion.

Thursday, August 7, 2008

ASP.NET Page Life Cycle

When an ASP.NET page is requested by the client-browser, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. Moreover, for custom controls, understanding the page life cycle is very important in order to correctly initialize controls, populate control properties with view-state data, and run any control behavior code.

Page Life-cycle Stages
When a web page is requested it goes through a number of stages to get completely built. In addition to the page life-cycle stages, there are application stages that occur before and after a request to the page. Following are the stages under which a page goes before getting rendered to the client.

Page Request: The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled or whether a cached version of the page can be sent in response without running the page.

Start: In this step, the HTTP properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the
IsPostBack property. The page's UICulture property is also set.

Page initialization: During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. For the page post backs the controls values are not set in this stage from the view state.

Load: During load stage, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Validation: The Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
Postback event handling: If the request is a postback, any relevant event handlers are called.

Rendering: Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

Unload: Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

Life-cycle Events
At each stage of the page life cycle, the page raises certain events that can be used for custom coding. For control events, the event handlers must be bound to the enets. The following lists the page life-cycle events:
1. PreInit
2. Init
3. InitComplete
4. PreLoad
5. Load
6. Control events
7. LoadComplete
8. PreRender
9. SaveStateComplete
10. Render
11. Unload

Wednesday, August 6, 2008

How to Read/Write registry in C#?

Reading and writing to a registry is a routine task that an application developer has to perform using the C# code. Here is a handy way to read/write Windows registry using the C# code.

Required namespace:

using Microsoft.Win32;

Simple Way to Read/Write Registry:

public string GetRegistryValue(string key)
return Convert.ToString(Registry.GetValue
(@"HKEY_CURRENT_USER\Software\Yahoo\Common", "Sandy", "OLD"));

public void SetRegistryValue()
Registry.SetValue(@"HKEY_CURRENT_USER\Software\Yahoo\Common", "Sandy", NEW");

The above given is a simple method for accessing the registry. More complex class can be written to leverage advance registry functionality.

Tuesday, May 27, 2008

How to send mail in C# ?

Often a c# programmer has to write code to send e-mails. This feature is required in many scenarios such as sending a mail once a scheduled job is over or sending a mail after the daily builds are done etc. Here is a sample code that can be used to send emails using C#.

using System.Net.Mail;

namespace EmailHelper
public static class EMail
public static void SendMail()
// Create mail message object
MailMessage mail = new MailMessage();
// Add the FROM address
mail.From = new MailAddress("");
// Add TO address
mail.To.Add(new MailAddress(""));
// Enter the subject
mail.Subject = "This is a test Mail.";
// Enter body of email
mail.Body = "This is the body of the test mail.";
// Put smtp server you will use
SmtpClient smtpServer = new SmtpClient("SMTP Host");
// Send the mail

In the above code we make use of System.Net.Mail namespace. In the SendMail method, we first create a mail message using the MailMessage class and then send it using the SmtpClient. A SMTP server is specified which is used to send mails.

Comments are Welcome !

How to secure .NET Remoting communication ?

Often we require securing the .NET remoting communication. Here is a fantastic article that will enable you to secure .net remoting communication using asymmetric encryption and decryption.


Thursday, May 15, 2008

All New Microsoft Forums !!!

Microsoft has proposed to launch new MSDN forums : MSDN TechNet Expression Microsoft. The existing posts will be moved to the new forums in May. The points that are gained by the users will be preserved. A Sandbox forum, where you can create threads and try out functionality, and a suggestions forum where you can give your feedback.

Wednesday, May 14, 2008

How to get Printer Submitted Jobs in C# ?

Here is a handy method that gives you a collection of all the jobs submitted to the printer. This method uses the ManagementObjectSearcher and the ManagementObjectCollection classes from the .NET framework. The query “SELECT * FROM Win32_PrintJob” is used to get a collection of the submitted jobs. These jobs are added to a StringCollection and this collection is returned back.

#region GetPrintJobsCollection

/// <summary>
/// Returns the jobs in printer queue
/// </summary>
/// <param name="printerName">Printer Name.</param>
/// <returns>StringCollection</returns>
public StringCollection GetPrintJobsCollection(string printerName)
StringCollection printJobCollection = new StringCollection();
//Query the printer to get the files waiting to print.
string searchQuery = "SELECT * FROM Win32_PrintJob";

ManagementObjectSearcher searchPrintJobs = new ManagementObjectSearcher(searchQuery);
ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();

foreach (ManagementObject prntJob in prntJobCollection)
String jobName = prntJob.Properties["Name"].Value.ToString();

//Job name would be of the format [Printer name], [Job ID]
char[] splitArr = new char[1];
splitArr[0] = Convert.ToChar(",");
string prnName = jobName.Split(splitArr)[0];
string documentName = prntJob.Properties["Document"].Value.ToString();
if (String.Compare(prnName, printerName, true) == 0)
catch (Exception ex)
// Log the exception.
return printJobCollection;

#endregion GetPrintJobsCollection

Monday, May 12, 2008

How to Cancel Printing in C# ?

In the previous blog post we have seen How to print a file/string in C#. In this post we would be looking at how to cancel a print job submitted to the printer. These are some of the common functionalities required in most applications.

For cancellation of the printer job we will be using the System.Management namespace of the .NET framework. Using the ManagementObjectSearcher class we will get a list of all the queued printer jobs. Then using the ManagementObject we will delete the appropriate printer job. Please note that for Cancellation of a printer job, the JobName or JobID is required. Please find below the function that accepts a jobID and then deletes that job from the printer queue. A Boolean true value is returned if successful in deleting the job else a false value is returned.

Remember to Add a Reference to the System.Management .Net assembly.

#region CancelPrintJob

/// <summary>
/// Cancel the print job. This functions accepts the job number.
/// An exception will be thrown if access denied.
/// </summary>
/// <param name="printJobID">int: Job number to cancel printing for.</param>
/// <returns>bool: true if cancel successfull, else false.</returns>
public bool CancelPrintJob(int printJobID)
// Variable declarations.
bool isActionPerformed = false;
string searchQuery;
String jobName;
char[] splitArr;
int prntJobID;
ManagementObjectSearcher searchPrintJobs;
ManagementObjectCollection prntJobCollection;
// Query to get all the queued printer jobs.
searchQuery = "SELECT * FROM Win32_PrintJob";
// Create an object using the above query.
searchPrintJobs = new ManagementObjectSearcher(searchQuery);
// Fire the query to get the collection of the printer jobs.
prntJobCollection = searchPrintJobs.Get();

// Look for the job you want to delete/cancel.
foreach (ManagementObject prntJob in prntJobCollection)
jobName = prntJob.Properties["Name"].Value.ToString();
// Job name would be of the format [Printer name], [Job ID]
splitArr = new char[1];
splitArr[0] = Convert.ToChar(",");
// Get the job ID.
prntJobID = Convert.ToInt32(jobName.Split(splitArr)[1]);
// If the Job Id equals the input job Id, then cancel the job.
if (prntJobID == printJobID)
// Performs a action similar to the cancel
// operation of windows print console
isActionPerformed = true;
return isActionPerformed;
catch (Exception sysException)
// Log the exception.
return false;

#endregion CancelPrintJob

Friday, May 9, 2008

What is hallucination?

A hallucination is the brain's reception of a false sensory input. This essentially means that the person having a hallucination is experiencing an event through one of their senses that is not occurring in the real world. This can be through any of the senses. When auditory hallucinations are examined, the most common are hearing one's own thoughts as if they were being spoken aloud, followed by hearing one's name being called by a voice when alone.

Common hallucinations include:

  • Feeling a crawling sensation on the skin
  • Hearing voices when no one has spoken
  • Seeing patterns, lights, beings, or objects that aren't there

Hallucinations related to smell or taste are rare.

There are many causes of hallucinations, including:

  • Being drunk or high, or coming down from such drugs as marijuana, LSD, cocaine or crack, heroin, and alcohol
  • Fever, especially in children and the elderly
  • Sensory problem, such as blindness or deafness
  • Severe illness, including liver failure, kidney failure, and brain cancer
  • Some psychiatric disorders, such as schizophrenia, psychotic depression, and post-traumatic stress disorder

All of us some time or the other experience hallucination in our life...

How to Format C#, VB Code for Blogger (HTML) ?

Hurrey !!! Here is a fantastic on-line tool that helps you format your C#, VB, XML code for your web site, blogs etc. This tool allows you to format your C#, VB, HTML, XML, T-SQL or MSH (code name Monad) code.
Thanks a ton to ""!

Code Formatter:

Great help to all on-line code contributors....

How to Print File/String in C# ?

A C# developer often requires developing an application or a feature in a product that will print the documents. Sometimes we require printing a single line using the printer, this situation may arise when we want to print some status on a pre-printed form. Here is a code which will print the file or print a string using the default printer installed on the machine.
Comments are added to each line of code so as to make it easy to understand !

#region Reference

using System;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Diagnostics;
// Add a reference to the System.Management dll.
using System.Management;

#endregion Reference

namespace PrinterHelper
/// <summary>
/// Contains common functions for accessing printer
/// </summary>
public class PrinterHelper
#region Member Variables & Method Signatures

// String data to be printed.
static string prnData = string.Empty;

//Add the printer connection for specified pName.
public static extern bool AddPrinterConnection(string pName);

//Set the added printer as default printer.
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Name);

#endregion Member Variables & Method Signatures

#region Public Methods
#region Print File
/// <summary>
/// Sends the file to the printer choosed.
/// </summary>
/// <param name="fileName">Name & path of the file to be printed.</param>
/// <param name="printerPath">The path of printer.</param>
/// <param name="numCopies">The number of copies send to printer.</param>
public bool PrintFile(string fileName, string printerPath, int numCopies)
// Check if the incomming strings are null or empty.
if (string.IsNullOrEmpty(fileName) string.IsNullOrEmpty(printerPath))
return false;

//Instantiate the object of ProcessStartInfo.
Process objProcess = new Process();
// Set the printer.
//Print the file with number of copies sent.
for (int intCount = 0; intCount < numCopies; intCount++)
objProcess.StartInfo.FileName = fileName;
objProcess.StartInfo.Verb = "Print";
objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
objProcess.StartInfo.UseShellExecute = true;
// Return true for success.
return true;
catch (Exception ex)
// Log the exception and return false as failure.
return false;
// Close the process.

#endregion Print File

#region SendStringToPrinter

/// <summary>
/// Sends a string to the printer.
/// </summary>
/// <param name="szString">String to be printed.</param>
/// <returns>Returns true on success, false on failure.</returns>
public bool SendStringToPrinter(string szString)
PrintDocument prnDocument;
string printername;
//Get the default printer name.
prnDocument = new PrintDocument();
printername = Convert.ToString(prnDocument.PrinterSettings.PrinterName);
if (string.IsNullOrEmpty(printername))
throw new Exception("No default printer is set.Printing failed!");
prnData = szString;
prnDocument.PrintPage += new PrintPageEventHandler(prnDoc_PrintPage);
return true;
catch (COMException comException)
//Log the exception
return false;
catch (Exception sysException)
//Log the exception
return false;

/// <summary>
/// Printes the page.
/// </summary>
/// <param name="sender">object : Sender event</param>
/// <param name="e">PrintPageEventArgs</param>
static void prnDoc_PrintPage(object sender, PrintPageEventArgs e)
System.Drawing.Font fnt = new System.Drawing.Font(System.Drawing.FontFamily.GenericSerif, 10);
e.Graphics.DrawString(prnData, fnt, System.Drawing.Brushes.Black, 0, 0);

#endregion SendStringToPrinter

#endregion Public Methods
Your comments are always welcome !