October 30, 2005

C# Variable Types (Value Type)

The following table lists, and gives information about, the predefined value types. Because in C# all of the apparently fundamental value types are in fact built up from the (actually fundamental) object type, the list also indicates which System types in the .Net framework correspond to these pre-defined types.

C# Type.Net Framework (System) typeSigned?Bytes OccupiedPossible Values
sbyteSystem.SbyteYes1-128 to 127
shortSystem.Int16Yes2-32768 to 32767
intSystem.Int32Yes4-2147483648 to 2147483647
longSystem.Int64Yes8-9223372036854775808 to 9223372036854775807
byteSystem.ByteNo10 to 255
ushortSystem.Uint16No20 to 65535
uintSystem.UInt32No40 to 4294967295
ulongSystem.Uint64No80 to 18446744073709551615
floatSystem.SingleYes4Approximately ±1.5 x 10-45 to ±3.4 x 1038 with 7 significant figures
doubleSystem.DoubleYes8Approximately ±5.0 x 10-324 to ±1.7 x 10308 with 15 or 16 significant figures
decimalSystem.DecimalYes12Approximately ±1.0 x 10-28 to ±7.9 x 1028 with 28 or 29 significant figures
charSystem.CharN/A2Any Unicode character (16 bit)
boolSystem.BooleanN/A1 / 2true or false

Delegates in C#

Delegates are reference types, which allow indirect calls to methods. Delegates are similar to function pointers C++, but delegates are reference types rather than value types and some single delegates can reference multiple methods. Delegates can encapsulate both static methods of a class as well as instance methods. Delegates are called single-cast delegates when they encapsulate a single method, and are called multi-cast delegates when they encapsulate more than one method. Multi-cast delegates are useful as event-handlers.

Declaring delegates: use the delegate keyword. There is no difference in the manner of declaration between single-cast and multi-cast delegates.
public delegate String MyDelegate();

Delegate Constructor: The constructor takes two arguments, where the first argument is the object whose method we are binding to the delegate and the second argument is the address of the method. For static methods we don't need to pass the first argument.

For a single-cast delegate we use the default delegate constructor
MyDelegate oFirstDelegate = new MyDelegate (t1.TestAbc); //instance method
MyDelegate oSecondDelegate = new MyDelegate (Test.TestAbc); //static method

For multi-cast delegates + and += operators has been overloaded in C# and adding a delegate to another delegate is done simply by using the + operator on any number of delegates. Similiarly for removing C# is using - and -=
oFirstDelegate = oSecondDelegate + new MyDelegate (Test.TestAbc); //using the + operator
oFirstDelegate += new MyDelegate (Test.TestAbc); //using the += operator

Sample rogram #1
In this program we will declare a single cast delegate. Our delegated is void and takes a String as argument. We'll assign an instance method of an object to the delegate and then invoke the delegate. Then we'll assign a static method of a class to the same delegate object and again invoke the delegate.

using System;
namespace Delegates
public class DelegateTest
public DelegateTest(){}
public delegate void delgTest(string sText);
public static void StaticMethod(string sText)
{ Console.WriteLine(sText); }
public void InstanceMethod(string sText)
{ Console.WriteLine(sText); }
public static void Main()
delgTest oDelegate = new delgTest(StaticMethod);
oDelegate = new delgTest(new DelegateTest().InstanceMethod);
public static void ShowInConsole(delgTest oDelegate)
{ oDelegate("Displayed in the Console"); }

Sample Program #2
In the example we are using a multi-cast delegate. Our delegate takes zero arguments and returns void. We'll first create two single-cast delegates, one based on an instance method and the other one based on a static method. Then we'll create our multi-cast delegate by combining the two delegates and invoke our multi-cast delegate. Now we remove one of the delegates from our multi-cast delegate and again invoke it.

