In this post we will talk about building RESTful services. However before we do that I would recommend reading the previous part of the series

 

 

One of the biggest roadblock in developing REST base systems are influencing technical factors like Object Oriented design, abstractions or the technologies that the architects are familiar with. This situation could even become worse if the architect has good technical background in web technologies like MVC and thinks about implementation in these technologies while designing REST services.

 

Design Workflow for Agile Board

We need to think independently of any technology or other influential factors that might corrupt our design. We should not think about classes or methods while designing a RESTful system and I think the best way to do that is stay away from the computer and use pen and paper for the design purpose. To practice that let’s think of the process of managing the task tracking workflow with the example of an agile board.

Agile Board

Agile Board

 

Let’s think about the process of managing an agile task board. When we want to design the workflow, the first thing that we look at are the elements that enable the workflow. The elements that enable the workflow are:

  • Agile board – The agile board is divided into 5 sections to do, design, code, test, done. When a new task is created it would go in the “to do” list. When a team member will start of work on a task then it would be moved to the “design” list and so on to the different lists.

 

  • Sticky notes – These are the communication interface for communicating among the team members as well outside the team as well. The sticky note will have the story number, description, estimate and Assignee.
Sticky Note

Sticky Note

This would seem like a very simple workflow but we are making an assumption here that all the team members know how to move tasks across the agile board. We are also expecting the team to know that new tasks will be going in the “to do” as well. What if we change the process then we would have to share the same knowledge with complete team. We could eliminate all of this by a simple solution. We could define icon for each of the lists on the agile board.

Agile Board With Icons

Agile Board With Icons

We also add the corresponding items to the sticky node as well then we could easily track the current stage of the task. Now in the sticky we could see the icons of the various stages of the task starting from “to do” till “done”.

Sticky Note Icons

Sticky Note Icons

We can track it by simply crossing out the stage which the task has already passed through. In the image below it clearly shows that the task has passed though the “to do” and “design” list and currently in the code phase.

Sticky Note Stage 3

Sticky Note Stage 3

Whenever any changes happen in the sequence or number of stages we just need to update the board and the sticky and no other communication is needed to anyone. Suppose we remove the design phase from our systems. Now we could simply update the board and the sticky and everyone using it would be able to understand as what needs to be done. Whenever a task is being moved then the team member crosses off the icon of the current state and look at the next icon and move the task to that list.

Agile Board Without Design

Agile Board Without Design

Sticky Note Without Design

Sticky Note Without Design

Now if you image this kind of change to be done in an RPC system then it would require versioning and redeployment of the clients so that they are aware that they have to call a different method.  And this might be a reason for the failure of the RPC system. However in this model our client workflow hasn’t changed at all whereas the system workflow has changed. And hence it adheres to the RESTful principle where I could change the system workflow without changing the client workflow. The client workflow is still the same where the team member has to cross off the current matching icon and look for the next matching column on the board and place the sticky note in that column.

 

Software design for Agile Board

Now when we are comfortable with the idea and workflow of a physical agile board, we can go ahead and design for a software based agile board. Like any software system before we start working on the software we will list down a few high level requirements. Since this is an example we will keep the requirements pretty simple:

  • Add new tasks to the backlog
  • Move task to design
  • Move task to code
  • Move task to test
  • Move task to done

State Transitions

We have a simple domain hence we have a simple state transition model. From the starting state we could reach to different states each of which is a collection tasks. You could see in the diagram below that we have captured two types of information:

  • Application states such as entry and task collection. This will be useful when we will design the media type later in the module.
  • States that a task can go through like to do, design, etc. This information will be used in the next section of the module to identify resources.
State Transitions

State Transitions

Using this state transition our client would have to know about only one url that is the entry url and then the client should be able to discover all the other services from there.

 

Identifying the Resources

Now let us create the resources corresponding to the states for the application. The resources with their urls are shown below in the image.

Resources

Resources

  • /tasks – The entry point of the application. It supports the following operation

o   GET – fetches the hypermedia elements for navigation and addition of a new bug to backlog.

  • /tasks/todo – The list of the tasks that have not been started yet.

