Angular with .NET WebAPI validation, and single-point-of-truth - asp.net-mvc

Is there an approach that preserves the single-definition of validation, allows immediate client-side validation, and still provides the strength of server-side validation?
I'm familiar with the following two approaches:
ngval (https://github.com/alisabzevari/ngval)
http://www.danielroot.info/2013/09/hooking-angularjs-validation-to-aspnet.html
The first renders ng-validation syntax in Razor output, based on rules stated in the model. That seems like it couples me too tightly to building Razor views, when Razor views often won't intuitively pair with a well-organized Angular app. I could use this approach, but it seems it's more a result of someone wanting to replicate "Unobtrusive jQuery/MVC Validation", than building something well-suited to Angular.
The second approach just returns server-side validation back to Angular to render. It also doesn't do a thorough job of it. If needed I could run without client-side validation, since a single-page app still won't get screen flashes... but it's not ideal.
For example, maybe there is a toolset to more directly reflect the validation rules directly on WebAPIs and consume them in an Angular app. Or another approach that I haven't found?
At https://www.youtube.com/watch?v=lHbWRFpbma4#t=1336 , the presenter seems to imply this problem is already well-solved for Angular, and refers to specification (DDD Using Specification pattern for Validation). If you are aware of any tools that make this applicable to my problem, I'd love to hear it.
p.s. It seems like this is almost certainly an often-asked question. I'm sorry I was unable to find an answer here before posting
p.p.s. I'm currently planning to use Entity Framework, but I'd switch to address this. Heck, I'd consider switching to a whole different platform for this, my first Angular-focused project.

The approach I recommend is based on #Esteban Felix commented and I used similar strategy in Java/Bean Validation and JSON schema generator.
Annotate your Domain model using Validate Model Data Using DataAnnotations
Generate schema using JSON.net other useful links
Create a AutoValidate directive that goes on and decorate fields with AngularJS build in directives for form validation e.g. ngPattern and simple things like min/max. In my case I created a mapping from Java world to AngularJS directives and wherever I needed we created custom directives.

Related

Why does HotTowel include Breeze?

This may sound like a dumb question on the surface, but why does the Hot Towel SPA Template include Breeze at all?
I've been spending the last few days learning Hot Towel and its dependencies, and as far as I can tell, nothing in the template actually uses Breeze. Perhaps that is going to change with some future release?
Sure, Breeze is a good library. But it's bound to CRUD methodology and requires you design your ApiControllers a particular way. (Metadata, SaveChanges, etc.) see here
It also guides you to Entity Framework. While this is more of a soft-dependency, since Breeze also shows a sample without it, it still guides you down a similar pattern of implementation using a modified repository pattern.
If you are using a NoSQL datastore, or CQRS patterns instead of CRUD, then Breeze becomes very difficult to use. There are alternative libraries for data access that work well in this style, such as AmplifyJS.
But the rest of Hot Towel is excellent! I especially like Durandal. So the question begs, if the template isn't actually doing any data access - why include any data access component at all? It would be better to ship it without Breeze, and if the end-user wants to use Breeze, or Amplify, or whatever - then so be it. The rest of Hot Towel would continue to shine as a great SPA implementation.
Matt - Good question. Since I created it I guess I should answer :)
When I built the template I had a focus on providing enough to get folks going with the right tools, and just enough starter code to guide the way. I did not want anyone ripping out code. I'm not a fan of templates that start you down a path and make you remove tons of files and code and change direction. Those are samples.
Samples are good. In fact, samples can be excellent (like the other templates, which I feel are more like samples). Those serve another purpose: to show how you can do things.
Back to the Hot Towel template ...if I include code that uses Breeze, I would be tempted to add a datacontext.js and a model.js on the client. They would contain data access code and code to extend the models on the client. Then I would be tempted to add a controller, some server side models, an ORM and a database. Once there, I'd want to use the data in multiple screens, which leads me to more Knockout and caching with Breeze. Then I might be tempted to add editing, which would lead to change tracking. Soon I have a full blown app. Or more conservatively, I have a sample again. While these approaches would provide more guidance on how to put these together, they would not help you "get started" with a template where you can just start building and adding your own code. If I stop short of some of these features, it's still walking down a road that requires you to change how I did it.
As it stands today, HotTowel is pretty darn close to a template in the truest sense. You create a new project and you are off and adding your own code.
You could argue (and you may be) that Breeze shouldn't be in there since I don't use it in the template. Nor do I use moment.js, BTW. However, I argue that they are both excellent libraries that I would not want to build a CRUD based SPA without them. Breeze is flexible, as you suggest, so you don't have to walk a specific path.
The best way to understand the value of Breeze is to build an app that has its features but without Breeze. Then you can see how much code that takes and how involved it is. For one such example, see my intermediate level SPA course at Pluralsight where I do exactly this: http://jpapa.me/spaps
So you ask "why Breeze?" ... because I strongly recommend it for building a SPA.
Thanks for asking and good luck !
Thanks for asking the question.
John, as author of HT, has offered an answer. I, as a principal of the Breeze project, am inclined to agree with him :)
HotTowel generates a foundation for you to build upon. It is not the building itself.
It is a foundation intended for a specific kind of application, a CRUD application based on a specific set of cooperating JavaScript and ASP.NET technologies. Breeze is a contributor ... but not the only one. Knockout, with its MVVM design and 2-way data binding, is particularly well-suited to the data-entry tasks typical of CRUD apps.
Of course there are other kinds of SPAs. There's an important class of apps that mostly present information and accept little user input. Such apps don't benefit as much from data binding and the people who write them can get pretty hostile about data binding in general and KO in particular.
My point is that HT targets a particular class of application ... one that happens to be immensely successful at least when measured by sustained popularity. It delivers the goods for people who build those apps. It may not be the right starting place for other kinds of apps.
It is true that the easy road to Breeze runs through Web API, EF, and a relational database. Take those away, and you may writing more code on the server (and a little more on the client). That may be the perfect trade-off for you.
The authors of Breeze would like to make that path easier. I don't think BreezeJS makes it harder. I don't understand your statement "Breeze becomes very difficult to use." Have you tried it?
Your client can communicate with any HTTP resource in any manner you chose. It is pretty easy to use existing Web API controllers (albeit easier with Breeze Web API controllers). You can use amplify.js if you prefer (btw, you can tell Breeze to make AJAX calls with amplify). You don't even have to use the Breeze EntityManager to query and save data if you don't want to.
The rest of BreezeJS may still have value for you. There remains plenty of work to do after you've figured out how you'll retrieve and store data and whether you prefer Entity-ChangeSet style or Command/Query style.
You'll have to find answers to these questions:
How will you shape the raw JSON data into bindable objects?
How will you hold on to these objects and share them across multiple screens without making redundant round-trips to the server?
How will you navigate from one object to a related object as you do when binding an Address to a combobox of StatesAndProvinces?
How will you track changes?
How will you validate them?
How will you store some or all of the data in local storage when the app "tombstones"?
Breeze can help with these chores even if you don't want it to query and save for you.
And if you're answer remains "I'll do all of that myself, thank you" ... well, removing Breeze from your HotTowel project is as easy as:
Uninstall-Package breeze.webapi

