I was just about to implement IDataErrorInfo, when I saw INotifyDataErrorInfo was to be used for asynchronous validation. When digging a bit further, I noticed the examples using those interfaces were all on the ViewModel. I need my validation on the model, and I need the errors stored with the model for persistence. I have a large graph with many entities. This graph needs to be passed back to the server for a complex validation. I'm not sure what approach I am supposed to use now.
Do I simply move my inteface implementations to the model?
Another example I saw had a separate validation service. In my case, my validation rules are complex, and I was thinking of using Windows Workflow and its rule engine to improve the maintainability of the validation rules.
Do I need a separate validation service?
Once the validation has completed, the graph must be passed back to the client. Any errors/warnings need to be displayed then.
Should I implement INotifyDataErrors in the model and raise the event when the validation returns to the client to post the errors to the View (through ViewModel)?
As it turns out, I am having trouble referencing the assembly that contains INotifyDataErrors in the class library. It creates a conflict in an assembly that is sharing those classes.
When you have big projects RIA may not be a good idea, for example applications with different layers (Services, Application, Domain, Infrastructure).
Some time ago I had to implement Validation in a Silverlight app with complex rules. I was using Self-tracking entities generated with the Entity Framework. And one of my need was to rehuse all the validation code.
First I tried to use the EntLib Validation Block and use the same code on both the client and the server. This approach doesn't work as you get some problems as SL and .NET4.0 use different versions of the DataAnnotations assembly.
Finally I ended up writing some sort of validation service on the server that returns the errors of an entity if any. Something like this:
interface IValidate
{
IEnumerable<string> Validate(Entity entity);
}
And then on the Client make the ViewModels implement INotifyDataErrorInfo (this interface supports async validation), so you can validate the entity with the Service and save the errors on the ViewModel.
class SomeViewModel : INotifyDataErrorInfo
{
public Entity Entity { get; set; }
public void Validate()
{
this.ClearErrors();
// this method make the service calls
var service = -- service instance --;
var errors = -- get errors from service --;
foreach (string error in errors)
this.AddTopLevelError(error);
}
{...}
}
This way all the validation logic lies on the Server and it can change at any time without affecting the client, because all the entities are passed througth this service before being added to a DataBase (if you're using one).
The service could also return the errors and the property associated with the error, this way you could get a richer interaction with Silverlight. So the service could be:
interface IValidate
{
IEnumerable<PropertyError> Validate(Entity entity);
}
class PropertyError
{
public string PropertyName { get; }
public IEnumerable<string> Errors { get; }
}
Here you can notice that the validation rules could change on the server, and it doesn't matter how this logic is implemented. All this works fine and meets your requeriments, the problem is that Silverlight requires that the object being validated contains all the properties with errors.
This is not a common scenario when working with Databases, as you could have for example (and this is a simple model)
this model was done using Entity Framework 4.1
Because if you have a user instance and want to access to the Email property, you'll have to type: user_instance.Person.Email. So the Email property isn't in the user type, and here is the problem with this solution because you may want to validate the EMails too.
Is this wasn't like this, when you have a ViewModel (implementing INotifyDataErrorInfo) with an Entity (like above) and wants the entity (User in this case) to be validated, you only have to add an error to the property Entity.Person.Email.
But the world isn't perfect, so the solution i found was to duplicate each one of the properties to be validated on the ViewModel, something like this:
class SomeViewModel : INotifyDataErrorInfo
{
public User Entity { get; set; }
public string Name { get { return Entity.UserName; } set {...} }
public string Email { get { return Entity.Person.Email; } set {...} }
{...}
}
This way you can bind the controls to the ViewModels properties instead of the entities properties, but it gets a bit hard to work with the change notifications.
You may also want to check: this toolkit. It solves this problem defining a wapper to your entity and using DynamicObject simulates an object that has all the properties from the wrapped one. This is a bit slow when working with large ammounts of data, but simplifies the work a lot.
Hope this helps.
Related
For my WPF-Application I decided for MVVM. Here is my Concept how I will implement this pattern.
My Models (Business Objects) are responsible for the validation (that's a must for me).
ViewModels are responsible to wrap my Model for a friendly User-Interaction and some security aspects.
My first question was about wrap or not wrap my Model in ViewModel.
When I don't wrap my Model in ViewModel and expose the Model directly to the view – then I don't understand why I need a ViewModel (it seems sensless)
ViewModel should wrap the Model for various reasons:
I don't like direct binding to the strongly typed properties in Model (DateTime, int, …), because when I do this => WPF takes control over my validation for this types. That's really bad, because when the user write ‘aaaa’ in a Datepicker, my Model is valid (my model never know about that, because WPF takes the control over strongly typed properties) and the Save-Button is enable – that's really wrong.
I don't expose all properties of my Model to the view, my ViewModel should protect my Model (I have some properties, that should have at presentation layer only getter and no setter)
My Decision is that ViewModel should definitely wrap the Model. So the ViewModel implements INotifyPropertyChanged.
But now I have problem with the business validation.
When I take the nice IDataErrorInfo, then I have the whole business rules in the ViewModel, that's breaks my concept. The business rules should definitely be in the model.
Example: When user choose Type A, then Field 1, and Field 2 are mandatory. When user choose Type B, then Field 3 is mandatory – this field should be marked as red and the Save-Button is disable when is it not valid. Also more heavy things like free/occupied DateTime-Ranges.
It's definitely bad, when I do this things in ViewModel, because most things are business part.
So how I can achieve this?
At the Moment I have this workaround:
All ValidationRules are in the Model as simple Methods, e.g.
public string ValidateBirthday(string birthay)
{
if (...)
{
return "Birthday should be…";
}
return string.Empty;
}
In my ViewModel I implemented the IDataErrorInfo, and redirect to my Model-Validation like this:
public string this[string columnName]
{
get
{
switch (columnName)
{
case "Birthday":
return Model.ValidateBirthday(Birthday);
case "XXX":
return Model.ValidateXXX(XXX);
case "YYY":
return Model.ValidateYYY(YYY);
break;
}
}
}
I never see something like this (the redirect to Model) in an example, so I'm very doubtful about my implementation.
Is my workaround OK or do you see any problems about this?
I try to give more information about what I mean…
I know about the implementation INotifyPropertyChanged and IDataErrorInfo in the Model.
This works good with direct Binding from View to Model.
Direct Binding from View to Model:
public class PersonViewModel : INotifyPropertyChanged
{
private Person _personModel;
public Person PersonModel
{
get { return _personModel; }
set
{
if (_personModel != value)
{
_personModel = value;
NotifyPropertyChanged();
}
}
}
public PersonViewModel(Person person)
{
PersonModel = person;
}
…
}
View:
<DatePicker Text="{Binding PersonModel.Birthday}"/>
The big disadvantage is: WPF takes the Control over all strong typed Property.
Example:
The user typed 07/20/2008 in the datepicker, so the PersonModel will be informed and PersonModel can check this, when OK, then PersonModel is valid => SaveButton is enable.
Now the user typed 'aaa' in the datepicker, WPF takes the control over this validation, because it's a binding to a strongly typed property (DateTime). PersonModel will not be informed about that, so the PersonModel is still valid => SaveButton is enable!
So for that 'problem' I need the ViewModel correctly.
ViewModel wrap the Model like this:
public class PersonViewModel : INotifyPropertyChanged
{
private Person _personModel;
public string Birthday
{
get
{
if (_personModel. Birthday!= null)
{
return ((DateTime) _personModel. Birthday).ToShortDateString();
}
else
{
return String.Empty;
}
}
set
{
if (_personModel. Birthday.ToString() != value)
{
DateTime dateValue;
if (DateTime.TryParse(value, out dateValue))
{
_personModel.Birthday = dateValue;
…
}
else
{
…
}
}
}
}
public PersonViewModel(Person person)
{
_personModel = person;
}
…
}
Now I don't bind the Model direct from View. I bind the Properties from ViewModel that wrapped the Model.
<DatePicker Text="{Binding Birthday}"/>
The big advantage is: now I have the full control about what the user types in the fields.
When the user types strings like 'aaa' in Datepicker I can catch this => set the state to invalid and SaveButton is disabled.
That's one reason, why I don't take the direct binding from View to Model.
Other reason are readonly Property. In Model I have get and set on every Property, but for security Issue I won't offer all Properties from Model with get and set. So this can also solved by ViewModel by wrapping this Properties with only get. With direct Binding you can't do all this things.
My point is, I will definitely wrap all Properties from my Model in ViewModel, but how can I use the nice IDataErrorInfo in Model (It works only with direct Binding)?
You are mixing two concepts here: Bussiness objects and validation.
Almost every system nowadays uses the client-server architecture, even if its an standalone application.
In such scenario you have two validation locations:
The client is responsible for ensuring that the data entered is valid before sending anything to the server in order to enhance user experience and avoid server overloads and security issues.
The server is responsible for the verification of the incoming data, to avoid malformed, misformatted data and security issues.
Also:
The Bussiness Objects (BO) are the classes used by server, tipically represeting the data base.
The Data Transfer Objects (DTO) are the classes that the server sends to the client.
The ViewModels are both the backend code for the UI and the wrappers for the DTOs.
Your model objects shouldn't have any logic, since you will spoil them with some code that at some point you will need to reuse.
As exposed here, you should separate that validation logic into services that only know about that object and how to validate them. This way, you can use validation services from the UI.
Your Save button should react only on UI changes, and you will only get those from a ViewModel.
Basically, you will be applying SOLID principles here: Each layer has very clear responsibilities (model -> data, services -> validation, dto -> data ready for the client, viewmodels -> UI interaction). All the code will be easy to work with, easy to extend and easy to refactor.
Edit
1st and 2nd questions:
UI only validates the input: no random characters in number fields, no sql characters in text fields, Date has correct format, etc.
Thinks like "if this then that" should be handled by the backend, as you describe:
Save is clicked.
UI data is valid.
DTO sent to backend.
Backend analizes DTO and it is not valid.
Backend sends back the errors found.
UI shows the errors found.
3rd question:
That looks right to me.
4th question:
DTO is just a concept, you can use a real backend server that communicates via WCF, or you can just have a bunch of classes that act as a service but are called in the same application domain (like any other project reference). In either case you can choose what data is being sent and received.
You should start developing in that direction and then see what better fits you.
I'm currently writing my first MVVM application which uses EntityFramework for data access.
The Application relies heavly on the underlying database and has to add new Data to the DB in many cases.
However, I'm uncertain about whether or not it is a good idea to call the ObjectContext inside the ViewModel.
e.g.
public class SomeViewModel : ViewModelBase
{
public IEnumerable<User> AllUsers { get; private set; }
private void SomeMethod()
{
var __entities = new DatabaseEntities();
AllUsers = __entities.Users.Where(...).ToList();
}
}
I've seen solutions like this, but there are some question coming along with it.
For example how long the ObjectContext actually lives, or if one should prefer a single, global accessable ObjectContext.
Or should calls like those not be part of the VM in the first place?
Currently I can also imagine to implement like StaticHelpers for each DB table and use Methods like GetAllUsers().
In Josh Smith's sample Application about MVVM he uses a Repository thats injected in the Constructor of each VM.
public AllCustomersViewModel(CustomerRepository customerRepository)
Despite the fact that this has to be a common issue, I found no satisfying answer on how this issue is approached for smaller applications (best practice)?
In the descripton of the DbContext class on MSDN it states "Represents a combination of the Unit-Of-Work and Repository patterns", so it can act as your Repository layer, although it doesn't have to, and it is intended to be used for a "Unit of Work" which doesn't fit using a global one for the entire app. Besides keeping a single one around for everything could cause issues with cached data and other undesirable things (memory usage, etc...).
Hope this helps.
my first real (not test) NHibernate/Castle.ActiveRecord project is developing quickly.
I am working with NHibernate/Castle.ActiveRecord about one month now but still have not a real idea how to handle Sessions in my WindowsForms application.
The common handling-methods seam not to work for me:
SessionPerRequest, SessionPerConversation, etc. all only work for WebApplications, etc.
SessionPerApplication is not recomanded/highly dangerous when I am correct
SessionPerThread is not very helpfull, since I either have only one thread, the WindowsForms-thread, or for each button-click a new thread. The first thing would make my applicaton use too much memory and to hold old objects in the memmory. With worker-threads for ech button click I would disable lazy-loading, since my loaded objects would live longer then the thread.
SessionPerPresenter is not working as well, because it is common, that I open a "sub-presenter" in a form to let the user search/load/select some referenced objects (foreigen key) and of cause the presenter is destroyed - what means session closed - but the object used in the "super-presenter" to fill the referencing property (foreigen key).
I've used google and bing for hours and read a lot, but only found one good website about my case: http://msdn.microsoft.com/en-us/magazine/ee819139.aspx . There SessionPerPresenter is used, but to a "sub-presenter" it is only given the id, not the entire object! And it seams that there are no foreigen-keys in this example and no scenari in wich a object is returned to a "super-presenter".
Qestions
Is there any other method of session handling for windowsforms/desktop-application?
I could add a session-property or a session-constructor-parameter to all of my presenters, but it feels not right to have session-handling all over my ui-code.
When an Exception occures NHibernate want's me to kill the session. But if it is 'only' a business-logic exception and not an NHibernate-Exception?
Example
I am trying to make an example the covers most of my problem.
// The persisten classes
public class Box
{
public virtual int BoxId{get;set;}
public virtual Product Content{get;set;}
...
}
public class User
{
public virtual int UserId{get;set;}
public virtual IList<Product> AssigenedProducts{get;set;}
...
}
public clas Product
{
public virtual int ProductId{get;set;}
public virtual string PrductCode{get;set;}
}
.
// The presenter-classes
public class ProductSearchPresenter : SearchPresenter<Product> { ... }
public class ProductEditPresenter : EditPresenter<Product> { ... }
public class UserSearchPresenter : SearchPresenter<User> { ... }
public class UserEditPresenter : EditPresenter<User> { ... }
public class BoxSearchPresenter : SearchPresenter<Box> { ... }
public class BoxEditPresenter : EditPresenter<Box> { ... }
// The search-presenters allow the user to perform as search with criterias on the class defined as generic argument and to select one of the results
// The edit-presenters allow to edit a new or loaded (and given as parameter) object of the class defined as generic argument
Now I have the following use-cases, wich all can be performed in the same application at the same time asyncronous (the use simply switchs between the presenters).
using an instance of BoxSearchPresenter to search and select a object
part of this usecase is to use an instance of the ProductSearchPresenter to fill a criteria of the BoxSearchPresenter
part of this usecase is to use an instance of the BoxEditPresenter to edit and save the selected object of the BoxSearchPresenter-instance
using an instance of UserSearchPresenter to search and select a object
part of this usecase is to use an instance of the UserEditPresenter to edit and save the slected object of the UserSearchPresenter
part of this usecase is to use a ProductSearchPresenter to search and select objects that will be added to User.AssignedProducts.
Using an instance of ProductSearchPresenter to search and select a object.
part of this usecase is to use an instance of ProductEditPresenter to edit and save a selected object of the ProductSearchPresenter.
It's only a small collection of usecases, but there are allready a lot of the problems I have.
UseCase 1. and 2. run at the same time in the same ui-thread.
UseCase 1.1. and 2.2. return there selected objects to other presenters that use this objects longer then the presenters exist that have loaded the object.
UseCase 3.1. might alter a object loaded from 2.2./1.1. before 3.1. was started, but when 2.2./1.1. is commited before 3.1. is finished the object would be saved and it would not be possible to "rollback" 3.1.
Here is just a short view of what I found best to fit into our WinForms application architecture (based on MVP).
Every presenter is constructor dependent on repositories which it needs, for example if you have InvoicePresenter then you have InvoiceRepository as dependency, but you will probably have CustomerRepository and many others depending on complexity (CustomerRepsitory for loading all customers into the customers combobox if you want to change customer of the invoice, stuff like that).
Then, every repository has a constuctor argument for UnitOfWork. Either you can abstract the session with UnitOfWork pattern, or you can have your reporitories depend on ISession.
Everything is wired together by IoC container, where we create presenters based on "context". This is a very simple concept, context is per presenter and all sub presenter, which in turn we create as composite block of more complex presenters to reduce complexitiy (if for example you have multiple tabs of options to edit some entity or something).
So, in practice, this context is 90% time form based, because one form is at least one presenter / view.
So to answer your questions:
Session per presenter and session per conversation (works with WinForms as well) are only really usable patterns here (and opening closing sessions all over the place, but not really good way to handle that)-
this is best solved by making repositories depend on session, not presenters. You make presenters depend on repositories, repositories depend on session, and when you create all, you give them common session; but as I state again, this is only practical when done in contexts. You cannot share session for presenter editing invoices and another presenter editing customers; but you can share session when editing invoice via main presenter and invoice details and invoice notes sub presenter.
Please clarify, didn't understand this...
I'm starting up with Entity Framework and RIA Services. I'm also evaluating whether to use POCO or not, I believe it is the way to go since we will work on an agile (scrum) environment... (so far)
With the self-tracked entities I could add decorators on the metadata in order to get client-side validation. How can I achieve the same with POCO classes? I wouldn't want to modify generated files, cause they will be genrated tons of times biefore the final release and (of course) I don't want to write my validation code every time.
Can't you continue to do it with partial classes and metadata types? Something like this.
[MetadataType(typeof(MyEntity.Metadata))]
public partial class MyEntity
{
private class Metadata
{
[Required]
[StringLength(5)]
public string MyProperty;
}
}
Currently for ASP.Net stuff I use a request model where a context is created per request (Only when needed) and is disposed of at the end of that request. I've found this to be a good balance between not having to do the old Using per query model and not having a context around forever. Now the problem is that in WPF, I don't know of anything that could be used like the request model. Right now it looks like its to keep the same context forever (Which can be a nightmare) or go back to the annoying Using per query model that is a huge pain. I haven't seen a good answer on this yet.
My first thought was to have an Open and Close (Or whatever name) situation where the top level method being called (Say an event handling method like Something_Click) would "open" the context and "close" it at the end. Since I don't have anything on the UI project aware of the context (All queries are contained in methods on partial classes that "extend" the generated entity classes effectively creating a pseudo layer between the entities and the UI), this seems like it would make the entity layer dependent on the UI layer.
Really at a loss since I'm not hugely familiar with state programming.
Addition:
I've read up on using threads, but the
problem I have with a context just
sitting around is error and recovery.
Say I have a form that updates user
information and there's an error. The
user form will now display the changes
to the user object in the context
which is good since it makes a better
user experience not to have to retype
all the changes.
Now what if the user decides to go to
another form. Those changes are still
in the context. At this point I'm
stuck with either an incorrect User
object in the context or I have to get
the UI to tell the Context to reset
that user. I suppose that's not
horrible (A reload method on the user
class?) but I don't know if that
really solves the issue.
Have you thought about trying a unit of work? I had a similar issue where I essentially needed to be able to open and close a context without exposing my EF context. I think we're using different architectures (I'm using an IoC container and repository layer), so I have to cut up this code a bit to show it to you. I hope it helps.
First, when it comes to that "Something_Click" method, I'd have code that looked something like:
using (var unitOfWork = container.Resolve<IUnitOfWork>){
// do a bunch of stuff to multiple repositories,
// all which will share the same context from the unit of work
if (isError == false)
unitOfWork.Commit();
}
In each of my repositories, I'd have to check to see if I was in a unit of work. If I was, I'd use the unit of work's context. If not, I'd have to instantiate my own context. So in each repository, I'd have code that went something like:
if (UnitOfWork.Current != null)
{
return UnitOfWork.Current.ObjectContext;
}
else
{
return container.Resolve<Entities>();
}
So what about that UnitOfWork? Not much there. I had to cut out some comments and code, so don't take this class as working completely, but... here you go:
public class UnitOfWork : IUnitOfWork
{
private static LocalDataStoreSlot slot = Thread.AllocateNamedDataSlot("UnitOfWork");
private Entities entities;
public UnitOfWork(Entities entities)
{
this.entities = entities;
Thread.SetData(slot, this);
}
public Entities ObjectContext
{
get
{
return this.Entities;
}
}
public static IUnitOfWork Current
{
get { return (UnitOfWork)Thread.GetData(slot); }
}
public void Commit()
{
this.Entities.SaveChanges();
}
public void Dispose()
{
entities.Dispose();
Thread.SetData(slot, null);
}
}
It might take some work to factor this into your solution, but this might be an option.