jump to navigation

MVVM in WPF Part II February 13, 2009

Posted by wesaday in Programming.
Tags: , , ,
11 comments

This is the second part in a two part article on the Model-View-ViewModel design pattern in WPF.

The Model

Our friend the Model is responsible for getting and holding onto the data. The data could come from anywhere, a file, a database, thin air, etc. Our Model is the one that is going to read the data out of the file and store it in a DataTable so that the ViewModel can present it to the View. So add a Model class to the Model project. I called mine “MainModel” because it’s going to the MainWindow. We are going to need three things in our Model, a constructor, a method to get the data from the file, and a property to expose the data to the outside world. The method is easy as we are just going to copy the same code from the previous article and make minor modifications to it. So here is our GetFileData method.

        public bool GetFileData(string filename)

        {

            const string connectionString = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\csvfiles\;Extended Properties=’text;HDR=Yes'”;

            string commandText = string.Format(“Select * from {0}”, filename);

            OleDbConnection conn = new OleDbConnection(connectionString);

 

            conn.Open();

 

            OleDbDataAdapter da = new OleDbDataAdapter(commandText, conn);

            DataSet temp = new DataSet();

            da.Fill(temp);

            FileData = temp.Tables[0];

            return true;

        }

Here we are opening a file from the C:\csvfiles directory and filling a DataTable with the results. FileData is the name of the property that is holding the data. So lets add that next.

        public DataTable FileData

        {

            get; set;

        }

Pretty simple. The only thing left to do is to add the constructor.

        public MainModel()

        {

            FileData = new DataTable();

        }

That’s it for the Model. Remember to reference the System.Data and OleDb namespaces for the GetFileData method. Here is the complete listing for the Model.

namespace Article.Model

{

    using System.Data;

    using System.Data.OleDb;

 

    public class MainModel

    {

        public MainModel()

        {

            FileData = new DataTable();

        }

 

        public DataTable FileData

        {

            get; set;

        }

 

        public bool GetFileData(string filename)

        {

            const string connectionString = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\csvfiles\;Extended Properties=’text;HDR=Yes'”;

            string commandText = string.Format(“Select * from {0}”, filename);

            OleDbConnection conn = new OleDbConnection(connectionString);

 

            conn.Open();

 

            OleDbDataAdapter da = new OleDbDataAdapter(commandText, conn);

            DataSet temp = new DataSet();

            da.Fill(temp);

            FileData = temp.Tables[0];

            return true;

        }

    }

}

Nothing to it. That is it for the Model. Next we will move to the ViewModel.

The ViewModel

Most of the action happens in the ViewModel so it naturally follows that the ViewModel is the most complex which was my stumbling block. There is so much that can, and does, go on in there that it can quickly get confusing.  The very first thing to do is to create a base ViewModel class that we could use to base our ViewModels on. For this simple example it really is not necessary but it does serve as a good base to build from. So add a new class to the ViewModels folder in the project and call it BaseViewModel.  Make the base class abstract and implement the INotifyPropertyChanged and IDisposable interfaces. Implementing those interfaces in the base class saves us from having to implement them in each and every other ViewModel.  Some of this code is strictly for debugging purposes and those are commented. I believe that 99% of the base class code was Josh Smiths. I added some code comments but that was about it.  This is the code stripped down. Not much to it and should be pretty much self explanatory.

    public abstract class BaseViewModel : INotifyPropertyChanged, IDisposable

    {

        protected BaseViewModel()

        {

        }

 

        ~BaseViewModel()

        {

            string msg = string.Format(“{0} ({1}) ({2}) Finalized”, GetType().Name, DisplayName, GetHashCode());

            Debug.WriteLine(msg);

        }

 

        public event PropertyChangedEventHandler PropertyChanged;

 

        public virtual string DisplayName

        {

            get; protected set;

        }

 

        protected virtual bool ThrowOnInvalidPropertyName

        {

            get; private set;

        }

 

        public void Dispose()

        {

            OnDispose();

        }

 

        [Conditional(“DEBUG”)]

        [DebuggerStepThrough]

        public void VerifyPropertyName(string propertyName)

        {

            // Verify that the property name matches a real,

            // public, instance property on this object.

            if (TypeDescriptor.GetProperties(this)[propertyName] == null)

            {

                string msg = “Invalid property name: “ + propertyName;

 

                if (ThrowOnInvalidPropertyName)

                {

                    throw new Exception(msg);

                }

 

                Debug.Fail(msg);

            }

        }

 

        protected virtual void OnDispose()

        {

        }

 

        protected virtual void OnPropertyChanged(string propertyName)

        {

            VerifyPropertyName(propertyName);

 

            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler == null)

            {

                return;

            }

 

            var e = new PropertyChangedEventArgs(propertyName);

            handler(this, e);

        }

    }

