Dusan Czupek's blog

Blog related .NET, Android & web development

Recent posts

Tags

Categories

Navigation

Pages

    Archive

    Blogroll

      Disclaimer

      The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

      Simple validation in Model View Presenter

      Last time I wrote about how to implement simple page by Model View Presenter pattern.  Quickly we created form with 2 textboxes, label and button for firing presenter method SaveData. This time let's focus a bit to validation in presenter and co-working your page with validation result. Why validation in present Let's imagine we have form for validating user contact information. I will assume that you will have presenter in separate assembly. The assembly it self will contains interface of view (used for communication between presenter and page) and presenter logic (presenter logic and interface of presenter). 1) create new assembly, call it for example WebAppPresenter. Create new interface for View namespace WebAppPresenter { public interface IDataView { string FirstName { get; } string LastName { get; } string EmailAddress { get; } string Status { set; } } } Another one for interface of presenter namespace WebAppPresenter { public interface IDataPresenter { void SaveData(); bool AreDataValid(); } } 2) the Presenter will implement IDataPresenter inferface created above. using System; using System.Text.RegularExpressions; namespace WebAppPresenter { public class DataPresenter : IDataPresenter { private IDataView _view; public DataPresenter(IDataView view) { _view = view; } public void SaveData() { if (AreDataValid()) { _view.Status = "Data could be saved"; } } public bool AreDataValid() { if (String.IsNullOrEmpty(_view.FirstName)) { _view.Status = "First Name cannot be blank"; return false;} if (String.IsNullOrEmpty(_view.LastName)) { _view.Status = "Last Name cannot be blank"; return false; } if (!String.IsNullOrEmpty(_view.EmailAddress)) { if (!Regex.IsMatch(_view.EmailAddress,@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")) {_view.Status="Email address is not valid!"; return false;} } else { _view.Status = "Email address is not valid!"; return false; } return true; } } } Let's stop for a while to describe what is happening here. Constructor populating user entries from webpage through IDataView interface. Method SaveData executes validations and set Status based on validation results. The AreDataValid method is the one which is responsible for validation within presenter. It goes through user inputs present in property _view, validating each value and if one of the field is invalid set Status with proper error message. Because AreDataValid method is present in interface and it's public can be called directly from webpage for example to prevent execution of other code (such SaveData() ) once the input data are not in good shape. It's up to you whether you make validation method visible outside presenter.   3) Now let's make user interaction with presenter. So firstly create some form for getting information from visitors: (extract from the page) <form id="frmContact" runat="server"> First name:<asp:TextBox ID="tbFirstName" runat="server" /><br /> Last name:<asp:TextBox ID="tbLastName" runat="server" /><br /> Email Address:<asp:TextBox ID="tbEmailAddress" runat="server" /><br /><br /> Result:<asp:Label ID="lblStatus" runat="server" /><br /> <asp:Button ID="btnSave" runat="server" Text="Submit" /> </form> 4) Code behind of the page. Firstly do not forget to inherit from the View (in my scenario it should be IDataView) to be able make connection between Presenter and View layer. public partial class MyPage : System.Web.UI.Page,IDataView { #region IDataView Members public string FirstName { get { return this.tbFirstName.Text; } } public string LastName { get { return this.tbLastName.Text; } } public string EmailAddress { get { return this.tbEmailAddress.Text; } } public string Status { set { this.lblStatus.Text = value; } } #endregion protected void Page_Load(object sender, EventArgs e) { } } I inherited from IDataView to be able implement it's members and connect them with the webform 5) In Page_Load() method is good to connect to the Presenter and initialize it. protected void Page_Load(object sender, EventArgs e) { IDataPresenter _presenter = new DataPresenter(this); } Notice that Presenter constructor had one parameter in its definition and that parameter is the View. So when I initializing presenter I need to populate it with the View. In my scenario View will be webform it self because it inherits from IDataView, so I can use this object. 6) Now just need to wire up button btnSave click event to launch SaveData method from Presenter. protected void Page_Load(object sender, EventArgs e) { IDataPresenter _presenter = new DataPresenter(this); btnSave.Click += delegate{ _presenter.SaveData(); }; } As I mentioned above you can also call the _presenter.AreDataValid() first and then based on the result call _presenter.SaveData()
      Posted: Sep 24 2009, 22:49 by dczupek | Comments (0) RSS comment feed |
      • Currently 1/5 Stars.
      • 1
      • 2
      • 3
      • 4
      • 5
      Filed under: dotNet

      Model View Presenter (MVP) Pattern

      Model-View-Presenter is a user interface design pattern engineered to facilitate automated unit testing and improve the separation of concerns in presentation logic. The Model is an interface defining the data to be displayed or otherwise acted upon in the user interface. The View is an interface that displays data (the Model) and routes user commands to the Presenter to act upon that data. The Presenter acts upon the Model and the View. It retrieves data from repositories, persists it, manipulates it, and determines how it will be displayed in the View. The degree of logic permitted in the View varies among different implementations. At one extreme, the View is entirely passive, forwarding all interaction operations to the Presenter. In this formulation, when a user triggers an event method of the View, it does nothing but invoke a method of the Presenter which has no parameters and no return value. The Presenter then retrieves data from the View through methods defined by the View interface. Finally, the Presenter then operates on the Model and updates the View with the results of the operation. Other versions of Model-View-Presenter allow some latitude with respect to which class handles a particular interaction, event, or command. This is often more suitable for web-based architectures, where the View, which executes on a client's browser, may be the best place to handle a particular interaction or command. From a layering point of view, the Presenter class might be considered as belonging to the application layer in a multilayered architectured object-oriented system with common layers but it can also be seen as a Presenter layer of its own between the Application layer and the User Interface layer.   Sample of MVP implementation in few steps: 1) create an interface (later in the topic will be note like view-interface ) with properties  which will contain values from webpage/form. public interface IDataView { string FirstName { get; } string LastName { get; } string Status { set; get; } } 2) make webpage/form to implement this interface public partial class MyPage : System.Web.UI.Page,IDataView   3) implement interface members and map them to webpage/form entries (such labels, textboxes, etc.) public string FirstName { get { return this.tbFirstName.Text; } }public string LastName { get { return this.tbLastName.Text; } }public string Status { set { this.lblStatus.Text = value; } get { return this.lblStatus.Text; } }   4) create new class for presenter public class DataPresenter { }   5) declare a variable of view-interface type (created at point 1), variable value will be initialized through constructor public class DataPresenter{ private IDataView _view;}   6) create/extend constructor with input parameter of view-interface type public class DataPresenter{ private IDataView _view; public DataPresenter(IDataView view) { _view = view; }}   7) create public method(s) for manipulate with view public class DataPresenter{ private IDataView _view; public DataPresenter(IDataView view) { _view = view; } public void SaveData() { _view.Status = string.Format("FirstName={0}; LastName={1}", _view.FirstName, _view.LastName); }}   8) in webpage/form create an instance of the presenter, constructor requires input value of view-interface type. Because the webpage/form already implements an view-interface, input value for constructor will be this. private DataPresenter _presenter;protected void Page_Load(object sender, EventArgs e){ _presenter = new DataPresenter(this);}   9) now you can calling presenter’s method(s) from the events etc. If the presenter method change view’s data you’ll get back updated data automatically based on mapping from point 3. protected void Page_Load(object sender, EventArgs e){ _presenter = new DataPresenter(this); btnSave.Click += delegate { _presenter.SaveData(); };}   In my sample I called the SaveData method on  _presenter presenter.
      Posted: Jun 30 2009, 19:56 by dczupek | Comments (1) RSS comment feed |
      • Currently 4.333333/5 Stars.
      • 1
      • 2
      • 3
      • 4
      • 5
      Filed under: dotNet