Thursday, 26 August 2010

How to Use the Canonical Tag

Google, Yahoo & Microsoft Unite On “Canonical Tag” To Reduce Duplicate Content Clutter

The web is full of duplicate content. Search engines try to index and display the original or “canonical” version. Searchers only want to see one version in results. And site owners worry that if search engines find multiple versions of a page, their link credit will be diluted and they’ll lose ranking.

Today, Google, Yahoo and Microsoft (links are to their separate announcements) have united to offer a way to reduce duplicate content clutter and make things easier for everyone. Webmasters rejoice! Worried about duplicate content on your site? Want to know what “canonical” means? Read on for more details.

Multiple URLs, one page

Duplicate content comes in different forms, but a major scenario is multiple URLs that point to the same page. This can come up for lots of reasons. An ecommerce site might allow various sort orders for a page (by lowest price, highest rated…), the marketing department might want tracking codes added to URLs for analytics. You could end up with 100 pages, but 10 URLs for each page. Suddenly search engines have to sort through 1,000 URLs.

This can be a problem for a couple of reasons.

* Less of the site may get crawled. Search engine crawlers use a limited amount of bandwidth on each site (based on numerous factors). If the crawler only is able to crawl 100 pages of your site in a single visit, you want it to be 100 unique pages, not 10 pages 10 times each.

* Each page may not get full link credit. If a page has 10 URLs that point to it, then other sites can link to it 10 different ways. One link to each URL dilutes the value the page could have if all 10 links pointed to a single URL.

Using the new canonical tag

Specify the canonical version using a tag in the head section of the page as follows:

<link rel="canonical" href="http://www.example.com/product.php?item=swedish-fish"/>

That’s it!

* You can only use the tag on pages within a single site (subdomains and subfolders are fine).
* You can use relative or absolute links, but the search engines recommend absolute links.

This tag will operate in a similar way to a 301 redirect for all URLs that display the page with this tag.

* Links to all URLs will be consolidated to the one specified as canonical.
* Search engines will consider this URL a “strong hint” as to the one to crawl and index.

Canonical URL best practices

The search engines use this as a hint, not as a directive, (Google calls it a “suggestion that we honor strongly”) but are more likely to use it if the URLs use best practices, such as:

* The content rendered for each URL is very similar or exact
* The canonical URL is the shortest version
* The URL uses easy to understand parameter patterns (such as using ? and %)

Can this be abused by spammers? They might try, but Matt Cutts of Google told me that the same safeguards that prevent abuse by other methods (such as redirects) are in place here as well, and that Google reserves the right to take action on sites that are using the tag to manipulate search engines and violate search engine guidelines.

For instance, this tag will only work with very similar or identical content, so you can’t use it to send all of the link value from the less important pages of your site to the more important ones.

If tags conflict (such as pages point to each other as canonical, the URL specified as canonical redirects to a non-canonical version, or the page specified as canonical doesn’t exist), search engines will sort things out just as they do now, and will determine which URL they think is the best canonical version.

For more info visit
http://searchengineland.com/canonical-tag-16537
http://googlewebmastercentral.blogspot.com/2007/09/google-duplicate-content-caused-by-url.html
http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html
How to Use the Canonical Tag

Regular Expressions

A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. You are probably familiar with wildcard notations such as *.txt to find all text files in a file manager. The regex equivalent is .*\.txt$.

Some Definitions

We are going to be using the terms literal, metacharacter, target string, escape sequence and search string in this overview. Here is a definition of our terms:

literal A literal is any character we use in a search or matching expression, for example, to find ind in windows the ind is a literal string - each character plays a part in the search, it is literally the string we want to find.

metacharacter A metacharacter is one or more special characters that have a unique meaning and are NOT used as literals in the search expression, for example, the character ^ (circumflex or caret) is a metacharacter.

escape sequence An escape sequence is a way of indicating that we want to use one of our metacharacters as a literal. In a regular expression an escape sequence involves placing the metacharacter \ (backslash) in front of the metacharacter that we want to use as a literal, for example, if we want to find ^ind in w^indow then we use the search string \^ind and if we want to find \\file in the string c:\\file then we would need to use the search string \\\\file (each \ we want to search for (a literal) is preceded by an escape sequence \).

target string This term describes the string that we will be searching, that is, the string in which we want to find our match or search pattern.

search expression This term describes the expression that we will be using to search our target string, that is, the pattern we use to find what we want.

Brackets, Ranges and Negation

Bracket expressions introduce our first metacharacters, in this case the square brackets which allow us to define list of things to test for rather than the single characters we have been checking up until now. These lists can be grouped into what are known as Character Classes typically comprising well know groups such as all numbers etc.

