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.

<!-- MasterPage.master -->
<%@ Master Language="C#" %>
<html>
<body>
    <form runat="server">
        <h1>My Common Header</h1>
        <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server" />
    </form>
</body>
</html>

 

<!-- Page1.aspx -->
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </asp:Content>

 

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.

<!-- SiteTemplate.master -->

<%@ Master Language="C#" %>
<html>

<body>
<form runat="server"> 
<h1>common header</hl> 
<asp: ContentPIaceHoIder" runat="server" />
<!-- SecondaryTempIate.master -->

<%@ Master Language="C#" MasterpageFile="~/SiteTemplate.master" %> 
<asp: ContentPlaceholderID="mainContentPlaceholder" runat="server"> 
<table><tr><td>
<asp:ContentPlaceholder ID="leftContentPlaceholder" runat="server"  />

</td><td>

<asp:ContentPlaceholder ID="rightContentPlaceholder" runat="server"  />

</tr></table>
</asp :Content>

 

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.

<asp:button runat="server" borderStyle="Solid" borderwidth="2px" bordercolor="#66ff66" backcolor="#99ffff" />

<asp:calendar runat="server" borderStyle="Solid" borderwidth="2px" bordercolor="#66ff66" backcolor="#99ffff" />

 

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.
<%-- File:Global.asax --%>
<%@ Application Language="C#" %>
<script runat="server">
void Application_PreRequestHandlerExecute(object src, EventArgs e) {
    Page p = this.Context.Handler as Page;
    if(p!=null)
        p.PreInit += new EventHandler(page_PreInit);
}

void page_PreInit(object sender, EventArgs e) {
    Page p = this.Context.Handler as Page;
    if(p!=null)
        p.Theme = (string)Context.Profile["theme"];
}
</script>

 

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.

protected override void(EventArgs e)
{
    base.OnLoad(e);
}

 

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.

protected void Page_Load(object sender, EventArgs e)
{
}

 

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.

this.Load += new EventHandler(EventPage_Load);
this.Load += EventPage_Load;
void EventPage_Load(object sender, EventArgs e)
{
}

 

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:Button ID="ClickMeButton_Click" runat="server" Text="Click me!" onClick="_clickMeButton_Click" />

 

protected void ClickMeButton_Click(object sender, EventArgs e)
{
}

 

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.

 

 

 

 

Hey guys,

In this post i am going to talk about the most import part of the Silverlight and WPF applications, the View Model and the MVVM pattern.

UI development Challenges

View Models are designed to solve certain problems that pop during the UI designing.

  • The major problem is that the User Interface code is difficult to test especially with automated tests. This is because the Code behind lives in the UI. Suppose we want to test a method in a code behind file like MainPage.xaml.cs then we have no other choice but to make an instance to the MainPage class, so when we do that the constructor is called will call InitializeComponent()  and it will load all the xaml controls which will make the copy of the User Interface tree available and this a major problem in Unit Testing because some components might not work correctly till they are displayed as they make assumptions about the messaging and event handling. So the behavior of MainPage might be different from what it would have been at runtime.
  • Another problem with code behind is that big and complex classes which are really difficult to maintain and are not flexible. You can easily get used to using the code behind for you code because that’s where Visual Studio adds the event handlers automatically. The best approach for coding is to have well defined classes with narrow responsibilities.
  •  The code behind job is to interact with the User Interface objects but when we start to add behaviors in the code behind which interact with User Interface objects we give our classes a wider scope and that’s the start of problems. It becomes all the more problematic when the application logic starts to integrate with the User Interface elements and the state of the application is saved with the help of user Interface elements.
  • Another reason for the problem is overdoing the Data Binding. When you application logic starts depending on your Data Binding states. One example that comes to mind is that when the validation rules are made dependent on Data Binding which should actually always be the part of our application logic.

Separated Presentation

This is the technique which is recommended for overcoming the problems mentioned above. By using separated presentation we can avoid xaml codebehind by removing user interface manipulation logic in code behind, interaction logic in code behind, application logic in code behind and everything else not required in code behind. The best thing to do is to keep as less as code as possible in the xaml code behind. Keep any kind of application logic in a separate class which is generally named as Model. So we should make the model only concerned with the application which says what the application does and not how the user interacts with the application. Now UI class should not have any of the interaction logic because of the problems I described in the previous section so we need to create another class which will hold the interaction logic. This is the View Model. This governs any non-trivial logic. It will have the logic for the User Interface to behave the way we want it to behave.

Model View View Model

