Wednesday, June 30, 2010

How to loop through all rows of the DataTable?

I know this tip is very easy for 6 month experienced professionals but still some time few new professional are looking for this tip.

foreach (DataRow row in dTable.Rows)
{
yourvariable = row["ColumnName"].ToString();
}

//OR
for (int j = 0; j< dTable.Rows.Count; j++)
{
yourvariable = dTable.Rows[j]["ColumnName"].ToString()l
}

Tuesday, June 29, 2010

Two approaches to update database row if exists, insert if not

The biggest challenge with update/insert (so called upsert) is to minimize any kind of locks. Unfortunately there is no silver bullet for this yet. So let's review two the most commonly used methods:


1. Update, if @@ROWCOUNT = 0 then insert
UPDATE Table1 SET Column1 = @newValue WHERE Id = @id
IF @@ROWCOUNT = 0
BEGIN
INSERT INTO Table1 (Id, Column1) VALUES (@id, @newValue)
END
This method is good if you know that in most of the cases a row will exist and update will be performed. Otherwise the second method should be used.

2. If row exists update, otherwise insert
IF EXISTS(SELECT * FROM Table1 WHERE Id = @id)
BEGIN
UPDATE Table1 SET Column1 = @newValue WHERE Id = @id
END
ELSE
BEGIN
INSERT INTO Table1 (Id, Column1) VALUES (@id, @newValue)
END
This one is good if you know that in most of the cases a row will not exist and insert will be performed. For such cases it executes SELECT statement followed by INSERT statement. That results in less expensive lock comparing to UPDATE + INSERT in previous method.

Monday, June 28, 2010

Correct event invocation

Be aware that if there are no subscribers a .NET event will be null. Therefore when raising the event from C# test it for null first.
public event EventHandler SelectedNodeChanged;

protected virtual void OnSelectedNodeChanged(object sender, EventArgs e)
{
//Event will be null if there are no subscribers
if (SelectedNodeChanged != null)
{
SelectedNodeChanged(this, e);
}
}
However in multithreaded application the last subscriber can unsubscribe immediately after the null check and before the event is raised. To avoid a null reference exception make a temporary copy of the event.
public event EventHandler SelectedNodeChanged;

protected virtual void OnSelectedNodeChanged(object sender, EventArgs e)
{
//Make a temporary copy of the event to avoid possibility of
//a race condition if the last subscriber unsubscribes
//immediately after the null check and before the event is raised.
EventHandler handler = SelectedNodeChanged;

//Event will be null if there are no subscribers
if (handler != null)
{
handler(this, e);
}
}

Organize Usings

if you are on VS 2008, you can right-click anywhere inside your .cs source file and choose Organize Usings > Remove Unused Usings, Sort, or Remove and Sort.good way to clean up your usings and will speed up your build.

Debugger variable $exception

If your catch block do nothing with caught exception you may declare block argument without name (to avoid warning message "CS0168: The variable 'ex' is declared but never used"):
try
{
...
}
catch (Exception)
{
// deliberately suppressing all exceptions
}
But one day during debugging you may actually want to examine Exception. Since you don't have variable where exception is stored you can use debugger variable $exception provided by the Visual Studio.NET 2005 Debugger to examine the exception in a catch block. Just add it to Watch Window.

Thursday, June 24, 2010

Label to a form input field

If you set a label to a form element set the AssociatedControlID property. This will force the label to render as label rather than span. A benefit of using the AssociatedControlID property is that clicking a label when this property is set automatically changes the form focus to the associated form input.

Wednesday, June 23, 2010

Turn off Session State if you're not using it

Since ASP.NET Session State is on by default, you pay the cost in memory even if you don't use it. If you're not using Session State, turn it off and save yourself the overhead. There are serveral ways to do this:
If you're not using Session State at all, turn it off completely via web.config file:



If you're using Session State, but it's required only for a few pages, then first turn it off for all pages:



then enable it for a specific page:


obviously such optimization makes sense only for high-traffic web sites.

Tuesday, June 22, 2010

Return read-only collection if you want to control its modification

Let's review the following example:
public class Order
{
private List _orderItems = new List();

public ReadOnlyCollection OrderItems
{
get { return _orderItems.AsReadOnly(); }
}

public void AddOrderItem(OrderItem orderItem)
{
...
_orderItems.Add(orderItem);
}
}

The class has a public property of a collection type and I want to have “controlled access “to this collection. What I mean is, that a consumer of these classes should not to add an OrderItem to the collection directly . since some additional actions need to be executed. He should always use the AddOrderItem method id he wants to add an OrderItem To the Order.

In Such cases keep the collection private, create the necessary methods to provide the necessary controlled access to the collection and create a public property which returns a read-only instance of the collection. So that you can iterate through the collection, change existing instances of objects within the collection, get the number of objects that are in the collection etc

Monday, June 21, 2010

Speed testing in .NET - System.Diagnostics.Stopwatch

System.Diagnostics.Stopwatch is a replacement for what most people probably do to identify the time spent on excecuting a method. The process usually goes something like: create a DateTime.Now value at the start and then subtract the ending DateTime.Now to get the TimeDuration value that elapsed.

As an alternative, the Stopwatch class was built using low-level API calls, with less overhead than other .NET methods. If the hardware and Windows version of the computer support a high-resolution performance counter, it will use this counter instead of the standard PC clock.

Here is a simple example:

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

watch.Start();



//do my stuff

...



watch.Stop();

MessageBox.Show("Time spent: " + watch.Elapsed.ToString());

Use Tab twice to get the code snippets that are available within code editor

Take for example of foreach loop, just press 2 tabs after typing "fore"... that's it you got the code snippet as mentioned below:


Other useful code snippets are:
•for - for loop
•while - for while loop
•equals - snippet for implementing Equals() according to quidelines
•prop - for public property and backing field
•tryf - for try finally
•indexer - for indexer

Tip Of the Day

?? operator (C#)
The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand. For example:

int? x = null;

...

// y = x, unless x is null, in which case y = -1.

int y = x ?? -1;

The ?? operator also works with reference types:

//message = param, unless param is null

//in which case message = "No message"

string message = param ?? "No message";

Sunday, June 20, 2010

My first day on blog

Hello

My name is Pawan Tiwari Currently working as a Senior Software engineer.
I am writing this blog to share my views and knowledge on Dot net technology and also want your feedback on my shared views.
This will help me to get time for my knowledge inhancement on regular basis.

Thanks