public class MultiCastDelegateTest
public MultiCastDelegateTest(){}
public delegate void delgTest();
public static void StaticMethod()
{ Console.WriteLine("Static Method"); }
public void InstanceMethod()
{ Console.WriteLine("Instance Method"); }
public static void Main()
delgTest oDelegate1 = new delgTest(StaticMethod);
delgTest oDelegate2 = new delgTest(new MultiCastDelegateTest().InstanceMethod);
oDelegate1 += oDelegate2;
oDelegate1(); // Invoking Delegate
oDelegate1 -= oDelegate2;

October 26, 2005

How to make Visual Studio .NET create web projects in a folder other then inetpub\wwwroot

Before creating your web project in VS.NET, perform these steps:

1. Create a new folder where you want your web project files to reside.
2. Convert the folder into a virtual directory using IIS.

Open Visual Studio .NET and perform these steps:
1. Create a new web project.
2. In the Location text box in the New Project dialog box, type the virtual directory name of folder you created.
Visual Studio .NET will proceed creating the web project in the specified folder.

October 21, 2005

CSS Tips

Use first-letter pseudo-element to add a special effect to the first letter
of a text.

<style type="text/css">

p:first-letter {color: #ff0000; font-size:xx-large}


<p>First Letter Testing</p>

Background Image

To repeat a background image vertically

body{ background-image: url('bgImage.jpg'); background-repeat: repeat-y}

To repeat a background image horizontally

body{ background-image: url('bgImage.jpg'); background-repeat: repeat-x}

To Fix a background image

body{ background-image: url('bgImage.jpg'); background-repeat: no-repeat; background-attachment:

October 12, 2005

A quick reference to .NET string formatting in C#

Every object has a method called ToString that returns a string representation of the object. The ToString method can accept a string parameter, which tells the object how to format itself - in the String.Format call, the formatting string is passed after the position, for example, "{0:##}"

The text inside the curly braces is {index[,alignment][:formatString]}. If alignment is positive, the text is right-aligned in a field the given number of spaces; if it's negative, it's left-aligned.

String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value); :- This will output "$1,240.00" if passed 1243.50.

Basic number formatting specifiers:
SpecifierTypeFormat Output (Passed Double 1.42)Output (Passed Int -12400)
dDecimal (Whole number){0:d}System.FormatException-12400
fFixed point{0:f}1.42-12400.00
nNumber with commas for thousands{0:n}1.42-12,400
rRound trippable{0:r}1.42System.FormatException

Custom number formatting:
SpecifierTypeExample Output (Passed Double 1500.42)Note
0Zero placeholder{0:00.0000}1500.4200Pads with zeroes.
#Digit placeholder{0:(#).##}(1500).42
.Decimal point{0:0.0}1500.4
,Thousand separator{0:0,0}1,500Must be between two zeroes.
,.Number scaling{0:0,.} 2Comma adjacent to Period scales by 1000.
%Percent{0:0%}150042%Multiplies by 100, adds % sign.
eExponent placeholder{0:00e+0}15e+2Many exponent formats available.
;Group separatorsee below

The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious: Dates

Note that date formatting is especially dependant on the system's regional settings; the example strings here are from my local locale.
SpecifierTypeExample (Passed System.DateTime.Now)
dShort date10/12/2002
DLong dateDecember 10, 2002
tShort time10:11 PM
TLong time10:11:29 PM
fFull date & time December 10, 2002 10:11 PM
FFull date & time (long)December 10, 2002 10:11:29 PM
gDefault date & time10/12/2002 10:11 PM
GDefault date & time (long)10/12/2002 10:11:29 PM
MMonth day patternDecember 10
rRFC1123 date stringTue, 10 Dec 2002 22:11:29 GMT
sSortable date string2002-12-10T22:11:29
uUniversal sortable, local time2002-12-10 22:13:50Z
UUniversal sortable, GMTDecember 11, 2002 3:13:50 AM
YYear month patternDecember, 2002

Custom date formatting:
SpecifierTypeExample Example Output
dddDay name{0:ddd}Tue
ddddFull day name{0:dddd}Tuesday
f, ff, ...Second fractions{0:fff}932
gg, ...Era{0:gg}A.D.
hh2 digit hour{0:hh}10
HH2 digit hour, 24hr format{0:HH}22
mmMinute 00-59{0:mm}38
MMMonth 01-12{0:MM}12
MMMMonth abbreviation{0:MMM}Dec
MMMMFull month name{0:MMMM}December
ssSeconds 00-59{0:ss}46
ttAM or PM{0:tt}PM
yyYear, 2 digits{0:yy}02
zzTimezone offset, 2 digits{0:zz}-05
zzzFull timezone offset{0:zzz}-05:00

Detecting Page Refresh

How to stop the user from refreshing the page. The problem arises, if the previous request to the server was a PostBack, which, for example, inserts some data. This will result in the addition of duplicate rows in the database. we can’t stop the user from refreshing the page, but we can determine if this event has already occurred and then take appropriate action.

Create the function below and check Page.IsRefresh to check whether the page is resending the info. If you are using a base page from which all your pages are derived, then better you include this function on base page, so need not to duplicate the function. I m using Viewstate to store the info.

#region "Page Refresh Handling"

/// Code for checking the refresh event after any postback occured

private bool _refreshState;
private bool _isRefresh;

public bool IsRefresh
return _isRefresh;

protected override void LoadViewState(object savedState)
object[] allStates = (object[]) savedState;
_refreshState = (bool) allStates[1];
_isRefresh = _refreshState == (bool) Session["__ISREFRESH"];

protected override object SaveViewState()
Session["__ISREFRESH"] = _refreshState;
object[] allStates = new object[2];
allStates[0] = base.SaveViewState();
allStates[1] = !_refreshState;
return allStates;

October 07, 2005

How to get the confirmation of Yes/No from a javascript pop-up and display the value on the page

The sample code is on the most frequently asked query on "How to get the
confirmation of Yes/No from a javascript pop up and display the value on the page
using ASP.NET"Create a webpage main.aspx Drag and drop a hidden control and
control on the web form. [bold]Step 1. main.aspx.vb[/bold] Write the following
code on page load event

Button1.Attributes.Add("onclick", "getMessage()")

[bold]Step 2.In main.aspx[/bold] Add the client side-script block

<SCRIPT language=javascript>

function getMessage()


var ans;

ans=window.confirm('Is it your confirmation.....?');

//alert (ans);

if (ans==true)











[bold]Step 3. main.aspx.vb[/bold] To display the value of the value selected
by the user in the pop up write the following code


How to send authenticated emails

If you are using the .NET Framework 1.0, this cannot be done. However, in the
1.1 version, the MailMessage.Fields property was added. This allowed access to
the underlying CDO.Message fields.

The following example demonstrates sending your username and password to the
SMTP server to provide authentication.

[ C# ]

private void Page_Load(object sender, System.EventArgs e)


MailMessage mail = new MailMessage();

mail.To = "me@mycompany.com";

mail.From = "you@yourcompany.com";

mail.Subject = "this is a test email.";

mail.Body = "Some text goes here";

"1"); //basic authentication

"my_username_here"); //set your username here