[ ] Match anything inside the square brackets for one character position once and only once, for example, [12] means match the target to either 1 or 2 while [0123456789] means match to any character in the range 0 to 9.

- The - (dash) inside square brackets is the 'range separator' and allows us to define a range, in our example above of [0123456789] we could rewrite it as [0-9].

You can define more than one range inside a list e.g. [0-9A-C] means check for 0 to 9 and A to C (but not a to c).

NOTE: To test for - inside brackets (as a literal) it must come first or last, that is, [-0-9] will test for - and 0 to 9.

^ The ^ (circumflex or caret) inside square brackets negates the expression (we will see an alternate use for the circumflex/caret outside square brackets later), for example, [^Ff] means anything except upper or lower case F and [^a-z] means everything except lower case a to z.

NOTE:Spaces, or in this case the lack of them, between ranges are very important.

Positioning (or Anchors)

^ The ^ (circumflex or caret) outside square brackets means look only at the beginning of the target string, for example, ^Win will not find Windows in STRING1 but ^Moz will find Mozilla.

$ The $ (dollar) means look only at the end of the target string, for example, fox$ will find a match in 'silver fox' since it appears at the end of the string but not in 'the fox jumped over the moon'.

. The . (period) means any character(s) in this position, for example, ton. will find tons and tonneau but not wanton because it has no following character.

Iteration 'metacharacters'

The following is a set of iteration metacharacters (a.k.a. quantifiers) that can control the number of times a character or string is found in our searches.

? The ? (question mark) matches the preceding character 0 or 1 times only, for example, colou?r will find both color and colour.

* The * (asterisk or star) matches the preceding character 0 or more times, for example, tre* will find tree and tread and trough.

+ The + (plus) matches the previous character 1 or more times, for example, tre+ will find tree and tread but not trough.

More 'metacharacters'

The following is a set of additional metacharacters that provide added power to our searches:

() The ( (open parenthesis) and ) (close parenthesis) may be used to group (or bind) parts of our search expression together.

"MSIE.(5\.[5-9])|([6-9])" matches MSIE 5.5 (or greater) OR MSIE 6+.

| The | (vertical bar or pipe) is called alternation in techspeak and means find the left hand OR right values, for example, gr(a|e)y will find 'gray' or 'grey'.

Common Extensions and Abbreviations

Character Class Abbreviations

\d Match any character in the range 0 - 9
\D Match any character NOT in the range 0 - 9
\s Match any whitespace characters (space, tab etc.).
\S Match any character NOT whitespace (space, tab).
\w Match any character in the range 0 - 9, A - Z and a - z
\W Match any character NOT the range 0 - 9, A - Z and a - z

Positional Abbreviations

\b Word boundary. Match any character(s) at the beginning (\bxx) and/or end (xx\b) of a word, thus \bton\b will find ton but not tons, but \bton will find tons.
\B Not word boundary. Match any character(s) NOT at the beginning(\Bxx) and/or end (xx\B) of a word, thus \Bton\B will find wantons but not tons, but ton\B will find both wantons and tons.

See Regular Expressions - User guide for more information.

http://www.regular-expressions.info/

Monday, 26 July 2010

Unload Event in ASP.NET Page Life Cycle

The Unload event is raised 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 cleanup is performed.

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.

protected override void OnUnload(EventArgs e)
{
base.OnUnload(e);

// your code
}


ASP.NET Page Life Cycle Overview

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 stage, 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. The page also sets the UICulture property.

Initialization
During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. 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.

Postback event handling
If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Rendering
Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

Unload
The Unload event is raised 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 cleanup is performed.

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. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
* Create or re-create dynamic controls.
* Set a master page dynamically.
* Set the Theme property dynamically.
* Read or set profile property values.

***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. The Init event of individual controls occurs before the Init event of the page.

Use this event to read or initialize control properties.

InitComplete
Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.

Use this event to make changes to view state that you want to make sure are persisted after the next postback.

Preload
Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

Load
The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.

Use the OnLoad event method to set properties in controls and to 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.
Note : 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
Raised at the end of the event-handling stage.

Use this event for tasks that require that all other controls on the page be loaded.

PreRender

Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)

The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

PreRenderComplete
Raised after 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.

SaveStateComplete
Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.

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 to send 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
Raised 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.

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

Tuesday, 20 July 2010

ASP.NET 2.0 Wizard Control

One of the useful new controls in ASP.NET 2.0 is the <asp:wizard> control, which allows developers to easily create multi-step UI (with built-in previous/next functionality and state management of values).

