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.

 

Working with Data in Expression Blend 4

Element to Element Data Binding

In this section we are going to see how we can use data binding in Expression Blend. We will see how we can create sample data sources and how to use them in data binding.

Data binding is a functionality that both Silverlight and WPF have that helps us set the property of an element to an external data source. That data source can be xml if we are using WPF and can be any CLR object if we are using Silverlight or WPF. It could also be a sample data source. When we apply data binding to an element then that element does not get its value directly but it has to go to some other location for getting its value. This other location can be another element or a database or an xml.

  • Let’s have a look at the element to element data binding. Open Expression blend 4 and create a new Silverlight Project.
  • Now go to the tools pallet and select rectangle.
Expression Blend 4 : Rectangle

Expression Blend 4 : Rectangle

  • Now create a rectangle by pressing the left button of the mouse and dragging it on the artboard.

 

Expression Blend 4 : Rectangle

Expression Blend 4 : Rectangle

  • Now go to the properties of the rectangle and set the horizontal alignment to stretch and left and right margins to 0.

 

Expression Blend 4 : Rectangle Properties

Expression Blend 4 : Rectangle Properties

  • Let’s go back to the tools pane and grab a slider and drop it on the artboard.

 

Expression Blend 4 : Slider

Expression Blend 4 : Slider

  • If you have a look at the properties of the slider you would see values like Maximum (The maximum value of the slider), Minimum (the minimum value of a slider), SmallChange (the value that will change when user has focused the slider and uses the up and down arrow key to change the value of the slider), LargeChange (the value that will change when do a mouse click at any location on the slider track). Let’s set these properties as shown below.

 

Expression Blend 4 : Slider Properties

Expression Blend 4 : Slider Properties

  • Now let’s setup the data binding. There are two ways to set the data binding: one way or two way. In one way data binding only one property can change the other but not vice versa. In two way data binding both the properties can change each other. In this case we want only one way binding so that the width of the rectangle can change on the change in the slider. So let’s select the rectangle and go to the width property and click on the property marker next to it.
Expression Blend 4 : Rectangle Property Marker

Expression Blend 4 : Rectangle Property Marker

 

  • And select element property binding.

 

Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

  • Now our cursor has been moved to the object picker mode so we need to point to the element with which we want to do the property binding. In this case we will move our cursor to the slider and click on the slider.

 

Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

  • Once we will click on the slider we will get an option select which property of the slider we want to bind to and we will select value.

 

Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

  • The moment we do this we see that the width of the rectangle is changed and the Width property has a yellow rectangle around it showing that this property is getting its value from some other location.
Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

 

  • Now we can run the application and see that the width of the rectangle will change as we change the slider value.

 

Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

Two Way Data Binding

In this section we will see how we can create two way data binding. Along with the Slider we will provide a textbox to modify the width of the rectangle.

  • Let’s drag out a textbox on to the artboard.

 

Expression Blend 4 : Element Property Binding Two Way

Expression Blend 4 : Element Property Binding Two Way

  • Now go to the text property of the textbox and click on the property marker and select Element Property Binding.

 

Expression Blend 4 : Element Property Binding Two Way

Expression Blend 4 : Element Property Binding Two Way

  • Select the slider control again and select its value property again as we did in the case of the rectangle. Also we will select the TwoWay Binding so that both the controls i.e. TextBox and Slider can change each other’s value.

 

Expression Blend 4 : Element Property Binding Two Way

Expression Blend 4 : Element Property Binding Two Way

  • Now we can run the application and change the value of the slider or textbox and we will see that the width of the rectangle is changing and the other control’s value is also updated.

Data Binding with Data Sources

 

In this section we will see how we can use data binding with data sources. Data sources can either be xml or any other CLR object. As we know that xml works only with WPF so for this demo we will have to use data binding with sample data. When we work on an actual project we have CLR objects in which data is stored and they definitely follow some schema. So we can build up sample data in Blend to represent that sample data. So let’s get started.

  • Create a new project in Blend. Navigate to the data tab in the right panel. If the data tab is not visible then goto the window menu of blend and select data.
Expression Blend 4 : Data

