Djaka PM's Weblog

Self Notes

Posts Tagged ‘unity framework

Composite WPF Application Part 3 – The Data Context

with 3 comments

This article will dig more about Data Context that used in the previous Part 2
Base on the MVVM concept i have learned so far, that the ViewModel is always be the View data context. I may keep this in mind while designing the UI using xaml.

In my humble opinion the models on an application should divide into two types; business model and UI model. For complex application with complex UI structure the separation of the models is a must; for smaller application might not need to do this ( e.g you have separate UI model class and Database model class). The main concern to separate the models is that UI models might need something else such as, it must be aware to its fields changes; so it will be an additional code beside the usual getter and setter or properties in .Net term.

Reusing the single module application from Part 2. We will modify some parts and add some new toys
the great Data Context and Data Binding.

What is Data Context?

From my point of view a Data Context is a simple class or object that backed-up the UI logic and stored your view state.
In the realm of MVVM; i have learnt so far as i mention before the ViewModel is always be the View data context.
Data Context cannot overlapped each other, confusion may arise when dealing with complex UIs and complex UI models.

What is Data Binding?

You can imagine that the View is the body and the ViewModel is the soul :D .
But basically Data Binding is to bind a UI Component to a Data Context’s field which is as mention above the Data Context is an object or a class.

Lets modified the codes from Part 2, we will add a data model class into it.

Adding The Data Model

After you opened the solution from Part 2 first lets add a folder called DataModel in the project. Now create one class inside the folder and called it Citizen which has the following fields as shown in Figure 1. Due to the length of the class i will just show important parts of it:


Figure 1.1 Citizen class declaration


Figure 1.2 Citizen class field declaration


Figure 1.3 Citizen class INotifyPropertyChanged implementation

Figure 1. Citizen class

Just a plain simple class, no big deal. Now we have adjust the FirstView.xaml and Shell.xaml to synchcronize with the data model class.
Change the FirstView.xaml as show in Figure 2 and Figure 3 respectively.


Figure 2. FirstView.xaml


Figure 3. Shell.xaml

Now we continue our changes to the ViewModel, we only have one ViewModel; FirstViewModel.cs. The changes take place only in two regions; Constructors and Events region. As shown in Figure 4 and Figure 5 respectively.


Figure 4. Constructors region changes


Figure 5. Events region changes

I am adding one helper class to build the Citizen object called CitizenBuilder, but i will not show the class on this post, later on you can download the final result see the class for your self :D .
Try to build you solution by pressing F6, make sure no compile error. Run it by pressing F5; key-in some data make sure it shown the right data.

The Highlights

There is few things i have to highlight here, especially for Data Binding part. If you look closer the FirstView.xaml especially the parts that data bind to the UI components, such as this:

Text="{Binding Path=CurrentCitizen.Company, Mode=TwoWay}"

I will try to explain what is Mode in the data binding. I think the Mode is important to be understand when you use data binding in WPF.
Basically there is 5 available Modes:

  • Default
  • OneTime
  • OneWay
  • OneWayToSource
  • TwoWay

Note: I will try to use the ViewModel point of view during the explanation

Default

See OneWayToSource
Note: If you did not specify the Mode in the Binding it will use OneWayToSource

OneTime

OneTime is used when you do not want any changes take effect after you assign a value for the first time to a the data model field.

OneWay

OneWay is used when the data changes only came from the ViewModel to to View, e.g the View used only as read-only. It is the opposite of OneWayToSource.

OneWayToSource

OneWayToSource is used when the data changes only came from the View to ViewModel. It is the opposite of OneWay.

TwoWay

TwoWay is used when it desired when any changes to either side will affect both View and ViewModel. In order to use this the data model need to implements INotifyPropertyChanged
Note: implementing the INotifyPropertyChanged do you no harm if only one model, but more often than not, in time your model will grow in size and number, it is better to move it to an abstract class and extend your data model from that abstract class, maybe it is time for another post :D

That is all folks, i hope this simple explanation help. Feedback are welcome.
Please download the final code here
Note: This is just a small part of Data Context and Data Binding. There is many parts i have not covered, maybe you can! :D

Now you are officially WPF Data Binder :D .

Generated using Markdown 1.0.1

Written by Djaka Pribadi Maulana

4 July, 2010 at 9:41 AM

Posted in .Net, Tips and tricks

Tagged with , ,

Composite WPF Application Part 2 – The First Module

with 6 comments

