This article discusses various options for state management for web applications developed using ASP.NET. Generally, web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.
Developer is forced to implement various state management techniques when developing applications which provide customized content and which "remembers" the user.
Here we are here with various options for ASP.NET developer to implement state management techniques in their applications. Broadly, we can classify state management techniques as client side state management or server side state management. Each technique has its own pros and cons. Let's start with exploring client side state management options.
Client side State management Options:
ASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of client side state management options.
Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request.
Cookie:
A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.
Let's see an example which makes use of cookies to customize web page.
if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!";
else
lbMessage.text = "Guest,welcome to our website!";
If you want to store client's information use the below code
Response.Cookies["UserId"].Value=username;
Advantages:
• Simplicity
Disadvantages:
• Cookies can be disabled on user browsers
• Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
• Inappropriate for sensitive data..
Hidden fields:
Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
//to assign a value to Hidden field
Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;
Advantages:
• Simple to implement for a page specific data
• Can store small amount of data so they take less size..
Disadvantages:
• Inappropriate for sensitive data
• Hidden field values can be intercepted(clearly visible) when passed over a network
View State:
View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.
// Add item to ViewState
ViewState["myviewstate"] = myValue;
//Reading items from ViewState
Response.Write(ViewState["myviewstate"]);
Advantages:
• Simple for page level data
• Encrypted
• Can be set at the control level
Disadvantages:
• Overhead in encoding View State values
• Makes a page heavy
Query strings:
Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by using the following codes:
string productid;
productid=Request.Params["productid"];
Advantages:
• Simple to Implement
Disadvantages:
• Human Readable
• Client browser limit on URL length
• Cross paging functionality makes it redundant
• Easily modified by end user
Control State:
Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled. For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage
of sessions object for state management can create load on server causing performance degradation
Application object:
Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea
Application.Lock();
Application["mydata"]="mydata";
Application.UnLock();
Session object:
Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the <session State> section in the application's web.config file.
Configuration information:
<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
cookieless = <"true" | "false">
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
Mode:
This setting supports three options. They are InProc, SQLServer, and State Server
Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.
Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes
SqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer.
Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.
Port:
This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.
You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
• In process mode (in-memory)- State information is stored in memory of web server
• Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
• Database mode – session state is maintained on a SQL Server database.
In process mode:
This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server
Configuration information:
<sessionState mode="Inproc"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Fastest mode
• Simple configuration
Disadvantages:
• Session data will be lost if the worker process or application domain recycles
• Not ideal for web gardens and web farms
Out-of-process Session mode (state server mode):
This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line.
Net start aspnet_state
Configuration information:
<sessionState mode="StateServer"
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
cookieless="false" timeout="20"/>
Advantages:
• Supports web farm and web garden configuration
• Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
Disadvantages:
• Out-of-process mode provides slower access compared to In process
• Requires serializing data
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.
SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory
C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will manage the session state.
Configuration Information:
<sessionState mode="SQLServer"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Supports web farm and web garden configuration
• Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.
Disadvantages:
• Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various factors including available server resources, scalability and performance. We have to leverage both client side and server side state management options to build scalable applications.
When leveraging client side state options, ensure that little amount of insignificant information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including size of application, reliability and robustness. Smaller the application, In process is the better choice. We should account in the overheads involved in serializing and deserializing objects when using State Server and Database based session state. Application state should be used religiously.
Thursday, March 4, 2010
Dot Net Directives
Asp.Net web form page framework supports the following directives
1. @Page
2. @Master
3. @Control
4. @Register
5. @Reference
6. @PreviousPageType
7. @OutputCache
8. @Import
9. @Implements
10. @Assembly
11. @MasterType
@Page Directive
The @Page directive enables you to specify attributes and values for an Asp.Net Page to be used when the page is parsed and compiled. Every .aspx files should include this @Page directive to execute. There are many attributes belong to this directive. We shall discuss some of the important attributes here.
a. AspCompat: When set to True, this allows to the page to be executed on a single-threaded apartment. If you want to use a component developed in VB 6.0, you can set this value to True. But setting this attribute to true can cause your page's performance to degrade.
b. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.
c. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same .aspx file or in code behind. The default value is true.
d. CodeFile: Specifies the code-behid file with which the page is associated.
e. Title: To set the page title other than what is specified in the master page.
f. Culture: Specifies the culture setting of the page. If you set to auto, enables the page to automatically detect the culture required for the page.
g. UICulture: Specifies the UI culture setting to use for the page. Supports any valid UI culture value.
h. ValidateRequest: Indicates whether request validation should occur. If set to true, request validation checks all input data against a hard-coded list of potentially dangerous values. If a match occurs, an HttpRequestValidationException Class is thrown. The default is true. This feature is enabled in the machine configuration file (Machine.config). You can disable it in your application configuration file (Web.config) or on the page by setting this attribute to false.
i. Theme: To specify the theme for the page. This is a new feature available in Asp.Net 2.0.
j. SmartNavigation: Indicates the smart navigation feature of the page. When set to True, this returns the postback to current position of the page. The default value is false.
k. MasterPageFile: Specify the location of the MasterPage file to be used with the current Asp.Net page.
l. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
m. ErrorPage: Specifies a target URL for redirection if an unhandled page exception occurs.
n. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.
There are also other attributes which are of seldom use such as Buffer, CodePage, ClassName, EnableSessionState, Debug, Description, EnableTheming, EnableViewStateMac, TraceMode, WarningLevel, etc. Here is an example of how a @Page directive looks
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Sample.aspx.cs" Inherits="Sample" Title="Sample Page Title" %>
@Master Directive
The @Master directive is quite similar to the @Page directive. The @Master directive belongs to Master Pages that is .master files. The master page will be used in conjunction of any number of content pages. So the content pages can the inherits the attributes of the master page. Even though, both @Page and @Master page directives are similar, the @Master directive has only fewer attributes as follows
a. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.
b. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same master file or in code behind. The default value is True.
c. CodeFile: Specifies the code-behid file with which the MasterPage is associated.
d. Title: Set the MasterPage Title.
e. MasterPageFile: Specifies the location of the MasterPage file to be used with the current MasterPage. This is called as Nested Master Page.
f. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
g. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.
Here is an example of how a @Master directive looks
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="WebMaster.master.cs" Inherits="WebMaster" %>
@Control Directive
The @Control directive is used when we build an Asp.Net user controls. The @Control directive helps us to define the properties to be inherited by the user control. These values are assigned to the user control as the page is parsed and compiled. The attributes of @Control directives are
a. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.
b. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same .ascx file or in code behind. The default value is true.
c. CodeFile: Specifies the code-behid file with which the user control is associated.
d. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
e. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.
f. Debug: Indicates whether the page should be compiled with debug symbols.
g. Src: Points to the source file of the class used for the code behind of the user control.
The other attributes which are very rarely used is ClassName, CompilerOptions, ComplieWith, Description, EnableTheming, Explicit, LinePragmas, Strict and WarningLevel.
Here is an example of how a @Control directive looks
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyControl.ascx.cs" Inherits=" MyControl " %>
@Register Directive
The @Register directive associates aliases with namespaces and class names for notation in custom server control syntax. When you drag and drop a user control onto your .aspx pages, the Visual Studio 2005 automatically creates an @Register directive at the top of the page. This register the user control on the page so that the control can be accessed on the .aspx page by a specific name.
The main atttribues of @Register directive are
a. Assembly: The assembly you are associatin with the TagPrefix.
b. Namespace: The namspace to relate with TagPrefix.
c. Src: The location of the user control.
d. TagName: The alias to relate to the class name.
e. TagPrefix: The alias to relate to the namespace.
Here is an example of how a @Register directive looks
<%@ Register Src="Yourusercontrol.ascx" TagName=" Yourusercontrol " TagPrefix="uc1" Src="~\usercontrol\usercontrol1.ascx" %>
@Reference Directive
The @Reference directive declares that another asp.net page or user control should be complied along with the current page or user control. The 2 attributes for @Reference direcive are
a. Control: User control that ASP.NET should dynamically compile and link to the current page at run time.
b. Page: The Web Forms page that ASP.NET should dynamically compile and link to the current page at run time.
c. VirutalPath: Specifies the location of the page or user control from which the active page will be referenced.
Here is an example of how a @Reference directive looks
<%@ Reference VirutalPath="YourReferencePage.ascx" %>
@PreviousPageType Directive
The @PreviousPageType is a new directive makes excellence in asp.net 2.0 pages. The concept of cross-page posting between Asp.Net pages is achieved by this directive. This directive is used to specify the page from which the cross-page posting initiates. This simple directive contains only two attibutes
a. TagName: Sets the name of the derived class from which the postback will occur.
b. VirutalPath: sets the location of the posting page from which the postback will occur.
Here is an example of @PreviousPageType directive
<%@ PreviousPageType VirtualPath="~/YourPreviousPageName.aspx" %>
@OutputCache Directive
The @OutputCache directive controls the output caching policies of the Asp.Net page or user control. You can even cache programmatically through code by using Visual Basic .NET or Visual C# .NET. The very important attributes for the @OutputCache directive are as follows
Duration: The duration of time in seconds that the page or user control is cached.
Location: To specify the location to store the output cache. To store the output cache on the browser client where the request originated set the value as ‘Client’. To store the output cache on any HTTP 1.1 cache-capable devices including the proxy servers and the client that made request, specify the Location as Downstream. To store the output cache on the Web server, mention the location as Server.
VaryByParam: List of strings used to vary the output cache, separated with semi-colon.
VaryByControl: List of strings used to vary the output cache of a user Control, separated with semi-colon.
VaryByCustom: String of values, specifies the custom output caching requirements.
VaryByHeader: List of HTTP headers used to vary the output cache, separated with semi-colon.
The other attribues which is rarely used are CacheProfile, DiskCacheable, NoStore, SqlDependency, etc.
<%@ OutputCache Duration="60" Location="Server" VaryByParam="None" %>
To turn off the output cache for an ASP.NET Web page at the client location and at the proxy location, set the Location attribute value to none, and then set the VaryByParam value to none in the @ OutputCache directive. Use the following code samples to turn off client and proxy caching.
<%@ OutputCache Location="None" VaryByParam="None" %>
@Import Directive
The @Import directive allows you to specify any namespaces to the imported to the Asp.Net pages or user controls. By importing, all the classes and interfaces of the namespace are made available to the page or user control. The example of the @Import directive
<%@ Import namespace=”System.Data” %>
<%@ Import namespace=”System.Data.SqlClient” %>
@Implements Directive
The @Implements directive gets the Asp.Net page to implement a specified .NET framework interface. The only single attribute is Interface, helps to specify the .NET Framework interface. When the Asp.Net page or user control implements an interface, it has direct access to all its events, methods and properties.
<%@ Implements Interface=”System.Web.UI.IValidator” %>
@Assembly Directive
The @Assembly directive is used to make your ASP.NET page aware of external components. This directive supports two attributes:
a. Name: Enables you specify the name of an assembly you want to attach to the page. Here you should mention the filename without the extension.
b. Src: represents the name of a source code file
<%@ Assembly Name="YourAssemblyName" %>
@MasterType Directive
To access members of a specific master page from a content page, you can create a strongly typed reference to the master page by creating a @MasterType directive. This directive supports of two attributes such as TypeName and VirtualPath.
a. TypeName: Sets the name of the derived class from which to get strongly typed references or members.
b. VirtualPath: Sets the location of the master page from which the strongly typed references and members will be retrieved.
If you have public properties defined in a Master Page that you'd like to access in a strongly-typed manner you can add the MasterType directive into a page as shown next
<%@ MasterType VirtualPath="MasterPage.master" %>
this.Master.HeaderText = "Label updated using MasterType directive with VirtualPath attribute";
1. @Page
2. @Master
3. @Control
4. @Register
5. @Reference
6. @PreviousPageType
7. @OutputCache
8. @Import
9. @Implements
10. @Assembly
11. @MasterType
@Page Directive
The @Page directive enables you to specify attributes and values for an Asp.Net Page to be used when the page is parsed and compiled. Every .aspx files should include this @Page directive to execute. There are many attributes belong to this directive. We shall discuss some of the important attributes here.
a. AspCompat: When set to True, this allows to the page to be executed on a single-threaded apartment. If you want to use a component developed in VB 6.0, you can set this value to True. But setting this attribute to true can cause your page's performance to degrade.
b. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.
c. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same .aspx file or in code behind. The default value is true.
d. CodeFile: Specifies the code-behid file with which the page is associated.
e. Title: To set the page title other than what is specified in the master page.
f. Culture: Specifies the culture setting of the page. If you set to auto, enables the page to automatically detect the culture required for the page.
g. UICulture: Specifies the UI culture setting to use for the page. Supports any valid UI culture value.
h. ValidateRequest: Indicates whether request validation should occur. If set to true, request validation checks all input data against a hard-coded list of potentially dangerous values. If a match occurs, an HttpRequestValidationException Class is thrown. The default is true. This feature is enabled in the machine configuration file (Machine.config). You can disable it in your application configuration file (Web.config) or on the page by setting this attribute to false.
i. Theme: To specify the theme for the page. This is a new feature available in Asp.Net 2.0.
j. SmartNavigation: Indicates the smart navigation feature of the page. When set to True, this returns the postback to current position of the page. The default value is false.
k. MasterPageFile: Specify the location of the MasterPage file to be used with the current Asp.Net page.
l. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
m. ErrorPage: Specifies a target URL for redirection if an unhandled page exception occurs.
n. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.
There are also other attributes which are of seldom use such as Buffer, CodePage, ClassName, EnableSessionState, Debug, Description, EnableTheming, EnableViewStateMac, TraceMode, WarningLevel, etc. Here is an example of how a @Page directive looks
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Sample.aspx.cs" Inherits="Sample" Title="Sample Page Title" %>
@Master Directive
The @Master directive is quite similar to the @Page directive. The @Master directive belongs to Master Pages that is .master files. The master page will be used in conjunction of any number of content pages. So the content pages can the inherits the attributes of the master page. Even though, both @Page and @Master page directives are similar, the @Master directive has only fewer attributes as follows
a. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.
b. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same master file or in code behind. The default value is True.
c. CodeFile: Specifies the code-behid file with which the MasterPage is associated.
d. Title: Set the MasterPage Title.
e. MasterPageFile: Specifies the location of the MasterPage file to be used with the current MasterPage. This is called as Nested Master Page.
f. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
g. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.
Here is an example of how a @Master directive looks
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="WebMaster.master.cs" Inherits="WebMaster" %>
@Control Directive
The @Control directive is used when we build an Asp.Net user controls. The @Control directive helps us to define the properties to be inherited by the user control. These values are assigned to the user control as the page is parsed and compiled. The attributes of @Control directives are
a. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.
b. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same .ascx file or in code behind. The default value is true.
c. CodeFile: Specifies the code-behid file with which the user control is associated.
d. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
e. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.
f. Debug: Indicates whether the page should be compiled with debug symbols.
g. Src: Points to the source file of the class used for the code behind of the user control.
The other attributes which are very rarely used is ClassName, CompilerOptions, ComplieWith, Description, EnableTheming, Explicit, LinePragmas, Strict and WarningLevel.
Here is an example of how a @Control directive looks
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyControl.ascx.cs" Inherits=" MyControl " %>
@Register Directive
The @Register directive associates aliases with namespaces and class names for notation in custom server control syntax. When you drag and drop a user control onto your .aspx pages, the Visual Studio 2005 automatically creates an @Register directive at the top of the page. This register the user control on the page so that the control can be accessed on the .aspx page by a specific name.
The main atttribues of @Register directive are
a. Assembly: The assembly you are associatin with the TagPrefix.
b. Namespace: The namspace to relate with TagPrefix.
c. Src: The location of the user control.
d. TagName: The alias to relate to the class name.
e. TagPrefix: The alias to relate to the namespace.
Here is an example of how a @Register directive looks
<%@ Register Src="Yourusercontrol.ascx" TagName=" Yourusercontrol " TagPrefix="uc1" Src="~\usercontrol\usercontrol1.ascx" %>
@Reference Directive
The @Reference directive declares that another asp.net page or user control should be complied along with the current page or user control. The 2 attributes for @Reference direcive are
a. Control: User control that ASP.NET should dynamically compile and link to the current page at run time.
b. Page: The Web Forms page that ASP.NET should dynamically compile and link to the current page at run time.
c. VirutalPath: Specifies the location of the page or user control from which the active page will be referenced.
Here is an example of how a @Reference directive looks
<%@ Reference VirutalPath="YourReferencePage.ascx" %>
@PreviousPageType Directive
The @PreviousPageType is a new directive makes excellence in asp.net 2.0 pages. The concept of cross-page posting between Asp.Net pages is achieved by this directive. This directive is used to specify the page from which the cross-page posting initiates. This simple directive contains only two attibutes
a. TagName: Sets the name of the derived class from which the postback will occur.
b. VirutalPath: sets the location of the posting page from which the postback will occur.
Here is an example of @PreviousPageType directive
<%@ PreviousPageType VirtualPath="~/YourPreviousPageName.aspx" %>
@OutputCache Directive
The @OutputCache directive controls the output caching policies of the Asp.Net page or user control. You can even cache programmatically through code by using Visual Basic .NET or Visual C# .NET. The very important attributes for the @OutputCache directive are as follows
Duration: The duration of time in seconds that the page or user control is cached.
Location: To specify the location to store the output cache. To store the output cache on the browser client where the request originated set the value as ‘Client’. To store the output cache on any HTTP 1.1 cache-capable devices including the proxy servers and the client that made request, specify the Location as Downstream. To store the output cache on the Web server, mention the location as Server.
VaryByParam: List of strings used to vary the output cache, separated with semi-colon.
VaryByControl: List of strings used to vary the output cache of a user Control, separated with semi-colon.
VaryByCustom: String of values, specifies the custom output caching requirements.
VaryByHeader: List of HTTP headers used to vary the output cache, separated with semi-colon.
The other attribues which is rarely used are CacheProfile, DiskCacheable, NoStore, SqlDependency, etc.
<%@ OutputCache Duration="60" Location="Server" VaryByParam="None" %>
To turn off the output cache for an ASP.NET Web page at the client location and at the proxy location, set the Location attribute value to none, and then set the VaryByParam value to none in the @ OutputCache directive. Use the following code samples to turn off client and proxy caching.
<%@ OutputCache Location="None" VaryByParam="None" %>
@Import Directive
The @Import directive allows you to specify any namespaces to the imported to the Asp.Net pages or user controls. By importing, all the classes and interfaces of the namespace are made available to the page or user control. The example of the @Import directive
<%@ Import namespace=”System.Data” %>
<%@ Import namespace=”System.Data.SqlClient” %>
@Implements Directive
The @Implements directive gets the Asp.Net page to implement a specified .NET framework interface. The only single attribute is Interface, helps to specify the .NET Framework interface. When the Asp.Net page or user control implements an interface, it has direct access to all its events, methods and properties.
<%@ Implements Interface=”System.Web.UI.IValidator” %>
@Assembly Directive
The @Assembly directive is used to make your ASP.NET page aware of external components. This directive supports two attributes:
a. Name: Enables you specify the name of an assembly you want to attach to the page. Here you should mention the filename without the extension.
b. Src: represents the name of a source code file
<%@ Assembly Name="YourAssemblyName" %>
@MasterType Directive
To access members of a specific master page from a content page, you can create a strongly typed reference to the master page by creating a @MasterType directive. This directive supports of two attributes such as TypeName and VirtualPath.
a. TypeName: Sets the name of the derived class from which to get strongly typed references or members.
b. VirtualPath: Sets the location of the master page from which the strongly typed references and members will be retrieved.
If you have public properties defined in a Master Page that you'd like to access in a strongly-typed manner you can add the MasterType directive into a page as shown next
<%@ MasterType VirtualPath="MasterPage.master" %>
this.Master.HeaderText = "Label updated using MasterType directive with VirtualPath attribute";
Labels:
Asp.Net
The Types of Caching in ASP.NET
ASP.NET supports three types of caching:
• Output Caching: Caches the output from an entire page and returns it for future requests instead of re-executing the requested page.
• Fragment Caching: Caches just a part of a page which can then be reused even while other parts of the page are being dynamically generated.
• Data Caching: Programmatically caches arbitrary objects for later reuse without re-incurring the overhead of creating them.
Which type of caching you decide to use obviously depends on your situation, but I'll briefly cover them all so you can make an informed decision.
Output Caching
Output caching is the simplest of the caching options offered by ASP.NET. It is useful when an entire page can be cached as a whole and is analogous to most of the caching solutions that were available under classic ASP. It takes a dynamically generated page and stores the HTML result right before it is sent to the client. Then it reuses this HTML for future requests bypassing the execution of the original code.
Telling ASP.NET to cache a page is extremely simple. You simply add the OutputCache directive to the page you wish to cache.
<%@ OutputCache Duration="30" VaryByParam="none" %>
The resulting caching is similar to the caching done by browsers and proxy servers, but does have one extremely important difference... you can tell a page which parameters to the page will have an effect on the output and the caching engine will cache separate versions based on the parameters you specify. This is done using the VaryByParam attribute of the OutputCache directive. The code listing below (a shortened version of output_vary.aspx from the zip file available at the end of this article) illustrates a very simple example of output caching.
<%@ Page Language="VB" %>
<%@ OutputCache Duration="30" VaryByParam="test" %>
<html>
<body bgcolor="#FFFFFF">
<p>
This page was generated at: <strong><%= Now() %></strong>
</p>
</body>
</html>
This piece of code will cache the result for 30 seconds. During that time, responses for all requests for the page will be served from the cache. It also specifies that the caching should vary by the parameter "test". As such, the page will cache a different version for each value of "test" that it is passed and will return the appropriate version based on the value of "test" in the incoming requests.
Fragment Caching
Sometimes it's not possible to cache an entire page. For example, many shopping sites like to greet their users by name. It wouldn't look very good if you went to a site and instead of using your name to greet you it used mine! In the past this often meant that caching wasn't a viable option for these pages. ASP.NET handles this by what they call fragment caching.
Honestly, I find this a little misleading... while you can technically cache part of a page, in order to do so you need to make the section to be cached into a user control and set the OutputCache directive in the new user control. Then you use this control from your dynamic page. The solution works well, but in my mind I think of it as caching a separate mini-page and not really a fragment of a page. I guess it's just semantics, but it is a separate file so it can be a little bit of work to implement.
The caching part is very similar to the code above. Aside from making the section a user control and then using the user control (which we covered in our User Controls lesson) it's pretty boring. There's a sample in the zip file, but I'm not including the code here.
Data Caching
This is the most powerful of the caching options available in ASP.NET. Using data caching you can programmatically cache anything you want for as long as you want. The caching system exposes itself in a dictionary type format meaning items are stored in name/value pairs. You cache an item under a certain name and then when you request that name you get the item back. It's similar to an array or even a simple variable.
In addition to just placing an object into the cache you can set all sorts of properties. The object can be set to expire at a fixed time and date, after a period of inactivity, or when a file or other object in the cache is changed.
The main thing to watch out for with data caching is that items you place in the cache are not guaranteed to be there when you want them back. While it does add some work (you always have to check your object exists after you retrieve it), this scavenging really is a good thing. It gives the caching engine the flexibility to dispose of things that aren't being used or dump parts of the cache if the system starts running out of memory.
Here's a simple example of data caching. Once again it's simply a streamlined version of the script in the zip file.
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Dim strTimestamp As String
' Retrieve our object
strTimestamp = Cache.Get("SomeData")
' Check to see if we got our object back or not.
' If not, deal with it:
If strTimestamp Is Nothing Then
' Assign a value to our object
strTimestamp = Now()
' Insert into cache:
Cache.Insert("SomeData", strTimestamp, Nothing, _
DateTime.Now.AddMinutes(.5), TimeSpan.Zero)
End If
Caching Rules... Get The Code
If you couldn't tell by now, I really like caching. It's an easy way to make your web pages and applications faster and it really doesn't cost you anything except for a little bit of time to figure out what to cache and for how long to cache it. It does use some memory, but with the price of memory these days, adding a little more (if needed) is a small price to pay for a faster web site.
As usual, the code from this lesson is all zipped up in a nice little file so you can download it and play with it on your own.
• Output Caching: Caches the output from an entire page and returns it for future requests instead of re-executing the requested page.
• Fragment Caching: Caches just a part of a page which can then be reused even while other parts of the page are being dynamically generated.
• Data Caching: Programmatically caches arbitrary objects for later reuse without re-incurring the overhead of creating them.
Which type of caching you decide to use obviously depends on your situation, but I'll briefly cover them all so you can make an informed decision.
Output Caching
Output caching is the simplest of the caching options offered by ASP.NET. It is useful when an entire page can be cached as a whole and is analogous to most of the caching solutions that were available under classic ASP. It takes a dynamically generated page and stores the HTML result right before it is sent to the client. Then it reuses this HTML for future requests bypassing the execution of the original code.
Telling ASP.NET to cache a page is extremely simple. You simply add the OutputCache directive to the page you wish to cache.
<%@ OutputCache Duration="30" VaryByParam="none" %>
The resulting caching is similar to the caching done by browsers and proxy servers, but does have one extremely important difference... you can tell a page which parameters to the page will have an effect on the output and the caching engine will cache separate versions based on the parameters you specify. This is done using the VaryByParam attribute of the OutputCache directive. The code listing below (a shortened version of output_vary.aspx from the zip file available at the end of this article) illustrates a very simple example of output caching.
<%@ Page Language="VB" %>
<%@ OutputCache Duration="30" VaryByParam="test" %>
<html>
<body bgcolor="#FFFFFF">
<p>
This page was generated at: <strong><%= Now() %></strong>
</p>
</body>
</html>
This piece of code will cache the result for 30 seconds. During that time, responses for all requests for the page will be served from the cache. It also specifies that the caching should vary by the parameter "test". As such, the page will cache a different version for each value of "test" that it is passed and will return the appropriate version based on the value of "test" in the incoming requests.
Fragment Caching
Sometimes it's not possible to cache an entire page. For example, many shopping sites like to greet their users by name. It wouldn't look very good if you went to a site and instead of using your name to greet you it used mine! In the past this often meant that caching wasn't a viable option for these pages. ASP.NET handles this by what they call fragment caching.
Honestly, I find this a little misleading... while you can technically cache part of a page, in order to do so you need to make the section to be cached into a user control and set the OutputCache directive in the new user control. Then you use this control from your dynamic page. The solution works well, but in my mind I think of it as caching a separate mini-page and not really a fragment of a page. I guess it's just semantics, but it is a separate file so it can be a little bit of work to implement.
The caching part is very similar to the code above. Aside from making the section a user control and then using the user control (which we covered in our User Controls lesson) it's pretty boring. There's a sample in the zip file, but I'm not including the code here.
Data Caching
This is the most powerful of the caching options available in ASP.NET. Using data caching you can programmatically cache anything you want for as long as you want. The caching system exposes itself in a dictionary type format meaning items are stored in name/value pairs. You cache an item under a certain name and then when you request that name you get the item back. It's similar to an array or even a simple variable.
In addition to just placing an object into the cache you can set all sorts of properties. The object can be set to expire at a fixed time and date, after a period of inactivity, or when a file or other object in the cache is changed.
The main thing to watch out for with data caching is that items you place in the cache are not guaranteed to be there when you want them back. While it does add some work (you always have to check your object exists after you retrieve it), this scavenging really is a good thing. It gives the caching engine the flexibility to dispose of things that aren't being used or dump parts of the cache if the system starts running out of memory.
Here's a simple example of data caching. Once again it's simply a streamlined version of the script in the zip file.
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Dim strTimestamp As String
' Retrieve our object
strTimestamp = Cache.Get("SomeData")
' Check to see if we got our object back or not.
' If not, deal with it:
If strTimestamp Is Nothing Then
' Assign a value to our object
strTimestamp = Now()
' Insert into cache:
Cache.Insert("SomeData", strTimestamp, Nothing, _
DateTime.Now.AddMinutes(.5), TimeSpan.Zero)
End If
Caching Rules... Get The Code
If you couldn't tell by now, I really like caching. It's an easy way to make your web pages and applications faster and it really doesn't cost you anything except for a little bit of time to figure out what to cache and for how long to cache it. It does use some memory, but with the price of memory these days, adding a little more (if needed) is a small price to pay for a faster web site.
As usual, the code from this lesson is all zipped up in a nice little file so you can download it and play with it on your own.
Labels:
Asp.Net
Life-cycle Events
PreInit
Use this event for the following:
Check the IsPostBack property to determine whether this is the first time the page is being processed.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
NoteNote:
If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
Init
Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.
InitComplete
Raised by the Page object. Use this event for processing tasks that require all initialization be complete.
PreLoad
Use this event if you need to perform processing on your page or control before the Load event.
Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
Load
The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.
Use the OnLoad event method to set properties in controls and establish database connections.
Control events
Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
NoteNote:
In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
LoadComplete
Use this event for tasks that require that all other controls on the page be loaded.
PreRender
Before this event occurs:
The Page object calls EnsureChildControls for each control and for the page.
Each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.
SaveStateComplete
Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.
Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.
Render
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Unload
This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
NoteNote:
During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.
Use this event for the following:
Check the IsPostBack property to determine whether this is the first time the page is being processed.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
NoteNote:
If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
Init
Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.
InitComplete
Raised by the Page object. Use this event for processing tasks that require all initialization be complete.
PreLoad
Use this event if you need to perform processing on your page or control before the Load event.
Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
Load
The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.
Use the OnLoad event method to set properties in controls and establish database connections.
Control events
Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
NoteNote:
In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
LoadComplete
Use this event for tasks that require that all other controls on the page be loaded.
PreRender
Before this event occurs:
The Page object calls EnsureChildControls for each control and for the page.
Each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.
SaveStateComplete
Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.
Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.
Render
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Unload
This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
NoteNote:
During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.
Labels:
Asp.Net
General Page Life-cycle Stages :
Page request :
The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.
Start :
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.
Page initialization :
During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
Load :
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
Validation :
During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
Postback event handling :
If the request is a postback, any event handlers are called.
Rendering :
Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.
Unload :
Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.
The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.
Start :
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.
Page initialization :
During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
Load :
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
Validation :
During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
Postback event handling :
If the request is a postback, any event handlers are called.
Rendering :
Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.
Unload :
Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.
Labels:
Asp.Net
Wednesday, March 3, 2010
Top 10 Lorgest Bridges in World
10. Seven Mile Bridge
The Seven Mile Bridge, in the Florida Keys, runs over a channel between the Gulf of Mexico and the Florida Strait, connecting Key Vaca (the location of the city of Marathon, Florida) in the Middle Keys to Little Duck Key in the Lower Keys. Among the longest bridges in existence when it was built, it is one of the many bridges on US 1 in the Keys, where the road is called the Overseas Highway.

