User input validation in MVP pattern - c#

I want to validate the details provided by the user before taking them into the processing.
My UIs have Text boxes, Combos mainly. In some fields, user must provide data, in some fields only certain type of data may will be accepted like texts, Dates/times, numbers etc. When it comes to date/ time we should check whether the provided values are in the valid range.
My question are
Q1. Where to do validation in MVP pattern?
My options are
Implement validation as a service available to Presenters. (Through DI for ex.)
Do the validation in the UI itself in a event like KeyPress.
Presenter itself handles the validation.
Q2. How to do the validation.
My options are
i. All controllers like text boxes in the View are encapsulated in properties (Getters / Setters)
public string Age
{
get { return txtAge.Text; }
set { txtAge.Text = value; }
}
ii. UI fires the event Validate(sender, e)
iii. Presenter listen and hook it up to the handler which then invokes Validate() method
iv. In Validate() method it'll detect the controller raised the event (sender) and read the corresponding property to get the value in the controller.
v. Then it will check the type against the type in the model and decide the validity and then alert the user
The problem here is that I may have to expose all controllers through string properties as other wise it will give exceptions when the user enters an invalid type.
If I do something like this
public int Age
{
get { return Convert.ToInt32(txtAge.Text); }
set { txtAge.Text = Convert.ToString(value); }
}
Then the problem would be the presenter cannot do the validation as already its converted to int?

Where to do validation in MVP pattern
Implement validation as a service available to Presenters. (Through DI for ex.)
Do the validation in the UI itself in a event like KeyPress.
Presenter itself handles the validation.
It depends - there is no "one size fits all", you have to make a decision for each kind of validation.
Think of what will happen if you change the View layer by a different one (with a different UI technology). This mental model helps to make the right decision, even if you use only one kind of UI. If the validations could be done in the presenter, they will available for every kind of view, without the need of reimplementing them. On the other hand, it is not wise to make too many assumptions in your presenter layer about the available events of the specific UI.
So as a general rule: put the validations into the view which depend on the specific UI (for example, validating directly for each "KeyPress" is a typical candidate for validation in the view). Put validations in the presenter which will be the same for each different View layer (type checking is an edge case, see below). If you have validation code which might be reused between different presenters, put that code into a helper class or service. And if this has to be a service provided by "DI" depends mainly if it is a very complex validation which needs to access the database or something like that.
Q2. How to do the validation.
[in case of type conversions]
Actually, if possible, avoid the necessity of doing type checking at the presenter level by restricting what the user can enter at the UI level. Most modern UIs (desktop and web as well) provide mechanics to forbid the entering of data if the data does not match a certain type. For example, use a specific number edit field. If such a thing is not available in the specific UI technology, you could still implement a type validation mechanics for each edit field only at the UI level, without involving the presenter. So I see this best handled at the View level.
Of course, similar types of validation (like a range check) might be better handled at the presenter level, since the test would be always the same, whatever View implementation you have. So they are better placed at the presenter level. But a range check does not provide you with the type conversion problem given in your question.

Related

How to avoid a databinding / events hell on a complex screen?