For this second post on learning WPF, i will take you a bit deeper in world of WPF.
Perhaps i will introduce to some new toys in this post.

  • Modules
  • Commands
  • UI Layouts
  • Code Regions

If you want a jump start just download the codes.

In the Part 1 i have explained how to make an empty application shell. We will continue our little adventure by adding more new things as i mention above. You can either use the file that can be downloaded in the Part 1 or you can create new solution, it is your call. For now i will create a new project on a new solution using Visual Studio C# 2010, lets call it SingleModuleApplicationDemo. Visual Studio C# 2010 Express will make the solution name same as the main project`s name. Like the usual after you create the project, save it before you touch anything ( nothing in particular just my habit :D ).

After finished preparing the application shell just like in the Part 1.

Building The First Module

What kind of application are we going to build ?

We will try to build simple registration form. With Save and Cancel buttons. Input fields Name, Address and Phone No.. Some actions when the user click the Save button a dialog box will display the user input; in other hand Cancel button will hide the form instead.

The module will try to use MVVM pattern. First step is you add a new Class Library project, maybe you are wondering why i choose a Class Library project rather than WPF project. The reason behind this is that with creating Class Library you get less file to remove and more clean start. Lets name our newly added project as Module.FirstModule. As you can see you will be given one C# class called Class1.cs. For now just rename it to be FirstModule.cs.

Add / Remove the References on the Module.FirstModule and the SingleModuleApplicationDemo Project respectively. You also need to add the Module.FirstModule project as a Reference on SingleModuleApplicationDemo project.

The references for the SingleModuleApplicationDemo :


Figure 1. References for SingleModuleApplicationDemo Project

as you can see that the Module.FirstModule is one of the SingleModuleApplicationDemo`s libraries/references.

Next is the references for the Module.FirstModule


Figure 2. References for Module.FirstModule Project

Create two new folders on the Module.FirstModule project; View and ViewModel
Right click on the ViewModel folder then choose Add > New Item…
add an interface called IFirstViewModel
Inside your IFirstViewModel interface should be look like the following code:


Figure 3. IFirstViewModel.cs

It is pretty simple, do not worry, I will explain more detail later on in this post about the important parts of this application.

Add one more interface for the View, like usual right click on the View folder then choose Add > New Item… add an interface called IFirstView. Inside your IFirstView interface should be look like the following code:


Figure 4. IFirstView.cs

Little explanation on the codes above:
string ViewName{get;}
the implementation of above method will be return arbitrary view name.
string Name { get; }
string Address { get; }
string PhoneNo { get; }
these three methods as you expected these helper methods represent the fields on our screen later on;
for name, address and phoneNo respectively. Ok, the skeletons are set.

Building The First Module`s ViewModel

Now it is time to us to add a ViewModel class to our little project.
Right click on the ViewModel folder then choose Add > New Item add a class called FirstViewModel.
Due to the length of the FirstViewModel codes, It would be better if i split the codes into several section followed by some explanations.

Declaration and Imports


Figure 5. FirstViewModel.cs Declaration and Imports

Later on the ViewModel classes will contain all the UI logic for our form,
FirstViewModel is a ViewModel class so we will all the UI behaviour or interaction logic in this class.

Regions


Figure 6. FirstViewModel.cs Regions

What is a region actually?

A #region in Visual Studio context is some kind of markup tag, that used to visually group codes.
#region is exist since Visual Studio 2005 as far as i know.
#region is the best tool to create outlines for your class;
#region is collapsable; #region name can even contain spaces and special characters.
It is easy to add a region, here is a simple example how to use #region:

#region @Helper Method@
     private void SomeHelperMethod()
     {
      }
#endregion

Now lets visit the first region in the FirstViewModel class.

Instance Variables Region


Figure 7. FirstViewModel.cs Instance Variables

The first two lines we have DelegateCommands
CloseFormCommand which is will be used to hide our form and it will be assigned to the Cancel button.
ShowInputDataCommand which is will be used to show user input data using dialog box and it will be assigned to the Save button.
The last line we have a RegionManager, region manager used manage Region which is view areas,
you can think of Regions similar to divs in web design.

Constructors Region


Figure 8. FirstViewModel.cs Constructors

We use the Unity Framework to do the dependency injection, which means that Unity Framework will create all the constructor’s parameter objects as necessary.
In the first two line of the constructor we have this.View = view, basically we tied the FirstViewModel class and a class that implemented the IFirstView interface as a View-ViewModel couple.
Third line is a class that implemented IRegionManager interface which will act as the RegionManager, later on we will use it to hide/show our View.