Expression Blend 4 : Data

  • Click on the Create Data Source.

 

Expression Blend 4 : Create Data Source

Expression Blend 4 : Create Data Source

  • And select New Sample Data. You will also see option to create Sample data using XML or Class. If we have those then we can use them. When we select any of those two options then blend will not exactly use those but take them as a basis for generating sample data.

 

Expression Blend 4 : Add new Sample Data

Expression Blend 4 : Add new Sample Data

  • Give the Sample Data Source some name and select the define in as project. We do want to enable sample data when application is running so keep It checked.
Expression Blend 4 : Add new Sample Data

Expression Blend 4 : Add new Sample Data

 

  • When we click ok we will see that the data source appears in the data tab at project level and we have a collection with properties in it.

 

Expression Blend 4 : Sample Data

Expression Blend 4 : Sample Data

  • We can also see that in the Projects that a new folder is added named SampleData. When we expand it we see that there is a xaml in it which will store all the data and an xsd which is the schema.

 

Expression Blend 4 : Sample Data Folder

Expression Blend 4 : Sample Data Folder

  • If we open the MyAddresses.xaml, we will see that we have some items already added in the data source. We modify their values or add new items.
Expression Blend 4 : Sample Data xaml

Expression Blend 4 : Sample Data xaml

 

  • Let’s go back to the data tab and click on Edit Sample Values as shown in the image below.
Expression Blend 4 : Edit Sample Data

Expression Blend 4 : Edit Sample Data

 

  • We will see something like below. We can edit the values or the types of these properties.

 

Expression Blend 4 : Edit Sample Data

Expression Blend 4 : Edit Sample Data

  • Let’s rename the properties as shown below. Also lets change the specification of the Address property as shown below.
Expression Blend 4 : Edit Sample Data Property Type and Format

Expression Blend 4 : Edit Sample Data Property Type and Format

 

  • Also similarly change the Format of name to Name. When we do that if you go back to Edit Values we will see that the data is has been populated according to the format selected.

 

Expression Blend 4 : Edit Sample Values

Expression Blend 4 : Edit Sample Values

  • Let’s add email, phone number  and CustomColor properties.Also modify the format accordingly
Expression Blend 4 : Edit Sample Values Format

Expression Blend 4 : Edit Sample Values Format

 

  • And we will see data something like below.

 

Expression Blend 4 : Add Properties in Sample Values

Expression Blend 4 : Add Properties in Sample Values

  • Now let’s start using this data that we have created. Drag and drop the Collection onto the artboard.
Expression Blend 4 : Create Databound ListBox

Expression Blend 4 : Create Databound ListBox

 

 

  • And a listbox will be automatically created. And each entry will show all the fields. Also the yellow rectangle around the datasource shows data binding.

 

Expression Blend 4 : Create Databound ListBox

Expression Blend 4 : Create Databound ListBox

  • Let’s improve the look of the List Box by the use of Data Template. Right Click the ListBox and Go to Edit Additional Template à Edit Generated Items (ItemTemplate) à Edit Current

 

Expression Blend 4 : Edit Generated Items

Expression Blend 4 : Edit Generated Items

  • We would something like this. Let’s delete the Color textblock as we do not want to display the color in this way. When we delete that textblock you would see that that textblock is deleted from each item and that’s the way templates work.

 

Expression Blend 4 : ListBox DataTemplate

Expression Blend 4 : ListBox DataTemplate

  • Now let’s select the listbox from the breadcrumb bar and stretch it.
Expression Blend 4 : ListBox DataTemplate

Expression Blend 4 : ListBox DataTemplate

 

  • Now let’s go back to the template and change the  orientation of the stackpanel to horizontal from vertical. And then build the solution. We will see something like below.

 

Expression Blend 4 : StackPanel Orientation

Expression Blend 4 : StackPanel Orientation

  • Lets give specific width to all the textblocks and we will see a clean layout.
Expression Blend 4 : StackPanel Orientation

Expression Blend 4 : StackPanel Orientation

 

  • Let’s delete all the textblocks except the Name TextBlock. Then let’s go back and select the listbox and reduce its width.

 

