Mar 27 2008

To night I understood what you gain using the Model-View-ViewModel pattern

Category: C# | Patternsfossmo @ 15:19

To follow me in this post I believe you need to have some pre knowledge about this Model/View/ ViewModel-pattern.

In my company we have a thing called "fagkveld". Its basically 1,5 hours where we present different design patterns and best practices to each other. To night Kjetil talked about something that I think is really exiting; the pattern Model View ViewModel. It's a pattern, among other things, for separating the (business) logic from the GUI (in Windows Presentation Foundation).

I have implemented the Model View Controller pattern in WPF earlier, and didn't then see the advantage of using a ViewModel. To night I understood what you gain using a ViewModel.

When using ViewModel on top of a (domain) model you get the benefit of customizing the ViewModel to exactly fit your views needs. If you need to change the data before you present it in the view, you can do this in the ViewModel. Let's say you have a model representing a person and you want to merge the persons first name and last name into one textbox in the view. You can do this in the ViewModel to avoid adding logic to the code behind file in the view. To completely remove code from the view, you also can use the Routed command pattern included in WPF. If you have a (domain) model that isn't suitable to databind to your view, ViewModel is your savior.

A problem I see using a ViewModel, is that the (domain) model isn't updated before you specific tell it to update it self. If other parts of the application relies on the model being updated "on the fly", you may have a problem. But, i guess this problem is possible to overcome.

Model View ViewModel is perfect to adapt an "old" domain model to support the mind blowing features in Windows Presentation Foundation.

Good reading for learning about the pattern:

http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Feb 20 2008

The Immediate Window in Visual Studio 2008 can save you some time!

Category: C# | Softwarefossmo @ 16:59

As you probably know, you can use the Visual Studio Immediate window to execute a method while your application is running, but you also can execute a method while the application is not running. Lately I have used this functionality to execute methods I'm working on without running the project. Like, for instance, in the figure below I didn't remember the syntax to format a date. So I wrote a test method and fired up the Immediate Window (Control-Alt+I or from the menu: Debug->Windows->Immediate) and entered Model.Tasks.testDate() (Model is the namespace, Task is the class and testDate is the method). The method was executed, and I got confirmed that my syntax was correct. This way I saved a lot of time. I didn't need to wait for VS.NET to compile the code, and execute the project.

 

immediate

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Jan 20 2008

What is the factory method pattern?

Category: C# | Patternsfossmo @ 10:29

The factory method pattern is a creational pattern. You can use it when you don't know witch object you must use at runtime.

Advantage of this pattern; you can delay assigning action code till more information is available. It's also easy to add other classes (in the code example below; color classes).
 

factory method pattern

What happens in the figure above?

The first thing that happens, is that a parameter is passed into the GetInstance method in the Factory class. Depending on the parameter passed in, a object is returned. In this instance, a object from class Blue is returned. The factory method pattern is as simple as that. If I wanted to work with the Green object, I would have passed Green as a parameter.

This patterns can be used in all parts of your code. You can use it to choose, for instance, databases or different graphical user interface frameworks at runtime.

Let's look at some code:

 

   1:  using System;
   2:   
   3:  namespace FactoryPattern
   4:  {
   5:      // Color objects to choose
   6:      enum MyColors
   7:      {
   8:          Green, Blue
   9:      }
  10:   
  11:      // The contract the objects have to implemet
  12:      interface IColor
  13:      {
  14:          void ShowFavoriteColor();
  15:      }
  16:   
  17:      class Factory
  18:      {
  19:          // A instance of a object is returned based on the input parameter.
  20:          public IColor GetInstance(MyColors type)
  21:          {
  22:              IColor color = null;
  23:   
  24:              // Whice object to return is decided.
  25:              switch (type)
  26:              {
  27:                  case MyColors.Green:
  28:                      color = new Green();
  29:                      break;
  30:                  case MyColors.Blue:
  31:                      color = new Blue();
  32:                      break;
  33:              }
  34:              return color;
  35:          }
  36:      }
  37:   
  38:      class Green : IColor
  39:      {
  40:          public void ShowFavoriteColor()
  41:          {
  42:              Console.WriteLine("My favorite color is green");
  43:          }
  44:      }
  45:   
  46:      class Blue : IColor
  47:      {
  48:          public void ShowFavoriteColor()
  49:          {
  50:              Console.WriteLine("My favorite color is blue");
  51:          }
  52:      }
  53:   
  54:      class ColorChooser
  55:      {
  56:          public static void Main()
  57:          {
  58:              Factory factory = new Factory();
  59:   
  60:              // Decides which instance to start
  61:              IColor baseClass = factory.GetInstance(MyColors.Blue);
  62:   
  63:              // Executes method in chosen instance
  64:              baseClass.ShowFavoriteColor();
  65:   
  66:              Console.ReadKey();
  67:          }
  68:      }
  69:  }

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Jan 8 2008