So let’s talk about each component.

  • Model – A model is a classic model which comprises of the C# classes. It has not reference to the user interface and is not aware of the existence of any User Interface.  The Model classes are compileable without any reference to the User Interface classes. The types in the Model consist of the concepts our application works with. If should be able to take these classes to any console application, web application or windows application and they should be able to compile with no problems. During the design of the Model we need to take decisions on how will the model be used? For example we situations where the Model is shared by both the client and the server or the model can mostly stay in the server or the model can completely stay in the client.
  • View – View is generally a User Control. In Silverlight it is a good idea to split up the user interface into multiple User Controls.
  • View Model – For each View we write a View Model. So the main purpose of the existence of a View Model is to serve the View. It’s possible for a particular view model to span into multiple classes. The bottom line is that the View model serves the purpose of presenting data or screen to your application. The reason it’s called a view model because adapts a particular model for the specific view. Like the model, the view model is a C# class and is not required to derive from a particular class. Sometimes it makes sense to make a base view model and derive from the same but the pattern does not demand that. But unlike Model it can use Silverlight types in its properties. The important things that define the View Model is that the information flows between View and ViewModel via Data Binding and this enables ViewModel to change the View without having to depend on the view. This is very useful for testability as we can instantiate the ViewModel without having to create the View. We can just use the View Model and invoke the methods and get the values back for testing.

Let’s see some code now.

  • Create a new Silverlight application. And create 3 folders in the Solution Explorer named Model, Views and ViewModel.
Silverlight 4 : Model View View Model

Silverlight 4 : Model View View Model

  • Let’s add a couple of classes in the Models folder. Add 2 new classes named UserModel and MessageModel to the Models folder and add the content as below.

 

Silverlight 4 : Model View View Model

Silverlight 4 : Model View View Model

  • To increase the abstractions lets add a new folder in the solution named services and add an interface to it named IModelProvider and add the following code to it. This abstraction will make testing easier for us.

 

IModelProvider

IModelProvider

 

  • Let’s add another class named ModelProvider.cs in the services folder which will be dummy data provider for this sample application. Add the following code to this class.

 

ModelProvider

ModelProvider

 

ModelProvider

ModelProvider

  • The way we will handle user input in this application is via commands. .NET provides an interface named ICommand which gives us abilities on a User Action – Invoke and Enabled. ViewModels often provide commands through properties because it provides an option to connect the button to the view model without needing any code in the code behind. It is a good approach if you want a way to enable or disable the availability of command as anyways there will be a property exposed to the view by the view model. So it makes a lot sense to use one property to handle the enabling and invoking a command via one property. Silverlight does not implement icommand. Only button and Hyperlink are able to user ICommand but we need to implement it in our code. Let’s add a new class named RelayCommand inherting from ICommand. This will be the relay the action to the method of our choice. We can also refer this as a delegate command as we use a delegate a to specify the method to invoke. Let’s add the following code to the RelayCommand.

 

Relay Command

Relay Command

  • In the Views folder let’s create new viewmodels. Create a new class named MessageItemViewModel.cs and add the following code to it. It’s the job of the view model to provide the data to be displayed. The all message view model will create one of these for each item in the page. So it will not only require a reference to the model provier but also the particular message which it will wrap. We will add three properties which will extract the MessageAuthor, Message Title, Message Body from the underline model object.

 

MessageItemViewModel

MessageItemViewModel

 

  • Let’s add another ViewModel for all available messages name AllMessagesViewModel. The view model asks the provider for all the available messages and then wraps each one into the message item view model. So that the view can have an items control which can have a list of the items.

 

AllMessagesViewModel

AllMessagesViewModel

  • Now let’s create the View for the ViewModels that we have created. Create a new UserControl named MessageItemView.xaml. let’s first add a reference to ViewModels

xmlns:vm=”clr-namespace:ViewModelSample.ViewModels”

  • Also set the reference of the DataContext to the MessageItemViewModel. The d: here represents that this data context is design time and will not be effective at runtime so we need specify that later as well.

d:DataContext=”{d:DesignInstance vm:MessageItemViewModel}”

  • Now add the following code to the MessageItemView.xaml. This will contain the per message user interface.

 

MessageItemView

MessageItemView

  • Let’s another View which will be the home for the View that we just created. Let’s name this view as AllMessagesView.xaml and add the following code in the xaml. This view just contains a ItemsControl inside scrollviewer and this items control just has a item template as the MessageItemView. It will create an item view for each message item.

 

AllMessagesView

AllMessagesView

  • Also let’s add the following code in the code behind for this.

 

AllMessagesView

AllMessagesView

 

  • Finally add the following code to your MainPage.xaml.

 

MainPage.xaml

MainPage.xaml

 

