Validation in ASP.NET MVC using Code Contracts - validation

I want to know the available options for using the "Code Contracts" attributes as the validations rules in ASP.NET MVC 2.

You could do this by customizing the Runtime Checker.
Although it is possible to tweak Code Contracts into being used as a validation framework, I would advise against it. It is one of the more advanced features to tweak the Runtime Checker and more importantly, not what Code Contracts is made for.
Code Contracts is basically a means of integrating Design by Contract in your project. Although one of its purposes is to validate your code against your class design, it is not a validation framework.
In my opinion, you should use it next to another real validation framework.
Before you start using Code Contracts, I suggest you read the user manual here. It has all the information, including how to customize the Runtime Checker.

Yes that is true that the main purpose of "Code Contracts" is to validate my code against my class design but it also describes the valid states of my object.
All I can think of validation scenarios, is of these three types:
Input Validation ( UI Validation )
Domain Validation ( DbC )
Output Validation (Persistence
Validation, Ex: NHibernate
Validator )
I consider validation as a logical question whether the target object is in a valid state or not.
The DbC has three parts,
the validation rules
the static checker
the runtime checker
The first part ( the rules) is common in all three scenarios of validation. When I tag a property with "Not Null" using "Code Contracts" to validate its design, isn't it ugly to have it tagged "Not Empty" using "System.ComponentModel.DataAnnotations" for MVC (UI Validation) ?
In abstract, the definition of valid states is core and the shared part of validation frameworks and "Code Contracts" provides it, with one extra which is the "Static Cheker" for the domain design (not the I/O).

Related

Handling Action errors/output inside out-of-the-box Workflows

I am working on designing a lengthy approval system in CRM using a combination of OOB workflows (designed using CRM UI Workflow Designer) and custom actions (actions written using .NET code). Idea is to keep the entire branching/simpler logic in OOB workflow and call custom Actions wherever necessary. However I have few questions with this approach:
How can I handle run-time errors generated in the action code?
For example, one of my Actions contain the code to push data to an external system via web service. In case this web service call fails, I need to perform some steps in the parent workflow.
How can I handle 'if conditions' which can't be handled by 'Check Condition' step? For example, suppose that before performing a certain workflow step I need to check some data which can't be queried within CRM. I can create an Action which will return true/false based on the custom logic which can then be checked in parent workflow.
An alternate approach would be to use plugins but I am inclined towards using OOB functionalities as much as possible. Any inputs would be helpful.
First of all let's clear the semantics, because I'm not sure if you understand what are you talking about - there are Actions (you can refer to them as custom actions, but then you should refer to every workflow you create as custom and I figured out of your post that you are describing them as OOB, which also is semantically wrong - every workflow you create is a custom workflow, maybe it's using OOB steps, but that's a different story) and Custom Workflow Activities. I'm assuming that you want to use Custom Workflow Activities, because the are more suited for what you are trying to achieve here. Also you tagged your question as CRM 2011 and CRM 2013 - not sure what you meant, because Actions were not available for CRM 2011.
So basically Custom Workflow Activities can have Input and Output parameters. Output parameters are answer to both your questions, because you can use them to get the error message after your custom processing or use then in conditional statements later in your workflow. Output parameters can be defined like that:
[Output("Error message")]
public OutArgument<string> ErrorMessage { get; set; }
You can find more examples here:
https://technet.microsoft.com/en-us/library/gg327842.aspx
You can of course set this properties simply by calling
ErrorMessage.Set(executionContext, messageText)
So now when you define your workflow, wherever you need something not configurable in OOB blocks, you can put your Custom block, after it's done simply check it's output for the error (this is just an example, you can pimp it up by adding additional output parameters, to make it more generic), if it's empty then do something, if not then do something else for example send email with the error message. It all depends on what are you trying to achieve.
Actions are serving different purposes, they are useful to create a logic that can be easily called through plugin or javascript (webAPI) and allows you to also put a plugin on it alongside doing everything within one transaction. Maybe it will be useful somewhere in your workflow, but as far as I remember in CRM 2013 actions could not be called from a workflow...
UPDATE:
Ok so if we are dealing with CRM 2016, we can call Action from a workflow. What is best in this situation really depends on the scenario and what we are trying to achieve, but to make it easier to decide let me highlight main differences:
1) Activities are simply a blocks of code that can be put inside your workflow. Actions by themself are not code, they are custom Messages that you can call. Of course you can register a plugin on this custom Message and do there any custom logic you want, but this is another step to take
2) Actions can be run in transaction, Activities not (but you can run Activities inside Actions, so in this case they can run in transaction)
3) Actions can be called directly from Javascript, plugins and workflows. It's a great thing, but if you will make let's say 10 custom Actions which you will be using ONLY inside you one workflow, they will be visible when you will be registering plugins (and also any js developer will be able to call them with JS)
So basically Actions are a big, fat feature that can serve many purposes (including running Activities on their own!), Activities are much simpler but in your case they will also do their job. So you should ask yourself questions:
Do I need my logic to run inside transaction?
And
Do I need to call this logic somewhere else than my workflow?
If you have any "Yes" then go for Actions, of no, then go for Activities, because you will be overcomplicating things without any good reason.