Now we are ready for the MainViewModel. Add a new class to the ViewModels and name it MainViewModel. Make sure to derive from the BaseViewModel class. Because there is a lot of stuff going on in here, we are going to take it nice and easy getting through this. This is the class definition.

    public class MainViewModel : BaseViewModel

    {

    }

The two things that we need right now is two private variables, one for the Model and one for the data that the View is going to display.

        private readonly MainModel _model;

 

        private DataTable _fileData;

 

Because I am simple minded, we are going to initialize the variables in the constructor:

        public MainViewModel()

        {

            _model = new MainModel();

            _fileData = new DataTable();

        }

 

Now we need a method to call to get the data from the model:

        public void GetData()

        {

            _model.GetFileData(“test.csv”);

            FileData = _model.FileData;

        }

We have hard code a file name here but, if you wanted to you could open a file browser and let the user select a file to open.

And then a property to expose the data to view:

        public DataTable FileData

        {

            get

            {

                return _fileData;

            }

 

            set

            {

                _fileData = value;

                OnPropertyChanged(“FileData”);

            }

        }

 

Notice that the property called OnPropertyChanged in the setter. When that happens the view is automatically updated with the changed information. Magic!

As long as we are here we are going to introduce a Command. The command that we are going to use is going to get used when the user clicks the Button on the main window.  The command will get routed to the ViewModel and the ViewModel will handle the command.  We are going to need another variable for the command:

private RelayCommand _getDataCommand;

We are going to use the RelayCommand class to encapsulate the RoutedCommand. The RelayCommand class was also written by Josh Smith. Now to expose the command to the View we do this:

        public ICommand GetDataCommand

        {

            get

            {

                if (_getDataCommand == null)

                {

                    _getDataCommand = new RelayCommand(param => GetData());

                }

 

                return _getDataCommand;

            }

        }

The main point of this is the initialization of the Command. The RelayCommand is passed the method that it is going to call when the button is clicked. In this case, the GetData method is going to be that method.

As hard as it is to believe, that is it for the hardest part. After the code listing we are off to the View. This is the complete listing for the MainViewModel:

    public class MainViewModel : BaseViewModel

    {

        private readonly MainModel _model;

 

        private DataTable _fileData;

 

        private RelayCommand _getDataCommand;

 

        public MainViewModel()

        {

            _model = new MainModel();

            _fileData = new DataTable();

        }

 

        public DataTable FileData

        {

            get

            {

                return _fileData;

            }

 

            set

            {

                _fileData = value;

                OnPropertyChanged(“FileData”);

            }

        }

 

        public ICommand GetDataCommand

        {

            get

            {

                if (_getDataCommand == null)

                {

                    _getDataCommand = new RelayCommand(param => GetData());

                }

 

                return _getDataCommand;

            }

        }

 

        public void GetData()

        {

            _model.GetFileData(“test.csv”);

            FileData = _model.FileData;

        }

    }

The View

The view is oh so simple, really. The first thing that you need to do is to go over to www.codeplex.com and get the WPFToolkit, http://www.codeplex.com/wpf. I used the data grid control for WPF for this example. So this will also show you how to use the data grid in a most basic fashion. So after you install the toolkit you will need to add a reference to the WPFToolkit.dll to the View project. Once you do that, you can add the namespace reference to the View XAML file. Open up the MainWindow.xaml file and add the namespace to the top of the file:

xmlns:dg=”clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit”

This tells the program that we are going to be using the Microsoft.Windows.Controls namespace and we are going to reference in our code as “dg”. Once we have the namespace mapped in, we can include the data grid control and binding it to our data source:

<dg:DataGrid ItemsSource=”{Binding Path=FileData}” Margin=”0,30,0,0″ />

The ItemsSource property is binding to the FileData property of the ViewModel. And that is all you need to do here to get the data grid to show the data. Cool huh? The only other thing that we are going to do here is to add a button that we can use to tell the ViewModel to go get the data:

<Button Height=”22″HorizontalAlignment=”Left” Margin=”8,4,0,0″ Name=”button1″VerticalAlignment=”Top” Width=”48″ Command=”{Binding Path=GetDataCommand}”>Button</Button>

The important part of this is theCommand=”{Binding Path=GetDataCommand}”” part. This is the part that tells the program that when the button is clicked that it is to execute the GetDataCommand. If you recall the GetDataCommand is the command in the ViewModel that gets the data from the Model. There is not an event handler in the traditional sense. More of the magic of WPF. That is it for the XAML for the MainWindow. The XAML for the MainWindow now looks like this:

<Window x:Class=”Article.MainWindow”

    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

    xmlns:dg=”clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit”

    Title=”MainWindow” Height=”300″ Width=”300″>

    <Grid>

        <dg:DataGrid ItemsSource=”{Binding Path=FileData}” Margin=”0,30,0,0″ />

        <Button Height=”22″HorizontalAlignment=”Left” Margin=”8,4,0,0″ Name=”button1″VerticalAlignment=”Top” Width=”48″ Command=”{Binding Path=GetDataCommand}”>Button</Button>

    </Grid>

</Window>

Now, before we continue I have to say that this in not the only way to code this up. You caninstantiate the ViewModel in the XMAL and not do anything at all in the code behind however, I am going to save that for another time. That being said open up the MainWindow.cs file and find the constructor for the window. Right after the InitializeComponent method call, add the following:

DataContext = new MainViewModel();

 That is all you need to do to set the DataContext of the window which is where the data binding looks to find the data. You will also need to add a reference to the ViewModel assembly. This is the MainWindow code:

namespace Article

{

    using System.Windows;

    using ViewModel.ViewModels;

 

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            DataContext = new MainViewModel();

        }

    }

}

Conclusion

That completes the discussion of the basic architecture of a WPF MVVM application. We created a basic Model class that read a .csv file and exposed that data as a property of the class. We created a base ViewModel class to serve as a base from which to build upon and created a derived ViewModel to bind the data to the View raising a NotifyPropertyChanged event to update the data binding. We also included in our ViewModel a command using a RelayCommand that would be used from the View to go get the data and the View displayed the data in the WPF data grid control through data binding. Attached is a Visual Studio 2008 solution containing all of the code discussed in this article, including the .csv file used to display data in the data grid. Rename the .doc file to .zip before trying to open it. This is a wordpress.com requirement. articlezip

Model-View-ViewModel in WPF Part I February 12, 2009

Posted by wesaday in Programming.
Tags: , ,
4 comments

Introduction

The Model-View-ViewModel (MVVM) is the current “standard” for developing applications in Windows Presentation Foundation but there seems to be no hard and fast rules. It’s more like a guideline. It took me a long time to figure what was going on in this design pattern. I read the articles written by John Gossman, http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx, and Dan Crevier http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx but for the absolute beginner I was not able, or smart enough, to understand the material. After looking at a huge amount of example code and research I was finally able to decompose one of the example applications and figure out how it worked. This code that I am presenting here is a derivative of the demo application written by Josh Smith, http://joshsmithonwpf.wordpress.com. Josh is a WPF God and you can learn a lot from his articles. Anyway, after much frustration the pieces fell together and I began to comprehend what was going on in the MVVM.

