Tuesday, March 13, 2007


"beforeFieldInit" is a special flag marked by compiler to the types which doesn't have static constructor.
This special flag tells "calling a static method does not force the system to initialize the type." Means that calling a static method does not make sure the static variables are initialized in the type.
public class ResourceClass
private static StreamWriter sw = new StreamWriter();
public static StreamWriter GetInstance()
return sw;
In the above type it is not guranteed that when you call GetInstance the static variable "sw" would be created. Because of the reason the class is marked as "beforeFieldInit".
public class ResourceClass
private static StreamWriter sw = new StreamWriter();
static ResourceClass() { };

public static StreamWriter GetInstance()
return sw;


In the above type it is guranteed that when you call GetInstance the static variable "sw" would be created. Because of the reason the class contains "static constructor".
Properties of static constructor
  • Static constructors are not inherited, and cannot be called directly.
The exact timing of static constructor execution is implementation-dependent, but is subject to the following rules:
  1. The static constructor for a class executes before any instance of the class is created.
  2. The static constructor for a class executes before any of the static members for the class are referenced.
  3. The static constructor for a class executes after the static field initializers (if any) for the class. The static constructor for a class executes, at most, one time during a single program instantiation.
  4. The order of execution between two static constructors of two different classes is not specified.
But CLI does insist that all of the field variables will be initialized as soon as one of the static fields is accessed. So if we are depending on some side effects based on static variable initialization, then we may be waiting for a long time that to happen.

Thursday, December 28, 2006

Validate Windows Domain Account in C#

In C# we can validate windows domain account using following code snippet.

public class WinAPI{
// Use NTLM security provider to check
public const int LOGON32_PROVIDER_DEFAULT = 0x0;
// To validate the account
public const int LOGON32_LOGON_NETWORK = 0x3;

// API declaration for validating user credentials
[DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out int phToken);
//API to close the credential token
[DllImport("kernel32", EntryPoint="CloseHandle")] public static extern long CloseHandle (long hObject);

int hToken=2;
bool ret = WinAPI.LogonUser(strUserName,strDomain,strPwd, WinAPI.LOGON32_LOGON_NETWORK ,
out hToken);

MessageBox.Show (" Valid Windows domain User ");
WinAPI.CloseHandle (hToken);
MessageBox.Show (" Not an valid Windows domain User ");


We call LogonUser Win32 API to validate the user credentials. The class WinAPI declares the required Win32 API's and the constants used.

LogonUser takes username, password and password as plain text and validates the user name against the domain with the given password, if the user name is correct then it returns a handle to the user token in hToken out parameter which can be used by the user to Impersonate or create process using his account. If this is not used then hToken should be closed using CloseHandle Win32 API.

Satellite Assemblies

Assemblies which contains only resources (no executable code) are called as Satellite assemblies. These are created with the help of al.exe (Assembly Linker). The .resources files are compiled using al.exe to create assemblies, these are generally used for localizing the applications.

Satellite assemblies are created for different cultures and at run time the localization will select appropriate assembly based on current resource.
For more info

Wednesday, December 27, 2006

Windows environment variables

Windows has two kinds of environment variables
1) User specific environment variables
2) System wide environment variables

User specific environment variables are available only to the user for which it is created and System wide are available to all the users.

These environment variables are stored in the following registry location

You can modify user environment variables by editing the following Registry key: HKEY_CURRENT_USER \Environment

You can modify system environment variables by editing the following Registry key: HKEY_LOCAL_MACHINE \SYSTEM \CurrentControlSet \Control \Session Manager \Environment

Note: If you modify the environment variables it won't reflect immediately till you log-off and log-in again.

Changes to environment variable

To effect the changes to the environment variable immediately without log off, broadcast the WM_SETTINGCHANGE message to all windows in the system, so the system will will peform read from registry again to update the environment variable.

C# code to propagate environment variable changes

