Search This Blog

Monday, August 29, 2011

How to make your website off line using app_offline.htm


If you place a file with this name (app_offline.htm) in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.  ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the app_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

This provides a convenient way to take down your application while you are making big changes or copying in lots of new page functionality (and you want to avoid the annoying problem of people hitting and activating your site in the middle of a content update).  It can also be a useful way to immediately unlock and unload a SQL Express or Access database whose .mdf or .mdb data files are residing in the /app_data directory.

Once you remove the app_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and life will continue along as normal.

Sample app_offline.htm 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Application Offline</title>
    <style  type="text/css">

    div {
        background-color:#ffffcc;
        padding-top:10px;
        padding-bottom:10px;
        padding-left:10px;
        padding-right:10px;   
        border-style:solid;
        border-color:Black;
        border-width:1px;
    }

    </style>
</head>
<body>
    <div>
        This application is currently offline.  To enable the application, remove the
        app_offline.htm file from the application root directory.
    </div>
</body>
</html>


Friday, August 26, 2011

Advantages and Disadvantages of Frames


A frames page itself contains no visible content, it contains instructions on which pages to show simultaneously and how they will be displayed within the browser window . Think of it as a clear overlay, much like a paneled window frame - except this window frame allows you to look into different rooms of the house. A frames page can contain references to many other pages, but usually they consist of references to pages to be used as the header, the content, a left hand menu bar and a perhaps a footer bar. When a hyperlink is clicked in one frame, say the left hand navigation window, it will open a page in the content window, or the target frame.


This makes site-wide changes easy to implement (especially when used in conjunction with Cascading Style Sheets) as you can change the items such as the menu bar and logo for your site in one page, and that will update the entire site.


Using a frame for the header (top) area or navigation bar of your pages will also make it static (fixed) so visitors can easily access menus etc... no more scrolling back up the page.


All this sounds great, but there are a number of points you need to consider before implementing a framed site, especially when using WYSIWYG (What You See Is What You Get) web page editors .


1) Many search engines cannot index framed sites. Because the home page is merely a frame, with very little content or hyperlinks to follow, search engine spiders may stop dead on the page and have 'nothing to report'. A way around this is the proper implementation of Meta tags and use of the "noframes" tag.


2) If a search engine does manage to spider your site, visitors from search engines may land on the content pages, rather than the full-framed version, i.e. they may arrive on your site and all they will see is the menu bar.

Search Engines

Search engines don't deal with frames well. Some search engines can't follow framed pages at all, but even the best search engines will have problems. More importantly, many search engines choose not to index frames because they are so problematic.

Although search engines can theoretically index frames well enough, there is no way to reliably organize them in a database and display them in results pages using the correct framesets. Remember that search engines find individual pages with the relevant content, and then have to work backwards to determine which frameset each page belongs to. How would they do that? Answer: They can't, so they don't try.

In theory, for very small databases, there might be some way to track and record framesets. This would be impractical for large search engines, but it would also be hopelessly unreliable. For example, if a page appears in two different framesets, how would a search engine know which frameset to use when that page is returned in a result? What happens when a page is moved from one frameset to another, or placed in a frameset temporarily — how would the search engines know? There are many other such problems which make frames unsuitable for search result pages.

So.... search engines can't reconstruct framesets from individual pages. The only option is to show the pages isolated (independent of their frameset). Therefore most search listings to framed pages result in broken framesets.
The situation with search engines will not change for two reasons:
  1. The root of the problem is with frames themselves, not the search engines, so there is little hope that search engines will "get better" at dealing with them.
  2. Frames are out of fashion, especially amongst the types of site the search engines are trying to target, so the problems associated with frames are not a priority for search engines.
Note: Search engines index the "noframes" content of a frameset, which is why search engines will often show a site's description as: "Sorry, your browser doesn't support frames so you are unable to view this website". That's not going to attract many visitors! You can get around this to some extent by providing better noframes content, but it's more work and will never have the same results as standard pages.

3) Non-frames capable browsers. Fortunately, only 1% of visitors browsers fall into this category. Once again the use of the 'noframes' tag will assist, but to be used effectively you basically need to create two sites, one framed, one not - the "time saving" is suddenly gone.


4) Bookmarking. A visitor cannot bookmark a specific page in your site without requiring additional customised scripting for each page. Even then there is a risk of visitors landing on the content frame, with no navigation frames to view.


5) Visitor opinion. Many find frames annoying.


6) Copyright issues. You'll need to ensure that all links within your site that point to external sources open in a new window to avoid copyright wrangles. There have been legal precedents in relation to this issue. Many site owners object to their content appearing in someone else's frame, to the point that special "frame busting" code is used.


7) Internal linking. Special attention will need to be paid to your internal links to ensure that any page pointing to, for example, the home page opens as a "whole page", otherwise the framed home page will appear in the target window, causing confusion to visitors.


8) Printing issues. Visitors need to take further steps within their print settings to ensure the information they want is printed correctly. In most cases, a full page cannot be printed as displayed on the screen, only in sections corresponding to the frame.


9) Scroll bars, divider bars. If your framed site uses a number of frames, scroll bars can prove to be unsightly. These can be removed, but check compatibility with other popular browsers. (See further resources at the end of this article).


10) External linkages to your site. If other sites wish to link to specific pages in your site, it is more difficult for them to do so.


11) Refresh/Reload problems. Again, special care needs to be taken with coding otherwise   when a visitor tries to refresh a particular page, they may be taken back to the original frameset. A common problem.



Working with frames in asp.net


Introduction

Any developer who has had the dubious task of developing a Web site utilizing frames knows it can be an uphill battle. Many argue that frames should be avoided at all costs, while others realize how they can benefit a Web site's user interface. When my team had to develop a Web site that displayed pdf's in a management dashboard, we knew frames were the way to go. Unfortunately, we were not sure how to best work with frames in ASP.NET. When I used my list of normal search engines/newsgroups, I could not find much in the way of useful information. Here is one reply I got when asking how to best work with frames in .NET:

Ok, My list of suggestion for Frames.
  1. Frames are Evil
  2. The Devil created Frames
  3. If you are having a problem related to the Target, refer to item 1
  4. If you are trying to refresh data in a particular frame, refer to 1
