Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Archive for February, 2011

How to make ComboBox highlight color to none?

Posted by JP on February 24, 2011

In some forums I have seen developers wanted to change the selected color (usually Blue) of ComboBox to normal background color. I would like to add the code for following.

Custom Drawing

The method used for accomplishing this is Custom Drawing.


1. Create a new windows application and place a combo box on the form

2. Set the property DrawMode to OwnerDrawVariable

3. On the combo box DrawItem event, add the following code:

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)


ComboBox combo = sender as ComboBox;

e.Graphics.FillRectangle(new SolidBrush(combo.BackColor), e.Bounds);

e.Graphics.DrawString(combo.Items[e.Index].ToString(), e.Font, new

SolidBrush(combo.ForeColor), new Point(e.Bounds.X, e.Bounds.Y));


Testing the Application

You can add some test data items to the combox and run the application.


Now you can see that eventhough the mouse is on the dropdown list area the highlight color is not there.


Posted in WinForms | Tagged: , , | Leave a Comment »

What is Foreground thread? / What is Background thread?

Posted by JP on February 24, 2011



Threading is a concept we all knows and most of us would have been implemented it in the real world applications. I would like to inform about one more inner level detail on threads – that is Foreground and Background threads.

Types of Threads

Basically, there are two types of threads which fall into:

  • Foreground Thread
  • Background Thread

Foreground Thread

Foreground threads are threads which will continue to run until the last foreground thread is terminated. In another way, the application is closed when all the foreground threads are stopped.

So the application won’t wait until the background threads are completed, but it will wait until all the foreground threads are terminated.

By default, the threads are foreground threads. So when we create a thread the default value of IsBackground property would be false.

Background Thread

Background threads are threads which will get terminated when all foreground threads are closed. The application won’t wait for them to be completed.

We can create a background thread like following:

Thread backgroundThread = new Thread(threadStart);

backgroundThread.IsBackground = true;


Test Application

We can see the difference by using a windows or console application. In the attachment, I have provided such an application. The application is explained below:


The application contains 2 buttons, on click of each it will create a thread.

Each thread will be executing a method which takes 25 seconds to execute through a mere Thread.Sleep() invoke.

private void TenSecondsMethod()


// Method of 25 seconds delay



The first one will be Background thread and second would be Foreground.

After clicking each button, you can try closing the application.

From the windows task manager we can see the application would not be listed in the case of Background thread created.

From the windows task manager we can see the application would be still running in the case of Foreground thread created.

The following image shows the snapshot of task manager just after closing the application after invoking a foreground thread. The application will continue to run until all the foreground threads are completed.


Recommended Usage

We can specify foreground threads for business critical tasks.

Meantime, the background threads can be useful for polling services or logging services which could be discontinued once the application is closed.

Posted in C# | Tagged: , , | 2 Comments »

When to use lock?

Posted by JP on February 19, 2011

The lock keyword in C# provides good control over a multi-threaded application.

But if we are using it in an unwanted scenario it could impact performance. Sometimes, the usage of threading itself would not be benefited.

I am trying to explain a valid scenario where lock is advised in a multi-threaded application.

Lock while writing to a file – Advisable

In a multithreaded environment, if a particular method is writing to a file, it is advisable to use lock – otherwise exception will occur.

private void WriteToFile_Locked()


lock (this)


StreamWriter streamWriter = File.AppendText("File.txt");

streamWriter.WriteLine("A line of text..");




Lock while fetching a network resource – Not Advisable

Suppose in a method which is relying on a network resource like copying a file over a network or downloading a file from internet. In this case the lock would degrade the performance as all the threads will be waiting to enter the critical section.

If we use lock in the above scenario we will not be gaining from the threading advantage.

private void ReadNetworkResource()


WebClient client = new WebClient();

var result = client.DownloadData("");


If we implement lock to the above method it will degrade the performance.

Test Application

A test application is provided to check the performance in both the above scenarios.


The application contains buttons which are self explanatory. The first row of buttons deals with the file issue and it is solved by implementing the lock keyword.

The second row of buttons deal with the network resource issue where lock is implemented and performance was degraded. On clicking the buttons we can see the time difference it is taking to perform the actions.

In the test machine it took 10 seconds for the first one and 25 seconds for the second.

This shows that if lock is not wisely used it could impact the performance in a multi threaded application.

Without Lock

With Lock

10 seconds

25 seconds

About the Source

The source for the above application is attached with the article.

Posted in C# | Tagged: , , | Leave a Comment »

How to find the configuration path of the exe in .Net?

Posted by JP on February 10, 2011


While on debugging use the following


string path = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None).FilePath