/* Declare the Win32 API for propagating the environment variable */
[DllImport("user32.dll",CharSet=CharSet.Auto, SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)]
public static extern bool SendMessageTimeout(
IntPtr hWnd,
int Msg,
int wParam,
string lParam,
int fuFlags,
int uTimeout,
int lpdwResult
/* Constant to broadcast message to all windows */
public const int HWND_BROADCAST = 0xffff;
public const int WM_SETTINGCHANGE = 0x001A;
public const int SMTO_NORMAL = 0x0000;
public const int SMTO_BLOCK = 0x0001;
public const int SMTO_ABORTIFHUNG = 0x0002;
public const int SMTO_NOTIMEOUTIFNOTHUNG = 0x0008;

/* Call the API passing the last parameter as out parameter */
int result,retun_value;
return_value = SendMessageTimeout( (System.IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment",SMTO_BLOCKSMTO_ABORTIFHUNG SMTO_NOTIMEOUTIFNOTHUNG, SomeTimeoutValue, out result);

MessageBox.Show(" Broadcast to all window successfull! ");
MessageBox.Show(" Broadcast to all window failed! ");

For more information check out the following links



Wednesday, November 08, 2006

Get Domain name of the system

System Name or NetBIOS Name

//Retrieve the NetBIOS name.


DNS name or Fully Qualified name

//It retrieves the domain name of the current user


//Retrieve the DNS name of the computer.

//WMI Script to retireve only domain name of current computer
ManagementPath path = new ManagementPath();
path.Server = System.Net.Dns.GetHostName();
path.NamespacePath = @"root\CIMV2";
path.RelativePath = "Win32_ComputerSystem.Name='" + path.Server + "'";
System.Management.ManagementObject o = new ManagementObject(path);

//Read domain and host name from windows registry in VB.NET
Dim rk As RegistryKey = Registry.LocalMachine
Dim rkSub As RegistryKey
rkSub = rk.OpenSubKey("SYSTEM\CurrentControlSet\Services\Tcpip\Parameters")
If rkSub Is Nothing Then
MessageBox.Show("Program error, invalid registry key", "Error", MessageBoxButtons.OK,MessageBoxIcon.Error)
Exit Sub
End If
mDomain = CType(rkSub.GetValue("Domain"), String)
mHostName = CType(rkSub.GetValue("HostName"), String)
If mDomain.Length > 0 Then
mFullHostName = mHostName & "." & mDomain
mFullHostName = mHostName
End If

Monday, November 06, 2006

T-SQL Script to kill users of DB

Kill Users of DB

DECLARE @SPID smallint
DECLARE @Loginame varchar(32)

CREATE TABLE #usrkill ( spid smallint,
ecid int,
status varchar(32),
loginame varchar(32),
hostname varchar(32),
blk char(8),
dbname varchar(32),
cmd varchar(255)

INSERT #usrkill exec sp_who

SELECT SPID, Loginame from #usrkill where UPPER(dbname) IN ('MyDB1','MyDB2')
FETCH NEXT FROM KILL_USERS into @spid, @Loginame
IF @@FETCH_STATUS <> 0 GOTO Last_User_Record
Print 'Killing User: ' + @Loginame
select @KILLSTATE = 'KILL ' + CONVERT(char, @spid)
FETCH NEXT FROM KILL_USERS into @spid, @Loginame

DROP TABLE #usrkill

The above T-SQL statements will all kill the users of the DB MyDB1 and MyDB2. It uses the sp_who proceudre which returns all the users of DB.

T-SQL Script to find n/w port of SQL Server

T-SQL Script

set nocount on
DECLARE @test varchar(20), @key varchar(100)
if charindex('\',@@servername,0) <>0
set @key = 'SOFTWARE\MICROSOFT\Microsoft SQL Server\'
set @key = 'SOFTWARE\MICROSOFT\MSSQLServer\MSSQLServer \Supersocketnetlib\TCP'

EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE',
@key=@key,@value_name='Tcpport',@value=@test OUTPUT

SELECT 'Server Name: '+@@servername + ' Port Number:'+convert(varchar(10),@test)

The above T-SQL reads the SQL Server Port number from the registry for the current SQL Server instance.

T-SQL to list all the user tables and row counts in a DB

SELECT distinct B.[name] as [Table Name], max(A.rowcnt) as [Row Count]FROM sysindexes AINNER JOIN sysobjects BON A.id = B.idWHERE B.type = 'U'GROUP BY B.[name]ORDER BY B.[name]

The above query returns all the user tables and the count of all rows in the current DB.

Saturday, July 22, 2006

Compare tables in two DB using C#

Compare tables of two DB

It is not possible to compare two DB easily, there are tools with which we can compare, but the tools costly, the following simple C# program will help to find whether there is any difference in tables in DB, and it won’t compare data to find whether it is same but compares the table in the DB. In C# we can get the list of all table names from the SQL Server DB easily, the following code will help us in getting the table names from two databases and help us to compare for the tables created in the DB.

{ int recPos=0;
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
object[] objArrRestrict;
objArrRestrict = new object[] {null, null, null, "TABLE"};
schemaTbl = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,objArrRestrict);

OleDbConnection con1 = new OleDbConnection(connectionString);
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = con1;
object[] objArrRestrict1;
objArrRestrict1 = new object[] {null, null, null, "TABLE"};
schemaTbl1 = con1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,objArrRestrict1);

if(schemaTbl.Rows.Count!= schemaTbl1.Rows.Count)
MessageBox.Show(“Both DB don’t have equal number of tables! “);
DataView schema1TblView = schemaTbl.DefaultView;
schema1TblView.Sort = "TABLE_NAME";
foreach (DataRow row in schemaTbl1.Rows)
recPos = schema1TblView.Find(tblName);
MessageBox(“DB’s are different”);
catch (Exception ex){ MessageBox.Show("Error" + ex.Message);

The basic idea here is get table names from both the tables, create view for the 1st table names list, loop through the 2nd table names list try to find that in the first list if it is not there then just show message box saying that “DB are different”. Also first compare whether the table count in both of the DB are equal before comparing the each table names.


GetOleDbSchemaTable method of OleDbConnection object will help us in getting the table names list from DB. The table view will help us to locate the name in the list, so we create a view in one list and loop through another list to check for all table names. If the recPos==-1 means that the name we are searching on the 1st list is not available so we can confirm that the table is not available in the DB.

Get table list in DB using C# and ADO.NET

How to get list of all tables from SQL Server DB in C#?

In C# we can get the list of all table names from the SQL Server DB easily, the following code will help us in getting the table names and it also load all the table data to the dataset.


If we use the following code we need not know all the table names to get the data from the DB.

OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
object[] objArrRestrict;
objArrRestrict = new object[] {null, null, null, "TABLE"};
schemaTbl = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,objArrRestrict);
foreach (DataRow row in schemaTbl.Rows)
cmd.CommandText = "select * from ["+row["TABLE_NAME"]+"]";
da.SelectCommand = cmd;
da.Fill(ds, row["TABLE_NAME"].ToString());
catch (SqlException ex)
MessageBox.Show("Error" + ex.Message);

The above code will load the dataset “ds” with the data in all the tables in DB given in the connection string.

The method "GetOleDbSchemaTable" does the magic here, it helps us to retrieve all the tables names.


The below code snipper will also help us to retrieve set of table names.
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "select * from sysobjects where type='U'";
ds = cmd.ExecuteQuery();
catch (SqlException ex)
MessageBox.Show("Error" + ex.Message);

This code makes use of the SQL server system table to fetch all the user tables.

Option#1 is used to retrieve Schema information of any OLEDB data source. Option #2 is restricted to SQL Server because othee RDBMS don't have system table which lists the tables. Also note that SqlConnection object don't have the method "GetOleDbSchemaTable" to retrieve schema information.

Monday, June 12, 2006

Get the application exe name

The following are the different ways we can get the current exe name through code.

Method 1

This returns the exe name.

Method 2

This returns the path with exe name

Method 3

This returns path with the exe name.

Determining the Internet Explorer Version

To date, Microsoft has released a number of versions of the Internet Explorer browser.

Firstly, the version numbers used internally by Microsoft. Furthermore, the version numbers do not increment in the same manner as that in the product name. You will have to use a lookup table to match the version numbers against the product names.
For the version look up table go to website

Determining the Internet Explorer Version from the Registry

We can get the full version string from the Registry using the Version string value.
The version number of the installed Internet Explorer can be found under the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer

For Internet Explorer 4.0 and later, the Build value is a string that contains a five-character value, followed by a period and four more characters, in the following format:
E.g. the Build value for Internet Explorer 5 is "52014.0216."

In addition, it adds a Version string value under the same key, in the following format.
E.g. the Version value for Internet Explorer 5 is "5.00.2014.0216".

If none of these values is in the registry, Internet Explorer is not installed properly or at all.

Determining the Internet Explorer Version from Shdocvw.dll

You may use the version number of the Shdocvw.dll (Shell Document Object and Control Library) file to determine the version of Internet Explorer installed. However, note that this approach can only be used on Internet Explorer 3.0 and later since this file does not exist in previous versions of Internet Explorer.

Also, do take note that the version number of this dll is not the same as that stored in the registry. (Although the later versions are starting to have the same numbers.) A table listing the version numbers of the Shdocvw.dll file and the corresponding versions of Internet Explorer may be found <http://www.codeproject.com/shell/detectie.asp>

The Shdocvw.dll file is installed in the Windows\System folder in Windows 95/98, and in the Winnt\System32 folder in Windows NT/2000. If the Shdocvw.dll file does not exist,
Internet Explorer 3.0 or later is not installed properly or at all.

What is Verbatim string?

In C# we can escape the characters without using Escape character, for example we can use like @"C:\temp" instead of "C:\\temp". These strings which starts with @" and ends with matching end quotes are called as Verbatim String literals.

They don't need escape characters. Strings written using the verbatim string syntax can span multiple lines, and whitespace is preserved.

The only character that needs escaping is the double-quote character, the escape sequence for which is two double-quotes together.

For instance, suppose that you want to set the variable 'text' to the following value:
MS word "shorcut" to copy

Using the verbatim string syntax, the command would look like this:
string text = @"MS word ""shortcut"" to copy"

Get Windows Login name

We can get the windows login in 2 ways,

1) Using Environment

str = System.Environment.UserDomainName + "\" + System.Environment.UserNamestr;
str will Contain the Login name with the domain name.

2) Using the System.Security

Using System.Security.Principal;
WindowsPrincipal wp = New WindowsPrincipal(WindowsIdentity.GetCurrent());
MessageBox.Show("Your login id:" + wp.Identity.Name);

3) Using SystemInformation