Dependency Injection explained

Category: C# | Patternsfossmo @ 11:35

Dependency Injection (DI) is a fancy word for a very simple pattern. You probably use DI at some sort every time you code. In it simplest form, a variable is injected into a method and the method can interact with the variable. That's DI.

I often use DI in a other pattern called Model View Presenter. 

In the figure below, I visually try to show how DI works.

DependencyInjection

(Click on the image to view larger)

Below is a example of how I often use the pattern.

   1:  namespace DependencyInjection
   2:  {
   3:      class Program
   4:      {
   5:          static void Main(string[] args)
   6:          {
   7:              Class1 class1 = new Class1();         
   8:          }
   9:      }
  10:   
  11:      public interface IProperties
  12:      {
  13:          string MyValue { get; set; }
  14:      }
  15:   
  16:      public class Class1:IProperties
  17:      {
  18:          string _myValue = "Class1 value";
  19:          Class2 class2;
  20:   
  21:          public Class1() 
  22:          {
  23:              Console.WriteLine(MyValue);
  24:              class2 = new Class2(this);
  25:              class2.ChangeMyValue();
  26:              Console.WriteLine(MyValue);
  27:              Console.ReadKey();
  28:          }
  29:   
  30:          public string MyValue
  31:          {
  32:              get
  33:              {
  34:                  return _myValue;
  35:              }
  36:              set
  37:              {
  38:                  _myValue = value;
  39:              }
  40:          }     
  41:      }
  42:   
  43:      public class Class2
  44:      {
  45:          private IProperties _view;
  46:   
  47:          public Class2(IProperties view)
  48:          {
  49:              _view = view;
  50:          }
  51:   
  52:          public void ChangeMyValue()
  53:          {
  54:              _view.MyValue = "Changed by instance of Class 2";
  55:          }
  56:      }
  57:  }
 
 
 
In line 7, a instance of Class 1 is created. The constructor in Class 1 is executed (line 21). 
Class 2 is called with the instance of the current object (Class 1). 
This is possible because Class 1 implements the interface IProperties (line 11). In line 25, class 2
calls the method ChangeMyValue. The property MyValue in Class 1 is changed.
 
That's the dependency injection pattern.
 

Tags:

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Dec 26 2007

Model View Presenter explained

Category: C# | Patterns | Scrum | Testingfossmo @ 18:36

I have used Model View Presenter (MVP) a lot the last months. It's a great pattern, but a lot of the people I talk to have problem understanding how it works, and how to use it. I will try to explain it simple in this blog post.

Passive View and Supervising controller
The creator of MVP, Martin Fowler, spilt the pattern into to new patterns. This was due to apparent confusions between Model View Controller and MVP. The new patterns is called Passive View and Supervising Controller. The main difference between this to patterns, is that Passive View puts all the view update behavior in the controller/presenter and Supervising Controller encourage the view to do most of the updating itself, and only brings in the presenter/controller when there's more complex logic involved. In my example application later in this blog post, I show Passive View.

When to use it
MVP is a great pattern to ease up unit testing the graphical user interface (GUI), and to decouple the GUI from the underlying model. MVP makes switching GUI a breeze.

Explained graphically
MVP is a pursuance of an other pattern called Model View Controller. In MVP, the view and the model don't know of each other, but in MVC the view knows of the model, and gets its updates from it.
I will cover MVC in a later post.

The figure below visually illustrates the pattern.

mvpgrap

More thoroughgoing, this is what happens:

1) The user executes a action. The action is forwarded to the presenter.
2) The presenter asks the database (model) for the data to view.
3) The model sends the data back to the presenter.
4) The presenter updates the view with the new data.

There are normally four main classes used in the MVP pattern. To be more specific,  three classes and a interface; the view, typical a WinForm, WebForm or XAML-file. The interface, witch describes the fields in the view. The presenter, witch executes the views actions and communicates with the model. And, of course,  the underlying model, e.g. a database.

Example application
I have created an application witch displays name, e-mail, state, etc. The application uses the MVP pattern. This is what the application does: You enter a name into the search text box and the program reads information from a textfile. Information about the user is displayed in the form. 

Application 
Shows the GUI in the application

Project
The solution consists of three projects. One view, one presenter and one model. If you wanted to have several forms, you would have to create more presenters and views. 

projectstructur
Shows the project structure

