views:

220

answers:

9

I have the following code in my application:

using (var database = new Database()) {
    var poll = // Some database query code.

    foreach (Question question in poll.Questions) {
        foreach (Answer answer in question.Answers) {
            database.Remove(answer);
        }

        // This is a sample line  that simulate an error.
        throw new Exception("deu pau"); 

        database.Remove(question);
    }

    database.Remove(poll);
}

This code triggers the Database class Dispose() method as usual, and this method automatically commits the transaction to the database, but this leaves my database in an inconsistent state as the answers are erased but the question and the poll are not.

There is any way that I can detect in the Dispose() method that it being called because of an exception instead of regular end of the closing block, so I can automate the rollback?

I don´t want to manually add a try ... catch block, my objective is to use the using block as a logical safe transaction manager, so it commits to the database if the execution was clean or rollbacks if any exception occured.

Do you have some thoughts on that?

A: 

You could inherit from the Database class and then override the Dispose() method (making sure to close the db resources), this could then raise a custom event to which you can subscribe in your code.

David Neale
Why would Dispose be virtual?
Steven Sudit
+1  A: 

I could be reading this wrong, but I would decouple the transaction commitment from the disposal of the object. Dispose should be cleaning up your resources, not doing a major operation such as persisting changes to your database. Commit (or rollback), then dispose.

Anthony Pegram
This is rather a comment than an answer, don't you think ?:)
Oskar Kjellin
The idea of dispose is to clean things up, so it does make sense to have it roll back. Having said that, I think an explicit commit is the right way to go.
Steven Sudit
+1  A: 

Sound like you need TransactionScope http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx

Oskar Kjellin
+1  A: 

You should wrap the contents of your using block in a try/catch and roll back the transaction in the catch block:

using (var database = new Database()) try
{
    var poll = // Some database query code.

    foreach (Question question in poll.Questions) {
        foreach (Answer answer in question.Answers) {
            database.Remove(answer);
        }

        // This is a sample line  that simulate an error.
        throw new Exception("deu pau"); 

        database.Remove(question);
    }

    database.Remove(poll);
}
catch( /*...Expected exception type here */ )
{
    database.Rollback();
}
Joel Coehoorn
I don´t want to, I want to use "using" as a helper for that operation, with addiction of other boilerplate that I have to make.
Augusto Radtke
@Augusto - rollback works well with "using". See my updated answer
Joel Coehoorn
Using is simply a shortcut syntax for try{} finally{ o.Dispose() }Replacing the using with a single try{} catch{ rollback } finally{ dispose } is the correct thing to do.
chilltemp
I tried to explain in my answer why a class design without an explicit `Complete` or `Commit` method is possible: http://stackoverflow.com/questions/2830073/detecting-a-dispose-from-an-exception-inside-using-block/2830501#2830501
Steven
+5  A: 

Look at the design for TransactionScope in System.Transactions. Their method requires you to call Complete() on the transaction scope to commit the transaction. I would consider designing your Database class to follow the same pattern:

using (var db = new Database()) 
{
   ... // Do some work
   db.Commit();
}

You might want to introduce the concept of transactions outside of your Database object though. What happens if consumers want to use your class and do not want to use transactions and have everything auto commit?

Eric Hauser
+1  A: 

As Anthony points out above, the problem is a fault in your use of the using clause in this scenario. The IDisposable paradigm is meant to ensure that an object's resources are cleaned up regardless of the outcome of a scenario (thus why an exception, return, or other event that leaves the using block still triggers the Dispose method). But you've repurposed it to mean something different, to commit the transaction.

My suggestion would be as others have stated and use the same paradigm as TransactionScope. The developer should have to explicitly call a Commit or similar method at the end of the transaction (before the using block closes) to explicitly say that the transaction is good and ready to be committed. Thus, if an exception causes execution to leave the using block, the Dispose method in this case can do a Rollback instead. This still fits in the paradigm, since doing a Rollback would be a way of "cleaning up" the Database object so that it is not left an invalid state.

This shift in design would also make it much easier to do what you want to do, since you won't be fighting the design of .NET to try and "detect" an exception.

Heather McLean
+1  A: 

All others already wrote what the correct design of your Database class should be, so I won't repeat that. However, I didn't see any explanation why what you want to is not possible. So here it goes.

What you want to do is detect, during the call to Dispose, that this method is called in the context of an exception. When you would be able to do this, developers won't have to call Commit explicitly. However, the problem here is that there is no way to reliable detect this in .NET. While there are mechanisms to query the last thrown error (like HttpServerUtility.GetLastError), these mechanisms are host specific (so ASP.NET has an other mechanism as a windows forms for instance). And while you could write an implementation for a specific host implementation, for instance an implementation that would only work under ASP.NET, there is another more important problem: what if your Database class is used, or created within the context of an exception? Here is an example:

try
{
    // do something that might fail
}
catch (Exception ex)
{
    using (var database = new Database())
    {
        // Log the exception to the database
        database.Add(ex);
    } 
}

When your Database class is used in the context of an Exception, as in the example above, how is your Dispose method supposed to know that it still must commit? I can think of ways to go around this, but it will quite fragile and error prone. To give an example.

During creation of the Database, you could check whether it is called in the context of an exception, and if that’s the case, store that exception. During the time Dispose is called, you check whether the last thrown exception differs from the cached exception. If it differs, you should rollback. If not, commit.

While this seems a nice solution, what about this code example?

var logger = new Database();
try
{
    // do something that might fail
}
catch (Exception ex)
{
    logger.Add(ex);
    logger.Dispose();
}

In the example you see that a Database instance is created before the try block. Therefore is can not correctly detect that it sould not roll back. While this might be a contrived example, it shows the difficulties you will face when trying to design your class in a way no explicit call to Commit is needed.

In the end you will be making your Database class hard to design, hard to maintain, and you'll never really get it right.

As all others already said, a design that needs an explicit Commit or Complete call, would be easier to implement, easier to get right, easier to maintain, and gives usage code that is more readable (for instance, because it looks what developers expect).

Last note, if you're worried about developers forgetting to call this Commit method: you can do some checking in the Dispose method to see whether it is called without Commit is called and write to the console or set a breakpoint while debugging. Coding such a solution would still be much easier than trying to get rid of the Commit at all.

Update: Adrian wrote an intersting alternative to using HttpServerUtility.GetLastError. As Adrian notes, you can use Marshal.GetExceptionPointers() which is a generic way that would work on most hosts. Please note that this solution has the same drawbacks explained above and that calling the Marshal class is only possible in full trust

Steven
How do you detect the exception in a call to `.Dispose()`?
Lasse V. Karlsen
@Lasse: As you can read in my answer, one possibility is by calling HttpServerUtility.GetLastError when your code is running in the ASP.NET host.
Steven
+1 for "What if you want to write to the database in the case of an exception"
ck
+3  A: 

As others have said, your use of the Disposable pattern for this purpose is what is causing you the problems. If the pattern is working against you, then I would change the pattern. By making a commit the default behaviour of the using block, you are assuming that every use of a database results in a commit, which clearly is not the case - especially if an error occurs. An explicit commit, possibly combined with a try/catch block would work better.

However, if you really want to keep your use of the pattern as is, you can use:

bool isInException = Marshal.GetExceptionPointers() != IntPtr.Zero
                        || Marshal.GetExceptionCode() != 0;

in your Displose implementation to determine if an exception has been thrown (more details here).

adrianbanks
Adrian, you got it, I don´t want coaching about pattern usages, just a technical solution, it worked beautifully.
Augusto Radtke
@Adrian: Please take a look at my answer. I try to explain why checking for exceptions inside a `Dispose` method is a bad idea.
Steven
@Steven: As most of the answers (including yours) have agreed, this is not a wise pattern to use. Even so, the original question asked whether it is *possible* to know whether an exception has been thrown when in a `Dispose` method, which is what my answer shows - even if it does have associated problems.
adrianbanks
+1  A: 

In short: I think that's impossible, BUT

What you can do is to set a flag on your Database class with default value "false" (it's not good to go) and on the last line inside using block you call a method that sets it to "true", then in the Dispose() method you may check whether the flag "has exception" or not.

using (var db = new Database())
{
    // Do stuff

    db.Commit(); // Just set the flag to "true" (it's good to go)
}

And the database class

public class Database
{
    // Your stuff

    private bool clean = false;

    public void Commit()
    {
        this.clean = true;
    }

    public void Dispose()
    {
        if (this.clean == true)
            CommitToDatabase();
        else
            Rollback();
    }
}
BrunoLM
Unfortunately this is not a proper design of a class. `Dispose` should do as little as possible. When you're doing more than just disposing resources in a `Dispose` method, the changes of an exception being thrown from that `Dispose` method are higher. `Dispose` is also called in the context of an `Exception`, and in that case you would be replacing that exception with a new one, making debugging, and finding the cause of the exception, harder. Also, don't actively rollback a db transaction in a `Dispose` because of the same reasion. Just dispose the underlying transaction.
Steven
I guess this comment should be on the question, not on my answer, but anyway..."Dispose is also called in the context of an Exception" he knows that, and that's why he wants to find out if there were or not an exception, and instead of throw a exception again he would have a try catch around CommitToDatabase and Rollback or something like that
BrunoLM
@Bruno: I commented on the code I saw in your answer, but you're right about that: My comment would indeed be more appropriate on the question itself. btw. It is very hard to get the design right when trying to do this without an explicit `Commit` method, as I tried to explain in my answer: http://stackoverflow.com/questions/2830073/detecting-a-dispose-from-an-exception-inside-using-block/2830501#2830501
Steven