Message 1 of 5
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
I'm trying to export selected ViewTemplates (using a custom winform) to a new project file, so they can be imported into another project. However, ElementTransformUtils.CopyElements (line 54) yields a ModificationOutsideTransactionException even though it's wrapped inside a Transaction (line 41).
Does anyone know what may be causing it?
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace scripts
{
[Transaction(TransactionMode.Manual)]
public class ExportViewTemplatesToRvt : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIApplication uiApp = commandData.Application;
UIDocument uiDoc = uiApp.ActiveUIDocument;
Document doc = uiDoc.Document;
// Get all view templates in the document
FilteredElementCollector collector = new FilteredElementCollector(doc);
List<Autodesk.Revit.DB.View> viewTemplates = collector.OfClass(typeof(Autodesk.Revit.DB.View))
.Cast<Autodesk.Revit.DB.View>()
.Where(v => v.IsTemplate)
.ToList();
List<string> properties = new List<string> { "Title" };
var selectedViews = CustomGUIs.DataGrid<Autodesk.Revit.DB.View>(viewTemplates, properties);
// Prompt user to choose location and file name
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Revit File (*.rvt)|*.rvt";
saveFileDialog.Title = "Save As";
saveFileDialog.ShowDialog();
// Check if the user cancelled the operation
if (saveFileDialog.FileName == "")
return Result.Cancelled;
// Start a transaction
using (Transaction transaction = new Transaction(doc, "Export View Templates"))
{
transaction.Start();
// Create a new Revit document
var revitApp = uiApp.Application;
Document newDoc = revitApp.NewProjectDocument(UnitSystem.Imperial);
// Copy the selected elements to the new document
List<ElementId> copiedIds = new List<ElementId>();
foreach (Autodesk.Revit.DB.View viewTemplate in viewTemplates)
{
CopyPasteOptions copyOptions = new CopyPasteOptions();
ElementId copiedId = ElementTransformUtils.CopyElements(doc, new List<ElementId> { viewTemplate.Id }, newDoc, Transform.Identity, copyOptions).FirstOrDefault();
copiedIds.Add(copiedId);
}
// Save the new document as .rvt
string filePath = saveFileDialog.FileName;
SaveAsOptions saveAsOptions = new SaveAsOptions { OverwriteExistingFile = true };
newDoc.SaveAs(filePath, saveAsOptions);
// Commit the transaction
transaction.Commit();
TaskDialog.Show("Success", "Selected objects have been exported to a new .rvt file.");
}
return Result.Succeeded;
}
}
}
Solved! Go to Solution.