Problem when reusing command

Problem when reusing command

carlosrdrzalns
Advocate Advocate
892 Views
2 Replies
Message 1 of 3

Problem when reusing command

carlosrdrzalns
Advocate
Advocate

Hi there, 

 

I was developing a command to change some text inside a viewport depending on that viewport scale. 

It works fine when i used, but if i tried to use it again in the same drawing and VP, autoCAD chrashed giving the next alert:

 

Captura.PNG

 

Manually debugging the code, i found that the problem comes from the time it tried to resize again the text, as if i comment that line, it works fine. 

 

It funny the fact that it also change the Width and contents properties of the Mtext and works fine but chrashes when triying to change the TextHeigth property. 

I was wondering if maybe there is a bad practice in my code, maybe something that must be closed the first time i used and it is not; that may be producing this problem. 

 

If there is anybody that has experimented the same problem or knows about good practices i may have left behind it would be great to get his feedback on the issue, as I only find webs saying that this problem happens when the drawing is corrupt. 

 

I leave the code below with the problematic line with a comment:

 

 

Imports System
Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.EditorInput
Imports Autodesk.AutoCAD.Geometry
Imports Autodesk.Civil.DatabaseServices.Styles
Imports Autodesk.Civil.ApplicationServices
Imports Autodesk.Civil.DatabaseServices

Imports System.Runtime.CompilerServices

Module Extensionmethods
    <Extension()>
    Function DCS2WCS(ByVal vp As Viewport) As Matrix3d
        Return Matrix3d.Rotation(-vp.TwistAngle, vp.ViewDirection, vp.ViewTarget) * Matrix3d.Displacement(vp.ViewTarget.GetAsVector()) * Matrix3d.PlaneToWorld(vp.ViewDirection)
    End Function

    <Extension()>
    Function WCS2DCS(ByVal vp As Viewport) As Matrix3d
        Return Matrix3d.WorldToPlane(vp.ViewDirection) * Matrix3d.Displacement(vp.ViewTarget.GetAsVector().Negate()) * Matrix3d.Rotation(vp.TwistAngle, vp.ViewDirection, vp.ViewTarget)
    End Function

    <Extension()>
    Function DCS2PSDCS(ByVal vp As Viewport) As Matrix3d
        Return Matrix3d.Scaling(vp.CustomScale, vp.CenterPoint) * Matrix3d.Displacement(vp.ViewCenter.Convert3d().GetVectorTo(vp.CenterPoint))
    End Function

    <Extension()>
    Function PSDCS2DCS(ByVal vp As Viewport) As Matrix3d
        Return Matrix3d.Displacement(vp.CenterPoint.GetVectorTo(vp.ViewCenter.Convert3d())) * Matrix3d.Scaling(1.0 / vp.CustomScale, vp.CenterPoint)
    End Function

    <Extension()>
    Function Convert3d(ByVal pt As Point2d) As Point3d
        Return New Point3d(pt.X, pt.Y, 0.0)
    End Function
End Module




Public Class Commands
    Dim docCol As Autodesk.AutoCAD.ApplicationServices.DocumentCollection = Application.DocumentManager
    Dim oDoc As Document = docCol.MdiActiveDocument
    Dim m_Database As Database = docCol.MdiActiveDocument.Database
    Dim ed As Editor = docCol.MdiActiveDocument.Editor