The MVVM design pattern is sort of a descendent of the Model-View-Presenter design pattern. I published a series of articles introducing that design pattern starting here, https://wesaday.wordpress.com/2009/01/27/winforms-model-view-presenter-a-tutorial. However, the MVVM pattern takes advantage of some advanced features of WPF. I fully expect that this article will evolve into several parts also. Actually, I am just going to make this a two parter.

Goals

The goal of this article is to explain the MVVM pattern in an easy to understand tutorial manner, exploring the various facets. We will redo the application presented in the MVP article series in WPF. To recap, the final application will read a CSV file and display the data in a data grid in the main view and will turn out to look something like this:

 

The goal

The goal

The players

I learn best in a tutorial fashion so in this section we will introduce the entities that make up the MVVM.  A simplified diagram of the design pattern might look something like this:

MVVM diagram

MVVM diagram

The View object pretty remains the same. This is the window and controls that the user sees and interacts with. The major goal in using this pattern is to move as much of the code to the ViewModel as possible making the View code-behind a desolate wasteland.

The ViewModel contains the properties that are used in databinding data to the View and handlers that respond to user input. The ViewModel assumes most of the responsibility of knowing what is going on in the View andhandling the Model. I would imagine that most of the code that you are going to write in a real world application would reside in the View Model. The ViewModel implements the INotifyPropertyChanged interface. This is really cool since when the data in the ViewModel changes, the INotifyPropertyChanged updates the databinding and the View magically gets updated with the updated information.

Our friend the Model does not change all that much. It is still responsible for obtaining the requested data and giving it to the ViewModel.

Setting up

The solution that I describe is what worked for me so that is what I am going to stick to. In no way should this be construed as production code. This is stripped down code that eliminated unnecessary code to get down to the guts of the method. To use this is production code; you would definitely want to implement error handling and checking. Also I will probably not describe how to add projects or classes to the solution as you should know that already.

The first thing to do is to create a new WPF application. Being the imaginative soul that I am, I named my solution “Article”. You, of course, are free to name it whatever you want. I habitually rename the generated window class to “MainWindow”.  Add to the solution two more projects. The first project I named Article.Model and the second I named Article.ViewModel. In the Article.ViewModel project, add two new folders name on “Commands” and name the other “ViewModels”.  When you get all that done, your solution should end up looking something like this:

Solution setup

Solution setup

 

That is it for Part I. In Part II we will explore the Model, the View and the ViewModel in depth. And will include a sample solution illustrating the concepts.

XAML power toys February 11, 2009

Posted by wesaday in Programming.
Tags:
add a comment

Another WPF guru, Karl Shifflet has released a new version of his XMAL power toys here http://karlshifflett.wordpress.com/xaml-power-toys/

Model-View-ViewModel February 11, 2009

Posted by wesaday in Programming.
Tags: ,
add a comment

The WPF guru, Josh Smith, has published an excellent article describing the MVVM design pattern in WPF. You can read all about it on his blog, http://joshsmithonwpf.wordpress.com/ and you can follow the link to his article on MSDN. Well done Josh!

Karl Shifflet and Jaime Rodriguez conducted a MVVM class. You can get the presentation and code for Jaime’s blog here, http://blogs.msdn.com/jaimer/archive/2009/02/10/m-v-vm-training-day-sample-application-and-decks.aspx

Winform – Model-View-Presenter – Part V the View January 30, 2009

Posted by wesaday in Programming.
Tags: , ,
39 comments

Finally we come to the conclusion. This the the final part to the Model-View-Presenter in Winforms series.

Open the MainForm in the designer. This is probably the easiest step of all. Drag and drop a DataGridView on to the form. To make it look semi-decent, you might want to set the Anchor property so that the control fills the form as this is the only thing that we are going to do.