This is more of an architecture / design question.
I have run into a few projects in the past written in WPF/Windows Forms, etc. that have complex screens with a lot of fields and these fields are connected to each other (their values depend on each other with some logic involved).
These projects I have taken on after they were implemented, and I found a lot of events / data bind hell - what I mean by this is that because all these fields are depending on others they have implemented INotifyPropertyChanged and other fields are being modified as a result. This causes the same fields being updated 5-6 times when the screen loads and the order in which fields are populated causes horrible bugs. (For example, Date was set before Job Type, instead of after Job Type, so I end up with a different Job Fee.)
To make matters worse, some hacks are implemented on UI events (for example, DropDown changed to update field X) while others are in the domain model that the UI binds to.
Basically, it's a huge mess, and I just want to know what the best way to implement something like this is if I was to start from scratch. Or is it a good idea to avoid such a complex screen in the first place?
I would try to keep the business logic out of the property setters as much as possible.
First of all, if several properties are needed for one calculation, I'd write one method that does the calculation, and call that method when appropriate. E.g. if all different combinations of property values make sense, one could just call the method in the setters of each property, making sure that the same code runs any time one of the properties is changed. If you only can evaluate special combinations of property values, you could either implement a command and let the user decide when to calculate the resulting changes, or you could provide feedback through validation, and only evaluate the property changes if the combination is valid. If there are several interdependent properties, I often use a "ChangeInitiator" variable to indicate what property has changed, so that it is clear in the calculation method which property is responsible for the change and which others should change as a result. Basically, this is the same as doing one part of the calculation in each property setter, but I find that it helps me to keep an overview of things if the different parts of the relationship are all in one method.
In a program I wrote once, I had some calculations running on a background thread periodically, so I would just set a flag whenever a piece of data changed that required a new calculation, and do all the updates based on a timer every second or so... that could also help you get the logic more straight, and it avoids to have the calculation run several times for one set of related changes.
With regard to change notification, I'd really try to only use it for UI data binding.
We have fairly complex UIs (including several related fields of different types in, say for example a Row in a DataGrid) and the MVVM pattern has worked pretty well for us. All the properties coming from the Model and exposed to the View that have complex logic related are "wrapped" by an equivalent property in the ViewModel, which has no Backing Field, but rather points directly to the Model:
public class SomeComplexViewModel
{
public SomeModel Model {get;set;}
public string SomeCrazyProperty
{
get
{
return Model.SomeCrazyProperty;
}
{
Model.SomeCrazyProperty = value;
//... Some crazy logic here, potentially modifying some other properties as well.
}
}
}
<TextBox Text="{Binding SomeCrazyProperty}"/>
This removes the "initial value" problem, as the initial value read by the Binding is actually the real value coming from the Model, and thus the logic placed in the Setter is executed only when needed.
Then, for dummy properties (which have no logic behind), we bind directly from the View to the Model:
<TextBox Text="{Binding Model.SomeRegularProperty}"/>
This reduces the bloat in the ViewModel.
With regard to events in the code behind, I totally avoid that. My code behind files are almost always one InitializeComponent() and nothing else.
Only View-Specific logic is placed in the code behind (such as animations stuff, etc), when it cannot be directly done in XAML, or is easier to do in code (which is not the case most of the time).
Edit:
It's important to mention that the winforms binding capabilities are a joke compared to the XAML-based ones. could that be the cause you're seeing those horrible messes in those projects?