o   GET – fetches the list of tasks in the todo list

o   POST – adds a new task to the todo list

  • /tasks/design – The tasks that are currently in the design phase

o   GET – fetches the list of tasks in the design list

o   POST – adds a new task to the design list

  • /tasks/code – The tasks that are currently in code phase

o   GET – fetches the list of tasks in the code list

o   POST – adds a new task to the code list

  • /tasks/test – The tasks that are currently in test phase

o   GET – fetches the list of tasks in the test list

o   POST – adds a new task to the test list

  • /tasks/done – The tasks that are done.

o   GET – fetches the list of tasks in the done list

o   POST – adds a new task to the done list

 

Designing the representation of Resources

Once we have identified the application states, the transitions between them and mapped them onto the Uniform Interface element of resources and self-describing messages then we need to figure out how we want to represent our resources.

We have multiple options to decide from and Mike Amundsen in his book on Hypermedia API design, has broken these options into 4 questions.

 

  1. What format do we want to base our representation on?

This can be anything however the most common formats being used by the API today are JSON, XML, etc. We could choose to support multiple base formats as well.

  1. What type of state transfer will the API support?

The various types of state transfers could be

  • Read Only – In this type of state transfer, the client does not transfer any data to the servers.
  • Predefined – In this type of state transfer, the client is aware of the valid transfer elements beforehand via the media types shared by the server.
  • Ad-hoc – In this type of state transfer, the details of the valid transfer elements id shared with the clients in a representation.

 

  1. How will the domain elements map onto the base format?

There are 3 ways in which we could map the domain elements onto the base format.

  • Specific – In this style we create domain specific elements and attributes. For example in case of an XML based format we could create a task element having a title attribute.
  • General – This style as you might have guessed will be bound to a generic domain. It will not be specific to our business domain. One of the majorly used domain media type is Atom.
  • Agnostic – This style we would have a media type is completely unrelated to any specific business domain like HTML.
  1. What will be the application flow?

Application flow are the elements that allows a client to recognize and respond to possible state transitions. It could also be thought of as how the representation format will tell a client that a links exists and what the client can do with it. The application flow identifiers could be:

  • None – The client does not have any flow identifiers.
  • Intrinsic – The media type have built in elements for representing links and expressing the semantics.
  • Applied – The media type does not have the full capabilities to express the media type identifiers. This opens up the opportunity for the designer to apply attributes to the elements to express the identifiers. The example for this application flow could be seen in rel and class attributes of HTML.

 

Task Tracking Service Representation

Let’s make the choices for designing the task tracking service:

Base Format = HTML (since it’s easier to test)

State Transfer = Ad-hoc (since we will be using HTML forms to provide state transfer information to the clients. This way the client will just have to fill in the values and submit the form.)

Domain Style = Agnostic (Since HTML is domain agnostic)

Application Flow = Applied (Since HTML is a domain agnostic language so we will have to apply the custom application flow identifiers using an element of HTML)

 

Based on the above information and decisions we would need the elements for:

  • List of tasks
  • Link template to add a task
  • Link template to move task to to do
  • Link template to move task to design
  • Link template to move task to code
  • Link template to move task to test
  • Link template to move task to done
  • Navigation links

The advantage of using the Hypermedia design is that not all these elements will exits for each of the states. When a task is in to do state then only the design link will be visible and so on. This is how a hypermedia enabled design will help the client in deciding the right thing to do without any prior knowledge.

 

Mapping domain style to base format

Below is a table showing the mapping of domain style onto the base format which is HTML here. This is really useful way to document the representation. Here we are capturing all the details that client will need to recognize. Since in rest we do not have service description hence the client will look for a documentation top understand the representation.

 

Attribute Value AppliedTo Description
id task DIV Container for task state elements
name id INPUT[hidden] The task identity. Found as a child of FORM.move
  title Input[text] The task title state transfer element. Found as a child of FORM.new
