How does validation work in database-first dbContext (EF4.3.1 & MVC3)? - asp.net-mvc-3

How does validation work in database-first DbContext (EF4.3.1 & MVC3)?
I'm doing this (yes, it's VB):
If ModelState.IsValid Then
db.SaveChanges()
But the SaveChanges throws DbEntityValidationException with the following message:
Validation failed for one or more entities. See
'EntityValidationErrors' property for more details.
I expect it to return the view again with the appropriate validation messages, but clearly I'm missing something because I don't know why it should work that way! You would expect Google to help, but most examples seem to be code-first.
This is database first, so the model has been generated. I would expected the validation constraints to be generated too (at least simple ones like NOT NULL in SQL Server) , but that doesn't seem to work.
Oddly, some fields are working as expected and others aren't.
For example, I have a non-nullable text field in the database. It appears as non-nullable in the EF designer and in the generated code. But when I submit it, I get the exception instead of returning the form with the field highlighted.
On the other hand, I have a date field that is non-nullable. It is checked prior to trying to update the database, and the form is presented again with the field highlighted for correction.

Related

How to check thrown errors during Sequelize validation execution

I have a sequelize model, which needs custom validation. That custom validation relies on some foreign keys being valid (valid as in valid uuid, not checked that they exist in db) on a record. There is also another validator appended that checks for mutual exclusivity of the foreign keys (only one can be present at the same time). After all this, I access the database in another validator to fetch data from another collection. I dont want this to happen if any of above validators fail because I dont want to access the database if I dont have to and I dont want to check if uuid is valid again because that is a job for one of previous validators.
The order is like so:
check if field contains valid type (uuid) - field type validator
check that field is not clashing with another field (mutually exclusive) - model-wide validator
fetch record from another collection to do further validation - model-wide validator
I want to check if previous validator has already thrown an error and not execute the next one if it has. Even better if I can check which one has thrown an error. Sequelize executes all validators even if error was already thrown. In documentation it says:
Any error messages collected are put in the validation result object
alongside the field validation errors, with keys named after the
failed validation method's key in the validate option object. Even
though there can only be one error message for each model validation
method at any one time, it is presented as a single string error in an
array, to maximize consistency with the field errors.
I tried several ways to access this "error" object but to no avail. Is there a way at all to know if error was already thrown by one of previous validators?

Validation running on all rows when tabbing Oracle ADF

I want a validation to fire after hitting tab on a field. The thing is every time I click on the empty field it runs the validation to all rows. Which causes errors because the other existing rows in the table aren't in the scope of the validation. I am using a back bean function to and can see the validation is called everytime I hit the empty field. I think this has to do with autosubmit being on but how else can I validate on a tab?
I don't know that this will answer your q's but might be a start:
http://www.slideshare.net/stevendavelaar/18-invaluable-lessons-about-adfjsf-interaction
https://docs.oracle.com/cd/E15586_01/web.1111/b31973/af_validate.htm
https://rohanwalia.blogspot.com/2013/10/client-side-validation-in-adf-faces.html
https://www.jobinesh.com/2009/08/how-to-skip-validation.html
Also, if you're doing ADF work definitely get Jobinesh's book as it covers many things in depth: https://www.barnesandnoble.com/w/oracle-adf-real-world-developers-guide-jobinesh-purushothaman/1111982100
Also consider ADF Cookbook.

Drupal: After any AJAX form event, all Entity Reference Fields are blank

After any AJAX event in the form (Upload image, add a new field collection row etc.) All Entity Reference fields go blank.
I have multiple entity reference fields, all using a view to get list options.
The issue is occurring on the node edit form.
On first page load, all entity form values are there, and you can edit and save them with no problems. However, If you edit any field that uses AJAX to update, then after ajax has run, all of the entity reference fields lose their options and only show "None" as the single option.
Can anyone think why this would be happening, and what steps I can take to either provide more info, or find a fix?
After using an AJAX field, and then trying to save the form, I get this error in watchdog,
TYPE form
DATE Tuesday, 21 June, 2016 - 08:47
USER collins
MESSAGE Illegal choice 7 in Venue element.
SEVERITY error
This obviously happens because the select lists are all empty, and illegal choices are detected.
heres a screencast of the issue.
http://tinypic.com/r/2pod2dy/9
Is there a way to use form API to rebuild the form and entity reference options after an ajax action?
I finally solved this.
There is a patch here... https://www.drupal.org/files/issues/entityreference-use-tokens-2010898-126.patch That allows you to use tokens in the Entity Reference Fields "Pass argument to view" field.
The problem was that after AJAX, the view I was using for the Entity Reference was losing its contextual filter argument. This patch, and the use of the token fixes the problem nicely.

