Catching broken database contraints in C# - Best Practice - c#

Say I have an SQL table that has a unique key (or other) constraint on one of the columns.
Then, I have an application (lets go ASP.NET MVC) that allows a user to edit this column.
When the user attempts to save, and the constraint is/will be broken, I need show a user-friendly error message to the user. As such, which of the following is better practice?
Have the application query the database to ensure the constraints are not broken, and then insert/update the row (results in two queries to the db)
OR
Immediately attempt to perform the insert/update, and catch the SqlException should the constraint be broken. I like this, because of only one trip to the db, however how should you then extract which index/constraint was broken and affix the appropriate message? (apart from inspecting Exception.Message?)

1 is the better all-around solution. Db calls are not the only expensive operation, exceptions are costly too. You should really only let your db throw an exception when something goes wrong due to your code, not a user action.
For example, you might later want to install Elmah and get exceptions logged and/or mailed to you. Elmah would log/mail such an exception unless you explicitly told it not to.
Plus like you said, exceptions don't always have the most businessy information to communicate to users (especially SQL exceptions, which are SQL-specific). You have these unique and other constraints for a reason. For those reasons, validate the information before trying to store it.
Take twitter, gmail, etc. When you go to get a username, the application first checks to see if it is taken. These are uniqueness constraints at the application level, which may or may not ultimately be realized as SQL constraints. Since it is your application that faces the user, you should not try to communicate to them by translating from SQL to English.

The problem with option 1 is that it requires the application to have separate distinct knowledge of what the constraints are, which conflicts with a DRY principle, and could lead to problems later when the database constraint gets changed, and the application is not updated - a tight coupling between the data logic, and the application. Also, there is no guarantee of the constraint checks that were performed are still valid at the subsequent pont when you then attempt the update.
This doesn't preclude augmenting your application with some UI layer validation to aid the user before the commit is attempted.
So if that is discarded we are left with option 2, and some translation is necessary somewhere in the application. Where you put that translation and that logic, whether in a Stored Procedurce or a Business Logic layer, is up to you.

Related

Abstraction of SqlExceptions (using Entity Framework)

I have been using Entity Framework 6 and trying to handle some common problems like Primary/Foreign/Unique Key constraints via EF. EF gives SqlException as an InnerException and it seems that - as far as I found upto now - the only way to understand the actual problem is using error codes in that SqlException object?
I would like to abstract these exceptions by catching EF exceptions and throwing my own exceptions by analyzing the error code in the InnerException. I have some considerations at that point.
SQL Server codes change by the server version or not? Should I handle
different versions of SQL Server in a different way like creating different implementations for 2008, 2012 and etc?
Instead of SQL Server it is possible to use other SQL Servers like
MySQL and its another reason I am trying to abstract these
exceptions.
For example, as in the accepted answer of that question, I would like catch specific errors, but instead of rethrowing I would like to throw my own exception(s). If I do not want to do something special or I do not have any special exception for the error I can create and use a more generic exception in which I can store the original exception into that generic exceptions InnerException field.
I read this blog post and unfortunately the problematic case was my first way to go. I would like to do that without using any third party library as much as possible (of course this is not more important doing it right). I wonder if there is tested and accepted way of doing this, otherwise I am open to any suggestion.
SQL Server codes change by the server version or not?
Exception numbers cannot change once released. Deadlock is and will remain 1205, unique index duplicate key is and will remain 2601, unique constraint violation is and will remain 2627 and so on and so forth. But, you see, in the very examples I choose I show you the danger lurking in relying on these: what decides the difference between 2601 and 2627? Your friendly DBA can decide that it should drop an unique index and instead add an unique constraint (enforce by an index, but that is irrelevant) and all of the sudden your app sees new errors. By doing deep inspection of the exception you add coupling between the application code and the SQL storage, and risk breaking the app when the storage modifies in what would otherwise be a completely transparent change (eg. add an index). Be warned.
I think is feasible to add handling for several well known cases. But you must allow for generic exception you are not aware of ad development time, and handle those.
As for cross-platform, you would have to customize for each platform. The good news is that a 'primary key violation' is the same concept on SQL Server and on MySQL, so you could translate it to a PrimaryKeyViolationException for both providers. Is not trivial, but it is possible.
And finally, a heads up: I've seen folk trying to do similar before, to mix results. The benefits are not exactly overwhelming, and the effort put in is considerable.

Spreading of business logic between DB and client