Concerns about ASP.NET SPA(Single Page Application)

Here is my knowing about ASP.NET SPA:
have to use Upshot to talk to the server;
have to use DbDataController to provide Web APIs;
have to use Entity Framework Code first...
so, many concerns come out:
have to provide metadata for the upshot to work, this will obviously expose the structure of your database;
can i use Entity Framework Database First instead of Code First? You may ask why. Because Code First don't provide you the ability to customize your database(index customization, stored procedure...etc.);
A problem i met: when i add a "TestUpshot.edmx" file(generated from database 'northwind') to the MySpaApp.Models folder(trying to test whether i can use the edmx classes in the MyDbDataController class, and generate proper metadata in the client side), and run the application, there is an exception:"System.ArgumentException: Could not find the conceptual model type for MySpaApp.Models.Categories."...
Need help here, thanks in advance.
Dean
I may be missing something, but there is no requirement to use any of the technologies you've listed.
An SPA is just a pattern. You can use whatever you need to achieve that. There may be benefits with choosing certain technologies, ie templates, tutorials, etc.
Doesn't really answer your question, but should lead you to experiment with what you've got.
SPA is actually a way to conceptualize your client application. SPA comes the closest to the fat client - data server concept from the current web approaches. Definitely this will be the ruling concept within a couple of years.
Your concerns can be addressed using JayData at http://jaydata.codeplex.com that provides advanced, high level data access for JavaScript against any kind of EntityFramework back-ends (db, model or code first). Check out this video that presents the whole cycle from importing your EDMX from SQL (this could eighter be model first definition as well) to inserting a new product item in the Products table from JavaScript.

ASP.NET MVC with Knockout and Web API: does it make sense?

