Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework


About Me

Great Blogs

March 2010 - Posts

ASP.NET 4.0 meta tags and Search engine optimisation

I am thinking to create a new series of posts regarding ASP.NET and SEO (Search Engine Optimisation).

I am going to start with this post , talking about some new features that make our apps more SEO friendly.

At the end of the day, there is no point having a great application and somehow "scare" the search engines away. This is going to be a short post so let's quickly have a look at meta keywords and ASP.NET 4.0. Meta keywords and description are important elements of a page and make it search engine friendly. ASP.Net 4.0 added 2 new properties on the Page object to let us define the Meta Keywords and Description. Create a simple application using Visual Studio 2010. In the Default.aspx.cs code behind file type:

Page.MetaKeywords = ",vb,c#,css,html,"; Page.MetaDescription = "This is my blog that focuses on ASP.NET.";
Alternatively we can add those two meta tags in the Page directive
<%@ Page Language="C#" MetaKeywords=",vb,c#,css,html" MetaDescription="This is my blog that focuses on ASP.NET." AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
Run your application. Go to View->Source and see the meta tags
</title><meta name="description" content="This is my blog that focuses on ASP.NET." /><meta name="keywords" content=",vb,c#,css,html" /></head>
Now we can demonstrate the use of meta keywords in another example.
We will have a simple application where someone selects the categories from the dropdown list, and the relevant products appear in the Gridview control.
We will try to see how to make those dynamically created pages more SEO friendly.
I assume that you have access to a version of SQL Server and Northwind database.
If you do not, you can download and install the free SQL Server Express edition from here. If you need the installation scripts for the sample Northwind database, click here
1) Fire the VS 2010
2) Create a new website and use C# as the development language
3) Drag and drop a Gridview control from the Toolbox in the default.aspx page. Leave the default name.
4) Drag and drop a Dropdown control from the Toolbox in the default.aspx page. Leave the default name.
5) Drag and drop a SqlDataSource control from the Toolbox in the default.aspx page. Leave the the default name (SqlDataSource1).
6) Drag and drop a SqlDataSource control from the Toolbox in the default.aspx page. Leave the the default name (SqlDataSource2).
7) Configure the SqlDataSource2 control to use a connection string and open a connection string to the Northwind database.
The SQL statement should be "SELECT DISTINCT [CategoryName], [CategoryID] FROM [Categories]"
8) For the Dropdownlist1 control, set the datasource to the SqlDataSource2 and enable the AutoPostBack
9) Configure the SqlDataSource1 control to use a connection string and open a connection string to the Northwind database.
The SQL Statement should be something like this "SELECT CategoryID, ProductName FROM Products WHERE (CategoryID = @categoryid)"
Naturally we have a parameter, the categoryid is passed to the above query from the dropdownlist control.
10)  For the GridView1 control, set the datasource to the SqlDataSource1.
11) In the Page_Load event method type the following
protected void Page_Load(object sender, EventArgs e)

            string myvalue = Convert.ToString(DropDownList1.SelectedItem);

            switch (myvalue)
                case "Beverages":
                    Page.MetaDescription = "display products that belong to beverages";
                    Page.MetaKeywords = "beverages,refreshements";
                case "Condiments":
                    Page.MetaDescription = "display products that belong to condiments";
                    Page.MetaKeywords = "condiments";
                case "Confections":
                    Page.MetaDescription = "display products that belong to confections";
                    Page.MetaKeywords = "confections";
                case "Dairy Products":
                    Page.MetaDescription = "display products that belong to dairy products";
                    Page.MetaKeywords = "dairy products";
                case "Grains/Cereals":
                    Page.MetaDescription = "display products that belong to grains/cereals";
                    Page.MetaKeywords = "grains";
                case "Meat/Poultry":
                    Page.MetaDescription = "display products that belong to meat/poultry";
                    Page.MetaKeywords = "meat/poultry";
                case "Produce":
                    Page.MetaDescription = "display products that belong to produce";
                    Page.MetaKeywords = "produce";
                case "Seafood":
                    Page.MetaDescription = "display products that belong to seafood";
                    Page.MetaKeywords = "seafood";
                    Page.MetaDescription = "Welcome to our products sites";
                    Page.MetaKeywords = "beverages,condiments,seafood";

