jump to navigation

Caching an ASP.Net page October 6, 2010

Posted by fofo in asp.net, VB 2005, VB 2008, VB 9.0, Visual Basic 10.0, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010, VS 2010.
1 comment so far

The issue of “caching” keeps coming up in my asp.net seminars so I though it would be a good idea to write a post. I know it is a well documented feature and widely used but I really believe most people will be able to use this rather simple example and understand the concepts behind caching.

You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 express editions work fine).

I will use VS 2010 Ultimate edition and VB.net as the .Net language of choice.

1) Create an Asp.net web site and name it as you want.

2) In the default.aspx page add a new paragraph or header with content of your choice.In my case i have added something like this

<h2>Caching is really useful!!!!</h2>

3) Let’s think simple at first. We do want to cache the entire page (default.aspx)

Just below the Page directive ( top of the page ) you add the following bit of code:

<%@ OutputCache Duration="20" VaryByParam="none" %>

We do cache the page for 20 seconds. That is determined by the Duration Attribute.

4) Save your work and run your application. The first time we see the output of the asp.net page, this is served directly from the asp.net engine.

If you hit refresh for a period for less than 20 seconds the page is served from the Cache.

5) Let’s see a more complex scenario involving query strings and how we can make a decision on whether to cache the page or not based on the value of the query string. Add a new label control to the .aspx page

 <asp:Label ID="mylabel" runat="server"></asp:Label>

In the Page_Load event handler routine add the code

If (Not Request("id") Is Nothing) Then 
mylabel.Text = " The query string value is " + Request("id").ToString()

End If

6) Change the OutputCache directive to

 <%@ OutputCache Duration="20" VaryByParam="id" %>

7) Run your application and type in the url address bar http://localhost:6141/caching/Default.aspx?id=5. See the results. If you hit refresh right away the page is refreshed from the cache and it is not reloaded.

If you type this http://localhost:6141/caching/Default.aspx?id=6 ( within the 20 seconds period ) it senses that the id has changed now and it re-renders the page. It also sets a new caching period of 20 seconds.

8) What is really interesting to bear in mind ( and not many people know ) is that you can have different caching settings depending on the client’s browser.The first step is to change the OutputCache directive to this

<%@ OutputCache Duration="20" VaryByParam="id" VaryByCustom="browser" %>

9) Basically we say “Continue to cache the page as long as the clients use the same browser”. So if you have 3 people in a row that have IE8 hitting your page, will all get the same cached version of the page.

If someone hits our page with Firefox or Chrome, they will a brand new rendered page. At this time it will be created a 20 seconds cache window period specific for each browser.This functionality is built into the caching module, and will insert separate cached versions of the page for each browser name and major version.

10) Now if we need to apply the caching techniques we just learnt in all pages of our asp.net application we will have to make a few modifications in the web.config file.We will add something that is called “Cache Profiles”

Just below the <system.web> add this snippet

          <add name="basic" 




So we have created a new profile that is called “basic”. Now let’s apply this cache profile to one or more pages in our website.

So we switch back to our default.aspx page and in the OutputCache directive, type

 <%@ OutputCache CacheProfile="basic" %>

Run your application again and you will see that we do have the same caching effects.

Obviously you can create different cache profiles and apply them to various pages.

I will have more posts on caching shortly.

Hope it helps!!!


Session State in ASP.Net October 5, 2010

Posted by fofo in asp.net, VB 2008, Visual Basic 10.0, Visual Studio 2008, Visual Studio 2010.
add a comment

In this post I will talk about ASP.Net State management. I will provide a hands on example with VS and VB.Net.

Before I go on with my example I would like to give a short introduction first.

Web applications are built on Hypertext Transfer Protocol (HTTP).  HTTP is a stateless protocol and each request to the server from the client is understood as an independent request.

ASP.NET provides a powerful way to store a user’s session specific data using the Session State which is accessible as long as the user’s session is alive.

At some point we might need to access complex information such as custom objects.Obviously we can’t persist them to cookies.In our application we could have strict security requirements that prevents us  from storing information about a client in view state or in a custom cookie. In cases like that, we must use the built-in session state facility.We can store any type of data in memory on the server. The information is protected, because it is never transmitted to the client, and it’s uniquely bound to a specific session. Every client that accesses
the application has a different session and a distinct collection of information. We could store in session state things such as the items in the current user’s shopping basket when the
user browses from one page to another.

One might ask, “What is the mechanism for session tracking?”
ASP.NET uses a unique 120-bit identifier and produces a unique value  that  evil people can’t reverse-engineer or “hack” the session ID a given client is using. This is the only piece of session-related information that is transmitted between the web server and the client.

The client presents the session ID, the what happens is that ASP.NET looks up the corresponding session, retrieves the objects stored and places them into a special collection so they can be accessed by our code.

The client must present the appropriate session ID with each request.

We can accomplish this in two ways:

Cookies: In this case, the session ID is transmitted in a special cookie (named
ASP.NET_SessionId), which ASP.NET creates automatically when the session collection is
Using URLs: In this case, the session ID is transmitted in a specially modified URL. This allows you to create applications that use session state with clients
that don’t support cookies.
Session state can slow down our application. It solves many of the problems associated with other forms of state management but places a heavy load on the server in terms of memory.
If we have hundreds or thousands of clients access the site then the performance will be very bad.
The last thing we want is to have an application that cannot scale gracefully.

I will be using VS 2010 Ultimate edition and VB.Net to create a simple asp.net application.
We will use in our next example session state to store several Car objects.

1) Launch Visual Studio 2010/2008/2005.Express edition will suffice.

2) Create a web site with an appropriate name.

3) Add a class file in your site and name it Car.vb. The code should be like this

Public Class Car
    Public Name As String
    Public Colour As String
    Public Cost As Double
    Public Sub New(ByVal name As String, _
    ByVal colour As String, ByVal cost As Double)
        Me.Name = name
        Me.Colour = Colour
        Me.Cost = cost
    End Sub
End Class

4) Add a listbox,2 label controls and a button in the default.aspx page. Name the listbox control as lstItems, the 2 labels as lblSessionInfo and lblCarInfo. Leave the default name for the button control.

5) In the Page_Load event handling routine type

If Me.IsPostBack = False Then
            Dim car1 As New Car("BMW", _
            "Blue", 32000)
            Dim car2 As New Car("VW Polo", _
            "Black", 18667)
            Dim car3 As New Car("Audi", _
            "Red", 30345)
            Dim car4 As New Car("Citroen", _
            "Gray", 9878)
            Session("mycar1") = car1
            Session("mycar2") = car2
            Session("mycar3") = car3
            Session("mycar4") = car4
        End If
        lblSessionInfo.Text = "Session ID: " & Session.SessionID
        lblSessionInfo.Text &= "<br />Number of Objects: "
        lblSessionInfo.Text &= Session.Count.ToString()
        lblSessionInfo.Text &= "<br />Mode: " & Session.Mode.ToString()
        lblSessionInfo.Text &= "<br />Is Cookieless: "
        lblSessionInfo.Text &= Session.IsCookieless.ToString()
        lblSessionInfo.Text &= "<br />Is New: "
        lblSessionInfo.Text &= Session.IsNewSession.ToString()
        lblSessionInfo.Text &= "<br />Timeout (minutes): "
        lblSessionInfo.Text &= Session.Timeout.ToString()

The Car objects are created the first time when the page is loaded, and they’re stored in
session state. The user can then choose from a list of car names. When a selection
is made, the corresponding object will be retrieved, and its information will be displayed.The code is very simple.

6) Double click on the button and in the event handling routine type

  If lstItems.SelectedIndex = -1 Then
            lblCarInfo.Text = "No item selected."
            Dim Key As String
            Key = "mycar" & _
        (lstItems.SelectedIndex + 1).ToString()
            Dim TheCar As Car = CType(Session(Key), Car)
            lblCarInfo.Text = "Name: " & TheCar.Name
            lblCarInfo.Text &= "<br />Color: "
            lblCarInfo.Text &= TheCar.Colour
            lblCarInfo.Text &= "<br />Cost: " & TheCar.Cost.ToString("c")

We retrieve the current Car object from Session like this

 Dim TheCar As Car = CType(Session(Key), Car)

7) Run your application and see the names of the Car objects stored in the Session listed in the ListBox control. You will also see when the page loads useful information about the Session.

Select one car name and hit the button. You will see whole information about the specific car object stored in the session state.

Email me if you want the source code.

Hope it helps!!!

VB 10.0 new features and Visual Studio 2010 IDE enhancements June 27, 2009

Posted by fofo in Visual Basic 10.0.
Tags: ,
add a comment

I have downloaded the .Net 4.0 version of the framework and VS 2010 beta version 1 from the microsoft site and I started looking at the new features, IDE e.t.c. Visual studio 2010 has some exciting features.

In this post I will try with a step by step example to highlight the new features of VB 10.0. I will also highlight some of the new enhancements on VS 2010 IDE. There are many new things in .net 4.0 and VS 2010 and certainly I will not cover everything in this post.

The first thing we must do is to create a sample application. I will create a console application. So just fire VS 2010 and from the available templates select a Console application.

Consume first mode

There is a new enhancement in the IntelliSense functionality. We have two alternatives for IntelliSense statement completion: standard mode and consume-first mode. This basically means that we consume classes,types,methods before we actually define them. Have a look at the picture below. In the Main() method I start to use this method without even declaring it first.

Sub Main()

addtwonums(3, 5)

End Sub


When I type the new method I receive a curly line from the compiler and I can realise that there is not a method with such a name.

If I hit CTRL + . a simple method structure is created for me.

Private Sub addtwonums(ByVal p1 As Integer, ByVal p2 As Integer)
Throw New NotImplementedException
End Sub

Now I can go on and finish my method.

This works equally well with classes I have not implemented yet. I have the declaration below in my Main() method.

Dim myperson As New Person