.NET and Operating System Core Processes

Microsoft recommends not to use .NET and other high level runtime loadable components in Core Operating System processes like Winlogon.exe.,

They say the behaviour is undefined and recommends only C and Win32 API's.

For More information look in to the following website


Changing the Project version from VS.NET 2003 to VS.NET 2002

When we open our VS.NET 2002 project file in VS.NET 2003 then the IDE will ask for converting the project from VS.NET 2002 to VS.NET 2003 solution. But after converting the solution to VS.NET 2003 can we convert back to VS.NET 2002?

Yes it is possible. The difference between the project is only few configuration tags value and different version identifiers.

Step 1:
Modify the Solution Files Change the first line of the solution files from “Microsoft Visual Studio Solution File, Format Version 8.00” to “Microsoft Visual Studio Solution File, Format Version 7.00”

Step 2: Modify the Project Files.

ProjectType = "Local"
ProductVersion = "7.10.3707"
SchemaVersion = "2.0"
ProjectGuid = "{20502969-7071-4065-BDB5-09EDB3C31E3C}">

Change the above lines to the following lines:
ProjectType = "Local"
ProductVersion = "7.0.9466"
SchemaVersion = "1.0"
ProjectGuid = "{20502969-7071-4065-BDB5-09EDB3C31E3C}">