Properties Region


Figure 9. FirstViewModel.cs Properties

This is where we store the View.

Events Region


Figure 10. FirstViewModel.cs Events

This is where the rubber meet the road. This region contain the codes for UI events.

Show Input Data Action

This is the action for the Save button. This action build up from three different methods.

public ICommand ShowInputDataAction

This method will return this.ShowInputDataCommand, it is a DelegateCommand type. this.ShowInputDataCommand = new DelegateCommand(ShowInputData, CanShowInputData) line will construct the command. A DelegateCommand need two methods as its parameters, each method must have certain method signature.

private void ShowInputData(object parameter)

As the first parameter to the ShowInputDataCommand, this method must have this signature:

  • void return type
  • an object as the parameter

within this method the real logic will be coded down.
There is only one line inside this method:

MessageBox.Show("Name: "+this.View.Name+"\n Address: "+this.View.Address+"\n Phone No.: "+this.View.PhoneNo);

above line will display the message box below containing user input when we click the Save button.


Figure 11. FirstViewModel.cs Dialog box showing user input

private bool CanShowInputData(object parameter)

As the second parameter to the ShowInputDataCommand, this method must have this signature:

  • bool return type
  • an object as the parameter

this method will be executed before the ShowInputData method.
If the CanShowInputData return false it will not execute ShowInputData method and all UI components that connected to ShowInputDataCommand will be disabled otherwise ShowInputData will be executed.

Close Form Action

Basically this action has same pattern as the Show Input Data Action, so i will not explain the details. I will only highlight the following line of code:
this.regionManager.Regions["MainRegion"].Deactivate(this.View);
above line will be hide our form from the user. Maybe you are wondering what is "MainRegion"; it is a UI region name in the Shell.xaml file inside the SingleModuleApplicationDemo project ( Figure 12 ).


Figure 12. Shell.xaml

It seems we already finish building the ViewModel lets continue building the View