I think you get the idea. The fact of the matter is frames can provide an aesthetically pleasing site, which in many situations is more user-friendly. This of course is only the case if you avoid the pitfalls of frames, such as multiple scroll bars and too many frame windows. I will not address these pitfalls in this article because there is certainly an over-abundance of information/opinions on that subject. In my opinion frames have gotten a bad reputation from users because so many developers misused them. On the other hand they have a well deserved reputation from the developer side because in the past they were very difficult to work with. The purpose of this article is to show you that this is no longer the case. I will also present one alternative to using frames, called Smart Navigation.

In the end we solved the problem of working with frames by utilizing a mix of JavaScript code and the Attributes property of .NET Web Forms. This is essentially the key behind working with frames in .NET.
Frames and Frame Alternatives

Although this article will be used to address the usage of frames in .NET, it is important to talk about the use of frames and some alternatives. My team has developed the majority of our sites without frames because they did not fit into a model in which they were required. We use frames when we need to present the users with a control or set of controls that maintain a certain state, while another part of the page needs to load a file in or some other type of control(s). The MSDN site illustrates a good use of frames in its library section: http://msdn.microsoft.com/library/default.asp In the past we have also used frames to control screen refresh. On an ASP 2.0 or 3.0 page, the entire page would refresh any time you needed to perform a server side event. One alternative to solving the screen refresh issue in ASP.NET is Smart Navigation. This tag can be set at page level through page properties, or at site level through web.config. With this turned on, only the controls within the form tag will be refreshed. So if you have other images, headers, etc., the users will not get screen flicker. It is important to note that behind the scenes ASP.NET is using Iframes, so this will only work on IE5.0 and greater browsers. The use of inline frames allows for this targeted refresh because each frame is treated independently. The following link will provide you with more information on Iframes and some issues related to them: http://www.cs.tut.fi/~jkorpela/html/iframe.html 

To see how Smart Navigation can be used, let's take a look at an example.

<%@ Page Language="vb" AutoEventWireup="false" 
Codebehind="smart_tag.aspx.vb" Inherits="asptoday_frames.smart_tag" 
smartNavigation="True"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
	<HEAD>
		<title>smart_tag</title>
		<meta content="Microsoft Visual Studio.NET 7.0" 
name="GENERATOR">
		<meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
		<meta content="JavaScript" name="vs_defaultClientScript">
		<meta content="http://schemas.microsoft.com/intellisense/ie5"    
name="vs_targetSchema">
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="frmImage" style="Z-INDEX: 101; LEFT: 6px; POSITION: 
absolute; TOP: 18px" runat="server">
<asp:button id="btnRefresh" style="Z-INDEX: 104; LEFT: 19px; POSITION: 
absolute; TOP: 13px" runat="server" Text="Refresh"></asp:button><asp:label id="lblRefresh" 
style="Z-INDEX: 105; LEFT: 96px; POSITION: absolute; TOP: 18px" 
runat="server"></asp:label></form>
		<IMG style="Z-INDEX: 103; LEFT: 27px; WIDTH: 507px; POSITION: 
absolute; TOP: 87px; HEIGHT: 259px" height="259" alt="" src="test.GIF" 
width="507">
		<IMG style="Z-INDEX: 102; LEFT: 16px; WIDTH: 507px; POSITION: 
absolute; TOP: 78px; HEIGHT: 259px" height="259" alt="" src="test.GIF" 
width="507">
	</body>
</HTML>
Code Behind

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class smart_tag : System.Web.UI.Page
{
	private System.Web.UI.WebControls.Button withEventsField_btnRefresh;
	protected System.Web.UI.WebControls.Button btnRefresh {
		get { return withEventsField_btnRefresh; }
		set {
			if (withEventsField_btnRefresh != null) {
				withEventsField_btnRefresh.Click -= btnRefresh_Click;
			}
			withEventsField_btnRefresh = value;
			if (withEventsField_btnRefresh != null) {
				withEventsField_btnRefresh.Click += btnRefresh_Click;
			}
		}
	}

	protected System.Web.UI.WebControls.Label lblRefresh;
	private void Page_Load(System.Object sender, System.EventArgs e)
	{
		this.lblRefresh.Text = "";
	}

	private void btnRefresh_Click(System.Object sender, System.EventArgs e)
	{
		this.lblRefresh.Text = "Page Refreshed";
	}
	public smart_tag()
	{
		Load += Page_Load;
	}
}

At the top of the page we are setting smartNavigation="True" so that the only the lblRefresh and btnRefresh make a roundtrip to the server. I have added two images at the bottom of the page to illustrate the difference that smart navigation makes. If you set smartNavigation = False, you will notice some flashing of the images, even when running local to the Web server. IFrames can be useful in forcing refresh of only part of the screen, but it cannot fully replace the functionality that comes with working with regular frames. The biggest drawback with Iframes is that you cannot implement two separate form tags in the same page, which may be required for some sites.

Questions Regarding Frames
The main problem that most people have when working with frames is cross-frame communication. There are several consistent questions I see on frames including:
  • How do I pass data to another frame?
  • How do I refresh a specific frame?
    This issue is compounded when you start dealing with pop-up windows.

The Solution
Solving the above described problems has become much easier with some basic knowledge of the windows and frames properties in javascript and the ASP.NET Attributes property. In this article I am going to break my code up into several sections, starting with a very easy to follow hello world style example. After that I will address working with pop-ups, adding a very useful HTML control into the mix.
The Code

Goal #1: Pass data between left and right frames
UI Design
Before I get into the code, it is important that you receive the visual of the two frames that we will be working with:
CODE
For the purpose of brevity, I will exclude code automatically generated by Web forms.
To start we have the simple default.htm page that will contain our two aspx pages.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
	<head>
		<title>How to Work with frames in .Net</title>
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" 
content="http://schemas.microsoft.com/intellisense/ie5">
		<meta name="GENERATOR" content="Microsoft Visual Studio.NET 
7.0">
		<meta name="ProgId" content="VisualStudio.HTML">
		<meta name="Originator" content="Microsoft Visual Studio.NET 
7.0">
	</head>
	<frameset border="1" frameborder="1" framespacing="0" 
cols="30%,70%">

<frame name="left frame" src="leftframe.aspx"/>
<frame name="right frame" src="rightframe.aspx"/>

