Using ASP.NET Server-Side State Management

Except from storing states on the client, you can also store state data on the server. It is a good practice to store very sensitive information, like bank information, on the server instead of the client. You might also have states that are application wide and not client specific that you need to store on the server.

In ASP.NET there is two ways of storing state on the server. There is application state and session state.

Application State

Application state information is is global to the application and is available to all pages, regardless of the identity of the client. It is a form of application-level caching of data that can be used for every request. Application data is stored in an instance of the HttpApplicationState class that is provided through the Page.Application property. This class is a key-value dictionary, where each value is stored and accessed by its key. You can add and read from the application state from any page on the server.

Data stored in the Application object is not permanent; it will be lost any time the application is restarted. In particular, IIS might restart you ASP.NET application at any point. To read an write values to the Application object you can do the following.

image

Because the Application object is not thread-safe, you need to lock it when writing data to it. In the example above it is not that important but imagine if you have a visitors counter that adds and remove visitor count. Then if it is not Locked/Unlocked you might end up with a incorrect number of visitors.

Application Events

Application events can be used to handle events raised by the Application, the most common events are Application_Start, Application_End and Application_Error.

  • Application_Start This event is raised every time the application is started.
  • Application_End This event is raised every time the application ends.
  • Application_Error This event is raised when there is an unhandled error propagating up to the application-level.

Session State

Session state is a user-specific state that is stored by the server. It is available only to pages accessed by a single user during a visit to you site. It is very similar to use as the Application state, but it the data is unique to the user. Session state is lost if the user ends hos or her session (or time out).

Reading and Writing Session Data

You read and write data the Session object the same way you would to for the Application object. The Session object is a an instance of the HttpSessionState class and represents a key-value dictionary collection. The following examples shows how.

image

Unlike the application there is no need to lock the Session object because it is user-specific and the value is only changed for the current user making the request.

ASP.NET writes a cookie to the client to keep track of the session. This cookie is called ASP.NET_SessionId and contains a random 24-byte value. Requests made by the client submits this cookie to the server and ASP.NET maps the cookie’s value to the session on the server. However if the client browser do not support cookies, or have it turned off, ASP.NET allows you to enable cookieless session state.

Without cookies ASP.NET tracks sessions by using the URL, embedding the session ID in the URL after the application name and before any remaining file or virtual directory identifier. For example.

image

This behavior can be configured by using the SessionState element in the web.config.

image

You can also disable session state entirely by setting mode=”off” in the SessionState configuration.

image

If you want to disable session state for a specific page you can use the EnableSessionState in the @ page directive on the page.

Session Events

The Session object have two events that can be handled by the developer. This two are Session_Start and Session_End. Like Application events they you handle them by creating methods in the Global.asax file.

  • Session_Start Raised when a new user requests a page on you site and thus begins a new session.
  • Session_End Raised when a session is abandoned or expires. This event can be used to log information or free per-session resources. This event is only raised when using the InProc session mode, more on that later.

The following shows an example of using the Session events.

image

Storing Session State

ASP.NET provides five ways of storing the session state on the server-side.

  • InProc Stores session states in memory on the web server. This is the default mode. It offers much better performans then the other two but is limited to only using one server. So you can not use this in a web farm.
  • StateServer Stores session in a service called the ASP.NET State Service. This ensures that session state is preserved if the web application is restarted and also makes session state available to multiple servers in a web farm. When configuring Session state mode to StateServer, remember to always set the ASP.NET State Service to startup type Automatic.
    image
  • SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the web application is restarted and also makes session state available to multiple servers in a web farm. You will want to performance-test when using SQLServer mode.
  • Custom Enables you to specify a custom session stage storage provider. You also need to implement the custom storage provider.
  • Off Disables session state.

Configuring Session State Modes

You can configure the Session state mode in the sessionState element in your application’s web.config file. The following example shows the session state stored in a SQL server.

image

To use the SQLServer mode you need to create the ASPState database on the SQL server. To do this run the following command.

aspnet_regsql.exe -ssadd -sstype p -E
image

Then you have a new database in you SQL server.

image

Now the sessions state will be stored in the dbo.ASPStateTempSessions table.

image

Using ASP.NET Client-Side State Management to store information on the client

Almost every web application today need to store some information about a user to use later, for example a authentication token, theme name, or language. One thing to remember is not to store sensitive information on the client, like credit card numbers or bank information, even thou you can enable encryption on view state it is not as secure as storing that type of information on the server.

ASP.NET provides five ways of storing user information on the client.  The five ways are:

  • View state
  • Control state
  • Hidden fields
  • Cookies
  • Query string

View State

View state is a mechanism used in ASP.NET to store user-specific request and response data between page requests. The information in the view state is sent back to the user with the response of the page. When the user makes the next request the view state is returned with the request.

When the page is processed it pulls the view state data from the request and use it reset properties on the page and controls. View state is always enabled as a part on every ASP.NET page. The Page.ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This object is of the type StateBag.
When a page is requested by the user the current state of the page and it’s controls is hashed into a string and saved in the page as an HTML hidden field called __VIEWSTATE. If data is to long for a single field (based on the value of the Page.MaxPageStateFieldLength property), ASP.NET performs a view state chunking to split it across multiple hidden fields. In the HTML response the view state hidden field looks like this.

image

As you can se the value in __VIEWSTATE is hashed, compressed and encoded for Unicode implimentations, this is to be a bit more secure and provide better performance.