<CommandMethod("ChangeTextStyle")>
    Public Sub SetTextStyle()
        Try

            Dim TextDic As New Dictionary(Of String, TextStyleTableRecord)
            Using tr As Transaction = m_Database.TransactionManager.StartTransaction()
                '' Get the current Annotation Scale on the drawing
                Dim scale As String = m_Database.Cannoscale.Name
                Dim subscale As String = scale.Substring(scale.IndexOf(":") + 1, scale.IndexOf("(") - scale.IndexOf(":") - 1)

                '' Create a dictionary with the text styles and names
                Dim acTextStyleTable As TextStyleTable = tr.GetObject(m_Database.TextStyleTableId, OpenMode.ForRead)
                For Each id As ObjectId In acTextStyleTable
                    Dim Symbol As TextStyleTableRecord = tr.GetObject(id, OpenMode.ForRead)
                    TextDic.Add(Symbol.Name, Symbol)
                    'ed.WriteMessage("estilo de texto: " + Symbol.Name + vbCrLf)
                Next

                Dim keys As Dictionary(Of String, TextStyleTableRecord).KeyCollection = TextDic.Keys


                Dim stri As String = "TfL_m1-" + subscale



                'Ask the user to select a viewport
                Dim opt As PromptEntityOptions = New PromptEntityOptions("Pick a Viewport")
                opt.SetRejectMessage("object must be a viewport")
                opt.AddAllowedClass(GetType(Viewport), True)
                Dim per As PromptEntityResult = ed.GetEntity(opt)

                If per.Status <> PromptStatus.OK Then
                    ed.WriteMessage("Error intentando obtener el objeto seleccionado. Saliendo de la función.")
                    Return
                End If


                Dim MSVPpoints As Point3dCollection = New Point3dCollection
                Using VP As Viewport = tr.GetObject(per.ObjectId, OpenMode.ForRead)
                    TranslateVPPointsToModelSpace(MSVPpoints, VP)

                End Using

                ed.SwitchToModelSpace()

                Dim acTypValAr(1) As TypedValue
                acTypValAr.SetValue(New TypedValue(DxfCode.LayerName, "SE-Zz_2-E"), 0)
                acTypValAr.SetValue(New TypedValue(DxfCode.Start, "MTEXT"), 1)
                Dim acSelFtr As SelectionFilter = New SelectionFilter(acTypValAr)

                Dim SelectionResult As PromptSelectionResult = ed.SelectCrossingPolygon(MSVPpoints, acSelFtr)
                If SelectionResult.Status <> PromptStatus.OK Then
                    ed.WriteMessage("error en la selección")
                    Return
                End If
                Dim SelectSet As SelectionSet = SelectionResult.Value
                AgruparTexto(tr, SelectSet)

                SelectSet.Dispose()

                Dim SelectionResult2 As PromptSelectionResult = ed.SelectCrossingPolygon(MSVPpoints, acSelFtr)
                If SelectionResult2.Status <> PromptStatus.OK Then
                    ed.WriteMessage("error en la selección")
                    Return
                End If
                Dim SelectSet2 As SelectionSet = SelectionResult2.Value
                For Each objss As SelectedObject In SelectSet2


                    Dim tx As MText = tr.GetObject(objss.ObjectId, OpenMode.ForWrite)
                    tx.Width = tx.Width * TextDic(stri).TextSize / tx.TextHeight
                    tx.TextStyleId = TextDic(stri).ObjectId
                    ed.WriteMessage("el tamñaño del texto es {0}" + vbCrLf, tx.TextHeight)
                    tx.TextHeight = TextDic(stri).TextSize  ''<--- here it is where the problem comes from




                Next


                SelectionResult2 = Nothing
                SelectSet2.Dispose()
                SelectSet2 = Nothing




                ed.UpdateScreen()
                ed.Regen()

                tr.Commit()


            End Using



        Catch ex As System.Exception
            ed.WriteMessage(ex.Message + ex.StackTrace)
        End Try
    End Sub

    ''' <summary>
    ''' translate Viewport point form paper space to model space using extensions asigned to points3d
    ''' </summary>
    ''' <param name="MSVPpoints"></param>
    ''' <param name="VP"></param>
    Private Sub TranslateVPPointsToModelSpace(ByRef MSVPpoints As Point3dCollection, ByVal VP As Viewport)
        'VP.Locked = True
        Try
            Dim PSVPpoints As Point3dCollection = New Point3dCollection
            VP.GetGripPoints(PSVPpoints, New IntegerCollection(), New IntegerCollection())





            Dim tpm As Point3d = PSVPpoints(2)
            PSVPpoints(2) = PSVPpoints(1)
            PSVPpoints(1) = tpm

            PSVPpoints.Remove(PSVPpoints(PSVPpoints.Count - 1))



            Dim PSDSC2UCS = PSDCS2DCS(VP) * DCS2WCS(VP) * ed.CurrentUserCoordinateSystem


            For Each pnt As Point3d In PSVPpoints
                Dim point As Point3d
                point = pnt.TransformBy(PSDSC2UCS)

                MSVPpoints.Add(point)

            Next
        Catch ex As System.Exception
            ed.WriteMessage("error al transladar los putnos")

        End Try

    End Sub

    ''' <summary>
    ''' gruop Mtext single lines in a Mtext multiline and asign correct attatchment
    ''' </summary>
    ''' <param name="tr"></param>
    ''' <param name="SelectSet"></param>
    Private Sub AgruparTexto(tr As Transaction, SelectSet As SelectionSet)

        Try
            Dim izqCollect As Collection = New Collection
            Dim key As Integer = 1

            For Each obss As SelectedObject In SelectSet

                Dim tx As MText = tr.GetObject(obss.ObjectId, OpenMode.ForWrite)



                For Each auxobjss As SelectedObject In SelectSet
                    Dim IntPnt As Point3dCollection = New Point3dCollection
                    Dim auxtx As MText = tr.GetObject(auxobjss.ObjectId, OpenMode.ForRead)

                    If tx.ObjectId <> auxtx.ObjectId And Not auxtx.IsErased Then
                        Dim entitybelow As Boolean = IsTextBelow(tx, auxtx)
                        If entitybelow = True Then
                            If tx.Location.X = auxtx.Location.X Then
                                If auxtx.Width > tx.Width Then tx.Width = auxtx.Width
                                tx.Contents += vbCrLf + auxtx.Contents
                                tx.Attachment = AttachmentPoint.TopLeft
                                auxtx.Erase()

                            ElseIf Math.Round(tx.Location.X + tx.ActualWidth / 2, 1) = Math.Round(auxtx.Location.X + auxtx.ActualWidth / 2, 1) Then
                                If auxtx.Width > tx.Width Then tx.Width = auxtx.Width
                                tx.Contents += vbCrLf + auxtx.Contents
                                tx.Location = New Point3d(tx.Location.X + tx.ActualWidth / 2, tx.Location.Y, 0)
                                tx.Attachment = AttachmentPoint.TopCenter
                                auxtx.Erase()


                            Else
                                If auxtx.Width > tx.Width Then tx.Width = auxtx.Width
                                tx.Contents += vbCrLf + auxtx.Contents
                                izqCollect.Add(tx, key)
                                key += 1
                                auxtx.Erase()
                            End If
                        End If

                    End If


                Next

            Next

            For Each tx As MText In izqCollect
                If Not tx.IsErased Then
                    Dim pos As New Point3d(tx.Location.X + tx.ActualWidth, tx.Location.Y, 0)
                    tx.Attachment = AttachmentPoint.TopRight
                    tx.Location = pos
                End If

            Next
        Catch ex As System.Exception
            ed.WriteMessage("error al agrupar los textos")

        End Try
    End Sub


    ''' <summary>
    ''' find if there is any text inmediatly below
    ''' </summary>
    ''' <param name="tx"></param>
    ''' <param name="entitybelow"></param>
    ''' <returns></returns>
    Private Function IsTextBelow(ByVal tx As MText, ByVal entitybelow As MText) As Boolean
        Try


            Dim pl As Polyline = New Polyline
            Dim VerticesX = New Integer() {0, 1, 1, 0}
            Dim VerticesY = New Integer() {0, 0, -1, -1}
            For i As Integer = 0 To VerticesX.Count - 1
                Dim pnt As Point2d = New Point2d(tx.Location.X + tx.ActualWidth * VerticesX(i), tx.Location.Y + (tx.ActualHeight + tx.TextHeight) * VerticesY(i))
                pl.AddVertexAt(0, pnt, 0, 0, 0)
            Next
            pl.Closed = True
            Dim IntPnt As Point3dCollection = New Point3dCollection
            pl.IntersectWith(entitybelow, Intersect.OnBothOperands, IntPnt, New IntPtr(0), New IntPtr(0))
            pl.Dispose()

            If IntPnt.Count > 0 Then
                Return True
            Else
                Return False
            End If


        Catch ex As System.Exception
            ed.WriteMessage("error al encontrar el texto inferior")
            Return False
        End Try



    End Function
End Class

 

 

 

0 Likes
Accepted solutions (1)
893 Views
2 Replies
Replies (2)
Message 2 of 3

mujibur.rahman
Enthusiast
Enthusiast
Accepted solution

Hi,
when you run command in debug mode you can find the line of code where the error occurs.....
but anyhow this kind of error occurs only when we OpenMode is read only 

please replace 'OpenMode.ForRead' with the 'OpenMode.ForWrite' in you code and then try

sure it will work..

if it works, please accept this as soluton 

0 Likes
Message 3 of 3

carlosrdrzalns
Advocate
Advocate

Thank you for your quick answer @mujibur.rahman . 

 

It works fine but i don't really understand why this is happening, as they variable openned with the "OpenMode.ForRead" is used for read only and, althought it is the same that is opened before for read, if I close the object it keep iving the problem. In addition, I dont undertand neither why this happened only with the TextHeight property, as i can modify with my previous code other attributes and no problem appear. 

 

Anyway, this works, thank you so much for the information, i will keep this in mind for future works.

 

Regards. 

0 Likes