Script error Civil 3d 2022 section view

why this code not runnig ? I use cpython3 and civil 3d 2022

# Load the Python Standard and DesignScript Libraries
import sys
import clr

# Add Assemblies for AutoCAD and Civil3D
clr.AddReference('AcMgd')
clr.AddReference('AcCoreMgd')
clr.AddReference('AcDbMgd')
clr.AddReference('AecBaseMgd')
clr.AddReference('AecPropDataMgd')
clr.AddReference('AeccDbMgd')

# Import references from AutoCAD
from Autodesk.AutoCAD.Runtime import *
from Autodesk.AutoCAD.ApplicationServices import *
from Autodesk.AutoCAD.EditorInput import *
from Autodesk.AutoCAD.DatabaseServices import *
from Autodesk.AutoCAD.Geometry import *

# Import references from Civil3D
from Autodesk.Civil.ApplicationServices import *
from Autodesk.Civil.DatabaseServices import *

# The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN

# Inputs from Dynamo
alignment_name = IN[0]
sample_line_group_name = IN[1]
surface_name = IN[2]
section_view_style_name = IN[3]

# Setup document and editor
adoc = Application.DocumentManager.MdiActiveDocument
editor = adoc.Editor
civilDoc = CivilApplication.ActiveDocument

created_views = []

with adoc.LockDocument():
    db = adoc.Database
    tm = db.TransactionManager
    tr = tm.StartTransaction()
    try:
        # Get alignment
        alignment = None
        for id in civilDoc.AlignmentCollection:
            a = tr.GetObject(id, OpenMode.ForRead)
            if a.Name == alignment_name:
                alignment = a
                break
        if alignment is None:
            raise Exception("Alignment not found")

        # Get sample line group
        slg_id = None
        for gid in alignment.GetSampleLineGroupIds():
            g = tr.GetObject(gid, OpenMode.ForRead)
            if g.Name == sample_line_group_name:
                slg_id = gid
                break
        if slg_id is None:
            raise Exception("Sample Line Group not found")

        sl_group = tr.GetObject(slg_id, OpenMode.ForRead)

        # Get surface
        surface = civilDoc.GetSurfaceByName(surface_name)
        if surface is None:
            raise Exception("Surface not found")

        # Get section view style
        styles = civilDoc.Styles.SectionViewStyles
        style_id = ObjectId.Null
        for sid in styles.GetSectionViewStyleIds():
            s = tr.GetObject(sid, OpenMode.ForRead)
            if s.Name == section_view_style_name:
                style_id = sid
                break
        if style_id.IsNull:
            raise Exception("Section View Style not found")

        # Create section views at origin (or change insertion point logic)
        for sl_id in sl_group.GetSampleLineIds():
            sample_line = tr.GetObject(sl_id, OpenMode.ForRead)
            for section_id in sample_line.GetSectionIds():
                section = tr.GetObject(section_id, OpenMode.ForRead)
                if section.SurfaceId != surface.ObjectId:
                    continue
                # Create section view
                view_id = SectionView.Create(section.ObjectId, style_id, Point3d(0, 0, 0))
                view = tr.GetObject(view_id, OpenMode.ForWrite)
                created_views.append(view.Name)

        tr.Commit()
    except Exception as e:
        OUT = f"Error: {str(e)}"
    finally:
        tr.Dispose()

if 'OUT' not in locals():
    OUT = created_views

What is the warning?

Warning: TypeError : No method matches given arguments for OnExit: (<class ‘Autodesk.AutoCAD.ApplicationServices.DocumentLock’>, <class ‘type’>, <class ‘AttributeError’>, <class ‘traceback’>) [’ File “”, line 99, in \n’]Preformatted text

Hi,
try to use a context manager instead try-except

# Load the Python Standard and DesignScript Libraries
import sys
import clr
import System
# Add Assemblies for AutoCAD and Civil3D
clr.AddReference('AcMgd')
clr.AddReference('AcCoreMgd')
clr.AddReference('AcDbMgd')
clr.AddReference('AecBaseMgd')
clr.AddReference('AecPropDataMgd')
clr.AddReference('AeccDbMgd')