Beaware of the ProjectGuid, it should be same with actual ones.

Determine whether service packs installed on the .NET Framework

With the .NET Framework 1.1, a new registry hive has been created specifically to make it easier to find the service pack level.

Start Registry Editor, and then locate the following registry key:

Key Name: HKEY_LOCAL_MACHINE\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322

Value: SP

Data type: REG_DWORD

The data in the SP value tells you which service pack is installed for the .NET Framework 1.1. For example, if the value of SP is 0, no service pack is installed for the .NET Framework 1.1. If the value is 1, Service Pack 1 for the .NET Framework 1.1 is installed.Note that this method cannot be used to detect if any hotfixes are installed for the .NET Framework 1.1.

How to find version of SQL Server running?

To determine which version of SQL Server 2000 is running, connect to SQL Server 2000 by using Query Analyzer, and then run the following code: SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')The results are:

The product version (for example, 8.00.534).
The product level (for example, "RTM" or "SP2").
The edition (for example, "Standard Edition").

For example, the result looks similar to:8.00.534 RTM Standard EditionThe following table lists the Sqlservr.exe version number:

Release                  Sqlservr.exe

RTM 2000.80.194.0
SQL Server 2000 SP1 2000.80.384.0
SQL Server 2000 SP2 2000.80.534.0
SQL Server 2000 SP3 2000.80.760.0
SQL Server 2000 SP3a 2000.80.760.0
SQL Server 2000 SP4 2000.8.00.2039

sp_server_info gives set of SQL Server configuration information. Look for the attribute "DBMS_VER" to find the release.

Another way of finding the version is using "@@VERSION", its a system level variable which stores the versio.

Determining the Service Pack Installed in Office

To find out what version of Microsoft Office Service Pack is currently installed, click on Outlook (for example) Help menu and About Microsoft Outlook. The service pack version is indicated by the word ‘SP’ next to the Outlook version number.

For example,
Microsoft Outlook 2000 ( SP-1a is service pack 1a
Microsoft Outlook 2000 (9.23.1285.131) SP-2 is service pack 2
Microsoft Outlook 2002 (10.2340.4560.21) SR-1 is Office security update and not a service pack

Determining the Service Pack Installed in Windows

Service Packs
1. Service packs are the means by which Microsoft Windows product updates are distributed.
2. Service packs keep the product current, extend, and update your computer's functionality.
3. Service packs include updates, system administration tools, drivers, and additional components.
4. All are conveniently bundled for easy downloading.
5. Service packs are cumulative - each new service pack contains all the fixes in previous service packs, as well as any new fixes.

Determining the Service Pack Installed

There are two methods to determine which Microsoft Windows Service Pack is installed on an system. Choose the method best suited for you.

Method One
From a command window or from the Run dialog box, type winver and click OK.

Method Two
From a command window or from the Run dialog box, type winmsd and click OK.

How to Throw SqlException in C# manually?

It is not possible to throw SqlException maually in C# because SqlException class doesn't have any public constructor or even protected cosntructor.

But we can do that indirectly using the RAISEERROR function in SQLServer

For Example

SqlCommand cmd =
new SqlCommand("raiserror('Manual SQL exception', 16, 1)",DBConn);
}catch (SqlException ex)
string msg = ex.Message; // msg = "Manual SQL exception"

The above code will throw an SqlExpcetion but the problem here is it takes a round trip time to database for executing the RAISEERROR function on DB Server.

Late Binding in C# and VB.NET

What is Late Binding?

Binding is the process of locating the declaration (that is, the implementation) that corresponds to a uniquely specified type. When this process occurs at run time rather than at compile time, it is called late binding.

Late binding in C# and VB.NET

Each .NET program assembly have Metadata which allows the user to dynamically load an assembly and execute methods of it, this is called Late Binding.

This Late Binding requires the use of Reflection in C# and VB.NET. In VB.NET it is optional because we have implicit late binding which allows us to have Late Binding without the use of Refelection.


Now lets see, by example, how can we load and invoke assembly dynamically. We require two programs here.