Now, open up the code-behind file. The first thing to do is to reference the class library in the main project. Right click the references in the solution explorer and select Add Reference. Click the Project tab, Select the Common.Lib.dll and then click OK.

 

Add reference

To the usings statements, add a ‘using Common.Lib.Interfaces’ statement. Now we can go ahead and implement the IMainView interface.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using Common.Lib.Interfaces;

 

namespace ProjectSkeleton

{

    public partial class Form1 : Form, IMainView

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        #region IMainView Members

 

        public DataSet CSVData

        {

 

        }

 

        #endregion

    }

}

This gives us a property that we will be using to bind the data to the DataGridView. Which is exactly what we are going to do. Bind the DataSource property of the DataGridView to the value of the DataSet like this:

        public DataSet CSVData

        {

            set { dataGridView1.DataSource = value.Tables[0]; }

        }

Now we need to instantiate the Presenter and give is a file name to open. I hard coded a file name in this example. Of course you could implement a file browser and open any file that you can. Create a private member of the DataPresenter;

        private DataPresenter _presenter;

Then instantiate the presenter passing is the mainview so it can give us the data. Then finally tell the presenter to open the test file.

       _presenter = new DataPresenter(this);

       _presenter.Display(“test.csv”);

Now you can run the solution and you should be able to see the grid is filled with the data from the test.csv file. There you have a complete solution that demonstrates the Model-View-Presenter design pattern with Winforms. There is a link to the complete Visual Studio 2008 solution below. Rename the .doc filename to .zip before you open it. This is a wordpress requirement. finalzip This link is the document that contains the all 14 pages of the text. The caveat is that the document may or may not exactly match since I have had to do a lot of editing online 🙂 mvp-in-winforms Note that this is an Office 2007 document.

 

 

 

Winforms – Model-View-Presenter – Part IV the Presenter January 29, 2009

Posted by wesaday in Programming.
Tags: , ,
4 comments

This is the fourth in a series describing the MVP pattern in Winforms.

The Presenter

Add two classes to the Presenters folder. One named Presenter and the other named DataPresenter. We are going to implement the Presenter as a generic so in case you change the Model or the View we could use the same Presenter or interchange Presenter classes. This will make enhancing the example as a base application easier. So declare the Presenter class as a Generic class where the parameter implements the IBaseInterface interface:

    public class Presenter<T> where T : IBaseInterface

    {

 

    }

Now declare two class properties, one for the Model and one for the View. Since the Presenter, and derivations, is the only one that will be using these properties, make them protected.

        protected static IModel Model { get; private set; }

        protected T View { get; private set; }

Now we are going to create two contructors, a static constructor and an public constructor that takes a parameter. The static constructor is going to initialize the Model for us. The other constructor is going to set the view for us. There also other ways to do this. I have seen where the Model is set in the constructor when the class is instantitated. It’s a matter of style. This way seems “cleaner” to me as the view does not have to know about the Model so the Presenters can use different Models and the View does need to know anything about it.

So our base Presenter class now looks like this:

using Common.Lib.Interfaces;

using Common.Lib.Models;

 

namespace Common.Lib.Presenters

{

    public class Presenter<T> where T : IBaseInterface

    {

        protected static IModel Model { get; private set; }

        protected T View { get; private set; }

        static Presenter()

        {

            Model = new Model();

        }

 

        public Presenter(T view)

        {

            View = view;

        }

    }

}

Okay now. For the real Presenter class. Open up the DataPresenter class. The first thing to do is to modify the class definition to derive from the Presenter class and define what the interface for our view that we are going to handle.

    public class DataPresenter : Presenter<IMainView>

    {

    }

Then this class simply needs to define a constructor and a public method to call to get the data from the Model and give it to the View.

 

        public DataPresenter(IMainView view)

            : base(view)

        {         

        }

 

        public void Display(string filename)

        {

            if (View != null) View.CSVData= Model.GetData(filename);

        }

The constructor is passed a IMainView interface which is also passed along to the base class. This also give access to the Model that is instantiated in the base class. The method simply calls the Model’s GetData method passing along the filename to get the data from and giving that back to the View. This is it for the class library. All we need to do now to finish this up is to finish our main view.