"super_secret"); //set your password here

SmtpMail.SmtpServer = "mail.mycompany.com"; //your real server goes

SmtpMail.Send( mail );


Home Page

1. Emphasize what your site offers that's of value to users and how your services
differ from those of key competitors: When users have needs, they typically query
search engines and allocate only a few seconds to scan each of the sites that
the search engine drags up.

2. Use a liquid layout that lets users adjust the homepage size: Different users
have different monitor sizes. People with big monitors want to be able to resize
their browsers to view multiple windows simultaneously. You can't assume that
everyone's window width is 800 pixels:

3. There's no reason to label the search box if there's a "Search" button
right next to it.

4. Don't include an active link to the homepage on the homepage

a. If they click it, a link leading to the current page is an utter waste of users'

b. Worse, such links cause users to doubt whether they're really at the location
they think they're at.

c. Worst of all, if users do follow these no-op links they'll be confused as to
their new location,

particularly if the page is scrolled back to the top.

Thread Safety

Is a static method thread safe? Is a static method a bottleneck?

First, let’s go shopping.

Let’s say I take a grocery cart of 10 items into a checkout lane at my local grocery store. The clerk takes each item from my cart and computes a total cost for all the items. Unless there was a human error (or an item was priced incorrectly), we would expect the clerk’s cash register to compute the correct total.