MyAssembly.cs (This will contain simple class with few methods)
LoadInvoke.cs (This is the main assembly loader and invoke program which will load and invoke MyAssembly.dll (i.e. Compiled MyAssembly.cs file)

Listing 1: MyAssembly.cs

Listing 1: MyAssembly.cs

using System;

public class MyAssembly
public void PrintHello()
Console.WriteLine("Hello World");

Listing 2: LoadInvoke.cs

1 using System;
2 using System.Reflection;
4 public class LoadInvoke
5 {
6 public static void Main(string CmdArgs[])
7 {
8 Assembly a = Assembly.LoadFrom(CmdArgs[0]);
10 Types[] mytypes = a.GetTypes();
12 BindingFlags flags = (BindingFlags.NonPublic
13 BindingFlags.Public
14 BindingFlags.Static
15 BindingFlags.Instance)
18 foreach(Type t in mytypes)
19 {
20 MethodInfo[] mi = t.GetMethods(flags);
22 Object obj = Activator.CreateInstance(t);
24 foreach(m in mi)
25 {
26 m.Invoke(obj, null);
27 }
28 }
29 }
30 }

Compile Listing 1 program (MyAssembly.cs) at command prompt:

Csc /t:library MyAssembly.cs

This makes MyAssembly.dll file.

Then you compile Listing 2 program (LoadInvoke.cs) at your command prompt:

Csc LoadInvoke.cs

This makes LoadInvoke.exe

Run LoadInvoke.exe with command line argument as MyAssembly.dll
e.g. C:\>LoadInvoke Myassembly.dll

LoadInvoke loads MyAssembly.dll and executes (invoke) PrintHello method. The console window output is shown below

Hello World

Lets understand LoadInvoke program step by step

At line number 8 we have created an instance of Assembly object as a where MyAssembly.dll is loaded by Assembly.LoadFrom method, the assembly name to be loaded we got from the command line arguments. This method accepts one string argument and that is the name and path of assembly (i.e. MyAssembly.dll). So the object a is pointing to the loaded assembly MyAssembly.dll.

Assembly can have one or more classes in it (in our case it is MyAssembly public class), which we are obtaining from Assembly object’s instance method GetTypes(). This method returns array of Type object, which is saved in mytypes array.

Line number 12 – 16 gives the BindingFlags enumerations. Here is the explnation of each enumeration we used.

BindingFlags.NonPublic -> Specifies that non-public members are to be included in the search.
BindingFlags.Public -> Specifies that public members are to be included in the search.
BindingFlags.Static -> Specifies that static members are to be included in the search.
BindingFlags.Instance -> Specifies that instance members are to be included in the search.

Line number 18-28 shows the foreach loop browsing through each type in mytypes. Each type (i.e. class) can have one or more

methods in it. At line 20 we are executing t.GetMethods(flags) which returns the method information array and saved in array mi of type System.Reflection.MethodInfo

At Line 22 the instance of type t (i.e. MyAssembly class) is created using Activator.CreateInstance method. Here the instance is referenced with obj.

Now, as we have instance of class MyAssembly and the Method to execute also, so it is very easy to execute the instance method PrintHello. Here is the reference information:

obj -> refers to instance of MyAssembly class

mi -> MethodInfo array, contains all methods info from type t

m -> MethodInfo of method MyMethod1 available in class MyAssembly

Now, to execute the method PrintHello we need to use the Invoke method of MethodInfo m. See line number 26 m.Invoke(obj, null). It takes two parameters, first parameter should be type instance (instance variable obj) and second parameter is

object array of method parameters. In case your method contains parameters then you need to create object array of parameters. In our case MyMethod1 does not have any parameter, so we are passing null as a parameter here.

Calling COM Components from .NET using Refelection

In this example we are going to call a Excel application by loading COM component using .NET Late Binding

1 //Variable

2 Type excel;
3 object[] parameter= new object[1];
4 object excelObject;
5 try
6 {
7 //Get the excel object
8 excel = Type.GetTypeFromProgID("Excel.Application");
9 //Create instance of excel
10 excelObject = Activator.CreateInstance(excel);
11 //Set the parameter whic u want to set
12 parameter[0] = true;
13 //Set the Visible property
14 excel.InvokeMember("Visible", BindingFlags.SetProperty,

null, excelObject, parameter);
15 }
16 catch(Exception e)
17 {
18 Console.WriteLine("Error Stack {0} ", e.Message) ;
19 }
20 finally
21 {
22 //When this object is destroyed the Excel application

will be closed
23 //So Sleep for sometime and see the excel application
24 Thread.Sleep(5000);
25 //Relaese the object
26 //GC.RunFinalizers()
27 }

In line 8 we are using Type class method to get the COM object like the one which we have used is GetTypeFromProgID("Application") , this method get the COM ID from the System Registry.

In line 10 we are using the STATIC class member of Activator.CreateInstance() we create a new instance of the COM object.

In line 11 to invoke the methods,function and Properties of the COM object we have to use the InvokeMethod() of the Type object with proper settings , this methos takes many arguments of which the inportant one is the methods type ex property
(get or set)in example we have used a set property for Excel.Visible to make the Excel application visible.

Member Selection and Argument Coercion

The following example shows the three possible combinations of argument coercion (type conversion) and member selection.

public class CustomBinderDriver

public static void Main (string[] arguments)
Type t = typeof (CustomBinderDriver);
CustomBinder binder = new CustomBinder();
BindingFlags flags;

flags = BindingFlags.InvokeMethodBindingFlags.Instance

// Case 1. Neither argument coercion nor member

selection is needed.
args = new Object[] {};
t.InvokeMember ("PrintBob", flags, binder, null, args);

// Case 2. Only member selection is needed.
args = new Object[] {42};
t.InvokeMember ("PrintValue", flags, binder, null, args);

// Case 3. Only argument coercion is needed.
args = new Object[] {"5.5"};
t.InvokeMember ("PrintNumber", flags, binder, null, args);

public static void PrintBob ()
Console.WriteLine ("PrintBob");

public static void PrintValue (long value)
Console.WriteLine ("PrintValue ({0})", value);

public static void PrintValue (String value)
Console.WriteLine ("PrintValue\"{0}\")", value);

public static void PrintNumber (double value)
Console.WriteLine ("PrintNumber ({0})", value);

In Case 1, no argument coercion or member selection is needed, because this is a direct call to non-overloaded function.
In Case 2, only member selection is needed, because the function we are calling is overloaded PrintValue(long) and PrintValue(string).
In Case 3, only argument coercion is needed, because the argument the function PrintNumber takes is double and the argument we are passing is string.

When to use?

1) In some applications, we don't know which assembly to load during compile time, so we ask the user to enter the assembly name and type during run time and the application can load assembly.