When using view state you need to consider the security in using it. As said in the previous sentence, the view state is hashed, it also includes a message authentication code (MAC). This MAC is used by ASP.NET to determine if the view state data sent by the client have been tampered with. Do not mistake this as fully encrypted data, it is not. But for the most part it helps ensure security in many situations.
If you do store sensitive data in the view state, you would want to enable encryption on the view state. To do so you use the Page.ViewStateEncryptionMode property. This will secure the view state but also have a big impact on performance on the server, both CPU for encryption/decryption and bandwidth for the server and client because the view state sent between the two is much bigger.

To enable view state on the entire site you can set the following in the web.config.

image

If you want to set encryption on single pages you can do this in the @ page directive on each page.

image

Disabling View State Date 
View state is enabled by default for all the controls in your pages. This includes controls such as Literal and Label, that you might never need to include as part of the view state. It is a best practice to have view state enabled on as few controls as possible, this is because it minimize the amount of data sent back and forth between the client and server.

You can control the view state on the page level by enabling and disabling Page.EnableViewState and Page.ViewStateMode, for controls you can use Control.EnableViewState and Control.ViewStateMode.

The ViewStateMode is new in .NET Framework 4. The ViewStateMode property of a page or control has an effect only if EnableViewState is true. By default Page.EnableViewState is Enabled and Control.ViewStateMode is Inherited, which causes the control to use the page’s view state. There for if you do not change ViewStateMode, EnableViewState controls it entirely.

If you set EnableViewState to false, view state is disabled for the page or control, regardles of the value of ViewStateMode. If EnableViewState is set to true, you can set ViewStateMode to disable view state. Because ViewStateMode can inherit the page’s setting, you should always leave EnableViewState set to true and use ViewStateMode to control view state.

To disable view state for all controls on a page, simply set Page.ViewStateMode to Disabled. You can then selectively re-enable view state for specific controls by setting each control’s ViewStateMode property to Enable. Essentially, ViewStateMode allows you to opt in to view state, whereas EnableViewState requires you to opt out.

You can also disable view state for the entire website by setting enableViewState in the web.config file.

image

Custom View State
You can use the this.ViewState dictionary collection to read and write your own view state data. Adding data to the view state in this way is a efficient and secure way of storing data between requests. The view state is only stored for the same page, so this method of storing user data is only usable for storing temporary data for a single page. Below is a example of reading and writing your own view state data.

image

The result of the example looks like this;

image

and after the Submit button was clicked;

image

 

Hidden Fields

Hidden fields in HTML are simply input fields that are embedded in the page’s HTML, not displayed for the user. ASP.NET provides a control that lets you create your own custom hidden fields in a manner similar to how you create other controls. The HiddenField control allows you to store a store data in its Value property. You can add a HiddenField control to you page by using the following code in you markup.

image

To programmatically set the Value property of the HiddenField1 you do the following.

image

When viewing the HTML source of the page this is what you see.

image

What differentiate hidden fields from view state is that it is not encrypted, hashed or chunked and the user can view and modify the value.

 

Cookies

A cookie is a small amount of data that you write to the client to be stored and then passed with requests to your site. You write persistent cookies to a text file on the client machine. These cookies are meant to survive even if the user shuts down the browser and reopens it at a later time. You can also write temporary cookies that survive as long as the browser not shuts down because they are stored in the browsers memory. These cookies are used only during the current web session.

The mechanism that client and server use to create cookies is as follows.

  1. The client requests a page.
  2. The server responds with the HTML and a cookie
  3. The client request another page, and also sends the cookie in the request.

Cookies are a simple and reliable way of storing data on the client. However the client can delete a cookie at any time. No matter what expiration date the server have set.

Reading and Writing Cookies
A web application creates a cookie by sending it to the client as a header in an HTTP response. The following example shows how to read and write a cookie.

image

This checks to see if the cookie object exists in the Page.Request.Cookeis collection, if it exists, it writes the value otherwise it writes First time visitor. Then it sets the value of the lastVisit cookie, and set the Expires property to the next day.
If you do not set the Expires property the cookie is stored in the client’s browser memory and is removed when the browser shuts down. You can also create a cookie by using the Page.Response.Cookies.Add() method, which takes a HttpCookie object as a argument.

image

By default a browser do not send a cookie for a host to a website with a different host, this is a security feature. You also have control over the scope of the cookies. You can limit it to a specific directory on you web server or expand the scope to the entire domain. The scope of the cookie determines which pages have access to the cookie. To limit the scope of a cookie to a directory you specify the Path property of the HttpCookie class. For example,

image

This will limit the cookie so that it is only sent with the request in pages in the /MyApplication directory on the server.

To expand the scope of a cookie to the entire domain you specify the Domain property of the HttpCookie class.

image

Setting the Domain property will cause the cookie to be sent to all pages of the domain. It will also be sent with request to pages hosted on any subdomain of the domain specify. In the previous example that would mean the cookie would also be sent to www.frejnorling.com, private.frejnorling.com and so on.

Storing Multiple Values in a Single Cookie
The size of your cookie is dependent on the browser. Each cookie can be up to 4 KB in length. In addition, you can typically store up to 20 cookies per site. If you need to work around the 20-cookie limit, ASP.NET let you store multiple values in a single cookie by setting the cookie’s name and its key value. The following shows a example.

image

As you can se the property Expires is set just once for all values, this is because all values are stored in a single cookie on the client. When the client requests a page the server sends the following Set-Cookie header in the response back.

image

This will then be sent with every request made from the client, and the server will parse the string and populate the HttpCookieCollection accordingly.

You can not delete a cookie from the client, but you can change its Expires property to null. That will make the browser delete the cookie from the client when the browser shuts down.

 

