validation with Entity framework and WPF/Silverlight or ASP.Net - asp.net

In a wpf application using POCO classes with Entity framework, what is the best way to perform validation on data. I am aware of data annotations but if I am not compeltely wrong they are more used with ASP.Net MVC than WPF (i didnt find many examples with WPF). Earlier I was having my Domain classes implement the IDataErrorInfo interface but I wasnt sure if this was the correct approach. If I would want to share my EntityFramework classes at a later stage with say a silverlight application or an ASP.NET application what would be my best approach so that I can reuse my validation rules. (With ASP.net i believe my IDataErrorInfo way of handling errors would be useless?).I can find a lot of similar questions but not one that particularly meets my needs. It would be great if anyone can point me in the right direction
I have been using T4 templates on my domain model to generate the POCO classes and have been using these POCO class objects as business objects too

Out of the box, WPF Validation uses IDataErrorInfo and/or ValidationRule's on bindings. IDataErrorInfo being the partial classes that provide a way to tie in additional logic to make sure the value is valid (IE: The Person.Age property is between 1-100) and ValidationRule's being able to inspect the value before it is ever applied to the binding (IE: The Person.Age property is an integer at all). IDataErrorInfo is obviously only helpful when the value of a Binding gets updated with a compatible datatype, ValidationRule's are helpful in the event somebody types "Ten" instead of 10, in your Age textbox and the datatypes are not compatible.
IDataErrorInfo is reusable for all WPF/Silverlight/ASP.NET projects, (see: How to use IDataErrorInfo in ASP.NET)
Whereas ValidationRule's are to be used with Bindings and therefore not useful in a ASP.NET project. They could be considered the equivalent of Javascript validation.
In short, IDataErrorInfo is exactly what you're looking for and will provide the most reuse for those technologies.

IDataErrorInfo is not supported out-of-the box with EF validation. Annotations are used not only for validation but also can be used to define your model (e.g. Required, MaxLenght, StringLength attributes etc.). Out-of-the box you can use a few more mechanisms to validate your entities - by writing your own attribute by deriving from ValidationAttribute, by using CustomValidationAttribute or by implementing IValidatableObject. That's what EF supports out of the box. If neither of these works for you can replace built-in validation by overwriting DbContext.ValidateEntity() method and use any validation mechanism that works for you. A couple useful links: http://blogs.msdn.com/b/adonet/archive/2010/12/15/ef-feature-ctp5-validation.aspx
http://blogs.msdn.com/b/adonet/archive/2011/05/27/ef-4-1-validation.aspx

Related

Is it common to use POCOs and model binding to do contextual validation?

I've noticed in ASP.NET MVC, it's commonplace to use model binding and validation annotations in conjunction with business objects that also interact with the database.
Unfortunately, this means that the scope of the request and the validation taking place must always be 1:1 with domain models. At the very least not without having to code a bunch of exceptions.
If I'm looking for a way to do contextual validation in ASP.NET MVC, are there any examples of or is it an accepted practice already to use POCO classes that represent the incoming data?
Let's say I call these "Request Models". An example might be that I create a class called UpdateUserRequestModel. I define only the data that I allow for a user update, then, I have MVC bind the values into this surrogate model. Later in my controller/services, I access the request model's public properties for the values I wish to move over to the user object.
So, the question here is: Is there already any example of this practice in commonly accepted ASP.NET MVC conventions? Does it have a particular name? Failing that, when I wish to do contextual validation, are there any better options than the default model binders and value providers that MVC ships with?
I do it on my apps. I validate actions the user performs, putting validation attributes etc on that view model that represents that action (conveniently models the form in the view and model binds the result on the way back). I even ported the ContosoUniversity app to reflect this style:
https://github.com/jbogard/ContosoUniversity

ASP.NET SPA with a legacy domain objects