2) Using this, you can load an assembly at run time, obtain information about types in that assembly, specify the type that you want, and then invoke methods or access fields or properties on that type.

3) This technique is useful if you do not know an object's type at compile time, such as when the object type is dependent on user input.

4) Using this, we can also call the COM components.

Implicit Late binding

Visual Basic .NET allows you to use implicit late binding in your code; the Visual Basic
compiler calls a helper method that uses reflection to obtain the object type. The
arguments passed to the helper method cause the appropriate method to be invoked
at run time. These arguments are the instance (an object) on which to invoke the method,
the name of the invoked method (a string), and the arguments passed to the invoked
method (an array of objects).

An object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object. For example, the following code fragment declares an object variable to hold an object returned by the CreateObject function:

1'To use this example, you need Microsoft Excel
2 Option Strict Off 
' Option Strict Off allows late binding.
3 Sub TestLateBinding()
4 Dim xlApp As Object
5 Dim xlBook As Object
6 Dim xlSheet As Object
7 xlApp = CreateObject("Excel.Application")
8 'Late bind an instance of an Excel workbook.
9 xlBook = xlApp.Workbooks.Add
10 'Late bind an instance of an Excel worksheet.
11 xlSheet = xlBook.Worksheets(1)
12 xlSheet.Activate()
13 xlSheet.Application.Visible = True

' Show the application.
14 ' Place some text in the second row of the sheet.
15 xlSheet.Cells(2, 2) = "This is column B row 2"
16 End Sub

In the lines 4-6, we create an generiv Object.
In the lines 7-15, we call the methods to activate the Excel application and it is done
through Implicit Late binding because only at runtime the exact type of object is known.

Disadvantages of Using Late binding

1) Early Binding allow the compiler to make important optimizations that yield more
efficient applications.
2) Early-bound objects are significantly faster than late-bound objects.
3) It makes your code easier to read and maintain by stating exactly what kind of
objects are being used.
4) It enables useful features such as automatic code completion and Dynamic Help
because the Visual Studio .NET integrated development environment (IDE) can
determine exactly what type of object you are working with as you edit the code.
5) Early binding reduces the number and severity of run-time errors because it

Rename SQL Server DB through SP

sp_renamedb Changes the name of a database.

Syntaxsp_renamedb [ @dbname = ] 'old_name' , [ @newname = ] 'new_name'
Arguments[@dbname =] 'old_name'

Is the current name of the database. old_name is sysname, with no default.
[@newname =] 'new_name'

Is the new name of the database. new_name must follow the rules for identifiers. new_name is sysname, with no default.

Return Code Values 0 (success) or a nonzero number (failure)

PermissionsOnly members of the sysadmin and dbcreator fixed server roles can execute sp_renamedb.

EXEC sp_renamedb 'user', 'useraccounts'

This example changes the name of the user database to useraccounts.

Windows XP Look and Feel in C# Windows Forms Application

The look and feel of Windows C# application can be changed to Windows XP style, with a XML manifest file. The file must be kept in the same directory with the same name of the executable with ".manifest" extension. For example if "User.exe" is executable name then the manifest file name is "user.exe.manifest".

The file must contain the dependancy attribute and under this attribute we must set the identity of the component our application is dependenting, in this case the new "Microsoft Windows Common-Controls" version 6.0. The following example shows the appearance of this application manifest file.

1 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>

2 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestversion="1.0">

3 <assemblyidentity name="MyVisualStyleApp" type="win32" processorarchitecture="X86" version="">

4 <description>Your app description here</descriptio>>

5 <dependency>

6 <dependentassembly>

7 <assemblyidentity language="*" name="Microsoft.Windows.Common-Controls" type="win32" processorarchitecture="X86" version="" publickeytoken="6595b64144ccf1df">

8 </dependentassembly>

9 </dependency>

10 </assembly>


The line 3 says the version of the application, the processor architecture for which the application is developed, name of the application and type of the application.
The line 7 says the Type of the dependency component, such as Win32, name of the component, version of the component, processor that the component is designed for, Key token used with this component and Language of the component.

How this look and feel? All the functions necessary to draw a Windows XP style button is in "UxTheme.dll" under the system directory. Before draw your custom control you must take care of one thing, the "UxTheme.dll" is found only in Windows XP actually, this means if you try running an application on the Windows 98 for example, your application will crash.

How can I take care of this? Verifying the Windows version and ID. The following lines of code show you how to do that.