</frameset>
</html>
Next is the left frame page, which will contain a mix of javascript and VB.NET code. The mix of this code will enable us to pass a text string from a textbox on the left frame to a textbox in the right frame.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class leftframe : System.Web.UI.Page
{
	protected System.Web.UI.WebControls.Button btnTright;
	protected System.Web.UI.WebControls.Button btnPop;

	protected System.Web.UI.WebControls.TextBox txtTright;
	private void Page_Load(System.Object sender, System.EventArgs e)
	{
		//enclose the add attributes in the not is post back block, so they
		// are called to be added only once.
		if (!IsPostBack) {
			btnTright.Attributes.Add("onclick", "javascript:tranRight(txtTransferRight.value)");
			btnPop.Attributes.Add("onclick", "javascript:openWindow()");
			//remove file name from session
			Session.Remove("fileName");
		}

	}
	public leftframe()
	{
		Load += Page_Load;
	}

}
The key to working with frames is the Attributes property along with its Add method, which allows us to dynamically insert calls to javascript functions, passing in our server side control's data. The Attributes property allows you to declare any event handler that is associated with a specific Web control. Any of the attributes that you add to the controls collection will be rendered at run time. For a text box you could add a call to the textchanged event. Note, if you do make reference to an unsupported event, it will be ignored by the browser. For now you can ignore the session remove, which will be needed for a later part of this article. Here is the HTML code that exists for the left frame page.

<%@ Page Language="vb" AutoEventWireup="false" 
Codebehind="leftframe.aspx.vb" Inherits="asptoday_frames.leftframe"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
	<HEAD>
		<title>leftframe</title>
		<meta content="Microsoft Visual Studio.NET 7.0" 
name="GENERATOR">
		<meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
		<meta content="JavaScript" name="vs_defaultClientScript">
		<meta content="http://schemas.microsoft.com/intellisense/ie5" 
name="vs_targetSchema">
	</HEAD>
	<body MS_POSITIONING="GridLayout">
<form id="frmTransterRight" method="post" runat="server">
<asp:button id="btnTransferRight" style="Z-INDEX: 101; LEFT: 23px; 
POSITION: absolute; TOP: 100px" runat="server" Text="Send to right frame" 
Width="131px"></asp:button><asp:textbox 
id="txtTransferRight" style="Z-INDEX: 102; LEFT: 26px; POSITION: absolute; TOP: 
64px" runat="server" Width="170px" Height="24px">Text to go to right 
frame</asp:textbox><asp:button id="btnPop" style="Z-INDEX: 103; 
LEFT: 24px; POSITION: absolute; TOP: 136px" runat="server" Text="Open Pop-Up" 
Width="129px"></asp:button></form>
<script language="javascript">		

//this function takes a value (ltext) and transmits that to the left hand frame

function tranRight(ltext)
{
   parent.frames(1).document.forms("frmReceive").item("txtReceive").value = ltext;	
}
</script>
</body>
Notice the tranRight javascript function, which will enable us to transfer the text in the left frame to the right frame. The tranRight function is called from the click event of the btnTransferRight button Parent.Frames(1) indicates we are targeting the right frame, while Parent.Frames(0) is the current page that the code is getting initialized from. When the btnTransferRight button is clicked, only the left frame will be re-rendered because the button's event is set to run client side. 


With that simple code, we have established basic interaction between our frames.

Goal #2: Pass text between pop-up and right frame
In this section we will pass text from a pop-up screen launched from the left frame to a textbox in the right frame. UI Design The "Send Via QS" button will trigger the event that will transmit the text. The lower section of this UI will be addressed in Goal#3

UI Code
The first key is the code which allows this pop-up to be launched from the left frame. This is a line in the original left frame codebehind listed as part of example #1:
 
btnPop.Attributes.Add("onclick", "javascript:openWindow()")
This is the JavaScript which launches this pop-up:

function openWindow() 
{ msgWindow=window.open("popup.aspx","", 
"fullscreen=no,toolbar=no,status=yes,menubar=yes,scrollbars=no,resizable=no,
directories=no,location=no,width=500,height=400"); 
if (msgWindow.opener == null) msgWindow.opener = self; }
Now that we have established the launch of the popup, we can look at the pageload event of the popup Web form.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class popup : System.Web.UI.Page
{
	protected System.Web.UI.HtmlControls.HtmlInputButton btnLfile;
	protected System.Web.UI.WebControls.Button btnWFrame;
	protected System.Web.UI.WebControls.Button btnHframe;
	protected System.Web.UI.WebControls.TextBox txtPop;

	protected System.Web.UI.HtmlControls.HtmlInputFile myFile;
	private void Page_Load(System.Object sender, System.EventArgs e)
	{
		//enclose the add attributes in the not is post back block, so they
		// are called to be added only once.
		if (!IsPostBack) {
			btnSendQS.Attributes.Add("onclick", "javascript:openpdf(txtPop.value)");
			btnSendSession.Attributes.Add("onclick", "javascript:openviacache()");
		}
	}
	public popup()
	{
		Load += Page_Load;
	}
}
Once again we are adding attributes to two of the buttons which call javascript functions. The first button is the one we will concentrate on for the time being. As you can see we are passing in the value of the txtPop textbox. Here is the javascript which transmits the text.

function transferText(strTxtTransfer) { 
window.opener.parent.frames[1].location.href = "rightframe.aspx?strText="+ strTxtTransfer; window.close(); }
By using window.opener.parent we are able to reference the original frame, so we then in turn can reference the right frame to transmit the data to (by inserting and index of 1). The text itself is encased within a query string. This query string is then read by the right frame on load of the page and presented within that page's textbox.

Goal #3 Use HTML input control in pop-up to load user file to server and then launch pdf in right fr
In this section we will be using the HTML input control to load a pdf file to the Web server and then subsequently call for the load of that pdf into the right frame. The HTML input control, which is provided with .NET, makes file uploading far more simple by presenting users with the standard Windows file browsing window. UI Design

UI Code

<form id="Form1" method="post" encType="multipart/form-data" 
runat="server">
The first section of code to review is the HTML in the pop-up.aspx page. In the form you must add the Tag encType="multipart/form-data". This will allow the HTML input control to work.

 private void btnLoadFile_ServerClick(System.Object sender, System.EventArgs e)
{
	//Grab the file name from its fully qualified path at client 
	string strFileName = myFile.PostedFile.FileName;
	// only the attched file name not its path
	string strShortFile = System.IO.Path.GetFileName(strFileName);
	//Save uploaded file to server @ rootweb\pdf_files and add to session
	myFile.PostedFile.SaveAs(Server.MapPath(".") + "\\pdf_files\\" + strShortFile);
	Session.Add("fileName", Server.MapPath(".") + "\\pdf_files\\" + strShortFile);
}
This codebehind for the loadfile button saves the file up to the server and stores the name and location in session. This was the reason for the clearing of session that was seen in the codebehind of the left frame page. The browse button is what presents the user with the standard Windows Explorer file selection box and fills in the lower text box. This functionality is all encapsulated in the HTML input control. Below is the HTML and JavaScript that exists behind the pop-up aspx page.

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="popup.aspx.vb" 
Inherits="asptoday_frames.popup"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
	<HEAD>
		<title>popup</title>
		<meta content="Microsoft Visual Studio.NET 7.0" 
name="GENERATOR">
		<meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
		<meta content="JavaScript" name="vs_defaultClientScript">
		<meta content="http://schemas.microsoft.com/intellisense/ie5" 
name="vs_targetSchema">
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="frmPopUp" method="post" encType="multipart/form-data" 
runat="server">
			<asp:label id="Label1" style="Z-INDEX: 106; LEFT: 26px; 
POSITION: absolute; TOP: 90px" runat="server" Height="20px" ForeColor="Red" 
Font-Bold="True" Width="280px">Session 
Example</asp:label><asp:label id="lblSession" style="Z-INDEX: 
107; LEFT: 26px; POSITION: absolute; TOP: 117px" runat="server" Height="20px" 
ForeColor="DimGray" Font-Bold="True" Width="459px" Font-
Size="Smaller">Click Browse, Find PDF file, click load file and then the 
send via session button</asp:label> 
			<INPUT id="btnLoadFile" style="Z-INDEX: 100; LEFT: 334px; 
WIDTH: 79px; POSITION: absolute; TOP: 148px; HEIGHT: 23px" type="button" 
value="LoadFile " runat="server">
			<asp:button id="btnSendSession" style="Z-INDEX: 101; 
LEFT: 18px; POSITION: absolute; TOP: 179px" runat="server" Width="112px" 
Text="Send Via Session"></asp:button><asp:button 
id="btnSendQS" style="Z-INDEX: 102; LEFT: 266px; POSITION: absolute; TOP: 41px" 
runat="server" Width="113px" Text="Send Via 
QS"></asp:button><INPUT id="myFile" style="Z-INDEX: 103; 
LEFT: 18px; WIDTH: 311px; POSITION: absolute; TOP: 148px; HEIGHT: 22px" 
type="file" size="32" name="myFile" runat="server">
			<asp:textbox id="txtPop" style="Z-INDEX: 104; LEFT: 25px; 
POSITION: absolute; TOP: 43px" runat="server" Width="225px">Transmit to 
right frame</asp:textbox><asp:label id="lblQS" style="Z-INDEX: 
105; LEFT: 32px; POSITION: absolute; TOP: 13px" runat="server" ForeColor="Red" 
Font-Bold="True" Width="251px">Query String 
Example</asp:label></form>
		<script language="javascript">			

function transferText(strTxtTransfer)
{
window.opener.parent.frames[1].location.href = "rightframe.aspx?strText="+ strTxtTransfer;
window.close();
}


function openviacache()
{
window.opener.parent.frames[1].location.href = "rightframe.aspx";
window.close();
}
		</script>
	</body>
</HTML>
A refresh of the right frame is called from the "Send Via Cache" button, which has an onclick event call to the openviacache JavaScript function. This function calls for the re-load of the right frame page. We want the page to reload so the code in the page load event of the right hand frame page will execute. The code behind of the right frame page looks for the fname session key and loads a pdf in the page based on that filename. In this block of code, I first test to make sure the file passed from session is a pdf. This is because I am using Response.contentType so that the browser can interpret the file as a pdf and display it properly in the browser.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class rightframe : System.Web.UI.Page
{

	protected System.Web.UI.WebControls.TextBox txtFleft;
	private void Page_Load(System.Object sender, System.EventArgs e)
	{
		//Put user code to initialize the page here

		string strTxtTransfer = Request.QueryString.Get("strText");
		//first find out if this page is getting called from the send via qs button by looking for a query string
		if (!string.IsNullOrEmpty(strTxtTransfer)) {
			this.txtReceive.Text = strTxtTransfer;
		// if session fname is populated and the file is a pdf load the pdf
		} else if (!string.IsNullOrEmpty((Session["filename"])) & Strings.Right((Session["filename"]), 3) == "pdf") {
			Response.Expires = 0;
			Response.Buffer = true;
			Response.Clear();
			Response.ContentType = "application/pdf";
			Response.WriteFile(Session["filename"]);
			Response.End();
		//if session has a value and it is not a pdf send an error message
		} else if (!string.IsNullOrEmpty((Session["filename"])) & Strings.Right((Session["filename"]), 3) != "pdf") {
			var _with1 = this.txtReceive;
			_with1.ForeColor = Color.Red;
			_with1.Text = "sorry you must choose a pdf file to display";
		}
	}
	public rightframe()
	{
		Load += Page_Load;
	}
}
The final result looks like this:

 

Thursday, August 25, 2011

How to avoid copy, paste and backspace error on AsyncFileUpload control in asp.net


Use below code to avoid above problems

<ajax:AsyncFileUpload runat="server" ID="flTripImages"
OnClientUploadStarted="SetTermAgrement" OnUploadedFileError="flTripImages_UploadedError"                                                OnClientUploadComplete="EnableCheckBox"
OnUploadedComplete="flTripImages_UploadedComplete"
oncontextmenu="return false;" />

use oncontextmenu="return false;" to avoid the contextmenu on the upload control, this will take care of above problems

Wednesday, August 24, 2011

Passing a control.ClientID to a javascript function in asp.net


Use below code to pass control client id to javascript function:

<asp:TextBox ID="demo1" runat="server"></asp:TextBox>
<img src="images/cal.gif" onclick="javascript:NewCssCal('<%= demo1.ClientID %>')"
   style="cursor: pointer" alt="sdf" />

how to implement facebook like button in asp.net pages or master page

1) One way to add the like button on your site.go to this page,
http://developers.facebook.com/docs/reference/plugins/like-box
just enter your facebook details then press on the "Get Code" button, u will get the copy & paste code like below.

This is an example:

<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fplatform&amp;width=292&amp;colorscheme=light&amp;show_faces=true&amp;border_color&amp;stream=true&amp;header=true&amp;height=427" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:427px;" allowTransparency="true"></iframe>

 2) Another way To implement facebook like button copy & paste the below code replace "MahindraHomestays" with "your facebook id"

  <iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2FMahindraHomestays&amp;layout=button_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font&amp;colorscheme=light&amp;height=21"
            scrolling="no" frameborder="0" style="border: none; overflow: hidden; width: 80px;
            height: 21px;" allowtransparency="true"></iframe>














