Tuesday, March 23, 2010
What is diffgram in asp.net
Stored Procedures Optimization Tips
This can reduce network traffic, because your client will send to server only stored procedure name (perhaps with some parameters) instead of large heavy-duty queries text. Stored procedures can be used to enhance security and conceal underlying data objects also. For example, you can give the users permission to execute the stored procedure to work with the restricted set of the columns and data.
# Include the SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a Transact-SQL statement.
This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a Transact-SQL statement.
# Call stored procedure using its fully qualified name.
The complete name of an object consists of four identifiers: the server name, database name, owner name, and object name. An object name that specifies all four parts is known as a fully qualified name. Using fully qualified names eliminates any confusion about which stored procedure you want to run and can boost performance because SQL Server has a better chance to reuse the stored procedures execution plans if they were executed using fully qualified names.
# Consider returning the integer value as an RETURN statement instead of an integer value as part of a recordset.
The RETURN statement exits unconditionally from a stored procedure, so the statements following RETURN are not executed. Though the RETURN statement is generally used for error checking, you can use this statement to return an integer value for any other reason. Using RETURN statement can boost performance because SQL Server will not create a recordset.
# Don't use the prefix "sp_" in the stored procedure name if you need to create a stored procedure to run in a database other than the master database.
The prefix "sp_" is used in the system stored procedures names. Microsoft does not recommend to use the prefix "sp_" in the user-created stored procedure name, because SQL Server always looks for a stored procedure beginning with "sp_" in the following order: the master database, the stored procedure based on the fully qualified name provided, the stored procedure using dbo as the owner, if one is not specified. So, when you have the stored procedure with the prefix "sp_" in the database other than master, the master database is always checked first, and if the user-created stored procedure has the same name as a system stored procedure, the user-created stored procedure will never be executed.
# Use the sp_executesql stored procedure instead of the EXECUTE statement.
The sp_executesql stored procedure supports parameters. So, using the sp_executesql stored procedure instead of the EXECUTE statement improve readability of your code when there are many parameters are used. When you use the sp_executesql stored procedure to executes a Transact-SQL statements that will be reused many times, the SQL Server query optimizer will reuse the execution plan it generates for the first execution when the change in parameter values to the statement is the only variation.
# Use sp_executesql stored procedure instead of temporary stored procedures.
Microsoft recommends to use the temporary stored procedures when connecting to earlier versions of SQL Server that do not support the reuse of execution plans. Applications connecting to SQL Server 7.0 or SQL Server 2000 should use the sp_executesql system stored procedure instead of temporary stored procedures to have a better chance to reuse the execution plans.
# If you have a very large stored procedure, try to break down this stored procedure into several sub-procedures, and call them from a controlling stored procedure.
The stored procedure will be recompiled when any structural changes were made to a table or view referenced by the stored procedure (for example, ALTER TABLE statement), or when a large number of INSERTS, UPDATES or DELETES are made to a table referenced by a stored procedure. So, if you break down a very large stored procedure into several sub-procedures, you get chance that only a single sub-procedure will be recompiled, but other sub-procedures will not.
# Try to avoid using temporary tables inside your stored procedure.
Using temporary tables inside stored procedure reduces the chance to reuse the execution plan.
# Try to avoid using DDL (Data Definition Language) statements inside your stored procedure.
Using DDL statements inside stored procedure reduces the chance to reuse the execution plan.
# Add the WITH RECOMPILE option to the CREATE PROCEDURE statement if you know that your query will vary each time it is run from the stored procedure.
The WITH RECOMPILE option prevents reusing the stored procedure execution plan, so SQL Server does not cache a plan for this procedure and the procedure is recompiled at run time. Using the WITH RECOMPILE option can boost performance if your query will vary each time it is run from the stored procedure because in this case the wrong execution plan will not be used.
# Use SQL Server Profiler to determine which stored procedures has been recompiled too often.
To check the stored procedure has been recompiled, run SQL Server Profiler and choose to trace the event in the "Stored Procedures" category called "SP:Recompile". You can also trace the event "SP:StmtStarting" to see at what point in the procedure it is being recompiled. When you identify these stored procedures, you can take some correction actions to reduce or eliminate the excessive recompilations.
Thursday, March 11, 2010
Niagara Falls - Amazing Power and Beauty!
The Niagara Falls are massive waterfalls on the Niagara River, straddling the international border separating the Canadian province of Ontario and the U.S. state of New York. The falls are 17 miles (27 km) north-northwest of Buffalo, New York, 75 miles (120 km) south-southeast of Toronto, Ontario, between the twin cities of Niagara Falls, Ontario, and Niagara Falls, New York.
Niagara Falls is composed of two major sections separated by Goat Island: Horseshoe Falls, on the Canadian side of the border and American Falls on the United States side. The smaller Bridal Veil Falls also is located on the American side, separated from the main falls by Luna Island. Niagara Falls were formed when glaciers receded at the end of the Wisconsin glaciation (the last ice age), and water from the newly-formed Great Lakes carved a path through the Niagara Escarpment en route to the Atlantic Ocean.
While not exceptionally high, the Niagara Falls are very wide. More than six million cubic feet (168,000 m³) of water falls over the crest line every minute in high flow, and almost 4 million cubic feet (110,000 m³) on average. It is the most powerful waterfall in North America.
The Niagara Falls are renowned both for their beauty and as a valuable source of hydroelectric power. Managing the balance between recreational, commercial, and industrial uses has been a challenge for the stewards of the falls since the 1800s.
Peak numbers of visitors occur in the summertime, when Niagara Falls are both a daytime and evening attraction. From the Canadian side, floodlights illuminate both sides of the Falls for several hours after dark (until midnight). The number of visitors in 2008 is expected to total 20 million and by 2009, the annual rate is expected to top 28 million tourists a year. The oldest and best known tourist attraction at Niagara Falls is the Maid of the Mist boat cruise, named for an ancient Ongiara Indian mythical character, which has carried passengers into the whirlpools beneath the Falls since 1846. Cruise boats operate from boat docks on both sides of the falls.
American side
From the U.S. side, the American Falls can be viewed from walkways along Prospect Point Park, which also features the Prospect Point Park observation tower and a boat dock for the Maid of the Mist. Goat Island offers more views of the falls and is accessible by foot and automobile traffic by bridge above the American Falls. From Goat Island, the Cave of the Winds is accessible by elevator and leads hikers to a point beneath Bridal Veil Falls. Also on Goat Island are the Three Sisters Islands, the Power Portal where a huge statue of Nikola Tesla can be seen, and a walking path which enables views of the rapids, the Niagara River, the gorge, and all of the Falls. Most of these attractions lie within the Niagara Falls State Park.
The Niagara Scenic Trolley offers guided trips along the American Falls and around Goat Island. Panoramic and aerial views of the falls can also be viewed from the Flight of Angels helium balloon ride, or by helicopter. The Niagara Gorge Discovery Center showcases the natural and local history of Niagara Falls and the Niagara Gorge. A casino and luxury hotel was opened in Niagara Falls, New York, by the Seneca Indian tribe. The Seneca Niagara Casino occupies the former Niagara Falls Convention Center. The new hotel is the first addition to the city's skyline since completion of the United Way office building in the twenties.
Canadian side
On the Canadian side, Queen Victoria Park features manicured gardens, platforms offering spectacular views of both the American and Horseshoe Falls, and underground walkways leading into observation rooms which yield the illusion of being within the falling waters. The observation deck of the nearby Skylon Tower offers the highest overhead view of the Falls, and in the opposite direction gives views as far as distant Toronto. Along with the Minolta Tower (formerly the Seagrams Tower, currently the Konica Minolta Tower), it is one of two towers in Canada with a view of the Falls.
Along the Niagara River, the Niagara River Recreational Trail runs the 35 miles (56 km) from Fort Erie to Fort George, and includes many historical sites from the War of 1812.
The Whirlpool Aero Car, built in 1916 from a design by Spanish engineer Leonardo Torres y Quevedo, is a cable car which takes passengers over the whirlpool on the Canadian side. The Journey Behind the Falls - accessible by elevators from the street level entrance - consists of an observation platform and series of tunnels near the bottom of the Horseshoe Falls on the Canadian side.
There are two casinos on the Canadian side of Niagara Falls, the Niagara Fallsview Casino Resort and Casino Niagara. The former is situated in the Fallsview Tourist Area, alongside many of the area's hotels, whilst the latter is adjacent to Clifton Hill, on Falls Avenue, a major tourist promenade.
Improve Your Web Site’s SEO With SEOmoz’s Free API
Search Engine Optimization, or SEO, is vital to any successful website. The team at SEOmoz are experts in this field and now offer a number of premium SEO tools including the recently released Open Site Explorer, which provides a wealth of information on backlinks and link popularity. Now the same information available through Open Site Explorer can be accessed via a new, free API. From their announcement:
The launch of Open Site Explorer last week opens up a lot of link data, filters, and anchor text to a much wider audience than we’ve ever had before. In that same vein, today we’re announcing our new and improved SEOmoz Free API.
Any registered (it’s free) SEOmoz member can visit our API Portal and get an API key that gives you access to:
- Data for any URL in our index including
- Domain and Page Authority
- mozRank
- total link count
- external, followed link count
- The first 500 links to any page, sub domain or domain
- Filtering on those links: 301s, Follows, External, etc.
- The first 3 domains linking to any page, sub domain or domain
- The first 3 anchor text terms or phrases in links to any page, sub domain or domain
Reaction to Open Site Explorer has been good (like here and here), and the API Moz API is already being put to use by a number of parters including Buzzstream, Brandwatch, HubSpot’s Grader Suite and Quirk’s Search Status toolbar. New developers will find plenty of source code and examples on this wiki.
Those looking for more detailed information can make use of the SEOmoz paid API, which includes additional features seen in Open Site Explorer Pro.
You can find more information in our SEOmoz API profile, along with links to a dozen other SEO-related APIs.
"
Thursday, March 4, 2010
State Management Summary
1. View State
Advantage:
ASP.Net in built state management technique.
Can be used to store small amount of information in encrypted form at client side.
Disadvantage :
It is sent back and forth in each page request and post back so their may be performance hit if large amount of data is stored in that.
Recommended:
State is retained only when post request is made to page. When small amount of data needs to be stored on the page which is needed when post request is made to a page.
Life Time/Scope:
Per Page
2.Query Strings:
Advantage:
It can be used to pass small amount of data b/w pages.
Disadvantage :
Data passed in the url so security may be issue and it should not be used to pass any sensitive data.
Recommended:
It can be used to pass any general information b/ pages of application.
Life Time/Scope:
Per Page
3.Hidden Fields :
Advantage:
It can be very useful when additional information needs to sent to client side for validations.
Disadvantage :
All the information is stored at client side and anyone can view it using source of the web page.
Recommended:
It can be used very carefully as all the information is at client side. Generally it is used to pass data which can be used to validate user entries on the page. Or it can b used to contain values specific to user.
Life Time/Scope:
Per Page
4. Cookies:
Advantage:
State is stored at client side. It can be shared across multiple sessions in case of permanent cookie.
Disadvantage :
Depends on client browser setting.
It can not be used for large amount of data as it is sent back and forth in each page request.
Recommended:
When small amount of data less than 4 KB needs to stored at client side. Generally used for authentication in ASP.Net. It can be used in case site retains user preferences.
Life Time/Scope:
Per Client
Server Side State Management
5. Session State :
Advantage:
It can be shared with different machine and different processors.
It can use persistent medium like SQL server or different processes.
Disadvantage :
Storing state in persistent medium can be hard to maintain.
Uses Cookies or URL to manage state.
Recommended:
Generally used in ASP.Net application to store state specific information this can be shared across page for a single client.
Life Time/Scope:
Per Client
6. Application State
Advantage:
It can be shared across all the clients.
Disadvantage :
It can not be shared b/w machines and processors.
Its use should be limited as it can reduce scalability of the application.
State Management Techniques in ASP.NET
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.
Dot Net 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";
The Types of Caching in ASP.NET
• 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.
Life-cycle Events
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.
General Page Life-cycle Stages :
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.
Wednesday, March 3, 2010
Top 10 Lorgest Bridges in World
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.