The clerk is like a thread. Like a thread in an application, the clerk executes a set of instructions to compute the total cost of my grocery items. The clerk will process one cart of items at a time, and each will make use of a cash register to tally the items.

Now picture a different scenario. Picture 5 checkout lanes, each lane with one clerk, but only one shared cash register for the entire store. If multiple clerks are ringing up items on the shared cash register for different shoppers at the same time, nobody will receive the correct total. My clerk might ring up two items and then pause for a second, which allows a second clerk to come in and add another shopper’s item to the current list in the cash register. The total cost for items in my cart would be incorrect. This is an analogy of what can happen if a method is not thread safe – corrupted data.

The solution to the shared cash register problem is to ensure a clerk will have exclusive possession of the single cash register while totaling my order. No other clerks are allowed to use the register until my 10 items are finished. These steps will produce the correct results, but as you might imagine, it can make for long lines at the checkout. Everyone is waiting on this one cash register to come free. This is an analogy of what can happen to the scalability of an application when threads are locked while waiting for a shared resource.

There is a delicate balance to strike when writing code that is both high performance and thread safe with shared resources.

SQL Performance Tuning using Indexes

1. Useful Index Queries

Just like the reader searching for a word in a book, an index helps when you are
looking for a specific record or set of records with a WHERE clause. This includes
queries looking for a range of values, queries designed to match a specific value,
and queries performing a join on two tables. Since index entries are stored in
sorted order, indexes also help when processing ORDER BY clauses. Grouping records
with a GROUP BY clause will often require sorting.

2. Index Drawbacks

Indexes are a performance drag when the time comes to modify records. Any time
a query modifies the data in a table the indexes on the data must change also.
Static systems, where databases are used heavily for reporting, can afford more
indexes to support the read only queries. A database with a heavy number of transactions
to modify data will need fewer indexes to allow for higher throughput. Indexes
also use disk space. The exact size will depends on the number of records in the
table as well as the number and size of the columns in the index. Generally this
is not a major concern as disk space is easy to trade for better performance.

3. Building The Best Index

Short Keys

Larger index keys will cause the database to perform more disk reads, which
limits throughput. Secondly, since index entries are often involved in comparisons,
smaller entries are easier to compare. A single integer column makes the absolute
best index key because an integer is small and easy for the database to compare.
Character strings, on the other hand, require a character-by-character comparison
and attention to collation settings.

Distinct Keys

The most effective indexes are the indexes with a small percentage of duplicated
values. An index with a high percentage of unique values is a selective index.
Obviously, a unique index is highly selective since there are no duplicate entries.

As an analogy, think of a phone book for a town where almost everyone has the
last name of Smith. A phone book in this town is not very useful if sorted in
order of last name, because you can only discount a small number of records
when you are looking for a Smith.

Covering Queries

Indexes generally contain only the data values for the columns they index and
a pointer back to the row with the rest of the data. Generally the database
will have to follow pointers from an index back to a row to gather all the information
required for a query. However, if the index contains all of he columns needed
for a query, the database can save a disk read by not returning to the table
for more information. The database could use just the index entries to satisfy
the following query.

