In this blog post we are going to talk about the basics and new features in ASP.NET 5 and Visual Studio 2015 by creating our favourite Hello World Program.

Visual Studio 2015 is a File based project system now which means that when we add a file in the file system then it is automatically picked up and a dynamic compilation happens that could result in faster refresh and faster build behind the scenes. This is possible because of the Rosyln compiler https://github.com/dotnet/roslyn.
In the newer version of Visual studio we can develop applications with the full featured .Net framework as well as the Cloud Optimized Core CLR. The idea of designing this new Core CLR is to make the application with fast startup, low memory usage and high throughput (I wonder why this is not the default framework always). Core CLR is designed to work on the  environments other than windows as well like Linux and OSX. Core CLR is available as a nuget package and hence could be deployed as part of the application itself but keep in mind, this being an optimized CLR might be missing types available in the full features .NET framework.

 

The newer version of ASP.NET has taken steps towards unification by combining ASP.NET MVC + WebAPI into one class itself which means that it would have only one base controller for both.

MVC6 WebPage MVC WebAPI

MVC6 WebPage MVC WebAPI

 

MVC 6 does not rely on the System.Web anymore and also the minimum size of the HttpContext is reduced to 2kb from 30kb. Let’s create our favourite project HelloWorld in ASP.NET 5

 

New ASP.NET 5 Project

New ASP.NET 5 Project

Make sure you select the Web Application under ASP.NET 5 Templates. and Uncheck the Host in Cloud checkbox for now.

Hello World ASP.NET 5 Project

Hello World ASP.NET 5 Project

 

Now let’s navigate to the Controllers folder of the project in the File Explorer and create a new file named HellowWorldController.cs

New Controller

New Controller

You would notice that this file is automatically refreshed in the solution

 

File Explorer Sync

File Explorer Sync

Now let’s add some code to this controller to see it in action.

 

Build and run the project by pressing Ctrl + F5 and change the url to call the controller that we just created.

Run ASP.NET 5

Run ASP.NET 5

 

This was certainly less painful as we do not have to remember what files we created in the file system (Not that I do, Git takes care of all that) as Visual Studio automatically takes care of that.

Now if we change the controller and save the file and then refresh the browser, my changes are reflected which was not the case before while working with C# files.

Run ASP.NET 5 After File Save

Run ASP.NET 5 After File Save

 

The root of the website is not longer the root of the project. By default the root of the website is wwwroot folder which contain all the static resources of the Website (including the bin folder for dlls) by default. We can add more static resources here as well. This allows a clear separation between the files that need to deployed to webserver and the configuration files.

 

WebRoot wwwroot

WebRoot wwwroot

By default the views also reference resources from the webroot (~) of the website.

Reference Webroot wwwroot

Reference Webroot wwwroot

 

We could change it by modifying the webroot in the project.json file.We will also notice the new way of declaring dependencies.

Change Webroot wwwroot

Change Webroot wwwroot

However the dependencies that could be added in project.json has be 100% .NET dependencies. We could include these dependencies using the good old Manage Nuget Packages option.

 

Manage Nuget Packages

Manage Nuget Packages

or we could hand type the dependencies in the project.json files itself and intellisense would help us out there. We could specify the version we want to target or add empty string (“”) to use the latest always.

Add nuget reference manually

Add nuget reference manually

Once we do that and save the project.json file we would see that the References section in the solution explorer will show the progress of getting and mapping the package that we just added. And at last building the project.

Auto Build

Auto Build

 

If you look further down in the project.json file you would see in the framework section that both full featured dotnet and dotnet core frameworks have been included. This will make visual studio build the solution against both the framework which could be beneficial when we are supporting multiple frameworks.

 

Target Multiple Frameworks

Target Multiple Frameworks

When we run the project in the local system it would run against only one of the framework so to check which framework we are running against we could go to the project properties we could select the framework.

Select One Framework

Select One Framework

 

When we are working in the solution on anything like say in the HelloWorldController I want to return the current date and time using timezone then we could see the information of availability in intellisence.

Package Availability

Package Availability

 

We could use the # defined symbols to write code against specific frameworks. Like we could use #dnx451 for dotnet framework and #dnxcore50 for core framework.

 

 

Use # directive

Use # directive

Now if you see the in the current solution of the project you would not find the packages that are listed as dependencies. The reason is because they are present under the user profile folder in .dnx folder.

 

Framework Location

Framework Location