Ok guys, another my question is seems to be very widely asked and generic. For instance, I have some accounts table in my db, let say it would be accounts table. On client (desktop winforms app) I have appropriate functionality to add new account. Let say in UI it's a couple of textboxes and one button.
Another one requirement is account uniqueness. So I can't add two same accounts. My question is should I check this account existence on client (making some query and looking at result) or make a stored procedure for adding new account and check account existence there. As it for me, it's better to make just a stored proc, there I can make any needed checks and after all checks add new account. But there is pros and cons of that way. For example, it will be very difficult to manage languagw of messages that stored proc should produce.
POST EDIT
I already have any database constraints, etc. The issue is how to process situation there user is being add an existence account.
POST EDIT 2
The account uniqueness is exposed as just a simple tiny example of business logic. My question is more abour handling complicated business logic on that accounts domain.
So, how can I manage this misunderstanding?
I belive that my question is basic and has proven solution. My tools are C#, .NET Framework 2.0. Thanks in advance, guys!
If the application is to be multi-user ( i.e. not just a single desktop app with a single user, but a centralised DB with the app acting as clients maybe on many workstations), then it is not safe to rely on the client (app) to check for such as uniqueness, existance, free numbers etc as there is a distinct possibility of change happening between calls (unless read locking is used, but this often become more of an issue than a help!).
There is the ability of course to precheck and then recheck (pre at app level, re at DB), but of course this would give extra DB traffic, so depends on whether it is a problem for you.
When I write SPROCs that will return to an app, I always use the same framework - I include parameters for a return code and message and always populate them. Then I can use standard routines to call them and even add in the parameters automatically. I can then either display the message directly on failure, or use the return code to localize it as required (or automate a response). I know some DBs (like SQL Svr) will return Return_Code parameters, but I impliment my own so I can leave inbuilt ones for serious system based errors and unexpected failures. Also allows me to have my own numbering systems for return codes (i.e. grouping them to match Enums in the code and/or grouping by severity)
On web apps I have also used a different concept at times. For example, sometimes a request is made for a new account but multiple pages are required (profile for example). Here I often use a header table that generates a hidden user ID against the requested unique username, a timestamp and someway of recognising them (IP Address etc). If after x hours it is not used, the header table deletes the row freeing up the number (depending on DB the number may never become useable again - this doesn;t really matter as it is just used to keep the user data unique until application is submitted) and the username. If completed correctly, then the records are simply copied across to the proper active tables.
//Edit - To Add:
Good point. But account uniqueness is just a very tiny simple sample.
What about more complex requirements for accounts in business logic?
For example, if I implement in just in client code (in winforms app) I
will go ok, but if I want another (say console version of my app or a
website) kind of my app work with this accounts I should do all this
logic again in new app! So, I'm looking some method to hold data right
from two sides (server db site and client side). – kseen yesterday
If the requirement is ever for mutiuse, then it is best to separate it. Putting it into a separate Class Library Project allows the DLL to be used by your WinForm, Console program, Service, etc. Although I would still prefer rock-face validation (DB level) as it is closest point in time to any action and least likely to be gazzumped.
The usual way is to separate into three projects. A display layer [DL] (your winform project/console/Service/etc) and Business Application Layer [BAL] (which holds all the business rules and calls to the DAL - it knows nothing about the diplay medium nor about the database thechnology) and finally the Data Access Layer [DAL] (this has all the database calls - this can be very basic with a method for insert/update/select/delete at SQL and SPROC level and maybe some classes for passing data back and forth). The DL references only the BAL which references the DAL. The DAL can be swapped for each technology (say change from SQL Server to MySQL) without affecting the rest of the application and business rules can be changed and set in the BAL with no affect to the DAL (DL may be affected if new methods are added or display requirement change due to data change etc). This framework can then be used again and again across all your apps and is easy to make quite drastic changes to (like DB topology).
This type of logic is usually kept in code for easier maintenance (which includes testing). However, if this is just a personal throwaway application, do what is most simple for you. If it's something that is going to grow, it's better to put things practices in place now, to ease maintenance/change later.
I'd have a AccountsRepository class (for example) with a AddAcount method that did the insert/called the stored procedure. Using database constraints (as HaLaBi mentioned), it would fail on trying to insert a duplicate. You would then determine how to handle this issue (passing a message back to the ui that it couldn't add) in the code. This would allow you to put tests around all of this. The only change you made in the db is to add the constraint.
Just my 2 cents on a Thrusday morning (before my cup of green tea). :)
i think the answer - like many - is 'it depends'
for sure it is a good thing to push logic as deeply as possible towards the database. This prevent bad data no matter how the user tries to get it in there.
this, in simple terms, results in applications that TRY - FAIL - RECOVER when attempting an invalid transaction. you need to check each call(stored proc, or triggered insert etc) and IF something bad happens, recover from that condition. Usually something like tell the user an issue occurred, reset the form or something, and let them try again.
i think at a minimum, this needs to happen.
but, in addition, to make a really nice experience for the user, the app should also preemptively check on certain data conditions ahead of time, and simply prevent the user from making bad inserts in the first place.
this is of course harder, and sometimes means double coding of business rules (one in the app, and one in the DB constraints) but it can make for a dramatically better user experience.
The solution is more of being methodical than technical:
Implement - "Defensive Programming" & "Design by Contract"
If the chances of a business-rule being changed over time is very less, then apply the constraint at database-level
Create a "validation or rules & aggregation layer (or class)" that will manage such conditions/constraints for entity and/or specific property
A much smarter way to do this would be to make a user-control for the entity and/or specific property (in your case the "Account-Code"), which would internally use the "validation or rules & aggregation layer (or class)"
This will allow you to ensure a "systematic-way-of-development" or a more "scalable & maintainable" application-architecture
If your application is a website then along with placing the validation on the client-side it is always better to have validation even in the business-layer or C# code as well
When ever a validation would fail you could implement & use a "custom-error-message" library, to ensure message-content is standard across the application
If the errors are raised from database itself (i.e., from stored-procedures), you could use the same "custom-error-message" class for converting the SQL Exception to the fixed or standardized message format
I know that this is all a bit too much, but is will always good for future.
Hope this helps.
As you should not depend on a specific Storage Provider (DB [mysql, mssql, ...], flat file, xml, binary, cloud, ...) in a professional project all constraint should be checked in the business logic (model).
The model shouldn't have to know anything about the storage provider.
Uncle Bob said something about architecture and databases: http://blog.8thlight.com/uncle-bob/2011/11/22/Clean-Architecture.html

