Thursday, October 29, 2009

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

Wednesday, October 28, 2009

BAD DESIGN



now check this one.
i have developed this..



now this is your choice to find the best UI.

According to me second one is good.

Monday, October 26, 2009

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

Saturday, October 24, 2009

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();
}
image
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 = @””;
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
image1
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();
}
image2
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();
}
image3

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:
listview-detailsview
Hey, I didn't say it was gonna be fancy. ;) That part is up to you!

Friday, October 23, 2009

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.

Thursday, October 22, 2009

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.

Wednesday, October 14, 2009

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: ///

14: /// Summary description for MyURL

15: ///

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:

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

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...