Archive for the ‘Uncategorized’ Category

Hello world!

February 24, 2009

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

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

December 25, 2008

I have faced this issue a lot of time, where I want to know what control caused the asp.net page to postback. If you study carefully, you will find that ALL the server side asp.net 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 asp.net page is nothing but a plain HTML. Now when the page causes a postback, the asp.net 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 asp.net engine know what control has caused postback???

If you view the source of the rendered asp.net 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 asp.net 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;
break;
}
}

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 );
}
else
{

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

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

Hope this helps 🙂

How to implement Threading in C#.NET?

August 26, 2008

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.Start();

Thread.CurrentThread.Name = "Main_Thread";
pg.Fun();

Console.ReadLine();
}

public void Fun()
{
Console.WriteLine(Thread.CurrentThread.Name);
}
}
}

Output:

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.Start();

Thread.CurrentThread.Name = "Main_Thread";
pg.Fun();

Console.ReadLine();
}

public void Fun()
{
// The C# “lock” statement will lock the execution of the thread
lock(sync)
{
Console.WriteLine(Thread.CurrentThread.Name);
}
}
}

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 !

How to add a program to Windows Startup ?

April 7, 2008

Adding a program/application to Windows Startup can be accomplished in various ways such as:

  • Modifying registry settings.
  • Writing to the startup files.

A list of registry keys that can start a program when Windows boots-up and some of the file to be modified is given below. You can add the programs to the below given keys, as required. In the article I have frequently used two root keys i.e. HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER.
The HKEY_LOCAL_MACHINE registry sub-tree contains information about the local computer system, including hardware and operating system data, such as bus type, system memory, device drivers, and startup control parameters.
The HKEY_CURRENT_USER registry sub-tree contains the user profile for the user who is currently logged on to the computer. The user profile includes environment variables, personal program groups, desktop settings, network connections, printers, and application preferences. The data in the user profile is similar to the data stored in the Win.ini file in Windows 3. x.

Modifying Registry Keys
When we turn on the computer the registry keys are loaded in the following order:

RunServicesOnce
This key is designed to start services when a computer boots up. These entries can also continue running even after you log on, but must be completed before the HKEY_LOCAL_MACHINE\..\..\..\RunOnce registry can start loading its programs.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce

RunServices
This key is designed to start services also. These entries can also continue running even after you log on, but must be completed before the HKEY_LOCAL_MACHINE\…\RunOnce registry can start loading its programs.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices
* Logon Prompt is placed on Screen. After a user logs in the rest of the keys are loaded.

RunOnce Local Machine Key
These keys are normally used by Setup programs. Entries in these keys are started once and then are deleted from the key (registry). If there an exclamation point preceding the value of the key, the entry will not be deleted until after the program completes, otherwise it will be deleted before the program runs. This is important, because if the exclamation point is not used, and the program referenced in this key fails to complete, it will not run again as it will have already been deleted. All entries in this key are started synchronously in an undefined order. The RunOnce keys are ignored under Windows 2000 and Windows XP in Safe Mode.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnceEx

Run
These are the most common startup locations for programs to install auto start from. By default these keys are not executed in Safe mode. If you want to run these keys in safe mode, then prefix asterisk (*) to the value of the key.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run registry key

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run registry key

All Users Startup Folder
For Windows XP, 2000, and NT, this folder is used for programs that should be auto started for all users who will login to this computer. It is generally found at:

Windows XP C:\Documents and Settings\All Users\Start Menu\Programs\Startup

Windows NT C:\wont\Profiles\All Users\Start Menu\Programs\Startup

Windows 2000 C:\Documents and Settings\All Users\Start Menu\Programs\StartupUser Profile Startup Folder – This folder will be executed for the particular user who logs in. This folder is usually found in:

Win 9X, ME c:\windows\start menu\programs\startup

Windows XP C:\Documents and Settings\LoginName\Start Menu\Programs\Startup

RunOnce Current User Key
These keys are designed to be used primarily by Setup programs. Entries in these keys are started once and then are deleted from the key. If there a exclamation point preceding the value of the key, the entry will not be deleted until after the program completes, otherwise it will be deleted before the program runs. This is important, because if the exclamation point is not use, and the program referenced in this key fails to complete, it will not run again as it will have already been deleted. The RunOnce keys are ignored under Windows 2000 and Windows XP in Safe Mode. The RunOnce keys are not supported by Windows NT 3.51.
Registry Keys:

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce

Explorer Run
These keys is normally used to load programs as part of a policy set in place on the computer or user.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run

•HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run

UserInit Key
This key specifies the program to be launched after a user logs into Windows. For example: HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit = C:\windows\system32\userinit.exe,c:\windows\badprogram.exe. If you observer carefully we have two comma separated programs listed above. The userinit.exe is a default program that loads users profile and should always be present in this key. You can add your own programs by separating them using comma.
Registry Keys:

•HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit

Notify
This key is used to add a program that will run when a particular event occurs. Events include logon, logoff, startup, shutdown, startscreensaver, and stopscreensaver. When Winlogon.exe generates an event such as the ones listed, Windows will look in the Notify registry key for a DLL that will handle this event. Malware has been known to use this method to load itself when a user logs on to their computer. Loading in such a way allows the malware program to load in such a way that it is not easy to stop.
Registry Keys:
•HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify

SharedTaskScheduler
This section corresponds to files being loaded through the SharedTaskScheduler registry value for XP, NT, 2000 machines.The entries in this registry run automatically when you start windows.
Registry Keys:

•HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SharedTaskScheduler

You can also modify the below given files to add your programs to start-up:
c:\autoexec.bat
c:\config.sys
windir\winstart.bat
windir\win.ini – [windows] “load”
windir\win.ini – [windows] “run”
windir\system.ini – [boot] “shell”