Building The First Module`s View

Add a new User Control(WPF) in the View folder, right click on the View
folder Add > New Item and choose User Control(WPF) name it FirstView.xaml
I will not teach you how to use the drag-and-drop design feature ( maybe i should :D ) but from my experiences drag-and-drop will just slows you down,
if you are familiar other markup language such as HTML editing the code by hand would be faster.

Your xaml code more or less should be like this:


Figure 13. FirstView.xaml

Lets highlight the important parts.

UserControl

UserControl tags is the place holder for any custom component that we might create,
i see it as an empty panel for us to put the UI component or maybe other custom component.

DockPanel

i do used a DockPanel as the main layout because it is has the region that common in any desktop application the top region this is where we put toolbar and application main menu, the bottom region is where the status bar lies and the center regions where we display the main part of the application such as form or data table; i do used the DockPanel for the Shell.xaml DockPanel is similar to the Java Swing BorderLayout, it has Top, Bottom, Left, Right and Center region.

ContentControl
ContentControl is a arbitrary place holder for single UI component.

When the UI hit the Command

<Button Content="Save" Margin="5" Command="{Binding Path=ShowInputDataAction}"/>
<Button Content="Cancel" Margin="5" Command="{Binding Path=CloseFormAction}"/>

Yes as you expected, those commands are the method names that return an ICommand type in the FirstViewModel.cs
this possible because we set the FirstViewModel as the FirstView DataContext implicitly in the FirstView codebehind, you can see the codebehind
by pressing F7 after opened the FirstView.xaml file Figure 13:


Figure 14. FirstView.xml.cs

Note: FirstViewModel is implements IFirstViewModel so you might not see FirstViewModel there.

FirstView codebehind only has one region which is Properties region.
As you can see there are the implementation of the helpers methods:

public string Name { get { return this.name.Text; } }
public string Address { get { return this.address.Text; } }
public string PhoneNo { get { return this.phoneNo.Text; } }

name, address, and phoneNo are the name of the TextBoxes in the Figure 13

Open and edit FirstModule.cs file and make necessary changes as the following:


Figure 15. FirstModule.cs

Look at the following line of codes:

public void Initialize()
The above method is compulsory when you are implementing Unity Framework IModule interface.

this.container.RegisterType();

which contain

this.container.RegisterType<IFirstView, FirstView>();
this.container.RegisterType<IFirstViewModel, FirstViewModel>();

This is where Unity Framework does its works, in order to do dependency injection you have to register all the classes and their types.
One class only can have one type.

Note: At the time i wrote the post it seems if you register two class with the same type, only the lastest class that registered will bind to the interface.
e.g
this.container.RegisterType<IFirstView, FirstView>();
this.container.RegisterType<IFirstView, SecondView>();
Only SecondView will be recognized as the instance of type IFirstView, by time i wrote this i do still do not know how to share the type among the classes.

In future post i might use different way to register a class to a type; a class can be a type for itself, e.g.
this.container.RegisterType<FirstView>();


IFirstView menuView = this.container.Resolve().View;
this.regionManager.Regions["MainRegion"].Add(menuView,menuView.ViewName);

The line above is where we put our FirstView to the Shell.xaml, you must aware that region names are global and unique even they are existed in different files.

We have finished building the Module.FirstModule, to make sure everything is OK right click on the Module.FirstModule project and choose Build.
Now we have to integrate the module to the application.
Open and edit Bootstrapper.cs file in SingleModulApplicationDemo project to match the following figure:


Figure 16. Bootstrapper.cs in SingleModuleApplicationDemo Project

catalog.AddModule(typeof(FirstModule)); this is the line for module registration.
Do not forget to add the Module.FirstModule project as a References to the SingleModuleApplicationDemo project.
Press F6 to build the whole solutions and make sure no compile error. Run the solution using F5.

Final Result


Figure 17. Final Result

Download the codes.
See you next time in the next series : Composite WPF Application Part 3 – The Data Context.

Generated using Markdown 1.0.1

Written by Djaka Pribadi Maulana

26 June, 2010 at 1:34 PM

Posted in .Net, Tips and tricks

Tagged with , ,

Composite WPF Application Part 1 – The Empty Shell

with 3 comments

Several days ago i bumped into WPF ( Windows Presentation Foundation ) at work. I just want to share my experiences on learning the WPF. In this post i will try to explain how to create an empty application shell using WPF as the GUI and Unity Framework for managing objects.

Here are my tools and environment :

Note: .Net Framework 4 and WPF will be included when you installed Visual Studio C# 2010 Express

Required libraries :

  • Microsoft.Practices.Composite.dll
  • Microsoft.Practices.Composite.Presentation.dll
  • Microsoft.Practices.Composite.UnityExtensions.dll
  • Microsoft.Practices.Unity.dll
  • .Net Framework 4 built-in libraries
    • PresentationCore.dll
    • PresentationFramework.dll
    • System.dll
    • System.Core.dll
    • System.Xaml.dll
    • WindowsBase.dll

You no need to download these libraries files. I have provide a download link to the whole project.
Well enough for introduction, lets begin.

Create a new WPF project using Visual Studio C# 2010 Express and save the newly created project
( Visual Studio C# 2010 Express will create a new solution with the same name as the project by default ).

First thing you have to do is rename the given file MainWindow.xaml to Shell.xaml do not forget to rename the codebehind class from MainWindow.cs to Shell.cs after done this, make sure the name refactoring works correctly open the Shell.cs file and check its class name. Later on this Shell.xaml file will be our application GUI container, we will leave it empty for now.

Second step is to add a class called Bootstrapper.cs to your project, in order to do this simply right click on the project Add > Class. The content of the class is more or less would be like this:


Figure 1. Bootstrapper.cs

Third step is to open the App.xaml file, remove the following line StartupUri="MainWindow.xaml"
Go to the App.xaml file codebehind by pressing F7 replace the code as the following example:


Figure 2. App.xaml.cs

Add all the required libraries into you project by right click on the Reference folder and choose Add Reference…..
After finished adding all the necessary libraries, try to build the entire solution by pressing F6 make sure no compile errors.
The final state of your project on the Solution Explorer more or less would be like this :


Figure 3. Solution Explorer

Try to run the project using F5

Final result


Figure 4. Final Result

By the way the download link contain a Solution so you can directly open it
using Visual Studio C# 2010 Express and start play with the codes. I hope this simple tutorial help.

See you next time in the next series : Composite WPF Application Part 2 – The First Module.

Generated using Markdown 1.0.1

Written by Djaka Pribadi Maulana

23 June, 2010 at 12:23 AM

Posted in .Net, Tips and tricks

Tagged with , ,

Follow

Get every new post delivered to your Inbox.