You can see what I am doing here. I just find the selected value that the user selected and display the relevant meta keywords that I want.
12) Run your application and make sure everything works ok. Then go to your browser window and select View->Source and see the meta keywords for all the various selections of categories you make.  
Leave a comment with your email of you need the source code.
Hope it helps!!!
Compress session state in ASP.Net 4.0

Hello folks,

In this post I would like to talk about a new feature of ASP.NET 4.0 -  easy state compression.

When we create applications the user must feel that whenever he interacts with the website, he actually interacts with something that can be safely described as an application.

What I mean by this is that is that during a postback the whole page is re-created and is sent back to the client in a fraction of a second. The server has no idea what the user does with the page.

If we had to work on that basis then we would not have an application but a series of disconnected web pages with no use at all.

In order to overcome this deficit, we do have various session state mechanisms that are well documented elsewhere on the internet.

ASP.NET session state can identify requests from the same user during a specified time interval and gives us a way to preserve variable values for the duration of that session-time interval.

Here come the obvious question. Where are all those variables stored?

ASP.NET session state supports several different storage options for session data. One of them is SQL Server.

All the variables data persist to a SQL Server database rather than being stored in memory.

We must create the tables and stored procedures that ASP.NET will look for on the SQL Server. Have a look here for more details on how to accomplish that.

So what happens is that Session state is serialised into bytes and stored in those sql server tables.

Now we must add some configuration to our application. and how do we do that?

We do add some lines in the web.config file.Have a look

<sessionState allowCustomSqlDatabase="true" sqlConnectionString="data source=local;Initial Catalog=sessionstatedb" compressionEnabled="true" />

The important setting that was added in ASP.Net 4.0 is the last setting, compressionEnabled="true".

This means that all the session data that is transferred between the client and the server can now be compressed, resulting in better performance.

Hope it helps!!!

Permanently redirect your pages in ASP.Net 4.0

 Hello all,

In this post, I would like to talk about a new method of the Response object that comes with ASP.Net 4.0.

The name of the method is RedirectPermanent.

Let's talk a bit about 301 redirection and permanent redirection.301 redirect is the most efficient and Search Engine Friendly method for webpage redirection.

Let's imagine that we have this scenario. This is a very common scenario. We have redesigned and move folders to some pages that have high search engine rankings. We do not want to lose those rankings.

We can permanently redirect traffic to the new pages without losing page rankings by using the 301 permanent redirect. RedirectPermanent help us to achieve that.

In order to demonstrate this new helper method, I will create the default website that comes with 4.0.

1) Fire VS 2010 and create a new website. Choose the filesystem to save your website ann VB as the .net language for this website

This is a much richer template that the previous ones that were created with VS 2008.

We have a Home page and an About page.

2) Create a new page and call it NewAbout (NewAbout.aspx)

3) Write some dummy content on it like "This is our new About us page"

4) Move to the About.aspx.vb, and in the page load event, type the following

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    End Sub

5)  Now run your application and then click "About" page. You will permanently redirect to the new "NewAbout" page.

Hope it helps!!!!


Maintain scroll position in ASP.NET

One of the most common questions I get is " How to maintain the scroll position-location when a postback occurs in our ASP.NET application? "

A lot of times when  we click on a e.g a button in our application and a postback occurs, our application "loses" its scroll position.

The default behaviour is to go back to the top of the page.

There is a very nice feature in ASP.NET that enables us to maintain the scroll position in ASP.NET.

The name of this attribute is MaintainScrollPositionOnPostBack.

We can set the  MaintainScrollPositionOnPostBack="true"

we can do that within the Page directive e.g

<% Page Language ="C#"  MaintainScrollPositionOnPostBack="true" %>

So now the browser remembers where it was before the post back occured and knows how to keep track of the scroll position.