Interface
Let's look at the interface. It's found in the presenter project, and is named IPerson. It includes all the fields I want to display in the view.

interface

The last field in the interface is Message. You will find it in the lower part of Form1, displaying: "Data fetched.". If any error occurs in the application, it's shown there. The class Form1 (Form1.cs), implements the interface.

implemented interface   

Form1 implements all the properties in the interface. This is, as you know the startingpoint of the application. A instance of the presenter is created in the view. This way the presenter and view can communicate, and the presenter can update the GUI elements.

implementations
Shows some of the properties in Form1

When the search textbox is filled with a name, a event is triggered. It ends up in the method txtSearch_KeyUp in the class Form1:

keypressed

The presenters constructor, inputs the view and the class fetching data from the model, as parameters. Hence, the presenter has access to the view and the model. This way of doing things is called Dependency Injection.

presenter

In the method UpdateData (called from the view), data is fetched from the datasource, and the view is filled with the returning data. If a exception occurs the field message, in the view, displays the error message. If nothing happens, the field displays "Data fetched.".

ReadData

In the model (Data project), data is fetched from the file and put into a person object. Person object is returned to the presenter. If no data is found, an exception is thrown (witch is displayed in the message field in the GUI).

nodatafound

That is the course of events in the Model View Presenter pattern.
I recommend you to fire up Visual Studio and debug the sample application.

If you want to download the sourcecode for this example, you can find a link below.  

Tags: ,

Currently rated 5.0 by 5 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Nov 29 2007

System.AddIn

Category: C# | TechEdfossmo @ 17:13

At TechEd some weeks ago, I went to a presentation about System.AddIn. It's a new cool addin framework for .NET. It's shipped with the .NET 3.5 framework. Making addIns and using them is much easier with this framework. To demonstrate how easy creating addins is, I will create a simple addin.

Here we go:

For this project I'm using Visual Studio 2008 Express. In the Express version, advanced build configuration is turned off by default. Lets turn it on:

In VS2008 Express choose Tools -> Options and then Show all settings.

SS-11.28.2007-12.54.05AM

Then choose Projects and solutions -> General -> Show advanced build configuration.

SS-11.28.2007-12.59.03AM

Now advanced build configuration is turned on and you can choose debug and release from the dropdown menu. Set it to debug.

SS-11.28.2007-01.03.16AM

I am going to create a console application. I'll name it TestAddIn.

In the Main method, I add the following line:

string addInPath = Environment.CurrentDirectory;

This line tells the application where to look for the addins.

Then I add references to this namespaces:

System.AddIn and System.AddIn.Contract

These two references have to be added to all the projects in this solution.

Next, I updates my addIns in store so the application is aware of the addins:

AddInStore.Update(addInPath);

To discover the addIns, add this line of code:

Collection<AddInToken> tokens = AddInStore.FindAddIns(typeof(MyTextHostView), addInPath);

The class MyTextHostView does not exist yet, so I have to create it. I add a new class library, and call it Host.View and add the following code:

public abstract class MyTextHostView
{
    public abstract string ViewText(string inputText);
}
 

SS-11.28.2007-05.21.51PM

Back in the main method, add:

foreach (AddInToken addinsToken in tokens)
{
     MyTextHostViewtextInstance =
        addinsToken.Activate<MyTextHostView>(AddInSecurityLevel.Internet);
     Console.WriteLine(textInstance.ViewText("My input text"));
}

The addin views define the base class for the add-ins. It is the way the addin receives the calls from the host. I create a class library called AddIn.Views and add this code:

[AddInBase]
public class MyTextAddinView
{
    public abstract string ViewText(string inputText);
}

SS-11.27.2007-12.55.59AM

Set the output path to ..\build\AddInViews.

SS-11.28.2007-05.30.33PM

Then it's time to create the first addin.

A new class library is required; AddIn.First. Add this code:

[AddIn("First addIn", Version="1.0.0.0")]
public class First:MyTextAddinView
{
    public override string ViewText(string inputText)
    {
        return "Addin 1: " + inputText;
    }
}


Set the output path to ..\build\AddIns\First\

Add a reference to the AddIn.View project, and make sure you set Copy Local = False.

SS-11.28.2007-05.52.55PM 

The interface between the host and the addIns, is expressed by a contract.

Create a class library called Contracts and add this code:

[AddInContract]
public interface IMyTextContract : IContract
{
    string ViewText(string name);
}

SS-11.27.2007-12.51.35PM

Set the output path to ..\build\Contracts\

An other class library is needed. Create a library called Host.Adapters. You know the drill; add the following code:

[HostAdapter]
public class MyTextContractToHostViewAdapter : MyTextHostView
{
    private IMyTextContract _contract;
    private ContractHandle _handle;