9. San Mateo-Hayward Bridge
The San Mateo-Hayward Bridge (commonly called San Mateo Bridge) is a bridge crossing California’s San Francisco Bay in the United States, linking the San Francisco Peninsula with the East Bay. More specifically, the bridge’s western end is in Foster City, the most recent urban addition to the eastern edge of San Mateo. The eastern end of the bridge is in Hayward. The bridge is owned by the state of California, and is maintained by Caltrans, the state highway agency.

8. Confederation Bridge
The Confederation Bridge (French: Pont de la Confédération) is a bridge spanning the Abegweit Passage of Northumberland Strait, linking Prince Edward Island with mainland New Brunswick, Canada. It was commonly referred to as the “Fixed Link” by residents of Prince Edward Island prior to its official naming. Construction took place from the fall of 1993 to the spring of 1997, costing $1.3 billion. The 12.9-kilometre (8 mi) long bridge opened on 31 May 1997.

7. Rio-Niteroi Bridge
The Rio-Niteroi Bridge is a reinforced concrete structure that connects the cities of Rio de Janeiro and Niteroi in Brazil.
Construction began symbolically on August 23, 1968, in the presence of Queen Elizabeth II of the United Kingdom and Prince Philip, Duke of Edinburgh, in their first and thus far only visit to Brazil. Actual work begun in January, 1969, and it opened on March 4, 1974.
Its official name is “President Costa e Silva Bridge”, in honor of the Brazilian president who ordered its construction. “Rio-Niteroi” started as a descriptive nickname that soon became better known than the official name. Today, hardly anyone refers to it by its official name.

