Posts

Showing posts from October, 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 ValuessbyteSystem.SbyteYes1-128 to 127shortSystem.Int16Yes2-32768 to 32767intSystem.Int32Yes4-2147483648 to 2147483647longSystem.Int64Yes8-9223372036854775808 to 9223372036854775807byteSystem.ByteNo10 to 255ushortSystem.Uint16No20 to 65535uintSystem.UInt32No40 to 4294967295ulongSystem.Uint64No80 to 18446744073709551615floatSystem.SingleYes4Approximately ±1.5 x 10-45 to ±3.4 x 1038 with 7 significant figuresdoubleSystem.DoubleYes8Approximately ±5.0 x 10-324 to ±1.7 x 10308 with 15 or 16 significant figuresdecimalSystem.DecimalYes12Approximately ±1.0 x 10-28 to ±7.9 x 1028 with 28 or 29 significant figures…

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

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.

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}

</style>

<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:
fixed}

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.

Numbers
Basic number formatting specifiers: SpecifierTypeFormat Output (Passed Double 1.42)Output (Passed Int -12400)cCurrency{0:c}$1.42-$12,400dDecimal (Whole number){0:d}System.FormatException-12400eScientific{0:e}1.420000e+000-1.240000e+004fFixed point{0:f}1.42-12400.00gGeneral{0:g}1.42-12400nNumber with commas for thousands{0:n}1.42-12,400rRound trippable{0:r}…

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
{
get
{
return _isRefresh;
}
}

protected override void LoadViewState(object savedState)
{
object[] allStates = (object[]) savedState;
base.LoadViewState(allStat…

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)

{

//alert('Yes');

document.Form1.hdnbox.value='Yes';

}

else

{

//alert('No');

document.Form1.hdnbox.value='No';}
}

</SCRIPT>

[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

Response.Write(Request.Form("…

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

mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",
"1"); //basic authentication

mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",
"my_username_here"); //set your username here

mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",
"super_secret&…

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'
time.

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 …

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

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

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

How to make a button Default Button ?

Create a funtion
public static void MakeDefault(System.Web.UI.Page oPage, TextBox oTxt, ImageButton
oBtn)

{

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(" } ");

sb.Append("}");

sb.Append("</SCRIPT>");

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 ValuesbyteSystem.Sbyte-128127byteSystem.Byte0255shortSystem.Int16-32,76832,767ushortSystem.UInt16065,535intSystem.Int32-2,147,483,6482,147,483,647uintSystem.UInt3204,294,967,295longSystem.Int64-9,223372,036,854,775,8089,223372,036,854,775,808ulongSystem.UInt64018,446,744,073,709,551,615charSystem.Char065,535floatSystem.Single1.5 x 10-453.4 x 10 38doubleSystem.Double5.0 x 10-3241.7 x 1010308boolSystem.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"
rel="stylesheet">

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:

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetAllowResponseInBrowserHistory(false);

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

Hi

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