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

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?

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

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.

Thursday, June 01, 2006

Exiting from .NET Application

There are 2 ways by which you can exit from an application.

They are
1) Application.Exit
2) Environment.Exit

If you are using VB.NET then you have one more option "End"

Difference between Application.Exit and Environment.Exit

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. This is the call to use if you are running a WinForms application.

Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.
As a general guideline, use "Application.Exit" call if you have called System.Windows.Forms.Application.Run or if it is a console application then call "Environment.Exit(int)".

What about "End"?

The End statement stops code execution abruptly, without invoking the Finalize method or any other Visual Basic code. Object references held by other programs are invalidated. The End statement provides a way to force your program to halt. For normal termination of a Visual Basic program, you should unload all forms.

How to check my program is running using Message Loop?

You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.

If (System.Windows.Forms.Application.MessageLoop)
{// Use this since we are a WinForms appSystem.
// Use this since we are a console appSystem.

You can use Application.ExitThread() to exit only from the current thread.