6. Penang Bridge
The Penang Bridge (Jambatan Pulau Pinang in Malay) E 36 is a dual-carriageway toll bridge that connects Gelugor on the island of Penang and Seberang Prai on the mainland of Malaysia on the Malay Peninsula. The bridge is also linked to the North-South Expressway in Prai and Jelutong Expressway in Penang. It was officially opened to traffic on September 14, 1985. The total length of the bridge is 13.5 km (8.4 miles), making it among the longest bridges in the world, the longest bridge in the country as well as a national landmark. PLUS Expressway Berhad is the concession holder which manages it.

5. Vasco da Gama Bridge
The Vasco da Gama Bridge (Portuguese: Ponte Vasco da Gama, pron. IPA: [’põt(?) ‘va?ku d? ‘g?m?]) is a cable-stayed bridge flanked by viaducts and roads that spans the Tagus River near Lisbon, capital of Portugal. It is the longest bridge in Europe (including viaducts), with a total length of 17.2 km (10.7 mi), including 0.829 km (0.5 mi) for the main bridge, 11.5 km (7.1 mi) in viaducts, and 4.8 km (3.0 mi) in dedicated access roads. Its purpose is to alleviate the congestion on Lisbon’s other bridge (25 de Abril Bridge), and to join previously unconnected motorways radiating from Lisbon.