Posted in C# | Tagged: , , | Leave a Comment »

How to avoid security error in ASP.NET textbox while inputting html content?

Posted by JP on February 9, 2011

The ASP.NET handler checks for security threats on page submissions.  This is part of the security checks, otherwise malicious scripts could be injected to the server.

But, in some alternative cases we need to bypass this – say we need to save a webpage into the database.  But the page validation throws the error.

You can try the following:

1. Create a web application and place a textbox and button on it.

2. Run the application and try entering the following data into the textbox

<html>Test Content</html>

3. Click the button to submit the page

4. You will be receiving the following error:

Server Error in ‘/’ Application.

A potentially dangerous Request.Form value was detected from the client (TextBox1=”<html>test</html>”).

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.
Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (TextBox1=”<html>Test Content</html>”).



Set the ValidateRequest property to false in the page level

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”WebApplication2._Default” ValidateRequest=”false” %>

Now try rerunning the application and click the button.  The error is disappeared now.

Posted in ASP.NET | Tagged: , , | 2 Comments »

How to view disassembly code in VS 2005/2008?

Posted by JP on February 7, 2011

I found that some of the community members are relying on third party tools to view the disassembly generated for .Net applications.  It would be nice to see that already this feature is supported by Visual Studio 2005/2008.

In the following application I am trying to show the disassembly generated.

Step 1: Create a console application

Create a new console application and replace the main method with the following code.

    static void Main(string[] args)
        int i = 10;
        int j = 20;

        int sum = i + j;

        Console.WriteLine(string.Format(“Sum is: {0}”, sum));

Step 2: Place a breakpoint at the end of Main method()

It is depicted in the image below.


Step 3: Execute the application

Press F5 to debug the application, and when control reaches the breakpoint, right click on the code and from the context menu choose  “Go to Disassembly”


You can see the following output:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DisassemblyApp
    class Program
        static void Main(string[] args)
00000000  push        ebp 
00000001  mov         ebp,esp
00000003  sub         esp,20h
00000006  mov         dword ptr [ebp-4],ecx
00000009  cmp         dword ptr ds:[04D2707Ch],0
00000010  je          00000017
00000012  call        5F311579
00000017  xor         edx,edx
00000019  mov         dword ptr [ebp-10h],edx
0000001c  xor         edx,edx
0000001e  mov         dword ptr [ebp-0Ch],edx
00000021  xor         edx,edx
00000023  mov         dword ptr [ebp-8],edx
00000026  nop             
           int i = 10;
00000027  mov         dword ptr [ebp-8],0Ah
           int j = 20;
0000002e  mov         dword ptr [ebp-0Ch],14h

            int sum = i + j;
00000035  mov         eax,dword ptr [ebp-8]
00000038  add         eax,dword ptr [ebp-0Ch]
0000003b  mov         dword ptr [ebp-10h],eax

            Console.WriteLine(string.Format(“Sum is: {0}”, sum));
0000003e  mov         ecx,62D708h
00000043  call        FA13826C
00000048  mov         dword ptr [ebp-14h],eax
0000004b  mov         eax,dword ptr ds:[02AF8370h]
00000051  mov         dword ptr [ebp-1Ch],eax
00000054  mov         eax,dword ptr [ebp-14h]
00000057  mov         edx,dword ptr [ebp-10h]
0000005a  mov         dword ptr [eax+4],edx
0000005d  mov         eax,dword ptr [ebp-14h]
00000060  mov         dword ptr [ebp-20h],eax
00000063  mov         ecx,dword ptr [ebp-1Ch]
00000066  mov         edx,dword ptr [ebp-20h]
00000069  call        dword ptr ds:[001F8E20h]
0000006f  mov         dword ptr [ebp-18h],eax
00000072  mov         ecx,dword ptr [ebp-18h]
00000075  call        dword ptr ds:[04816794h]
0000007b  nop             
0000007c  nop             
0000007d  mov         esp,ebp
0000007f  pop         ebp 
00000080  ret             

Posted in C# | Tagged: , , | Leave a Comment »

How to send Html Email using c#?

Posted by JP on February 7, 2011

SmtpClient client = new SmtpClient(“”);
client.Credentials = new NetworkCredential(“”, “password”);

MailMessage message = new MailMessage(“”,
                               “Testing Html Email”,
                               “<h1>Your Email Content</h1>”);

message.IsBodyHtml = true;

Posted in C# | Tagged: , , | Leave a Comment »

Automatic History using Triggers

Posted by JP on February 5, 2011

I would like to take a moment to explain the following problem I am facing:

I do have a table named Equity which contains the company name and the current PE Ratio. 


