Set Gird and Level From 3D to 2D make Revit Crash

import clr
import time  # Importing time module for delays
clr.AddReference("System")
from System.Collections.Generic import List

from Autodesk.Revit.DB import * 
from pyrevit import forms, script
from pyrevit.forms import ProgressBar


doc = __revit__.ActiveUIDocument.Document
logger = script.get_logger()
output = script.get_output()

allowed_view_types = [ViewType.AreaPlan, ViewType.CeilingPlan, ViewType.EngineeringPlan, ViewType.FloorPlan]
all_grids = FilteredElementCollector(doc).OfClass(Grid).WhereElementIsNotElementType().ToElements()
datum_extent_types = list(clr.GetClrType(DatumExtentType).GetEnumValues())

# Correctly defined filter function
def filter_views(view):
    return view.ViewType in allowed_view_types

# UI Froms Alerts
res = forms.alert("Warning: This script may cause Revit to crash. "
                  "It is highly recommended that you Synchronize your model or Save your file.\n"
                  "Are you sure you want to run the script?",
                  options=["Run Script", "Exit"])

# UI Select View
if res == "Run Script":
    selected_views = forms.select_views(title='Select Levels', 
                                     button_name='Select', 
                                     multiple=True, 
                                     filterfunc=filter_views,
                                     doc=None, 
                                     use_selection=False)
else:
    script.exit()


# Main Function
if selected_views:
    max_value = len(selected_views)  # Set max_value based on the number of selected views
    
    with ProgressBar(title="Processing Views", cancellable=True) as pb:
        with Transaction(doc, __title__) as t:
            t.Start()
            success_count = 0
            data = []

            try:
                for counter, view in enumerate(selected_views):  # Enumerate through selected views
                    if pb.cancelled:
                        break
                        
                    view_success = False
                    
                    for grid in all_grids:
                        try:
                            grid.SetDatumExtentType(DatumEnds.End0, view, datum_extent_types[1])
                            grid.SetDatumExtentType(DatumEnds.End1, view, datum_extent_types[1])
                            view_success = True
                        except Exception as e:
                            if "The datum plane cannot be visible in the view." in str(e):
                                continue

                    if view_success:
                        success_count += 1
                        data.append([view.ViewType, view.Name, 'TRUE', output.linkify(view.Id)])
                    else:
                        data.append([view.ViewType, view.Name, 'FALSE', output.linkify(view.Id)])

                    # Update the progress bar with the current progress
                    pb.update_progress(counter + 1, max_value)

            except Exception as e:
                logger.error("Unexpected error: {}".format(str(e)))

            finally:
                data.sort(key=lambda x: x[2], reverse=False)
                output.print_table(
                    table_data=data,
                    title="Set Grid to 2D",
                    columns=["View Type", "View Name", "Set Grid 2D", "OwnerView"],
                    formats=['', '', '', '']
                )
            t.Commit()

In my script, it’s very straightforward: simply select ‘view’ and then run the script. However, several of my scripts cause Revit to crash.

Hi, I didn’t read your code carefully, but you can review my code below:

# -*- coding: utf-8 -*-

import clr
from pyrevit import forms
from System.Collections.Generic import *
from rpw.ui.forms import Alert
import sys

clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

doc = __revit__.ActiveUIDocument.Document
view = doc.ActiveView
uidoc = __revit__.ActiveUIDocument
app = __revit__.Application
DB = Autodesk.Revit.DB

# ----------------------------START CODE------------------------------
try:
    # ----------------------------Select Template Sheet------------------------------
    grid_activeview = FilteredElementCollector(doc, view.Id).OfClass(Grid).WhereElementIsNotElementType().ToElements()

    selected_option = forms.CommandSwitchWindow.show(
        ['3D to 2D', '2D to 3D'],
        message='Select Option:', )

    # ----------------------------TRANSACTION------------------------------
    if not selected_option:
        sys.exit()
    if selected_option == '3D to 2D':
        t = Transaction(doc, 'Convert Grids')
        t.Start()

        for i in grid_activeview:
            i.SetDatumExtentType(DatumEnds.End0, view, DatumExtentType.ViewSpecific)
            i.SetDatumExtentType(DatumEnds.End1, view, DatumExtentType.ViewSpecific)

        t.Commit()

    if selected_option == '2D to 3D':
        t = Transaction(doc, 'Convert Grids')
        t.Start()

        for i in grid_activeview:
            i.SetDatumExtentType(DatumEnds.End0, view, DatumExtentType.Model)
            i.SetDatumExtentType(DatumEnds.End1, view, DatumExtentType.Model)

        t.Commit()

    Alert('Convert Grids Sucessfully', 'Transaction Done')

except Autodesk.Revit.Exceptions.OperationCanceledException:
    pass

except Exception as ex:
    TaskDialog.Show("Error", "Warning: {}".format(ex))

1 Like