PlatformID platformId = Environment.OSVersion.Platform; Version version = Environment.OSVersion.Version; Version targetVersion = new Version("5.1.2600.0"); if ((version > = targetVersion) && (platformId == PlatformID.Win32NT))

There's another thing, the user can disable Visual Styles under Windows XP and your application could crash again. And now, how can I handle this? Verifying if Visual Styles are enabled or disabled with the following piece of code.
if (NativeMethods.IsThemeActive() == 1)

The "IsThemeActive" method of the "UxTheme.dll" library will return the value 1 if Visual Styles are enabled or 0 if not.To apply the theme call the "OpenThemeData" method this way.

hTheme = NativeMethods.OpenThemeData(this.Handle, "Button");

"hTheme" holds the handle returned from the "OpenThemeData" method containing the Visual Style (if exists). The following methods could be used to draw Windows XP style controls.
- DrawThemeBackground- DrawThemeText- DrawThemeParentBackgroundAnd don't forget to close the theme handle when you exit the program! You can do it by using "CloseThemeData" method.

Button Look? If we apply this using manifest file, the button visual is not changed so how to change the button, for changing the button visual set the "FlatStyle" property of the button for "System".

SQL Server Login Error


"Login failed for user 'sa'. Reason: Not associated with a trusted SQL Server Server Connection."

If tyou get the above error then try

osql /U sa /P passwd /S servname

If the execution give the same error then we can conclude that theAuthentication is not changed to SQL Server and Windows mode.
Open the enterprise manager --> navigate to your server --> right click on the left pane --> choose properties --> select the security taband change the "Windows only" to "SQL Server and Windows".

STOP and START MSSQL Server service

Note:By default the 'sa' password is blank. Change it quickly. Go to the securityfolder (Enterprise manager) of your server and change the sa password.Include this password in your connection string.

Installation Process error with InstallShield

Detect and End Previously Running Installation Processes
DescriptionInstallation issues may arise if the same installation has two instances running simultaneously. This may cause conflict between the two instances of the installation engine.

ERROR The error like "Another installation is running close to continue installation" and "Script runtime initialization failed" can be solved by the following procedure.

Detect if another installation process is running
Press Ctrl + Alt + Del and select Task Manager. Go to the Processes tab.
Check the running processes for any or some of these names:

End previously running installation processesFollow these steps for any of the above processes that are found running on the system.Select each process. Select End Process.

How to declare global Variables in VB.NET and C#?

In VB.NET we have module to declare global variable, which can be accessed across all the forms

Module Module1
Public moduleinteger As Integer
End Module

In C#.NET we don't have any Module to declare global variables, so in C# we can declare a public class with public static variable which can be across all the forms

namespace Module{
public class Module1
public static int moduleinteger;

access like Module1.moduleinteger

Mem Usage and VM Size in Windows TASKBAR

Windows TASK BAR has lot options that we can use to explore information about the process.

we can view information like Imagename, User name, Mem Usage, VM Size, PID, CPU Time etc.,

The terminology may seem odd, but it’s just developer-speak. ‘Working Set’ is equivalent to ‘Mem Usage’ in the XP Task Manager and it refers to the total amount of physical memory allocated to this process. This sounds straightforward, but keep in mind that processes can share RAM, so some memory pages may be included in the total more than once.

‘VM Size’ in the XP Task Manager, reports memory allocated exclusively to this process, which may therefore be swapped out to your paging file. Some, all or none of that figure may be in the paging file right now, but there’s no way to tell. If you’re simply looking for a memory leak, then the distinction doesn’t really matter. Just look for a figure that increases over time and you’ve found the problem.

Occasionally, a process may eventually clean up after itself, but this may take a very long time. In situations like this, you should take a look for the Peak memory values to highlight the maximum amount of RAM that the process has ever used. This is one situation where the Windows 2000/XP Task Manager may be a better choice for monitoring than Process Explorer.

Static VS Dynamic SQL

Which is best static or Dynamic? Surely Static because of the reason below.

In order that a SQL satement can be executed, it has to be parsed (checked for syntactic and semantic correctness) and the execution plan has to be calculated. All this costs computational resources.To save on these costs, the Oracle instance maintains a system-wide LRU cache (aka the shared cursor cache) - exposed via v$sqlarea - of previously encountered SQL statements and appropriate derived information so that when the next SQL statement is submitted for parsing it is checked for match against the cached ones. (The definition of the criterea for a match is beyond the scope of this tutorial. Roughly speaking, the current statement must be both textually identical to its match candidate, famously to the extent of whitespace and upper/lower case identity, and the types of the bind variables must match.) When the current statement is matched, the stored derived information (parse tree, execution plan, etc) is reused and computational cost is saved.

The execution plan of the sql statements are chached only if it is static if it is dynamic it won't use the already stored execution plan, so it incurs additional cost of parsing, preparing execution plan and then running it.
But why Dynamic SQL?We use Dynamice SQL at some places we dont' know the where clause till runtime. So we go for dynamic sql. In Oracle Dynamic SQL is executed using "EXECUTE IMMEDIATE" of DBMS_SQL pacakge.

For more information on static and dynamic sql with Cursors visit the following link.

ShowDesktop shortcut

How to recreate the Show Desktop Shortcut?

If your Show Desktop item has been deleted, you can re-create the script quite easily. Or perhaps you'd like to create a Show Desktop item in a different folder.
Simply follow these steps:

Use Notepad to create a text file with the following contents:

Save the file as Show Desktop.scf.
(You can name it something else if you prefer, but make sure you use the .scf file extension.)

You can save the file where you want, and then create a shortcut on your Quick Launch toolbar.

Dynamic Properties .NET

What is Dynamic Proprty?
Dynamic properties allow you to configure your application so that some or all of its property values are stored in an external configuration file rather than in the application's compiled code. By providing administrators with the means to update property values that may need to change over time, this can reduce the total cost of maintaining an application after the application has been deployed.
For example, suppose you are building an application that uses a test database during the development process, and you need to switch it to a production database when you deploy it.

How to read from configuration file in C#?
this.sqlConnection1.ConnectionString = ((string)( System.Configuration.ConfigurationSettings.AppSettings.GetValues("SqlConnection1.ConnectionString"))));