When you go inside the .dnx folder you would see the packages folder where all the packages referenced by the current project and all the other projects will be present so that all of them could be reusable.

Packages Location

Packages Location

 

You would also see a runtimes folder where we could see the available runtimes which are x64 and x86 versions of both full dotnet framework and core framework.

 

Runtime Location

Runtime Location

 

Any questions, comments and feedback are always welcome.

 

Master Pages

The most important thing to have in the website is a consistent look and feel for the whole website and it involves have a similar colour scheme and similar structure for all the pages on the website. Generally the pages in the website are structured in a way that they have a fixed header, fixed side navigation panels, fixed footer and dynamic centre content. The goal is always not replicate the code in the header, footer and side navigation panels. So we need to have a mechanism by which we can place this code in separate file and when we change those vales the changes should be propagated to all the pages.

Master page in ASP.NET provides this facility. So the way it works is that we have a single top level file named with extension as .master. This master page will contain the overall look and feel of the page. We can define our header, footer and panels in the master page file and we also place a placeholder position where the content of the page will be placed. Then we build up the content pages. These pages will be standard ASP.NET pages wired up with the master page and when they render their content then their content is surrounded with the header, footer and panels from the master page. There can be any number of the master page, content place holders, etc.

 

Master Pages ASP.NET

Master Pages ASP.NET

The actual code for the master page and content page will look like something below. The master pager will end with the .master extention and it will have the similar attributes that the Page Directive does like the Language. Then there will be top level layout and then we put one or more ContentPlaceHolder and this is where the ASP.NET pages will have their regular content.

The Page will have a link to the master page and then it will have a content control which is linked to the ContentPlaceHolder of the master page. Any content specified will be injected into the ContentPlaceHolder.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now let’s have a look at the actual code in Visual Studio. So lets create a new asp.net website and delete all the files and folder in it except Default.aspx and Web.Config from the solution explorer. Now add a MasterPage to the site named SiteTemplate.master and add the following code to it. This master page will have the header, footer and the maincontentplaceholder for the site.

 

Master Pages ASP.NET

Master Pages ASP.NET

Add the following content to the Default.aspx page. At the top of the page we add a reference to the MasterPage. And then we place a Content control wired up to the ContentPlaceHolder of the MasterPage and add the a couple of calendar controls into it.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now add two more pages to the website named Page1.aspx and Page2.aspx and add the following code to them. Similar to the default.aspx we have added a reference to the MasterPage which will govern the header, footer and side panel of the website and the content control that we have added will be the content that will be different on different pages.

 

Master Pages ASP.NET

Master Pages ASP.NET

Let’s now have a look as to how the master page injects content into the content pages. We should think it in a way that the content page is the endpoint and it is responsible for dispatching the content and the master page is going to be injected as the child control in the hierarchy of the content page. The other important thing to know is that the actual content that is added to the content page is dropped into the ContentPlaceHolder inside the hierarchy in the master page. But in the end the content is rendered as the normal html content. We can a have a look at the hierarchy in the image below.

 

Master Pages ASP.NET

Master Pages ASP.NET

When you open the default.aspx in the Design mode then you would notice that the design interface of Visual studio will allow you to edit on the content part of the page and the remaining part of you page which is derived from master is not editable.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now let see the relationship between the master page and the content with regards to the control hierarchy. So let’s enable the trace at default.aspx.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now let’s run the site and the trace part looks something like below.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now as the master page is defining the content of the page hence we need to know a few things for our pages to look the way we want them to look like.

  • Title attribute of the pages – This is really important because the title attribute is being defined as the part of the master page and that is where we need to place the title but we need have a distinct title for different pages. It’s really staring forward to do while using master page because the head content is marked as runat server and the title attribute takes it value from the content page title. So we could have the default title of the site in the mater page as shown below.

 

Master Pages ASP.NET

Master Pages ASP.NET

And then we can set the Title of the content pages which will overwrite the default title in the master page.

 

Master Pages ASP.NET

Master Pages ASP.NET

  • Now on some of the page we might want to hide our side panel so what we need to do is add a panel and add the code for the left pane inside it

 

Master Pages ASP.NET

Master Pages ASP.NET

Now let’s add a property to the MasterPage using which we will use to set the visibility of the Left Panel.

 

Master Pages ASP.NET

Master Pages ASP.NET

 

Now we access this property for hiding and showing the visibility of the left pane by accessing the master property for this page in the pageload method.

 

Master Pages ASP.NET

Master Pages ASP.NET

