EXISTS or COUNT(*) Which Do You Use To Check How Many Rows There Are?
Do you use this
IF (SELECT COUNT(*) FROM SomeTable
WHERE SomeColumn = SomeValue ) > 0
Or do you use this
IF EXISTS (SELECT * FROM SomeTable WHERE SomeColumn = SomeValue )
If you answered COUNT(*) then maybe you should take a look these two articles
Andrew Kelly has a nice post on SQLBlog
http://sqlblog.com/blogs/andrew_kelly/archive/2007/12/15/exists-vs-count-the-battle-never-ends.aspx
Matija Lah has a good post on his snaps & snippets blog
http://milambda.blogspot.com/2006/10/exists-or-not-exists-that-is-question.html
Text Box Enter Key in ASP.NET
One of the common requests in ASP.NET is to submit a form when visitor hits an Enter key. That could be a case if, for example you want to make Login Screen. It is expected that user just hit enter when he insert a user name and password instead to of forcing him to use a mouse to click login button. If you want to make search function on your web site, it is frequently required to give a possibility to hit enter after you insert a search terms instead of mouse click on a Search button.
In HTML or classic ASP pages is not hard to submit forms using the enter key on keyboard. Programmer use a to make a default button. If web site visitor click on that button or press enter key, the form will be submited.
Of course, you can have a more than one form on your page and individual submit button for every form.
You don’t want to submit a form with Enter key?
Rarely, you will need to disable an Enter key and avoid to submit form. If you want to prevent it completely, you need to use OnKeyDown handler on tag of your page. The javascript code should be:
if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
}
Common ASP.NET problems with Enter key
If you try to use Enter key in ASP.NET, according to your browser’s type, you can get really weird results. For example, try to place one ASP.NET textbox and a button to the web form. Write a code on a OnClick event of a button. That could be something simple, like:
Response.Write(“The button was clicked!”);
Now start debugging and write something to textbox. If you press enter while focus is on textbox, form will submit, but your code for button’s click event will not be executed.
Stop the debuging and place one more simple HTML textbox to the form. You will not write anything in this textbox, so you can even make it invisible. Just place it somewhere inside of your form tag.
Start debugging again. You cannot see the second textbox, and everything looks like before. Try again to write something in first textbox. If you press enter now, form will submit, and your code for button’s click event will now be executed. This is extremely different behavior, and you did nothing except you placed one invisible textbox on web form. :)
Maybe it is not best practice, but placing invisible textbox could be simple solution for you if you have only one button on your web form. But, what if you have a different situation? What if you have a few buttons with only one textbox, or more than one text box with only one button, or many text boxes and many buttons with different code for each button, and all that on one form?
Different browsers have a different behavior in these cases. In case that you have more buttons, only first button will be “clicked” every time. So, we need some other approach to get an universal solution.
Enter Key in ASP.NET
One of the common requests in ASP.NET is to submit a form when visitor hits an Enter key. That could be a case if, for example you want to make Login Screen. It is expected that user just hit enter when he insert a user name and password instead to of forcing him to use a mouse to click login button. If you want to make search function on your web site, it is frequently required to give a possibility to hit enter after you insert a search terms instead of mouse click on a Search button.
In HTML or classic ASP pages is not hard to submit forms using the enter key on keyboard. Programmer use a to make a default button. If web site visitor click on that button or press enter key, the form will be submited.
Of course, you can have a more than one form on your page and individual submit button for every form.
You don’t want to submit a form with Enter key?
Rarely, you will need to disable an Enter key and avoid to submit form. If you want to prevent it completely, you need to use OnKeyDown handler on tag of your page. The javascript code should be:
if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
}
Common ASP.NET problems with Enter key
If you try to use Enter key in ASP.NET, according to your browser’s type, you can get really weird results. For example, try to place one ASP.NET textbox and a button to the web form. Write a code on a OnClick event of a button. That could be something simple, like:
Response.Write(“The button was clicked!”);
Now start debugging and write something to textbox. If you press enter while focus is on textbox, form will submit, but your code for button’s click event will not be executed.
Stop the debuging and place one more simple HTML textbox to the form. You will not write anything in this textbox, so you can even make it invisible. Just place it somewhere inside of your form tag.
Start debugging again. You cannot see the second textbox, and everything looks like before. Try again to write something in first textbox. If you press enter now, form will submit, and your code for button’s click event will now be executed. This is extremely different behavior, and you did nothing except you placed one invisible textbox on web form. :)
Maybe it is not best practice, but placing invisible textbox could be simple solution for you if you have only one button on your web form. But, what if you have a different situation? What if you have a few buttons with only one textbox, or more than one text box with only one button, or many text boxes and many buttons with different code for each button, and all that on one form?
Different browsers have a different behavior in these cases. In case that you have more buttons, only first button will be “clicked” every time. So, we need some other approach to get an universal solution.
How to make a default button in ASP.NET
We need to specify exactly which button will be “clicked” when visitor press Enter key, according to which textbox currently has a focus. The solution could be to add onkeydown attribute to textbox control with this code:
TextBox1.Attributes.Add(“onkeydown”, “if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById(‘”+Button1.UniqueID+”‘).click();return false;}} else {return true}; “);
This line of code will cause that button Button1 will be “clicked” when visitors press Enter key and cursor is placed in TextBox1 textbox. On this way you can “connect” as many text boxes and buttons as you want.
Default buttons in ASP.NET 2.0 and ASP.NET 3.5
ASP.NET 2.0 makes this problems easier and introduce a concept of a “default button”. New defaultbutton attribute can be used with or control. What button will be “clicked” depends of where actually cursor is and what button is chosen as a default button for form or a panel.
———
In asp.net
We can use the Panel/Form Default Button Property to make the button to default press when we press the enter key..
For Panel in asp.net
<asp:Panel ID=”Panel1″ runat=”server” DefaultButton=”">
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:button ID=”btnDefault” runat=”server” Text=”Default Button Panel” OnClientClick=”btnDefault_Click” />
</asp:Panel>
for Form tag in asp.net
<form id=”form1″ runat=”server” defaultbutton=”btnDefault”>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:button ID=”btnDefault” runat=”server” Text=”Default Button Form” OnClientClick=”btnDefault_Click” />
</form>
After making the default button, press enter key on textbox you will notice that without pressing Button click events, btnDefault’s btnDefault_Click is fired.
—
Enjoy Programming
DateTime String Format In Asp.net
Here are some of the string formats that you can try out:
| Specifier | type | output (June 8, 1970 12:30:59) |
|---|---|---|
| dd | Day | 08 |
| ddd | Short Day Name | Mon |
| dddd | Full Day Name | Monday |
| hh | 2 digit hour | 12 |
| HH | 2 digit hour (24 hour) | 12 |
| mm | 2 digit minute | 30 |
| MM | Month | 06 |
| MMM | Short Month name | Jun |
| MMMM | Month name | June |
| ss | seconds | 59 |
| tt | AM/PM | PM |
| yy | 2 digit year | 70 |
| yyyy | 4 digit year | 1970 |
| : | seperator, e.g. {0:hh:mm:ss} | 12:30:59 |
| / | seperator, e.g. {0:dd/MM/yyyy} | 08/06/1970 |
try this way
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”>
<Columns>
<asp:BoundField HeaderText=”CheckDateFormat” DataField=”Date” DataFormatString=”{0:M-dd-yyyy}” />
</Columns>
</asp:GridView>
–
check below one
DateTime dt = DateTime.Now;
String strDate="";
strDate = dt.ToString("MM/dd/yyyy"); // 07/21/2007
strDate = dt.ToString("dddd, dd MMMM yyyy"); //Saturday, 21 July 2007
strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm"); // Saturday, 21 July 2007 14:58
strDate = dt.ToString("dddd, dd MMMM yyyy hh:mm tt"); // Saturday, 21 July 2007 03:00 PM
strDate = dt.ToString("dddd, dd MMMM yyyy H:mm"); // Saturday, 21 July 2007 5:01
strDate = dt.ToString("dddd, dd MMMM yyyy h:mm tt"); // Saturday, 21 July 2007 3:03 PM
strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:04:10
strDate = dt.ToString("MM/dd/yyyy HH:mm"); // 07/21/2007 15:05
strDate = dt.ToString("MM/dd/yyyy hh:mm tt"); // 07/21/2007 03:06 PM
strDate = dt.ToString("MM/dd/yyyy H:mm"); // 07/21/2007 15:07
strDate = dt.ToString("MM/dd/yyyy h:mm tt"); // 07/21/2007 3:07 PM
strDate = dt.ToString("MM/dd/yyyy HH:mm:ss"); // 07/21/2007 15:09:29
strDate = dt.ToString("MMMM dd"); // July 21
strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"); // 2007-07-21T15:11:19.1250000+05:30
strDate = dt.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"); // Sat, 21 Jul 2007 15:12:16 GMT
strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); // 2007-07-21T15:12:57
strDate = dt.ToString("HH:mm"); // 15:14
strDate = dt.ToString("hh:mm tt"); // 03:14 PM
strDate = dt.ToString("H:mm"); // 5:15
strDate = dt.ToString("h:mm tt"); // 3:16 PM
strDate = dt.ToString("HH:mm:ss"); // 15:16:29
strDate = dt.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'"); // 2007-07-21 15:17:20Z
strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:17:58
strDate = dt.ToString("yyyy MMMM"); // 2007 July
Hence we can format and getting the datetime value.
Export DataSet or DataTable to Word, Excel, PDF and CSV Formats
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
Function to get the results in datatable
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.
ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
As you can see above I am passing the query to the GetData function and it returns the results as datatable back.
Export to Word
protected void ExportToWord(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.doc”);
Response.Charset = “”;
Response.ContentType = “application/vnd.ms-word “;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