class all UL List of tasks
  title SPAN Task title. Found as child of LI
  description SPAN Task description. Found as child of LI
  new to do FORM Application flow identifier for adding a new task to to do
  next FORM Hints to the client for ideal next state transition. Should be used with FORM.move class
rel index A Navigate to index resource; should not be more than 1
  to do A Navigate to to do resource; should not be more than 1

 

Id – is used to represent a unique data element or block in a representation. We are using it here to identify the various state formats in the task tracking representation.

Name – is used to identify a state transition element within a representation. For example input elements.

Class – is used to identify any non-unique data element or block in a representation. Here we have used title to identify a task in the task list. It can have multiple value separated by space. This is used by the client to show available transitions instead of showing the same one dimensional list.

Rel – is used to identify a non-unique process flow element within the representation. Here we have used rel to identify the purpose for the link. It can have multiple value separated by space. This is used by the client to show available transitions instead of showing the same one dimensional list.

 

Sample Markup

The table provides a good visualization on how the representation looks like however nothing beats a dummy markup as shown below.

Sample Markup

Sample Markup

I have not provided any href and action attributes since the actual link value do not matter to the client. In REST url is not the most important part.

Also you would notice that I have specified move active next in the class value for the form. This would tell the client that it could show the optimal path as per the workflow.

 

Modifying the workflow dynamically

We will now go ahead and modify the workflow and remove the design phase. This will eliminate the transitions from todo to design, design to todo, design to code and code to design. It will add new transitions which are from todo to code and code to todo.

Modified Workflow

Modified Workflow

This will not have any impact on the clients since the clients do not need to know about the urls. The only thing that a client would have to know is about the new relationship values of both forms class and the rel attribute anchors since we removed a relationship value called design. Even if the client do not understand these, still the client doesn’t necessarily need to crash.

 

As per the new design a task in the todo list will never see a link to move it to design anymore. This design lets the client see only the valid operations that could be performed.

 

Versioning

Generally rolling out the version 1 of a service is easy and difficulties come in rolling out new versions and fixing the bugs in the previous versions as there may be many clients using it. In REST the contract is the uniform interface.

Versioning within representation

In this form of versioning we do not need to do anything in form of formal versioning as we would be doing the versioning inside the representation. The core concept lies in the fact that the service could add whatever they want and clients would ignore whatever they do not understand.

Versioning the representation

When the semantics of a representation change as a result of the rename or deletion of an element then we might need to version the representation. Here we could make use of content negotiations to make sure the clients are able to get the representations they need in order function properly. We could transfer this representation metadata from the client to server by:

  • Embedding this information as part of custom media type name.
  • Using a parameter on http accept header like version or profile
  • Using custom http header

Versioning the resource

When the service is no longer able to keep the mapping between the resource and its associated profile then we would have version the resource itself. This would more creating a new resource rather than versioning the old one. But it will manifest in the resource identifier which is url in http terms.

 

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 I am going to start talking about Windows Presentation Foundation or WPF in short. I hope you guys find this series interesting and informative.

So once you have decided to Learn WPF do not a step back or leave it in between because once learn the full power of WPF you would know how to create windows and web applications with awesome graphics easily.

What is WPF

At the very basic level WPF is just a framework which is used for building Windows application. Before WPF the windows applications majorly used couple of dlls (User32 and GDI32). These were the 32 bit versions of their 16 bit parents who were introduced in mid 1980s. Now if you have worked in Windows Forms you would know that the interface that you used to create an application were just a wrapper around these dlls.

Why to Use WPF

But WPF does not use GDI32 and barely uses USER 32. It’s not just a wrapper around these dlls. WPF was introduced as part of .NET 3.0 framework. It contains both managed and unmanaged code. It was designed from scratch so that .NET languages could be used to program in WPF. You would need to use .NET to use WPF as these are no public unmanaged API offered for this. This provides a lot of advantages as you don’t have to struggle with the issues you face using a wrapper around the unmanaged code. You need to be either on XP SP3, Vista, Windows 2003 or above to use WPF.