Query Strings

So query strings, there is not that much to say about them that have not been said before. But you give you a short summery of them anyway.

Query strings are set off from the URL with a question mark (?) followed by the query string term, or parameter name, an equal sign (=) and the value. You can append multiple query string parameters by using the ampersand (&). A typical query string might look like this

http://www.frejnorling.com?lang=en&theme=blue&q=hello+world

Values sent to your page via query string can be retrived on the server through the Page.Request.QueryString property.
To access the lang parameter in the example URL above you write the following.

Request.QueryString[“lang”];

There is a browser length limitation on query string, the maximum length of a query string is 2083 characters long. But if you want to send a URL link in a mail, you would use a maximum of 70 characters for the URL.

To add a query string value to your site, you need to manually append it to the hyperlink.

The ASP.NET Application Life Cycle, Page Life Cycle and Control Life Cycle

On a ASP.NET application running on IIS 7.5 the life cycle of your application looks like the following list.

  1. A user first makes a request for a page in you site.
  2. The request is routed to the processing pipeline, which forwards it to the ASP.NET runtime.
  3. The ASP.NET runtime creates an instance of the ApplicationManager class. The ApplicationManager instance represents the Microsoft .NET Framework domain that will be used to execute requests for you application. An application domain isolates global variables from other applications and allows each applications to load and unload separately as required.
  4. After the application domain has been created, an instance of the HostingEncironment class Is created. This class provides access to items inside the hosting environment, such as directory folders.
  5. ASP.NET creates instances of the core objects that will be used to process the request. This includes HttpContext, HttpRequest and HttpResponse objects.
  6. ASP.NET creates an instance of the HttpApplication class (or an instance is reused). This class is also the base class for a site’s Global.asax file. You can use this class to trap events that happen when your application starts or stops. When ASP.NET creates an instance of HttpApplication, it also creates the modules configured for the application, such as the SessionStateModule.
  7. Finally, ASP.NET processes requests through the HttpApplication pipeline. This pipeline also includes a set of events for validating requests, mapping URLs, accessing the cache, and more. These events are of interests to developers who want to extend the Application class.

Responding to Application Events

As said in the last item in the previous list, the HttpApplication class provides a several events you can handle to perform actions when ASP.NET raises certain events on the application level, the events wont work on a per-user level.

The following is some the most common events used by developers.

  • Application_Start  The Start event is raised when you application is started by IIS (usually as the result of a user request). This event is useful for initializing variables that are scoped at the application level.
  • Application_End  The End event is raised when your application stops or shuts down. This event is useful if you need to free application-level resources or perform some sort of logging.
  • Application_Error  The Error event is raised when an unhandled error occurs and rises up to the application scope. You should use this event to perform worst-case, catch-all error logging.
  • Application_LogRequest  The LogRequest event is raised when a request has been made to the application. You can use this event to write custom information regarding a request.
  • Application_PostLogRequest  The PostLogRequest event is raised after the logging of a request has completed.

Other events include Application_BeginRequest, Application_EndRequest, ResolveRequestCahce, and many others.

You can respond to these events by adding event handling methods in your Global.asax file.

image

The previous code tracks the number of requests made to the website, and store it in the global Application object.

The Page Life Cycle

Besides from the Applications life cycle there is also the Page life cycle for each page in a website. The following is a list of the page life cycle.

  1. The user makes a request to for a page.
  2. On the webserver, the ASP.NET compile the page (if necessary), or pull from cache (if available).
  3. (Start) Set request and response objects. Determine IsPostBack.
  4. (Init) Initialize page controls (but not their properties). Apply page theme.
  5. (Load) If PostBack, load control properties from view state.
  6. (Validation) Validate page and validator controls
  7. Call control event handlers (for PostBack request).
  8. (Rendering) Save view state. Render controls and display the page.
  9. (Unload) Unload request and response objects. Perform cleanup. Page is ready to be discarded. Return response to user.

Responding to Page Events

As with the Application events, the page raises various events through its stages. This events can be handled by the developer. It is important to know the order in which events are called, so that your code runs in the proper sequence. The following table shows a order list of the most common events of a page.

