this.GVMyCount.Rows.Count;
this is used to count the No. of Items (Rows) in the GridView.
Wednesday, November 11, 2009
Validation is not working in the Page !!
When validation is not working or not being fire , then where we use (Page.IsValid)? Use it at the Button for which you are using.
Use this when validation is not working on the page -
if (Page.IsValid)
{
}
On the Button_Submit.
When we have used validation on the page and validation is not working on Button click. Then use use Page.Isvalid on the Buttion Click.. Like that..
Protected void btnSubmit_Click(Object sender, EventArgs e)
{
if(Page.IsValid)
{
}
}
Use this when validation is not working on the page -
if (Page.IsValid)
{
}
On the Button_Submit.
When we have used validation on the page and validation is not working on Button click. Then use use Page.Isvalid on the Buttion Click.. Like that..
Protected void btnSubmit_Click(Object sender, EventArgs e)
{
if(Page.IsValid)
{
}
}
Date Time
# Date should always present in the user part in the dd/mm/yyyy formate.
# Date should always saved or inserted in the Database MM/dd/yyyy formate.
# Date is always present in the presentation form as - dd/mm/yyyy. So we have to convert it accordingly.
# Date should always saved or inserted in the Database MM/dd/yyyy formate.
# Date is always present in the presentation form as - dd/mm/yyyy. So we have to convert it accordingly.
Different Date Time Formate !!
lblDate.Text=DateTime.Today.TolongDateString();
This will show the Formate of Date time like that : Sunday, August 02, 2008
This will show the Formate of Date time like that : Sunday, August 02, 2008
Inset Date Through Query !!
string str = "insert into Registration (cust_id, cust_name, cust_date)
vaues ('"+txtname.Text+"','"+DateTime.Today.Date.Tostring()+"')"
vaues ('"+txtname.Text+"','"+DateTime.Today.Date.Tostring()+"')"
AddNews.aspx !!
Relation Between Insert Procedura and Page ;
Sql cmd =new SqlCommand ("insNews", Sqlcon)
Sqlcmd.CommandType=CommandType.StoreProcedure;
Sqlcmd.Parameters.AddWithVales("@headline",txtHeadline.Text);
string strtxtdate=txtDate.Text.Substring(3,2)+ "/" + txtDate.Text.Substring(0,2)+ "/" + txtDate.Text.Substring(6,4);
Sqlcmd.Parameters.Addwithvalue("@date",strtxtdate.ToString());
Sqlcmd.Parameters.Addwithvale("@active","");
Sqlcmd.Parameters.Addwithvalue("@delete","");
strImage=System.IO.Path.GetFileName(uploadImage.Post.PostedFile.fileName);
string savelocation= server.Mathpath("upload")+ "\" strImage;
uploadImage.Postfile.SaveAs(Savelocation);
Sqlcmd.Paremeters.Addwithvales("@image", stringImage.Tostring());
Sql cmd =new SqlCommand ("insNews", Sqlcon)
Sqlcmd.CommandType=CommandType.StoreProcedure;
Sqlcmd.Parameters.AddWithVales("@headline",txtHeadline.Text);
string strtxtdate=txtDate.Text.Substring(3,2)+ "/" + txtDate.Text.Substring(0,2)+ "/" + txtDate.Text.Substring(6,4);
Sqlcmd.Parameters.Addwithvalue("@date",strtxtdate.ToString());
Sqlcmd.Parameters.Addwithvale("@active","");
Sqlcmd.Parameters.Addwithvalue("@delete","");
strImage=System.IO.Path.GetFileName(uploadImage.Post.PostedFile.fileName);
string savelocation= server.Mathpath("upload")+ "\" strImage;
uploadImage.Postfile.SaveAs(Savelocation);
Sqlcmd.Paremeters.Addwithvales("@image", stringImage.Tostring());
Insert Procedure !!
CREATE PROCEDURE insNews
(
@headline varchar (50),
@date datetime,
@active varchar(3),
@delete varchar (3),
@image varchar (50),
)
as
inseart into tblNewsMaster
(
nm_headline,
nm_date,
nm_activce,
nm_delete,
image
)
values
(
@headline,
@date,
'Yes'
'No'
@Image
)
Go
(
@headline varchar (50),
@date datetime,
@active varchar(3),
@delete varchar (3),
@image varchar (50),
)
as
inseart into tblNewsMaster
(
nm_headline,
nm_date,
nm_activce,
nm_delete,
image
)
values
(
@headline,
@date,
'Yes'
'No'
@Image
)
Go
Update Procedure !!
CREATE PROCEDURE adminprojectupdate
(
@code varchar (50),
@startdate datetime,
@enddate datetime,
@amount varchar(50),
@title varchar (50),
@client varchar (200),
@des varchar (200),
pid int
)
as
update tblprojectmaster
pr_code=@code,
pr_startDate=@startDate,
pr_endDate=@amont,
pr_title=@title,
pr_client=@client,
pr_desc=@desc;
where pr_id=@pid
Go
(
@code varchar (50),
@startdate datetime,
@enddate datetime,
@amount varchar(50),
@title varchar (50),
@client varchar (200),
@des varchar (200),
pid int
)
as
update tblprojectmaster
pr_code=@code,
pr_startDate=@startDate,
pr_endDate=@amont,
pr_title=@title,
pr_client=@client,
pr_desc=@desc;
where pr_id=@pid
Go
Tuesday, August 25, 2009
What is the difference between int.parse() and convert.int32()
If we want to convert a string value (Lets say we have a string “23”) to integer we have 2 options. One is to use the Int.Parse method and other is to use the Convert.ToInt32.
The real query with every one was what is the difference between the two. The answer is null handling. The difference between the 2 is the manner in which null is handled. If you pass a null value to convert.ToInt32 method it will return back 0. But the same is not true with Int.Parse. If we pass null to Int.Parse method it will throw an ArgumentNullException exception.
Although Convert.ToInt32 method does not throw an exception but it can have a big drawbacks. If you use it on a query string value(where u are also expecting the value 0) then the Convert.ToInt32 might cause programmatic error.
######################################################################################
The difference lies in the way both handles NULL value.
When encountered a NULL Value, Convert.ToInt32 returns a value 0. On other hand,Parse is more sensitive and expects a valid value. So it would throw an exception when you pass in a NULL.
string stringInt = "01234";
int iParse = int.Parse(stringInt);
int iConvert = Convert.ToInt32(stringInt);
##################################################################################3
string MyString = "12345";
int MyInt = int.Parse(MyString);
MyInt++;
Console.WriteLine(MyInt);
// The result is "12346".
#################################################################################
int.Parse for Integer Conversion in C#
--------------------------------------
1. Using int.Parse
First, here we see the int.Parse method. int.Parse is the simplest method, and is also the author's favorite for many situations. It throws exceptions on invalid input, which can be slow if they are common. It is does not contain any internal null checks.
=== Example program that uses int.Parse (C#) ===
using System;
class Program
{
static void Main()
{
// Convert string to number.
string text = "500";
int num = int.Parse(text);
Console.WriteLine(num);
}
}
=== Output of the program ===
500
2. Using Convert.ToInt32
Third, we look at the Convert.ToInt32 method. Convert.ToInt32, along with its siblings Convert.ToInt16 and Convert.ToInt64, is actually a static wrapper method for the int.Parse method. It can be slower than int.Parse if the surrounding code is equivalent.
=== Example program that uses Convert.ToInt32 (C#) ===
using System;
class Program
{
static void Main()
{
// Convert 'text' string to an integer with Convert.ToInt32.
string text = "500";
int num = Convert.ToInt32(text);
Console.WriteLine(num);
}
}
=== Output of the program ===
500
3. Which method should I use?
The it's recommendation is to use int.Parse when your input will be valid, as it makes for simpler calling code. It isn't always perfect, but it is a winner. On the other hand, use int.TryParse when you will be dealing with corrupt data.
Good Website : http://dotnetperls.com/datetime-1
The real query with every one was what is the difference between the two. The answer is null handling. The difference between the 2 is the manner in which null is handled. If you pass a null value to convert.ToInt32 method it will return back 0. But the same is not true with Int.Parse. If we pass null to Int.Parse method it will throw an ArgumentNullException exception.
Although Convert.ToInt32 method does not throw an exception but it can have a big drawbacks. If you use it on a query string value(where u are also expecting the value 0) then the Convert.ToInt32 might cause programmatic error.
######################################################################################
The difference lies in the way both handles NULL value.
When encountered a NULL Value, Convert.ToInt32 returns a value 0. On other hand,Parse is more sensitive and expects a valid value. So it would throw an exception when you pass in a NULL.
string stringInt = "01234";
int iParse = int.Parse(stringInt);
int iConvert = Convert.ToInt32(stringInt);
##################################################################################3
string MyString = "12345";
int MyInt = int.Parse(MyString);
MyInt++;
Console.WriteLine(MyInt);
// The result is "12346".
#################################################################################
int.Parse for Integer Conversion in C#
--------------------------------------
1. Using int.Parse
First, here we see the int.Parse method. int.Parse is the simplest method, and is also the author's favorite for many situations. It throws exceptions on invalid input, which can be slow if they are common. It is does not contain any internal null checks.
=== Example program that uses int.Parse (C#) ===
using System;
class Program
{
static void Main()
{
// Convert string to number.
string text = "500";
int num = int.Parse(text);
Console.WriteLine(num);
}
}
=== Output of the program ===
500
2. Using Convert.ToInt32
Third, we look at the Convert.ToInt32 method. Convert.ToInt32, along with its siblings Convert.ToInt16 and Convert.ToInt64, is actually a static wrapper method for the int.Parse method. It can be slower than int.Parse if the surrounding code is equivalent.
=== Example program that uses Convert.ToInt32 (C#) ===
using System;
class Program
{
static void Main()
{
// Convert 'text' string to an integer with Convert.ToInt32.
string text = "500";
int num = Convert.ToInt32(text);
Console.WriteLine(num);
}
}
=== Output of the program ===
500
3. Which method should I use?
The it's recommendation is to use int.Parse when your input will be valid, as it makes for simpler calling code. It isn't always perfect, but it is a winner. On the other hand, use int.TryParse when you will be dealing with corrupt data.
Good Website : http://dotnetperls.com/datetime-1
Friday, August 14, 2009
What is ItemCommand ?
Dev Palmistry 
DataGrid.ItemCommand Event
System.Web.UI.WebControls Namespace DataGrid Class
Occurs when a button within a DataGrid control is clicked.
[ VB ]
Public Event ItemCommand As DataGridCommandEventHandler
[ C# ]
public event DataGridCommandEventHandler ItemCommand;
[ C++ ]
public: __event DataGridCommandEventHandler* ItemCommand;
In [ JScript ], you can handle the events defined by a class, but you cannot define your own.
Remarks
The ItemCommand event is raised whenever any button associated with an item in the DataGrid is clicked. This provides for programmatically determining which specific command button is clicked and take appropriate action. This event is commonly used to handle button controls with a given CommandName value in the DataGrid control.
Event Data
Information related to the ItemCommand event is passed via a DataGridCommandEventArgs object to the method assigned to handle the event. The following DataGridCommandEventArgs properties provide information specific to this event.
Property Description
CommandSource Gets the source of the command.
Item Gets the DataGridItem associated with the event.
DataGrid.ItemCommand Event
System.Web.UI.WebControls Namespace DataGrid Class
Occurs when a button within a DataGrid control is clicked.
[ VB ]
Public Event ItemCommand As DataGridCommandEventHandler
[ C# ]
public event DataGridCommandEventHandler ItemCommand;
[ C++ ]
public: __event DataGridCommandEventHandler* ItemCommand;
In [ JScript ], you can handle the events defined by a class, but you cannot define your own.
Remarks
The ItemCommand event is raised whenever any button associated with an item in the DataGrid is clicked. This provides for programmatically determining which specific command button is clicked and take appropriate action. This event is commonly used to handle button controls with a given CommandName value in the DataGrid control.
Event Data
Information related to the ItemCommand event is passed via a DataGridCommandEventArgs object to the method assigned to handle the event. The following DataGridCommandEventArgs properties provide information specific to this event.
Property Description
CommandSource Gets the source of the command.
Item Gets the DataGridItem associated with the event.
What is the namespace of StringBuilder ?
The System.Text is the namespace are used in StringBuilder
The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
You can create a new instance of the StringBuilder object by initializing your variable with one of the overloaded constructor methods, as illustrated in the following code example.
[ C# ]
StringBuilder myStringBuilder = new StringBuilder ( "Hello World!" );
The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
You can create a new instance of the StringBuilder object by initializing your variable with one of the overloaded constructor methods, as illustrated in the following code example.
[ C# ]
StringBuilder myStringBuilder = new StringBuilder ( "Hello World!" );
Setting and Retrieving the Connection String Using Web.Cofig !!
In Connecting to a Database, we have shown the essential steps to establish and open a connection to a data source from within a Web Forms page. In this application, we use a slightly different approach of storing the connection string in the application configuration file ( web.config ), thereby making the connection string globally available to any page in the application. This technique is basically implemented as follows.
In the web.config file for the application, include the following:
configuration>
appsettings>
add key="myDbConn" value="server=servername; uid=userid; pwd=password; database=dbname">
/add>
/appsettings>
changing the values ( shown in italics ) to correspond to your settings.
Then on each page that you need to initialize a connection, use:
SqlConnection myConn = new SqlConnection
( ConfigurationSettings.AppSettings [ "myDbConn" ] );
In the web.config file for the application, include the following:
configuration>
appsettings>
add key="myDbConn" value="server=servername; uid=userid; pwd=password; database=dbname">
/add>
/appsettings>
changing the values ( shown in italics ) to correspond to your settings.
Then on each page that you need to initialize a connection, use:
SqlConnection myConn = new SqlConnection
( ConfigurationSettings.AppSettings [ "myDbConn" ] );
Monday, August 3, 2009
N-Tier Architecture !!
Dev Palmistry 
3-Tier Architecture in ASP.NET with C#
3-Tier architecture is a very well know buzz word in the world of software development whether it web based or desktop based. In this article I am going to show how to design a web application based on 3-tier architecture.
Introduction
3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL) or Business Logic Layer and Data Access Layer (DAL).
Presentation Layer (UI)
Presentation layer cotains pages like .aspx or windows form where data is presented to the user or input is taken from the user.
Business Access Layer (BAL) or Business Logic Layer
BAL contains business logic, validations or calculations related with the data, if needed. I will call it Business Access Layer in my demo.
Data Access Layer (DAL)
DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc). For this demo application, I have taken a very simple example. I am assuming that I have to play with record of persons (FirstName, LastName, Age) and I will refer only these data through out this article.
Designing 3-Tier Architecture
For the ease of understanding, I have created BAL, DAL into the App_Code folder. In real scenario, you should create separate projects for BAL, DAL (as Class Library) and UI (as Web project) and reference your BAL into UI.

Data Access Layer
Lets proceed with desiging 3-Tier architecture. To do that lets proceed with DAL, BAL and then UI. Add a class named by right clicking App_Code folder. (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for DAL and add reference of this project into your BAL.) and copy-paste folowing code (Your can overwrite your default written code for the class file by pasting this code). Here, I have assumed that you will create the respective stored procedure yourself into the database or you may download attachment from http://www.dotnetfunda.com/articles/article18.aspx article and look for App_Data folder for complete database structure and stored procedure for this article.
Data Access Layer (DAL)
Code for Data Access Layer
In the above code, I have a member variable called connStr that is getting database connection string from my web.config file that is being used through out the class. I have separate method for inserting, deleting, updating records into database and loading records from database. I am not goint into details of how I am connecting database and manipulating the data just to make this tutorials short.
Business Access Layer (BAL)
Now, create a class named PersonBAL3 into App_Code folder by right clicking it and write respective methods for calling Insert, Delete, Update and Load methods of Data Access Layer class file (PersonDAL3) (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for BAL and add reference of this project into your Presentation Layer). As we don't have any business logic here so simply instantiate the PersonDAL3 class of DAL and call methods. Below is the code for BAL (Your can overwrite your default written code for the class file by pasting this code).
Till now we haev our Business Access Layer and Database Access Layer ready. Now we have to write our Presentation Layer that will use our Business Access Layer methods. Lets create a form that will have three textboxes for FirstName, LastName and Age.
Presentation Layer

Create an Insert.aspx page (make is as Startup page) and copy paste following code to bring the insert form something like displaying in the picture.
Code for Insert Record form
Now, lets write method that will fire when Submit button will be clicked on the from.
Code for AddRecords method
protected void AddRecords(object sender, EventArgs e)
{
//Lets validate the page first
if (!Page.IsValid)
return;
int intResult = 0;
// Page is valid, lets go ahead and insert records
// Instantiate BAL object
PersonBAL3 pBAL = new PersonBAL3();
// Instantiate the object we have to deal with
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
int age = Int32.Parse(txtAge.Text);
try
{
intResult = pBAL.Insert(firstName, lastName, age);
if (intResult > 0)
lblMessage.Text = "New record inserted successfully.";
else
lblMessage.Text = "FirstName ["+ txtFirstName.Text +"] alredy exists, try another name";
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
pBAL = null;
}
}
In the above code, first I am validating the page by using Page.IsValid method just to check if correct data has been entered. Then I have instantiated PersonBAL3 and calling Insert method of it (pBAL.Insert) by passing firstName, lastName, age as parameter.
Dispalying Records into GridView

Create a .aspx file called List.aspx and create a GridView something like displayed into the picture. To list the record into GridView that will also enable us to Edit, Delete record, copy paste following code.
Code for GridView
DataKeyNames="PersonID" AutoGenerateEditButton="True" AutoGenerateColumns="False"
OnRowEditing="EditRecord" OnRowUpdating="UpdateRecord" OnRowCancelingEdit="CancelRecord"
OnRowDeleting="DeleteRecord" PageSize="5" >
<%# Eval("FirstName") %>
asp:TextBox ID="txtFName" runat="Server" Text='<%# Eval("FirstName") %>'>
<%# Eval("LastName") %>
asp:TextBox ID="txtLName" runat="Server" Text='<%# Eval("LastName") %>'>
<%# Eval("Age") %>
asp:TextBox ID="txtAge" runat="Server" Text='<%# Eval("Age") %>'>
Code to Load records and Displaying Records into GridView
private DataTable BindGrid()
{
PersonBAL3 p = new PersonBAL3();
try
{
DataTable dTable = p.Load();
GridView1.DataSource = dTable;
GridView1.DataBind();
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
p = null;
}
return dTable;
}
In the above method I am instantiating PersonBAL3 class and calling Load method to get the record into DataTable and binding it into GridView.
Code to Delete Records
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
// instantiate BAL
PersonBAL3 pBAL = new PersonBAL3();
try
{
pBAL.Delete(personID);
lblMessage.Text = "Record Deleted Successfully.";
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
pBAL = null;
}
GridView1.EditIndex = -1;
// Refresh the list
BindGrid();
}
Above method will fire when Delete link will be clicked on the GridView. In the above code, I am instantiating PersonBAL3 and calling Delete method by passing personID as parameter so that select reocrds will be deleted from datbase.
Above method will fire when Update link will be clicked for a particular row of the GridView in edit mode. In the above method, I am instantiating PersonBAL3 and calling the Update method by p[assing required parameters.
Now we have all set to go, now just run your project and try inserting records. You can also navigate to another page your created (list.aspx) and try updating, deleting records.
Conclusion
By using 3-Tier architecture in your project you can achive
1. Seperation - the functionality is seperated from the data access and presentation so that it is more maintainable
2. Independence - layers are established so that if one is modified (to some extent) it will not affect other layers.
3. Reusability - As the layers are seperated, it can exist as a module that can be reused by other application by referencing it.
Hope this article helped you understanding 3-Tier architecture and desiging it.
Thanks and Happy Coding !!!
3-Tier Architecture in ASP.NET with C#
3-Tier architecture is a very well know buzz word in the world of software development whether it web based or desktop based. In this article I am going to show how to design a web application based on 3-tier architecture.
Introduction
3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL) or Business Logic Layer and Data Access Layer (DAL).
Presentation Layer (UI)
Presentation layer cotains pages like .aspx or windows form where data is presented to the user or input is taken from the user.
Business Access Layer (BAL) or Business Logic Layer
BAL contains business logic, validations or calculations related with the data, if needed. I will call it Business Access Layer in my demo.
Data Access Layer (DAL)
DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc). For this demo application, I have taken a very simple example. I am assuming that I have to play with record of persons (FirstName, LastName, Age) and I will refer only these data through out this article.
Designing 3-Tier Architecture
For the ease of understanding, I have created BAL, DAL into the App_Code folder. In real scenario, you should create separate projects for BAL, DAL (as Class Library) and UI (as Web project) and reference your BAL into UI.
Data Access Layer
Lets proceed with desiging 3-Tier architecture. To do that lets proceed with DAL, BAL and then UI. Add a class named by right clicking App_Code folder. (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for DAL and add reference of this project into your BAL.) and copy-paste folowing code (Your can overwrite your default written code for the class file by pasting this code). Here, I have assumed that you will create the respective stored procedure yourself into the database or you may download attachment from http://www.dotnetfunda.com/articles/article18.aspx article and look for App_Data folder for complete database structure and stored procedure for this article.
Data Access Layer (DAL)
Code for Data Access Layer
In the above code, I have a member variable called connStr that is getting database connection string from my web.config file that is being used through out the class. I have separate method for inserting, deleting, updating records into database and loading records from database. I am not goint into details of how I am connecting database and manipulating the data just to make this tutorials short.
Business Access Layer (BAL)
Now, create a class named PersonBAL3 into App_Code folder by right clicking it and write respective methods for calling Insert, Delete, Update and Load methods of Data Access Layer class file (PersonDAL3) (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for BAL and add reference of this project into your Presentation Layer). As we don't have any business logic here so simply instantiate the PersonDAL3 class of DAL and call methods. Below is the code for BAL (Your can overwrite your default written code for the class file by pasting this code).
Till now we haev our Business Access Layer and Database Access Layer ready. Now we have to write our Presentation Layer that will use our Business Access Layer methods. Lets create a form that will have three textboxes for FirstName, LastName and Age.
Presentation Layer
Create an Insert.aspx page (make is as Startup page) and copy paste following code to bring the insert form something like displaying in the picture.
Code for Insert Record form
| Add Records | ||
|---|---|---|
First Name: | Display="dynamic"> | |
Last Name: | Display="dynamic"> | |
Age: | Display="dynamic"> Operator="DataTypeCheck" Type="Integer"> | |
Now, lets write method that will fire when Submit button will be clicked on the from.
Code for AddRecords method
protected void AddRecords(object sender, EventArgs e)
{
//Lets validate the page first
if (!Page.IsValid)
return;
int intResult = 0;
// Page is valid, lets go ahead and insert records
// Instantiate BAL object
PersonBAL3 pBAL = new PersonBAL3();
// Instantiate the object we have to deal with
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
int age = Int32.Parse(txtAge.Text);
try
{
intResult = pBAL.Insert(firstName, lastName, age);
if (intResult > 0)
lblMessage.Text = "New record inserted successfully.";
else
lblMessage.Text = "FirstName ["+ txtFirstName.Text +"] alredy exists, try another name";
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
pBAL = null;
}
}
In the above code, first I am validating the page by using Page.IsValid method just to check if correct data has been entered. Then I have instantiated PersonBAL3 and calling Insert method of it (pBAL.Insert) by passing firstName, lastName, age as parameter.
Dispalying Records into GridView
Create a .aspx file called List.aspx and create a GridView something like displayed into the picture. To list the record into GridView that will also enable us to Edit, Delete record, copy paste following code.
Code for GridView
DataKeyNames="PersonID" AutoGenerateEditButton="True" AutoGenerateColumns="False"
OnRowEditing="EditRecord" OnRowUpdating="UpdateRecord" OnRowCancelingEdit="CancelRecord"
OnRowDeleting="DeleteRecord" PageSize="5" >
<%# Eval("FirstName") %>
asp:TextBox ID="txtFName" runat="Server" Text='<%# Eval("FirstName") %>'>
<%# Eval("LastName") %>
asp:TextBox ID="txtLName" runat="Server" Text='<%# Eval("LastName") %>'>
<%# Eval("Age") %>
asp:TextBox ID="txtAge" runat="Server" Text='<%# Eval("Age") %>'>
Code to Load records and Displaying Records into GridView
private DataTable BindGrid()
{
PersonBAL3 p = new PersonBAL3();
try
{
DataTable dTable = p.Load();
GridView1.DataSource = dTable;
GridView1.DataBind();
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
p = null;
}
return dTable;
}
In the above method I am instantiating PersonBAL3 class and calling Load method to get the record into DataTable and binding it into GridView.
Code to Delete Records
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
// instantiate BAL
PersonBAL3 pBAL = new PersonBAL3();
try
{
pBAL.Delete(personID);
lblMessage.Text = "Record Deleted Successfully.";
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
pBAL = null;
}
GridView1.EditIndex = -1;
// Refresh the list
BindGrid();
}
Above method will fire when Delete link will be clicked on the GridView. In the above code, I am instantiating PersonBAL3 and calling Delete method by passing personID as parameter so that select reocrds will be deleted from datbase.
Above method will fire when Update link will be clicked for a particular row of the GridView in edit mode. In the above method, I am instantiating PersonBAL3 and calling the Update method by p[assing required parameters.
Now we have all set to go, now just run your project and try inserting records. You can also navigate to another page your created (list.aspx) and try updating, deleting records.
Conclusion
By using 3-Tier architecture in your project you can achive
1. Seperation - the functionality is seperated from the data access and presentation so that it is more maintainable
2. Independence - layers are established so that if one is modified (to some extent) it will not affect other layers.
3. Reusability - As the layers are seperated, it can exist as a module that can be reused by other application by referencing it.
Hope this article helped you understanding 3-Tier architecture and desiging it.
Thanks and Happy Coding !!!
N-Tier Architecture !!
Dev Palmistry 
What is n-Tier Architecture?
This is a very important topic to consider when developing an application. Many elements need to be considered when deciding on the architecture of the application, such as performance, scalability and future development issues. When you are deciding on which architecture to use, first decide on which of the three aforementioned elements you think is most valuable -- as some choices you make will impact on others. For example, some choices that boost performance will impact on the scalability or future development of your design, etc.
Here we will talk generally about what n-Tier architecture is, and then we will have a look at different n-Tier architectures you can use to develop ASP.NET applications and issues that arise relating to performance, scalability and future development issues for each one.
Firstly, what is n-Tier architecture? N-Tier architecture refers to the architecture of an application that has at least 3 "logical" layers -- or parts -- that are separate. Each layer interacts with only the layer directly below, and has specific function that it is responsible for.
Why use n-Tier architecture? Because each layer can be located on physically different servers with only minor code changes, hence they scale out and handle more server load. Also, what each layer does internally is completely hidden to other layers and this makes it possible to change or update one layer without recompiling or modifying other layers.
This is a very powerful feature of n-Tier architecture, as additional features or change to a layer can be done without redeploying the whole application. For example, by separating data access code from the business logic code, when the database servers change you only needs to change the data access code. Because business logic code stays the same, the business logic code does not need to be modified or recompiled.
[Note] tier and layer mean the same thing [End Note]
An n-Tier application usually has three tiers, and they are called the presentation tier, the business tier and the data tier. Let's have a look at what each tier is responsible for.
Presentation Layer
Presentation Layer is the layer responsible for displaying user interface and "driving" that interface using business tier classes and objects. In ASP.NET it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.
Business Tier
Business Tier is the layer responsible for accessing the data tier to retrieve, modify and delete data to and from the data tier and send the results to the presentation tier. This layer is also responsible for processing the data retrieved and sent to the presentation layer.
In ASP.NET it includes using SqlClient or OleDb objects to retrieve, update and delete data from SQL Server or Access databases, and also passing the data retrieved to the presentation layer in a DataReader or DataSet object, or a custom collection object. It might also include the sending of just an integer, but the integer would have been calculated using the data in the data tier such as the number of records a table has.
BLL and DAL
Often this layer is divided into two sub layers: the Business Logic Layer (BLL), and the Data Access Layers (DAL). Business Logic Layers are above Data Access Layers, meaning BLL uses DAL classes and objects. DAL is responsible for accessing data and forwarding it to BLL.
In ASP.NET it might be using SqlClient or OleDb to retrieve the data and sending it to BLL in the form of a DataSet or DataReader. BLL is responsible for preparing or processing the data retrieved and sends it to the presentation layer. In ASP.NET it might be using the DataSet and DataReader objects to fill up a custom collection or process it to come up with a value, and then sending it to Presentation Layer. BLL sometimes works as just transparent layer. For example, if you want to pass a DataSet or DataReader object directly to the presentation layer.
Data Tier
Data tier is the database or the source of the data itself. Often in .NET it's an SQL Server or Access database, however it's not limited to just those. It could also be Oracle, mySQL or even XML. In this article we will focus on SQL Server, as it has been proven to be the fastest database within a .NET Application.
Logical Layers vs. Physical Layers (Distributed)
Logical Layers and Physical Layers are the ones that confuse people. Firstly, a logical layer means that layers are separate in terms of assembly or sets of classes, but are still hosted on the same server. Physical layer means that those assemblies or sets of classes are hosted on different servers with some additional code to handle the communication between the layers. E.g. remoting and web services.
Deciding to separate the layers physically or not is very important. It really depends on the load your application expects to get. I think it's worth mentioning some of the facts that might affect your decision.
Please DO note that separating the layers physically WILL slow your application down due to the delay in communicating between the servers throughout the network, so if you are using the physical layer approach, make sure the performance gain is worth the performance loss from this.
Hopefully you would have designed your application using the n-Tier approach. If this is the case, then note that you can separate the layers in the future.
Cost for deploying and maintaining physically separated applications is much greater. First of all, you will need more servers. You also need network hardware connecting them. At this point, deploying the application becomes more complex too! So decide if these things will be worth it or not.
Another fact that might affect your decision is how each of the tiers in the application are going to be used. You will probably want to host a tier on a separate server if more than 1 service is dependent on it, e.g. You might want to host business logic somewhere else if you have multiple presentation layers for different clients. You might also want a separate SQL server if you have other applications using the same data.
#####################################################################################
3-Tier Architecture
As the 3-Tier Architecture is the most commonly used architecture in the world, I will start my blogging on this topic.
I have noticed in the past 6 years of writing software that many developers ignore this software engineering paradigm for many reasons. Some include ...
*
Return on Investment
*
Software Lifecycle Turnaround time
*
Knowledgeable Resources
*
and the list goes on
I will discuss in more details of these reasons in another blog entry so back to the topic of 3-Tier architecture.
A 3-Tier architecture uses the Divide and Conquer strategy and is broken down into 3 logical layers.
*
Presentation Layer (PL)
*
Business Logic Layer (BLL)
*
Data Access Layer (DAL)
Ideally, each layer specializes in one or a handful of functionalities that service the upper layer. Each of the three layers should be designed so that the layer above it does not need to understand nor know the implementation details of any of the layers below it. This is accomplished by providing well defined interfaces that the above layers use. The advantage of "Programming to the Interface" is that, you can change the implementation details and still have the application work as defined. One caveat is that, if the interfaces change, then it will take more effort and time to update the layer above it. Therefore, when designing an application, its important to define the interfaces properly.
Here is an example:
public interface IDatasource
{
Customer GetCustomer(int id)
}
public TextDataSource : IDataSource
{
public Customer GetCustomer(int id)
{
// reads data from a text file
}
}
public SQLDataSource : IDataSource
{
public Customer GetCustomer(int id)
{
// uses ADO.NET to read data from a SQL Server database
}
}
public class MyProgram
{
public static void Main(string[] args)
{
// the DataSourceFactory will create a data source depending on some settings
// and return the appropriate implementation of the data source
IDataSource ds = DataSourceFactory.GetInstance().GetDataSource();
Console.WriteLine(ds.GetCustomer(15).FirstName)
}
}
As you can see from the example, MyProgram does not need to know which datasource it is querying. All it needs to know is the interface it must use to retrieve a customer record. If we have numerous implementations then by changing only the configurations which are declarative and available outside of the compiled code, we can change the datasource the application should use to retrieve data without changing the application logic itself.
Now lets see how we can use the "Programming to the Interface" paradigm to create a 3-Tier architecture.
The Presentation Layer is responsible for rendering the data retrieved by the BLL (with the help of the DAL). The only logic that is necessary in this layer is how to manipulate the data and display it to the user in an easy to consume manner. Along with rendering the content, it should be responsible for rudimentary data validation such as missing fields, regular expression matching for emails and other content, numeric validation, range validations, etc.
In .NET, there are a slew of UI specific controls that one may use to render the data. Some controls include the DataList, DataGrid, Label, TextBox and of course custom controls for the advanced developers. There are also pre-built validation controls that are bundled with the .NET framework. I'll post some links later with examples of how to use these controls soon.
Depending on the application you are building, the presentation layer may be one or more of the following types of applications: web, windows, windows service, smart client or console. By properly defining the responsibilities of each layer, the only logic that is necessary for developers to write is the presentation layer. Since retrieving a customer record is the same throughout the application (through the BLL) you can abstract out all the details hence simplifying your software.
On the same note, your application may also expose Web services and Remoting services so it is essential to centralize the code. Otherwise the logic for retrieving a customer (which may include security authorization and authentication, data validation, pre-processing and post-processing) will need to be duplicated in many places. Code duplication may seem like a viable solution at the early stages of the software lifecycle, but it is extremely hard to maintain such pieces of software.
The Business Logic Layer is like your kernel for your application. It should be the component that performs all the business logic for your application. This ranges from validations, running business logic, running application processes such as sending emails and retrieving and persisting data using the Data Access Layer.
Although, validations were performed on the presentation layer, it is imperative that you revalidate the data because browsers could have been spoofed or older browsers might have completely ignored some of the validations or the developers working on the presentation layer did not validate the data properly.
Depending on the complexity of your application, businesses logic code may not reside on the same server or in a centralized location so there are advanced means of executing such logic remotely. With .NET this process has been extremely simplified and available to you within a few clicks of your mouse. One of which is .NET Remoting which is an advanced topic that I'll opt out for now. And the other is the buzz word that many have heard; Web Services.
Both writing and using a Web Service is once again simplified by Microsoft. Visual Studio 2003 and 2005 will be able to download the WSDL and generate the proxies for you so you can invoke the functions as you may within business object in your application. If you don't have Visual Studio, then you may use the "wsdl.exe" utility that is bundled with .NET Framework on the command prompt.
If you have business logic on legacy systems that were built with Microsoft Technologies such as COM+ that can not be rewritten for what ever reason, not to worry. You can use COM+ wrappers provided by the .NET Framework to communicate with the legacy systems.
The Data Access Layer is responsible for accessing and manipulating data from data sources such as SQL Server, Microsoft Access, Oracle, MySQL, etc. Many applications on the Internet today rely heavily on data found in many databases and it is important to centralize the access to this data. Some reasons are ...
*
Security
*
Code Maintenance and Resue
*
Scalability
Databases contain confidential information about people and it is not necessary for everyone in your organizational hierarchy to have access to such data. For example, credit card information stored on Amazon.com shouldn't be available for an entry level employee working in a warehouse. By centralizing the access the database, we are able to authenticate and authorize the users requesting data and manipulating the data.
Since our economy is constantly in a flux, it is never safe to assume that once you have created your data model, it will not change for a decade. In fact, that data model may change tomorrow, a week from now or in an year, but it will change and as software architects, it is our responsibility to foresee such events and design systems that will be able to change with time. If the code isn't centralized, a database change as simple as adding a new column may result in days of changes to many systems, regression testing and deployment of many applications. Is this really necessary?
By creating simple reusable components, developers are able to abstract out all of the details of creating connections, handling errors, invoking appropriate stored procedures or executing Transact-SQL or SQL/PL code, retrieving the data, closing the connection away from the Business Logic Layer.
Typical code (using ADO.NET) to retrieve a customer record may look as the following:
SqlConnection connection = null;
try
{
connection = new SqlConnection(mySqlConnection);
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM Customers WHERE CustomerID = " + cid
return CustomerFactory.GetInstance().GetCustomer(cmd.ExecuteReader());
}
catch (Exception e)
{
Console.WriteLine("Exception :: " + e.Message);
}
finally
{
if (connection != null && connection.State != ConnectionState.Closed)
connection.Close();
}
So what's the big deal about writing a few lines of code? Well, imagine repeating these lines in 5 different places and 2 weeks later, making a change and remembering all the pieces of code to change. Compared to this solution, I suggest the following:
Customer customer = CustomerDAO.GetInstance().GetCustomer(customerID);
Where the ADO.NET code is abstracted away by the GetCustomer(int) function and now making a change to the function will take minutes and the change will affect all pieces of code that depends on retrieving customer records. The above examples use Design Patterns, more specifically the Factory Pattern and the Singleton Pattern and you may further read about them at your leisure.
Scalability is huge to enterprise level applications that require time crucial data. It’s beyond the scope of this article so I will leave it out for the time being.
##################################################################################
What is n-Tier Architecture?
This is a very important topic to consider when developing an application. Many elements need to be considered when deciding on the architecture of the application, such as performance, scalability and future development issues. When you are deciding on which architecture to use, first decide on which of the three aforementioned elements you think is most valuable -- as some choices you make will impact on others. For example, some choices that boost performance will impact on the scalability or future development of your design, etc.
Here we will talk generally about what n-Tier architecture is, and then we will have a look at different n-Tier architectures you can use to develop ASP.NET applications and issues that arise relating to performance, scalability and future development issues for each one.
Firstly, what is n-Tier architecture? N-Tier architecture refers to the architecture of an application that has at least 3 "logical" layers -- or parts -- that are separate. Each layer interacts with only the layer directly below, and has specific function that it is responsible for.
Why use n-Tier architecture? Because each layer can be located on physically different servers with only minor code changes, hence they scale out and handle more server load. Also, what each layer does internally is completely hidden to other layers and this makes it possible to change or update one layer without recompiling or modifying other layers.
This is a very powerful feature of n-Tier architecture, as additional features or change to a layer can be done without redeploying the whole application. For example, by separating data access code from the business logic code, when the database servers change you only needs to change the data access code. Because business logic code stays the same, the business logic code does not need to be modified or recompiled.
[Note] tier and layer mean the same thing [End Note]
An n-Tier application usually has three tiers, and they are called the presentation tier, the business tier and the data tier. Let's have a look at what each tier is responsible for.
Presentation Layer
Presentation Layer is the layer responsible for displaying user interface and "driving" that interface using business tier classes and objects. In ASP.NET it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.
Business Tier
Business Tier is the layer responsible for accessing the data tier to retrieve, modify and delete data to and from the data tier and send the results to the presentation tier. This layer is also responsible for processing the data retrieved and sent to the presentation layer.
In ASP.NET it includes using SqlClient or OleDb objects to retrieve, update and delete data from SQL Server or Access databases, and also passing the data retrieved to the presentation layer in a DataReader or DataSet object, or a custom collection object. It might also include the sending of just an integer, but the integer would have been calculated using the data in the data tier such as the number of records a table has.
BLL and DAL
Often this layer is divided into two sub layers: the Business Logic Layer (BLL), and the Data Access Layers (DAL). Business Logic Layers are above Data Access Layers, meaning BLL uses DAL classes and objects. DAL is responsible for accessing data and forwarding it to BLL.
In ASP.NET it might be using SqlClient or OleDb to retrieve the data and sending it to BLL in the form of a DataSet or DataReader. BLL is responsible for preparing or processing the data retrieved and sends it to the presentation layer. In ASP.NET it might be using the DataSet and DataReader objects to fill up a custom collection or process it to come up with a value, and then sending it to Presentation Layer. BLL sometimes works as just transparent layer. For example, if you want to pass a DataSet or DataReader object directly to the presentation layer.
Data Tier
Data tier is the database or the source of the data itself. Often in .NET it's an SQL Server or Access database, however it's not limited to just those. It could also be Oracle, mySQL or even XML. In this article we will focus on SQL Server, as it has been proven to be the fastest database within a .NET Application.
Logical Layers vs. Physical Layers (Distributed)
Logical Layers and Physical Layers are the ones that confuse people. Firstly, a logical layer means that layers are separate in terms of assembly or sets of classes, but are still hosted on the same server. Physical layer means that those assemblies or sets of classes are hosted on different servers with some additional code to handle the communication between the layers. E.g. remoting and web services.
Deciding to separate the layers physically or not is very important. It really depends on the load your application expects to get. I think it's worth mentioning some of the facts that might affect your decision.
Please DO note that separating the layers physically WILL slow your application down due to the delay in communicating between the servers throughout the network, so if you are using the physical layer approach, make sure the performance gain is worth the performance loss from this.
Hopefully you would have designed your application using the n-Tier approach. If this is the case, then note that you can separate the layers in the future.
Cost for deploying and maintaining physically separated applications is much greater. First of all, you will need more servers. You also need network hardware connecting them. At this point, deploying the application becomes more complex too! So decide if these things will be worth it or not.
Another fact that might affect your decision is how each of the tiers in the application are going to be used. You will probably want to host a tier on a separate server if more than 1 service is dependent on it, e.g. You might want to host business logic somewhere else if you have multiple presentation layers for different clients. You might also want a separate SQL server if you have other applications using the same data.
#####################################################################################
3-Tier Architecture
As the 3-Tier Architecture is the most commonly used architecture in the world, I will start my blogging on this topic.
I have noticed in the past 6 years of writing software that many developers ignore this software engineering paradigm for many reasons. Some include ...
*
Return on Investment
*
Software Lifecycle Turnaround time
*
Knowledgeable Resources
*
and the list goes on
I will discuss in more details of these reasons in another blog entry so back to the topic of 3-Tier architecture.
A 3-Tier architecture uses the Divide and Conquer strategy and is broken down into 3 logical layers.
*
Presentation Layer (PL)
*
Business Logic Layer (BLL)
*
Data Access Layer (DAL)
Ideally, each layer specializes in one or a handful of functionalities that service the upper layer. Each of the three layers should be designed so that the layer above it does not need to understand nor know the implementation details of any of the layers below it. This is accomplished by providing well defined interfaces that the above layers use. The advantage of "Programming to the Interface" is that, you can change the implementation details and still have the application work as defined. One caveat is that, if the interfaces change, then it will take more effort and time to update the layer above it. Therefore, when designing an application, its important to define the interfaces properly.
Here is an example:
public interface IDatasource
{
Customer GetCustomer(int id)
}
public TextDataSource : IDataSource
{
public Customer GetCustomer(int id)
{
// reads data from a text file
}
}
public SQLDataSource : IDataSource
{
public Customer GetCustomer(int id)
{
// uses ADO.NET to read data from a SQL Server database
}
}
public class MyProgram
{
public static void Main(string[] args)
{
// the DataSourceFactory will create a data source depending on some settings
// and return the appropriate implementation of the data source
IDataSource ds = DataSourceFactory.GetInstance().GetDataSource();
Console.WriteLine(ds.GetCustomer(15).FirstName)
}
}
As you can see from the example, MyProgram does not need to know which datasource it is querying. All it needs to know is the interface it must use to retrieve a customer record. If we have numerous implementations then by changing only the configurations which are declarative and available outside of the compiled code, we can change the datasource the application should use to retrieve data without changing the application logic itself.
Now lets see how we can use the "Programming to the Interface" paradigm to create a 3-Tier architecture.
The Presentation Layer is responsible for rendering the data retrieved by the BLL (with the help of the DAL). The only logic that is necessary in this layer is how to manipulate the data and display it to the user in an easy to consume manner. Along with rendering the content, it should be responsible for rudimentary data validation such as missing fields, regular expression matching for emails and other content, numeric validation, range validations, etc.
In .NET, there are a slew of UI specific controls that one may use to render the data. Some controls include the DataList, DataGrid, Label, TextBox and of course custom controls for the advanced developers. There are also pre-built validation controls that are bundled with the .NET framework. I'll post some links later with examples of how to use these controls soon.
Depending on the application you are building, the presentation layer may be one or more of the following types of applications: web, windows, windows service, smart client or console. By properly defining the responsibilities of each layer, the only logic that is necessary for developers to write is the presentation layer. Since retrieving a customer record is the same throughout the application (through the BLL) you can abstract out all the details hence simplifying your software.
On the same note, your application may also expose Web services and Remoting services so it is essential to centralize the code. Otherwise the logic for retrieving a customer (which may include security authorization and authentication, data validation, pre-processing and post-processing) will need to be duplicated in many places. Code duplication may seem like a viable solution at the early stages of the software lifecycle, but it is extremely hard to maintain such pieces of software.
The Business Logic Layer is like your kernel for your application. It should be the component that performs all the business logic for your application. This ranges from validations, running business logic, running application processes such as sending emails and retrieving and persisting data using the Data Access Layer.
Although, validations were performed on the presentation layer, it is imperative that you revalidate the data because browsers could have been spoofed or older browsers might have completely ignored some of the validations or the developers working on the presentation layer did not validate the data properly.
Depending on the complexity of your application, businesses logic code may not reside on the same server or in a centralized location so there are advanced means of executing such logic remotely. With .NET this process has been extremely simplified and available to you within a few clicks of your mouse. One of which is .NET Remoting which is an advanced topic that I'll opt out for now. And the other is the buzz word that many have heard; Web Services.
Both writing and using a Web Service is once again simplified by Microsoft. Visual Studio 2003 and 2005 will be able to download the WSDL and generate the proxies for you so you can invoke the functions as you may within business object in your application. If you don't have Visual Studio, then you may use the "wsdl.exe" utility that is bundled with .NET Framework on the command prompt.
If you have business logic on legacy systems that were built with Microsoft Technologies such as COM+ that can not be rewritten for what ever reason, not to worry. You can use COM+ wrappers provided by the .NET Framework to communicate with the legacy systems.
The Data Access Layer is responsible for accessing and manipulating data from data sources such as SQL Server, Microsoft Access, Oracle, MySQL, etc. Many applications on the Internet today rely heavily on data found in many databases and it is important to centralize the access to this data. Some reasons are ...
*
Security
*
Code Maintenance and Resue
*
Scalability
Databases contain confidential information about people and it is not necessary for everyone in your organizational hierarchy to have access to such data. For example, credit card information stored on Amazon.com shouldn't be available for an entry level employee working in a warehouse. By centralizing the access the database, we are able to authenticate and authorize the users requesting data and manipulating the data.
Since our economy is constantly in a flux, it is never safe to assume that once you have created your data model, it will not change for a decade. In fact, that data model may change tomorrow, a week from now or in an year, but it will change and as software architects, it is our responsibility to foresee such events and design systems that will be able to change with time. If the code isn't centralized, a database change as simple as adding a new column may result in days of changes to many systems, regression testing and deployment of many applications. Is this really necessary?
By creating simple reusable components, developers are able to abstract out all of the details of creating connections, handling errors, invoking appropriate stored procedures or executing Transact-SQL or SQL/PL code, retrieving the data, closing the connection away from the Business Logic Layer.
Typical code (using ADO.NET) to retrieve a customer record may look as the following:
SqlConnection connection = null;
try
{
connection = new SqlConnection(mySqlConnection);
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM Customers WHERE CustomerID = " + cid
return CustomerFactory.GetInstance().GetCustomer(cmd.ExecuteReader());
}
catch (Exception e)
{
Console.WriteLine("Exception :: " + e.Message);
}
finally
{
if (connection != null && connection.State != ConnectionState.Closed)
connection.Close();
}
So what's the big deal about writing a few lines of code? Well, imagine repeating these lines in 5 different places and 2 weeks later, making a change and remembering all the pieces of code to change. Compared to this solution, I suggest the following:
Customer customer = CustomerDAO.GetInstance().GetCustomer(customerID);
Where the ADO.NET code is abstracted away by the GetCustomer(int) function and now making a change to the function will take minutes and the change will affect all pieces of code that depends on retrieving customer records. The above examples use Design Patterns, more specifically the Factory Pattern and the Singleton Pattern and you may further read about them at your leisure.
Scalability is huge to enterprise level applications that require time crucial data. It’s beyond the scope of this article so I will leave it out for the time being.
##################################################################################
Tuesday, June 16, 2009
Executing Managed Code !!
Dev Palmistry 
Assemblies provide a way to package modules containing MSIL and metadata into units for deployment. The goal of writing code is not to package and deploy it, however; it's to run it. The final section of this chapter looks at the most important aspects of running managed code.
Assemblies are loaded into memory only when needed
Loading Assemblies
When an application built using the .NET Framework is executed, the assemblies that make up that application must be found and loaded into memory. Assemblies aren't loaded until they're needed, so if an application never calls any methods in a particular assembly, that assembly won't be loaded. (In fact, it need not even be present on the machine where the application is running.) Before any code in an assembly can be loaded, however, it must be found. How is this done?
The answer is not simple. In fact, the process the CLR uses to find assemblies is too complex to describe completely here. The broad outlines of the process are fairly straightforward, however. First, the CLR determines what version of a particular assembly it's looking for. By default, it will look only for the exact version specified for this assembly in the manifest of the assembly from which the call originated. This default can be changed by settings in various configuration files, so the CLR examines these files before it commences its search.
The CLR follows well-defined but involved rules to locate an assembly
Once it has determined exactly which version it needs, the CLR checks whether the desired assembly is already loaded. If it is, the search is over; this loaded version will be used. If the desired assembly is not already loaded, the CLR will begin searching in various places to find it. The first place the CLR looks is usually the global assembly cache (GAC), a special directory intended to hold assemblies that are used by more than one application. Installing assemblies in this global assembly cache requires a process slightly more complex than just copying the assembly, and the cache can contain only assemblies with strong names.
The CLR looks first in the global assembly cache
If the assembly it's hunting for isn't in the global assembly cache, the CLR continues its search by checking for a codebase element in one of the configuration files for this application. If one is found, the CLR looks in the location this element specifies, such as a directory, for the desired assembly. Finding the right assembly in this location means the search is over, and this assembly will be loaded and used. Even if the location pointed to by a codebase element does not contain the desired assembly, however, the search is nevertheless over. A codebase element is meant to specify exactly where the assembly can be found. If the assembly is not at that location, something has gone wrong, the CLR gives up, and the attempt to load the new assembly fails.
The CLR can next look in the location referenced by a codebase element
If there is no codebase element, however, the CLR will begin its last-ditch search for the desired assembly, a process called probing, in what's known as the application base. This can be either the root directory in which the application is installed or a URL, perhaps on some other machine. (It's worth pointing out that the CLR does not assume that all necessary assemblies for an application are installed on the same machine; they can also be located and installed across an internal network or the Internet.) If the elusive assembly isn't found here, the CLR continues searching in several other directories based on the name of the assembly, its culture, and more.
If no codebase element exists, the CLR searches in other places
Despite the apparent complexity of this process, this description is not complete. There are other alternatives and even more options. For developers working with the .NET Framework, it's probably worth spending some time understanding this process in detail. Putting in the effort up front is likely to save time later when applications don't behave as expected.
Compiling MSIL
A compiler that produces managed code always generates MSIL. Yet MSIL can't be executed by any real processor. Before it can be run, MSIL code must be compiled yet again into native code that targets the processor on which it will execute. Two options exist for doing this: MSIL code can be compiled one method at a time during execution, or it can be compiled into native code all at once before an assembly is executed. This section describes both of these approaches.
JIT Compilation
The most common way to compile MSIL into native code is to let the CLR load an assembly and then compile each method the first time that method is invoked. Because each method is compiled only when it's first called, the process is called just-in-time (JIT) compilation.
MSIL code is typically JIT compiled before it's executed
Assemblies provide a way to package modules containing MSIL and metadata into units for deployment. The goal of writing code is not to package and deploy it, however; it's to run it. The final section of this chapter looks at the most important aspects of running managed code.
Assemblies are loaded into memory only when needed
Loading Assemblies
When an application built using the .NET Framework is executed, the assemblies that make up that application must be found and loaded into memory. Assemblies aren't loaded until they're needed, so if an application never calls any methods in a particular assembly, that assembly won't be loaded. (In fact, it need not even be present on the machine where the application is running.) Before any code in an assembly can be loaded, however, it must be found. How is this done?
The answer is not simple. In fact, the process the CLR uses to find assemblies is too complex to describe completely here. The broad outlines of the process are fairly straightforward, however. First, the CLR determines what version of a particular assembly it's looking for. By default, it will look only for the exact version specified for this assembly in the manifest of the assembly from which the call originated. This default can be changed by settings in various configuration files, so the CLR examines these files before it commences its search.
The CLR follows well-defined but involved rules to locate an assembly
Once it has determined exactly which version it needs, the CLR checks whether the desired assembly is already loaded. If it is, the search is over; this loaded version will be used. If the desired assembly is not already loaded, the CLR will begin searching in various places to find it. The first place the CLR looks is usually the global assembly cache (GAC), a special directory intended to hold assemblies that are used by more than one application. Installing assemblies in this global assembly cache requires a process slightly more complex than just copying the assembly, and the cache can contain only assemblies with strong names.
The CLR looks first in the global assembly cache
If the assembly it's hunting for isn't in the global assembly cache, the CLR continues its search by checking for a codebase element in one of the configuration files for this application. If one is found, the CLR looks in the location this element specifies, such as a directory, for the desired assembly. Finding the right assembly in this location means the search is over, and this assembly will be loaded and used. Even if the location pointed to by a codebase element does not contain the desired assembly, however, the search is nevertheless over. A codebase element is meant to specify exactly where the assembly can be found. If the assembly is not at that location, something has gone wrong, the CLR gives up, and the attempt to load the new assembly fails.
The CLR can next look in the location referenced by a codebase element
If there is no codebase element, however, the CLR will begin its last-ditch search for the desired assembly, a process called probing, in what's known as the application base. This can be either the root directory in which the application is installed or a URL, perhaps on some other machine. (It's worth pointing out that the CLR does not assume that all necessary assemblies for an application are installed on the same machine; they can also be located and installed across an internal network or the Internet.) If the elusive assembly isn't found here, the CLR continues searching in several other directories based on the name of the assembly, its culture, and more.
If no codebase element exists, the CLR searches in other places
Despite the apparent complexity of this process, this description is not complete. There are other alternatives and even more options. For developers working with the .NET Framework, it's probably worth spending some time understanding this process in detail. Putting in the effort up front is likely to save time later when applications don't behave as expected.
Compiling MSIL
A compiler that produces managed code always generates MSIL. Yet MSIL can't be executed by any real processor. Before it can be run, MSIL code must be compiled yet again into native code that targets the processor on which it will execute. Two options exist for doing this: MSIL code can be compiled one method at a time during execution, or it can be compiled into native code all at once before an assembly is executed. This section describes both of these approaches.
JIT Compilation
The most common way to compile MSIL into native code is to let the CLR load an assembly and then compile each method the first time that method is invoked. Because each method is compiled only when it's first called, the process is called just-in-time (JIT) compilation.
MSIL code is typically JIT compiled before it's executed
What is the Page Life Time in Asp.Net ?
Understanding Page Life Time:
The first time that an Asp.Net web form page is executed, the code contained with the page (any codebehind class module associated with the page ) is complied into a class that inherits from the Page base class ( actually, the code-behing class inherits from the Page class and then the .aspx file inherits from code-behind class via the Inherits attributes of the @ Page directive ).

The following illustration show the relationship between the Page, its code-behind class (if any) and the complied assembly. Once complied, the class is executed, the resulting Html is rendered to the browser, and the class removed from hte memory.
The first time that an Asp.Net web form page is executed, the code contained with the page (any codebehind class module associated with the page ) is complied into a class that inherits from the Page base class ( actually, the code-behing class inherits from the Page class and then the .aspx file inherits from code-behind class via the Inherits attributes of the @ Page directive ).
The following illustration show the relationship between the Page, its code-behind class (if any) and the complied assembly. Once complied, the class is executed, the resulting Html is rendered to the browser, and the class removed from hte memory.
What is Localhost ?
Localhost:
Local host is an alias for the address 127.0.0.1, an addrss that always indicate local computer.
This is the address that a computer can use to refer to itself .
For Exp: When testing a web application on the same computer as the server. You can use the address:
http:// 127.0.0.1
http:// localhost
Local host is an alias for the address 127.0.0.1, an addrss that always indicate local computer.
This is the address that a computer can use to refer to itself .
For Exp: When testing a web application on the same computer as the server. You can use the address:
http:// 127.0.0.1
http:// localhost
What is Webservices ?
Dev Palmistry 
Web Services:
Web services are stored on server and delivered to user over internet. A web application is usually a three- tier sturcture, comprising a User Services Tier (allowing user to access application), a Business Service tier(allowing user to carry out complex activites) and Data Services tier (which allows data storage and ritrival)
Web Services:
Web services are stored on server and delivered to user over internet. A web application is usually a three- tier sturcture, comprising a User Services Tier (allowing user to access application), a Business Service tier(allowing user to carry out complex activites) and Data Services tier (which allows data storage and ritrival)
What is Reflaction ?
Refelection :
List of class name , method anme
# Refelection is way through which we can identify metadata about assembly runtime.
Exp : We have a .net Assembly file (.dll file ), which cosists of two class definition and 10 method Names. We can get information about classes and methods names through reflaction.
Few Exp Of Reflaction :
# Loading Assembly file
Assembly assem= Assembly.LoadForm(SAssemblyFileName)
# Get the List of Class Name
Type[]types=assem.GetTypes();
------------------------------------------------------------------------
Refliction:
It extend the benifits of maetadata by allowing the developers to ispect and use it at run time.
# For exp: It dynamically detemined all the classes contained in a given assembly and invoke their methos.
# Reflaction Provides objects that encapsulate assemblies, methods and types
# System.Reflaction namespace contain classes that can be used to introgate the types for module/ assemly.
# All .NeT compliers produce metadata about the types defined in the modules they produce. This metadata is package along with the module (modules in the terms are packaged together assemblies) can be accessed by the machinism called reflection.
# You can use reflaction to dynamically create an instance of a type , bind the type to an existing object, or get the type from an existing object.
List of class name , method anme
# Refelection is way through which we can identify metadata about assembly runtime.
Exp : We have a .net Assembly file (.dll file ), which cosists of two class definition and 10 method Names. We can get information about classes and methods names through reflaction.
Few Exp Of Reflaction :
# Loading Assembly file
Assembly assem= Assembly.LoadForm(SAssemblyFileName)
# Get the List of Class Name
Type[]types=assem.GetTypes();
------------------------------------------------------------------------
Refliction:
It extend the benifits of maetadata by allowing the developers to ispect and use it at run time.
# For exp: It dynamically detemined all the classes contained in a given assembly and invoke their methos.
# Reflaction Provides objects that encapsulate assemblies, methods and types
# System.Reflaction namespace contain classes that can be used to introgate the types for module/ assemly.
# All .NeT compliers produce metadata about the types defined in the modules they produce. This metadata is package along with the module (modules in the terms are packaged together assemblies) can be accessed by the machinism called reflection.
# You can use reflaction to dynamically create an instance of a type , bind the type to an existing object, or get the type from an existing object.
Monday, June 15, 2009
How to Write Cover Letter-2 !!
Devesh Mishra
dev.net9@gmail.com
South Ex, India
Cell: 9911360392
___________________________________________________
Date: Jun 15, 2009
Human Resource Manager
Software Developmentl Pvt. Ltd.
TChetu India, Noida
India
Dear Sir,
I am writing to express my interest in the .NET Programmers post for your organization as mentioned in the national daily 'Times of India' on Jun 10, 2009, and have enclosed my resume for your consideration.
I am a computer engineer with much enthusiasm and experience in developing software systems. I have the experience of leading, organizing and successfully accomplishing software projects with rich set of feature and functionality. Especially, I have been successful in bending abstract system requirements into real software solutions having high security and performance. I have listed below my strengths that will help you learn my background in software development.
# Excellent ability in analyzing requirements and bending them into real software solutions
# Quick in learning and adopting new technology and smart in best utilizing resources
# Speedy in making development strategy and fast in developing solutions
# Strong command over team management and leadership
# Strong power in delivering complex task and getting with long and tedious working environment
With strong communication, team cooperation and programming capability, I am confident I can be a valuable asset in both software development teams and promotion.
I would welcome the opportunity to interview with your selection team and look forward to hearing from you in the near future. Thank you for your time and consideration.
Sincerely,
Devesh Kr. Mishra
Software Engineer,
Arete Consultants Pvt Ltd.
New Delhi-110 002.India
dev.net9@gmail.com
South Ex, India
Cell: 9911360392
___________________________________________________
Date: Jun 15, 2009
Human Resource Manager
Software Developmentl Pvt. Ltd.
TChetu India, Noida
India
Dear Sir,
I am writing to express my interest in the .NET Programmers post for your organization as mentioned in the national daily 'Times of India' on Jun 10, 2009, and have enclosed my resume for your consideration.
I am a computer engineer with much enthusiasm and experience in developing software systems. I have the experience of leading, organizing and successfully accomplishing software projects with rich set of feature and functionality. Especially, I have been successful in bending abstract system requirements into real software solutions having high security and performance. I have listed below my strengths that will help you learn my background in software development.
# Excellent ability in analyzing requirements and bending them into real software solutions
# Quick in learning and adopting new technology and smart in best utilizing resources
# Speedy in making development strategy and fast in developing solutions
# Strong command over team management and leadership
# Strong power in delivering complex task and getting with long and tedious working environment
With strong communication, team cooperation and programming capability, I am confident I can be a valuable asset in both software development teams and promotion.
I would welcome the opportunity to interview with your selection team and look forward to hearing from you in the near future. Thank you for your time and consideration.
Sincerely,
Devesh Kr. Mishra
Software Engineer,
Arete Consultants Pvt Ltd.
New Delhi-110 002.India
How to Write Cover Letter-1 !!
Dear Sir/Madam,
As you can see from my CV, my career in software development is quite
extensive. I have a very good reputation in my field and have an
excellent rapport with my colleagues.
My objective is to establish a time when we can meet to discuss how my
talent, professionalism and enthusiasm will add value to your company.
I look forward to speaking with you soon.
Current ctc: 2.4 lacs per annum
Expected ctc: 3.0 lacs per annum
Total IT exp:2 years
Relevant exp: 2 years
DOB: 14 Feb 1983
Notice Period: 15 working days
Current Location: Delhi
Reason for change:Career growth
Education: MCA
--
With best regards
Devesh Kr. Mishra
Software Engineer,
Arete Consultants Pvt Ltd.
New Delhi-110 002.India
As you can see from my CV, my career in software development is quite
extensive. I have a very good reputation in my field and have an
excellent rapport with my colleagues.
My objective is to establish a time when we can meet to discuss how my
talent, professionalism and enthusiasm will add value to your company.
I look forward to speaking with you soon.
Current ctc: 2.4 lacs per annum
Expected ctc: 3.0 lacs per annum
Total IT exp:2 years
Relevant exp: 2 years
DOB: 14 Feb 1983
Notice Period: 15 working days
Current Location: Delhi
Reason for change:Career growth
Education: MCA
--
With best regards
Devesh Kr. Mishra
Software Engineer,
Arete Consultants Pvt Ltd.
New Delhi-110 002.India
Wednesday, June 10, 2009
Short Answer .NET Interview Questions !!
Q1. Explain the differences between Server-side and Client-side code?
Ans. Server side code will execute at server (where the website is hosted) end, & all the business logic will execute at server end where as client side code will execute at client side (usually written in javascript, vbscript, jscript) at browser end.
Q2. What type of code (server or client) is found in a Code-Behind class?
Ans. Server side code.
Q3. How to make sure that value is entered in an asp:Textbox control?
Ans. Use a RequiredFieldValidator control.
Q4. Which property of a validation control is used to associate it with a server control on that page?
Ans. ControlToValidate property.
Q5. How would you implement inheritance using VB.NET & C#?
Ans. C# Derived Class : Baseclass
VB.NEt : Derived Class Inherits Baseclass
Q6. Which method is invoked on the DataAdapter control to load the generated dataset with data?
Ans. Fill() method.
Q7. What method is used to explicitly kill a user's session?
Ans. Session.Abandon()
Q8. What property within the asp:gridview control is changed to bind columns manually?
Ans. Autogenerated columns is set to false
Q9. Which method is used to redirect the user to another page without performing a round trip to the client?
Ans. Server.Transfer method.
Q10. How do we use different versions of private assemblies in same application without re-build?
Ans.Inside the Assemblyinfo.cs or Assemblyinfo.vb file, we need to specify assembly version.
assembly: AssemblyVersion
Q11. Is it possible to debug java-script in .NET IDE? If yes, how?
Ans. Yes, simply write "debugger" statement at the point where the breakpoint needs to be set within the javascript code and also enable javascript debugging in the browser property settings.
Q12. How many ways can we maintain the state of a page?
Ans. 1. Client Side - Query string, hidden variables, viewstate, cookies
2. Server side - application , cache, context, session, database
Q13. What is the use of a multicast delegate?
Ans. A multicast delegate may be used to call more than one method.
Q14. What is the use of a private constructor?
Ans. A private constructor may be used to prevent the creation of an instance for a class.
Q15. What is the use of Singleton pattern?
Ans. A Singleton pattern .is used to make sure that only one instance of a class exists.
Q16. When do we use a DOM parser and when do we use a SAX parser?
Ans. The DOM Approach is useful for small documents in which the program needs to process a large portion of the document whereas the SAX approach is useful for large documents in which the program only needs to process a small portion of the document.
Q17. Will the finally block be executed if an exception has not occurred?
Ans.Yes it will execute.
Q18. What is a Dataset?
Ans. A dataset is an in memory database kindof object that can hold database information in a disconnected environment.
Q19. Is XML a case-sensitive markup language?
Ans. Yes.
Q20. What is an .ashx file?
Ans. It is a web handler file that produces output to be consumed by an xml consumer client (rather than a browser).
Q21. What is encapsulation?
Ans. Encapsulation is the OOPs concept of binding the attributes and behaviors in a class, hiding the implementation of the class and exposing the functionality.
Q22. What is Overloading?
Ans. When we add a new method with the same name in a same/derived class but with different number/types of parameters, the concept is called overluoad and this ultimately implements Polymorphism.
Q23. What is Overriding?
Ans. When we need to provide different implementation in a child class than the one provided by base class, we define the same method with same signatures in the child class and this is called overriding.
Q24. What is a Delegate?
Ans. A delegate is a strongly typed function pointer object that encapsulates a reference to a method, and so the function that needs to be invoked may be called at runtime.
Q25. Is String a Reference Type or Value Type in .NET?
Ans. String is a Reference Type object.
Q26. What is a Satellite Assembly?
Ans. Satellite assemblies contain resource files corresponding to a locale (Culture + Language) and these assemblies are used in deploying an application globally for different languages.
Q27. What are the different types of assemblies and what is their use?
Ans. Private, Public(also called shared) and Satellite Assemblies.
Q28. Are MSIL and CIL the same thing?
Ans. Yes, CIL is the new name for MSIL.
Q29. What is the base class of all web forms?
Ans. System.Web.UI.Page
Q30. How to add a client side event to a server control?
Ans. Example... BtnSubmit.Attributes.Add("onclick","javascript:fnSomeFunctionInJavascript()");
Q31. How to register a client side script from code-behind?
Ans. Use the Page.RegisterClientScriptBlock method in the server side code to register the script that may be built using a StringBuilder.
Q32. Can a single .NET DLL contain multiple classes?
Ans. Yes, a single .NET DLL may contain any number of classes within it.
Q33. What is DLL Hell?
Ans. DLL Hell is the name given to the problem of old unmanaged DLL's due to which there was a possibility of version conflict among the DLLs.
Q34. can we put a break statement in a finally block?
Ans. The finally block cannot have the break, continue, return and goto statements.
Q35. What is a CompositeControl in .NET?
Ans. CompositeControl is an abstract class in .NET that is inherited by those web controls that contain child controls within them.
Q36. Which control in asp.net is used to display data from an xml file and then displayed using XSLT?
Ans. Use the asp:Xml control and set its DocumentSource property for associating an xml file, and set its TransformSource property to set the xml control's xsl file for the XSLT transformation.
Q37. Can we run ASP.NET 1.1 application and ASP.NET 2.0 application on the same computer?
Ans. Yes, though changes in the IIS in the properties for the site have to be made during deployment of each.
Q38. What are the new features in .NET 2.0?
Ans. Plenty of new controls, Generics, anonymous methods, partial classes, iterators, property visibility (separate visibility for get and set) and static classes.
Q39. Can we pop a MessageBox in a web application?
Ans. Yes, though this is done clientside using an alert, prompt or confirm or by opening a new web page that looks like a messagebox.
Q40. What is managed data?
Ans. The data for which the memory management is taken care by .Net runtime’s garbage collector, and this includes tasks for allocation de-allocation.
Q41. How to instruct the garbage collector to collect unreferenced data?
Ans. We may call the garbage collector to collect unreferenced data by executing the System.GC.Collect() method.
Q42. How can we set the Focus on a control in ASP.NET?
Ans. txtBox123.Focus(); OR Page.SetFocus(NameOfControl);
Q43. What are Partial Classes in Asp.Net 2.0?
Ans. In .NET 2.0, a class definition may be split into multiple physical files but partial classes do not make any difference to the compiler as during compile time, the compiler groups all the partial classes and treats them as a single class.
Q44. How to set the default button on a Web Form?
Ans.
Q45.Can we force the garbage collector to run?
Ans. Yes, using the System.GC.Collect(), the garbage collector is forced to run in case required to do so.
Q46. What is Boxing and Unboxing?
Ans. Boxing is the process where any value type can be implicitly converted to a reference type object while Unboxing is the opposite of boxing process where the reference type is converted to a value type.
Q47. What is Code Access security? What is CAS in .NET?
Ans. CAS is the feature of the .NET security model that determines whether an application or a piece of code is permitted to run and decide the resources it can use while running.
Q48. What is Multi-tasking?
Ans. It is a feature of operating systems through which multiple programs may run on the operating system at the same time, just like a scenario where a Notepad, a Calculator and the Control Panel are open at the same time.
Q49. What is Multi-threading?
Ans. When an application performs different tasks at the same time, the application is said to exhibit multithreading as several threads of a process are running.2
Q50. What is a Thread?
Ans. A thread is an activity started by a process and its the basic unit to which an operating system allocates processor resources.
Q51. What does AddressOf in VB.NET operator do?
Ans. The AddressOf operator is used in VB.NET to create a delegate object to a method in order to point to it.
Q52. How to refer to the current thread of a method in .NET?
Ans. In order to refer to the current thread in .NET, the Thread.CurrentThread method can be used. It is a public static property.
Q53. How to pause the execution of a thread in .NET?
Ans. The thread execution can be paused by invoking the Thread.Sleep(IntegerValue) method where IntegerValue is an integer that determines the milliseconds time frame for which the thread in context has to sleep.
Q54. How can we force a thread to sleep for an infinite period?
Ans. Call the Thread.Interupt() method.
Q55. What is Suspend and Resume in .NET Threading?
Ans. Just like a song may be paused and played using a music player, a thread may be paused using Thread.Suspend method and may be started again using the Thread.Resume method. Note that sleep method immediately forces the thread to sleep whereas the suspend method waits for the thread to be in a persistable position before pausing its activity.
Q56. How can we prevent a deadlock in .Net threading?
Ans. Using methods like Monitoring, Interlocked classes, Wait handles, Event raising from between threads, using the ThreadState property.
Q57. What is Ajax?
Ans. Asyncronous Javascript and XML - Ajax is a combination of client side technologies that sets up asynchronous communication between the user interface and the web server so that partial page rendering occur instead of complete page postbacks.
Q58. What is XmlHttpRequest in Ajax?
Ans. It is an object in Javascript that allows the browser to communicate to a web server asynchronously without making a postback.
Q59. What are the different modes of storing an ASP.NET session?
Ans. InProc (the session state is stored in the memory space of the Aspnet_wp.exe process but the session information is lost when IIS reboots), StateServer (the Session state is serialized and stored in a separate process call Viewstate is an object in .NET that automatically persists control setting values across the multiple requests for the same page and it is internally maintained as a hidden field on the web page though its hashed for security reasons.
Q60. What is a delegate in .NET?
Ans. A delegate in .NET is a class that can have a reference to a method, and this class has a signature that can refer only those methods that have a signature which complies with the class.
Q61. Is a delegate a type-safe functions pointer?
Ans. Yes
Q62. What is the return type of an event in .NET?
Ans. There is No return type of an event in .NET.
Q63. Is it possible to specify an access specifier to an event in .NET?
Ans. Yes, though they are public by default.
Q64. Is it possible to create a shared event in .NET?
Ans. Yes, but shared events may only be raised by shared methods.
Q65. How to prevent overriding of a class in .NET?
Ans. Use the keyword NotOverridable in VB.NET and sealed in C#.
Q66. How to prevent inheritance of a class in .NET?
Ans. Use the keyword NotInheritable in VB.NET and sealed in C#.
Q67. What is the purpose of the MustInherit keyword in VB.NET?
Ans. MustInherit keyword in VB.NET is used to create an abstract class.
Q68. What is the access modifier of a member function of in an Interface created in .NET?
Ans. It is always public, we cant use any other modifier other than the public modifier for the member functions of an Interface.
Q69. What does the virtual keyword in C# mean?
Ans. The virtual keyword signifies that the method and property may be overridden.
Q70. How to create a new unique ID for a control?
Ans. ControlName.ID = "ControlName" + Guid.NewGuid().ToString(); //Make use of the Guid class
Q71A. What is a HashTable in .NET?
Ans. A Hashtable is an object that implements the IDictionary interface, and can be used to store key value pairs. The key may be used as the index to access the values for that index.
Q71B. What is an ArrayList in .NET?
Ans. Arraylist object is used to store a list of values in the form of a list, such that the size of the arraylist can be increased and decreased dynamically, and moreover, it may hold items of different types. Items in an arraylist may be accessed using an index.
Q72. What is the value of the first item in an Enum? 0 or 1?
Ans. 0
Q73. Can we achieve operator overloading in VB.NET?
Ans. Yes, it is supported in the .NET 2.0 version, the "operator" keyword is used.
Q74. What is the use of Finalize method in .NET?
Ans. .NET Garbage collector performs all the clean up activity of the managed objects, and so the finalize method is usually used to free up the unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc.
Q75. How do you save all the data in a dataset in .NET?
Ans. Use the AcceptChanges method which commits all the changes made to the dataset since last time Acceptchanges was performed.
Q76. Is there a way to suppress the finalize process inside the garbage collector forcibly in .NET?
Ans. Use the GC.SuppressFinalize() method.
Q77. What is the use of the dispose() method in .NET?
Ans. The Dispose method in .NET belongs to IDisposable interface and it is best used to release unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc from the memory. Its performance is better than the finalize() method.
Q78. Is it possible to have have different access modifiers on the get and set methods of a property in .NET?
Ans. No we can not have different modifiers of a common property, which means that if the access modifier of a property's get method is protected, and it must be protected for the set method as well.
Q79. In .NET, is it possible for two catch blocks to be executed in one go?
Ans. This is NOT possible because once the correct catch block is executed then the code flow goes to the finally block.
Q80. Is there any difference between System.String and System.StringBuilder classes?
Ans. System.String is immutable by nature whereas System.StringBuilder can have a mutable string in which plenty of processes may be performed.
Q81. What technique is used to figure out that the page request is a postback?
Ans. The IsPostBack property of the page object may be used to check whether the page request is a postback or not. IsPostBack property is of the type Boolean.
Q82. Which event of the ASP.NET page life cycle completely loads all the controls on the web page?
Ans. The Page_load event of the ASP.NET page life cycle assures that all controls are completely loaded. Even though the controls are also accessible in Page_Init event but here, the viewstate is incomplete.
Q83. How is ViewState information persisted across postbacks in an ASP.NET webpage?
Ans. Using HTML Hidden Fields, ASP.NET creates a hidden field with an ID="__VIEWSTATE" and the value of the page's viewstate is encoded (hashed) for security.
Q84. What is the ValidationSummary control in ASP.NET used for?
Ans. The ValidationSummary control in ASP.NET displays summary of all the current validation errors.
Q85. What is AutoPostBack feature in ASP.NET?
Ans. In case it is required for a server side control to postback when any of its event is triggered, then the AutoPostBack property of this control is set to true.
Q86. What is the difference between Web.config and Machine.Config in .NET?
Ans. Web.config file is used to make the settings to a web application, whereas Machine.config file is used to make settings to all ASP.NET applications on a server(the server machine).
Q87. What is the difference between a session object and an application object?
Ans. A session object can persist information between HTTP requests for a particular user, whereas an application object can be used globally for all the users.
Q88. Which control has a faster performance, Repeater or Datalist?
Ans. Repeater.
Q89. Which control has a faster performance, Datagrid or Datalist?
Ans. Datalist.
Q90. How to we add customized columns in a Gridview in ASP.NET?
Ans. Make use of the TemplateField column.
Q91. Is it possible to stop the clientside validation of an entire page?
Ans. Set Page.Validate = false;
Q92. Is it possible to disable client side script in validators?
Ans. Yes. simply EnableClientScript = false.
Q93. How do we enable tracing in .NET applications?
Ans. <%@ Page Trace="true" %>
Q94. How to kill a user session in ASP.NET?
Ans. Use the Session.abandon() method.
Q95. Is it possible to perform forms authentication with cookies disabled on a browser?
Ans. Yes, it is possible.
Q96. What are the steps to use a checkbox in a gridview?
Ans.
OnCheckedChanged="Check_Clicked">
Q97. What are design patterns in .NET?
Ans. A Design pattern is a repeatitive solution to a repeatitive problem in the design of a software architecture.
Q98. What is difference between dataset and datareader in ADO.NET?
Ans. A DataReader provides a forward-only and read-only access to data, while the DataSet object can carry more than one table and at the same time hold the relationships between the tables. Also note that a DataReader is used in a connected architecture whereas a Dataset is used in a disconnected architecture.
Q99. Can connection strings be stored in web.config?
Ans. Yes, in fact this is the best place to store the connection string information.
Q100. Whats the difference between web.config and app.config?
Ans. Web.config is used for web based asp.net applications whereas app.config is used for windows based applications.
Ans. Server side code will execute at server (where the website is hosted) end, & all the business logic will execute at server end where as client side code will execute at client side (usually written in javascript, vbscript, jscript) at browser end.
Q2. What type of code (server or client) is found in a Code-Behind class?
Ans. Server side code.
Q3. How to make sure that value is entered in an asp:Textbox control?
Ans. Use a RequiredFieldValidator control.
Q4. Which property of a validation control is used to associate it with a server control on that page?
Ans. ControlToValidate property.
Q5. How would you implement inheritance using VB.NET & C#?
Ans. C# Derived Class : Baseclass
VB.NEt : Derived Class Inherits Baseclass
Q6. Which method is invoked on the DataAdapter control to load the generated dataset with data?
Ans. Fill() method.
Q7. What method is used to explicitly kill a user's session?
Ans. Session.Abandon()
Q8. What property within the asp:gridview control is changed to bind columns manually?
Ans. Autogenerated columns is set to false
Q9. Which method is used to redirect the user to another page without performing a round trip to the client?
Ans. Server.Transfer method.
Q10. How do we use different versions of private assemblies in same application without re-build?
Ans.Inside the Assemblyinfo.cs or Assemblyinfo.vb file, we need to specify assembly version.
assembly: AssemblyVersion
Q11. Is it possible to debug java-script in .NET IDE? If yes, how?
Ans. Yes, simply write "debugger" statement at the point where the breakpoint needs to be set within the javascript code and also enable javascript debugging in the browser property settings.
Q12. How many ways can we maintain the state of a page?
Ans. 1. Client Side - Query string, hidden variables, viewstate, cookies
2. Server side - application , cache, context, session, database
Q13. What is the use of a multicast delegate?
Ans. A multicast delegate may be used to call more than one method.
Q14. What is the use of a private constructor?
Ans. A private constructor may be used to prevent the creation of an instance for a class.
Q15. What is the use of Singleton pattern?
Ans. A Singleton pattern .is used to make sure that only one instance of a class exists.
Q16. When do we use a DOM parser and when do we use a SAX parser?
Ans. The DOM Approach is useful for small documents in which the program needs to process a large portion of the document whereas the SAX approach is useful for large documents in which the program only needs to process a small portion of the document.
Q17. Will the finally block be executed if an exception has not occurred?
Ans.Yes it will execute.
Q18. What is a Dataset?
Ans. A dataset is an in memory database kindof object that can hold database information in a disconnected environment.
Q19. Is XML a case-sensitive markup language?
Ans. Yes.
Q20. What is an .ashx file?
Ans. It is a web handler file that produces output to be consumed by an xml consumer client (rather than a browser).
Q21. What is encapsulation?
Ans. Encapsulation is the OOPs concept of binding the attributes and behaviors in a class, hiding the implementation of the class and exposing the functionality.
Q22. What is Overloading?
Ans. When we add a new method with the same name in a same/derived class but with different number/types of parameters, the concept is called overluoad and this ultimately implements Polymorphism.
Q23. What is Overriding?
Ans. When we need to provide different implementation in a child class than the one provided by base class, we define the same method with same signatures in the child class and this is called overriding.
Q24. What is a Delegate?
Ans. A delegate is a strongly typed function pointer object that encapsulates a reference to a method, and so the function that needs to be invoked may be called at runtime.
Q25. Is String a Reference Type or Value Type in .NET?
Ans. String is a Reference Type object.
Q26. What is a Satellite Assembly?
Ans. Satellite assemblies contain resource files corresponding to a locale (Culture + Language) and these assemblies are used in deploying an application globally for different languages.
Q27. What are the different types of assemblies and what is their use?
Ans. Private, Public(also called shared) and Satellite Assemblies.
Q28. Are MSIL and CIL the same thing?
Ans. Yes, CIL is the new name for MSIL.
Q29. What is the base class of all web forms?
Ans. System.Web.UI.Page
Q30. How to add a client side event to a server control?
Ans. Example... BtnSubmit.Attributes.Add("onclick","javascript:fnSomeFunctionInJavascript()");
Q31. How to register a client side script from code-behind?
Ans. Use the Page.RegisterClientScriptBlock method in the server side code to register the script that may be built using a StringBuilder.
Q32. Can a single .NET DLL contain multiple classes?
Ans. Yes, a single .NET DLL may contain any number of classes within it.
Q33. What is DLL Hell?
Ans. DLL Hell is the name given to the problem of old unmanaged DLL's due to which there was a possibility of version conflict among the DLLs.
Q34. can we put a break statement in a finally block?
Ans. The finally block cannot have the break, continue, return and goto statements.
Q35. What is a CompositeControl in .NET?
Ans. CompositeControl is an abstract class in .NET that is inherited by those web controls that contain child controls within them.
Q36. Which control in asp.net is used to display data from an xml file and then displayed using XSLT?
Ans. Use the asp:Xml control and set its DocumentSource property for associating an xml file, and set its TransformSource property to set the xml control's xsl file for the XSLT transformation.
Q37. Can we run ASP.NET 1.1 application and ASP.NET 2.0 application on the same computer?
Ans. Yes, though changes in the IIS in the properties for the site have to be made during deployment of each.
Q38. What are the new features in .NET 2.0?
Ans. Plenty of new controls, Generics, anonymous methods, partial classes, iterators, property visibility (separate visibility for get and set) and static classes.
Q39. Can we pop a MessageBox in a web application?
Ans. Yes, though this is done clientside using an alert, prompt or confirm or by opening a new web page that looks like a messagebox.
Q40. What is managed data?
Ans. The data for which the memory management is taken care by .Net runtime’s garbage collector, and this includes tasks for allocation de-allocation.
Q41. How to instruct the garbage collector to collect unreferenced data?
Ans. We may call the garbage collector to collect unreferenced data by executing the System.GC.Collect() method.
Q42. How can we set the Focus on a control in ASP.NET?
Ans. txtBox123.Focus(); OR Page.SetFocus(NameOfControl);
Q43. What are Partial Classes in Asp.Net 2.0?
Ans. In .NET 2.0, a class definition may be split into multiple physical files but partial classes do not make any difference to the compiler as during compile time, the compiler groups all the partial classes and treats them as a single class.
Q44. How to set the default button on a Web Form?
Ans.
Q45.Can we force the garbage collector to run?
Ans. Yes, using the System.GC.Collect(), the garbage collector is forced to run in case required to do so.
Q46. What is Boxing and Unboxing?
Ans. Boxing is the process where any value type can be implicitly converted to a reference type object while Unboxing is the opposite of boxing process where the reference type is converted to a value type.
Q47. What is Code Access security? What is CAS in .NET?
Ans. CAS is the feature of the .NET security model that determines whether an application or a piece of code is permitted to run and decide the resources it can use while running.
Q48. What is Multi-tasking?
Ans. It is a feature of operating systems through which multiple programs may run on the operating system at the same time, just like a scenario where a Notepad, a Calculator and the Control Panel are open at the same time.
Q49. What is Multi-threading?
Ans. When an application performs different tasks at the same time, the application is said to exhibit multithreading as several threads of a process are running.2
Q50. What is a Thread?
Ans. A thread is an activity started by a process and its the basic unit to which an operating system allocates processor resources.
Q51. What does AddressOf in VB.NET operator do?
Ans. The AddressOf operator is used in VB.NET to create a delegate object to a method in order to point to it.
Q52. How to refer to the current thread of a method in .NET?
Ans. In order to refer to the current thread in .NET, the Thread.CurrentThread method can be used. It is a public static property.
Q53. How to pause the execution of a thread in .NET?
Ans. The thread execution can be paused by invoking the Thread.Sleep(IntegerValue) method where IntegerValue is an integer that determines the milliseconds time frame for which the thread in context has to sleep.
Q54. How can we force a thread to sleep for an infinite period?
Ans. Call the Thread.Interupt() method.
Q55. What is Suspend and Resume in .NET Threading?
Ans. Just like a song may be paused and played using a music player, a thread may be paused using Thread.Suspend method and may be started again using the Thread.Resume method. Note that sleep method immediately forces the thread to sleep whereas the suspend method waits for the thread to be in a persistable position before pausing its activity.
Q56. How can we prevent a deadlock in .Net threading?
Ans. Using methods like Monitoring, Interlocked classes, Wait handles, Event raising from between threads, using the ThreadState property.
Q57. What is Ajax?
Ans. Asyncronous Javascript and XML - Ajax is a combination of client side technologies that sets up asynchronous communication between the user interface and the web server so that partial page rendering occur instead of complete page postbacks.
Q58. What is XmlHttpRequest in Ajax?
Ans. It is an object in Javascript that allows the browser to communicate to a web server asynchronously without making a postback.
Q59. What are the different modes of storing an ASP.NET session?
Ans. InProc (the session state is stored in the memory space of the Aspnet_wp.exe process but the session information is lost when IIS reboots), StateServer (the Session state is serialized and stored in a separate process call Viewstate is an object in .NET that automatically persists control setting values across the multiple requests for the same page and it is internally maintained as a hidden field on the web page though its hashed for security reasons.
Q60. What is a delegate in .NET?
Ans. A delegate in .NET is a class that can have a reference to a method, and this class has a signature that can refer only those methods that have a signature which complies with the class.
Q61. Is a delegate a type-safe functions pointer?
Ans. Yes
Q62. What is the return type of an event in .NET?
Ans. There is No return type of an event in .NET.
Q63. Is it possible to specify an access specifier to an event in .NET?
Ans. Yes, though they are public by default.
Q64. Is it possible to create a shared event in .NET?
Ans. Yes, but shared events may only be raised by shared methods.
Q65. How to prevent overriding of a class in .NET?
Ans. Use the keyword NotOverridable in VB.NET and sealed in C#.
Q66. How to prevent inheritance of a class in .NET?
Ans. Use the keyword NotInheritable in VB.NET and sealed in C#.
Q67. What is the purpose of the MustInherit keyword in VB.NET?
Ans. MustInherit keyword in VB.NET is used to create an abstract class.
Q68. What is the access modifier of a member function of in an Interface created in .NET?
Ans. It is always public, we cant use any other modifier other than the public modifier for the member functions of an Interface.
Q69. What does the virtual keyword in C# mean?
Ans. The virtual keyword signifies that the method and property may be overridden.
Q70. How to create a new unique ID for a control?
Ans. ControlName.ID = "ControlName" + Guid.NewGuid().ToString(); //Make use of the Guid class
Q71A. What is a HashTable in .NET?
Ans. A Hashtable is an object that implements the IDictionary interface, and can be used to store key value pairs. The key may be used as the index to access the values for that index.
Q71B. What is an ArrayList in .NET?
Ans. Arraylist object is used to store a list of values in the form of a list, such that the size of the arraylist can be increased and decreased dynamically, and moreover, it may hold items of different types. Items in an arraylist may be accessed using an index.
Q72. What is the value of the first item in an Enum? 0 or 1?
Ans. 0
Q73. Can we achieve operator overloading in VB.NET?
Ans. Yes, it is supported in the .NET 2.0 version, the "operator" keyword is used.
Q74. What is the use of Finalize method in .NET?
Ans. .NET Garbage collector performs all the clean up activity of the managed objects, and so the finalize method is usually used to free up the unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc.
Q75. How do you save all the data in a dataset in .NET?
Ans. Use the AcceptChanges method which commits all the changes made to the dataset since last time Acceptchanges was performed.
Q76. Is there a way to suppress the finalize process inside the garbage collector forcibly in .NET?
Ans. Use the GC.SuppressFinalize() method.
Q77. What is the use of the dispose() method in .NET?
Ans. The Dispose method in .NET belongs to IDisposable interface and it is best used to release unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc from the memory. Its performance is better than the finalize() method.
Q78. Is it possible to have have different access modifiers on the get and set methods of a property in .NET?
Ans. No we can not have different modifiers of a common property, which means that if the access modifier of a property's get method is protected, and it must be protected for the set method as well.
Q79. In .NET, is it possible for two catch blocks to be executed in one go?
Ans. This is NOT possible because once the correct catch block is executed then the code flow goes to the finally block.
Q80. Is there any difference between System.String and System.StringBuilder classes?
Ans. System.String is immutable by nature whereas System.StringBuilder can have a mutable string in which plenty of processes may be performed.
Q81. What technique is used to figure out that the page request is a postback?
Ans. The IsPostBack property of the page object may be used to check whether the page request is a postback or not. IsPostBack property is of the type Boolean.
Q82. Which event of the ASP.NET page life cycle completely loads all the controls on the web page?
Ans. The Page_load event of the ASP.NET page life cycle assures that all controls are completely loaded. Even though the controls are also accessible in Page_Init event but here, the viewstate is incomplete.
Q83. How is ViewState information persisted across postbacks in an ASP.NET webpage?
Ans. Using HTML Hidden Fields, ASP.NET creates a hidden field with an ID="__VIEWSTATE" and the value of the page's viewstate is encoded (hashed) for security.
Q84. What is the ValidationSummary control in ASP.NET used for?
Ans. The ValidationSummary control in ASP.NET displays summary of all the current validation errors.
Q85. What is AutoPostBack feature in ASP.NET?
Ans. In case it is required for a server side control to postback when any of its event is triggered, then the AutoPostBack property of this control is set to true.
Q86. What is the difference between Web.config and Machine.Config in .NET?
Ans. Web.config file is used to make the settings to a web application, whereas Machine.config file is used to make settings to all ASP.NET applications on a server(the server machine).
Q87. What is the difference between a session object and an application object?
Ans. A session object can persist information between HTTP requests for a particular user, whereas an application object can be used globally for all the users.
Q88. Which control has a faster performance, Repeater or Datalist?
Ans. Repeater.
Q89. Which control has a faster performance, Datagrid or Datalist?
Ans. Datalist.
Q90. How to we add customized columns in a Gridview in ASP.NET?
Ans. Make use of the TemplateField column.
Q91. Is it possible to stop the clientside validation of an entire page?
Ans. Set Page.Validate = false;
Q92. Is it possible to disable client side script in validators?
Ans. Yes. simply EnableClientScript = false.
Q93. How do we enable tracing in .NET applications?
Ans. <%@ Page Trace="true" %>
Q94. How to kill a user session in ASP.NET?
Ans. Use the Session.abandon() method.
Q95. Is it possible to perform forms authentication with cookies disabled on a browser?
Ans. Yes, it is possible.
Q96. What are the steps to use a checkbox in a gridview?
Ans.
Q97. What are design patterns in .NET?
Ans. A Design pattern is a repeatitive solution to a repeatitive problem in the design of a software architecture.
Q98. What is difference between dataset and datareader in ADO.NET?
Ans. A DataReader provides a forward-only and read-only access to data, while the DataSet object can carry more than one table and at the same time hold the relationships between the tables. Also note that a DataReader is used in a connected architecture whereas a Dataset is used in a disconnected architecture.
Q99. Can connection strings be stored in web.config?
Ans. Yes, in fact this is the best place to store the connection string information.
Q100. Whats the difference between web.config and app.config?
Ans. Web.config is used for web based asp.net applications whereas app.config is used for windows based applications.
What does the virtual keyword in C# mean?
Que. What does the virtual keyword in C# mean?
Ans. The virtual keyword signifies that the method and property may be overridden.
Ans. The virtual keyword signifies that the method and property may be overridden.
Que. What is the access modifier of a member function of in an Interface created in .NET?
Que. What is the access modifier of a member function of in an Interface created in .NET?
Ans. It is always public, we cant use any other modifier other than the public modifier for the member functions of an Interface.
Ans. It is always public, we cant use any other modifier other than the public modifier for the member functions of an Interface.
How to prevent inheritance of a class in .NET?
Que. How to prevent inheritance of a class in .NET?
Ans. Use the keyword NotInheritable in VB.NET and sealed in C#.
Ans. Use the keyword NotInheritable in VB.NET and sealed in C#.
Que. How to prevent overriding of a class in .NET?
Que. How to prevent overriding of a class in .NET?
Ans. Use the keyword NotOverridable in VB.NET and sealed in C#.
Ans. Use the keyword NotOverridable in VB.NET and sealed in C#.
Subscribe to:
Posts (Atom)