Another way to do this is to use the VirtualPath property in the MasterType directive and set it to the masterpage of the site.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now as we have specified the MasterType at the masterpage so we do not need to typecast it as the SiteTemplate and we can simply directly access the Master Page.

 

Master Pages ASP.NET

Master Pages ASP.NET

  • We can set the masterpage of the content page in the code as well by setting the Page.MasterPageFile but for it work without exception we need to call it in Page_PreInit.

Nested Master Pages

It is perfectly alright to have a MasterPage for the MasterPage as well. So as you can see in the image below we have defined the MasterPageFile attribute in the Master directive of a master page. The reason to do this is to add an addition level of layout. Also you need to see that in the child master page we need to specify the content in the ContentControl just like the content page. But we need to be careful that to access the ContentPlaceHolder of the root master page then we need to redeclare it in the child masterpage.

 

Nested Master Pages ASP.NET

Nested Master Pages ASP.NET

Let’s see this in action by creating a new MasterPage

 

Nested Master Pages ASP.NET

Nested Master Pages ASP.NET

Let’s add a Content Panel for the head content so that if someone wants to access the head container in the root page then they can do that. Also let’s add a fieldset in the mainContentPlaceHolder with a legend.

 

Nested Master Pages ASP.NET

Nested Master Pages ASP.NET

Now let’s add a Page3.aspx which will use this SecondaryTemplate.master as the masterpage and add its content in the content place holder.

 

Nested Master Pages ASP.NET

Nested Master Pages ASP.NET

Themes in ASP.NET

Themes are a useful way to give a consistent look and feel to the controls throughout the application. It is a consolidation of UI elements by the use of stylesheets, skin files, images,etc. Let’s see how themes can be added and used in the application. So Theme is a directory in the application level directory in the App_Themes directory and it can contain zero or more .css files and all .css files are implicitly referenced.

 

Themes in ASP.NET

Themes in ASP.NET

This will add two directories added by this option.

Themes in ASP.NET

Themes in ASP.NET

 

Let’s add a stylesheet to this directory. And add the code shown below to it.

 

Themes in ASP.NET

Themes in ASP.NET

Themes in ASP.NET

Themes in ASP.NET

Now let’s add a new page which does not uses any maasterpage and add the following code to it.

 

Themes in ASP.NET

Themes in ASP.NET

 

When we run our application we will see that the textboxes will have the colo as specified in our theme css file.

The Theme folder may also contain one or more .skin files. A skin file will contain control declarations with default attributes. This will provide a consistent look and feel for the controls that use that skin. We did not put the ID against the controls because we do not want it to apply. We can also put the  ID against the controls so that the controls that indivisually want to use that style can do that by referring the ID.

 

Themes in ASP.NET

Themes in ASP.NET

Also the theme folder may contain zero or more subdirectories with resources like images or scripts. So all the resources used in  the theme could be placed here.

Let’s see this in action. Let’s add a new skin file in our theme1.

 

Skin File in ASP.NET

Skin File in ASP.NET

Now add the code to this theme file as shown in the image below. The first thing that we need to do is add SkinID to the controls in the MyTheme.skin, if we want to use these control styles on a per control basis.

 

Skin File in ASP.NET

Skin File in ASP.NET

Now let’s go back to MyThemedPage.aspx and use this style. Now as we have applied the Theme1 to the MyThemedPage.aspx the textboxes there will automatically pickup the style of the textbox which has no SkinID. If we want to use a style that has a skinid then you would need to add that skinid to the control we want to apply the style to. So the textbox1 will have the cssclass foo applied to it will be foo and textbox2 will have the cssclass bar applied to it.

A very simple thing to do is replicate our theme. We can just copy the Theme1 and paste it into the app_Themes folder.

 

Themes in ASP.NET

Themes in ASP.NET

We can then edit the css file in this skin very easily and use it as it already has the same structure and the class named and skin id are all the same and we change or add or delete styles in the css file.

 

Themes in ASP.NET

Themes in ASP.NET

Now let’s add a calendar control to the MyThemedPage.aspx and apply professional1 theme to it. It would look something like below as shown.

 

Themes in ASP.NET

Themes in ASP.NET

Now go back to the Source mode. We will see something like as shown below.

Themes in ASP.NET

Themes in ASP.NET

We will copy that calendar code and paste it in the Theme1àMyTheme.skin and remID and add a SkinID as professional.

 

Themes in ASP.NET

Themes in ASP.NET