Export to Excel
Below is the code to export the datatable to Excel Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as Excel Workbook. Also you will notice I applied textmode style to all the rows so that it in rendered as text.
protected void ExportToExcel(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.xls”);
Response.Charset = “”;
Response.ContentType = “application/vnd.ms-excel”;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add(”class”, “textmode”);
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @”<style> .textmode { mso-number-format:\@; } </style>”;
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

Export to Portable Document Format (PDF)
Below is the code to export the datatable to PDF Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as PDF document using the iTextSharp Library which is a free open source library and can be downloaded from here.
protected void ExportToPDF(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.ContentType = “application/pdf”;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.pdf”);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}

Export to Comma Separated Values (CSV)
Below is the code to export the datatable to CSV or Text Format. It first fills the datatable using the GetData function. To export dataset to CSV there is no need of dummy GridView. We just have to loop through the records and append the delimiting character comma.
protected void ExportToCSV(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
Response.Clear();
Response.Buffer = true;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.csv”);
Response.Charset = “”;
Response.ContentType = “application/text”;
StringBuilder sb = new StringBuilder();
for (int k = 0; k < dt.Columns.Count; k++)
{
//add separator
sb.Append(dt.Columns[k].ColumnName + ‘,’);
}
//append new line
sb.Append(”\r\n”);
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
//add separator
sb.Append(dt.Rows[i][k].ToString().Replace(”,”, “;”) + ‘,’);
}
//append new line
sb.Append(”\r\n”);
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}