Validation and ComplexTypes

I have read BreezeJS documention about validation and ComplexTypes. To my knowledge, there should be no reason for that scenario to work.
We use breeze.directives.js. BreezeJS version is 1.4.14. In our application, Person-entity has property PhoneNumber which is ComplexType. Person-entity is binded to a view in AngularJS app. For validation we used the example from Code Camper SPA. Person-entity gets validated and zValidate works as expected. To our surprise PhoneNumber-complextype gets validated too , but validation errors dont show up. So it seems there's problem with zValidation and ComplexTypes.
Anyone know if it should work ? Or are we just missing something?
Note: DocCode or any other sample didn't include this scenario implemented.
zValidate was not written to support ComplexTypes. zValidate is part proof-of-concept and part invitation to the community to contribute. It demonstrates one way to expose Breeze validation to the UI, declaratively, with an Angular directive. We invite you to fork it and offer improvements or alternatives. We're eager to tell the world about your work :-)

DataAnnotation for Required property - Why is it required for asp.net webapi?

I read through these posts
DataAnnotation for Required property
http://forums.asp.net/t/1835627.aspx/1
and I understand it has something to do with xml and not supporting required but I don't get why this is an issue.
I have a View Model that has a Required attribute over a Guid and that is what is causing the problem. I just don't get how the xml factors into this as the request is REST so where does the xml come in play to cause this problem.
The validator was added as a security measure because all Web APIs accept XML by default. And because the XML formatter doesn't raise model state errors for missing required members, you could end up in a situation where a required member was missing and yet the model state was valid.
With that said, this behavior has caused a lot more trouble than it's worth. So it is gone in the current nightly builds, and it won't be there in the next version of Web API. In the meantime, you can disable it with this line:
config.Services.RemoveAll(typeof(System.Web.Http.Validation.ModelValidatorProvider),v => v is InvalidModelValidatorProvider);

Enum in custom web test validation rule

I'm building a Web Test using Microsoft VS2010.
I used the explanation on MSDN: How to: Create a Custom Validation Rule for a Web Performance Test.
In the example there using string and int as private members with public "get" and "set" those parameters valid for edit in the UI when I add this validation rule to my test.
I want to have an Enum with 3 option that when I add the validation rule to the UI I can choose from.
Is there a way to add an Enum variable which will also be valid in the UI ?
Are there any other types which can be used which will be valid in the UI ?
Unfortunately the UI only shows String and primitive-type properties in user-created rules/plugins. Yet some built-in rules/plugins use enums... how can this be? Thanks to the magic of the disassember and some detective work, we discover that it only accepts enums whose assembly name contains the string "Microsoft.VisualStudio.QualityTools.WebTestFramework".
So if you go to the trouble of compiling your enums (or indeed, your entire project) into an assembly called, for example, "MyEnums.Microsoft.VisualStudio.QualityTools.WebTestFramework", BOOM your enum-typed properties will happily appear in the editor UI.

MVC3 is valid email

Is there a built in function which will test if an email address is valid?
I want to test the email address structure is valid before sending a confirmation email to the end user.
I understand i could create my own function easy enough with the use of a regular expression but if there is a built in function i would much rather use this.
You can do this with Data Annotations extensions I believe. Check out Scott Guthrie's blog post on it here: http://weblogs.asp.net/srkirkland/archive/2011/02/23/introducing-data-annotations-extensions.aspx.
There is a good point in Scott's post as to why you would use this rather than the MVC 3 Futures validators which might be relevant to your choice:
ASP.NET MVC 3 futures defines four new data annotations attributes which this project has as well: CreditCard, Email, Url and EqualTo. Unfortunately referencing MVC 3 futures necessitates taking an dependency on MVC 3 in your model layer, which may be unadvisable in a multi-tiered project. Data Annotations Extensions keeps the server and client side libraries separate so using the project’s validation attributes don’t require you to take any additional dependencies in your model layer which still allowing for the rich client validation experience if you are using MVC 3.
Yes, you can use
public class CustomerMetaData
{
// Add type information.
[DataType(DataType.EmailAddress)]
public object EmailAddress;
}
on your model. See more about it here.
however, last time I checked it does not work client sided.
I googled it, and from imran baloch's blog post it seems it does work now.

Resources