does it make sense to use KnockoutJS Viewmodels in combination with ASP.NET MVC3 or 4? Because it is not very DRY, isn't it? I have to write models for EF, Viewmodels for the MVC Views and Viewmodels for Knockout... and i lose a lot of magic. Automatic client-side validations for example.
Does it make sense to use MVC at all if one sticks with the MVVM Pattern?
With Knockout Mapping, you can automatically generate a KO view model from your MVC view model.
This is a proper pattern: your models are raw entities, your data. Your views are the UI. And your view models are your models adapted to that specific view.
This may be an unpopular answer, but I don't use ko.mapping to translate my C# POCOs into JS viewmodels. Two reasons, really.
The first is a lack of control. ko.mapping will turn everything into an observable if you let it. This can result in a lot of overhead for fields that just don't need to be observable.
Second reason is about extensibility. Sure, ko.mapping may translate my C# POCOS into JS objects with observable properties. That's fine until the point you want a JS method, which at some point, you invariably will.
In a previous project, I was actually adding extra methods to ko.mapped objects programmatically. At that point, I questioned whether ko.mapping was really creating more problems than it solves.
I take on board your DRY concerns, but then, I have different domain-focused versions of my POCOs anyway. For example a MyProject.Users.User object served up by a UserController might be very different from a MyProject.Articles.User. The user in the Users namespace might contain a lot of stuff that is related to user administration. The User object in the Articles namespace might just be a simple lookup to indicate the author of an article. I don't see this approach as a violation of the DRY principle; rather a means of looking at the same concept in two different ways.
It's more upfront work, but it means I have problem-specific representations of User that do not pollute each others' implementations.
And so it is with Javascript view models. They are not C# POCOs. They're a specific take on a concept suited to a specific purpose; holding and operating on client side data. While ko.mapping will initially give you what seems to be a productivity boost, I think it is better to hand-craft specific view-models designed for the client.
btw, I use exactly the same MVC3/KnockoutJS strategy as yourself.
We use knockout Mapping to generate the KO view models well.
We have a business layer in a separate project that does CRUD, reporting, caching, and some extra "business logic". We aren't going to be using EF, or something similar. Currently we've defined c# classes as MVC models, and our controllers call the business layer to construct the Models that are defined in the usual place in our MVC app. These C# models get serialized as JSON for use in our pages.
Since everything we do in the browser is c#/JSON based using knockout, we aren't using MVC models in the traditional MVC way - everything gets posted as JSON and serialized to c#, so we don't use MVC model binding, validation, etc. We're considering moving these models to our business layer so they can be tested independently of the web app.
Se we'll be left with an MVC app that has controllers and views, but no models - controllers will get models that are defined in the business layer. We're nervous about departing from the normal MVC structure, but a KO/javascript based client is fundamentally different from a DOM based client that MVC was originally built around.
Does this sound like a viable way to go?
I work now on project which mixes MVC3 and knockouts and I have to tell you - it's a mess...
IMO it's nonsense to force some patterns just to be up to date with trend.
This is an old topic, but now in 2014 (unfortunately) I still feel this question has a huge relevance.
I'm currently working on a project which mixes MVC4 with knockoutjs. I had some difficoulties to find whichs part should be handled on which side. Also, we needed a "SPA-ish" kind of architecture, where each module has its own page, but then inside that module there is only AJAX interaction. Also faced some heavy validation scenarios, and needed to provide user (and SEO) friendly URLs inside each module. I ended up with the following concept, which seems to be working well:
Basic MVC and .NET side roles:
Handling authentication and other security stuff.
Implementing the Web API interface for the client-side calls (setting up viewmodels, retrieving and mapping data from the domain, etc.)
Generating knockout viewmodels from my (pre-existing) C# viewmodels with T4 templates, also including knockout validation plugin extensions from .NET validation attributes. (This was inspired by this aticle). The generated viewmodels are easily extensible, and the generation can be finetuned with several "data annotation"-like custom or built-in attributes (such as DefaultValue, Browsable, DataType, DisplayFormat, etc.). This way the DRY doesn't get violated (too much).
Providing strongly typed, but data-independent partial view templates for each submodule (each knockout viewmodel). Because property names on C# viewmodels are same as in KO models, I can benefit from the strongly typed helpers specifically written for KO bindings, etc.
Providing the main view for each module similarly to previous point.
Bundling and minification of all scripts and stylesheets.
Basic client-side roles:
Loading the initial state of all viewmodels encapsulated into one module page, taking the whole URL into account with a simple route parser implementation.
Handling history with history.js
Data-binding, user interaction handling.
Posting relevant parts of viewmodels to the server, and processing the returned data (usually updating some viewmodel with it).
I hope this could help anyone else who feels lost in the world of trendy technologies. Please, if anyone has any thought on this, feel free to post any question or suggestion in the comments.

Is there any point to writing your own validation framework for MVC beta or do you expect one will be released soon?

There have been plenty of questions on MVC validation but so far the answer has been pretty much inconclusive.
For my needs in particular, I would like something that generates client validation and server validation from the same description and should allow both model based attributes as well as code based declarations for those using an ORM (e.g. LINQ TO SQL) exclusively.
I have seen some validation packs that have been whipped up to do this but they tend to introduce a lot of dependencies or are reasonably incomplete (e.g. no support for check boxes or no "higher-level" validation).
Do we begin writing our own validation framework or do we wait in hope that the team may actually release something now that they have the structure for validation in place and jQuery on board?
For those out there actually using MVC in the field now what are you using for validation?
Are you aware that validation semantics have been added in preview 5? This article from Scott Gu describes how to use it, and this one details the changes in the beta.
I have not personally used it, and it may not fit all your requirements, but I have no doubt it could be extended to behave like you want.
The best way as of the released MVC 1.0 is to use xVal.
You may also need to look at this post on implementing Linq2SQL with xVal in case that hasn't been resolved/doesn't work.

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