And now we could use that in our themed page.

 

Themes in ASP.NET

Themes in ASP.NET

Let’s add a images folder and add an image to it. Then we would add a asp:Image control and reference that image into it.

 

Themes in ASP.NET

Themes in ASP.NET

Now we will utilize this image in our MyThemedPage folder.

 

Themes in ASP.NET

Themes in ASP.NET

We would see something like bleow.

 

Themes in ASP.NET

Themes in ASP.NET

What we did before was applied the theme to the page level and now what I am going to do is apply that theme to all the pages in my site by specifying the same in the web.config file. This will impliclitly include a reference to the theme file into all the pages of my site.

 

Themes in ASP.NET

Themes in ASP.NET

Now let’s see how the theme actually works. The way we saw to set the theme on the web.config sets the theme globally and if do not want that theme to certain pages we can override by specify a different theme for that page in the Page directive of that page.

 

Themes in ASP.NET

Themes in ASP.NET

We can also set up the themes programmatically. We need to set the theme in the PreInit event handler of the page.

 

Themes in ASP.NET

Themes in ASP.NET

We can also set the themes globally dynamically.

  • We could subscribe to PreRequestHandlerExecute and wireup a PreInit handler on the fly.
  • Then set the theme in the PrInit handler and that will apply the changes to all the pages.
  • This can be stored in Profile, session, config,etc.
  • Same technique works for master pages as well.

 

Themes in ASP.NET

Themes in ASP.NET

 

Navigation Controls

In ASP.NET 2.0 3 new site navigation controls were introduced.

  • TreeView
  • Menu
  • SiteMapPath

All these 3 controls can use SiteMapProvider which derives its default data source from web.sitemap and it is a standard xml format for page.navigation. Let’s see how this works. Let’s add a sitemap to our site

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

Let us add the sitemapnodes to it hierarchal.

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

Now let’s go back to the MasterPage and go to the Navigation in the Toolbox and use the TreeView , menu and sitemappath.

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET
Navigation Controls in ASP.NET

This is how it looks

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

The image below shows the hierarchy of the navigation controls.

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

The Code for this post is available here.

 

Any questions, comments and feedback is most welcome…

 

HTML Controls

HTML Controls are collection of the server side controls that give the server side representation of the client side HTML elements. We can create a server side object by giving any client side HTML element with the attribute of runat=”server” and giving it an identifier. This is a very convenient way of manipulating server side elements without messing up the markup. It is useful at places where you have already existing HTML elements in you code and you do not want to completely replace them with the server side web controls then we can set up the marking for some of the controls to runat server.

Let’s have a look at this in action. Let’s open the exiting folder that contains the files HelloWorldCodeBehind.aspx and HelloWorldCodeBehind.aspx.cs as a website in Visual Studio

 

HTML Controls ASP.NET
HTML Controls ASP.NET

It would look something like below.

 

HTML Controls ASP.NET
HTML Controls ASP.NET

What we will see here is how to use an HTML server side control to get rid of the inline markup of GetType. The first way we can do this is go the h3 element and give it the runat server attribute and an id. Also we will remove the GetType call and replace it with xxxxxxxx to indicate that this value will be updated.

 

HTML Controls ASP.NET
HTML Controls ASP.NET

Now let’s go to the code behind. We will tap the load event and do what we were doing in the aspx. When we add the attribute runat server then we get access to that type in our server side code.

HTML Controls ASP.NET
HTML Controls ASP.NET

 

Web Controls

Another category of the server side controls is WebControls and its present in the System.Web.UI.WebControls namespace. These are generally used over there HTML counter parts as these are listed as the standard controls in the toolbox. They are more convenient to work with because they have more consistent property names. So once you know how to use one control you can easily use the other which is not the same in the case of HTML controls. Many of these Web Controls are replacement of the HTML controls and other are more complex.

Let’s see these web controls in code. So we have already used BulletedList which is a webcontrol that renders as an unordered list. So let’s remove the Response.Write and replace it with a label.

 

Web Controls ASP.NET
Web Controls ASP.NET

Now we will add the logic to display the total number of items in the label inside the Load Event in the server side code.

 

Web Controls ASP.NET
Web Controls ASP.NET

Let’s add a calendar and display it on the page.

Web Controls ASP.NET
Web Controls ASP.NET

 

When we view the source of the displayed aspx page we will not see a control but a table with all the elements defined in it.

 

Web Controls ASP.NET
Web Controls ASP.NET