How to add in Config file?
In the configuration file, the value for this property would be stored via XML, using the key indicated in the form's code:

Where I can find more information? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vboriintroductiontoapplicationsettingstorage.asp

Interacting with NT Service via Console

What is Windows Service?
Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. This makes services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer.

How to interact with Windows Service or NT Service?

Normally the interaction to the service done through the service console, which can be started by giving "services.msc" in the RUN option on windows.


We can also do the same set of operations like starting, stoping, creating, pausing etc., through console using "sc" command.
SC is a command line program used for communicating with theNT Service Controller and services.


Open the command prompt and type "sc" you can see list of options you can use with sc command.

sc start "service name" --> Starts a service given by "service name"
sc pause "service name" --> Sends a PAUSE control request to a service given by "service name"
sc continue "service name" --> Sends a CONTINUE control request to a service given by "service name"
sc stop "service name" --> Sends a STOP request to a service given by "service name"
sc delete "service name" --> Deletes the service given by "service name"

When it is useful?
1) When your associated service executable is no more available or it is giving error, then uninstalling service is a problem, so we can use "sc" command to delete the service manually from the console.
2) When the service is not responding with uninstalling, we can delete through the console.
3) We can start the service from console may through the batch (.bat) file.
4) To query the status of the service from the console

What else?

We can use the "sc" command to get the status of particular service, or enumerates the status for types of services.
If the query command is followed by a service name, the status for that service is returned. Further options do not apply in this case. If the query command is followed by nothing or one of the options listed below, the services are enumerated.
type= Type of services to enumerate (driver, service, all)(default = service)

state= State of services to enumerate (inactive, all)(default = active)

bufsize= The size (in bytes) of the enumeration buffer (default = 4096)


sc query - Enumerates status for active services & drivers

sc query type= driver - Enumerates only active drivers

sc query type= service - Enumerates only Win32 services

sc query state= all - Enumerates all services & drivers

sc query type= driver group= NDIS - Enumerates all NDIS drivers

Where? To get more information about this go to console and type "sc"

Deleting service --> "http://www.tweakxp.com/tweak1976.aspx"

Searchable Datagrid in Windows.Forms using C#

The datagrid don't have an option of serching for a particular value in its columns, so we need to rely on some other mechanism to do this. In this we are going to discuss about the grid with serachable column and moving the cursor to the column to the particular value.

Searchable Grid
DataView dv;
DataSet dataset11;
...connect to SQL Database
Grid.DataSource = dataset11.Tables[0];
dv = new DataView(dataSet11.Tables[0]);
CM =(CurrencyManager) BindingContext[Grid.DataSource];
Scrolling the cursor to particular row
int x = dv.Find(Int32.Parse(textBox2.Text));if (x>=0){CM.Position=x;}

1) Connect to DB
2) Fill the dataset using data adapter
3) Set the data source for the grid to display data on the grid
4) Create a dataview using the same data sourcedv = new DataView(dataSet11.Tables[0]);
5) Set the sort property of the dataview using a column name of the data source. The column name should be the column by which you want to serach the grid for values
So now we have the searchable data grid and we can search the date gird and find the position of row using the following line
dv.Find(value) --> This seraches the dataview for the value and returns the record index. If the record not found then it returns -1.

After having searchable data grid, use the currency manager to bind to grid and position at particular record.To position the cursor in the grid for the searched value follow the below steps
1) Get the Binding context of the grid source and store it on the currency manager
CM =(CurrencyManager) BindingContext[Grid.DataSource];
2) Use the find method to get the record index. 3) If it is a valid index then set the property of Currency manager "position" property to scroll in to searched record in the data grid.

For more information go to this link

Microsoft Application Updater Block

Nice feature from Microsoft, it is simple yet powerful.

What is Application Updater Block?
The Updater Application Block is a .NET component that you can use to detect, validate, and download application updates deployed in a central location. By using the Updater Application Block, you can keep desktop applications up to date with little or no user intervention. You can also extend the Updater Application Block to use custom classes for downloading and validating files, performing post-deployment configuration tasks, and controlling the update process.

Where we can get this?

For Download

In VS.NET 2005 this feature is build-in and its called as Click-Once deployment, it is easy to use this and there are lot of additional features for deployment.