Master / Detail Editing With a ListView and DetailsView
mplementing a master/detail editing-inserting-deleting interface using the ListView is not much different than doing it with a GridView. Here’s a quick tutorial that shows how it’s done.
I’m sure you’re all familiar with editing records in a master/detail scenario with a GridView and DetailsView. There are probably a thousand tutorials on the ‘net that show how to do this. So, when I happened upon a fellow on the ASP.NET forums asking about doing master/detail editing with the ListView instead of the GridView , my first thought was to post a link and tell him to have at it. However, to my surprise, a quick Google search didn’t really reveal any good, straightforward examples. That being the case, I decided to work one up, which I’ll share with you now.
The ListView is a new databound control introduced with the .NET Framework 3.5. You could think of the ListView as what you might get if a GridView and a Repeater had a baby. Like the GridView, the ListView can display, edit, delete, page, and sort records. And like the Repeater, the ListView is entirely template-driven. Also, the ListView supports inserting new records, functionality provided by neither the GridView nor the Repeater. In fact, due to the extreme flexibility of the ListView, you may find fewer situations in which building a master/detail interface using the DetailsView is needed.
The Solution
The example presented here doesn’t show off any of the native data-manipulation prowess of the ListView. Instead, it only displays and allows user selection of individual records, and passes all of the insertion, editing, and deleting functionality to an accompanying DetailsView.
Again, the tricky part is that with a ListView, you need to build your own presentation code. In the example, I’m displaying the records in a table; however, you could display the records however you want: as a bulleted list, a multicolumn grid, or totally free-form; whatever you want. You also need to provide buttons in the template to initiate the functionality you need. Here, in the ItemTemplate of the ListView, you’ll see a button with CommandName="Select". That allows the datasource for the DetailsView to pick up the value of the record’s primary key and fetch the individual record. Notice that in the SelectedItemTemplate, no button is defined. That means when a record is marked as selected in the ListView, the Select button won’t appear.
The example presented here uses selected fields from the Employees table of the Northwind database, and also uses SqlDataSource for simplicity. If you have the Northwind database, you should be able to paste this code into a blank .aspx file and run it locally. Just be sure to change the connection strings in each SqlDataSource to point to your own Northwind database.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="lvwEmployees" runat="server" DataKeyNames="EmployeeID" DataSourceID="SqlDataSourceEmpList">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("EmployeeID") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
</td>
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
</td>
<td>
<asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select" />
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr style="background-color: yellow; font-weight: bold;">
<td>
<asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("EmployeeID") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
</td>
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
</td>
</tr>
</SelectedItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="1" style="border-collapse: collapse;
border-width: 1px;">
<tr runat="server" style="background-color: #DCDCDC; color: #000000;">
<th runat="server">
EmployeeID
</th>
<th runat="server">
LastName
</th>
<th runat="server">
FirstName
</th>
<th runat="server">
Title
</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSourceEmpList" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title] FROM [Employees] ORDER BY [EmployeeID]">
</asp:SqlDataSource>
<br />
<asp:DetailsView ID="dvwEmployee" runat="server" DataSourceID="SqlDataSourceEmp"
AutoGenerateRows="False" DataKeyNames="EmployeeID">
<Fields>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False"
ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True"
NewText="Add" ButtonType="Button" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSourceEmp" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
DeleteCommand="DELETE FROM [Employees] WHERE [EmployeeID] = @EmployeeID" InsertCommand="INSERT INTO [Employees] ([LastName], [FirstName], [Title]) VALUES (@LastName, @FirstName, @Title)"
SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title] FROM [Employees] WHERE ([EmployeeID] = @EmployeeID)"
UpdateCommand="UPDATE [Employees] SET [LastName] = @LastName, [FirstName] = @FirstName, [Title] = @Title WHERE [EmployeeID] = @EmployeeID">
<SelectParameters>
<asp:ControlParameter ControlID="lvwEmployees" Name="EmployeeID" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="EmployeeID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Title" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
Below is an example of the output you can expect:
Hey, I didn’t say it was gonna be fancy. ;) That part is up to you!
Handling Session Timeouts
With new technology making the web a viable option for more and more applications, we are now seeing the web browser take over for the traditional desktop. Developers making this transition, quickly learn about some of the key differences between the two paradigms. One of the issues they are often forced to deal with is Session expiration. Out of the box, ASP.NET and IIS typically allow only 20 minutes of idle time before the session expires. This can be configured, but knowing that the session expired, or redirecting to a particular page often comes in handy. One way to do this is to add a cookie during the Session_Start method of the global.ascx.cs file, and then check for that same cookie the next time a session is created. If the cookie is there, the session either timed out, or was reset.
Here is an example:
protected void Session_Start(Object sender, EventArgs e)
{
//Check if there is a cookie from when the session started.
//If not, the session has not been started yet,
//so add the cookie.
HttpContext context = HttpContext.Current;
HttpCookieCollection cookies = context.Request.Cookies;
HttpCookie SessionCookie = cookies["SessionStarted"];
if (SessionCookie == null)
{
HttpCookie cookie = new HttpCookie(“SessionStarted”, DateTime.Now.ToString());
cookie.Path = “/”;
context.Response.Cookies.Add(cookie);
}
else
{
//If there was a cookie, but we are in this method starting a session
//Then the session must have expired or been reset.
//TODO: Do something useful with this info, log it, etc.
//update the cookie with the new session start time
cookies.Remove(“SessionStarted”);
SessionCookie.Value = DateTime.Now.ToString();
context.Response.Cookies.Add(SessionCookie);
//Redirect to the whatever page you want to handle this situation.
//An error page, login page, etc.
context.Response.Redirect(“~/Login.aspx”, true);
}
}
—-
thnx…enjoy programming.
What is httpHandler & httpModule?
httpHandler – Extenstion Based Preprocessor :
ASP.NET HTTP handler is the process that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.
httpModule – Event based Preprocessor :
An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.
When to use HTTP handlers:
- RSS feeds: To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
- Image server: If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler’s response.
When to use HTTP modules:
- Security: Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.
- Statistics and logging: Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.
- Custom headers or footers: Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.
Main Features:
- The IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules.
The IHttpAsyncHandler interface is the starting point for developing asynchronous handlers. - Custom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application.
- Handlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change.
- Modules can subscribe to a variety of request-pipeline notifications. Modules can receive notification of events of the HttpApplication object.
Built-in HTTP Handlers in ASP.NET
- ASP.NET page handler (*.aspx): The default HTTP handler for all ASP.NET pages.
- Web service handler (*.asmx): The default HTTP handler for Web service pages created as .asmx files in ASP.NET.
- Generic Web handler (*.ashx): The default HTTP handler for all Web handlers that do not have a UI and that include the @ WebHandler directive.
- Trace handler (trace.axd): A handler that displays current page trace information.
URL rewriting in asp.net
what is URL rewriting ?
URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL.
http://msdn.microsoft.com/en-us/library/ms972974.aspx
why URL rewriting?
1) Make User Friendly and Secure URL
Example : In your application, you create a page which display category information and it’s relevant category. At that time we normally passing a value via query string,
http://Site.com/category.aspx?categoryid=1. Any user play with URL, you can also do the URL Encryption. but sometime case is complex at that time it is not possible.
2) Make SEO Friendly URL
3) Usability & Maintainability
Use Of Browser file?
ASP.NET uses .browser files to determine the capabilities of the browser, and how to render markup to that browser.
Browser files are used to reduce the load of the page made by the view state by storing it in a server side session variable.
In particular Rewriting Module: Handling Post back with URL Rewriting.
what is ControlAdapter?
for more detail please check :
http://msdn.microsoft.com/en-us/library/system.web.ui.adapters.controladapter.aspx
Create demo project for URL Rewriting:
Step 1:
Create Web application with (Asp.net 2.0 with c#)
Step 2:
Put two button in the form (default.aspx)
Put Below code for Button1_Click Event :
Response.Redirect(“Default.aspx?id=1″);
Put Below code for Button2 _Click Event:
Response.Redirect(“/urlrewriting/FirstSection/Default.html”);
Step 3: Run Application
once you press Button2 it give Error page.
Step 4:
Create Class FormRewriterControlAdapter.cs
1: using System;
2: using System.Data;
3: using System.Configuration;
4: using System.Web;
5: using System.Web.Security;
6: using System.Web.UI;
7: using System.Web.UI.WebControls;
8: using System.Web.UI.WebControls.WebParts;
9: using System.Web.UI.HtmlControls;
10:
11: public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter
12: {
13: protected override void Render(HtmlTextWriter writer)
14: {
15: base.Render(new RewriteFormHtmlTextWriter(writer));
16: }
17: }
18:
19: public class RewriteFormHtmlTextWriter : HtmlTextWriter
20: {
21: public RewriteFormHtmlTextWriter(HtmlTextWriter writer)
22: : base(writer)
23: {
24: this.InnerWriter = writer.InnerWriter;
25: }
26:
27: public RewriteFormHtmlTextWriter(System.IO.TextWriter writer)
28: : base(writer)
29: {
30: base.InnerWriter = writer;
31: }
32:
33: public override void WriteAttribute(string name, string value, bool fEncode)
34: {
35: if (name == “action”)
36: {
37: HttpContext Context = HttpContext.Current;
38: if (Context.Items["ActionAlreadyWritten"] == null)
39: {
40: value = Context.Request.RawUrl;
41: Context.Items["ActionAlreadyWritten"] = true;
42: }
43: }
44: base.WriteAttribute(name, value, fEncode);
45: }
46: }
Create Class MyHttpHandler.cs
1: using System;
2: using System.Data;
3: using System.Configuration;
4: using System.Web;
5: using System.Web.Security;
6: using System.Web.UI;
7: using System.Web.UI.WebControls;
8: using System.Web.UI.WebControls.WebParts;
9: using System.Web.UI.HtmlControls;
10:
11: public class MyHttpHandler : IHttpModule
12:
13: {
14: public MyHttpHandler()
15: {
16: //
17: // TODO: Add constructor logic here
18: //
19: }
20:
21: #region IHttpModule Members
22:
23: public void Dispose()
24: {
25:
26: }
27:
28: public void Init(HttpApplication app)
29: {
30: app.BeginRequest += new EventHandler(Application_BeginRequest);
31: }
32:
33: private void Application_BeginRequest(object sender, EventArgs e)
34: {
35: System.Web.HttpApplication app = (System.Web.HttpApplication)sender;
36: string requestedUrl = app.Request.Path.ToLower();
37: string realUrl = GetRealUrl(requestedUrl);
38: if (!String.IsNullOrEmpty(realUrl))
39: app.Context.RewritePath(realUrl, false);
40: }
41:
42: private string GetRealUrl(string requestedUrl)
43: {
44: // Implement your own logic here
45: MyURL obj = new MyURL();
46: return obj.GetRealPath(requestedUrl);
47: }
48: #endregion
49: }
create Class MyURL.cs
1:
2: using System;
3: using System.Data;
4: using System.Configuration;
5: using System.Web;
6: using System.Web.Security;
7: using System.Web.UI;
8: using System.Web.UI.WebControls;
9: using System.Web.UI.WebControls.WebParts;
10: using System.Web.UI.HtmlControls;
11: using System.Collections.Generic;
12:
13: /// <summary>
14: /// Summary description for MyURL
15: /// </summary>
16: public class MyURL
17: {
18: public MyURL()
19: {
20: //
21: // TODO: Add constructor logic here
22: //
23: }
24:
25: public string GetRealPath(string requestedUrl)
26: {
27: string path = “”;
28: Dictionary<string, string> paths = GetPathsFromDatabase();
29: if (paths.ContainsKey(requestedUrl))
30: paths.TryGetValue(requestedUrl, out path);
31: return path;
32: }
33:
34: private static Dictionary<string, string> GetPathsFromDatabase()
35: {
36: Dictionary<string, string> paths = new Dictionary<string, string>();
37: paths.Add(“/urlrewriting/FirstSection/Default.html”.ToLower(), “/urlrewriting/Default.aspx?SectionID=1″);
38: paths.Add(“/urlrewriting/SecondSection/Default.aspx”.ToLower(), “/urlrewriting/Default.aspx?SectionID=2″);
39: paths.Add(“/urlrewriting/FirstSection/Page1.aspx”.ToLower(), “/urlrewriting/Default.aspx?SectionID=1&Item=1″);
40: paths.Add(“/urlrewriting/FirstSection/Page2.aspx”.ToLower(), “/urlrewriting/Default.aspx?SectionID=1&Item=2″);
41: paths.Add(“/urlrewriting/SecondSection/Page1.aspx”.ToLower(), “/urlrewriting/Default.aspx?SectionID=2&Item=1″);
42: paths.Add(“/urlrewriting/SecondSection/SubSection/AnotherOne/Page5.aspx”.ToLower(), “/urlrewriting/Default.aspx?SectionID=2&Item=5″);
43: paths.Add(“/urlrewriting/Default.aspx”.ToLower(), “/urlrewriting/Default.aspx”);
44: return paths;
45: }
46: }
Register Http Handler in to Web.Config
1: <system.web>
2: <httpModules>
3: <add name=”MyHttpHandler” type=”MyHttpHandler”/>
.Browser File
Add New .browser file from Add New Item.
1: <browsers>
2: <browser id=”NewBrowser” parentID=”Mozilla”>
3: <identification>
4: <userAgent match=”Unique User Agent Regular Expression” />
5: </identification>
6:
7: <capture>
8: <userAgent match=”NewBrowser (?’version’\d+\.\d+)” />
9: </capture>
10:
11: <capabilities>
12: <capability name=”browser” value=”My New Browser” />
13: <capability name=”version” value=”${version}” />
14: </capabilities>
15: </browser>
16:
17: <browser refID=”Mozilla”>
18: <capabilities>
19: <capability name=”xml” value=”true” />
20: </capabilities>
21: </browser>
22: <!–FormRewrite Control Adapter–>
23: <browser refID=”Default”>
24: <controlAdapters>
25: <adapter controlType=”System.Web.UI.HtmlControls.HtmlForm”
26: adapterType=”FormRewriterControlAdapter” />
27: </controlAdapters>
28: </browser>
29: </browsers>
step 5: Run Application
Now Press Button 2:
http://localhost:2696/urlrewriting/FirstSection/Default.html and it is run.
Now made some change in to system. Remove browser file and click button2, after that made postback at that time above URL is change to original URL.
Reference Site :
For Detail Example :
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx
Hope this help you.
Thnx
How do I get the IDENTITY / AUTONUMBER value for the row I inserted?
To get the indentity value of table we can use any of these:
1) INDENT_CURRENT : – IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
SELECT IDENT_CURRENT(’tablename’):- It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns theidentity value generated for a specific table in any session and any scope.
2) @@IDENTITY :- @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
SELECT @@IDENTITY :- It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get theidentity that was created last, even if it was the trigger that created it.
3) SCOPE_IDENTITY :- SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.
SELECT SCOPE_IDENTITY() :- It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a userdefined function.
Examaple of each:
Create Table #Table
(
Id int identity(1,1),
[name] varchar(10)
)
insert into #Table
select ‘P’
insert into #Table
select ‘S’
insert into #Table
select ‘G’
insert into #Table
select ‘PP’
select * From #Table
Select @@Identity As InsertId,IDENT_CURRENT(‘#Table’) As InsertId,SCOPE_IDENTITY() As InsertId
Drop table #Table
——————————————
Note : To avoid the potential problems associated with adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.
——————————————
Happy Programming…
Basic Differences in .Net
- Difference between == and .Equals Method?
- Difference between Close() and Dispose() Method
- Difference between Copy and Clone Method
- Value Type Vs Reference Type
- Struct Vs Class
- Static Member, Static Method, Static Constructor
- Difference between ADO and ADO.net Technology
- Difference between ADO.net Dataset and ADO Recordset
- Localization Vs Globalization
- Difference Between String and StringBuilder
- Response.Redirect(url,true) Vs Response.Redirect(url,false)
- Finalize Method Vs Destructor
- Difference between ExecuteReader, ExecuteNonQuery and ExecuteScalar.
- Difference between Dataset and DataReader
- “out” keyword Vs “ref” keyword
1.
What is Difference between == and .Equals() Method?
For Value Type: == and .Equals() method usually compare two objects by value.
For Example:
int x = 10;
int y = 10;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));
Will display:
True
True
For Reference Type: == performs an identity comparison, i.e. it will only return true if both references point to the same object. While Equals() method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.
For Example:
StringBuilder s1 = new StringBuilder(“Yes”);
StringBuilder s2 = new StringBuilder(“Yes”);
Console.WriteLine(s1 == s2);
Console.WriteLine(s1.Equals(s2));
Will display:
False
True
In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true. Remember there is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.
When to use “==” operator and when to use “.Equals()” method?
For value comparison, with Value Tyep use “==” operator and use “Equals()” method while performing value comparison with Reference Type.
2.
Difference between Close() and Dispose() Method
Close() Vs Dispose Method
The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.
Example showing difference between Close() and Dispose() Method:
using System;
using System.Data;
using System.Data.SqlClient;
public class Test
{
private string connString = “Data Source=COMP3;Initial Catalog=Northwind;User;Password=pass”;
private SqlConnection connection;
public Test()
{
connection = new SqlConnection(connString);
}
private static void Main()
{
Test t = new Test();
t.ConnectionStatus();
Console.ReadLine();
}
public void ConnectionStatus()
{
try
{
if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine(“Connection opened..”);
}
if(connection.State == ConnectionState.Open)
{
connection.Close();
Console.WriteLine(“Connection closed..”);
}
// connection.Dispose();
if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine(“Connection again opened..”);
}
}
catch(SqlException ex)
{
Console.WriteLine(ex.Message+”\n”+ex.StackTrace);
}
catch(Exception ey)
{
Console.WriteLine(ey.Message+”\n”+ey.StackTrace);
}
finally
{
Console.WriteLine(“Connection closed and disposed..”);
connection.Dispose();
}
}
}
In the above example if you uncomment the “connection.Dispose()” method and execute, you will get an exception as, “The ConnectionString property has not been initialized.”.This is the difference between Close() and Dispose().
3.
What is the difference between Copy and Clone Method.
Copy Vs Clone Method
Clone will copy the structure of a data where as
Copy will copy the complete structure as well as data .
4.
Value Type and Reference Type Concept in .Net
A variable is value type or reference type is solely determined by its data type.
Eg: int, float, char, decimal, bool, decimal, struct, etc are value types, while object type such as class, String, Array, etc are reference type.
Value Type
1) As name suggest Value Type stores “value” directly.
2) For eg:
//I and J are both of type int
I = 20;
J = I;
int is a value type, which means that the above statements will results in two locations in memory.
3) For each instance of value type separate memory is allocated.
4) Stored in a Stack.
5) It Provides Quick Access, because of value located on stack.
Reference Type
1) As name suggest Reference Type stores “reference” to the value
2) For e.g.:
Vector X, Y; //Object is defined. (No memory is allocated.)
X = new Vector(); //Memory is allocated to Object. //(new is responsible for allocating memory)
X.value = 30; //Initialising value field in a vector class
Y = X; //Both X and Y points to same memory location. //No memory is created for Y.
Console.writeline(Y.value); //displays 30, as both points to same memory
Y.value = 50;
Console.writeline(X.value); //displays 50
Note: If a variable is reference it is possible to indicate that it does not refer to any object by setting its value to null;
3) Reference type are stored on Heap
4) It provides comparatively slower access, as value located on heap
Note:
The behavior of strings is different, strings are immutable (unchangeable) if we alter a strings value, we create an entirely new string), so strings don’t display the typical reference-type behavior. Any changes made to a string within a method call won’t affect the original string.
5.
Difference between Struct and Class
Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.
Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.
Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.
Choosing between struct and class
Use of structure in following condition is desirable.
When you have small data structure
Data Structure does not require to extent the functionality.
When you want to perform faster operation on data structure. (As structure are stored on stack, operation performed on it are faster.)
Use of class in following condition is desirable.
When you have complex data structure
Data Structure requires to extend functionality.
When you want to optimize memory usage. (As class is stored on heap, they are about to be garbage collected when no reference pointing to an object.)
What is the difference between instantiating structures with and without using the new Keyword?
When a structure is instantiated using the new keyword, a constructor (no-argument or custom, if provided) is called which initializes the fields in the structure. When a structure is instantiated without using the new keyword, no constructor is called. Hence, one has to explicitly initialize all the fields of the structure before using it when instantiated without the new keyword.
6.
Static Members of the class
“static members” belong to the whole class rather than to individual object
How to access static member of class?
Static members are accessed with the name of class rather than reference to objects. Example: className.StaticMemberName
Example of Static Member
class Test
{
public int rollNo;
public int mathsMarks;
public static int totalMathMarks;
}
class TestDemo
{
public static void main()
{
Test stud1 = new Test();
stud1.rollNo = 1;
stud1.mathsMarks = 40;
stud2.rollNo = 2;
stud2.mathsMarks = 43;
Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;
}
}
Static Method of the class
- Static Method is Method that you can call directly without first creating an instance of a class. Example: Main() Method, Console.WriteLine()
- You can use static fields, methods, properties and even constructors which will be called before any instance of the class is created.
- As static methods may be called without any reference to object, you can not use instance members inside static methods or properties, while you may call a static member from a non-static context. The reason for being able to call static members from non-static context is that static members belong to the class and are present irrespective of the existence of even a single object.
Static Constructor
In C# it is possible to write a static no-parameter constructor for a class. Such a class is executed once, when first object of class is created.
One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used.
Example
Class MyClass
{
static MyClass()
{
//Initialization Code for static fields and properties.
}
}
7.
Difference between ADO and ADO.net
1. ADO used connected data usage, while ADO.net used disconnected data environment.
2. ADO used OLE DB to access data and is COM-based, while ADO.net uses XML as the format for transmitting data to and from your database and web application.
3. In ADO, Record set, is like a single table or query result, while in ADO.net Dataset, can contain multiple tables from any data source.
4. In ADO, it is sometime problematic because firewall prohibits many types of request, while in ADO.net there is no such problem because XML is completely firewall-proof.
8.
Difference between ADO.net Dataset and ADO Recordset
1 A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
2 A DataSet is designed to work without any continuing connection to the original data source.
3 Data in a DataSet is bulk-loaded, rather than being loaded on demand.
There’s no concept of cursor types in a DataSet.
4 DataSets have no current record pointer You can use For Each loops to move through the data.
5 You can store many edits in a DataSet, and write them to the original data source in a single operation.
6 Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
10.
Difference Between String and StringBuilder
| String Class | StringBuilder |
| Once the string object is created, its length and content cannot be modified. | Even after object is created, it can be able to modify length and content. |
| Slower | Faster |
11.
To avoid ThreadAbortException while Redirect
You don’t need to put the redirect in a try-catch block. Just replace all calls to Response.Redirect(url) with the following two lines:
Response.Redirect(url, false);
That will avoid the exception being thrown and gracefully end execution of the thread and event chain. See http://www.c6software.com/CodeSolutions/dotnet/ThreadAbortException.aspx for a full solution explanation.
12.
What is difference between ExecuteReader, ExecuteNonQuery and ExecuteScalar.
- ExecuteReader : Use for accessing data. It provides a forward-only, read-only, connected recordset.
- ExecuteNonQuery : Use for data manipulation, such as Insert, Update, Delete.
- ExecuteScalar : Use for retriving 1 row 1 col. value., i.e. Single value. eg: for retriving aggregate function. It is faster than other ways of retriving a single value from DB.
13.
Difference between Dataset and DataReader : Points to be consider while choosing between the DataSet and DataReader objects
DataSet object |
DataReader object |
| Read/Write access | Read-only access |
| Supports multiple tables from different databases | Supports a single table based on a single SQL query of one database |
| Disconnected mode | Connected mode |
| Bind to multiple controls | Bind to a single control |
| Forward and backward scanning of data | Forward-only scanning of data |
| Slower access to data | Faster access to data |
| Greater overhead to enable additional features | Lightweight object with very little overhead |
| Supported by Visual Studio .NET tools | Must be manually coded |
14.
What is “out” keyword in C# ??
“out Keyword” in C#.
out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized.
It is useful when we want to return more than one value from the method.
Point to be kept in mind while using out keyword.
You must assigned value to out parameter in method body, otherwise the method won’t compiled.
Example of “out keyword”:
class Test
{
public static void Main()
{
int a; // may be left un-initialized
DoWork(out a); // note out
Console.WriteLine(“The value of a is ” + a);
}
public static void DoWork(out int i) // note out
{
i=4; //must assigned value.
}
}
The program will result : The value of a is 4
15. —————————
.Net managed code enjoy’s benefits of CLR, which automatically checks for object scope and if it is not referenced by any object than it is removed from memory.
But you can also manually frees memory….
Finalize() Method of Object class
Each class in C# is automatically (implicitly) inherited from the Object class which contains a method Finalize(). This method is guaranteed to be called when your object is garbage collected (removed from memory). You can override this method and put here code for freeing resources that you reserved when using the object.
Example of Finalize Method
Protected override void Finalize()
{
try
{
Console.WriteLine(“Destructing Object….”);//put some code here.
}
finally
{
base.Finalize();
}
}
Destructor
1) A destructor is just opposite to constructor.
2) It has same as the class name, but with prefix ~ (tilde).
3) They do not have return types, not even void and therefore they cannot return values.
4) destructor is invoked whenever an object is about to be garbage collected
Example of Destructor in .Net
class person
{
//constructor
person()
{
}
//destructor
~person()
{
//put resource freeing code here.
}
}
What is the difference between the destructor and the Finalize() method? When does the Finalize() method get called?
Finalize() corresponds to the .Net Framework and is part of the System.Object class. Destructors are C#’s implementation of the Finalize() method. The functionality of both Finalize() and the destructor is the same, i.e., they contain code for freeing the resources when the object is about to be garbage collected. In C#, destructors are converted to the Finalize() method when the program is compiled. The Finalize() method is called by the .Net Runtime and we can not predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.
Garbage Collection Concept
1) Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable.
2) .Net Runtime performs automatically performs garbage collection, however you can force the garbage collection to run at a certain point in your code by calling System.GC.Collect().
3) Advantage of Garbage collection : It prevents programming error that could otherwise occur by incorrectly deleting or failing to delete objects.
-
Archives
- April 2011 (1)
- May 2010 (1)
- April 2010 (1)
- February 2010 (3)
- January 2010 (5)
- December 2009 (6)
- November 2009 (13)
- October 2009 (10)
- September 2009 (6)
- August 2009 (7)
- July 2009 (7)
- June 2009 (3)
-
Categories
-
RSS
Entries RSS
Comments RSS