This is the Visual Studio 2008 project so far. Change the name from .doc to .zip before you open it. This is a wordpress requirement. presenterzip

Winform – Model-View-Presenter – tutorial Part III the Model January 28, 2009

Posted by wesaday in Programming.
Tags: , , ,
2 comments

This is the third part of the MVP tutorial series. In this part we are going to discuss…

The Model

The Model provides a “model” for the data that is going to be exposed to the View. Add a new class and call it “Model”. Then have the class implement the IModel interface.

using Common.Lib.Interfaces;

namespace Common.Lib.Models

{

    public class Model : IModel

    {

       

    }

}

Now if you were to compile the project, you get an error because we said that we would implement the interface but have not yet. Right click on the IModel interface text in the editor then select Implement Interface, then select Implement Interface on the sub menu.

 

Implement  interface

Implement interface

Once you do that, Visual Studio will write a skeleton implementation for all of the methods in the IModel interface. In this case, Visual Studio will create a method named GetData taking a string as a parameter and returning a DataSet. Go ahead and delete the throwing of the not implemented exception. So you should end up with something like this:

using Common.Lib.Interfaces;

namespace Common.Lib.Models

{

    public class Model : IModel

    {

 

        #region IModel Members

 

        public System.Data.DataSet GetData(string filename)

        {

 

        }

 

        #endregion

    }

}

To fill the method in, we add the following code:

            string connectionString =

                @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\csvfiles\;Extended Properties=’text;HDR=Yes'”;

            string commandText = string.Format(“Select * from {0}”, filename);

            OleDbConnection conn = new OleDbConnection(connectionString);

            OleDbCommand cmd = new OleDbCommand(commandText, conn);

 

            conn.Open();

            OleDbDataAdapter da = new OleDbDataAdapter(commandText, conn);

            DataSet JobData = new DataSet();

            da.Fill(JobData);

            return JobData;

This is going to some of the hard work for us. Of course you are free to get the data from any source that you want to. Basically all we are doing here is using OLEDB to open a file in the csvfiles directory on the C drive and filling a DataSet with the data in the file. Of courses for production code you would check for errors and take appropriate action but this is just an example. That’s all there is to do for the Model.

This is a zip with the project so far. Rename the .doc to .zip before you open. This is a wordpress requirement.  modelszip

Winforms – Model-View-Presenter – Part II The interface January 27, 2009

Posted by wesaday in Programming.
Tags: , , ,
3 comments

This is part II of the MVP series for Winforms.

For this example we are going to create a very simple application. Our example is going to load a CSV file and display it in a data grid. But, it’s not what the application does that is important. The important thing is how the application does it. The final application will look like this:

 

app 

Interface this!

The key to the whole thing is the interface. Now the interface is kind of a strange animal to me.  An interface is declared in code like this:

    public interface IMyInterface

    {

       

    }

In my previous work, an interface was basically a set of functions that you could call on objects and get results back. In the .NET world and interface is an actual object. Not only can you pass an interface between other objects but you can assign the interface to a variable like any other data type!

    public class MyClass

    {

        private IMyInterface myInterface;

    }

The purpose of the interfaces is to allow the Presenters to communicate back to the View in a loosely coupled way. The Presenter uses the interface to update the data that the View is showing to the user.  And that is what we are going to do now. It is important to note that the interface defines a type of contract. It does not actually contain any code on its own but causes the class that inherits the interface to implement the contract. Right click on the Interfaces folder in the solution, then select Add, then New item.  Select Code File and name it IBaseInterface, then click Add,

interface

 

This interface will just serve as a base interface that all the other interfaces can inherit from. For this example this interface will not actually do anything. Define the interface,

namespace Common.Lib.Interfaces

{

    public interface IBaseInterface

    {

 

    }

}

The Main View interface