Control State Management

One of the most important things in Control State Management in ASP.NET is that they maintain their states even during the post backs. So sequence is as below:

  • The initial get request to a page creates the server side controls with their default values specified on the initial form.
  • Then if the user clicks on an element that generates a post request onto the same page then this would generate the POST message that would be handled in the server. Then when the server creates the page then the page creates the server side controls with the values in the POST body of the request that came back.
  • So the changes that are made by the client in the controls will be reflected in the server side controls and consequently the response for page render.

The flow of the Web Form Client interaction is shown in the image below.

 

Control State Management ASP.NET
Control State Management ASP.NET

Let’s see that in action. Let’s create a new page named State.aspx and add the following code to it.

 

Control State Management ASP.NET
Control State Management ASP.NET

 

Control State Management ASP.NET
Control State Management ASP.NET

When we run this page we can see state retention in action.

There are several implications of State Retention as well.

  • There is no need to re initialize state in controls when we are processing post back requests.
  • Can’t do cross page posting by default.
  • Controls that are not intrinsically included in a POST back will not retain their state by default and we will have to request their state propagation via hidden fields.

Let’s see this in action by optimizing our Load event code. We will check for the IsPostBack property of the page to determine whether this load is a post back or not. If it is not then only we assign states to the controls otherwise the state will be retained.

 

Control State Management ASP.NET
Control State Management ASP.NET

ViewState

The model of state retention for server side controls is pretty simple when we look at the input controls that are sent back as part of the post back. Now we need to see how the controls that do not contribute to the POST body will maintain their states. These elements includes div, span, li, p, table, etc. The answer is ViewState. ViewState is the additional hidden input element which is generated when each page is rendered and it is used by controls to insert additional state during post back.

The best way to see this is in code. Let’s create another Form named ViewState and add the following code to it.

 

ViewState ASP.NET
ViewState ASP.NET

So whenever we click on the button a post back happens but the state of the label is still persisting its state.

ViewState is persisted as a serialized tuple-based data structre and encoded as a base64 string. So we can use any base64 decoder to decode the ViewState. We can download a ViewState Decoderfrom http://tinyurl.com/4dn377. It would look something like below.

 

ViewState ASP.NET
ViewState ASP.NET

Disabling ViewState

ViewState is a perfectly useful way to propagate requests while dealing with small controls that have fairly less ViewState associated with them but large amount of ViewState on controls like databound controls we must turn it off. There are two way in which we can disable the ViewSate.

  • Set EnableViewState=”False” in the page directive. This will disable the ViewState for the entire page.
  • Set EnableViewState=”False” on the individual controls. You can identify thecontrols that does not require ViewSate and set this attribute and we should do this on the controls that have a significant ViewState usage.

This will reduce the amount of data in the request that goes back and forth.

Change Notification Events

In the previous section we have seen when and where to disable the ViewState. In this section we will see where we should not disable ViewState.

  • Do not disable ViewState on Server-Side controls that issue change notifications events based on ViewState.
    • Because the Prior Value is stored in the ViewState to keep track of the changes.
    • During subsequent POST requests the current and the cached values are compared and if they are different then a change notification is issued.

EventTarget and EventArgument Fields

There is another method to find out which server side control actually initiated the server side request and this has an EventTarget field and an EventArgument field. Some input elements like Button, imagebutton, etc already send data in the POST body that can help us identify the sender. But there are some controls that do not use standard postback mechanisms. For example the change notification in thelinkbutton, drop down list when autopostback=”true”. This does not have any data included in the POST that will help us identify that it is the control that initiated the postback. That is why there are these 2 other fields which helps us identify as to which control issued the postback. So the EventTarget Hidden field stores the control id that issued the event and the EventArgument Hidden Field will store any parameters sent for the event.

ControlState

ControlState is a feature which was added with release 2.0 of ASP.NET. The idea behind ControlState is to give the developer another repository for saving the state apart from the ViewState that cannot be disabled. This was to fix the issue that was faced in the previous version when the ViewState for certain controls like GridView, etc was disabled then the control did not work properly. So now the user has the option to distinguish the behaviour state by placing it into the controlstate and by placing simple data into viewstate. ControlState is not a separate hidden field but it is an additional collection of state data appended to the end of ViewState. So we can now turn off the view state for the controls without any issues. So all of the newer data-bound controls in ASP.NET makes use of the Control State.

Explicit Use of ViewState