There is a nice 14 minute online video now available that walks through how to build an ASP.NET 2.0 application from scratch that provides a customer online signup form system using the <asp:wizard> control, the asp.net validation controls, and the new System.Net.Mail mail library. You can watch it being built from scratch and learn the high-level concepts of how the Wizard control works here (to find other short task-focused videos in the new ASP.NET 2.0 "How Do I" series click here).

Here are a few other articles you can read to learn more about the <asp:wizard> control and how to take advantage of it:

* MSDN Magazine Cutting Edge Article (note: this is a little old -- but provides a good conceptual overview)
* ASP.NET QuickStart Samples for the Wizard Control
* Create a Basic Wizard Control
* Create an Advanced Wizard Control
* Wizard Control MSDN Reference Overview

One nice tip/trick you can use with the Wizard control is to host it within the new <atlas:updatepanel> control -- which turns the wizard into an Ajax based wizard (no full page post-backs required). This is trivial to-do and doesn't require any code changes. This blog post of Scott Gu talks a little about using the <atlas:updatepanel> with the december CTP drop of Atlas, and builds an Ajax task-list in 39 lines of code with it (no javascript required -- it can all be done with C#). You can learn more about the January CTP drop (which has a lot of enhancements and new features for the <atlas:updatepanel> here).

http://weblogs.asp.net/scottgu/archive/2006/02/21/438732.aspx

Wednesday, 7 July 2010

Explicit and Implicit Interface Implementation

A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.

Explicit interface implementation also allows the programmer to inherit two interfaces that share the same member names and give each interface member a separate implementation.


http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx

Generating Forms Authentication Compatible Passwords (SHA1)

Why would we want to create an SHA1 Password Hash?
The answer to this is easy. It is dangerous to store passwords anywhere in plain text!! SHA1 gives a quick and easy way to encode a password into a non-human readable form. This means it is safer to store in a database, and should the database be viewed by anyone who shouldn't know the passwords, it will be much more difficult for them to work out what a user's password is.

When creating a Web Application we can use the HashPasswordForStoringInConfigFile object in the FormsAuthentication namespace to generate our SHA1 password hash.

The following section of code shows an example of this:

Dim encpass As String = _
FormsAuthentication.HashPasswordForStoringInConfigFile(tbxPassword.Text, _
"sha1")
tbxResult.Text = encpass.ToString()

The code takes the text from the "thePassword" textbox control and hashes the contents with the SHA1 algorithm. The result is then in the "theResult" textbox control.

This hashed password can then be placed in your web.config file or in a database and used in your web application for Forms Authentication. In a future tutorial we will show how to go on and use this in an application.


http://www.stardeveloper.com/articles/display.html?article=2003062001&page=1

Cookieless Forms Authentication

ASP.NET 2.0 supports cookieless forms authentication. This feature is controlled by the cookieless attribute of the forms element. This attribute can be set to one of the following four values:

* UseCookies. This value forces the FormsAuthenticationModule class to use cookies for transmitting the authentication ticket.
* UseUri. This value directs the FormsAuthenticationModule class to rewrite the URL for transmitting the authentication ticket.
* UseDeviceProfile. This value directs the FormsAuthenticationModule class to look at the browser capabilities. If the browser supports cookies, then cookies are used; otherwise, the URL is rewritten.
* AutoDetect. This value directs the FormsAuthenticationModule class to detect whether the browser supports cookies through a dynamic detection mechanism. If the detection logic indicates that cookies are not supported, then the URL is rewritten.

If your application is configured to use cookieless forms authentication and the FormsAuthentication.RedirectFromLoginPage method is being used, then the FormsAuthenticationModule class automatically sets the forms authentication ticket in the URL. The following code example shows what a typical URL looks like after it has been rewritten:

http://localhost/CookielessFormsAuthTest/(F(-k9DcsrIY4CAW81Rbju8KRnJ5o_gOQe0I1E_jNJLYm74izyOJK8GWdfoebgePJTEws0Pci7fHgTOUFTJe9jvgA2))/Test.aspx


The section of the URL that is in parentheses contains the data that the cookie would usually contain. This data is removed by ASP.NET during request processing. This step is performed by the ASP.NET ISAPI filter and not in an HttpModule class. If you read the Request.Path property from an .aspx page, you won't see any of the extra information in the URL. If you redirect the request, the URL will be rewritten automatically.

Note It is not possible to secure authentication tickets contained in URLs. When security is paramount, you should use cookies to store authentication tickets.

http://msdn.microsoft.com/en-us/library/ff647070.aspx