Wednesday, August 17, 2011

How To: Prevent Cross-Site Scripting in ASP.NET

Applies To

  • ASP.NET version 1.1
  • ASP.NET version 2.0

Summary

This How To shows how you can help protect your ASP.NET applications from cross-site scripting attacks by using proper input validation techniques and by encoding the output. It also describes a number of other protection mechanisms that you can use in addition to these two main countermeasures.
Cross-site scripting (XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. Common vulnerabilities that make your Web applications susceptible to cross-site scripting attacks include failing to properly validate input, failing to encode output, and trusting the data retrieved from a shared database. To protect your application against cross-site scripting attacks, assume that all input is malicious. Constrain and validate all input. Encode all output that could, potentially, include HTML characters. This includes data read from files and databases.

Objectives

  • Understand the common cross-site scripting vulnerabilities in Web page validation.
  • Apply countermeasures for cross-site scripting attacks.
  • Constrain input by using regular expressions, type checks, and ASP.NET validator controls.
  • Constrain output to ensure the browser does not execute HTML tags that contain script code.
  • Review potentially dangerous HTML tags and attributes and evaluate countermeasures.

Overview

Cross-site scripting attacks exploit vulnerabilities in Web page validation by injecting client-side script code. The script code embeds itself in response data, which is sent back to an unsuspecting user. The user's browser then runs the script code. Because the browser downloads the script code from a trusted site, the browser has no way of recognizing that the code is not legitimate, and Microsoft Internet Explorer security zones provide no defense. Cross-site scripting attacks also work over HTTP and HTTPS (SSL) connections.
One of the most serious examples of a cross-site scripting attack occurs when an attacker writes script to retrieve the authentication cookie that provides access to a trusted site and then posts the cookie to a Web address known to the attacker. This enables the attacker to spoof the legitimate user's identity and gain illicit access to the Web site.
Common vulnerabilities that make your Web application susceptible to cross-site scripting attacks include:
  • Failing to constrain and validate input.
  • Failing to encode output.
  • Trusting data retrieved from a shared database.

Guidelines

The two most important countermeasures to prevent cross-site scripting attacks are to:
  • Constrain input.
  • Encode output.

Constrain Input

Start by assuming that all input is malicious. Validate input type, length, format, and range.
  • To constrain input supplied through server controls, use ASP.NET validator controls such as RegularExpressionValidator and RangeValidator.
  • To constrain input supplied through client-side HTML input controls or input from other sources such as query strings or cookies, use the System.Text.RegularExpressions.Regex class in your server-side code to check for expected using regular expressions.
  • To validate types such as integers, doubles, dates, and currency amounts, convert the input data to the equivalent .NET Framework data type and handle any resulting conversion errors.
For more information about and examples of how to constrain input, see How To: Protect From Injection Attacks in ASP.NET.

Encode Output

Use the HttpUtility.HtmlEncode method to encode output if it contains input from the user or from other sources such as databases. HtmlEncode replaces characters that have special meaning in HTML-to-HTML variables that represent those characters. For example, < is replaced with &lt; and " is replaced with &quot;. Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML.
Similarly, use HttpUtility.UrlEncode to encode output URLs if they are constructed from input.

Summary of Steps

To prevent cross-site scripting, perform the following steps:
  • Step 1. Check that ASP.NET request validation is enabled.
  • Step 2. Review ASP.NET code that generates HTML output.
  • Step 3. Determine whether HTML output includes input parameters.
  • Step 4. Review potentially dangerous HTML tags and attributes.
  • Step 5. Evaluate countermeasures.

Step 1. Check That ASP.NET Request Validation Is Enabled

By default, request validation is enabled in Machine.config. Verify that request validation is currently enabled in your server's Machine.config file and that your application does not override this setting in its Web.config file. Check that validateRequest is set to true as shown in the following code example.

<system.web><pages buffer="true" validateRequest="true" /></system.web> 
 
You can disable request validation on a page-by-page basis. Check that your pages do not disable this feature unless necessary. For example, you may need to disable this feature for a page if it contains a free-format, rich-text entry field designed to accept a range of HTML characters as input. For more information about how to safely handle this type of page, see Step 5. Evaluate Countermeasures.
To test that ASP.NET request validation is enabled
  1. Create an ASP.NET page that disables request validation. To do this, set ValidateRequest="false", as shown in the following code example.
    <%@ Page Language="C#" ValidateRequest="false" %>
    <html>
     <script runat="server">
      void btnSubmit_Click(Object sender, EventArgs e)
      {
        // If ValidateRequest is false, then 'hello' is displayed
        // If ValidateRequest is true, then ASP.NET returns an exception
        Response.Write(txtString.Text);
      }
     </script>
     <body>
      <form id="form1" runat="server">
        <asp:TextBox id="txtString" runat="server" 
                     Text="<script>alert('hello');</script>" />
        <asp:Button id="btnSubmit" runat="server"   
                    OnClick="btnSubmit_Click" 
                    Text="Submit" />
      </form>
     </body>
    </html>
      
  2. Run the page. It displays Hello in a message box because the script in txtString is passed through and rendered as client-side script in your browser.
  3. Set ValidateRequest="true" or remove the ValidateRequest page attribute and browse to the page again. Verify that the following error message is displayed.
    A potentially dangerous Request.Form value was detected from the client (txtString="<script>alert('hello...").
      
    This indicates that ASP.NET request validation is active and has rejected the input because it includes potentially dangerous HTML characters.
    Note   Do not rely on ASP.NET request validation. Treat it as an extra precautionary measure in addition to your own input validation.

Step 2. Review ASP.NET Code That Generates HTML Output

ASP.NET writes HTML as output in two ways, as shown in the following code examples.
Response.Write
<% =
  
Search your pages to locate where HTML and URL output is returned to the client.

Step 3. Determine Whether HTML Output Includes Input Parameters

Analyze your design and your page code to determine whether the output includes any input parameters. These parameters can come from a variety of sources. The following list includes common input sources:
  • Form fields, such as the following.
    Response.Write(name.Text);
    Response.Write(Request.Form["name"]);
    Query Strings
    Response.Write(Request.QueryString["name"]);
      
  • Query strings, such as the following:
    Response.Write(Request.QueryString["username"]);
      
  • Databases and data access methods, such as the following:
    SqlDataReader reader = cmd.ExecuteReader();
    Response.Write(reader.GetString(1));
      
    Be particularly careful with data read from a database if it is shared by other applications.
  • Cookie collection, such as the following:
    Response.Write(
    Request.Cookies["name"].Values["name"]);
      
  • Session and application variables, such as the following:
    Response.Write(Session["name"]);
    Response.Write(Application["name"]);
      
In addition to source code analysis, you can also perform a simple test by typing text such as "XYZ" in form fields and testing the output. If the browser displays "XYZ" or if you see "XYZ" when you view the source of the HTML, your Web application is vulnerable to cross-site scripting.
To see something more dynamic, inject <script>alert('hello');</script> through an input field. This technique might not work in all cases because it depends on how the input is used to generate the output.

Step 4. Review Potentially Dangerous HTML Tags and Attributes

If you dynamically create HTML tags and construct tag attributes with potentially unsafe input, make sure you HTML-encode the tag attributes before writing them out.
The following .aspx page shows how you can write HTML directly to the return page by using the <asp:Literal> control. The code takes user input of a color name, inserts it into the HTML sent back, and displays text in the color entered. The page uses HtmlEncode to ensure the inserted text is safe.
<%@ Page Language="C#" AutoEventWireup="true"%>

<html>
  <form id="form1" runat="server">
    <div>
      Color:&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
      <asp:Button ID="Button1" runat="server" Text="Show color" 
         OnClick="Button1_Click" /><br />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
  </form>
</html>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
  {
    protected void Button1_Click(object sender, EventArgs e)
    {
      Literal1.Text = @"<span style=""color:" 
        + Server.HtmlEncode(TextBox1.Text)
        + @""">Color example</span>";
    }           
  }
</Script>
  

Potentially Dangerous HTML Tags

While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:
  • <applet>
  • <body>
  • <embed>
  • <frame>
  • <script>
  • <frameset>
  • <html>
  • <iframe>
  • <img>
  • <style>
  • <layer>
  • <link>
  • <ilayer>
  • <meta>
  • <object>
An attacker can use HTML attributes such as src, lowsrc, style, and href in conjunction with the preceding tags to inject cross-site scripting. For example, the src attribute of the <img> tag can be a source of injection, as shown in the following examples.
<img src="javascript:alert('hello');">
<img src="java&#010;script:alert('hello');">
<img src="java&#X0A;script:alert('hello');">
  
An attacker can also use the <style> tag to inject a script by changing the MIME type as shown in the following.
<style TYPE="text/javascript">
  alert('hello');
</style>
  

Step 5. Evaluate Countermeasures

When you find ASP.NET code that generates HTML using some input, you need to evaluate appropriate countermeasures for your specific application. Countermeasures include:
  • Encode HTML output.
  • Encode URL output.
  • Filter user input.

Encode HTML Output

If you write text output to a Web page and you do not know if the text contains HTML special characters (such as <, >, and &), pre-process the text by using the HttpUtility.HtmlEncode method as shown in the following code example. Do this if the text came from user input, a database, or a local file.
Response.Write(HttpUtility.HtmlEncode(Request.Form["name"]));
  
Do not substitute encoding output for checking that input is well-formed and correct. Use it as an additional security precaution.

Encode URL Output

If you return URL strings that contain input to the client, use the HttpUtility.UrlEncode method to encode these URL strings as shown in the following code example.
Response.Write(HttpUtility.UrlEncode(urlString));
  

Filter User Input

If you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page. If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept. A common practice is to restrict formatting to safe HTML elements such as bold (<b>) and italic (<i>).
To safely allow restricted HTML input
  1. Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @ Page directive.
  2. Encode the string input with the HtmlEncode method.
  3. Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.
The following .aspx page code shows this approach. The page disables ASP.NET request validation by setting ValidateRequest="false". It HTML-encodes the input and then selectively allows the <b> and <i> HTML elements to support simple text formatting.
<%@ Page Language="C#" ValidateRequest="false"%>

<script runat="server">

  void submitBtn_Click(object sender, EventArgs e)
  {
    // Encode the string input
    StringBuilder sb = new StringBuilder(
                            HttpUtility.HtmlEncode(htmlInputTxt.Text));
    // Selectively allow  <b> and <i>
    sb.Replace("&lt;b&gt;", "<b>");
    sb.Replace("&lt;/b&gt;", "");
    sb.Replace("&lt;i&gt;", "<i>");
    sb.Replace("&lt;/i&gt;", "");
    Response.Write(sb.ToString());
  }
</script>

<html>
  <body>
    <form id="form1" runat="server">
      <div>
        <asp:TextBox ID="htmlInputTxt" Runat="server" 
                     TextMode="MultiLine" Width="318px"
                     Height="168px"></asp:TextBox>
        <asp:Button ID="submitBtn" Runat="server" 
                     Text="Submit" OnClick="submitBtn_Click" />
      </div>
    </form>
  </body>
</html>
  

Additional Considerations

In addition to the techniques discussed previously in this How To, use the following countermeasures as further safe guards to prevent cross-site scripting:
  • Set the correct character encoding.
  • Do not rely on input sanitization.
  • Use the HttpOnly cookie option.
  • Use the <frame> security attribute.
  • Use the innerText property instead of innerHTML.

Set the Correct Character Encoding

To successfully restrict valid data for your Web pages, you should limit the ways in which the input data can be represented. This prevents malicious users from using canonicalization and multi-byte escape sequences to trick your input validation routines. A multi-byte escape sequence attack is a subtle manipulation that uses the fact that character encodings, such as uniform translation format-8 (UTF-8), use multi-byte sequences to represent non-ASCII characters. Some byte sequences are not legitimate UTF-8, but they may be accepted by some UTF-8 decoders, thus providing an exploitable security hole.
ASP.NET allows you to specify the character set at the page level or at the application level by using the <globalization> element in the Web.config file. The following code examples show both approaches and use the ISO-8859-1 character encoding, which is the default in early versions of HTML and HTTP.
To set the character encoding at the page level, use the <meta> element or the ResponseEncoding page-level attribute as follows:

<meta http-equiv="Content Type" 
      content="text/html; charset=ISO-8859-1" />

OR
<% @ Page ResponseEncoding="iso-8859-1" %>
  
To set the character encoding in the Web.config file, use the following configuration.
 
<configuration>
   <system.web>
      <globalization 
         requestEncoding="iso-8859-1"
         responseEncoding="iso-8859-1"/>
   </system.web>
</configuration>
  

Validating Unicode Characters

Use the following code to validate Unicode characters in a page.
using System.Text.RegularExpressions;
. . .

public class WebForm1 : System.Web.UI.Page
{
  private void Page_Load(object sender, System.EventArgs e)
  {
    // Name must contain between 1 and 40 alphanumeric characters
    // and (optionally) special characters such as apostrophes  
    // for names such as O'Dell

    if (!Regex.IsMatch(Request.Form["name"],
               @"^[\p{L}\p{Zs}\p{Lu}\p{Ll}\']{1,40}$"))
      throw new ArgumentException("Invalid name parameter");

    // Use individual regular expressions to validate other parameters
    . . .
  }
}
  
The following explains the regular expression shown in the preceding code:
  • ^ means start looking at this position.
  • \p{ ..} matches any character in the named character class specified by {..}.
  • {L} performs a left-to-right match.
  • {Lu} performs a match of uppercase.
  • {Ll} performs a match of lowercase.
  • {Zs} matches separator and space.
  • 'matches apostrophe.
  • {1,40} specifies the number of characters: no less than 1 and no more than 40.
  • $ means stop looking at this position.

Do Not Rely on Input Sanitization

A common practice is for code to attempt to sanitize input by filtering out known unsafe characters. Do not rely on this approach because malicious users can usually find an alternative means of bypassing your validation. Instead, your code should check for known secure, safe input. Table 1 shows various safe ways to represent some common characters.

Table 1: Character Representation
CharactersDecimalHexadecimalHTML Character SetUnicode
" (double quotation marks)&#34&#x22&quot;\u0022
' (single quotation mark)&#39&#x27&apos;\u0027
& (ampersand)&#38&#x26&amp;\u0026
< (less than)&#60&#x3C&lt;\u003c
> (greater than)&#62&#x3E&gt;\u003e

 

Use the HttpOnly Cookie Option

Internet Explorer 6 Service Pack 1 and later supports an HttpOnly cookie attribute, which prevents client-side scripts from accessing a cookie from the document.cookie property. Instead, the script returns an empty string. The cookie is still sent to the server whenever the user browses to a Web site in the current domain.
Note   Web browsers that do not support the HttpOnly cookie attribute either ignore the cookie or ignore the attribute, which means that it is still subject to cross-site scripting attacks.
The System.Net.Cookie class in Microsoft .NET Framework version 2.0 supports an HttpOnly property. The HttpOnly property is always set to true by Forms authentication.
Earlier versions of the .NET Framework (versions 1.0 and 1.1) require that you add code similar to the following to the Application_EndRequest event handler in your application Global.asax file to explicitly set the HttpOnly attribute.

protected void Application_EndRequest(Object sender, EventArgs e) 
{
  string authCookie = FormsAuthentication.FormsCookieName;
  foreach (string sCookie in Response.Cookies) 
  {
    // Just set the HttpOnly attribute on the Forms 
    // authentication cookie. Skip this check to set the attribute 
    // on all cookies in the collection

    if (sCookie.Equals(authCookie))
    { 
      // Force HttpOnly to be added to the cookie header
      Response.Cookies[sCookie].Path += ";HttpOnly";
    }
  }
}
  

Use the <frame> Security Attribute

Internet Explorer 6 and later support a new security attribute for the <frame> and <iframe> elements. You can use the security attribute to apply the user's Restricted Sites Internet Explorer security zone settings to an individual frame or iframe. By default, the Restricted Sites zone does not support script execution.
If you use the security attribute, it must be set to "restricted" as shown in the following.
<frame security="restricted" src="http://www.somesite.com/somepage.htm"></frame>
  

Use the innerText Property Instead of innerHTML

If you use the innerHTML property to build a page and the HTML is based on potentially untrusted input, you must use HtmlEncode to make it safe. To avoid having to remember to do this, use innerText instead. The innerText property renders content safe and ensures that scripts are not executed.
The following example shows this approach for two HTML <span> controls. The code in the Page_Load method sets the text displayed in the Welcome1 <span> element using the innerText property, so HTML-encoding is unnecessary. The code sets the text in the Welcome2 <span> element by using the innerHtml property; therefore, you must HtmlEncode it first to make it safe.
<%@ Page Language="C#" AutoEventWireup="true"%>

<html>
  <body>
    <span id="Welcome1" runat="server"> </span>
    <span id="Welcome2" runat="server"> </span>
  </body>
</html>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
  {
    // Using InnerText renders the content safe–no need to HtmlEncode
    Welcome1.InnerText = "Hello, " + User.Identity.Name;

    // Using InnerHtml requires the use of HtmlEncode to make it safe
    Welcome2.InnerHtml = "Hello, " + 
                        Server.HtmlEncode(User.Identity.Name);
  }
</Script>
  

Additional Resources
















Image Button alternate text (tooltip) is not working in ie 8 asp.net

To solve the Image Button alternate text is not working in ie 8 asp.net problem
follow the below code

.aspx

asp:Image ID="imgItinerary"   ImageUrl="~/images/search_thumb.jpg" runat="server"

.aspx.cs


Problem created code:
                i missed out tooltip property

                imgItinerary.AlternateText = "Image";

Solution for the above problem:
             
                imgItinerary.AlternateText = "Image";
                imgItinerary.ToolTip = "Image";















Thursday, August 11, 2011

How to add dynamic fevicon to your websites in asp.net page or master page


How  to add fevicon to your websites in asp.net page or master page. It is so simple. 
follow the below steps.

1) First you need to create a 16 * 16 px icon (if you give more size also it will accept but finally it will convert to 16 * 16 px only) and name it as favicon.ico (name may be anything and format either .ico or .jpg).

if you want to convert your images to icon click here.




2) Save your favicon to the root directory of your ASP.Net web application like above image.

3) For the latest versions of Firefox, Internet Explorer and Chrome, however, you need to add two links to your favicon to the head in your HTML.

Default.aspx:
 
<head> <title>My Websitetitle>  

<link runat="server" rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
<
link runat="server" rel="icon" href="favicon.ico" type="image/ico"/>

head>
   
Note:  Why 2 links are required - to work in all the browsers

For dynamic fevicon:

.aspx

<head> <title>My Websitetitle>  

<link runat="server" rel="shortcut icon" href="" type="image/x-icon"/>
<
link runat="server" rel="icon" href="" type="image/ico"/>

head>

.aspx.cs:


 protected void Page_Load(object sender, EventArgs e)
    {
        Link1.Attributes.Add("href", "favicon.ico");
        Link1.Attributes.Add("href", "favicon.ico");
    }

Final output looks like below image:






Wednesday, August 3, 2011

URL Rewritting in Asp.Net

 

All about URL Rewriting


Introduction:

You must be having URL's in your website like below:
http://yoursite.com/info/dispEmployeeInfo.aspx?EmpID=459-099&type=summary 
Don't say me NO... ok!  you should be having them ...  ;)


In the same way...  my Customer also want us to mask the actual URL ta make  them more readable (sucurable), and should be in a way to memorize very easily.


So, I have searched couple of websites, and found a procedure, but it turned to work only in IIS 6, where as our Client's environment is IIS 7 :( ... 
so, my search started again, and finally found it :)  and I would like to explain and share the procedure, hope you find it useful! 
here we go...




Why URL Rewrite?

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource.
With the URL Rewriting, you can change the above said URL to look like:
http://yoursite.com/people/sales/chuck.smith


Indirectly, with this procedure, you can also redirect the pages that no longer exists to the new one.


Moreover, this helps to improve the search relevancy of pages on your site with search engines like Google, Yahoo. 


Now, I will explain how easily, this can be done


How URL Rewrite works?


The IIS receives the request made by the client and dispatches it to aspnet_isapi.dll. Next, the ASP.NET engine initializes the configured HTTP modules. Finally, the proper HTTP handler is invoked and the requested resource is rendered, returning the generated markup back to IIS and back to the requesting client.


Here the custom module (Intelligencia.UrlRewriter) is used and when the URL request (http://abcd.com/LazyBubble/SecondPage) is made, the request reaches the IIS of the Server and the URL Rewrite is done based on the url mapping configured in the ‘Configuration file’, with the help of HTTP Module and HTTP Handler.




Steps:


1. Firstly, Download the code from here

2. Pick up the Intelligencia.UrlRewriter.dll from the the dowloaded code location - UrlRewrite_HttpModule\bin and add it to your Web Project.   


3. Add the following sections to your web.config file.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  
<configSections>
    
<section name="rewriter" requirePermission="false" 

type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
  configSections>

  
<system.web>    
    
<httpModules>
      
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, 
Intelligencia.UrlRewriter" />

    httpModules>  
  
system.web>

  
<system.webServer>
    
<modules runAllManagedModulesForAllRequests="true">
      
<add name="UrlRewriter" 

            type="Intelligencia.UrlRewriter.RewriterHttpModule"/>
    modules>
    
<validation validateIntegratedModeConfiguration="false" />
  system.webServer>

  
<rewriter>
    
<rewrite url="SecondPage" to="Page2.aspx" />
  rewriter>

  configuration>




4. Add the Form.Browser and Form Rewriter.vb from the above Code downloaded.




The problem when using URL-Rewriting is that the URL that the
control renders is not the original URL of the request (for example: /products/books), but rather the re-written one (for example: /products.aspx?category=books).  This means that when you do a postback to the server, the URL will not be your nice clean one.

  
Specifically, you can take advantage of the new ASP.NET 2.0 Control Adapter extensibility architecture to customize the rendering of the control, and override its "action" attribute value with a value you provide.  


This doesn't require you to change any code in your .aspx pages


Instead, just add a .browser file to your /app_browsers folder that registers a Control Adapter class to use to output the new "action" attribute.


For the VB code to run in C#, add th below section in your web.config file.



 <compilation debug="false">
      <codeSubDirectories>
        <add directoryName="VBCode"/> 
      codeSubDirectories>


compilation>



5.  Create a new ASP.Net website and add 2 Pages naming them as Page1.aspx & Page2.aspx
     Add the below code in those 2 pages.


Page1.aspx


<form id="form1" runat="server">
    <div>
        <asp:Button ID="btnRedirect" runat="server" Text="Redirect to Page2" onclick="btnRedirect_Click" />
    div>
form>

Page1.aspx.cs

protected void btnRedirect_Click(object sender, EventArgs e)
    {
        Response.Redirect("SecondPage", false);
    }


Page2.aspx

<form id="form1" runat="server">
    <div>
        <h1>
        This is Page 2
        h1>
    div>
form>

In web.config

<rewrite url="SecondPage" to="Page2.aspx" />


Build the Project and Run it. Browse the Page1.aspx

Click the Button on the Page.









It redirects to Page2.aspx. If you notice, the URL - http://localhost:3232/LazyBubble/SecondPage

"SecondPage" is the custom name which we defined in the web.config file, under the <rewriter> section.


In this way, you can redirect to the custom named files (SecondPage) hiding the actual Page name files (Page2.aspx).



Troubleshooting:


1. CSS/Images not working:
    This is because you might have relative References to these files within  
    their HTML pages - and  when you start  to re-write URLs within an 
    application you need to be aware that the browser will often be requesting 
    files in different logical hierarchy levels than what is really stored on the  
    server.


    For example, if our /products.aspx page above had a relative reference to 
    "logo.jpg" in the .aspx page, but was requested via the products/books.aspx   
    url, then the browser will send a request for /products/logo.jpg instead of 
    /logo.jpg when it renders the page.  To reference this file correctly, make  
    sure you root qualify CSS and Image references ("/style.css" instead of 
    "style.css").  
    For ASP.NET controls, you can also use the ~ syntax to reference files from 
    the root of the 
    application (for 
    example:
    The ~ will not work for HTML image control, so you have to use the ASP.Net 
    Image controls.


2. Reference to js file - not working
    Please take care in referencing the js files in the page. Probable you may 
    have follow this :
    


3.  Error - Cannot use a leading .. to exit above the top directory


   When you use relative paths incorrectly.  If you generate a url with too many 
   “../../../” levels in it that would take the user above the root directory, you 
   can generate the exception.


   If you are using Server.Transfer or HttpContext.RewritePath to redirect a 
   request (say map it to a template page) and have a HyperLink control with 
   the ImageUrl property set, you win an extra “../” by the framework.  The fix 
   is to wrap the HyperLink control around an Image control. 


   In code, if you have,
<asp:HyperLink ID="hlnkTripImages" runat="server" ImageUrl="~/images/camera_icon.gif">asp:HyperLink>

change it to,
<asp:HyperLink ID="hlnkTripImages" runat="server">

    <asp:Image runat="server" ID="imgTripImages" 
         ImageUrl="~/images/camera_icon.gif" ToolTip="Photo"/>
asp:HyperLink>



References 

Popular Posts