Expression Blend 4 : DataContext

Expression Blend 4 : DataContext

  • Now go to the data tab and select the view mode to details view.

 

Expression Blend 4 : DataContext

Expression Blend 4 : DataContext

  • Now let’s drag the Name field on to the art board. We will see that a grid is created along with textblock as its child. Now whenever we select the item in the listbox we will see that the content of the textblock in the grid is changing. This happens because the grid that got created has a concept called Data Context. The grid has its data context set to the list box. So as soon as an item is selected in listbox then the the value changes in the grid as the items in the grid have already specified what item of the listbox they want to display. We can other fields as well in the grid and see that their value change as the selection of the listbox changed.

 

Expression Blend 4 : DataContext

Expression Blend 4 : DataContext

  • When we run the application we will see something like below.

 

Expression Blend 4 : Run App with Sample Data

Expression Blend 4 : Run App with Sample Data

  • Lets go to the grid à Background à Property marker à Data Binding. We will a window like below.

 

Expression Blend 4 : Data Binding Background

Expression Blend 4 : Data Binding Background

  • Select Customcolor string and the background of the grid is bound to the color string of the selected item. The value conversion is going on in the background.

 

Expression Blend 4 : Data Binding Background

Expression Blend 4 : Data Binding Background

  • When we run the application we see something like below.

 

Expression Blend 4 : Data Binding Background

Expression Blend 4 : Data Binding Background

The code for this post can be found here.

 

Any questions, comments or feedback are welcome.

 

Microsoft has been offering data binding for all its user interface applications but it was an assumption that all the data binding that will happen will always be related to database. However WPF and Silverlight have a broader view assuming that the client side code is often not connected directly to the database. And Silverlight goes a step further by not providing the ADO.NET classes to connect to the database directly. This makes sense because Silverlight is used to design web pages and most organizations do not want to put their database onto the internet for obvious security reasons. So the way data comes into a Silverlight application is in the form of objects or xml. So the data biding framework in Silverlight focuses on objects. So the purpose of data binding is to connect the features of UI to the properties of the objects. Databinding can be used with nearly any property of any element.

Binding Expressions

To bind the property of a user interface element we use the binding markup extension. As you can see in below markup extensions are specified in the curly braces which are evaluated at runtime.

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname}”/>

 

So this markup binding extension binds the path property of the TextBox to property named Surname and the value of this TextBox text property is evaluated at runtime. Data binding will always connects 2 properties: the target property (generally the user interface property) and the source property (a dependency

Data Context

Now as we saw in the last section that we need to provide the data binding along with the source and target property. So if want to bind multiple targets then we do not need to write the source individually for each of the target property as multiple targets can use the same source for data binding. Let’s have a look at this with an example.

Let’s create a Person class in you user interface with the following Fields as shown below.

namespace DataBindingInSL

{

public class Person

{

public string GivenName { get; set; }

public string Surname { get; set; }

public double Age { get; set; }

}

}

 

Now we want to bind these properties in the User Interface. So lets add the following code in the code behind file of the view.

namespace DataBindingInSL

{

public partial class MainPage : UserControl

{

Person src = new Person { GivenName = “Max”, Surname = “Smith”, Age = 34 };

 

public MainPage()

{

InitializeComponent();

 

this.DataContext = src;

}

}

}

 

Now we are setting the DataContext of the User Interface as src.  By setting the DataContext property at the root element we have made the properties available at the all the elements in the tree as the DataContext in Silverlight cascades down the tree.  We could also set the datacontext on any panel as well and in that case the datacontext will apply only to the panel and its children. Once we have set this DataContext, it becomes the implicit source for all the user Interface elements. So in the View all we need to do is the property name in the binding path and the element will pick up the property from the source i.e. Data Context. Add the following code to the xaml of you SL app.

<Grid x:Name=”LayoutRoot” Background=”White”>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,38,0,0″ Name=”label1″ VerticalAlignment=”Top” Width=”120″ Content=”Name” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,38,22,0″

Name=”textBox1″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=GivenName}” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,95,0,0″ Name=”label2″ VerticalAlignment=”Top” Width=”120″ Content=”Last Name” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname}”/>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,153,0,0″ Name=”label3″ VerticalAlignment=”Top” Width=”120″ Content=”Age” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,153,22,0″