This is of course achieved with client-side Javascript code that it is injected into the page for us.

So if you go to View -->Source in your browser window, you will see the generated Javascript code.

Hope it helps!!!!


Retail Deployment of applications

I have this friend of mine who is responsible of a team of developers that develop applications for people from all walks of life.

One of his main concerns were that he had to check the deployment stage of every application very carefully and constantly had to correct common mistakes in the web.config file.

Some common mistakes in the web.config are detailed in this post

One of the most common corrections is  to set

<compilation debug ="true">  to <compilation debug ="false">

If we leave debug = "true" , we have an application that is less secure and not performing well.

It takes more time to compile. Memory usage is higher. Scripts and images cannot be cached.

His question was how to set  <compilation debug ="false">  to all web applications that are hosted under a particular server running IIS  - deployment machine.

We do know that lots of the settings in the web.config are inherited from the machine.config. The web.config settings can overwrite the settings in the machine.config.

Works like the cascading stylesheets ( the internal stylesheet overwrites the external, for the same property:value pair )

In order to have all our sites deployed in retail fashion we must open and edit the machine.config file. you can find this file in this path in your PC.


You can add these lines of code


        <deployment retail="true" />


This setting overrides application level security settings.

This means that even if we do have in our application web.config file this setting

 <compilation debug ="true">

it will just ignore it and force this web application of ours to behave like this

  • debug set to false
  • disable page output tracing
  • custom error pages to be shown to the remote users instead of detailed error messages or the stack trace

We should not edit machine.config too often, unless we have to.

Hope it helps !!!

Posted: Mar 05 2010, 10:58 PM by nikolaosk | with 1 comment(s) |
Filed under: ,
How to set the focus on an server control

It is a very common request when designing an application, to set the focus on an control.

We can set the focus on an control

  • dynamically
  • declaratively

Some of the most common server controls we can set the focus on are:

  • TextBox
  • ListBox
  • RadioButton
  • CheckBox
  • Hyperlink

Let's create an application with Visual studio

1) We fire the Visual Studio 2008-2010

2) We create an web site, from the available templates

3) We choose C# as a programming language

4) We drag and drop on the empty default.aspx the following controls

  • TextBox
  • HyperLink
  • Button

5) Leave the default names ( Button1, Hyperlink1, TextBox1 )

6) If we want to set the focus on the Hyperlink control

7) In the Page_Load event handler routine we can type the following

protected void Page_Load(object sender, EventArgs e)
        if (HyperLink1 != null) HyperLink1.Focus();

8) So we just use the Focus method of the Hyperlink control

9) We can also set the focus on a web server control, by using the SetFocus() method of the Page control, by passing as a parameter in the SetFocus() method, the control ID.

This is how we transform the code snippet above

protected void Page_Load(object sender, EventArgs e)
        if (HyperLink1 != null) Page.SetFocus(HyperLink1);

10 ) Another way to set the focus on a control (TextBox1) is to do so declaratively. In the default.aspx page we can write in the form tag

<form id="form1" runat="server" defaultfocus="TextBox1">

11) Now we can add another page, Validation.aspx , and this can be a page where, someone can log in to our web site. have a look at the screenshot below. We have textboxes, radio buttons and a button.


12) We also add RequiredFieldValidator controls on the page and we associate them with the controls.

13) So if the validation fails, the focus will be set on the control that failed in the validation process ( e.g email ).

14) Have a look at the code below. The important property to look for is SetFocusOnError="true"


<asp:requiredfieldvalidator id="_firstNameValidator" runat="server" width="100%" InitialValue="" ErrorMessage="First name must be filled in." SetFocusOnError="true"
                            Display="Dynamic" ControlToValidate="_firstname" ValidationGroup="SignUp"><img id="Img1" runat="server" enableviewstate="False" src='~/images/oops.jpg' />

Important Note:In order for the set focus on the controls to operate as above , the client side scripting on the browsers must be enabled.

If you need the source code, please email me at ""

Hope it helps!!!

More Posts