Using Oracle's GUID()-generated ID's in Grails/Hibernate

I trying to use Grails Scaffolding to throw a quick CRUD application together around some legacy database tables. It is an Oracle database, and the primary key value is intended to be populated by Oracle's GUID() function.
Based on this earlier StackOverflow question, I tried specifying "guid" as the Hibernate generator for this column in my Grails domain class:
...
static mapping = {
table name: "OWNER"
version false
columns {
id column: "OWNER_OID", generator: "guid"
name column: "NAME"
...
}
}
...
When I run my Grails app, viewing and even editing records works just fine. However, when I try to create a new record, things blow up with the Oracle error message "ORA-02289: sequence does not exist".
I enabled SQL logging for my datasource, and see Grails/Hibernate trying to execute the following during a save operation:
select hibernate_sequence.nextval from dual
This doesn't look right at all, and doesn't match the generated SQL from that earlier StackOverflow question linked above. Does anyone see something I am missing here, or otherwise know how to make Grails/Hibernate populate a primary key column with Oracle GUID values?
Whew... after another day of wrestling with this, I think I have my arms around the thing. This answer covers a bit more ground than the original question description, but that's because I found yet more problems after getting past the Hibernate generator issue.
Issue #1: Getting an Oracle GUID() value
As covered by Adam Hawkes' answer, the "guid" Hibernate generator is unmaintained and only works for older versions of the Oracle dialect.
However, if you use the Hibernate generator "assigned" (meaning that you want to set primary keys manually rather than have Hibernate auto-generate them), then you can insert values pulled from an Oracle SYS_GUID() call.
Even though Hibernate's newer Oracle dialects don't support "guid" seamlessly, they still understand the SQL necessary to generate these values. If you are inside of a Controller, you can fetch that SQL query with the following:
String guidSQL = grailsApplication.getMainContext().sessionFactory.getDialect().getSelectGUIDString()
If you are inside of a domain class instead, you can still do this... but you will need to first inject a reference to grailsApplication. You probably want to do this in a Controller, though... more on this below.
If you're curious, the actual String returned here (for Oracle) is:
select rawtohex(sys_guid()) from dual
You can execute this SQL and fetch the generated ID value like this:
String guid = grailsApplication.getMainContext().sessionFactory.currentSession.createSQLQuery(guidSQL).list().get(0)
Issue #2: Actually using this value in a Grails domain object
To actually use this GUID value in your Grails domain class, you need to use the Hibernate generator "assigned". As mentioned earlier, this declares that you want to set your own ID's manually, rather than letting Grails/GORM/Hibernate generate them automatically. Compare this modified code snippet to the one in my original question above:
...
static mapping = {
table name: "OWNER"
version false
id column: "OWNER_OID", generator: "assigned"
name column: "NAME"
...
}
...
In my domain class, I changed "guid" to "assigned". I also found that I needed to eliminate the "columns {}" grouping block, and move all my column information up a level (weird).
Now, in whichever Controller is creating these domain objects... generate a GUID as described above, and plug it into the object's "id" field. In a Controller generated automatically by Grails Scaffolding, the function will be "save()":
def save() {
def ownerInstance = new Owner(params)
String guidSQL = grailsApplication.getMainContext().sessionFactory.getDialect().getSelectGUIDString()
ownerInstance.id = grailsApplication.getMainContext().sessionFactory.currentSession.createSQLQuery(guidSQL).list().get(0)
if (!ownerInstance.save(flush: true, insert: true)) {
render(view: "create", model: [ownerInstance: ownerInstance])
return
}
flash.message = message(code: 'default.created.message', args: [message(code: 'owner.label', default: 'Owner'), ownerInstance.id])
redirect(action: "show", id: ownerInstance.id)
}
You might think to try putting this logic directly inside the domain object, in a "beforeInsert()" function. That would definitely be cleaner and more elegant, but there are some known bugs with Grails that prevent ID's from being set in "beforeInsert()" properly. Sadly, you'll have to keep this logic at the Controller level.
Issue #3: Make Grails/GORM/Hibernate store this properly
The plain truth is that Grails is primarily intended for virgin-new applications, and its support for legacy databases is pretty spotty (in fairness, though, it's a bit less spotty than other "dynamic" frameworks I've tried). Even if you use the "assigned" generator, Grails sometimes gets confused when it goes to persist the domain object.
One such problem is that a ".save()" call sometimes tries to do an UPDATE when it should be doing an INSERT. Notice that in the Controller snippet above, I have added "insert: true" as a parameter to the ".save()" call. This tells Grails/GORM/Hibernate explicitly to attempt an INSERT operation rather than an UPDATE one.
All of the stars and planets must be in alignment for this to work right. If your domain class "static mapping {}" block does not set the Hibernate generator to "assigned", and also set "version false", then Grails/GORM/Hibernate will still get confused and try to issue an UPDATE rather than an INSERT.
If you are using auto-generated Grails Scaffolding controllers, then it is safe to use "insert: true" in the Controller's "save()" function, because that function in only called when saving a new object for the first time. When a user edits an existing object, the Controller's "update()" function is used instead. However, if you are doing your own thing in your own custom code somewhere... it will be important to check on whether a domain object is already in the the database before you make a ".save()" call, and only pass the "insert: true" parameter if it really is a first-time insert.
Issue #4: Using natural keys with Grails/GORM/Hibernate
One final note, not having to do with Oracle GUID values, but related to these Grails issues in general. Let's say that in a legacy database (such as the one I've been dealing with), some of your tables use a natural key as their primary key. Say you have an OWNER_TYPE table, containing all the possible "types" of OWNER, and the NAME column is both the human-readable identifier as well as the primary key.
You'll have to do a couple of other things to make this work with Grails Scaffolding. For one thing, the auto-generated Views do not show the ID field on the screen when users are creating new objects. You will have to insert some HTML to the relevant View to add a field for the ID. If you give the field a name of "id", then the auto-generated Controller's "save()" function will receive this value as "params.id".
Secondly, you have to make sure that the auto-generated Controller's "save()" function properly inserts the ID value. When first generated, a "save()" starts off by instantiating a domain object from the CGI parameters passed by the View:
def ownerTypeInstance = new OwnerType.get( params )
However, this does not handle the ID field you added to your View. You will still need to set that manually. If on the View you gave the HTML field a name of "id", then it will be available in "save()" as "params.id":
...
ownerTypeInstance = new OwnerType()
ownerTypeInstance.id = params.id
// Proceed to the ".save()" step, making sure to pass "insert: true"
...
Piece of cake, huh? Perhaps "Issue #5" is figuring out why you put yourself through all this pain, rather than just writing your CRUD interface by hand with Spring Web MVC (or even vanilla JSP's) in the first place! :)
Support for using SYS_GUID() is dependent upon the Oracle dialect that you are using. Looking at the hibernate source on GitHub it appears that the dialect was only setup to use the Oracle-generated guid in Oracle9Dialect.java and Oracle8iDialect.java. Therefore, it won't work with the 9i or 10g dialects.
You should submit a patch to hibernate which will add the required function(s) to enable the same functionality as the other dialects.

Can ADO.NET create its own basic validation by reflecting the database structure?

I am now to the stage of adding validation to a simple app for editing a few SQL tables via data-bound controls. I can see that the BindingSource knows the limits of the table's structure: if I enter, for example, letters in a field that should contain only decimals, up pops a DataError exception with the message that you can only enter decimals there.
It seems to me that ADO.NET should be able to use reflection to generate basic validation for all the data-bound fields. But after a lot of Googling, I see only people creating their own validation by column by column.
Can I use ADO.NET's knowledge of the database structure to have it make some of the basic validation for me (e.g. data type, text field length limits)? Do you have some examples?
I'm sad that I've never gotten a good response on this question... but I think I have my answer:
Yes, it should be possible, but no, it hasn't been done yet.
(Maybe someday I'll start a project myself to make a tool which would auto-generate basic validation values for data-bound form fields.)

Resources