# Import references from AutoCAD
from Autodesk.AutoCAD.Runtime import *
from Autodesk.AutoCAD.ApplicationServices import *
from Autodesk.AutoCAD.EditorInput import *
from Autodesk.AutoCAD.DatabaseServices import *
from Autodesk.AutoCAD.Geometry import *

# Import references from Civil3D
from Autodesk.Civil.ApplicationServices import *
from Autodesk.Civil.DatabaseServices import *

# The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN

# Inputs from Dynamo
alignment_name = IN[0]
sample_line_group_name = IN[1]
surface_name = IN[2]
section_view_style_name = IN[3]

# Setup document and editor
adoc = Application.DocumentManager.MdiActiveDocument
editor = adoc.Editor
civilDoc = CivilApplication.ActiveDocument

created_views = []

class CManager:
    """
    a custom context manager for Disposable Object
    """
    lst_error = []
    def __init__(self, obj):
        self.obj = obj
        
    def __enter__(self):
        return self.obj
        
    def __exit__(self, exc_type, exc_value, exc_tb):
        print(clr.__version__)
        if "3." in clr.__version__: # for pythonnet 3.
            self.obj.Dispose()
        #
        if exc_type :
            error = f"{exc_type.__name__} - {exc_value} at line {exc_tb.tb_lineno}"
            self.__class__.lst_error.append(error)
            # optionnal for pythonet 3
            #if "3." in clr.__version__: 
            #    raise exc_type(exc_type.__name__, error)
        return self.obj # or return self

with adoc.LockDocument():
    with CManager(adoc.Database) as db:
       with CManager(db.TransactionManager.StartTransaction()) as tr:
            # Get alignment
            alignment = None
            for id in civilDoc.AlignmentCollection:
                a = tr.GetObject(id, OpenMode.ForRead)
                if a.Name == alignment_name:
                    alignment = a
                    break
            if alignment is None:
                raise Exception("Alignment not found")
    
            # Get sample line group
            slg_id = None
            for gid in alignment.GetSampleLineGroupIds():
                g = tr.GetObject(gid, OpenMode.ForRead)
                if g.Name == sample_line_group_name:
                    slg_id = gid
                    break
            if slg_id is None:
                raise Exception("Sample Line Group not found")
    
            sl_group = tr.GetObject(slg_id, OpenMode.ForRead)
    
            # Get surface
            surface = civilDoc.GetSurfaceByName(surface_name)
            if surface is None:
                raise Exception("Surface not found")
    
            # Get section view style
            styles = civilDoc.Styles.SectionViewStyles
            style_id = ObjectId.Null
            for sid in styles.GetSectionViewStyleIds():
                s = tr.GetObject(sid, OpenMode.ForRead)
                if s.Name == section_view_style_name:
                    style_id = sid
                    break
            if style_id.IsNull:
                raise Exception("Section View Style not found")
    
            # Create section views at origin (or change insertion point logic)
            for sl_id in sl_group.GetSampleLineIds():
                sample_line = tr.GetObject(sl_id, OpenMode.ForRead)
                for section_id in sample_line.GetSectionIds():
                    section = tr.GetObject(section_id, OpenMode.ForRead)
                    if section.SurfaceId != surface.ObjectId:
                        continue
                    # Create section view
                    view_id = SectionView.Create(section.ObjectId, style_id, Point3d(0, 0, 0))
                    view = tr.GetObject(view_id, OpenMode.ForWrite)
                    created_views.append(view.Name)
    
            tr.Commit()


if CManager.lst_error:
    OUT = CManager.lst_error
else:
    OUT = "result"
1 Like

I tried but i got the same error

my version of code with a context manager indicate this error

AttributeError - 'CivilDocument' object has no attribute 'AlignmentCollection'

Probably an attribute invented by an LLM ?

Here is the official API documentation to help you

Please
Attached example drawing & Dyn file

1 Like