Eg: SELECT Count(*), UnitPrice FROM Products GROUP BY UnitPrice (UnitPrice column

We call these types of queries covered queries, because all of the columns requested
in the output are covered by a single index. For your most crucial queries,
you might consider creating a covering index to give the query the best performance
possible. Such an index would probably be a composite index (using more than
one column), which appears to go against our first guideline of keeping index
entries as short as possible. Obviously this is another tradeoff you can only
evaluate with performance testing and monitoring.

Clustered Indexes

Many databases have one special index per table where all of the data from a
row exists in the index. SQL Server calls this index a clustered index. As a
general rule of thumb, every non-trivial table should have a clustered index.
If you only create one index for a table, make the index a clustered index.
In SQL Server, creating a primary key will automatically create a clustered
index (if none exists) using the primary key column as the index key. Clustered
indexes are the most effective indexes (when used, they always cover a query).
When choosing the column or columns for a clustered index, be careful to choose
a column with static data. If you modify a record and change the value of a
column in a clustered index, the database might need to move the index entry
(to keep the entries in sorted order). Remember, index entries for a clustered
index contain all of the column values. For this reason, clustered indexes are
often found on primary or foreign key columns. Key values will rarely, if ever,

HTML Control Vs Web Control

The web control approach is object oriented, easier to use server-side, and more robust than using HTML controls. Since everything in software development has a trade-off, you might be wondering what the downside to using a web control is (some may say the trade-off is performance, but in reality the overhead of using a web control is almost negligible). There really is no downside to using web controls over HTML controls – we should always favor using the web control.

Web Forms State Management Part1: Client-Based State Management Options

Web pages are recreated each time the page is posted to the server. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server. To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes — that is, for managing state. The page framework includes a facility called view state that automatically preserves property values of the page and all the controls on it between round trips. However, you will probably also have application-specific values that you want to preserve. To do so, you can use one of the state management options.Client-Based State Management Options: - Storing information either in the page or on the client computer.
1. View State: - When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.To store information in view state: - ViewState["Time"] = DateTime.Today.ToLongDateString();
To retrieve information from view state: - Response.Write( (string) ViewState["Time"]);The advantages of using view state are:
- No server resources required. The view state is contained in a structure within the page code.
- Simple implementation.
- Automatic retention of page and control state.
- Enhanced security features. The values in view state are hashed, compressed, and encoded for Unicode implementations, thus representing a higher state of security than hidden fields have.
The disadvantages of using the view state are:
- Performance. Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.
- Security. The view state is stored in a hidden field on the page. Although view state stores data in a hashed format, it can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue.
2. Hidden Form Fields: - A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP Form collection along with the values of other controls.
Note: If you use hidden fields you must submit your pages to the server using the HTTP POST method rather than requesting the page via the page URL (the HTTP GET method).
The advantages of using hidden fields are:
- No server resources are required. The hidden field is stored and read from the page.
- Broad support. Almost all browsers and client devices support forms with hidden fields.
- Simple implementation.
The disadvantages of using hidden fields are:
- Security: - The information in the hidden field can be seen if the page output source is viewed directly
- Limited storage structure. Hidden fields offer a single value field in which to place information. To store multiple values, you must implement delimited strings and the code to parse those strings.
- Performance. Storing large values can cause the page to slow down
3. Cookies: - Useful for storing small amounts of frequently changed information on the client.
Note: Cookies are often used for personalization, where content is customized for a known user. In most of these cases, identification is the issue rather than authentication, so it is enough to merely store the user name, account name, or a unique user ID (such as a GUID) in a cookie and use it to access the user personalization infrastructure of a site.
The advantages of using cookies are:
- No server resources are required. It is stored on the client.
- Simplicity. The cookie is a lightweight, text-based structure with simple key-value pairs.
- Configurable expiration. The cookie can expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.
The disadvantages of using cookies are:
- Limited size. Most browsers place a 4096-byte limit on the size of a cookie
- User-configured refusal. Some users disable their browser or client device's ability to receive cookies
- Security. Users can manipulate cookies on their computer
- Durability. The durability of the cookie on a client computer is subject to cookie expiration processes on the client and user intervention.

Set Cookies HttpCookie MyCookie = new HttpCookie("LastVisit");
DateTime now = DateTime.Now;

MyCookie.Value = now.ToString();
MyCookie.Expires = now.AddHours(1);


4. Query Strings: - is information appended to the end of a page's URL. They are an easy way to pass information from one page to another page where it will be processed. Note Query strings are a viable option only when a page is requested via its URL. You cannot read a query string from a page that has been submitted to the server.
The advantages of using query strings are:
- No server resources required.
- Broad support. Almost all browsers and client devices support passing values in a query string.
- Simple implementation.
The disadvantages of using query strings are:
- Security. The information in the query string is directly visible to the user via the browser user interface. - Limited capacity. Most browsers and client devices impose a 255-character limit on URL length.

How to make a button Default Button ?

Create a funtion

public static void MakeDefault(System.Web.UI.Page oPage, TextBox oTxt, ImageButton


StringBuilder sb = new StringBuilder();

sb.Append("<SCRIPT language='javascript'>");

sb.Append("function fnTrapKD(btn){");

sb.Append(" if (document.all){");

sb.Append(" if (event.keyCode == 13)");

sb.Append(" { ");

sb.Append(" event.returnValue=false;");

sb.Append(" event.cancel = true;");

sb.Append(" btn.click();");

sb.Append(" } ");

sb.Append(" } ");



oTxt.Attributes.Add("onkeydown", "fnTrapKD(document.all."
+ oBtn.ClientID + ")");

oPage.RegisterStartupScript("ForceDefaultToScript", sb.ToString());


Call this function, eg: MakeDefault(Page, TextBox1, Button1)

Data Types and its min & max value

Data Type PrefixData TypeMin ValueMax Value
floatSystem.Single1.5 x 10-453.4 x 10 38
doubleSystem.Double5.0 x 10-3241.7 x 1010308
boolSystem.BooleanFalse (0)True (1)
decimalSystem.Decimal1.0 x 10-287.9 x 1028

Run an exe using C#code

System.Diagnostic.Process.Start ("AppName.exe");

To print certain areas of a page

Create a style sheet for printing purpose, normally will remove background colors, images.... After that include it with media="print", so that this style sheet will be applied while printing

<LINK media="print" href="styles/printStyle.css" type="text/css"

Detecting Browser Capabilities

The capabilities of a browser include things such as whether it supports cookies, javascript and ActiveX controls and browser type and version. Based on these capabilities you can decide whether to provide rich DHTML functionality or render page differently.
The capabilities of browser are accessible from Request.Browser property. This property returns an instance of System.Web.HttpBrowserCapabilities class. The HttpBrowserCapabilities class contains many read only properties that tell us more about browser.

HOW TO: Prevent Caching of web forms by the browser

When you request a web form, ASP.NET processes it on the server and returns it back to the browser. Browsers generally keep cache of web pages they visit to improve performance and reduce network hits. That means when you navigate from one page to another and use Back button of the browser, you are given copy of the web form the browser cache and not from the server. Though this behavior is fine for most of the case in some you need to prevent browser from such caching. For example, you are developing a payment processing page where user enters credit card number and other details. Once the form is submitted it should not be cached on the client side. Pressing Back button should not display the old details like credit card number.

To solve this problem here is a quick solution:


Add above two lines of code in the Page_Load event handler.

How to loop through the Hash Table ?

foreach (DictionaryEntry entry in hashTable)
Console.WriteLine ("Key={0}, Value={1}\n", entry.Key, entry.Value);

To automatically refresh an aspx page at regular time intervals

<meta http-equiv="refresh" content="10">

My First blog, welcome


I m Roshan, running a small software devolopment company at Trivandrum, Kerala, India. Presently I m working on dot net. Blogs and communit forums really helped me to learn this powerful language. So I thought i should share my experience, knowledge and some useful code snippets with all of you.

Thanks & Regards
Roshan PM