You might still be wondering as to what’s the thinking behind creating a new framework such as WPF when we already have a Windows Forms for creating a Windows application which is used by lot of people and huge numbers of people are skilled in it. The reason is Microsoft did not want to lag behind after all the thinking and market changes that have happened since the initial framework for creating windows application was launched and was really hard to keep the future versions compatible with it ancestors. As whenever an upgrade happens to a new version, people expect it to be really smooth. At the time when the initial Windows application development architecture was designed then the computer was not capable of so much processing power or graphical capabilities. Nowadays the computer hardware capabilities have progressed in leaps and bounds. So there was a need to design a framework that could utilize that capability. WPF provide the interface using which could design rich graphical user applications without having to deal with complexity of the directx or OpenGL code. Now the old dlls that were used in creating WPF application does not provide any way of utilizing the directx capability unless you are ready to program in directx or OpenGL.

WPF is also auto scalable by default which means that if you run you WPF application on machine with different DPIs you application will automatically scale its contents according to the DPI and resolution of the machine. You can simply see that in action by simply creating a WPF application and zooming into it. If you zoom into other applications or graphics in your system you see it getting pixelated but with WPF you will not see that.

As the times have changed, people’s expectations from the applications have changed. A decade ago people were okay with console application running on their computers but today they want a rich and cool user interface to work with. The games that we see now have reached that level and same can be achieved for windows application using WPF. You can make your complete application be blended into a single theme that you want, like your company logo colors, etc.

It was easy to make websites carry branding before using HTML as anyone without any programming experience can also use HTML to make a nice looking website which corresponds to your company. WPF also utilizes the power of Markup to give the designer the ability to do more and be part of the graphical interface easily. The use of markup makes the Windows apps move forward to the level of web apps styling easily.

Now in today’s time we do have the option to create a visually appealing application but the problem is to integrate all those component together that make that visually appealing application. We do have HTML for Web, Win32 with easy interface for Windows applications, DirectX or OpenGL for developing rich graphics application and Flash for designing rich vector graphics but all these have different capabilities and it’s really difficult to integrate all of them together. But WPF provides us with a single integrated solution for it. The capabilities that WPF provides are already available with the technologies I mentioned before but the advantage with WPF is that it provides all these capabilities at one place and integrated.

WPF Architecture

As you could see in the image below the basic architecture of WPF is designed with directx at its base above kernel.

 

WPF Architecture

WPF Architecture

WPF utilizes the 3D hardware your system to render 3D or 2D graphics on your system. On top of Directx level is the most basic component of WPF called as the Media Integration Layer or MIL. This is the component that takes the various types of media like the bitmaps, images, videos, etc and renders them all into a single directx surface. This MIL is unmanged code because it has to talk to directx and there need to be lot of calls need to be made to the com interface while dealing with directx and directx uses a lot com calls as they are cheap in its context but when you come to .Net code that is not the case. Using com from needs you to go through the interop layer and made thousands of call through the interop layer wil burn a lot of CPU cycle. So that’s the advantage to MIL, as to render a complex shape you make just one interop call to MIL and MIL then internally makes thousand and hundreds of com calls to DirectX to render that shape. Above the MIL we have two dlls for WPF. Presentation Core and Presentation framework. Presentation core is the public face of the MIL, it provides the .NET API that exposes he rendering services of the MIL. Above this presentation core we have the Presentation Framework layer that provides the high level services. Presentation layer provides the concept of Controls, layouts, data binding, animations, etc. As a WPF developer you would be spending most your time with Presentation framework. And you would be using the Presentation Core at the time graphics programming. The reason for separation of these layers is to make the rendering available without being dependent on WPF features.

What is XAML (Extensible Application Markup Language)

When you create a WPF application you would see two code files in your project. One is the regular .cs or .vb file which is your standard code file and the other one is you XAML file which is something new to WPF. Now a XAML file looks a lot like a XML file. Now if you would have created a WPF application in the past then you would have seen XAML. I would like clarify here that XAML is independent of WPF and WPF is independent of XAML. They are separable. XAML is nothing but a language to create .NET objects and this means we could what we do XAML in C# or VB code as well. It’s on you to decide what to use when. So if you see the image below you would find XAML and its corresponding C# code.

 