With the same mechanism, CTRL+. we can have a new Person.vb file created in the Solutions window.

Auto-Implemented Properties

Auto-implemented properties, which is a feature that was available with C# 3.0, provides us with a way to specify a property of a class without having to write code to Get and Set the property.If I start setting values to the myperson object, like the code below

Dim myperson As New Person

myperson.name = “Michael”
myperson.surname = “Owen”


I can create properties (without Get and Set)for the name,surname and a method stub for the Walk() method.So in my Person.vb file I have:

Class Person

Property name As String
Property surname As String
Sub Walk()
Throw New NotImplementedException
End Sub
End Class

Also note that you can With auto-implemented properties, a property, including a default value, can be declared in a single line. For example

Public Property Name As String = “John”

It is great seeing that Microsoft has decided to bring VB to the same level as C#. For the future of VB you can listen to this fantastic podcast where Joe Stagner talks with Lisa Feigenbaum from the .NET Managed Languages Group. Another great thing is that Αnders Hejlsberg is going to be in charge of the VB language as well. We know Anders is probably the most suitable person for driving VB to the future.

Collection Initialisers

Collection initialisers was a feature of C# 3.0 and basically it is a new syntax we can create a collection and populate it with an initial set of values. Let’s create a collection of List(Person). Each value that is supplied in the collection initializer is passed to the appropriate Add method of the collection.Inside my Main() method I can create

Dim people As New List(Of Person) From {
{New Person With {.name = “michael”, .surname = “owen”}},
{New Person With {.name = “kenny”, .surname = “daglish”}},
{New Person With {.name = “robbie”, .surname = “fowler”}}}

Please note that there is no “_”, underscore anymore.For more information on this topic see this video and this site.

Multiline Lambdas

In order to demonstrate this, let’s add another console application to our solution. Until VB 9.0 we had only inline lambda expressions. In VB 10.0 we have multiline lambdas. Consider the code below, we just have an array of temperatures and we want to find values greater than 30 degrees.

Dim temperatures(4) As String

temperatures(0) = 12
temperatures(1) = 23
temperatures(2) = 34
temperatures(3) = 45

Dim heightemperatures = temperatures.Where(

Return (temperature > 30)

End Function).ToList()


End Sub)

As you can see in this line bit of the code,

Dim heightemperatures = temperatures.Where(Function(temperature)
Return (temperature > 30)

End Function).ToList()

I am using a multiline lambda expression where I pass into the temperature.

In this part of the code I just display the temperatures on the console by using  Lambda statements (a new feature in vb 10.0) by using the Sub keyword.


End Sub)

For our array declaration we could use .Instead of typing this

Dim temperatures(4) As String

temperatures(0) = 12
temperatures(1) = 23
temperatures(2) = 34
temperatures(3) = 45

we could type this equivalent chunk of code

Dim temperatures = {12, 23, 34, 45}

This is a another new feature called array literals.

Parallel Support

We can execute parts of our program asynchronously-not in sequence using the Parallel object of the.Net 4.0 framework.

The first thing is to import the relevant namespace at the beginning of our code.

Imports System.Threading

To give you a simple example , we can write the following bit of code to output two strings in parallel on the console.Place the code inside the Main () routine.

Console.WriteLine(“My name”)
End Sub,
Console.WriteLine(“My surname”)
End Sub

We use the Invoke method to execute the tasks in parallel.

Run the code and see that the two strings outputted  simultaneously on the screen.For more information on Parallel computing have a look here.

Call Hierarchies

This is a brand new feature of the IDE in VS 2010. If you select a method and right click on it and select View Call Hierarchy so we can see in a niew window that appears titled “Call Hierarchy” which method calls (Calls to) this particular method and what methods this method calls(Calls from). See the picture below.

call hierarchies

Quick Symbol Search

In the code editor if you type CTRL + , the Navigate To window appears. You can enter the name of the type,variable you want and it will find all instances and by clicking on them you will navigate easily to them. Have a look at the picture below.

quick search

Highlighting References

We can highlight all instances of a particular of property , method e.t.c by simply clicking on it.

We can navigate between instances with CTRL+SHIFT+DOWN ARROW or CTRL+SHIFT+UP ARROW.

Enhancements to ASP.NET Multi-Targeting

In Visual Studio 2008, when we targeted a project for an earlier version of the .NET Framework most features of the development environment adapted to the targeted version. However, IntelliSense displayed language features that are available in the current version, and property windows displayed properties available in the current version. In Visual Studio 2010 only language features and properties available in the targeted version of the .NET Framework are shown.

Code Editor

The new Code Editor makes code easier to read. You can zoom in on text by pressing CTRL and scrolling with the mouse wheel.

Visual Studio Debugger

There are Breakpoint enhancements in VS 2010 such as

  • Searching in the Breakpoints window
  • Label breakpoints
  • Import and export breakpoints
  • String comparison for breakpoint conditions in native debugging

See the picture below.



The Chart Control

This control sports various chart types, including point, column, bar, area, doughnut and many more.It can be rendered in a 3D mode. For more information click here and here .

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl