ASP.Net MVC datarow validation - asp.net-mvc

I am delevelopring my first MVC application and I am using a classic ADO.NET dataset as a model. The guide I am following is the NerdDinner ASP.NET MVC Tutorial and it mentions a GetRuleViolations() method for a Linq To SQL model. I would like to have a similar method to check that a datarow is valid after editing. How could I do such a thing?

Datasets are disconnected. As such they don't support validation rules unless you add constraints manually.
Edit: From the link:
We’ll implement IsValid and GetRuleViolations() by adding a “partial class” to our project. Partial classes
can be used to add methods/properties/events to classes maintained by a VS designer (like the Dinner
class generated by the LINQ to SQL designer) and help avoid the tool from messing with our code.
You could do something similar with a typed dataset.
See this link on validation with typed datasets.

I guess you should use the dataset for data transfer only. Not for business rule validation. In this way you can still follow the tutorial and keep the repository. But replace all Linq to SQL code inside of the repository with your own dataset code.
Your business objects will be the ones implementing the GetRuleViolation() method.

Related

Working with MVC 2.0 and the Model in a separate assembly

I'm new to MVC and even though there is a lot (and I do mean a lot) of information out there that is very useful - it's proofing very difficult to get a clear understanding on how to achieve my exact requirements with MVC 2.0.
I would like to set up a solution as follows:
Provide a web UI using an MVC 2.0 project.
Use Linq to SQL classes project for data persistence.
I have a two separate code modules that will need to access the above Linq to SQL model - so I won't be able to include my Linq to SQL model directly in the MVC project itself.
Also I have a Business Logic layer in front of my Linq to SQL project.
My questions are:
How do I set up the Model part of my MVC application to point to my Linq to SQL project via my BLL?
How do I perform web app validation? Can I use MVC 2.0 Model Validation? If not what are the alternatives?
Finally (and slightly aside) - What is the ViewModel and how does this differ from the Model?
So many questions. But this is an exciting new technology and data access issues aside, everything else I've got to grips with very quickly and I think MVC 2.0 is fantastic.
Thanks for any pointers you can provide.
How do I set up the Model part of my
MVC application to point to my Linq to
SQL project via my BLL?
Typically you'd use a repository pattern for this. Your controller has a reference to your repository - the repository returns your domain objects from your database. The MVC app has no knowledge LINQ to SQL exists.
How do I perform web app validation?
Can I use MVC 2.0 Model Validation? If
not what are the alternatives?
Put view models in your MVC project. These view models may closely align with your domain models but their concern is to be the presentation model. Put your data annotations for validation on these view models - the MVC framework will automatically ensure validation occurs on these view models decorated with data annotations. It's pluggable so you could use alternatives - but with MVC 2, it's baked in fairly well and this includes client side validation.
Finally (and slightly aside) - What is
the ViewModel and how does this differ
from the Model?
I partially answered this one above. the shape of your domain models may not be the shape you need to display your views - view models are great to bridge this gap. Additionally, even if the shape does match exactly - view models are still a good idea so that you can put UI validation code there and other presentation meta-data on them (since you do not want anything related to presentation logic on your domain model).
Here's link for view model patterns.
Hope this helps.
You can add a reference to the objects exposed from your BLL assembly and use them as your Models.
When you want to add validation to classes that are generated use buddy classes.
A ViewModel is a custom-shaped aggregate of Model data. There is exactly one per View, as the ViewModel's purpose is to surface exactly the data needed by a particular View in a convenient and concise way.
An example might be a View that contains both Order and OrderDetail information. A ViewModel can hold internal references to the repositories and business objects for each type. Properties of the ViewModel merge together the data from these objects.
ViewModels will be useful in your case also because you want your Models to be in a separate assembly. You can apply the DataAnnotations to ViewModel properties for validation. You would make the "raw" business object models internal properties of your ViewModels, and expose public methods to retrieve and persist data.

NHibernate.Validator vs DataAnnotations

In my APS.NET MVC project I'm using DataAnnotations for validations.
I moved from L2S to NHibernate orm and in fact found that NHibernate has its own validator (NHibernate.Validator)
Does it make sense to move to NHibernate.Validator as well?
For example DataAnnotations has [Required] attribute and NHibernate.Validator [NotEmpty, NotNull, NotNullNotEmpty] and it makes me think what to use.
I've used both in production projects and, if you have the time to make the switch, I would highly reccomend NHibernate.Validator for a couple of reasons:
NHibernate.Validators has a
richer set of validation attributes
(for example, the handful you
mention above)
If implemented
properly, NHibernate.Validators
validations are easier to unit test.
No. 1 wasn't huge for me, and may not be for you, as the set of attributes in DataAnnotations is pretty complete (and you can fall back to RegEx, if need be), but no. 2 was a big deal for me because I wanted to be able to include data validation as a part of my Domain Model unit tests, as opposed to testing those only through UI/Web testing via WatiN or Selenium. Using Validators also allowed me to mix Domain Model rule validation (Property X OR Y must have a value, but both cannot be null) without having to go to another place to do so.
For some basic guidance on using NHibernate Validators, check out this article: http://nhibernate.info/blog/2009/04/02/nhibernate-validator-and-asp-net-mvc.html, and I would also reccomend getting the source for S#arp Architecture, Billy McCafferty's great framework for creating DDD-style ASP.NET MVC applications. In particular, check out his implementation of Validators and the Validator ModelBinder you'll need to create to transfer NHibernate validation errors into MVC ModelErrors. Download the S#arpArchitecture source here: http://github.com/codai/Sharp-Architecture.
The bottom line is this: Using NHibernate.Validators is the more extensible, testable option, but it will take some doing for you to use it properly. DataAnnotations is baked into the framework and easier to get running with, there's no question about that.
Hope that helps.

connect to DB using MVC

I have an asp.net mvc application and i need to connecto to the DB i have saw a tutorial video that connect to DB using wizard by adding DB connection and determine the DB and add a model but i need to know if i can use connection string and query the DB or calling procedures in DB ???
I need any tutorials or step by step article that describe how to connect to DB without wizard and call procedures and query tables.
Thanks in advance and i am a begineer in MVC
I hesitate to respond to this, but EVERY video you have seen is likely using an OR/M to generate the Model and the DAL. The generated DAL will likely encapsulate your calls to the stored procedures that you're asking about.
The thing is -- and here's why you're not getting the answer you're looking for -- each OR/M is going to have a different method of retrieving data from and inserting data into the database. How you retrieve data from the DB using an OR/M is going to be different if you're using Entity Framework, Linq to SQL, SubSonic, NHibernate, or any other OR/M.
So, the question is to you. Are you using a OR/M? If so, which one? If not, then you will use the standard ADO.NET calls to retrieve and store data. This is also reflected in my comment to your original question.
Yes you can (google ado.net for tutorials on ado.net), but it's not the MVC way. The MVC way is to use some sort of ORM (Object-relational mapping) such as NHibernate, Subsonic or Linq for SQL.
how to connect to DB without wizard and call procedures and query tables.
To call a procedure (here it will return no result, just perform some action):
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection .Open();
using(SqlCommand command = connection.CreateCommand(nameofthestoredprocedure))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#someparameter", somevalue);
maCommande.ExecuteNonQuery();
}
}
You can put your connection string in the config, just like you're used to.
You can call procedures the same way you would from any .Net application too. #svinto's advice about using an ORM is another way of doing things and is well worth looking at too. Many of the good examples for ASP.Net MVC use the ORM techniques.
If you don't want to go down that route, you might benefit from creating a seperate class library project that you reference from your MVC application. Your Class Library project can act as your data access layer (DAL) where you handle db calls, etc...
Your Controllers can then call your DAL and processing methods to populate entities for the Views.
Ahmy, I think the best advice to give would be before you start off developing using the MVC framework is to have a look into the principles behind the MVC pattern and domain driven design.
Specifically , have a look at repository patterns etc.
You can still add connection strings to your web.config in a block and access them as you would have done in a webforms project, after all Asp.net MVC is based on webforms. Its just likely that you wouldn't really want to do this if you're utilising MVC the way it was intended, its all about seperation of concerns.
www.asp.net has some great intro. examples worth watching.
Try downloading NerdDinner, or even better ... ContactManager iteration 1 (the tutorial directly answers your Q). Those should give you a good idea for how to handle database access. I wouldn't suggest looking at something like Oxite or MS StoreFront though, as these are a bit more complex.
To specifically answer your question: the connection string, like in ASP.NET, can go in your web.config or hard-coded in your application.

How do you do validation in ASP.NET MVC RC?

Does ASP.NET MVC provide a standard validator functionality or do you have to create your own validation manually? If the latter, is there any third party validator available that you can use on ASP.NET MVC web applications?
Shortly after I posted this answer I found xval which is a validation framework for ASP.NET MVC.
ASP.NET MVC contains methods like Html.ValidationSummary() and Html.ValidationMessage(). These are updated automatically if you use TryUpdateModel. You could also validate manually and set the errormessages yourself. Here is an example of how use it.
David Hayden wrote an article over at www.codebetter.com describing a great way to handle validation. Of course xVal is an option but it's always great to have an understanding.
I implemented a variant of the code I found on Stephen Walther's blog. I use it with LINQ2SQL models by defining an IValidatedEntity interface that includes the GetRuleViolations() method and implementing the partial OnValidate method that calls GetRuleViolations() and throws a custom exception if the number of violations is non-zero. In the controller, this fires on SubmitChanges for the data context. If I get an exception I requery the model via the GetRuleViolations() method to build model errors to pass back to the view.
You can also checkout the .net validation framework. Its a rules framework that lets you create validators, apply the validators to rules, attach rules to your model, and check those rules at runtime on both the client and server. It provides flexible ways to configure rules - making heavy use of linq for both fluent and strongly typed configuration. It also provides extensibility points to create your own client script generators and rules.
The framework leverages the MVC RC HtmlHelpers and default conventions.
If you download the latest source you can see an example of the framework working in the SplitBranch -> QSAspMvc quickstart project. Its still being actively developed.

Which validation library for ASP.NET MVC?

I'm trying to decide what validation approach to take for a new ASP.NET MVC project. (And wow there are plenty of options!)
The project uses NHibernate, so the first thing I considered was the NHibernate Validator (Because of tight integration with NHibernate). However, as far as I can see there are only a couple of benefits to this tight integration:
1) DB Schemas generated by NHibernate will include details of validation (e.g. column lengths will be set to max value allowed in validation). (This is not really of interest to me though, as I generate schemas manually.)
2) NHibernate will throw an exception if you try to save data that doesn't meet the validation specs. (This seems fairly redundant to me, since the data presumably will already be validated by whatever mechanism you choose before saving anyway)
If there are more benefits to NHibernate Validator please let me know!
Other libraries which I've been reading a little about include:
MS DataAnnotations
Castle Validator
Something else?
I've also been thinking about using xVal to provide client side validation from the same set of rules. However, I hear that ASP.NET MVC v2 will include something similar to xVal (integration with jquery) out of the box? Will this new included functionality render some of the others redundant?
So, I'm basically asking for people's advice on which direction to take here. I don't want to implement a particular scheme, only to have to rip it out when another one becomes the dominant tech.
What has worked for you? Which option do you think has/will have the edge?
Thanks!
I have been using FluentValidation along with jQuery validation plugin and still cannot find a situation they cannot handle.
I like xVal.
You can implement very easily client and server validation with it. Also there is support for column (property) validation on entities that you would like to use.
DataAnnotations implemented by buddy classes and JQuery client validation
Make sure you're using MVC Preview 2
You might be interested in this delegate approach. I was because i didn't like the xVal idea (the solution im currently going with) and the fact that it didn't seem to cater for complex validation cases that crossed multiple properties of the same or even different class structures.

Resources