ViewState can also be used as the means to store client-specific state which will retained across the POST requests to the same page. But we need to make sure that the types are serializable. These are directly accessible from the Page.ViewState property on the page and it returns the collection of the ViewState properties.

So let’s see how we can make exclusive use of the ViewState property. Add a new WebForm to our existing website and add a listbox in the aspx file. Also lets add the label to the aspx.

 

ViewState ASP.NET
ViewState ASP.NET

Now let’s add a handler for selectionchanged event of the ListBox. We will add the logic that whenever the user clicks on the listbx we will update the label by storing the count in the ViewState.

 

ViewState ASP.NET
ViewState ASP.NET

The code for this Post can be found here.

Any questions, comments and feedback are most welcome.

 

This line of tutorials will take you through all the ASP.NET fundamentals

Architecture of ASP.Net

How an ASP.NET page is processed?

All the asp.net pages are parsed into a class definition and that class is then compiled into a.Net assembly who sole purpose is respond to request destined for the endpoint. This class is then loaded into the worker process i.e. w3wp.exe and the classes will then be created and will process the requests. These classes are created on demand and this happens for all the .aspx. So it’s safe to say that when you are writing an .aspx you are writing a class. So essentially when we are writing aspx we are just building additional classes and extending the base classes and controlling the class generation from .aspx files.

Let’s see this in action. I hope you have IIS installed on your machine. So just go to cà inetpub à wwwroot and create text file named HelloWorld.aspx and add the following content to it.

<html>

<h1> Hello World!!! </h1>

</html>

And then save it and close it. Now go to the Internet Explorer and type the following:

http://localhost/helloworld.aspx

And you will see something like below:

 

HelloWorld.aspx

HelloWorld.aspx

Now let’s understand what going on here. Let’s first add the code as shown below to the HelloWorld.aspx. The Page Directive will set the language as C# and also the Debug to true. Also we will access the GetType().Assembly.Location method as we know we are in .NET and we will be able to track the location of the class.

<%@ Page Language=”C#” Debug=”true” %>

<html>

<h1> Hello World !!! </h1>

<h3> This Page is loaded from

<%= GetType().Assembly.Location %>

</html>

The %= is the evaluation syntax in the server side script <%= GetType().Assembly.Location %>

Now when you will refresh the page, you could see the location from where the assembly was loaded along with the name of the assembly.

 

Temporary ASP.NET Files

Temporary ASP.NET Files

Now when we open up this directory (E:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\a2cc4162\951dc92c)

Temporary ASP.NET Files Directory

Temporary ASP.NET Files Directory

you could see that C# source code files are present here and if you open them you could see the class definition present in it. As you could see the name of the class is created by replacing the . with an _ and it derives from System.Web.UI.Page which is the base class for all the aspx pages.

ASP.NET generated Code file

ASP.NET generated Code file

Now if we scroll down the file we could see how the html is parsed and the method that we wrote injects the content.

 

ASP.NET generated Code file

ASP.NET generated Code file

Dynamic Content

Now as we could see in the image below, we could see Interspersed script notation which is root cause of many problems in a web site so we do not want to follow this as a practice at all. This syntax is still supported but we will try to move towards other techniques for easier to maintain code.

 

ASP.NET Dynamic Content

ASP.NET Dynamic Content

So the types of dynamic content that we can integrate onto our page is

  • Interspersed server-side script – So this is the way of dropping code onto the page but the language will be as specified in the page directive. It has to be in the language specified at the top of the page. Then we also have the evaluation syntax (GetDisplayItem) which is equivalent to Response.Write.
  • Server side scripts – So we can also include server side scripts as a block with the Runat sever attribute so that it is dumped into the class definition.

Let’s just add the following code to the HelloWorld.aspx from the previous example.

<%@ Page Language=”C#” Debug=”true” %>

<script runat=”server”>

const int _itemCount = 10;

string GetDisplayItem(int n)

{

return “item #” + n.ToString();

}

</script>

 

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head><title>Dynamic Content</title></head>

<body>

<h1> Hello World !!! </h1>

<h3> This Page is loaded from

<%= GetType().Assembly.Location %></h3>

 

<ul>

<% for (int i=0;i<_itemCount; i++)

{ %>

<li><%=GetDisplayItem(i)%></li>

<% } %>

</ul>

<%

Response.Write(“<h2>Total Number of items = ”

+ _itemCount.ToString() + “</h2>”);

%>

</body>

</html>

When we run the page we would see something like below:

 

ASP.NET Server Side Script