Save that file and repeat the process only name this interface IMainView. This class is going to serve as the interface the Presenter is going to use to communicate with the Main view. Define the interface and inherit from our base interface,

namespace Common.Lib.Interfaces

{

    public interface IMainView : IBaseInterface

    {

       

    }

}

Now what we are wanting to do is to display some data in a DataGridView on the main form. So since the main form is going to be implementing the interface. How that is going to be done is to databind the data to the grid. So, what we want the interface to do is to expose a property that will be used by the Presenter to supply the data. So, add a property to the interface that is a DataSet type with a property setter,

    public interface IMainView : IBaseInterface

    {

        DataSet CSVData { set; }

    }

 

To use the DataSet type you will have to add a using System.Data statement to the file. The entire file looks like this:

 

using System.Data;

 

namespace Common.Lib.Interfaces

{

    public interface IMainView : IBaseInterface

    {

        DataSet CSVData { set; }

    }

}

The Model interface

Now we are going to define an interface for the Model. Add a new code file and name it IModel. The Model interface is going to define the function that will be used to retrieve the data from the file (or where ever else you want to get it from). Since we defined that the data would be in a DataSet, we need a function that will return a DataSet. So add a function definition GetData that takes the name of the file as a string and returns a DataSet:

    public interface IModel

    {

        DataSet GetJobData(string filename);

    }

Remember to add the System.Data namespace to the top of the file.

using System.Data;

 

namespace Common.Lib.Interfaces

{

    public interface IModel : IBaseInterface

    {

        DataSet GetData(string filename);

    }

}

That’s it for the interfaces. This is a Visual Studio 2008 solution with our app so far. Rename the file from .doc to .zip, this is a wordpress requirement. interfaceszip

Winforms – Model-View-Presenter – A tutorial, the introduction January 27, 2009

Posted by wesaday in Programming.
Tags: , , , ,
4 comments

Introduction