Name=”textBox3″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Age}”/>

</Grid>

 

When you run the application you would see that all the TextBox will display the values that are picked up from the bindings.

Data Context Silverlight 4

Data Context Silverlight 4

Right now the data is flowing in only one direction i.e. from src to the User Interface. If we want the data to flow in both the directions then we need to specify the mode as TwoWay in the Binding as shown below:

Text=”{Binding Path=Age, Mode=TwoWay}”

 

Binding Updates

As we saw in the last section that the User interface is updated with the values that are set in source at load time but when the values are updated at a later point in time then also the data binding model of Silverlight can reflect the in the source to the user interface when the data source raises change notification. The change notification can be raised after implementing the INotifyPropertyChanged.

So let’s implement the INotifyPropertyChanged interface in the data source so that whenever the source changes the User Interface is updated along with it as well. This interface has only one event which is raised whenever a property changes in the class. So change the code of the Person class as below along with the implementation of INotifyPropertyChanged.

public class Person : INotifyPropertyChanged

{

public string GivenName { get; set; }

public string Surname { get; set; }

private double _age;

 

public double Age

{

get { return _age; }

set

{

if (value != _age)

{

_age = value;

OnPropertyChanged(“Age”);

}

}

}

 

public event PropertyChangedEventHandler PropertyChanged;

 

private void OnPropertyChanged(string propertyName)

{

if (PropertyChanged != null)

{

PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

}

}

}

 

Here after the implementation of INotifyPropetyChanged we change the code inside the set method of the Age property to call the OnPropertyChanged method which in turn raises the property changed event. So now when the Age property is changed the change will reflect in the User Interface as well. Change the code of the cs and xaml file to as shown below and you will be able to see the update in the property.

 

Silverlight 4 Binding Updates

Silverlight 4 Binding Updates

Data Template

We have seen the example of an adhoc binding in the previous section but Silverlight has a more structured way of defining the same using Data Template. A Data Template is similar to a Control Template. Just as the control Template determines how the Control should like, in a similar way a Data Template determines how the particular data would look like. Data Templates can be used by ItemsControls (ListBox, etc) and ContentControl (Buttons, etc). A Data Template will work at any place where a Content Model is in place.

Whenever there are custom properties in a class then it’s a good idea to define a Data Template in xaml so that the control knows how to display those types.  Let’s see this working in code.

<UserControl.Resources>

<DataTemplate x:Key=”dataTemplateBinding” >

<Grid>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,38,0,0″

Name=”label1″ VerticalAlignment=”Top” Width=”120″ Content=”Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,95,0,0″

Name=”label2″ VerticalAlignment=”Top” Width=”120″ Content=”Last Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,153,0,0″

Name=”label3″ VerticalAlignment=”Top” Width=”120″ Content=”Age” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,38,22,0″

Name=”textBox1″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=GivenName, Mode=TwoWay}” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname, Mode=TwoWay}”/>

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,153,22,0″

Name=”textBox3″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Age, Mode=TwoWay}”/>

</Grid>

</DataTemplate>

</UserControl.Resources>

<Grid x:Name=”LayoutRoot” Background=”White”>

<ContentControl Content=”{Binding}”

ContentTemplate=”{StaticResource dataTemplateBinding}” />

<Button Content=”Older” Height=”23″ HorizontalAlignment=”Left” Margin=”43,242,0,0″

Name=”button1″ VerticalAlignment=”Top” Width=”75″ Click=”button1_Click” />

</Grid>

</UserControl>

Binding to Collections

Instead of binding to one instance we can bind a control to a collection. Let’s modify the MainPage as below to create a collection of Person.

public partial class MainPage : UserControl

