Search code examples
exceptionplinqo

How to catch BrokenRuleException in PLINQO?


I’ve created a custom rule by adding the

 static partial void AddSharedRules()
 {
            RuleManager.AddShared<Tag>(
                new CustomRule<String>(
                    "TagName",
                    "Invalid Tag Name, must be between 1 and 50 characters",
                    IsNullEmptyOrLarge));
 }

to my Entity class.

I then added the rule (as seen on the video, although the video is dated and has wrong information):

public static bool IsNullEmptyOrLarge( string value )
    {
        return (value == null
            || String.IsNullOrEmpty(value)
            || value.Length > 50);
    }

But now I have the calling code…

try    
{    
    // some code
}
catch ( CodeSmith.Data.Rules… ??? )
{

// I can’t add the BrokenRuleException object. It’s not on the list.
}

I have: assign, security and Validation.

What’s the correct way to catch broken rule exceptions in PLINQO?


Solution

  • Here is what you need to do, first add a reference in your project to

    System.ComponentModel.DataAnnotations
    
    using CodeSmith.Data.Rules;
    

    Then

    try
    {
        context.SubmitChanges();
    }
    catch (BrokenRuleException ex)
    {
        foreach (BrokenRule rule in ex.BrokenRules)
        {
            Response.Write("<br/>" + rule.Message);
        }
    }
    

    If you want to change the default message then you can go to your entity and change the attribute from

    [Required]
    

    to

    [CodeSmith.Data.Audit.Audit]
    private class Metadata
    {
        // Only Attributes in the class will be preserved.
    
        public int NameId { get; set; }
    
        [Required(ErrorMessage="please please please add a firstname!")]
        public string FirstName { get; set; }
    

    You can also use these types of data annotation attributes

        [StringLength(10, ErrorMessage= "The name cannot exceed 10 characters long")]
        [Range(10, 1000, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
        [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "Characters are not allowed.")]
        public string FirstName { get; set; }
    

    HTH