Coming from a C/C++ and diving into the .NET, I am constantly surrounded by strange phrases, three letter acronyms and concepts that take a long time to get used to. One of those concepts is the Model-View-Presenter (MVP).  There are plenty of articles about MVP around the Web. Most are pointers to Martin Fowler (http://www.martinfowler.com/eaaDev/uiArchs.html) or the MSDN (http://msdn.microsoft.com/en-us/library/cc304760.aspx). There are also many articles on Code Project (www.codeproject.com). The problem that I have had in the reading of these articles is that most use big $.25 words and unfamiliar phrases that mean nothing to the beginner, along with diagrams that are just plain confusing. Nothing I found that was in plain simple English. After a lot of trial and error and study I think I finally have something that I can understand. I do not pretend that this is the “right way” or the only way but it works for me.

This is the first part of five. Links to the other parts are:

     Part II

     Part III

       Part IV

       Part V

 

MVP

The goal of using the MVP design pattern is to separate the responsibilities of the application in such a manner as to make the application code:

·         Testable in an automated manner

·         Make the application more maintainable

·         Make the application more extensible. 

The first bullet means that there are many tools out there in the world that can be used to test code in an automated manner, called “unit testing”. These tools cannot test code that is in form code-behind modules. So the aim is to take that code out of the form code and place it in a DLL that can be tested.

I do not know about anyone else, but for me application code is way more maintainable when it is separated out into modules that have a specific purpose. If something unexpected feature does make it through the unit testing, then you will have a pretty good idea where to look just based on knowing what the various classes’ responsibilities are.

The extensibility part comes in when you have this separation of concerns, adding additional functionality is made easier because the code modules are not closely tied together also known as “loose coupling”.

What does it all mean?

The first thing is to understand the meaning of what the terms mean.

View: A view is any form or window that is shown to the user of the application.

Presenter: The presenter is an entity that presents the data to the view that is to be shown to the user.

Model: The model is the actual data that the Presenter will request and gets displayed in the View. The Model is responsible for obtaining the data. So the Model is the one that reads files, or connects to a database or if you are really ambitious, gets the data from a data service object.

The pattern is typically drawn like this.

uml1 

Looks simple doesn’t it? Well what all those other articles, and examples, didn’t tell me was how to turn that simple diagram into a working application.

Get on with it already!

The first thing to do is to setup the solution. Open up Visual Studio and create a new Windows Forms Application.

 newproject1

 

Once Visual Studio is through creating your new project, add a class library to the solution to hold all of the various classes. Right click your solution object in the Solution Explorer, select Add then Add new project.

 addnew1

 

classlibrary 

 

I named mine Common.Lib.dll you can name yours whatever you want to. I have seen some people that create a class library to contain the business logic and another one to contain the data layer. I think is overkill for this simple example. Go ahead and delete the Class1.cs file that Visual Studio created for you.

I like to compartmentalize things so I group like classes together. Right click on the class library project; select Add then Select New Folder. Name the new folder, Interfaces. Repeat twice more and name the other two new folders Models and Presenters. Your project should now look like this.

solutionex

This is the end of Part 1. After starting the article it quickly grew to 14 pages and I was not done yet so I elected to post a series of pages.

 

This is the project skeleton so far. Change the extension from .doc to .zip before you open it. This is a workpress requirement. projectskeletonzip

Road rage January 17, 2009

Posted by wesaday in Politics.
Tags:
1 comment so far

No not the kind you think. When we bought our house several years ago, one of the things that appealed to us was that the road was a dead end road. The place used to be an orchard/farm and most of the road was a one lane country road. A nice quiet neighborhood, very little traffic on a private road. Once a year a private company would come in and patch the road. Little traffic so the road wasn’t all that bad most of the time.

Looking north from my house
Looking north from my house 

The road here is approximately 12 feet wide. Notice the lack of drainage and sidewalks.Well in 2007 or maybe early 2008 some moron in the city decided that our road didn’t need to be private anymore. So without any regard for the residents wishes or safety they made an arbitrary decision to open our road as a thouroughfare without informing the residents of what was going on. We had no idea at the time that they was removing the barrier at the end of the street until the barrier was gone that the Indianapolis 500 had started racing down our road. Since opening the road up to the public, our road has deteriorated and of course it isn’t getting fixed.road2road3 This is the far north end of the road. It’s remained pretty much like that since we moved in about 5 years ago. Complaints to the city get ignored. I complained about this situation in May 2008 and was told that there were “4 projects” going that would fix the road in 2008. Ha! Of course not. These pictures were taken mid Januaray 2009. As you can plainly tell the road has not been fixed nor has there been any attempt to. road4 Looking north from the other end of the street. This is the worst section of the road. road51road61

Notice still the lack of curbs, sidewalks and if you are really observant, you will notice that there are not even street lights!

 road71road81

Seeing that contacting the city road department didn’t get anywhere, I had a radical idea or going over their heads. I would email the mayor and the city council to come over and talk my evening walk with me and see for themselves how bad the road is an how incredilby dangerous it was to walk down the road in the dark.

road101road91

Not to mention that kids play in the street. Yes the one lane country road where dumb ass teenagers fly down the road at 40 – 50 mph without hands on the wheel because they are too busy texting. Well anyway, the mayor and the city council do not have an email address. But I did find an email address for something call the Citizen Advocate. I thought, “Ah ha! Perfect. Who better to champion the cause for the poor downtrodden citizen against the unrightgeous city government!” road111road121

So I contacted her at the end of December telling her that the road was totally substandard and not acceptable. And that I owuld be more than happy to escort the mayor and anyone else around on my evening walks to see for themselves. After all, they would not stand of their street to look like this I do not see why they would expect me to.

road161

The advocate passed my email along to the road department to answer (Of course, what else did you expect to happen? Some sort of action?) and so far nothing.

road171 Looking south down the street. For the space of 4 houses the road is wider, there are sidewalks and street lights. So yes I am mad about the condition of the street my house sits on. Seeing that the city ruined the neighborhood, I don’ t have much of a chance selling my house with the street in that condition so we can moved to a safer, quieter neighborhood.