WPF XAML

WPF XAML

Now XAML uses the type converter infrastructure to map the string and integer values to map to the property values at the run time. And it also XAML in knows as to what does the content contain. The most simple and important thing about XAML is that it creates objects and sets properties. Also when you create a WPF application and open any of the XAML files you would see something like this at the top of it.

 

WPF XAML

WPF XAML

This is simply references to the namespaces so that you could use the components in that namespace. If you are referencing any namespaces in xaml then this is the place to add them. Microsoft took a long time in developing xaml and figuring out how xaml does what it actually does.

UI Tree in WPF

The XAML interface objects are built as trees of objects. As you would see in the code below,

 

UI Tree in WPF

UI Tree in WPF

Here we have root element which is a Window. This Window contains a single child which is Grid. The grid contains other children and it’s the Grid job to assign as to where these children are placed in the layout. So you see a tree root structure.

WPF provides two tree structures: The Logical Tree and The Visual Tree. The visual tree will be of use if you are concentrating on the presentation.  The Visual Tree is simply the super set of the logical tree. You can see below that all the children of the logical tree are present in the visual tree. So these two trees are the different views of the same set of the objects that make up the UI. The logical tree provides you with the detail to focus on the core structure of the User Interface and to ignore the details of how exactly it is presented.

 

Visual and Logical Tree in WPF

Visual and Logical Tree in WPF

 

Events and Commands in WPF

There are two ways for handling input in a WPF application: Events and Commands.

Events are very closely tied into the visual tree. Any Mouse or keyboard inputs originate from an element. The one with the focus – keyboard input and the one with the stylus – mouse inputs. As we have already seen that the visual tree was pretty complex for just a couple of elements, you could imagine the complexity if there are a lot of controls in your visual tree. It would become all the more complex if you add an event handler to every element of the visual tree to receive the inputs.

To save us from this complexity WPF has Event routing. Event routing allows the ancestor of the element to handle the event. Now there are two types of routing in WPF – Tunneling and Bubbling.

Tunneling starts from the root of the visual tree and goes through the tree and reaches the element to which the event is targeted. Generally Preview events are the ones that tunnels. Bubbling Event works in the opposite direction. It starts from the Element and goes up the parent to the root. Main events are the one that bubbles. The concept behind providing a preview is to give the parent element a chance to handle the originating event.

For example if you have a button in the Grid and you want to handle the Mouse down event. Now if you want Grid to handle the event before the Button does you need to use the Preview events (PreviewMouseDown) and if you want the button to handle the event first then you should use the main event (MouseDown).

Commands on the other hands help you do the same action through multiple inputs like a keyboard shortcut, stylus gesture, menu clicks, button clicks, etc. So that multiple inputs can use the same command if they want same job to be accomplished.

Controls

Controls in the previous versions like Windows forms correspond to behavior as well and presentation of an element, whereas in WPF controls are a bit different. Let’s take a Button for Example, a button has a click event which is an API feature related to the user interaction. It also supports the content Model for composition which is also an API feature. It supports Focus which is an interactivity feature. It can be associated with Command which is again an API feature. It also supports the Automation API which makes it accessible to screen reader, automation testing, etc. But there one thing that a WPF button cannot do which its activex, Win32 counterparts can.

A WPF button is a lookless control which means it has no intrinsic look and it does not know how to present itself. The look of a control in WPF is controlled a distinct entity known as Template. So button may look like a circle or a star but it will still support all the API and interaction features. Let see how this works in code.

Use the following code in a WPF application and you would be able set the template property for the button control.

 

Controls WPF

Controls WPF

 