Software Design - Three-tier architecture

Layer 3 - Interface
Layer 2 - Business logic (get input from user, check if valid, send to database function)
Layer 1 - Database (creates, updates, gets records etc)
A user can add many contact phone numbers, if it is the first phone number added the system will automatically set that phone number to primary, and there after the user can change his primary phone number on his own.
When the first phone number record is created in the database, which layer is responsible to check if the phone number needs to be set to primary or not?
Business layer. The database should be storing data, not making decisions. The interface just interacts with the user. The business layer makes the rules.
Your business logic should handle it when the phone number gets added to the user. You can verify it works by providing unit/integration tests for it.
I guess it depends what you're aiming for. As it is your business layer should handle phone being validated/set as primary. Database would still need to store that information in some way I think.
However in certain cases like security verification you'll need to do some checks at Interface, Logic and Database level. Yes it is redundant but I think you'll want to guarantee that hackers that break your interface or logic, can't go around messing with your underlying data.
The data layer in an N-tier application isn't really supposed to do anything other than to put values in and get values in. Think of it as an persistence service.
Everything else goes into what's known as the business and/or logic layer except for UI code (you're supposed to keep those things separate in following something like MVP, MVC or MVVM).
Though this simple problem actually raises a issue with transactions, your data model should eventually prevent this, but if you cannot complete the operation as an atomic unit there always the chance that two phone numbers are put at the same time and they both end up as primary (depending on the latency between the application and database). To gracefully handling these situations you need at least think about error recovery (error handling) that propagates these problems in a meaningful manner. Don't just crash your application.
Just to add to the above answers, you might want to consider persisting input regardless of validity. Can add a bit more development (especially if you need to clean the data) but it can be worth it depending on your application

Recommended approach on handling SqlExceptions in db applications