Looking at the Single page application beta in the MVC 4 I don't see how I can use my legacy domain objects as the model. It seems to require that the model use the entity framework to using DbDataController to get the data etc.
I do not understand the entity framework so I am probably missing something.
How can I use my legacy domain (with it's own DAL) in the SPA of MVC 4?
This was answered by somebody else in an ASP.NET forum.
You won't be able to use anything other than EF if you want to use some of these RAD tools. However, SPA builds on top of MVC, so you should be able to build your own version rather easily. The important components would be building a DataController on top of ApiController and a js consumer for the service provided by your DataController. It's possible that if you were to format your models in the same format as the EF output (I think it's just OData) you could use upshot.js, as well and only have to implement a DataController to format your domain models.
I will add the following after working with it for a couple of days that you could, theoretically, use it if the following are handled/fixed by you and future versions of the SPA.
You can create a controller that inherits from System.Web.Http.Data.DataController (and maybe even ApiController). The objects it returns then must just have a property decorated with the System.ComponentModel.DataAnnotations.Key() attribute. I can get the views to work fine but some of the more advance features, like grouping, I am having problems with.
Readonly property will not be returned I guess because of a problem with the current JSON serializer used. Should be fixed.
Of course the entire object will be serialized which can be very problematic if your domain objects are complex with child objects. Especially if some of those objects have serialization issues of their own.
Related to the complex serialization the current JSON serializer cannot handle circular references in the domain objects referenced.
I have also run into problems getting update/deletes/inserts being posted back when using my own Controller that inherits from System.Web.Http.Data.DataController (the examples use DBDataController).

High level overview of ASP.net

I've spent a lot of time working in Django, and have grokked the framework well enough that I have started replacing the original components (view engine, etc.) with my own custom components and the sky hasn't fallen down.
I've been looking at ASP.NET MVC, and been quite interested (I really like C#/F#) but so far have learned... just about nothing. I've been digging through http://www.asp.net/mvc/mvc4 without much success. I suppose my main questions would be:
What are the main moving parts in a typical workflow? Let's say a request comes in. Who takes it, does stuff, and passes it on to who else? In Django, for example, a request goes through the URL Mapper, Middleware, goes to a controller, which may dig through some models (via explicit function calls) and get some data, pass it into a template (also via an explicit function call) to be rendered and pass it back.
What kind of client-server coupling is there? For example, in many frameworks there is a explicit coupling of each HTML-form with a serverside-validator, with a model, with a database table, such that client side validation code is automatically generated. Another example is Quora's Livenode, which explicitly links client-side HTML components with their dependencies in the model, allowing changes in the database to propagate and automagically update client-side code.
I think there is no better answer to your first question than ASP.NET MVC Pipeline :
http://www.simple-talk.com/content/file.ashx?file=6068
explained in more detail here :
http://www.simple-talk.com/dotnet/.net-framework/an-introduction-to-asp.net-mvc-extensibility/
To your second question : answer is none. ASP.NET application dont even have to render HTML output, you can write your own viewengine to give any representation of the data, not consumed by browser, but any http (REST) capable device. The only things you can consider as coupling "conventions" (for model binding for example), but they can be replaced and extended in any way you like.
What kind of client-server coupling is there?
As rouen said, none.
I am not familiar with Django, but unlike other MVC frameworks (including Rails) ASP.NET MVC is very skinny in that it only implements Views and Controllers of the traditional MVC pattern. You are pretty much on your own for the model part. That means there is no built-in support for database creation, ORM, et cetera.
ASP.NET MVC does implement a bunch of plumbing to route requests to the appropriate controllers and even some binding of parameters (e.g. query string parameters, form values) when instantiating controllers but this binding is not to a full blown model. The binding in this context is usually either single values or "viewModels"
ASP.NET MVC also implements the plumbing to select the right view to render.

Elegant validation techniques for Entity First MVC3 site?

Having never done an MVC site I am about to start a project for a very large one. I feel confidant enough to do it, but I have one thing I need help figuring out.
We are definitely going to be using an "Entity First" method and have a single .edmx file defining the models, there are multiple reasons for this but just know that this is a definite piece of the puzzle.
So the piece I need to figure out is how to come up with an elegant way to do validations against Entities on a page, without hand coding each page, at least for the majority of things.
Are there any already popular methods for doing some basic validations? Things like MaxLength or Required or MinDate, etc?
Anything more complex than that and I understand I'd have to code it myself, but this site is going to be very large and I really need to find a way to speed some of the basic tasks up.
EDIT
I should point out a couple important facts.
1) Our database already exists and was created by a DBA before developers even came into the picture.
2) There are hundreds of tables and stored procedures already created.
3) When changes will need to be made to the database, they will go through the DBA, who we will not always have instant access too.
First of all, if you use Entity Framework Code First, you don't have a .edxm file storing your models or relationships between them: you just write your POCO (Plain Old CLR Object) classes, and that's it — Code First will figure out the relations between your models based on naming conventions.
To validate your (view) models, I recommend using FluentValidation or DataAnnotations. Both let you define validation rules in one place, either using a fluent validation API in different entity validation classes (FluentValidation) or using attributes to decorate your entity properties (DataAnnotations). The advantage of DataAnnotations over FluentValidation is that you get additional client-side validation out of the box.
Whichever framework you choose, both ship with a bunch of predefined validation rules like Required, Range, or MaxLength (see Fluent Validation for .NET or System.ComponentModel.DataAnnotations Namespace for examples).
I would 100% absolutely still use some POCO class. Download the DBContext generator template that will then create the code first from your model, OR use the Entity Framework Power Tools to reverse engineer an existing database. The down side to these methods though is that you won't get client side validation, only when saving it will you get the validation. You can however still add your validation attributes if you so choose for client side validation in addition using
MetaData Classes to use Data Annotations on your properties and get client side validation using the built in jQuery unobtrusive validation.
However - what we're talking about here goes against the basic design of MVC good practices anyways. Ideally your views should have ViewModels that are at times only a portion of an entity, in this case your validation attributes are still generated on your properties as DataAnnotations in MetaDataClasses.
If you feel this is all too much work and you are fine with just the server validation and have made a decision not to use ViewModels and rely on the Entity Frameworks validation- or use ViewModels and still rely on EF validation, then you will need a handler like the following in your controller (or other layer that has been given access to ModelState) to catch the following exception. Note I use AutoMapper to copy the properties between my ViewModel to my Entity.
Entity Framework Power Tools (right click in your project in solution explorer after its installed and there will be an new 'Entity Framework' menu -> Reverse Engineer - note it doesnt generate [TimeStamp] attributes and forgets to put in schema names - besides that its pretty good)
[HttpPost]
public ActionResult Create(CustomerCreateViewModel customerViewModel)
{
if (ModelState.IsValid)
{
try
{
Mapper.CreateMap();
Customer customer = Mapper.Map(customerViewModel);
var repository = new CustomerRepository(db);
repository.Save(customer);
return RedirectToAction("Edit", new { id=customer.CustomerId});
}
catch (DbEntityValidationException ex)
{
foreach (var error in ex.EntityValidationErrors.First().ValidationErrors)
{
this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
return View();
}
}
return View(customerViewModel);
}
Jon Galloway has a nice article called Generating EF Code First model classes from an existing database which I think will help you greatly in getting your application up and going from what you described.
Secondly, from having built out our own MVC application so far, I've found that you're really not going to be working directly with Entity Framework models directly very often. Most of the time you'll end up with some type of view model for doing your gets and posts to. Adding DataAnnotations to those class properties will make it very easy for you to do your validations on the client side. Once you have validated the data from the client side and checked your entities against any business rules, you really should then be able to trust the data and use EF to do your basic CRUD work with.
Good luck, and hope this helps you some with your project.
What Marius is trying to tell you is that "Code First" refers to your "model" being defined by fluent code mappings that do not rely on an .edmx file. Therefore, if you're using an .edmx file, you're not doing "code first". You're doing either "Database First" or "Model First" (both of which use the .edmx).
In your case, you already have a database, so you're using the "Database First" approach, using EF 4.1 DbContext. This is not "Code First" (or as you incorrectly stated, Entity First). This is not a semantic quibble, as "code first" has a very specific meaning. This is not it.
Now, on to the rest of your question. Since all your database access has to go through stored procedures, Entity Framework is not a good choice in my opinion. You would be better off using something like nhibernate, which has much better stored procedure support.
EF is intended to represent your relational data model in objects, and generates all its own sql to access and fill these objects. If you have to go through the sprocs, EF will be a constant uphill battle for you.

Validation in the business logic - ASP.NET Web Forms

In reading up on ASP.NET MVC I came across some wonderful examples of validation where the business rules were associated with the model and the UI merely displayed the set of errors and flagged the form elements associated with invalid input. I think it makes fantastic sense to keep this logic in a single place rather than have every form perform its own unique validation.
Is it possible to achieve this separation in an elegant manner with an ASP.NET Web Application project (webforms)? I can keep the validation rules in the business logic layer and I can have methods that perform validation and return a set of errors. But I can't figure out a good way to flag problematic controls on the UI side.
In MVC the form elements and model are implicitly linked by property names. Should the UI in ASP.NET reference the unique property names of the model (either as ID/name or as a custom attribute)? Should the UI have access to a manually-generated mapping of control names to property names?
A way I like to do it is to create CustomValidators, bound to control on the screen and I call my BL validations in the OnServerValidate event. That way, my validation logic stay in one place.
Hope it will help
I'm sure I remember hearing some where that some improvements around Data Annotations would be available for WebForms in .NET 4.0, but after trying to search for it online I'm starting to think I dreamt it.
Although I did find this post of a guy that 'rolled his own':
http://adventuresdotnet.blogspot.com/2009/08/aspnet-webforms-validation-with-data.html

Resources