The PE Ratio will be updated daily or weekly based on the wish of user through a web application in ASP.NET.  When the process runs for many years, there will be many updating happening to the same record. 


Our problem is to get the historical PE Ratio values, so that we can find out the maximum and minimum values for decision making.

High Cost Solution

One of the solutions, we can prefer is while updating the record from our web application, take a copy of the record and insert it into another table. 

This involves changing the associated business logic layer in c# or changing the stored procedure.  I would say  this is more time consuming and lot of code we have to write to write to manage the new table if schema changes are involved.

Simple Solution

We can use database triggers to achieve the same.  The solution steps are as following.  Belive me, this will take only 5 minutes to do.

1. Create a new History Table with same structure

2. Create a Trigger for UPDATE operation

As our History table is not involved in any business logic currently, we can use the Trigger to solve the problem and move off.


First, we have to create our original Equity table.  The script is given below.  The script was generated from Sql Server 2005.

CREATE TABLE [dbo].[Equity](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [PERatio] [float] NULL,
    [ModifiedOn] [datetime] NULL,
    [Id] ASC

Create the History Table

We can create the EquityHistory table using the following script.  Please note that there is an additional column HistoryId which keeps track of the History record as there will be multiple history records for each original table record.

CREATE TABLE [dbo].[EquityHistory](
    [HistoryId] [int] IDENTITY(1,1) NOT NULL,
    [Id] [int],
    [Name] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [PERatio] [float] NULL,
    [ModifiedOn] [datetime] NULL,
    [HistoryId] ASC

Create the Trigger

The following Trigger script will do all the magic involved.  It says that create a trigger on table Equity whenever UPDATE statement is used.  The last line says that get the record from table inserted and insert it into the EquityHistory table

CREATE TRIGGER Equity_Update_Trigger
ON Equity
INSERT INTO EquityHistory SELECT * FROM inserted

The table inserted  is a pre-defined table insided triggers.  It will give the current record structure while using with INSERT/UPDATE triggers.

Testing the Whole

You can try inserting a new record to the original Equity table.  The corresponding record will get automatically inserted in the EquityHistory table.

Now, try changing the PERatio from the first able.  You can see a new record gets added to the history table.



The attachment file contains queries to create table, insert data, select data.  You can try running the file against an sql server database.

Posted in SQL Server | Tagged: , , , | Leave a Comment »

Simplest way of zipping and unzipping in .Net

Posted by JP on February 4, 2011

Add reference to Shell32.dll in c:\windows\system32 folder

Use the following unzipping code:

DirectoryInfo di = new DirectoryInfo(@”C:\Temp\”);
            foreach (FileInfo fi in di.GetFiles(“*.zip”))
                String file = fi.ToString();
                var destinationPath = @”C:\Temp\AppName\”;
                if (!Directory.Exists(destinationPath))
                Shell sh = new Shell();
                Folder destFlder = sh.NameSpace(destinationPath);
                Folder srcFlder = sh.NameSpace(fi.FullName);
                foreach (FolderItem F in srcFlder.Items())
                    destFlder.CopyHere(F, null);

Posted in C# | Tagged: , , | Leave a Comment »

Importance of TimeZoneInfo class

Posted by JP on February 3, 2011

I would like to take your attention on the following problems.

You are working on an ASP.NET application which is hosted in a server under USA time zone?

You need to send an email to your customers daily at Singapore time zone 10 AM. How is that possible?

How to get all the time zones in the current system?

What is the current time zone Id?

The answers for all these questions would be the TimeZoneInfo class.


The TimeZoneInfo class represents any time zone in the world. It contains a set of static methods/properties that allows us to get the current time zone information, conversion of datetime between time zones etc.


The important properties or methods are described below:





Static Property

Gets the current TimeZoneInfo of machine


Static Method

Returns the list of world TimeZoneInfo available


Static Method

Converts time in one zone to another


Instance Property

String identifier of TimeZoneInfo


Instance Property

Display name in localized text


Instance Method

Returns the difference in timezone difference with Universal Time (UTC)

The Test Application

The test application attached provides:

· Information on Current Time Zone

· Displays list of TimeZoneInfo available


Converting current datetime to another TimeZone

So what about converting the current time to another time zone?

Here is the answer: Use the TimeZoneInfo.ConvertTime() method.

Code Example:

TimeZoneInfo timeZone = TimeZoneInfo.GetSystemTimeZones().Where(t => t.Id == “Central Standard Time”).First();

DateTime newTime = TimeZoneInfo.ConvertTime(DateTime.Now, timeZone);

The method ConvertTime() takes the current time and new time zone as arguments.

Posted in C# | Tagged: , | Leave a Comment »