The code of this post is available here.

 

Any questions, comments or feedback is most welcome.

 

In this section we will see how we can break our pages into small pieces by the use of User Controls. If you have worked even once on Silverlight you will see that UserControl is the root Element. So whenever a Silverlight application is displayed in a browser then the first thing that a browser does instantiates the Root UserControl of the start page of the Silverlight application. A User Control can have any number of layout containers in it, it has its own code behind and has an entire system that builds an application. This is concept is extended by Silverlight by moving the pieces of the user control and moving them to the individual documents.

  • Create a new Silverlight application Expression Blend.  In the UserControl add 4 girds and in each grid add a rectangle and give that rectangle a different fill from the others.

 

Expression Blend 4 : Grids

Expression Blend 4 : Grids

  • Now right click on the 1st grid and select Make Into User Control. Build the solution.

 

Expression Blend 4 : User Control

Expression Blend 4 : User Control

  • We will see that the our application MainPage is still the samebut if we see the Objects and timeline the grid that we converted to User Control is replaced the UserControl. Also we will see and exclamation mark. Once we build our project it goes away.
  • Now if we go and change something in the user control we will see that the change is appearing in the MainPage but with and exclamation mark stating that something has changed.
  • But you may need to pay attention when you are working with resources and user Controls. Let me tell you what exactly I am talking about. Just Select a TextBlock and drag it onto the Blue Rectangle.

 

Expression Blend 4 : Text Blocks

Expression Blend 4 : Text Blocks

  • Type some text into the textblock. Come out of the edit mode by pressing ctrl + Enter. Now scroll down to the Text properties of the TextBlock and select the Font as Broadway and Font Size as 20 pt.

 

Expression Blend 4 : Font Family

Expression Blend 4 : Font Family

  • Now click on the property marker next to the Font Family and select Convert to new resource. Name it as MyFont.
Expression Blend 4 : Font Family Resource

Expression Blend 4 : Font Family Resource

 

  • Now let’s go ahead and create another text block in the Green user Control. Now try to use the local resources while the text of the textblock is selected.  We will notice that while we are in edit mode we cannot create or use resources.

 

Expression Blend 4 : Font Family Resource

Expression Blend 4 : Font Family Resource

 

  • Now let come out of the edit mode and select the local resource MyFont to set the font of the Shopping Cart.

 

Expression Blend 4 : Font Family Resource

Expression Blend 4 : Font Family Resource

  • If we place a textblock on the user control and try to use local Resource MyFont than it is not available because we have saved that MyFont as the local resource in the MainPage document.

 

Expression Blend 4 : Font Family Resource

Expression Blend 4 : Font Family Resource

  • Now lets add another text block to the bottom grid and use the local Resource MyFont.

 

Expression Blend 4 : Local Resource

Expression Blend 4 : Local Resource

  • Now let’s make the bottom grid into a user control and now we will see that the Textblock still is using the MyFont resource.
Expression Blend 4 : Local Resource

Expression Blend 4 : Local Resource

 

  • Now lets go to the resources tab and expand the UserControl and we will see that the MyFont Resource is present there.

 

Expression Blend 4 : Local Resource

Expression Blend 4 : Local Resource

  • Let’s drag MyFont resource to application level so that all the control can use it.

 

Expression Blend 4 : Application Resource

Expression Blend 4 : Application Resource

  • Now if we go to the top user control and use the MyFont resource.

 

Expression Blend 4 : Application Resource

Expression Blend 4 : Application Resource

  • Let’s say now we have a requirement of changing the font to some other font. That should be easy right. Go to the Resources tab and change the font to Courier New. You will be surprised to see something like below.

 

Expression Blend 4 : Application Resource

Expression Blend 4 : Application Resource

  • This is because the at value change the resources might not be updated. So let’s hit ctrl + Shift + B. Still the bottom control is not refreshing.

 

Expression Blend 4 : Application Resource

Expression Blend 4 : Application Resource

  • The reason is that when we converted that grid into a User Control it realized that it is referring a resource that it will not have access to when it is converted to a User Control so what it did was created a resource named MyFont in the user Control itself. We can see we navigate to the resource of the userControl2.

 

Expression Blend 4 : Application Resource

Expression Blend 4 : Application Resource

  • So let’s delete the resource of the UserControl then we will get a  message like below. So we will select don’t fix and so the UserControl will still be using the MyFont and will refer the application level resource.

 

Expression Blend 4 : Existing References Found

Expression Blend 4 : Existing References Found

  • Now when you build the application everything should be fine.

The code this post can be found here.

 

Any questions, comments or feedback is most welcome.