I would like to know if it is possible to disable the validation for a subset of modelelements which are specified in the metamodel.
The problem is that I'm getting some validation-errors from the Xtexteditor while writting my dsl-file. So my idea is to disable the validation for exactly this modelelement.
I try to build a real simple textual notation and want to serialize the (valid) model while saving the file. The saved model is modified during the saving process, so it is
valid at the end.
Regards,
Alex
Lets beginn with the grammer:
I'am working on an imported metamodel (UML2):
import "http://www.eclipse.org/uml2/4.0.0/UML"
Then I create all the necessary parserules to define a classdiagram. In my case the problem appears
in the parserrule for associations between classes:
AssociationClass_Impl returns AssociationClass:
{AssociationClass} 'assoc' name=ID'{'
(ownedAttribute+=Property_Impl)*
'}';
And of course the parserrule for properties:
Property_Impl returns Property:
name=ID ':' type=[Type|QualifiedName]
(association=[AssociationClass|QualifiedName])?
;
Now some words to the problem itself. While editing the xtext-file in the xtexteditor of the runtime eclipse, the build model is validated. The problem is here that the metamodel itself has several constraints for an AssociationClass (screenshot not possible yet ):
Multiple markers at this line
- The feature 'memberEnd' of 'org.eclipse.uml2.uml.internal.impl.AssociationClassImpl#142edebe{platform:/resource/aaa/test.mydsl#//Has}'
with 0 values must have at least 2 values
- The feature 'relatedElement' of 'org.eclipse.uml2.uml.internal.impl.AssociationClassImpl#142edebe{platform:/resource/aaa/test.mydsl#//Has}'
with 0 values must have at least 1 values
- The feature 'endType' of 'org.eclipse.uml2.uml.internal.impl.AssociationClassImpl#142edebe{platform:/resource/aaa/test.mydsl#//Has}'
with 0 values must have at least 1 values
- An association has to have min. two ownedends.
And now I wanted to know if it is possible to disable the validation for exactly this modelelement. So I can hide the errorinformation from the user. Because I want to serialize the created xtextmodel in the next step and will do some modeltransformations.
Seems like UML registers this validator in the global singleton registry. So you basically need to avoid using the registry. You can do that by binding a different element in your runtime modul:
public EValidator.Registry bindEValidatorRegistry() {
// return an empty one as opposed to EValidator.Registry.INSTANCE
return new org.eclipse.emf.ecore.impl.ValidationDelegateRegistryImpl();
}
Related
I'm currently building a Laravel 5.7 app where I have multiple boolean columns that indicate if some facilities are available for a building (model), eg, toilet yes/no. This works fine, but I was wondering what happens when I add more of these boolean columns later when I deploy the app.
Say I add a boolean column 'lights,' I could give it a default value of 0, but not NULL. So now all my existing buildings will say that there are no 'lights' (because the value is 0), where in reality it should be something like 'don't know' or 'undefined' Like a third state.
Should I use ENUM columns with yes/no/undefined instead? What are best practices for this scenario?
What I would do, is create separate table, with object_id, and facility_id. Now, you can have dynamic facilites table, and connect them with object. Connection will only have what it needs, so not every object "light" or something else.
You can certainly create them them as nullable()! It is a common practice, IMO.
As far as best practices go, it depends on how your application should be used. Do you want a user to notice that the state has not been selected one way or the other yet? Maybe you are displaying a prompt to configure the ones that are null. On the other hand, it may be safer to assume that the options should default to false in order to be rendered properly. If this is the case, maybe a notification can go out to your users to update this property.
This worked to me
$table->boolean('lights')->nullable();
Yes Yo are Right this could be a problem some times
But the Boolean CAN BE USED SUCH AS TRUE (OR) FALSE ie) 0 (OR) 1
where in reality it should be something like 'don't know' or 'undefined' Like a third state.
So in this Situation use Can use Enum
For Example Your table will have ups_availablity
Scenario One :
If you want to add NotAvailable by default just pass the value inside default method
$table->enum('ups_availablity', ['Available', 'NotAvailable'])->default('NotAvailable');
Scenario Two:
If you want to add Null add nullable method
$table->enum('ups_availablity', ['Available', 'NotAvailable'])->nullable();
If You have any clarification Kindly Comment Below
Hope its helps
Data validation should occur at the following places in a web-application:
Client-side: browser. To speed up user error reporting
Server-side: controller. To check if user input is syntactically valid (no sql injections, for example, valid format for all passed in fields, all required fields are filled in etc.)
Server-side: model (domain layer). To check if user input is domain-wise valid (no duplicating usernames, account balance is not negative etc.)
I am currently a DDD fan, so I have UI and Domain layers separated in my applications.
I am also trying to follow the rule, that domain model should never contain an invalid data.
So, how do you design validation mechanism in your application so that validation errors, that take place in the domain, propagate properly to the client? For example, when domain model raises an exception about duplicate username, how to correctly bind that exception to the submitted form?
Some article, that inspired this question, can be found here: http://verraes.net/2015/02/form-command-model-validation/
I've seen no such mechanisms in web frameworks known to me. What first springs into my mind is to make domain model include the name of the field, causing exception, in the exception data and then in the UI layer provide a map between form data fields and model data fields to properly show the error in it's context for a user. Is this approach valid? It looks shaky... Are there some examples of better design?
Although not exactly the same question as this one, I think the answer is the same:
Encapsulate the validation logic into a reusable class. These classes are usually called specifications, validators or rules and are part of the domain.
Now you can use these specifications in both the model and the service layer.
If your UI uses the same technology as the model, you may also be able to use the specifications there (e.g. when using NodeJS on the server, you're able to write the specs in JS and use them in the browser, too).
Edit - additional information after the chat
Create fine-grained specifications, so that you are able to display appropriate error messages if a spec fails.
Don't make business rules or specifications aware of form fields.
Only create specs for business rules, not for basic input validation tasks (e.g. checking for null).
I want to share the approach used by us in one DDD project.
We created a BaseClass having fields ErrorId &
ErrorMessage.
Every DomainModel derive from this BaseClass & thus have a two extra fields ErrorId & ErrorMessage available from
BaseClass.
Whenever exception occurs we handle exception(Log in server, take appropriate steps for compensating logic & fetch User Friendly message from client location based localized Resource file for message ) then propagate data as simple flow without raising or throwing exception.
At client side check if ErrorMessage is not null then show error.
It's basic simple approach we followed from start of project.
If it's new project this is least complicated & efficient approach, but if you doing changes in big old project this might not help as changes are big.
For validation at each field level, use Validation Application Block from Enterprise Library.
It can be used as :
Decorate domain model properties with proper attributes like:
public class AttributeCustomer
{
[NotNullValidator(MessageTemplate = "Customer must have valid no")]
[StringLengthValidator(5, RangeBoundaryType.Inclusive,
5, RangeBoundaryType.Inclusive,
MessageTemplate = "Customer no must have {3} characters.")]
[RegexValidator("[A-Z]{2}[0-9]{3}",
MessageTemplate = "Customer no must be 2 capital letters and 3 numbers.")]
public string CustomerNo { get; set; }
}
Create validator instance like:
Validator<AttributeCustomer> cusValidator =
valFactory.CreateValidator<AttributeCustomer>();
Use object & do validation as :
customer.CustomerNo = "AB123";
customer.FirstName = "Brown";
customer.LastName = "Green";
customer.BirthDate = "1980-01-01";
customer.CustomerType = "VIP";
ValidationResults valResults = cusValidator.Validate(customer);
Check Validation results as:
if (valResults.IsValid)
{
MessageBox.Show("Customer information is valid");
}
else
{
foreach (ValidationResult item in valResults)
{
// Put your validation detection logic
}
}
Code example is taken from Microsoft Enterprise Library 5.0 - Introduction to Validation Block
This links will help to understand Validation Application Block:
http://www.codeproject.com/Articles/256355/Microsoft-Enterprise-Library-Introduction-to-V
https://msdn.microsoft.com/en-in/library/ff650131.aspx
https://msdn.microsoft.com/library/cc467894.aspx
I'm building a CRM solution for a customer to replace their legacy Access databases. They have cases with case numbers that are referenced by external documents and want to keep them as the case number in CRM. I wrote a plugin that auto-increments and assigns case numbers when new cases are created and it works great. The problem is when I try to import their old data. I map their old case number field to the case number field in the import wizard but the imported cases get a new case number like PRE-12345-asdf.
Case number can't be updated by a workflow.
Ideally I'd like to be able to use the built in case number, but would I be losing out on any functionality if I just hid the built in case number field and added a custom field for it?
You can create a custom field to track your own Case Number instead (in this case we just called it "casenumber").
On the Case Entity form onLoad event we put the following function that updates the Case Number shown in the Header area as well as the Page/Tab title to be our custom field:
function UseCustomCaseNumber()
{
var caseNumber = Xrm.Page.getAttribute("new_casenumber").getValue();
document.getElementById('form_title_div').childNodes[2].innerHTML = caseNumber;
parent.document.title = "Case: " + caseNumber + " - Microsoft Dynamics CRM";
}
The built-in case number cannot be overwritten. Hiding it and using your own field seems relatively common, and won't cause you any issues.
I have a content type derived from plone.directives.form.Schema; it has several dozen fields across four fieldsets. I'm trying to create a zope.interface.invariant that looks at fields from two different fieldsets.
From tracing the behaviour, it looks like the invariant is called once for each fieldset, but not for the entire form.
I'm aware I can provide my own handler and perform all the checks I need there, but that feels chunky compared to distinctly defined invariants. While the obvious solution is to move related fields onto the same fieldset, the current setup reflects a layout that is logical the end user.
Is there an existing hook where I could perform validation on multiple fields across fieldsets?
The answer seems to be no: z3c.form.group.Group.extractData calls z3c.form.form.BaseForm.extractData once for each group/fieldset, and this call already includes invariant validation.
Instead of registering your own handler, you could also overwrite extractData:
from plone.directives import form, dexterity
from z3c.form.interfaces import ActionExecutionError,WidgetActionExecutionError
# ...
class EditForm(dexterity.EditForm):
grok.context(IMyEvent)
def extractData(self, setErrors=True):
data, errors = super(EditForm, self).extractData(setErrors)
if not None in(data['start'], data['end']):
if data['end'] < data['start']:
raise WidgetActionExecutionError('end', Invalid(_(u"End date should not lie before the start date.")))
if data['end'] - data['start'] > datetime.timedelta(days=7):
raise WidgetActionExecutionError('end', Invalid(_(u"Duration of convention should be shorter than seven (7) days.")))
return data, errors
Please note that this class derives from dexterity.EditForm, which includes Dexterity's default handlers, instead of form.SchemaForm.
WidgetActionExecutionError does not work reliably, though. For some fields, it produces a 'KeyError'.
I'm developing a SL3 application with Prism. I need to have support for validation (both field level (on the setter of the bound property) and before save (form level)), including a validation summary, shown when the save button is pressed.
But the samples I can find googling are either SL3 with a lot of code in code behind (very uncool and un-Prismy), or WPF related.
Does anyone know a reference application with some actual validation I can look into?
Cheers,
Ali
There aren't any from Microsoft at present, but I'll pass this one onto the PRISM team tomorrow to see if we can get a basic Form Validation example inside the next rev of PRISM.
That being said, you can put a validator per Form that essentially validates each field (semantic and/or syntax validation) and should all pass, will return a true/false state.
A way I typically do this is I attach a "CanSave" method to my Commands ie:
SaveOrderCommand = new DelegateCommand<object>(this.Save, this.CanSave);
private bool CanSave(object arg)
{
return this.errors.Count == 0 && this.Quantity > 0;
}
Then in the this.CanSave, i then put either the basic validation inside this codebase, or I call a bunch of other validators depending on the context - some would be shared across all modules (ie IsEmailValid would be one Validator i place in my Infrastructure Module as a singleton and pass in my string, it would then true/false as a result). Once they all pass, ensure CanSave returns true. If they fail, the CanSave will return False.
Now if they fail and you want to trigger a friendly reminder to the user that its failed theres a number of techniques you can use here. I've typically flagged the said control at validation as being "failed".. (i wrote my own mind you, so up to you which toolkits you could use here - http://www.codeplex.com/SilverlightValidator is a not bad one).
Now, I typically like to do more with Forms that have validation on them by not only highlighting the said control (red box, icon etc) but also explain to the user in more detail whats required of them - thus custom approach is a solution I've opted for.
At the end of the day, you're going to have to do some of the heavy lifting to validate your particular form - but look into ways to re-use validators where they make sense (email, SSN etc are easy ones to re-use).
HTH?
Scott Barnes - Rich Platforms Product Manager - Microsoft.