Is there a best practice way to validate user input? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Is there a best practice way to validate user input?
Actual Problem:
A user gives certain inputs in a window. When he is done with those inputs, he can click 'create'. Now, a pop up message should be shown with all invalid input given. If no invalid input, then just continue.
I could easily do this in the Form class. But I remember some best practice way of validating the input in the set properties. Problem is that I already created an instance of that class (or otherwise, can't set properties ;) ) if I validate this way. That should not happen, no instance of the class may be created unless input is valid.
I was planning to create a ErrorMessages class that contains a list where I can put all errorMessages. Every time an invalid input is given, a new message is added to the errorMessages list. So if user click's 'create' button, all messages in the list are shown. Is this a good way of handling things?
So is there a best practice way? Any design patterns that provide such solution?
Edit: This is a school task. So with illogical requirements. I HAVE to show all invalid inputs when I click 'create'. I would like to do this out of Form class. (So validation works even without GUI, I did't even create the GUI yet at this point). First making sure my functionality works correctly ;). I want to keep my code clean, abstract and OOP. So how should I show my error messages?
I was planning to create a ErrorMessages class that contains a list where I can put all errorMessages. Every time an invalid input is given, a new message is added to the errorMessages list. So if user click's 'create' button, all messages in the list are shown. Is this a good way of handling things?
Subjectively, I think it would be better to provide instant feedback that the value the user entered is invalid. That way, they can immediately go back and fix it.
I mean, think about it. The approach you propose would literally give them a giant list of problems at the end, which is not very user-friendly. Besides, how are they going to remember all of those problems to be able to go back and fix them one at a time? (Hint: they're not.)
Instead, I recommend using the ErrorProvider class to display any errors right next to the appropriate control. I talked a little bit more about this approach in my answer here and here.
Of course, you'll still need to make sure upon final submission (clicking the OK/Submit button) that all the input is valid, but then that's just a simple case of checking for the presence of any errors.
I could easily do this in the Form class. But I remember some best practice way of validating the input in the set properties.
Yes, the idea here is encapsulation. The Form class should only know about form stuff. It shouldn't be required to know what kind of input is/is not valid for all of your different controls.
Instead, this validation logic should be placed elsewhere, such as in a class that stores your data. That class would expose public properties to get and set the data, and inside of the setter method, it would verify the data.
That means that all your Form has to do is call a setter method on your data class. The Form needs to know nothing about how to validate the data, or even what the data means, because the data class handles all of that.
That should not happen, no instance of the class may be created unless input is valid.
If this is indeed the case, you will need to provide a constructor for the class that accepts as parameters all of the data it needs. The body of the constructor will then validate the specified data and throw an exception if any of it is invalid. The exception will prevent the class from being created, ensuring that no instance of a class that contains invalid data ever exists.
Such a class would probably not have setter methods at all—only getters.
However, this is kind of an unusual requirement in the world of C# (however common it may be in C++). Generally, placing your validation code inside of the setters works just fine.
My properties have some private setters. So they only get set in the constructor of my data class. Problem is now that this seems to make my validation not eassy
Why would that change anything? You still handle the validation inside of the private setters. If validation fails, you throw an exception. Because the constructor doesn't handle the exception, it continues bubbling up out of that method to the code that attempted to instantiate the object. If that code wants to handle the exception (e.g., to display an error message to the user), it can do so.
Granted, throwing an exception in the case of invalid input is not necessarily a "best practice". The reason is that exceptions should generally be reserved for unexpected conditions, and users screwing up and providing you with invalid data is, well, to be expected. However:
This is the only option you have for data validation inside of a constructor, because constructors can't return values.
The cost of exception handling is basically negligible in UI code since modern computers can process exceptions faster than users can perceive on-screen changes.
This is a simple requirement but sometimes being debated. This is my "current" approach how to deal with validation. I have not yet used this approach, and this is just a concept. This approach need to be developed more
First, create a custom validation attributes
public class ValidationAttribute : Attribute{
public type RuleType{get;set;}
public string Rule{get;set;}
public string[] RuleValue{get;set;}
}
Second, create a custom error handler / message
public class ValidationResult{
public bool IsSuccess{get;set;};
public string[] ErrorMessages{get;set;};
}
Then create a validator
public class RuleValidator{
public ValidationResult Validate(object o){
ValidationResult result = new ValidationResult();
List<string> validationErrors = new List<string>();
PropertyInfo[] properties = o.GetType().GetProperties();
foreach(PropertyInfo prop in properties){
// validate here
// if error occur{
validationErrors.Add(string.Format("ErrorMessage at {0}", prop.Name));
//}
}
result.ErrorMessages = validationErrors.ToArray();
}
}
To use it, then you can do like this:
public class Person{
[ValidationAttribute(typeof(string), "Required", "true")]
public string Name{get;set;}
[ValidationAttribute(typeof(int), "Min", "1")]
public int Age{get;set;}
}
To call the validator
public void ValidatePerson(Person person){
RuleValidator validator = new RuleValidator();
ValidationResult result = validator.Validate(person);
// generate the error message here, use result.ErrorMessages as source
}
What is the advantage:
You can use in any application platform (Winforms, Asp.Net, WCF,
etc)
You can set the rule in attribute-level
It can do automated validation
This approach can be used with DependencyInjection with custom
validators to separate validation logics
The disadvantage:
Hard to create the validators
If not handled well, the validators can become very large in number
Bad performance due to use of reflection
See the ErrorProvider class (documentation here). It provides a set of standard visual indicators that can be attached to most of the standard WinForms controls.
There are several possible approaches:
Use "instant" validation.
When user enters value it is checked during input (TextChanged) and validated right away. Create instance of a new class, call property/method what should accept string and return bool (or throw Exception in case of property), on false - draw special error condition (red label next to text box, something blinking, ErrorProvider or whatever you can do what should tell user "wrong!").
This one I like to use, but a bit differently, usually I only check Type and then just trying to parse it straight away in the form. It is possible to abstract more if form operate with the string's and all formattings and validation occurs in the class (property setters). Or you can supply form with additional information (by using query methods or attributes) so it can do instant validation without need to instantiate class or using setters. As example, double factor property can be identified in the form (or even control) to perform 'double.Parseand you can have attributeDefaultValuewhich can be used to display to the user value in the different way when it's different from default (like it is done byPropertyGrid`).
Use normal validation.
When user finished input, validate (by trying to set value and catching exception), if wrong - user can't "leave" or "progress" until he press ESC (to cancel changes) or correct his input to pass validation.
This one I dislike. Idea of holding user annoy me (and user ofc). Also it is hard to implement cross checks (like if you have Min and Max values, then user will be pushed to increase "right" one first, otherwise invalidation will fail).
Use "ok" validation.
That just means let user to enter everything and only validate when he clicks "Ok" button.
I think combining "Ok" button and interactive instant validation is the best for the user. As user knows where he made a mistake through input, but still is free to browse and only will get a "slap" from validation after clicking "Ok" button (at which step you can simply show him first of errors he did, not necessary to show them all).
Error messages can be provided by setters in the old-fashion LastError way or as a text in the Exception.

Requires a generic approach to validate control of ASP.Net form

I have a B2B we app having lots of forms taking input from registered users. So validation is mandatory there. I am using 3 tier architecture for my app. I am just ignoring server validation controls and client side validations. Instead i am thinking of Code Behind based validation, which i know will increase hit to my server, but too is most secure, if I am not wrong.
So what i am thinking is,
to enumerate all the controls of the page and check their validity. But this wayI can check only whether it is empty or not. Also I have to write it on each and every page.
Another approach, if i can set the maxlength , mandatory etc somewhere in my Model Layer where I have skeleton classes,and compare it while save button hit and tell what is missing and where.
Some common method that will take entire page controls as array of controls and check for validity...
Please guide me which one is possible or any other good solution.So that i can avoid code repetitions.
Model Layer means
public class Employee
{
public string Name {get;set;}
}
You can add a set of controls that inherit from ASP.NET controls, only with (a)additional type classification. For example: TextBox that accepts an attribute of DataType (enum) and values like: int, double, email etc. Another idea is for int type add a min/max values (i.e 15-32). And (b) a Validate function that returns true/false if the value matches the datatype.
Then, create a page base that inherits from Page and exposes a function called ValidateAllMyControls that iterates through all those special controls that are in use in the current form and calls the Validate function for each one. If one of them returns false - the form is not valid. :)

IDataErrorInfo and the property validation of an object

Since I am trying to learn WPF I see more and more the use of the interface IDataErrorInfo to bind the error to the interface. My problem is that I usually put the validation of the data in the setter of the property and not in a method like IDataErrorInfo.this[string columnName]... Here is a blog I have found that have make me confuse.
What is the good way to proceed in .Net 3.5 to validate data object? Do I need to implement validations in method called by the Setter AND the IDataErrorInfo? Or just the IDataErrorInfo? Or in the setter call the IDataErrorInfo?
Example: I have a firstname string that can have only 3 to 50 chars. Do I put the string validation in the setter (What I would do usually) or now I can simply use the IDataErrorINfo.this method, check the property name and return a String Error when the data is not the good length? I found more intuitive to throw an error in the setter and not using the Interface but most example I see use the IDataErrorInfo interface.
If you throw an exception in the setter, then IDataErrorInfo is redundant since it can't (in theory) get into an illegal state. IDataErrorInfo allows you to accept all input, but tell the user that there is a problem. The nice thing about this is that it allows less interruption to the UI (as the user can continue to enter data even though one field is in error and marked as such), and it is easy to report multiple errors at once - visually, rather than by message-boxes etc.
However, if you go this route you need to be sure to validate that the object is OK before saving it to a database, etc.
You could do this by checking .Error from your business logic (and check that it is null/empty), assuming that you write .Error to report all errors. Or a similar Validate() method.
I believe that the IDataError allows for a much richer user experience. Like Marc said, it allows less interruption, especially when editing a grid eg. a list of Customer objects.
I recommend you download the CSLA.net framework from www.lhotka.net, developed by Rocky Lhotka (He is the author of Expert C# 2008 Business Objects). This framework supports validation rules and each business object implements the IDataError. Each time a property is changed, the rules for that property are validated. If the property value is invalid, the object state will become InValid, causing a exception to be thrown whenever the Save() method is invoked.
His framework also supports n-level undo. When you start editing a business object, a snapshot of the object is taken (including the broken rules). So if you decide to rollback your changes, the state of the object returns to the previous state - even the broken rules!

Model view presenter, how to pass entities between view?

Edit : Accepted Chris Holmes response, but always ready to refactor if someone come up with a better way! Thanks!
Doing some winforms with MVP what is the best way to pass an entity to another view.
Let say I have a CustomerSearchView/Presenter, on doubleClick I want to show the CustomerEditView/Presenter. I don't want my view to know about the model, so I can't create a ctor that take an ICustomer in parameters.
my reflex would be,
CustomerSearchView create a new CustomerEditView, which create it's own presenter.
Then my CustomerSearchView would do something like :
var customerEditView = new CustomerEditView();
customerEditView.Presenter.Customer = this.Presenter.SelectedCustomer;
Other possible approach would be a CustomerDTO class, and make a CustomerEditView that accept one of those CustomerDTO, but I think it's a lot of work something simple.
Sorry for basic question but all example I can find never reach that point, and it's a brownfield project, and the approach used so far is giving me headache...
I don't know exactly how you are showing your views, so it's a bit difficult to give you specific advice here. This is how I've done this sort of thing before:
What we did was have the CustomerSearchViewPresenter fire an event like OpenCustomer(customerId). (That is assuming that your search view only has a few pieces of Customer data and the customerId would be one of them. If your search view has entire Customer objects listed then you could call OpenCustomer(customer). But I wouldn't build a search view and allow it to populate with entire objects... We keep our search views lightweight in terms of data.)
Somewhere else in the application is an event handler that listens for the OpenCustomer() event and performs the task of creating a new CustomerEditView w/ Presenter (and I'm going to defer to my IoC container do this stuff for me, so I don't have to use the "new" keyword anywhere). Once the view is created we can pass along the id (or customer object) to the new CustomerEditView and then show it.
This class that is responsible for listing the OpenCustomer() event and performs the creation of the CustomerEditView is typically some sort of Controller class in our app.
To further simplify this situation, I've done this another way: I create both the CustomerSearchView (& presenter) and CustomerEditView (& presenter) when the application or module starts up. When the CustomerSearchView needs to open a Customer for editing, the CustomerEditView becomes the responder to the OpenCustomer event and loads the data into itself, and knows how to show itself in whatever container it is supposed to do.
So there's multiple ways to do this.
How about:
//In CustomerSearchPresenter
var presenter = new CustomerEditPresenter();
var customerEditView = new CustomerEditView(presenter);
presenter.SetCustomer(customer);
//In CustomerEditPresenter
public void SetCustomer(customer)
{
View.Name = customer.Name;
View.Id = customer.Id;
...
}
In think your customer search view should just delegate to its presenter you need to have an action execute.
There are a couple of crucial insights to get a natural flow in any MVP code:
It's the presenter that drives the view, not the other way around.
Because of 1. the view need not know about the presenter's existence. Less dependencies usually means easier maintenance.
In C#, I find events being a great asset when decoupling presenters from views. More details in a previous answer: Model-View-Presenter in WinForms
I would look at MS Prism 4, and their nice Navigation interface. Also look at Silverlight and WCF Navigation. They are well done and handle things like prompting the user for confirmation from "dirty" forms, with cancellation.
I would look at the PageFunction() documentation in WCF as well, for how to "call" a page from another, and get back info.
Here's how it works (javascript, sorry):
User double-clicks customer on customer list:
CustomerList.onDblClick(customerId){
app.fireEvent('customerEditRequest', id)
}
...
app.onCustomerEditRequest(id){
this.mainRegion.requestNavigate('customers/edit', id);
}
If navigation to edit view was successful...
CustomerEditView.onNavigatedTo(context){
this.model.load(context.parameters.id));
}
CustomerEditView.onSaveButtonClick(){
this.model.save();
app.fireEvent('customerEdited', id);
}
...
app.onCustomerEdited(id){
app.mainRegion.requestNavigate('customerlist', id);
}
There are a few different ways you could do it:
send a callback function to the edit form, from the customer list. edit form will call it, and you do what you want when it's called.
have the edit form raise on "customerEdited" event that you listen to and react to (no app-wide bus)
use an application-wide Event Bus to manage the events centrally, shown.
I used to have my views communicate with their presenters, but have moved away from that. It doesn't conform to the original definition of a pattern (not a reason in itself for deviating just a contributing factor to exact those benefits). Views ideally should be kept as dumb and with as few dependencies as possible. View should communicate w/ Presenter (any "observers") via delegates/events/some "fire-and-forget" mechanism. As a matter of fact, I've introduced a controller into MVP specifically to intercept View events and either re-fire to presenter (rarely) to communite w/ Presenter, or to communicate with a system or Presenter-specific event bus - enabling me to change user action alerting mechanisms w/out touching the view. Have to be careful with an event bus though; pretty soon you start throwing all events in there, app gets chatty/bogged down in handling events, and events aren't the fastest things in .Net. Sunchronization is an added concern, esp if ur app need to have a more "conversational" interaction with your user.
Should bear in mind that although Presenter is usu view/process-specific, views (and view-models) can be reused; having the View in a containment/delegation relationship with the Presenter strongly couples View/limits its reuse. This could be reduced by some DI, but I find DI containers to be unnecessary complexity in most cases (since I have to know how to create objects anyway and how often do you change out an object for another semantically similar one after creating/testing it?). Concrete dependency goes nowhere except another layer/adds more obscurity/makes things more difficult to debug/trace. Been on a "simplicity" kick lately though, and mostly prefer to do my on Factory/object creations/ORM mappings for most apps, since there's usu a "1-to-1" btw db tables/entities and n need for the added complexity of a generic 3rd-party ORM tool that by taht generic context/needing to serve different apps has to make things harder than they need to be, even if u understand how they work (not the point).
Moreover, it's still quite feasible for View to observe Model in MVP (as in MVC), so I wouldn't be so quick to rule this out. I don't prefer to do this myself, but it' doesn't "break" the pattern. Matter of fact, I developed something similar to MVP about a decade ago because I didnt like the "circular loop" btw the MVC components (View knowing about Model); I preferred to have the cleaner separation btw View and Model that all these patterns (including MVC) professed, as well as a desire to keep View as dumb as possible (observing Model woujld mean View would need more intelligence to process Model changes). What I ended up doing was something like MVVM and strategy patter, where I used "substructures" of the model to pass in to the View, serving as "change notifiers". This kept everything view purpose-specific and flexible/reusable (tough combo).

Categories