Databases Reference
In-Depth Information
control on the web page. You also need to modify the HandleUniqueKeyConstraint
Violation method, as shown next, to take advantage of the new dictionary:
private static void HandleUniqueKeyConstraintViolation(SqlException error)
{
Match match = Regex.Match(error.Message,
“Violation of UNIQUE KEY constraint '(?<Constraint>.+?)'”,
RegexOptions.IgnoreCase);
string constraint = match.Groups[“Constraint”].Value;
ValidationResult validationResult;
if ( ConstraintErrors .TryGetValue(constraint, out validationResult))
ThrowValidationException(null, new [] { validationResult });
}
The new version the HandleUniqueKeyConstraintViolation method uses regular expres-
sions, namely the Regex class from the System.Text.RegularExpressions namespace, to
extract the constraint name from the error message. The regular expression pattern
includes a capture group called Constraint . Having extracted the name of the constraint
from the capture group, the code tries to lookup a ValidationResult object in the
ConstraintErrors dictionary and if the lookup was successful, calls the
ThrowValidationException method. As you might recall from Chapter 8, this method is
defined in the UnleashedObjectContext base class. It takes the entity object as its first
parameter, a list of ValidationResult objects, and throws an appropriate exception, either
a ValidationException or an AggregateException , depending on the number of valida-
tion results.
NOTE
Detailed discussion of regular expressions could take hundreds of pages. For addi-
tional information on this subject, please refer to the following resources:
.
http://msdn.microsoft.com/library/hs600312.aspx
.
Sams Teach Yourself Regular Expressions in 10 Minutes
Figure 9.10 shows the final version of the UNIQUE KEY error message displayed on the
Product insert page. Notice that a custom error message is now displayed at the top of the
page, and an asterisk indicates that Product Name is the field that caused the error.
 
Search WWH ::




Custom Search