I work on a database application written in C# with sql server as backend. And for data integrity, I try to enforce as much as possible on database level - relations, check constraints, triggers.
Due to them, if data is not consistent, the save / update / insert can fail, and app throw SqlException.
I do various validations both in UI (to present user with meaningful info if data entered is not valid), also in BL, which reports errors back to UI which presents it to user.
However, there are things that really cannot be checked in the app, and are handled by the db: I mean errors on delete when no cascade delete and user try to delete a entity from a master table, etc.
E.g. Employees table acts as master in lot of relations - manager of employee, manager of department, cashier, team leader, teams members etc, etc. If I add anew employee which is not involved in any relation I can delete it, but of user try to delete one that is master oin such relation, the delete fails (as it should) due to RI rules enforced at DB level, and that's ok.
I write delete code in a try ... catch and handle the exception, telling user he cannot delete that employee. But I want to give user more meaningful info - the reason the record cannot be deleted. Maybe it was just a test employee record, which was also added to a test team. But user forget where added that and if I could tell "Cannot delete employee because it is part of team T1", user will know to go first to Team T1, remove user then try to delete it again. That's a simple example, since as I said an employee can be involved in lot of relations - in my app I have at least 20.
The solution is to display the Message reported by SqlException, but that's not elegant at all. First, that msg is very technical - it talks about FK, PK, Triggers, which are meaningless for users and will scare them. Second my app is uses multi-lang UI and all menus and msgs are shown in user selected language (selected either at login time or in user profile). And the msg from SqlException is english (if I use english version) or worst, less common languages, like german or dutch, if it happens that sql server is in that language.
Is there any common or recommended approach to extract meaningful info from sql exception to be able to present user a meaningful msg (e.g. what relation or child table caused the failure, or what trigger, etc). but something I can test in program in a lang-independent fashion and then format my own error msg in a user-friendly way?
How do you handle this situation?
Thanks for all answers
(PS: Sorry for the long post)
Unfortunately, there isn't an easy answer here.
The amount of work involved will depend on the consistency of your error messages coming from your business layer. You are going to need to do some form of translation from the "technical" error message to your user oriented message.
This should be a matter of making some forms of lookups from your error messages to a resource key, which can be used to pull out your language-specific error message. However, if you need to parse the messages for more information (ie: table names, etc), then it gets a bit trickier. In that case, you'll probably need to have something that maps an error message to a regex/processor of some form as well as a new resource string. Then you could format the user's string with the information you extract from the original error, and present it to the user.
Well, from the database, you'll only ever get these technical messages, e.g. "violation of foreign key relation FK_something_to_another" or such.
Typically, in the SqlException, you also get a SQL error code or something else.
The best approach would probably be to have a separate table in your database which basically maps those technical SQL errors that can happen to more meaningful, user-oriented messages. E.g. if your SQL error says something like "fk violation blablabaal", you could have an entry in your "UserErrorTable" which maps this to a user message saying "could not delete user (this.and.that), most likely because ..... (he's still member of a team)" or whatever.
You could then try to catch those SqlExceptions in your business layer, translate those technical infos into a custom exception for your users, put in a user-friendly message, and stick the technical exception into the .InnerException of your custom exception type:
public class UserFriendlyException : Exception
{
public string UserErrorMessage { get; set; }
public UserFriendlyException(string message, SqlException exc) : base(message, exc)
{
UserErrorMessage = MapTechnicalExecptionToUserMessage(exc);
}
}
Marc
The short answer is "don't." Let the errors bubble out to the global error handling/logging. The validation and business rules should generally preclude database exceptions, so you are better off failing hard and fast and not submitting dirty data. Transactions help too.
Error Messages do not equate Exceptions. An error message is something that the user should find informative and most important actionable. There are some guidelines around error messages in the User Experience Guidelines I recommend you read up. Apple also has good generic guidelines in Writing Good Alert Messages.
You'll immediately notice that most, if not all, of SQL errors are not good end user messages. 'Constraint FKXF#455 violation' - Bad error for end user. 'Filegroup is full' - Bad error for end user. 'Deadlock' - same. What good applications do is they separate the roles of users. Administrators need to see these errors, not end users. So the application always logs the full SQL error with all the details, eventually notifies the administrator, and then display a different error to the user, something like 'A system error occurred, the administrator was notified'.
If the SQL error can is actionable by the end user, then you can display him an error message instruct him what to do to fix the problem (eg. change the invoice date in the input to satisfy a constraint). But even in this case most times you should not display the SQL error straight to the user ( you already seen a very good reason why not: localization). I understand that this creates a much bigger workload for your development team. You must know what errors are user actionable in each case, from the multitude of errors you may catch. That is well known, and that's exactly why good program managers know that about 80% of the code is handling the error cases, and why the application being 'done' usually means is 20% done. This is what differentiates great apps from ordinary ones: how they behave when things go wrong.
My suggestion is to start up with the principle of progressive disclosure. Display an generic error message stating 'the operation has failed'. Offer to display more details if the user presses a 'Show details...' button on the error message dialog, and display the SqlError collection (btw, you should always log and display the entire SqlError collection of SqlException.Errors, not the SqlException). Use the SqlError.Number property to add logic in the catch block that decides if the user can do anything about the error (decide if the error is actionable) and add appropriate information.
Unfortunately there is no pixie dust. You are touching the foot hils of what is probably the most difficult part of your project.
The way to do this is to write a stored procedure, and use TRY and CATCH. Use RAISERROR to raise your own custom messages, and check the error code in the SqlException.
We usually write some sort of translator in our projects.We compare the SQL exception message with some predefine patterns and show the equivalent message to user
About generic technical > userfriendly errors i can only support the answers already giving.
But to your specific example with the employer i must encourage you to not rely only on the SqlException. Before trying to delete the Employee you should make some check to see if he/she is a part of any teams, is manager etc. It will tremendiosuly improve the usability of your application.
Pseudo:
Employee e;
try {
IEnumerable<Team> teams = Team.GetTeamsByEmployee(e);
if (teams.Count() > 0) {
throw new Exception("Employee is a part of team "+ String.Join(",", teams.Select(o => o.Name).ToArray());
}
IEnumerable<Employee> managingEmployees = Employee.GetEmployeesImManaging(e);
if (managingEmployees.Count() > 0) {
throw new Exception("Employee is manager for the following employees "+ String.Join(",", managingEmployees.Select(o => o.Name).ToArray());
}
Employee.Delete(e);
} catch (Exception e) {
// write out e
}
Errors happen. When it doesn't particularly matter what kind or type of error you hit, or how you handle it, slapping your code in a TRY...CATCH... block and write a generic error reporting system is fine. When you want (or are required to) write something better than that, it can take serious effort, as outlined in some prior posts (which I too have upvoted).
I tend to classify errors as anticipatable or unanticipatable. If you can anticipate an error and you want to handle it with a clear an consice message, such as with your "delete employee" situation, you will have to plan and code accordingly. By their definition, you cannot do this for unanticipatable errors--that's usually where TRY/CATCH comes in.
For your situation, one way could be before deleting the row, check via queries against the child tables whether or not the delete could succeed. If it won't, you'll know precisely why (and for all child tables, not just the first one that would block the delete), and can present the user with a clear message. Alas, you must consider whether the data can change between the check and the actual delete -- perhaps not a problem here, but it could be in other situations.
An alternative based on the TRY...CATCH... would be to check the error number within the catch block. If it's a "can't delete due to foreign key", you could then query the children tables and generate the message, and if it was some other unanticipated error, you'd have to fall back on a generic message.
(A caveat: some times when it hits an error, SQL will raise two error messages in a row [is the FK constraint violation one of them?] and in these situations the various ERROR() functions will only return data for the second and invariably less useful message. This is incredibly aggravating, but there's not too much you can do about it.)
In summary I would caution against relying on SQL exceptions and errors. For me, if we rely on such errors we are storing up trouble. Such error messsages are normally not user readable. In addition UI developers may say "oh well, it will be caught by the database guys, I do not need to validate that". Totally incorrect!
Perhaps a better approach would be to ensure that validation prevents these issues in the first place. e.g. If you cannot delete object A because it is referenced by object B, then we should implement some kind of dependency service at a level higher than the database. It depends what kind of application it is.
Another example would be string length validation. Do we really want to rely on the database validation for checking string length of fields entered by the user. Of course, this is an extreme case!
Normally, if the database layer is throwing an exception it can be a sign of a bug elsewhere. With a client/server setup we can assert that validation is the responsibility of both. If it makes it to the database then normally it is too late.
You may want to use RAISEERROR so the calling code can be fed with an exception from a stored procedure. From that you can provide a sensible error message.
There is never a one size fits all approach. My motto here would be prevention is better than cure! Validate earlier rather than later.

Persistent Layer Validations

While saving data using a stored procedure often we encounter foreign key constraints, unique key constraints, etc. All such errors can be corrected by passing in the right data.
Validation can be done in the business logic layer and should be sent to the persistence layer only if it succeeds. But in some cases it is convenient to validate data while saving. Like in a stored procedure.
Say for example if the user enters some date range values it should be validated that the range do not overlap any existing ranges. In such situation it is better to return some error code which can tell us if the range is overlapping and cannot be saved.
In SQL Server we can simply raise custom exceptions but I want to do it without using exceptions. Is there any validation frameworks already available which I can use.
I am looking for a SQL Server 2005 and .net specific solution.
P.S.: I generally return custom error codes from the Stored Procs and then parse them by looking up in an xml file and then use it in my Business Layer rules engine.
Embedding business logic in the SQL Server might improve the performance but it's going to complicate the design by violating seperation of concerns. In order for me to have portable business logic, it should be in the business layer. I would remove the validation logic from the stored procs and only use them to make CRUD operations easier. You never know when the project stakeholders are going to say "make it run on Database X!". Do your best to keep the validation logic database independent.

Categories

Resources