{

Person src = new Person { GivenName = “Max”, Surname = “Smith”, Age = 34 };

List<Person> people = new List<Person>();

 

public MainPage()

{

InitializeComponent();

 

people.Add(src);

people.Add(new Person { GivenName = “Steve”, Surname=”Gaylon”, Age=44};

people.Add(new Person { GivenName = “John”, Surname=”Miller”, Age=14};

 

this.DataContext = people;

}

 

private void button1_Click(object sender, RoutedEventArgs e)

{

src.Age += 1;

}

}

 

Let’s change the xaml as below:

<UserControl.Resources>

<DataTemplate x:Key=”dataTemplateBinding” >

<Grid>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,38,0,0″

Name=”label1″ VerticalAlignment=”Top” Width=”120″ Content=”Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,95,0,0″

Name=”label2″ VerticalAlignment=”Top” Width=”120″ Content=”Last Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,153,0,0″

Name=”label3″ VerticalAlignment=”Top” Width=”120″ Content=”Age” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”40,38,22,0″

Name=”textBox1″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=GivenName, Mode=TwoWay}” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”40,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname, Mode=TwoWay}”/>

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”40,153,22,0″

Name=”textBox3″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Age, Mode=TwoWay}”/>

</Grid>

</DataTemplate>

</UserControl.Resources>

<Grid x:Name=”LayoutRoot” Background=”White”>

<ListBox ItemsSource=”{Binding}”

ItemTemplate=”{StaticResource dataTemplateBinding}” />

<Button Content=”Older” Height=”23″ HorizontalAlignment=”Left” Margin=”43,242,0,0″

Name=”button1″ VerticalAlignment=”Top” Width=”75″ Click=”button1_Click” />

</Grid>

 

Collection Updates

The INotifyPropertyChange will work only when a property is changed but when a collection is changed we need to implement the INotifyColectionChanged. We can either use ObservalbeCollection<T> or implement this interface to get the update whenever a new item is added to the collection.

Let’s add a new button along with a new event handler to add a new item to the collection so we need to change the xaml and cs file to as below:

private void button2_Click(object sender, RoutedEventArgs e)

{

people.Add(new Person { GivenName = “Scott”, Surname = “D”, Age = 62 });

}

 

<Button Content=”Add Item” Height=”23″ HorizontalAlignment=”Left” Margin=”325,182,0,0″

Name=”button2″ VerticalAlignment=”Top” Width=”75″ Click=”button2_Click” />

 

Now replace the List<Person> with ObservableCollection<Person>.

ObservableCollection<Person> people = new ObservableCollection<Person>();

 

And that is it. Now whenever you click the Add Item button a new item will be added to the collection and also the ListBox will be updated.

 

Grouping

If we want to group the data based on some criteria then we can use the CollectionViewSource. This groups the items based on the property specified of the items.

<UserControl.Resources>
    <CollectionViewSource x:Key="mySource" Source="{Binding Path=RawItems}">
        <CollectionViewSource.GroupDiscussions>
            <PropertyGroupDiscription PropertyName="EventTrack" />
        </CollectionViewSource.GroupDiscussions>
    </CollectionViewSource>
</UserControl.Resources>

 

DataGrid internally understands grouping but the ItemsControl does not. So this is an advantage as by using the ItemsControl we can have our own custom visualizations.

 

Silverlight 4 Grouping

Silverlight 4 Grouping

When we wrap a collection in a collection view source, it provides a property known as groups.  Normally we can bind to a wrapper but we can bind to the groups property instead.

<ItemsControl ItemsSource="{Binding Path=Groups, Source={StaticResource groupSource}}">
    <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding Path=Items}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
</ItemsControl>

Silverlight 4 Grouping

Hierarchical Binding

The basic ability to bind with hierarchical controls is provided by the HeadedItemsControl class. HeadedItemsControl derive from ItemsControl so the binding works in nearly the same way. The difference is in the ItemTemplate property as need to refer to HieraricalDataTemplate instead of a normal DataTemplate. The Hierarchical Data Template has one feature. It too has a ItemsSource Property.

<sdk:HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
    <TextBlock Text="{Binding Path=Label}" />
</sdk:HierarchicalDataTemplate>

Silverlight 4 Hierarchical Binding

 

Find the source code ralated to this post here.

 

Any questions, comments and feedback are most welcome.