Event Descrition
PreInt This is the first real event you might handle for a page. You usually use this event only if you need to set values such as master page or theme.
This event is also useful when you are working with dynamically created controls for a page without a master page. You should create controls inside this event. If you have a master page or theme, create controls in the Init event.
Init This event fires after each control has been initialized. You can use this event to change initialization values for controls.
If you need dynamically added controls to a content page, use this event.
InitComplete This event is raised after all initializations of a page and its controls have been completed.
PreLoad This event fires before view state has been loaded for the page and its controls and before postback processing. This event is useful when you need to write code after the page is initialized but before the control view state has been re-established.
Load The page is table at this time; it has been initialized and its state has been reconstructed. Code inside the page load event usually checks for postback and then sets control properties appropriately.
The page’s load event is called first. Then the load event for each child control is called in turn (and then the load events for their child controls, if any).
Control (postback) events ASP.NET now calls any events on the page or its controls that caused the postback to occur. This might be a button’s click event, or a drop down list’s SelectedIndexChanged event.
LoadComplete At this point all controls are loaded. If you need to do additional processing at this time, you can do so here.
PreRender This event allows final changes to the page or its control. It takes place after all regular postback events have taken place. This event takes place before ViewState is saved, so any changes made here are saved.
SaveStateComplete Prior to this event, the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored. This event is useful if you need to write processing that requires the view state to be set.
Render This is a method of the page object and its controls (not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output.
The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and scripts that are necessary to properly display a control on the browser.
This method is useful if you are writing your own custom control. You override this method to control output for the control.
Unload This event is used for cleanup code. You can use it to manually release resources, a process that is rarely necessary.

 

Dynamically add controls to a page

To dynamically add controls to a page you do this in the Page.PreInit event (when not using themes or master pages) or in Page.Init when using themes or master pages. The following example adds a textbox and a button and also handle the button Click event.

image

And the result looks like this.

image

After submit!

image

Control Life Cycles Events

Controls such as Button and Textbox share a common life cycle with the Page class. Each server control, including Init, Load, Render, and Unload, goes through the same life cycle as a page.
A control’s event is raised during the same event for its parent, so when a page executes the load event, all controls load event is also executed. And their child control executes the load event and so on.

Controls in ASP.NET have default events that are usually handled by the developer. For example, the Page object’s default event is Load, and the Button object’s default event is the Click event.

To handle a Page or Control event all you need to do is crate a Event Handle Method in the code behind file (C#). To do this you write a new method and set the method signature to comply to the event signature of the event. Like the following method to handle the Unload event for a button.

image

To programmatically add this event handler to the button you add a new EventHandler object to the Unload property of the button.

image

You can also set the event handler in the ASP.NET markup code like the following example.

image

 

Controlling the Automatic Postback

A control like the Button always cause a postback to the server when clicked, but a control like DropDownList do not cause a postback when a user select a choise.

To make a control do a postback on certain events you need to add the AutoPostBack=”true”

image

Now you need to add a event handler for the SelectedIndexChange event caused by the drop down list.

image

Then add a event handler to the SelecteIndexChanged property for the drop down list.

image

Now you can automatically handle selections on the drop down list in a method.

Configure IIS 7.5 to manage ASP.NET 4.0 web pages

After installing .NET Framework 4.0 on a machine there is a few configuration changes you need to do to IIS in order to get a ASP.NET 4.0 page running.

First set the Application pool to run in ASP.NET v4.0 “mode”.

image

Then you need to allow ASP.NET v4.0.x to run. This is done in the ISAPI and CGI Restrictions found on the server level.

image

Select the same version you have installed on your server, (32 bit or 64 bit). And change to Allowed. If this is not done you will get the following response from the server.

HTTP Error 404.2 – Not Found

The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

When this small configurations is in place you are all good to browse your ASP.NET 4.0 website.

How to use ASP.NET Themes

If you have read my previous post on master pages to handle different styles of a webpage you might thing that was not a good way of handling different styles for different users or devices, and guess what, you are right. There is a “better” way, or another way of doing the same thing, say hello to Themes.

What is Themes?

A theme is a way of controlling the look and feel of a webpage. You can have many themes on you website and apply them for different users or devices. A theme in ASP.NET can control what Cascading Style Sheet (CSS) is added in the <head> tag, what styling properties each controls get and what images to be showed for each theme.

Ok I get it, show me how!

Implementing themes is very easy. All themes is located in the special ASP.NET folder App_Themes. And each theme is placed in a sub-folder of the App_Themes folder i.e. /App_Themes/Red, /App_Themes/Blue for a red and blue theme.

It will look like the following,

image

In those folders (Red and Blue) you can add .skin files (a skin file is a text file with the markup for a ASP.NET control that will be used as a template for controls in the ASP.NET)

image

It is common to create a .skin file for each control you want to “theme”.

image

This two textbox controls are just templates of what the textbox controls will look like in the ASPX pages.
Notice the second line, there is a property skinid when applying a skinid property in the template .skin file, only controls with the same skinid will get the theme from that template.

The ASPX file have this two controls.

image

The result of this template looks like this.

image

The first textbox get the looks from the first line in the .skin file while the second have the SkinID property set to blueTextbox and therefor get the properties form the second line in the .skin file.

One thing to keep in mind is that the first line in the .skin file will apply to ALL textboxes that on all pages that implement the template.

What about style?

Implementing different style sheets for each theme is even easier. All you have to do is add a .css file in the theme folder, name it to whatever you want and when that theme is selected for a page it will automatically add a link to that css file in the <head> tag.

image

<head>
<title></title>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="App_Themes/Blue/blue.css" type="text/css" rel="stylesheet" />
<link href="App_Themes/Blue/style.css" type="text/css" rel="stylesheet" />
</head>

The Site.css is added in the master page in this case, and both blue.css and style.css is added from the theme folder. Very easy to do.

You said different images to?

Yes I did, when you want to specify different images to use for different themes, you do it the same way you do for controls.
Create a new .skin file in App_Themes/Blue folder, name it logo.skin or something else, type the following code in it.

image

This will set the ImageUrl property on all Images controls using skinID=”logo” to “~/App_Themes/Blue/logo_blue.jpg”.

To the same for the Red theme.
image

Now you just add a Image control to the page or master page, set the skinid to “logo” and your logo will change depending on the active theme.

image

 

Well how do I set the theme on the page then?

You can either set the theme for all pages in the web.config file or in the @ Page directive on each file.

To set a theme in the web.config file just add the following tag in the <pages theme="Red"></pages> in the <system.web> tag.

To set the theme on the page level add Theme="Blue" in the @ Page directive.

Themes have a priority among themselves for overriding each other, the priority goes as follows (first to last):

  1. Theme attributes in the @ Page directive
  2. <pages Theme=”themeName”> elements in <system.web> section of a Web.config file.
  3. Local control attributes
  4. StyleSheetTheme attributes in the @ Page directive
  5. <pages StyleSheetTheme =”themeName”> elements in <system.web> section of a Web.config file.

The difference between using Theme and StyleSheetTheme is that StyleSheetTheme can be overriden by local control attributes, this is true for both @ Page directive and when the theme is specified in the pages element in Web.config.

Apply a theme programmatically, just set the Page.Theme or Page.StyleSheetTheme to the theme name.

image

image

Now you are all set to implement themes in your website.

A programmers guide to Caching in ASP.NET

 

The cache object

You can use the System.Web.Caching.Cache object witch is a application wide object for storing data in memory, this object is a Key/Value collection and is used the same way as i.e. the Session object in the way you store data inside it. You can store any type of objects in the Cache as long as the objects can be serializable. When returning values form the cache object always check for the item not to be null, if the item is null then retrieve the data from its original source. Also remember to cast the value to its type when you retrieve the data.

The following is a simple example of storing a DateTime object in the Cache object.

image

Although the previous example is fine you can use the Cache objects Insert method to access much more sophisticated functionality. The following is a list of parameters for the Insert method

key This is the name (string) that you’ll use to access the cached object in the Cache collection.
value The data (object) you want to cache.
dependencies A CacheDependency object identifies a file or a key to another item in the cache. So that a change to a file or related item is changed, the cache will be removed. This is useful for i.e. a file cache, when the file changes the cache is removed.
absoluteExpiration The time (DateTime) at which the object should be removed from the cache.
slidingExpiration The time (TimeSpan) for how long a item will remain in the cache object, i.e. 10 seconds, if a user have not accessed the item in 10 seconds the item is removed, otherwise it will restart the time and add 10 more seconds.
priority

This is a CacheItemPriority enumeration value that you can use to determine which items are removed first when memory starts to run low (scavening). The lowest priority items will be removed first.

  1. Low
  2. BelowNormal
  3. Normal (default)
  4. AboveNormal
  5. High
  6. NotRemovable
onRemoveCallback This is an event handler that is called when the object is removed from the cache, This can be null if you don’t want to specify a callback method.

Now lets do the example form above but this time use the Insert method.

image

The true power of the Insert method comes when you add dependencies to your cached item.

Defining a Cache Dependency

A cache dependency lings a cached item to something else such as a file or another item in the cache collection. ASP.NET then handle the dependencies and removes cached items if the dependent items chances, such as a file change.
This is an example of a Cache object dependent on a file.

Add a text file to your project:

image

In the Page_Load method there is two Cache.Insert one without dependency and one with file dependency.

image

The TextFile.txt just contains the following text:

This is a cached text form a file!

When viewing the page it will look like the following image.

image

The first line comes from the Cache[“FileCache”] item which have no dependency to the file, and the other line is from Cache[“FileCacheDependent”] which does have a specified dependency to the file TextFile.txt. Now what happens when I change the text in the TextFile.txt. This is the result:

image

Notice the second line where it now says: The text has now changed! 
The Cache[“FileCacheDependent”] where automatically removed from the cache because the file changed.

There is also possible to add multiple dependencies for a cached item.
The following example create a new cache named DependentCacheItem that will be removed after 15 seconds if no user access it. Then two System.Web.Caching.CacheDependency objects is created, dep1 and dep2, where the first is a dependency on the file TextFile.txt used earlier, the second is a dependency for the cache item named DependentCacheItem created first. To manage all dependencies you create a object of type System.Web.Caching.AggregateCacheDependency, then add the two CacheDependency objects (dep1 and dep2) by using the AggregateCacheDependency.Add method.

So far we just created the objects for dependencies, after that you create the actual Cache item to use the dependencies, in this example it has the key CacheMultiDependent, Then in the Cache.Insert method specify the key parameter, the value parameter, and the AggregateCacheDependency object. And now the Cache item will be removed after 15 seconds if no user have accessed Cache[“DependendCacheItem”] or the text file TextFile.txt is changed.

image

 

The difference between Absolute Cache Expiration and Sliding Cache Expiration

When create a new cache item you can specify the expiration. In other words how the cache will expire. Two ways of doing so is the use of absolute or sliding expiration. You can use either absolute expiration or sliding expiration or both on the same cache item.

Absolute expiration
Absolute expiration is set as a DateTime object and specify when the cache item will expire.
To set absolute expiration you provide a DateTime object as the forth parameter in the Cache.Insert method.image

The code above shows a absolute expiration cache item. Notice the fifth parameter which is set to System.Web.Caching.Cache.NoSlidingExpiration this is required when not specifying a sliding expiration parameter.

Sliding expiration
Sliding expiration is set as a TimeSpan object and specify for how long the cache item will remain in memory when no user accesses it. When a user accesses the cache item, the time is reset and starts over.

image

It is possible that heavy usage will result in an item never being removed from the cache, preventing updates to the original object from being accessed. This situation can be avoided by specifying a absolute expiration in addition to a sliding expiration.

Using output caching in ASP.NET pages

To set caching on a page in ASP.NET you need to add a @ OutputCache directive to the top of a page’s markup. There are quite a few attributes that can be used to control how the output caching should work in terms of duration and variations of pages. The following table explains the available attributes.

Duration The number of seconds to cache the page. This is the only required parameter.
Location

One of the OutputCacheLocation enumeration values:

  • Any (default)
  • Client
  • Downstream
  • Server
  • None
  • ServerAndClient

This attribute can not be used in user controls (.ASCX files).

CacheProfile The name of the cache setting to associate with the page. You can create one or more CacheProfile in the Web.config file, and make different pages use different CacheProfiles. This attribute can not be used in user controls (.ASCX files).
NoStore A boolean value that determines whether to prevent secondary storage of sensitive information. This attribute can not be used in user controls (.ASCX files).
Shared A boolean value that determines whether user control output can be shared with multiple pages, default is false. This attribute can not be used in ASP.NET pages (.ASPX files).
VaryByParam

A semicolon-sparated list of strings used to vary the output cache. By default, these strings correspnd to a query string value sent with Get method attributes, or a parameter sent by using the Post method. When this attribute is set to multiple parameters, the output cache contains a different version of the requested document for each combination of the specified parameters. Possible values include the following;

  • none
  • *
  • i.e. search (this is a example of the following url, http://example.com?search=test, where the output cache would have a different version for each value in the search query string).
  • i.e search;category (this is a example of the following url, http://example.com?search=test&category, where the output cache would have a different version for each value in the search and category query string).
  • i.e. a ASP.NET-generated control name like, ctl00$MainContent$SearchTextbox, or ctl00$MainContent$CategoryDropDownList.

Either this or VaryByControls is required or a parser error occurs. If you do not want to vary by parameter, then set it to none.

VaryByControl A semicolon-separated list of strings used to vary a user control’s output cache. This strings represent the ID property values of ASP.NET server controls declared in the user control.
SqlDependency A string value that identifies a set of database and table name pairs that a page or control’s output cache depends on. Note that the SqlCacheDependency class monitors the table in a database that the output cache depends on, so that when items in a table are updated, those items are removed from the cache when using table-based polling. When using notifications (in Microsoft SQL Server 2005) with the value CommandNotification, ultimately a SqlDependency class is used to register for query notifications with the SQL Server 2005 server.
VaryByCustom Any text that represents custom output caching requirements. If this attribute is given a value of browser, the cache is varied by browser name and major version information, If a custom string is entered, you must override the GetVaryByCustomString method in you application’s Global.asax file.
VaryByHeader A semicolon.separated list of HTTP header used to vary the output cache. When this attribute is set to multiple headers, the output cache contains a different version of the requested document for each combination of specified headers.

 

To add output caching to a .ASPX page or user control add the @ OutputCache directive in the top of the page.

image

This will cache the page for 15 seconds regardless of the parameters passed to the page.

An alternative way of doing a partial page cache is to use a ASP.NET Control called Substitution, it is like a Label control but you can use it to load dynamic data to a cached page:
image

This control have one important method, MethodName which takes a string representing another method. In this example GetCurrentDateTime.

image

The GetCurrentDateTime is a simple method that takes a HttpContext object as a parameter and returns a string, which is the dynamic data inserted into the cached page.

image

Programmatically set Caching for single pages

To set output caching at runtime you can use the Response.Cache object. This object has limited functionality but can be useful in some situations. The methods that can be used is the following;

  • Response.Cache.SetExpires Use this method to specify a DateTime object that will expire the cache.
  • Response.Cache.SetCacheability Use this method to specify an HttpCacheability enumeration value, please see MSDN for all possibly values.
  • HttpCacheability.Public enables caching at both client and server
  • HttpCacheability.Server enables caching at the server only.
  • Response.Cache.SetValidUntilExpires Pass this method a true value to configure the cache to ignore cache-invalidation headers.
  • Let’s look at how we can invalidate a cached page. The following example shows how to programmatically invalidate a cached page.

    Add the following to your .ASPX page so it will be cached for 15 seconds, on all variations of query strings.

    image

    In the Page.Load event handler we add a new HttpCacheValidateHander to the Response.Cache.AddValidationCallback method. The first parameter of the HttpCacheValidateHander pass a object with your validation method for validation if the cache is valid or not.

    image

    The method to validate a cached page can look however as long as the signature of the method remains the same and the referenced HttpValidationStatus is set to one of the following three;

    • HttpValidationStatus.Invalid the cache is invalid, and the page is dynamically generated, this newly generated page is stored in the cache replacing the earlier cached version.
    • HttpValidationStatus.IgnoreThisRequest This cases the current page request to be dynamically generated without invalidating the  previously cached version of the page. The dynamically generated page output is not cached, and future requests might recive the previously cached output.
    • HttpValidationStatus.Valid Cases ASP.NET to return the cached page.

    image

    You can also programmatically create a cache dependency when using the Response.Cache object. To do so use one of the following methods;

    • Response.AddCacheDependency creates a dependency on a CacheDependency object.
    • Response.AddCacheItemDependency and Response.AddCacheItemDependencies creates a dependency to one or more other items in the cache.
    • Response.AddFileDependency and Response.AddFileDependencies These makes the validity of a cache response dependent on one or more files.

    Configure Caching for en Entire Application

    You can create caching profiles in the Web.config files to control the caching of the entire application from one place. This is a good way to manage many different caching properties for different pages and user controls. In the <system.web> element you can create outputCacheProfiles like the following example.

    image

    Then you can use this caching profiles on different pages.

    image

    Master pages in ASP.NET – Programmatically change master page

    Read my other posts on Master pages in ASP.NET

    If you use a master page in you website (most of us do), and also want to let the users select different themes or maybe you want a iPhone, iPad, Android or Windows Phone 7 (maybe not Win Phone 7), but the rest, version of your site. One way of doing this is to change the master page based on some external input, may it be a user selected theme from a drop down list or the User-Agent from the request.

    Change the master page please! – Said the user

    This is really simple to do, just do the following.

    First create two master pages, in this example I have Light and Dark. Edit each master page to fit your needs, i.e the background or layout.

    image

    Light.Master is the the default master page for all pages.

    Then create a drop down list with two options, light and dark, this is the themes (a.k.a master pages) of the site the user can choose between, the light version is the default master page.

    image

    The ASPX file looks like this, where the drpMaster_SelectedIndexChanged is the method that will execute after the selection of the “theme”.

    image

    To catch the post back event created by the drop down list, use this code in the code-behind file of the page.

    image

    The reason why we do not change the Page.MasterPageFile property in this method is that it will generate a error, telling us  that the MasterPageFile property can only be set in or before the Page_PreInit event. Therefor we need to store the value in a Session object and use it later. So we store it and redirect the browser to the current URL.

    In the Page_PreInit event we just checks that the Session object is not null and if it is not, we set the Page.MasterPageFile property accordingly.

    image

    When dark is selected the page changes to this.

    image

     

    Change the master page please! /Mobile device

    If you instead want to redirect the user to a mobile device automatically you can check the Request.Browser.IsMobileDevice property to see if the user is viewing your site with a mobile device.

    image

     

    You would also want to check the Session["master"] and only do a redirect if it is not set to Mobile otherwise you would get a endless redirect loop. (Thanks Jeremy)

    You can also use the Browser object to further fine grain the redirection, i.e a version for iPhone and a version for Andriod.

    8 steps to become a professional software developer

    So you want to become a professional developer? In this blog post I have put together a list of 8 things all professional developers should know.

    1. The syntax

    Start learning the syntax of the language you want to be a professional in. You need to have comprehensive knowledge about the programming language syntax . It is not enough to just know IF and For Loops. That won’t make you a new Jeff Atwoods or Jon Skeet. Spend time to really understand the syntax well, how you can use it to accomplish your will.

    Learn how you work with objects and types, how inheritance is used in the language. Generics (if supported) is also important to know and understand. You have also arrays and collections, operators, casts, delegates, lambdas (if supported) and events. Other important parts of the syntax is string manipulation e.g. regular expressions and how you can use regular expression patterns to manipulate strings. You have memory management (and pointers), errors and exceptions.

    Learn the tricks professional software developers use in their work. There is a lot of “shortcuts” in the syntax. For example, the one-line if statement in some languages, (expression) ? “value if true” : “value if false”. There is a lot to the syntax. Learn it well!

    2. The framework

    Equally important as the syntax is the framework on top of the syntax. It is in the framework the logic happens, the syntax itself is just instructions of how to use the framework. For example the framework lets you read and write files, manipulate images, using network sockets, messaging and much more. A good understanding of the framework you use is as important as knowing the syntax, they go hand in hand. Without the framework there is not much you can do with the syntax.

    The whole framework is a very big chunk of knowledge to put in your brain, so it might be a good idée to split it up a bit. Of course you need good knowledge about the core classes and types that is used or inherited throughout the framework  but for example, if you are a web developer, focus on the namespaces (classes / types) that is most targeted against web development. I do not say you only need that part of the framework, but you might not need to know every details of the image manipulation namespace (classes / types) if all you do is developing dynamic web pages (this argument of course rest upon the fact that you do not develop a web page that manipulates images.). You are smart, you get the point I’m trying to make.

    Also remember there is most likely a good documentation some poor developer or technical writer have posted somewhere on the internet just sitting waiting for your eyes to read. Use it!

    3. The IDE

    So you have a solid understanding of the syntax of your programming language and know a lot about the possibilities and limitations of the framework. To make it easier to craft your software, you need to have a good IDE (Integrated Development Environment). An IDE is like a lengthening of your fingers, you should know how to use it even if you are asleep. Know the hot-keys for faster and easier access to functions. Know the limitations of the IDE, where you need to install a plugin to the IDE, or use external tools, maybe even build you own tools for the job. There are a lot of good IDEs out there, e.g. Microsoft offers Visual Studio (and WebMatrix for simple ASP.NET development) for their .NET Framework, while you can use e.g. Eclipse for Java, PHP and C/C++ and other languages. Of course there is more to choose from. Use the one that fits you, and learn it well.

    4. Design patterns

    Design patterns is a programming pattern you use to solve common programming problems. There is three categories of design patterns, creational patterns, structural patterns, behavioral patterns. You also have a forth category, architectural design pattern that may be applied at the architecture level of the software. When you work on a project there might be problem you comes across that other, smarter (just kidding, you are the smartest, that’s why you read this post?), people have solved before you. Why would you invent the wheel again?

    So if you are going to to put the title professional developer under your name, you must be able to back it up with some design pattern knowledge. Of course you can not solve all problems just by throwing design patterns at the it. But you can solve a lot of them.

    5. Testing & Debugging

    Testing and debugging is a very important part of todays (and yesterdays) software development. With the tools available for us today it has become easy to do the same testing that where only done by enterprise development teams just a couple of years ago. Also with new programming methods using Agile practices like Scrum and XP it is now very important to have good test in place if you should be able to ship software fast, without compromising on quality. But what do you need to know about testing and debugging to become a professional developer?

    The first and most important (all testing is important but it’s a nice way of starting a sentence) is unit testing. This means you write a test to every method and function you develop. So when you need to change some part of the system you can validate that the software is not broken by running your unit tests.

    The second thing that is important is Integration testing. This is the part you test after all your unit tests have validated. This is where you combine you modules and test the integration between them.

    Then you need to know about System testing, this is the part where you test the whole system. If your application also have a GUI (Graphical User Interface) it would be a good to know how to test the GUI to.

    When all your testing have validated and a user reports a bug, you need to be able to debug your software. And because you have read 3. The IDE you know how to debug software with the help of your IDE. Learn it, use it!

    6. Source control & Deployment

    You are not a professional developer if you x-copy you source code to production and hope for the best. Or as Scott Hanselman and Rob Connery do it, using Dropbox to do some pair programming (delete the last, they are professionals, that’s what they say at least). You might consider yourself a pragmatic programmer that solves the damn problem, but there is better ways of solving this damn problem. A professional developer uses source control (also known as revision control or version control) to store the source of your development projects. When working in development teams (all developers in development teams are professionals right?) it is essential to have a centralized storage for the projects source. Then everybody in the team have access to the latest source and can check in changes to the source code. Even if you are a single developer you should use a source control system. It is also easy to keep backups of your source.  “The cat ate the source code!” is not a valid excuse to a program manager or customer.

    With todays source code system you have a lot of built in support for deployment, you can have daily or weekly builds automatically deploy to a staging server and reports on the output result of those build emailed to you. This is a good way of having control over your projects. There is a lot of good functionality in a source code system and you need to know how to utilize them.

    7. Infrastructure

    Are you developing software in vacuum with the purpose of never being deployed and run on hardware? If you do, you can jump this, to the others, keep reading. All professional developers should have a good understanding of the hardware and operation system the application will run on. For example, if you are a professional developer developing a website in ASP.NET would you thing you would be a better programmer if you know anything about Windows Server, IIS, HTTP and DNS? I bet you would. Maybe your network communication software would perform better and more stable if you know about how the TCP/IP works? It might even be required to get it running. Know your infrastructure!

    8. Documentation

    For many developers this might sound boring and time consuming. And yes it is, if you don’t know how to do it! Starting with a blank Word document is never a productive way of get things started. There is basically five types of documentation for software.

    • Requirements -  Statements that identify attributes, capabilities, characteristics, or qualities of a system. This is the foundation for what shall be or has been implemented.
    • Architecture/Design – Overview of software’s. Including relations to an environment and construction principles to be used in design of of software components.
    • Technical – Documentation of code, algorithms, interfaces, and APIs
    • End User – Manuals for the end-user, system administrators and support staff.
    • Marketing – How to market the product and analysis of the market demand.

    A professional developer might not need to master all the five types of documentation but one should know how to write Technical documentation and Architecture/Design documentation. Most IDEs can help with documentation, e.g. extracting code comment and class header comments and parse them into a readable document. Using the IDE and other tools, documentation do not need to be a boring, time consuming necessity, but instead a great way to be a more professional developer, automate the documentation as much as you can. Then the documentation will “come for free”.

     

    This 8 things is what I believe all professional software developers should know. You might think different, and if you do, please let me know in the comments below, I might argue against you or update this post. Just comment.

    One more thing, it might be the single most important thing, that all professional developer needs is experience.

    Master pages in ASP.NET – Accessing master page properties, methods and controls from the content page

    Read my other posts on Master pages in ASP.NET

     

    Accessing a master pages properties

    So you have a master page, with a lot of content pages using it, and you need the same data, i.e. UserId on all those content pages?

    A good way of doing this without breaking the DRY principle is to let content pages access master pages properties.

    To do so you need to create a public property in the masters code-behind file like this.

    image

    Then you add a @ MasterType directive in all the content pages, where you need to access this property.

    image

    This is placed right under @ Page directive. When you have done this, all you need to do to access the MyMasterProperty is to write the following:

    Master.MyMasterProperty  = “This is a new text.”;

    And to read it:

    Response.Write(Master.MyMasterProperty)

    image

    The same can be done with methods also.

     

    Accessing a master page controls

    Say you want to access the controls of a master page, then you can do it in the following way.

    We have the following control in the master page.

    <asp:Label runat=”server” id=”MasterLabel”></asp:Label>

    To programmatically access this control from a content page we need to use the FindControl method in the Master object and cast it to the right type. To do this just use the following code in the code-behind file in the content page.

    Label MasterLabel = (Label)Master.FindControl(“MasterLabel”);

    MasterLabel.Text = “This text will be displayed in the MasterLabel control in the master page”;

    image

    Because we are actually using a string to pass in the control id to the FindControl method, this is not strongly typed, witch I personally prefer (miss typing of the ID wont be found until runtime otherwise). You can expose the control as a property.

    image

    Then use the same technic described in the beginning of the post to access the master pages control.

    image

    Master pages in ASP.NET – Nested master pages

    Sometimes you want to use a generic layout to the entire website, and in 2 “sub sites” like forum and admin you want to have another master file to dictate layout for that specific section.

    What you need to do is create a parent master file and two sub master files. Like the image below.

    image

    The Parent.Master file have two ContentPlaceHolder controls.

    <asp:ContentPlaceHolder ID=”HeadContent” runat=”server”></asp:ContentPlaceHolder>
    <asp:ContentPlaceHolder ID=”MainContent” runat=”server”/>

    This two must exist in the child master files also.

    You also have to reference the Parent.Master file in both Admin.Master and Forum.Master like the image below (showing Forum.Master)

    image

    Now when all master pages is created and configured all you need to do to use them is to add a Web Form using Master Page, click Add. And select the master page you want.

    image

    image

    The @ Page directives will look like the following line of code, for pages using the Admin.Master.

    <%@ Page Title=”" Language=”C#” MasterPageFile=”~/Admin.Master” AutoEventWireup=”true” CodeBehind=”Admin.aspx.cs” Inherits=”Prototype_Master_Pages.Admin1″ %>

    And to round up this post a image of the actual ASPX page using the Admin.Master file.

    image

    The text Admin is rendered from the Admin.Master.

    Follow

    Get every new post delivered to your Inbox.