4. Chesapeake Bay Bridge
The Chesapeake Bay Bridge (commonly known as the Bay Bridge) is a major dual-span bridge in the U.S. state of Maryland; spanning the Chesapeake Bay, it connects the state’s Eastern and Western Shore regions. At 4.3 miles (7 km) in length, the original span was the world’s longest continuous over-water steel structure when it opened in 1952. The bridge is officially named the William Preston Lane, Jr. Memorial Bridge after William Preston Lane, Jr. who, as governor of Maryland, implemented its construction.

3. King Fahd Causeway
The King Fahd Causeway is multiple dike - bridge combination connecting Khobar, Saudi Arabia, and the island nation of Bahrain.
A construction agreement signed on July 8, 1981 led to construction beginning the next year. The cornerstone was laid on November 11, 1982 by King Fahd of Saudi Arabia and Sheikh Isa bin Salman al-Khalifa of Bahrain; construction continued until 1986, when the combination of several bridges and dams were completed. The causeway officially opened for use on November 25, 1986.

2. Donghai Bridge
Donghai Bridge (literally “East Sea Grand Bridge”) is the longest cross-sea bridge in the world and the longest bridge in Asia. It was completed on December 10, 2005. It has a total length of 32.5 kilometres (20.2 miles) and connects Shanghai and the offshore Yangshan deep-water port in China. Most of the bridge is a low-level viaduct. There are also cable-stayed sections to allow for the passage of large ships, largest with span of 420 m.

1. Lake Pontchartrain Causeway
The Lake Pontchartrain Causeway, or the Causeway, consists of two parallel bridges that are the longest bridges in the world by total length.[2] These parallel bridges cross Lake Pontchartrain in southern Louisiana. The longer of the two bridges is 23.87 miles (38.42 km) long. The bridges are supported by over 9,000 concrete pilings. The two bridges feature bascule spans over the navigation channel 8 miles (13 km) south of the north shore. The southern terminus of the Causeway is in Metairie, Louisiana, a suburb of New Orleans. The northern terminus is at Mandeville, Louisiana.
The Seven Mile Bridge, in the Florida Keys, runs over a channel between the Gulf of Mexico and the Florida Strait, connecting Key Vaca (the location of the city of Marathon, Florida) in the Middle Keys to Little Duck Key in the Lower Keys. Among the longest bridges in existence when it was built, it is one of the many bridges on US 1 in the Keys, where the road is called the Overseas Highway.
9. San Mateo-Hayward Bridge
The San Mateo-Hayward Bridge (commonly called San Mateo Bridge) is a bridge crossing California’s San Francisco Bay in the United States, linking the San Francisco Peninsula with the East Bay. More specifically, the bridge’s western end is in Foster City, the most recent urban addition to the eastern edge of San Mateo. The eastern end of the bridge is in Hayward. The bridge is owned by the state of California, and is maintained by Caltrans, the state highway agency.
8. Confederation Bridge
The Confederation Bridge (French: Pont de la Confédération) is a bridge spanning the Abegweit Passage of Northumberland Strait, linking Prince Edward Island with mainland New Brunswick, Canada. It was commonly referred to as the “Fixed Link” by residents of Prince Edward Island prior to its official naming. Construction took place from the fall of 1993 to the spring of 1997, costing $1.3 billion. The 12.9-kilometre (8 mi) long bridge opened on 31 May 1997.
7. Rio-Niteroi Bridge
The Rio-Niteroi Bridge is a reinforced concrete structure that connects the cities of Rio de Janeiro and Niteroi in Brazil.
Construction began symbolically on August 23, 1968, in the presence of Queen Elizabeth II of the United Kingdom and Prince Philip, Duke of Edinburgh, in their first and thus far only visit to Brazil. Actual work begun in January, 1969, and it opened on March 4, 1974.
Its official name is “President Costa e Silva Bridge”, in honor of the Brazilian president who ordered its construction. “Rio-Niteroi” started as a descriptive nickname that soon became better known than the official name. Today, hardly anyone refers to it by its official name.
6. Penang Bridge
The Penang Bridge (Jambatan Pulau Pinang in Malay) E 36 is a dual-carriageway toll bridge that connects Gelugor on the island of Penang and Seberang Prai on the mainland of Malaysia on the Malay Peninsula. The bridge is also linked to the North-South Expressway in Prai and Jelutong Expressway in Penang. It was officially opened to traffic on September 14, 1985. The total length of the bridge is 13.5 km (8.4 miles), making it among the longest bridges in the world, the longest bridge in the country as well as a national landmark. PLUS Expressway Berhad is the concession holder which manages it.
5. Vasco da Gama Bridge
The Vasco da Gama Bridge (Portuguese: Ponte Vasco da Gama, pron. IPA: [’põt(?) ‘va?ku d? ‘g?m?]) is a cable-stayed bridge flanked by viaducts and roads that spans the Tagus River near Lisbon, capital of Portugal. It is the longest bridge in Europe (including viaducts), with a total length of 17.2 km (10.7 mi), including 0.829 km (0.5 mi) for the main bridge, 11.5 km (7.1 mi) in viaducts, and 4.8 km (3.0 mi) in dedicated access roads. Its purpose is to alleviate the congestion on Lisbon’s other bridge (25 de Abril Bridge), and to join previously unconnected motorways radiating from Lisbon.
4. Chesapeake Bay Bridge
The Chesapeake Bay Bridge (commonly known as the Bay Bridge) is a major dual-span bridge in the U.S. state of Maryland; spanning the Chesapeake Bay, it connects the state’s Eastern and Western Shore regions. At 4.3 miles (7 km) in length, the original span was the world’s longest continuous over-water steel structure when it opened in 1952. The bridge is officially named the William Preston Lane, Jr. Memorial Bridge after William Preston Lane, Jr. who, as governor of Maryland, implemented its construction.
3. King Fahd Causeway
The King Fahd Causeway is multiple dike - bridge combination connecting Khobar, Saudi Arabia, and the island nation of Bahrain.
A construction agreement signed on July 8, 1981 led to construction beginning the next year. The cornerstone was laid on November 11, 1982 by King Fahd of Saudi Arabia and Sheikh Isa bin Salman al-Khalifa of Bahrain; construction continued until 1986, when the combination of several bridges and dams were completed. The causeway officially opened for use on November 25, 1986.
2. Donghai Bridge
Donghai Bridge (literally “East Sea Grand Bridge”) is the longest cross-sea bridge in the world and the longest bridge in Asia. It was completed on December 10, 2005. It has a total length of 32.5 kilometres (20.2 miles) and connects Shanghai and the offshore Yangshan deep-water port in China. Most of the bridge is a low-level viaduct. There are also cable-stayed sections to allow for the passage of large ships, largest with span of 420 m.
1. Lake Pontchartrain Causeway
The Lake Pontchartrain Causeway, or the Causeway, consists of two parallel bridges that are the longest bridges in the world by total length.[2] These parallel bridges cross Lake Pontchartrain in southern Louisiana. The longer of the two bridges is 23.87 miles (38.42 km) long. The bridges are supported by over 9,000 concrete pilings. The two bridges feature bascule spans over the navigation channel 8 miles (13 km) south of the north shore. The southern terminus of the Causeway is in Metairie, Louisiana, a suburb of New Orleans. The northern terminus is at Mandeville, Louisiana.
Labels:
General