I have been involved developing a C#.Net Compact Framework project were we are using Model-View-Presenter(MVP) pattern for quite a while now and I would like to share my experiences learned during this project with you.
First of all, using MVP in a Compact Framework project is done exactly the same way as you would do it for standard C#.Net (or any other programming language). For some reason (unknown to me) developers tend to skip using patterns in mobility projects. I guess they think that good architecture is not necessary in smaller projects, like mobility projects often are. Wrong! As a developer you should strive to achieve good architecture in your projects no matter what size or complexity they have. What pattern to choose is of course another discussion. We chose to base the project architecture on the MVP-pattern and succeeded doing so. Let me walk you through how we ended up using it.
The figure below shows how the MVP components interact with each other. The View are implemented in the screens (forms) and the Presenter presents the data to be displayed to the View. The Presenter is responsible for the business logic and retrieve/save data to the Model. The Model will often interact with a Data Access layer (left out in this example for simplicity). The Model will also have business specific objects that both the Presenter and View can use, but the View will never ask the Model for data or save data to the Model.

The objects passed between the MVP components should be defined by interfaces, by doing so you have isolated the Model, View and Presenter. You can now easily change your GUI without changing the business logic. You can also change the business logic with out changing the GUI. The business logic are totally separated from the GUI and the Data Access are also separated from the business logic. Sweet
I have created a simple MVP Concept project with a simple login screen. The user enters user name and password and by clicking the login button the login data will be validated and the result presented to the user.

Above you can see the simple screen for this login example (In a real project I will never use the built in GUI controls from Compact Framework, they just don’t look good enough. Most of the time I end up making my own custom controls/components to be able to have the look & feel I desire). OK, enough talk let’s look at some code:
The ILoginView interface will be implemented in the LoginScreen and the interface will be used by the LoginPresenter to know what methods to call.
The ILoginView interface
namespace MVP
{
public interface ILoginView
{
void InitializeView(TViewData viewData);
void LoginValidated(bool loginSuccessful);
}
}
The LoginViewData represents the data that the Presenter will be able to send to the View.
The LoginViewData class
namespace MVP
{
public class LoginViewData
{
private string _header;
private string _lbUserName;
private string _lbPassword;
private string _lbLogin;
public string LbLogin
{
get { return _lbLogin; }
set { _lbLogin = value; }
}
public string LbPassword
{
get { return _lbPassword; }
set { _lbPassword = value; }
}
public string LbUserName
{
get { return _lbUserName; }
set { _lbUserName = value; }
}
public string Header
{
get { return _header; }
set { _header = value; }
}
}
}
The ILoginPresenter will be implemented by the LoginPresenter
The ILoginPresenter interface
namespace MVP
{
public interface ILoginPresenter
{
void InitializeView();
void ValidateLogin(string userName, string password);
}
}
The LoginPresenter will populate and send data to the LoginView. It will also be responsible to process data from the View, in this case it will be to validate the login data.
The LoginPresenter class
namespace MVP
{
public class LoginPresenter : ILoginPresenter
{
private ILoginView _currentView;
public LoginPresenter(ILoginView view)
{
_currentView = view;
}
public void InitializeView()
{
LoginViewData viewData = new LoginViewData();
viewData.Header = "MVP Concept";
viewData.LbUserName = "User name:";
viewData.LbPassword = "Password:";
viewData.LbLogin = "Login";
_currentView.InitializeView(viewData);
}
public void ValidateLogin(string userName, string password)
{
// Validate user name and password
bool loginSuccessful = Login(userName, password);
//Send response to view
_currentView.LoginValidated(loginSuccessful);
}
private bool Login(string userName, string password)
{
// Try to login to system...
// Asume login was successful in this concept project
return true;
}
}
}
The LoginScreen implements the ILoginView and creates the LoginPresenter and ask for data to display. It also ask the LoginPresenter to validate the login data.
The LoginScreen class
using System;
using System.Windows.Forms;
namespace MVP
{
public partial class LoginScreen : Form, ILoginView
{
private LoginPresenter _presenter;
public LoginScreen()
{
InitializeComponent();
}
private void LoginScreen_Load(object sender, EventArgs e)
{
if (_presenter == null)
{
_presenter = new LoginPresenter(this);
_presenter.InitializeView();
}
}
public void InitializeView(LoginViewData viewData)
{
_lbHeader.Text = viewData.Header;
_lbUserName.Text = viewData.LbUserName;
_lbPassword.Text = viewData.LbPassword;
_btnLogin.Text = viewData.LbLogin;
}
private void _btnLogin_Click(object sender, EventArgs e)
{
_presenter.ValidateLogin(_lbUserName.Text, _lbPassword.Text);
}
public void LoginValidated(bool loginSuccessful)
{
if (loginSuccessful)
{
// Go to next screen...
}else
{
// Display feedback to user...
}
}
}
}
The LoginScreen is a partial class also containing auto generated code for the GUI seen in the image further up. I do not bother to show this in my example here. This is a very short and simple code example showing the MVP concept. You can of course isolate the View even more from the Presenter by introducing a ILoginData and pass this to the presenter instead of the string userName and string password I used in this example.
The beauty of the code above is that you have separated business logic from GUI, it’s easy to know were to look when you need to do changes in your code. It’s also easier to introduce unit testing to the projects with this kind of isolation.
Sure, you need to create more classes but it’s worth it!
You might also be interested in reading how to use the Model-View-Presenter pattern in Windows Phone 7 projects.
Follow me on twitter @PerOla
Share & enjoy
You can subscribe to my comments feed to keep track of new comments.
23 Comments to “Using Model-View-Presenter (MVP) pattern in Compact Framework”
4 Pingbacks to “Using Model-View-Presenter (MVP) pattern in Compact Framework”
-
[...] project will be based on the Model View Presenter pattern (previous post about MVP). I have created a solution in Visual Studio 2008 called RunSmartWithMe, to this solution I have [...]
-
[...] The following code examples are using the Model View Presenter (MVP) pattern. I will not explain the pattern in this post, but if you want to know more about the MVP pattern you can have a look at a previous post I have written: Using Model-View-Presenter (MVP) pattern in Compact Framework. [...]
-
[...] describing the MVP-pattern since I covered that pretty well in another post I wrote a while back: Using Model-View-Presenter (MVP) pattern in Compact Framework. What I will do is to show an example on how you can design your Windows Phone 7 app architecture [...]
-
[...] describing the MVP-pattern since I covered that pretty well in another post I wrote a while back: Using Model-View-Presenter (MVP) pattern in Compact Framework. What I will do is to show an example on how you can design your Windows Phone 7 app architecture [...]













