in

CodeSmith Community

Your Code. Your Way. Faster!

Where to catch EntityNotValidException in ASP.NET projects?

Last post 05-02-2007 8:19 AM by velum. 11 replies.
Page 1 of 1 (12 items)
Sort Posts: Previous Next
  • 11-20-2006 11:11 PM

    • velum
    • Top 25 Contributor
    • Joined on 07-14-2006
    • Montréal, Qc, Canada
    • Posts 186
    • Points 4,686

    Where to catch EntityNotValidException in ASP.NET projects?

    Hi!

    I would like to know where exceptions should be caught in a web project. I added an e-mail address Validation Rule to an entity. Now, if I enter an invalid e-mail address, I'm getting an error page with the following on it:

    Unhandled Execution Error

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: Mammouth.Entities.EntityNotValidException:

    Source Error:

    Line 826:			
    Line 827: if (!entity.IsValid)
    Line 828: throw new Entities.EntityNotValidException(entity, "Update", entity.Error);
    Line 829:

    Line 830: TransactionManager transactionManager = null;

     Where should I catch the exception in order to display a nice error message box on the form that caused the error itself?

    Cheers!

    JF 

    • Post Points: 75
  • 11-21-2006 1:36 AM In reply to

    • Crimper
    • Top 25 Contributor
    • Joined on 03-03-2005
    • Vancounver, BC Canada
    • Posts 172
    • Points 3,045

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    Better to add proper control validation using a validator such as the RegularExpressionValidator.  You should not rely on the entity to throw an exception.  The EntityNotValidException being thrown should be the last chance preventing invalid data from being saved to your database.
    Phil Bolduc
    Vancouver, BC Canada
    -------------------------------------------------
    Former member of the .NetTiers team
    2007 MSDN Code Award - Team Developer Award winner

    -------------------------------------------------
    • Post Points: 35
  • 11-21-2006 8:38 AM In reply to

    • velum
    • Top 25 Contributor
    • Joined on 07-14-2006
    • Montréal, Qc, Canada
    • Posts 186
    • Points 4,686

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    Hi Phil!

    That is exactly what I am doing. However, I still want to be able to display the message in a nice format, should an error arise. So the question remains, where should I catch the exception in order to be able to display the message in a nice or custom format?

    Cheers!

    JF


     

    • Post Points: 35
  • 11-21-2006 1:29 PM In reply to

    • Crimper
    • Top 25 Contributor
    • Joined on 03-03-2005
    • Vancounver, BC Canada
    • Posts 172
    • Points 3,045

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    I'll assume this exception is being thrown from a provider's Update() method. I would recommend wrapping those types of calls in try/catch.  How specifically to handle it in your application depends how you have implmented it.  The simplest example is if you were calling the providers Update() method from within a button clicked event.  You would catch the EntityNotValidException and handle it appropriately. Note that you could get other types of exceptions such as SqlException due to database related problems (database timeout, database became unavilable, PK, FK or UK constriant errors).  The EntityNotValidException has a reference to the offending entity and a message.

    This comes down to basic exception handling.  Do you know where the exception is being thrown from? Is there offending code that could be fixed? Can you catch and recover from the exception?  Should you wrap the exception inside another exception type and rethrow? Should catch and swallow the exception?  Swallowing exceptions should used only for specifically designed sitiations and should be clearly documented in code why the exception is being swallowed.

    Here are a reference for you to read (non-NetTiers related):

    Framework Patterns: Exception Handling, Logging, and Tracing 

     

    Phil Bolduc
    Vancouver, BC Canada
    -------------------------------------------------
    Former member of the .NetTiers team
    2007 MSDN Code Award - Team Developer Award winner

    -------------------------------------------------
    • Post Points: 35
  • 11-21-2006 2:22 PM In reply to

    • Meech
    • Top 50 Contributor
    • Joined on 02-14-2006
    • Posts 98
    • Points 2,788

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    What I did is I whipped up a few custom methods in the FormUtil class that catches these and displays them within a control on my masterpage.

    If you use a gridView, you can catch them in the RowUpdated, RowDeleted, etc events.
    If you use a formView, you can catch them in the ItemUpdated, ItemInserted, etc events.
    Or you can just use the Deleted, Insrted, Updated events on the datasource.

    I prefer catching them in a gridView/formView -vs- the datasource directly so you can set the KeepInInsertMode/KeepInEditMode flags.  This way the data entered stays (errors and all) and a nice error message is displayed.

    Here is a sample one that I use for formview Updates:

    public static void handleUpdate(FormView formView, String redirecturl)

    {

    if (formView != null)

    {

    formView.ItemUpdated += new FormViewUpdatedEventHandler

    (

    delegate(object sender, FormViewUpdatedEventArgs e)

    {

    if (e.Exception != null)

    {

    logException(e.Exception);

    displayMasterError(e.Exception, formView.Page);

    e.ExceptionHandled = true;

    e.KeepInEditMode = true;

    }

    else

    {

    if (!String.IsNullOrEmpty(redirecturl))

    {

    string url = String.Format(redirecturl, ((formView.SelectedValue == null) ? null : formView.SelectedValue));

    HttpContext.Current.Response.Redirect(url);

    }

    }

    }

    );

    }

     

    }

     

    Anyhow I'm too lazy to tidy that up so it doesn't take so much freakin space.   Community server sure looks pretty but....  Anyhow I digress.

    logException is a custom method that calls the enterprise exception handler.
    displaymastererror is a custom method that finds the error control within the masterpage and stuffs the error message in it/toggles visibility.

    This will (optionally) automatically redirect after a successfull update.

    • Post Points: 65
  • 11-21-2006 3:16 PM In reply to

    • swin
    • Top 10 Contributor
    • Joined on 06-14-2006
    • London, UK
    • Posts 921
    • Points 34,675

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    Hi Meech,

    This is cool. What about submitting all of your methods to be added to the standard FormUtil?

    Cheers

    swin

    -------------------------------------------------
    Member of the .NetTiers team
    -------------------------------------------------
    • Post Points: 5
  • 11-21-2006 9:21 PM In reply to

    • velum
    • Top 25 Contributor
    • Joined on 07-14-2006
    • Montréal, Qc, Canada
    • Posts 186
    • Points 4,686

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    Hi!

    Thanks for all that input! As I can see, there is no single best practice method.

    Phil: Merci pour le lien! I'll have a look at the article. About my application: I'm not calling Update*( from within a button clicked event. I'm using buttons like these ones in VormViews:

    <asp:Button ID="SaveButton" runat="server" CausesValidation="True" CommandName="Update" Text="Sauvegarder"/>

    <asp:Button ID="CancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Annuler"/>

    Using the FormView DataSource and the button CommandName, the application automatically "knows" what to do with the entity.

    Yes, I know where the offending code comes from. I made this error occur on purpose. I added a Validator to my entity, and then I entered invalid data through the FormView in order to test the new validator. The error message is not the problem. My problem is more about what is the best practice to have these error messages appear within the application on a form that I designed. Right now, it is appearing on the standard ASP.NET error page.

    I will try Meech's solution, although it seems to be a lot of work to add all that code on every form. I was hopping ASP.NET 2.0 and .netTiers would have a simpler mechanisme for this (read with less code).

    Cheers!

    JF


     

     

    • Post Points: 35
  • 11-21-2006 10:15 PM In reply to

    • Meech
    • Top 50 Contributor
    • Joined on 02-14-2006
    • Posts 98
    • Points 2,788

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    I don't put that in every page, i put those in the FormUtil class.

    Then on every page, I put something like:

    protected void Page_Load(object sender, EventArgs e)
        {
            FormUtil.handleSelect(HotListsDataSource);
            FormUtil.handleUpdate(GridView1);
            FormUtil.handleInsert(FormView1);
            FormUtil.handleDelete(GridView1);
        }

    I've attached a text file that contains most of my Formutil extensions.  It has all the handlexxxx that I use and a few helper functions.  You'll have to modify it to work in your particular scenario (exceptionpolicy name, master page control namse, etc)...



     

    • Post Points: 65
  • 11-22-2006 2:08 AM In reply to

    • swin
    • Top 10 Contributor
    • Joined on 06-14-2006
    • London, UK
    • Posts 921
    • Points 34,675

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    Hi Meech,

    Thanks for this!

    Cheers

    swin

    -------------------------------------------------
    Member of the .NetTiers team
    -------------------------------------------------
    • Post Points: 5
  • 11-22-2006 10:11 PM In reply to

    • velum
    • Top 25 Contributor
    • Joined on 07-14-2006
    • Montréal, Qc, Canada
    • Posts 186
    • Points 4,686

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    Hi Meech!

    I added your code to my project and it is working beautifully. Delegates are new to me, but they seem to simplify the task quite a bit. Your solution requires less code than I thought initially.

    Cheers!

    JF

    P.S. To display error messages, I used the ASP.NET Pop-up Control presented here: http://www.codeproject.com/aspnet/asppopup.asp. I find it quite interesting. 

    • Post Points: 5
  • 05-02-2007 12:51 AM In reply to

    • rduque
    • Top 75 Contributor
    • Joined on 03-08-2007
    • Bogotá, Colombia
    • Posts 61
    • Points 1,650

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    How do I must configure the entlib.config to use this method?

    postHandlingAction="NotifyRethrow" ??? "None"? "ThrowNewException" ??

     Thanks,

    RAUL DUQUE
    Bogotá, Colombia

    RAUL DUQUE
    Bogotá, Colombia
    • Post Points: 35
  • 05-02-2007 8:19 AM In reply to

    • velum
    • Top 25 Contributor
    • Joined on 07-14-2006
    • Montréal, Qc, Canada
    • Posts 186
    • Points 4,686

    Re: Where to catch EntityNotValidException in ASP.NET projects?

    Hola Raul!

    On my project, I'm using postHandlingAction="NotifyRethrow".

    Here is the whole section from my entlib.config:

     

        <exceptionHandling>

            <exceptionPolicies>

                <add name="NoneExceptionPolicy">

                    <exceptionTypes>

                        <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

                            postHandlingAction="NotifyRethrow" name="Exception">

                            <exceptionHandlers>

                                <add logCategory="Exceptions" eventId="100" severity="Error"

                                    title="Mammouth Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.XmlExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"

                                    priority="0" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"

                                    name="Logging Handler" />

                            </exceptionHandlers>

                        </add>

                    </exceptionTypes>

                </add>

            </exceptionPolicies>

        </exceptionHandling>

    I hope this helps!

    JF
     

    Filed under:
    • Post Points: 5
Page 1 of 1 (12 items)
Copyright © 2008 CodeSmith Tools, LLC
Powered by Community Server (Commercial Edition), by Telligent Systems