    public MyTextContractToHostViewAdapter(IMyTextContract contract)
    {
        this._contract = contract;
        _handle = new ContractHandle(contract);
    }

    public override string ViewText(string inputText)
    {
        return this._contract.ViewText(inputText);
    }

}

SS-11.28.2007-12.16.24AM

Add a reference to the Host.View project and Contracts project, and make sure you set Copy Local = False.

I also need a adapter on the addInside. Create a class library called AddIn.Adapter and add the code:

[AddInAdapter]
public class SimpleAddInViewToContractAdapter : ContractBase, IMyTextContract
{
    private MyTextAddinView _view;

    public SimpleAddInViewToContractAdapter(MyTextAddinView view)
    {
        this._view = view;
    }

    public string ViewText(string inputText)
    {
        return this._view.ViewText(inputText);
    }
}

SS-11.28.2007-06.06.03PM

Add a reference to the AddIn.View project and Contracts project, and make sure you set Copy Local = False.

Then it's time to test the project. Press F5, and run it.

SS-11.28.2007-06.11.30PM

I will write more in detail about this cool framework later.


Download project:

TestAddIn1.rar (19.56 KB)

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Oct 29 2007

Debug in Visual Studio 2008 Express

Category: C# | Testingfossmo @ 16:44

Visual Studio 2003-2008 Express are missing Add-In support and no ability for the debugger to attach to a process.

This brings up a problem when trying to debug your tests with Nunit. After Testdriven.NET no longer supports the express editions, we no longer have the possibility to run tests against code we develop in the express editions. Well, so it seems.

But, there is still a way around this. It's not as smooth as Testdriven.NET, but it works all right. In the folder which contains the test library you want to debug, add a file named the same as the project, but with the extension ".csproj.user". This is the content of one of my files:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Nunit|AnyCPU' ">
<EnableASPDebugging>false</EnableASPDebugging>
<EnableASPXDebugging>false</EnableASPXDebugging>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
<EnableSQLServerDebugging>false</EnableSQLServerDebugging>
<RemoteDebugEnabled>false</RemoteDebugEnabled>
<RemoteDebugMachine>
</RemoteDebugMachine>
<StartAction>Program</StartAction>
<StartArguments/>
<StartPage>
</StartPage>
<StartProgram>tools\nunit\nunit.exe</StartProgram>
<StartURL>
</StartURL>
<StartWorkingDirectory>
</StartWorkingDirectory>
<StartWithIE>false</StartWithIE>
</PropertyGroup>
</Project>

I have created my own solution configuration in VS.NET called Nunit. It is used when running the tests.
You can of course use the default configuration; DEBUG if you want to. Then you have to change a line in the content:
 '...$(Platform)' == 'Nunit|AnyCPU' ">'

to

'...$(Platform)' == 'Debug|AnyCPU' ">'.

This worked perfectly for me.

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Aug 11 2007

Podcasts I listen to

Category: C# | Podcastfossmo @ 12:37
I like reading books and blogs, but sometime its more convenient to listen to podcasts. For instance, when I'm walking or driving, it's ok to listen to a podcast about the latest technology.

Here are some links to podcasts I recommend:

http://www.dotnetrocks.com
http://www.hanselminutes.com
http://channel9.msdn.com/Shows/ARCast_with_Ron_Jacobs




 

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

May 25 2007

MBUnit unittest framework

Category: C#fossmo @ 05:10

I have resently switched from NUnit to MBUnit. One problem in MBUnit, when trying to run a test which uses System.Windows.Window object, was that the thread does not run as a STA thread. I got this error message: "The calling thread must be STA, because many UI components require this."

Example:
[Test]
public void Common_CheckIfListReturnsElement()
{
Window window = new Window();
}

It turns out that MbUnit overrides the ApartmentState, setting it to MTA by default. So you do need to specify the ApartmentState in the fixture attribute:

[TestFixture(ApartmentState = ApartmentState.STA)]
Problem solved!

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

May 6 2007

Microsoft Visual C# codename "Orcas" Express Edition

Category: C#fossmo @ 10:21
I was trying out Microsoft Visual C# codenam "Orcas" Express Edition the other day. When trying to create a WPF Application I got this error:
The project file 'C:\Documents and Settings\(Username)\Local Settings\Temp\vay1mynp.olr\Temp\(Application name).csproj' cannot be opened.

After searching around on the net for some minutes, I found a workaround. I had to go to this directory C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE and run this command regsvr32.exe ProjectAggregator.dll from the command prompt.

After doing this, the WPF Application template worked.


Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5