Validation in the business logic - ASP.NET Web Forms - asp.net

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

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

validation with Entity framework and WPF/Silverlight or 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

MVC3 : different validation for different input scenarios

I have used yii framework in php extensively and find scenarios very useful.
to summarize, scenarios let you have different validation criteria for different views.
Question
Can I use mvc3 built in validation and yet have different validation criteria for different views .Is there a built in function for this?
Explanation
In one of the forms I only want to validate change of password, in another form I just want to validate new user parameters, yet another place only requires validation of some detailed data input. All values are stored in the same table but need different input value sets
No, because the built in framework validation is attribute based, it makes it difficult to change validation requirements at run time if you're sharing models across views.
As such, your best bet would be to create different models for each view.
If you need to have custom validation applied at run time to your models then you can use http://fluentvalidation.codeplex.com/
It's not built in, but works with the existing ASP.NET MVC validation components and as such can be used with unobtrusive validation / model state etc.

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.

State Design Pattern - ASP .NET Webform

I'm thinking of implementing the state design pattern on an ASP .NET Webform.
The state would be determined by the query string passed to the page. Based on the state of the page, any action would call the method on the concrete implementation.
What I am trying to achieve is a page that can handle any number of different implementations of the same general functionality.
My questions are:
Will this work?
Does this sound like the right approach?
Using a state pattern is an approach you can take for this, but honestly what your describing is part of what the MVC framework was designed to accomplish.
Edit:
MVP/MVC
Since the MVC Framework isn't an option then I would take a look at Model View Presenter pattern (MVP) with either the passive view approach or superviser approach as described here: http://www.martinfowler.com/eaaDev/SupervisingPresenter.html
We found that the passive view approach worked with a little adaptation for our legacy code to work out good for us.
Edit:
Patterns:
In that case then which pattern you choose really depends upon what the business needs are.
State pattern:
State pattern is typically used for when you need to change the behavior of an object based upon its current state or the state of a relation to the object. A common usage of this pattern is with games when the behavior of the object depends upon which mouse cursor button is pressed.
http://en.wikipedia.org/wiki/State_pattern
Strategy pattern:
This pattern is good for when you need different implementation based upon a configuration. For example say you are defining an email system and you need to have a different implimentation based upon which email provider is being used to send the email.
http://en.wikipedia.org/wiki/Strategy_pattern
So State pattern could definetly be the right direction it just comes down to what the objective is and what behavior's your trying to meet.
What you'll often find with patterns is that they work well with eachother and you'll use multiple patterns in conjuction with eachother.
I think what you are suggesting would be a sound approach. The only advice I can really offer is to not get hung up on implementing the State Pattern perfectly. I think it would be perfectly acceptable to just have a switch which calls a method based on a query string value.

Resources