Dynamic Model Update, Exceptions, and Transactions (hint – look in the journal file)

In the last post I casually mentioned that during Dynamic Model Update we could delete the just-created elements. My first attempt was to add a transaction and Document.Delete(). That doesn’t work, and it also brings up a useful tip.

The error dialog shown on the right is Revit’s way of saying that your updater threw an exception, though it doesn’t give any technical details about the nature of the execption. “But what was the exception?” you will rightfully wonder! The answer is in the journal file, where in this case it explains:

' 2:< Exception caught from managed method RevitAPI::Autodesk.Revit.DB.TransactionStatus Start() <Autodesk.Revit.Exceptions.InvalidOperationException> <Starting a new transaction is not permitted. It could be because another transaction already started and has not been completed yet, or the document is in a state in which it cannot start a new transaction (e.g. during failure handling or a read-only mode, which could be either permanent or temporary).>

errorpublic void Execute(UpdaterData data)
{
    Document doc = data.GetDocument();
    Autodesk.Revit.ApplicationServices.Application app = doc.Application;
    foreach (ElementId addedElemId in data.GetAddedElementIds())
    {
        ImportInstance ii = doc.GetElement(addedElemId) as ImportInstance;
        if (ii.IsLinked == false)
            TaskDialog.Show("Hey!", app.Username + " - Maybe should should have linked that CAD instead of importing it.");

        // THIS DOESN'T WORK!
        Transaction t = new Transaction(doc,"delete that");
        t.Start();
        doc.Delete(ii);
        t.Commit();
    }
}

Thanks to that info in the journal file, we learn that we need to get rid of the transaction code. Doing so gives us this, which works fine to delete the import instance that was just created.

public void Execute(UpdaterData data)
{
    Document doc = data.GetDocument();
    Autodesk.Revit.ApplicationServices.Application app = doc.Application;
    foreach (ElementId addedElemId in data.GetAddedElementIds())
    {
        ImportInstance ii = doc.GetElement(addedElemId) as ImportInstance;
        if (ii.IsLinked == false)
            TaskDialog.Show("Hey!", app.Username + " - Maybe should should have linked that CAD instead of importing it.");
        doc.Delete(ii);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s