Great clear and simple post on MVP. I am wandering why all the UI patterns effort is aimed at WPF and Silverlight but not including WinForms and ASP net. I would think the same base model could apply for all these platforms. I just ran into one framework supporting Compact Framework MVC# ( at http://www.mvcsharp.org/Default.aspx ) which I will investigate further.
Hi Ragnar, the framework you mention looks interesting. Please let me know what you think about it when you are done looking at it. I think that most patterns should be able to use no matter what technology you are using. The pattern will be the same but of course the implementation will differ.
Hello,
I think that,
//Send response to view
_currentView.LoginValidated(loginSuccessful);
in LoginPresenter is not neccessary. Because
LoginPresenter could like this:
public void ValidateLogin(string userName, string password)
{
// Validate user name and password
return Login(userName, password);
}
and LoginScreen could like this:
private void _btnLogin_Click(object sender, EventArgs e)
{
bool loginSuccessful = _presenter.ValidateLogin(_lbUserName.Text, _lbPassword.Text);
if (loginSuccessful)
{
// Go to next screen…
}else
{
// Display feedback to user…
}
}
What do you think about that?
Why could be good doing the way was posted?
Anyway thanks for the post!!
Hi Raùl.
Doing it the way you suggested will work. I did it this way because I do not want the View to pull data direct from the Presenter. I do not want this kind of coupling between the View and Presenter.
The View simply sends a request to the Presenter and the Presenter is responsible for executing the request and to send a response to the View.
Since the LoginValidated is defined in the ILoginView I have ensured that if I change the View (maybe I want a web view to use the same Presenter) then the View must implement the LoginValidated method and I do not need to touch the LoginPresenter class.
Do you see the advantages now by doing it this way?
Thanks for the comment.
Hi Per Ola Sæther,
One advantage I see doing like you post is that code is more readable because it has an explicit line with “_currentView.LoginValidated(loginSuccessful);”. If I use “return blablabla” it´s more dificult to locate the endpoint.
So, I think it´s more important clear code. Your approach like me.
But I have another comment, Why LoginValidated is not outside the view? If you implements a new View for Login this method has to be duplicated and it should be the same for all login views.
Thanks,
This is dependent on the specific project you are using this for. Most likely if you have different Views (ex. web and mobile) you will handle a successful login in separate ways. You will have different controls in your view and the logic will probably be different as well. This is why I like to define these methods in the interface and implement them for each View.
If you discover that you will handle the LoginValidated equally in your different views I would move the LoginValidated code out to a Util/Support class but still have the LoginValidated method implemented in both my views:
Something like this:
public void LoginValidated(bool loginSuccessful)
{
LoginUtil.LoginValidated(loginSuccessful);
}
This way you are not duplicating the code, the code is clean and you have the possibility to handle LoginValidated differently in different views if needed.
Hi Raúl.
I think from your comments above that you maybe are missing the key part of this MVP implementation, – The goal of flexibility through use of interfaces.
Having the presenter do its work based on an interface contract, knowing that whatever called the presenter, it is bound by a common understanding of what methods exist.
If you have two views that implements the ILoginView interface you still would have two concrete implementations of the LoginValidated method. Each of the methods could of course again call a common helper util if you have similar functionality in both screens. But to achieve the flexibility of being able to implement alternative view implementations (could be silverlight or asp.net) you need to have “duplicate” methods in both concrete views.
I have written a post in my own blog that details the same MVP pattern design. This is a pattern and implementation both of us (we are co-workers) have found very useful in our projects. http://agilemobility.net/2009/10/14/setting-up-a-maintainable-windows-phone-project-in-visual-studio-2008/
Hi Alexander,
I understand the flexibility using interfaces, but i was thinking in a concrete case, implementing two equals view in winforms, and not in differents technologies.
I am trying to implement something like Microsoft CAB in Java, I need this kind of approaches like this post to glue all the ideas I have.
Thanks for your explication,
Hi Raúl,
The way to use MVP-pattern as described in this post is simply best practices that we have found/created during several projects. The good thing with patterns is that you can adopt a pattern and use it in a way that suits your project the best.
So you are developing a Composite UI Application Block for Java? Sounds interesting, keep me posted on your progress. I have earlier been heavily involved in creating a UI library for Java ME.
Good luck with your project
Hi Per Ola,
Ok, I am working hard to implement it, now I have a little part. A dinamic Menu generation, dinamic status bar generation, a login frame and a lot of the basic framework. I could send you the code if you want.
My idea is let this framework could work with Desktop and Web Java apps.
Hi, Raúl,
Sure you can send the code, but I can not promise that I will be able to help you or when I will have time to look at it. My days are kinda crazy right now.
You find my contact info in the about page (www.breathingtech.com/about)
Thank you for this post! So far it is the best and most complete I have found on the internet that helped me to understand in practice how the MPV works.
Do you know where I can look further for any related to yours example?
Hi George,
I am glad that you found the post helpful. What more do you want to know about MVP-pattern?
A lot of the examples found on the internet are incomplete and not very useful, that was why I wrote this post in the first place
Yeah, it is very true that it took me long time to find an easy to follow example considering that I am a new in the MVP concept.
Your sample gave me a lot of help. I am developing a GPS application using the GPS.NET 3.0 library and I have used your sample as a core. Thanks a lot!
OK. Microsoft have a GPS example delivered with the Windows Mobile 6 SDK. Just compile this project and add the Microsoft.WindowsMobile.Sample.Location.dll to your project and you are ready to use the GPS (http://msdn.microsoft.com/en-us/library/bb158708.aspx).
You can also use the FakeGPS utility tool by Microsoft to emulate GPS in the emulator (http://msdn.microsoft.com/en-us/library/bb158722.aspx).
Good Luck!
Hey, thanks for the info.
Let me also mention you the GPS.NET 3.0
“Formerly commercial .NET component maintained by GeoFrameworks, LLC from 2004 to 2009. In 2009, Jon Person”
“…Automatic detection of serial GPS devices (or devices found via a virtual serial port”
“Support for the GPS Intermediate Driver on Windows Mobile 5.0+”
http://gps3.codeplex.com/
Here is the documentation
http://www.gpsdotnet.com/Documentation/Product36.aspx
I know you are also developing your “pet” so you may find it useful, I have tested the library and it’s briliant. A good examle for starting can be found here:
http://gps3.codeplex.com/Thread/View.aspx?ThreadId=64812
Please note that is not working with the FakeGPS , you will need to debug it from your device.
The library seems to have an emulator but I haven’t looked on that yet.
Hi George,
Thanks for the GPS .NET 3.0 information. I have had a quick look at it and I like what I see. By using this framework you will be able to develop a much more sophisticated GPS application than you will by using the WindowsMobile.Sample.Location project.
I will for sure consider using this framework in my pet project.
Thanx
This is really a good example of the MVP…
can you tell me where i can find more complex examples?
Hi Sri: I am glad that you liked this MVP example. I do not know if there are more complex examples else where. I think that this should be enough to start using MVP and also to build quite complex solutions on MVP. Just follow the basic pattern described here.
Great concise article. I am a .NET developer but have been applying this to some J2ME projects recently. I am curious if you have used this pattern beyond a design guide and in a perhaps more concrete implementation. If you needed multiple ILoginView implementations for different mobile devices, for example, how would it be decided which ILoginView to use… eg. LoginScreen or WidescreenLoginScreen. Something like that.
Also, if you had a few similar views like IEmployeeView, IEmployerView, IContractorView… would you create an IPersonView from which the former views inherited? Just curious.
Hi Jeff, thank you for your comment.
I have used this pattern in three .NET Compact Framework projects at my work (three different industrial applications for external customers) and I am also using this pattern for one of my pet projects.
I have not had to handle different devices and screen sizes, the project are running on rugged devices with a fixed screen size. As I see it the ILoginView is implemented by your Screen and used by your Presenter. So the LoginScreen and the WideScreenLoginScreen will implement the same ILoginView and use the same Presenter. The functionality and data are similar for your two screens, only the layout differs. The layout should be handled in your Screen and not in the view or the presenter.
If you have several similar Views then I think you should use inheritance were you find that natural. As in all other patterns you do not want to duplicate your code. I also often create one or several “super” screens containing buttons, headers and common functionality and then all other screens in my project inherit from these.
Hi Per Ola,
I enjoyed reading your post. great read. very clear with regards to MVP implementation.
I need some feedback with regards to the LoginValidated method in the LoginScreen class.
it says
if (loginSuccessful)
{
// Go to next screen…
}else
{
// Display feedback to user…
}
My initial thoughts was to code the following in the else block
MessageBox.Show(“Incorrect login”);
Should I do this? or should i be activating the messagebox from the presenter? I am concern that I am not following the MVP principles. or maybe I should create another method in the ILoginView interface with the following
void FeebbackMessage(string message);
and in my LoginPresenter class, I have the following
public void ValidateLogin(string username, string password)
{
if (username.Equals(“”) || password.Equals(“”))
{
_currentView.FeedbackMessage(“Please enter Username/Password”);
}
else
{
// Validate user name and password
bool loginSuccessful = Login(username, password);
// send response to view
_currentView.LoginValidated(loginSuccessful);
}
}
What should be the best practice here? thanks again for your post.
Hi Chamkaur, I am glad that you enjoyed reading the post.
I would not let the presenter call a FeedbackMessage method in the view. The easiest is to let the presenter handle data and pass data on to the view. It is the views’ responsibility to decide what to do with the data from the presenter.
One solution could be to add one more parameter to the LoginValidated method for example LoginValidated(bool successful, string message)
This way you can also pass on the error message from the presenter if any and display this in your view.
I often tend to do simple not null or empty test in the view without calling the presenter with those data.
I hope this answered your question.