Saturday, January 17, 2009

Other Usage of using Statements

I've explained basics of using Statement in C#. In addition to this, there are some other ways to implement using Statement.

1) We can declare multiple objects within a using statement.

Code Example:


using (File File1 = new File(),File File2 = new File())
{
// Use File1 and File2.
}



2) We can instantiate the resource object outside the using Statement block and then pass the variable to the using statement, but this is not a good practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, it may cause an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.

Code Example:

File File3 = new File();
using (File3) // not recommended
{
// use File3
}
// File3 is still in scope
// but it may throw an exception.

using Statement in C#

using statement is a very important feature supported by C#. It ensures no Memory Leak and no Exceptions due to unmanaged resources. It is very important to free the memory once object is used and is not needed anymore, or to Dispose the resource. using statement does the same thing for you allowing coder to concentrate on other aspects of the project taking responsibility to free the resources occupied.

generally this is used for all places where we are using a connection to the underlaying datasource.

Example

using ( SqlConnection connection = new SqlConnection(connectionString) )
{
SqlCommand cmd = new SqlCommand(commandString, connection);
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// TODO : Do some work with each record.
}
}
}

Here, the SqlDataReader object is created with "using" statement, and hence there's no need to close the reader and underlaying connection explicitly. If we use the ILDASM to see the generated IL Code, we can see the using statement calling the Dispose method. If we don't use the "using" statement, then the alternative way is to use try-catch-finally block to ensure no exception thrown and resources are freed, that contains more code than the code block above. compare the code block below.

It's a always a good practice to use using statement, when using an IDisposable object. The using statement calls the Dispose method on the object in the correct way, and it also causes the object itself to go out of scope as soon as Dispose is called and allow GC to do his job. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

Notes:
* using Directive is used differently than using Statement
* Other Usage of using Statement

using Directive in C#

using Directive:
Basically it allows to the coder to use various objects, types or classes available in a name space whitout fully qualifying the object. this will reduce the code drastically if you are having some great number of lines being coded.

using Directive is totally different from using Statement in C# and it has two very basic usages

1) user do not have to qualify the use of a type in that namespace.
For example:

using System.Text;
StringBuilder sbTest = new StringBuilder();

instead of writing the whole namespace.
System.Text.StringBuilder sbTest = new System.Text.StringBuilder();

2) It allows to create an alias for a namespace need to be used.
For example:

using DAL = MyCompany.MyProject.DAL;

Important:

* It can't be used out side of file its being declared. The scope is limited to the file in which it is being declared
* The using keyword is also used to create using statements.

Monday, January 12, 2009

Difference between scope_identity(), @@Identity & ident_current()

First of all, let me explain two very basic concepts - what is Session and what is Scope:

Session: the current connection that's executing the command.
Scope: immediate context of a command.

For example:

1) Two commands executed within same stored procedures are in same Scope
2) Two stored procedure executing using same connection are in same Session.

As these two concepts are defined, here are the differences between the three identity retrieval methods:

* @@identity returns the last identity value generated in this session but any scope
* scope_identity() returns the last identity value generated in this session and this scope
* ident_current() returns the last identity value generated for a particular table in any session and any scope

Note: scope_identity() & iden_current() is applicable to SQL Server 2005 only

Friday, January 9, 2009

Difference between Mutable and Immutable

Let me first explain the general meaning of Mutable and Immutable.

Mutable: Capable of or tending to change in form or quality or nature

ImMutable: Not subject or susceptible to change or variation in form or quality or nature

the same thing in terms of .NET

ImMutable: String is a ImMutable Object. Whenever you refer string in your code, it will create a new object in memory. Means, a new memory location will be occupied to that string.

for Example: str1 = str1 + str2.

this operation require 3 memory locations not 2

Mutable: Sytem.Text.StringBuilder is Mutable Object. when you append string to string builder, or alter it's text, it will always use the single memory location. This is very important when you need to work on a large set of string operation.

