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

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.)

Related

Is there a way to sort a content query by the value of a field programmatically?

I'm working on a portal based on Orchard CMS. We're using Orchard to manage the "normal" content of the site, as well as to model what's essentially data for a small application embedded in it.
We figured that doing it that way is "recommended" for working in Orchard, and that it would save us duplicating a bunch of effort in features that Orchard already provides, mainly generating a good enough admin UI. This is also why we're using fields wherever possible.
However, for said application, the client wants to be able to display the data in the regular UI in a garden-variety datagrid that can be filtered, sorted, and paged.
I first tried to implement this by cobbling together a page with a bunch of form elements for the filtering, above a projection with filters bound to query string parameters. However, I ran into the following issues with this approach:
Filters for numeric fields crash when the value is missing - as would be pretty common to indicate that the given field shouldn't be considered when filtering. (This I could achieve by changing the implementation in the Orchard source, which would however make upgrading trickier later. I'd prefer to keep anything I haven't written untouched.)
It seems the sort order can only be defined in the administration UI, it doesn't seem to support tokens to allow for the field to sort by to be changed when querying.
So I decided to dump that approach and switched to trying to do this with just MVC controllers that access data using IContentQuery. However, there I found out that:
I have no clue how, if at all, it's possible to sort the query based on field values.
Or, for that matter, how / if I can filter.
I did take a look at the code of Orchard.Projections, however, how it handles sorting is pretty inscrutable to me, and there doesn't seem to be a straightforward way to change the sort order for just one query either.
So, is there any way to achieve what I need here with the rest of the setup (which isn't little) unchanged, or am I in a trap here, and I'll have to move every single property I wish to use for sorting / filtering into a content part and code the admin UI myself? (Or do something ludicrous, like create one query for every sortable property and direction.)
EDIT: Another thought I had was having my custom content part duplicate the fields that are displayed in the datagrids into Hibernate-backed properties accessible to query code, and whenever the content item is updated, copy values from these fields into the properties before saving. However, again, I'm not sure if this is feasible, and how I would be able to modify a content item just before it's saved on update.
Right so I have actually done a similar thing here to you. I ended up going down both approaches, creating some custom filters for projections so I could manage filters on the frontend. It turned out pretty cool but in the end projections lacked the raw querying power I needed (I needed to filter and sort based on joins to aggregated tables which I think I decided I didn't know how I could do that in projections, or if its nature of query building would allow it). I then decided to move all my data into a record so I could query and filter it. This felt like the right way to go about it, since if I was building a UI to filter records it made sense those records should be defined in code. However, I was sorting on users where each site had different registration data associated to users and (I think the following is a terrible affliction many Orchard devs suffer from) I wanted to build a reusable, modular system so I wouldn't have to change anything, ever!
Didn't really work out quite like I hoped, but to eventually answer the question in your title: yes, you can query fields. Orchard projections builds an index that it uses for querying fields. You can access these in HQL, get the ids of the content items, then call getmany to get them all. I did this several years ago, and I cant remember much but I do remember having a distinctly unenjoyable time with it haha. So after you have an nhibernate session you can write your hql
select distinct civr.Id
from Orchard.ContentManagement.Records.ContentItemVersionRecord civr
join civ.ContentItemRecord cir
join ci.FieldIndexPartRecord fipr
join fipr.StringFieldIndexRecord sfir
This just shows you how to join to the field indexes. There are a few, for each different data type. This is the string one I'm joining here. They are all basically the same, with a PropertyName and value field. Hql allows you to add conditions to your join so we can use that to join with the relevant field index records. If you have a part called Group attached directly to your content type then it would be like this:
join fipr.StringFieldIndexRecord sfir
with sfir.PropertyName = 'MyContentType.Group.'
where sfir.Value = 'HR'
If your field is attached to a part, replace MyContentType with the name of your part. Hql is pretty awesome, can learn more here: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html But I dunno, it gave me a headache haha. At least HQL has documentation though, unlike Orchard's query layer. Also can always fall back to pure SQL when HQL wont do what you want, there is an option to write SQL queries from the NHibernate session.
Your other option is to index your content types with lucene (easy if you are using fields) then filter and search by that. I quite liked using that, although sometimes indexes are corrupted, or need to be rebuilt etc. So I've found it dangerous to rely on it for something that populates pages regularly.
And pretty much whatever you do, one query to filter and sort, then another query to getmany on the contentmanager to get the content items is what you should accept is the way to go. Good luck!
You can use indexing and the Orchard Search API for this. Sebastien demoed something similar to what you're trying to achieve at Orchard Harvest recently: https://www.youtube.com/watch?v=7v5qSR4g7E0

Handling Relational Data Input

When creating an MVC application with a "Create" view for a particular entity and I want to relate it to another entity I could use a dynamic drop down menu.
However when the possible items is larger than 10 (for example) the drop down does not seem to offer the best user experience.
What is the recommended way to handle the input of a relationship between entities? A textbox that validates against the possible entities?
A textbox that validates against the possible entities?
That is pretty much the answer. The general idea would be to have a controller method that takes a query string and checks against the list of valid entities and returns the entities that match the query. The user can then choose from that filtered list.
You don't have to build it from scratch if you don't want to. Take a look at something like https://github.com/twitter/typeahead.js. There is also https://select2.github.io. However, there are probably lots of choices for that type of control.

Implementing a reusable APEX form validation definition for multiple, similar page items

I am currently using APEX 4.0. I would like to make a validation that would apply for multiple fields in a form. For example, I want specific fields to only accept a Y or N, and they must be uppercase letters. As of now, I have one validation for each field. Is there a way to make a single validation that would apply to all these fields?
Creating Re-Usable Form Validations in Oracle Application Express (APEX)
This solution was developed on a Apex instance hosted on Oracle OTN (apex.oracle.com). This instance is currently at version 4.2.5, but the design elements discussed within this solution should still be compatible across the versions from 4.0.0 and 4.2.5.
The way you can approach your form design is not necessarily to catch exceptions through a validation step once the form has been completed and submitted.
Instead, simply consider limiting the choices that the user can choose in their input, and control how that input is interpreted once it is submitted as changes to your data table.
Pre-Validate By Defining Restrictive Value Choices
Here is an example of the OP requirement defined as a "Shared Component" through the "Application Builder" menu. Create a named LOV (list of values) with a static definition. Here, you can define the value pairs of:
DISPLAY, which is anything user friendly you want the user to see. Even if Y or N is pretty self-explanatory, explore other options such as spelling it out (such as: YES) or combining the real value with the display (such as: Y (Yes)).
RETURN VALUE, which is where you enforce what goes into your database. In this case, the uppercase, single character values mentioned in the OP requirements would go here.
This is what that LOV definition looks like:
APEX LOV (list of values) Design Screen
Eliminate Free-form Data Form Item Display Types
Following with the initial concept of a limiting LOV, convert all your form items to use display-types which use a "List of Values" definition pointing to your "Shared Component" (or Named LOV).
Use the SAME LOV definition for questions requiring the same input rules. Now the user has no way of changing the data values outside of the OP definition, and there is some flexibility to use more instructive/descriptive display values so that they are more likely to make the right selection as well.
This is an example of how a input form with the same input data types can accomplish this task with no additional validation:
Sample APEX Form Design with Reusable Input Restriction Rules
In this example, I experimented with a few form item styles, including
The standard text-box entry field. (Problematic without coupling it with additional validation logic).
Select-list entry items worked the best. See the discussion at the end of this solution for more explanation on choosing specifics such as specifying "null field values".
Radio group selection buttons work well to as they provide a visual layout of the valid form choices without additional drilling-down or scrolling.
All three options used the same LOV definition.
Examples of Data Input Using LOV Enforced Restrictions
After experimenting with different kinds of inputs, here's a few things that may be helpful depending on the situation or the deeper requirements of this OP or other readers.
DISPLAY EXTRA VALUES should be left as set to NO. This is the reason for restricting the input possibilities in the first place.
DISPLAY NULL VALUE is best as NO if all answers require a response. If NULL is possible, there is a useful third (defaulted) value that can be used for additional user-friendliness.
Sample Data Inputs and Values from the LOV Restricted Form
Notice that the free-text entry field presents additional problems with data quality without some other form of validation or checking. The other form fields provided accurate data input reflected through the target database table.
Some Closing Comments and Points for Further Study
This solution is only a partial one with respect to protecting information stored in a database table. It is not uncommon for lots of other systems, applications, programs, api's, etc. to also have access to change or add data to this back-end data source.
What if another group of developers independently created an api for managing data in the same table? Unless they read the documentation of the OP or examined existing data sets already present, their project team may not have designed an accurate interpretation of the rules which sit at this point, only on this particular APEX application.
Depending on how vulnerable your system is, it is also good practice to apply relevant safeguards, such as schema level table constraints (such as check constraints), Not Null constraints (where applicable) and even DEFAULT values settings (established by triggers or table default values).
From the Author...
Again, it isn't all necessary to go to this detail... if the input form of the Apex application offers only two choices: "SOUP" or "SALAD", it is unlikely that "BACON-ORANGE-CHICKEN" will pop up in the table after deploying the application into users' hands.
This kind of design approach skips a server round trip worth of I/O because the user already know what is on the menu at the initial page loading event.
Although the OP request is very simple and generic (Y for YES or N for NO), it presents a useful pattern for more complex input screening procedures that can happen even before the data is submitted.
Good Luck, All!
Onward.

Store translated versions in database for Joomla component

I'm currently developing my first MVC component for Joomla 3.x. All in all I'm bit struggling with language/translation issues in database.
My problem is that I need to store translated content of user generated content which comes from the backend. For example someone enters a new item in German (stored in database) and needs a translation in another language. How to accomplish that in Joomla? I don't like to generate a new item for every different language when the rest is all the same.
I thought about a table "item" and a table "item_language" with that structure (strongly simplified for viewing purposes):
item
id PRIMARY INT
price DOUBLE(4,2)
item_language
itemid PRIMARY INT
language PRIMARY CHAR(5)
name VARCHAR(50)
In item_language I would like to store the different translated versions. In the language field there would be the region code (eg. de-DE) to identify the language.
My problems:
How to display the different (translated) versions in backend?
Is this the right database model?
Any help is appreciated!
You have really found yourself a nice task for a first component in Joomla!
A rather generalist answer:
The database model seems right. Alternatively you could encode in JSON the language data, but this could make later query operations potentially difficult. This way you will only have one table to work with.
As far as I know (if you are using JModel / JTable to manipulate the data) can't do this directly, as JTable is really only designed to manipulate single tables.
What you can do:
For editing: figure a way to represent this graphically ( for your users to see and edit this one to many relationship) and to post this data (language texts as an array) to JModel. In the model you can maintain the desired relationships and save the data using JTable.
Viewing (without editing) shouldn't be an issue, it would be a simple JOIN.
If you are willing to create a basic component on github, I might even give you a hand with JModel / JTable.
I found a way to deal with the things I needed.
Thanks Valentin Despa for guiding me in the right direction :-).
Here the whole procedure (simplified - validations and exact steps omitted):
Define the form fields in the models/forms/site.xml as normal.
In views/site/tmpl/edit.php add self coded Javascript (based on jQuery) to deal with the fields which have content in multiple languages stored as JSON in database.
Clone the original form element and modify the needed attributes (id, name, ...) to display a special version just for the defined languages. As content - extract the JSON for the needed language from original field content and display.
Hide the original field with Javascript and append the customized versions to DOM.
Afterwards in tables/site.php I read the dynamically generated content withJInput and build together the original field by generating JSON and saving to database.
It's working like expected.

Validating checkboxes in a simple drupal form

I have added some check boxes in my drupal form. User can select either one option or two or all the three given there. Though am able to throw a validation error that at least one of the check boxes should be selected, am not able to validate if two or three are selected or not and the values are also not getting stored in the database provided.
How to do the validation so that whatever values are selected, its getting stored in the database?
Requesting help please.
Storing the values in the database isn't typically part of the validation handler, it's usually handled by a submit handler function. The specifics of how the data should be stored depends a lot on what the data is and how it's going to be used, so you'd need to provide some more details in order to get a more concrete answer there.
In general, I'd recommend checking out the Examples for Developers project, which provides lots of working code samples that demonstrate various aspects of Drupal development, including a form example.

Resources