ASP.NET Server Side Script

 

Let’s go back to the directory and have a look at the generated content once again. So what we see here is that the server side code is injected directly into the code file. So whenever we use server side scripting then that is dropped into the class directly. So we used put only those things in server side scripting that would make sense if they are in the class definition directly. So we could not directly executable code in class definition.

 

Generated server side script ASP.NET

Generated server side script ASP.NET

And the client code is added to the function definition that will write onto the screen. So the code that was part of Interspersed script is put directly into a function within our class. We could not define function here as nested function definition is not allowed in C#.

 

Generated server side script ASP.NET

Generated server side script ASP.NET

Server Side Controls

We should avoid using Interspersed scripts as it tends to clutter pages and makes the code difficult to maintain. We should try to use the preferred model for dynamic content in an ASP.NET page. This model comes from the server side controls in ASP.NET. So any control that has a runat=”server” attribute will be added to the class definition as a server side member variable, so we could manipulate these variable instead of the Interspersed scripts. The state maintained for the Server side controls is implicitly POST to the same page.

Let’s revisit our page and replace the server side scripts with server side controls. Let’s first replace the dynamic generated script with the server side control definition. We are following a common technique of populating the server side control with some content even though this content will never be displayed. So we are using a server side control named bulleted list which will display an unordered list.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

Now we are going to write a method to populate this list. So we are overriding the OnLoad method which we inherited from the page base class. So we are using the already created list _displayList and clearing the items in it. Then we are iterating through the items and add the items to the _displayList.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

If you will run this page now you will get an error saying that the runat=”server” controls should be placed in the form with a runat=”server” attribute. So let’s add that.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

And now we run the page we will something like below.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

Let’s also have a look at the class definition changes with the addition of the server side controls. The very first thing that you will notice is that the BulletedList named _displayList is added as a protected member. And the interaction with that _diasplayList member is shown below it.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

Data Binding

In the previous section we edited the server side control at very low level but we can also use ASP.NET data binding model. So we will add a string array of the items we want to show. It has to be an Enumerable collection. It can be an array, dataset, datatable, strongly typed list class, etc. So all we need to do is the ItemsSource property to the collection we want to bind to and then exclusively call DataBind(). Let’s see the code of the same.

 

ASP.NET Data Binding

ASP.NET Data Binding

We will see a similar output if we run this page but instead of iterating and adding the items we have utilized the power of data binding.

Declarative Data Binding

Version 2.0 of .NET introduced data source controls. The idea behind declarative data binding is that instead of manually writing the code for data binding we hand it off to another control. In this case we will have a look at the ObjectDatSource as this lets us point the datasource to a class definition. To use it we have to specify the name of the class to use and the name of the method that will be used to retrieve the data. So now our page will not have any data access code as all that logic is separated to a separated class. So let’s write the code for this. Let’s go to the wwwroot folder and create a directory named App_Code. This is a special directory because if we place any source code files in this directory they will be implicitly complied if they are referred any of our pages. We will then add a file named ItemsDataSource.cs

 

ASP.NET Declarative Data Binding

ASP.NET Declarative Data Binding

We will remove all the server side code as it will be handled by this declarative data source. And then let’s wire up to the ItemsDataSource. We have added an object data source as MyDataSource and refer it in the BulletedList. So now when the list needs the data it will go and query the mentioned object data source which will in turn query the specified method in the specified class.

 

ASP.NET Declarative Data Binding

ASP.NET Declarative Data Binding

Code Behind V2.0

The ASP.NET version 2.0 code behind model is like shown below. We have specified in our aspx page the code behind for this page. Also we have the concept of partial class implemented for these classes.

 

ASP.NET Code Behind

ASP.NET Code Behind

Let’s change our code accordingly. Let’s add a new file names hellocodebehind.aspx.cs and move our code which not related to the presentation to this file.

 

ASP.NET Code Behind

ASP.NET Code Behind

Page Lifecycle

So now we have the ability to separate the code from the view as we saw in the previous section. Let’s understand the ASP.NET page lifecycle which is shown in the image as below. This will help us understand many other things that can be done inside the page class definition. Just refer the aspx.cs class that we wrote earlier and you will see that we have overridden the OnLoad event of the page. This is one of the events that take place while processing the request for the page and this is most common of the events in which users generally tap into for doing data binding modifying controls and there values. There are many other events that occur during the complete page request process as we could see in the image below. When a request for an aspx page is made then class is constructed and its constructors will be called and then this lifecycle sequence is launched starting from the top left to the bottom right. Another event for which handler is added is very commonly is Init. This event occurs early in the lifecycle of the page but after all the controls have been loaded into the control tree. Another event is the LoadComplete event which is fired after all the server side events have been fired. Pre render is a back stop which takes place just before the rendering is sent to the client. PreInit is the only event where we can edit master pages and themes. Render event occurs when the response is sent back to the client. Once the response is sent back to the client then Unload events occurs.

 