Note: always use StringBuilder whenever the operation involve large set of string operations, there will be a big difference in performance if you'll use string instead.

Center Content in Content Place Holder

Review the MasterPage Code below to make your content stick to centre.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage_MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<table cellpadding="0" cellspacing="0" border="1" width="90%">
<tr>
<td style="background-color: Black; width: 20%">
</td>
<td style="width: 80%">
<div style="text-align: center;">
<asp:ContentPlaceHolder ID="UserContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>
</div>
</td>
<td style="background-color: Black; width: 20%"></td>
</tr>
</table>
</form>
</body>
</html>

Tuesday, January 6, 2009

Undocumented Object Properties

I was inspired to write this post because I tried a lot to find this out. During debugging I needed it badly. There are many undocumented properties, that you can’t just alert. Sometimes, even you are in need of finding out a property/attribute of the object that accomplish your need. The code snippet below will list all the properties of any object with type. I’m sure this will be quite helpful to others too.

function ListAttributes(obj,debuggerId){

var result = "";
for (var i in obj)

result += "obj." + i + " = " + obj[i] + "";


document.getElementById(debuggerId).innerHTML=result;



}

Parameter List:

Obj = object to be reviewed
debuggerId = Id of the div or any other element, insider which you need to write the complete list of all attributes

Difference between Session.Abandon & Session.Clear

Session.Abandon()

The Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.

When the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.

For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.

<%
Session.Abandon
Session("MyName") = "Mary"
Reponse.Write(Session("MyName"))
%>

If you access the variable MyName on a subsequent Web page, it is empty. This is because MyName was destroyed with the previous Session object when the page containing the previous example finished processing.
The server creates a new Session object ( with a new SessionID) when you open a subsequent Web page, after abandoning a session. You can store variables and objects in this new Session object.

Session.Clear()

The Clear method removes all keys and values from the current session. Compare to Abandon method, it doesn't create the new session, It just make all variables in session to NULL.

How to find .NET Version Programaticallly?

It's really very simple. Here is the code snippet for the same.

VB.NET

Response.Write(System.Environment.Version.ToString())

C#

Response.Write(System.Environment.Version.ToString());

ASP.NET Viewstate

Why Viewstate?

As we know, HTTP is a state less protocol. State less means the protocol couldn't maintain state between request and response we must have to use some mechanism to accomplish this. (Like query string, cookie, etc.). When a request is sent from "Client Machine" to "Server Machine" based on the request header details, Server handover processing of request to appropriate process on the server. If the same "Client Machine" send subsequent request for the same Page, Server couldn't recognize that request is from the same machine. He just processes the request, and sends the response regardless of "Client Machine".

Consider we need to post some text fields on a page using classic ASP. Suppose some validations fails, so the response generated from server will contain on the Page HTML without the data in the text fields, as it doesn't know the present status of the page at client end. Think about the user who has filled almost 50 fields on the page, and page returns with all blank field and a validation message on top saying no data saved!!!

This was the main reason why Viewstate is introduced - to maintain the state of the page between round-trip.

What is Viewstate?

Viewstate is the ASP.NET state management technique introduced to maintain current page state between round-trip. It maintains state of the fields, using a hidden field with name = "__VIEWSTATE". It uses base64 encoding to store the state. Whenever the page is posted to the server, view state is also posted back in addition to the posted data. Click here to check more details on how hidden field is posted back to server

Here is the sample of Viewstate stored at the client side.

<input type="hidden" name="__VIEWSTATE" value="dDwyNTA3OTU0NDM7Oz7t5TntzkOUeB0QVV6FT2hvQwtpPw==" />

Important: As Viewstate is posted to the server each time, It should be used very carefully. Bulky Viewstate can result in performance issues. If you don't want to maintain the Viewstate, include the directive <%@ Page EnableViewState="false"%> at the top of an .aspx page If you do not want to maintain Viewstate for any control add the attribute EnableViewState="false" to any control.