You should notice a few things about the code above.

  • We have defined a ControlTemplate for the Button which changes the look and feel of the Button.
  • The Fill property of the Rectangle in the ControlTempalate is done using the TemplateBinding with Background. What this does is binds the Fill of the rectangle to the Background of the Button. So whatever background we set on the Button becomes the Fill of the rectangle.
  • You would also see Curly braces around the TemplateBinding which signifies that it a special property. This is considered to be Markup extension. Markup extension signifies that it would be decided at runtime as how this property will work. This syntax means that we need to create an instance of the TemplateBinding Class with Background as a string and a constructor parameter and WPF expects the whole thing inside the curly braces to derive from Markup extension base class. Now this Base class provides an abstract method named Provide Value. This method would be called at runtime to decide what value will the Fill property have a runtime. A custom markup extension can build depending on what we need.
  • You would also see the same thing as Rectangle Fill Property for TextBlock Text Property.

Lets change the code to look something like below:

 

Controls WPF

Controls WPF

You would now notice that the Content of the Button is now and Ellipse and to make that as the content of the button we need to need to use a ContentPresenter instead of a TextBlock because a TextBlock is a primitive control and it could only display text. So to display the any content we need to use the ContentPresenter and TemplateBind the Content property. So if we want any other content we could do that now.

Primitive Elements in WPF

As you have seen that the controls do not define their own look, so are you not wondering as to how do anything appear. Just as we saw above a button control derives its look from its template, and the controls derive their appearance from there templates so is there an infinite loop to look for the template?

That’s not the case. Only the controls have a template and most elements in WPF are not controls. Only the Controls that derive from the Controls Base class are supposed to have some kind of interactive behavior. Examples of controls are Button, TreeView, ListBox, TextBox, etc. Only the Controls derived from the Controls class have a template because it’s the Control class that introduces the template property.

Examples of Elements are Rectangle, Ellipse, Image, TextBlock etc. These do not derive from Controls and are more primitive and derived from FramworkElement (Base class for Controls as well). These elements do not have a template of their own and as they are more primitive and there presentation is specifically designed. Primitive elements are the one that provide an intrinsic appearance for them. These can be also considered to be lookful controls. Primitive elements do not have any intrinsic behavior of their own and you have to add the events and handler to get some interactive behavior from them.

You might note that a lot of elements that do not derive from the Control Class are placed in the namespace System.Windows.Control. This is confusing you should keep in mind that the Elements that derive from the Control Class are Controls.

Layout in WPF

The new and useful feature in WPF is the Layout primitive also known as Panels in have. The Panles are required at places where we need to position multiple childrens. The panels available in WPF are Grid (Advanced table/grid-based layout), Canvas (Fixed layout, supports anchoring), StackPanel (left to right and top to bottom layout), DockPanel (Docking layout) and WrapPanel (Flow-like formatting).

Flowed Text in WPF

WPF provides a flow layout for the text so that the text fits into whatever space is available. A Flow document has a HTML-like feature set and it has reader controls.

In a flow document we can integrate any mixture of text styles, user interface elements, HTML features (Lists, floating data, etc). WPF makes it much easier to render text in columns than HTML which is very useful because columns allow shorter line lengths which improves reading speed.

Data Binding in WPF

When you come across data binding you would think about databases or collections but in WPF databinding has much broader scope. Data Binding can be used at times when you want to present any data to the screen. WPF data binding either connects to objects or xml. WPF never assumes the presence of a database. Infact you never use data binding directly with database. You load the data from the database into your domain objects, datasets, etc and then data binding presents them on screen.

Data Binding brings up a very interesting concept in WP Known as DataTemplate. Similar to ControlTempalate which defines how a control should look like, DataTemplate defines how the data should look like. So you define the template for a particular class of application and the template can be used to present the data on the screen.

Its because of the power of Data Template that WPF does not contain a DataGrid as you could define how the data should be presented on screen.

Deployment

There are multiple ways in WPF to deploy the application to the user machine:

  • Build a MSI installer
  • Click Once deployment but is supported only in full trust environment.
  • XBAP – XAML Browser application. This is like the Click once but imparts the experience like the java applet style. This does not require full trust as it runs in browser.
  • .NET 3.5 SP1 deployment options
    • Client only framework – option to deploy only a part of the framework. Can be deployed in following ways:
      • Setup bootstrapper – this installs the framework before going to the normal windows setup
      • Deploy via Click Once

The code for this post can be downloaded here.

Any questions, Comments and feedback are most welcome.