ASP.NET Page Lifecycle

ASP.NET Page Lifecycle

Event Handling

Let’s talk about how we can wire up events. This is the techniques that can be used to wire up all the events in the page class. The naming convention for such events is On followed by the name of the event.

 

ASP.NET Event Handling

ASP.NET Event Handling

In Visual studio the standard techniques when using Visual Studio is to create a function named Page_ followed by the name of the event and .Net will implicitly add a delegate subscription. This function is called as the Auto Event Wire Up and this is the preferred model in Visual Studio.

 

ASP.NET Event Handling

ASP.NET Event Handling

Another way of accessing this events is to access these events as the members of the Page class. Simply .NET events defined on the System.Web.UI.Page Base class and all we need to do is use += to add a delegate.

 

ASP.NET Event Handling

ASP.NET Event Handling

So let’s see this in action. Let’s modify the HelloWorldCodeBehind.aspx to use the AutoEventWireUp.

 

ASP.NET Event Handling

ASP.NET Event Handling

Now let’s make use of Auto Event Wire up and tap into the LoadComplete event. We need to modify the HelloWorldCodeBehind.aspx.cs for this as below.

 

ASP.NET Event Handling

ASP.NET Event Handling

When we run this page we will see that the text is written at the top of the page.

 

Method Name for Implicit event subscription

The way AutoEventWireUp wire works is through the hashtable defined in the .NET. At runtime a check is made for the strings present in the code to match up with the string shown in the table below. So there is no algo for. So it’s just a set of hard wired strings that are looked for automatically when AutoEventWireUp property is set to true. This will work only if the signature also matches up with the event.

 

ASP.NET Event Handling

ASP.NET Event Handling

 

Control Event Handling

Other events that we will be handling in code are the events are raised by the controls on the page. So the recommended model for handling a control initiated event is go to the server side control in the view and add a prefix On to the event name and then set the handler for it. That handler in the code should have the correct signature of an event.

 

ASP.NET Control Event Handling

ASP.NET Control Event Handling

The other way to do it is use the += notation the code class to specify the handler for a particular event.

Let’s see this in action. Add a button and a label at the bottom of the HelloWorldCodeBehind.aspx file as shown below.

 

ASP.NET Control Event Handling

ASP.NET Control Event Handling

Now let’s go to the server side code i.e. HelloWorldCodeBehind.aspx.cs and add a handler for this button click event.

 

ASP.NET Control Event Handling

ASP.NET Control Event Handling

When we run the page we will see something like below.

 

ASP.NET Control Event Handling

ASP.NET Control Event Handling

Compilation

Another feature that was added to .NET 2.0 was the suite of directories as shown below.

  • App_Code directory is the place where we place the code and it automatically compiles as part of the aspx page request process.
  • App_Browsers directory is used for defining additional .browser files which define the additional browser capabilities.
  • App_GlobalResources directory automatically compiles .resx files into the application.
  • App_LocalResources directory automatically compiles .resx files into the application.
  • App_Themes directory is used for referencing themes in the site
  • App_WebReferences directory is where wsdl files are placed.

The version 2.0 ships with a  new compiler named aspnet_compiler.exe which helps us compile our directories manually into binary deployment files. Below is the detailed chart of all the directories and there usages.

 

ASP.NET Compilation

ASP.NET Compilation

Shadow Copying

The mechanism of shadow copying is import for the deployment, updating, etc. The idea behind it is this that we do not have to shut the site to deploy the new binaries. In classic ASP we need to shut down the server in order to release the references so that we can copy the new binaries without any errors. With version 2.0 we do not have to do that because of Shadow copying. As we can see in the diagram below when we try to access a binary what ASP.NET does is physically copies the binary to an obfuscated location and then runs so that there is no direct reference to the binary and also when the binary is updated then it updates the binary as well.

 

ASP.NET Shadow Copying

ASP.NET Shadow Copying

 

You can find the code for this post here.

 

Any questions, comments and feedback is most welcome.