Results 1 to 6 of 6

Thread: Insert dwg as block

  1. #1
    Member
    Join Date
    2015-11
    Posts
    38
    Login to Give a bone
    0

    Default Insert dwg as block

    Ok - stuck again!! how do you insert an unopend drawing into an open drawing as a block.

    This is the code I have so far, mostly obtained from the .net discussion groups .. but it fails at the AddNewlyCreatedObject line with an 'eNotInDatabase' exception. Any ideas greatfully recieved!!

    Code:
    Imports Autodesk.AutoCAD.ApplicationServices
    Imports Autodesk.AutoCAD.EditorInput
    Imports Autodesk.AutoCAD.Runtime
    Imports Autodesk.AutoCAD.DatabaseServices
    Imports Autodesk.AutoCAD.Geometry
    Imports System.IO
    
    <CommandMethod("mmm")> _
            Public Sub InsertDrawing()
                Dim DwgNm As String = "c:\abc.dwg"
                Dim blkNm As String = "abc"
                Dim insPt As New Point3d(2, 2, 0)
                Dim s3d As New Scale3d(1)
                Dim rot As Double = 0
                Dim AcDoc As Document = Application.DocumentManager.MdiActiveDocument
                Dim acCurDb As Database = AcDoc.Database
                Dim AcTrans As Transaction = AcDoc.TransactionManager.StartTransaction
                Using AcTrans
                    Try
                        Dim id As ObjectId = Nothing
                        Dim bt As BlockTable = AcTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead, True)
                        If Not bt.Has(blkNm) Then
                            Dim srcDB As Database = New Database(False, True)
                            srcDB.ReadDwgFile(DwgNm, FileShare.Read, False, vbNullString)
                            id = acCurDb.Insert(DwgNm, srcDB, False)
                            Dim blk As BlockTableRecord = AcTrans.GetObject(id, OpenMode.ForWrite, False, True)
                            blk.Name = blkNm
                        Else
                            id = bt.Item(blkNm)
                        End If
                        Dim btr As BlockTableRecord = AcTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite, True)
                        Dim bref As BlockReference = New BlockReference(insPt, id)
                        bref.ScaleFactors = s3d
                        bref.Rotation = rot
                        AcTrans.AddNewlyCreatedDBObject(bref, True)
                        AcTrans.Commit()
                    Catch ex As Exception
                        MsgBox(ex.ToString)
                    End Try
                End Using
    
            End Sub

    Regards Matt

  2. #2
    100 Club
    Join Date
    2002-10
    Posts
    154
    Login to Give a bone
    0

    Default Re: Insert dwg as block

    I did something simular. I inserted blocks from another drawing. I create a BlockItem class that goes into this. It basically has infomation about object ID, layer, FileName, ect...

    Code:
      Public Function CloneBlock(ByVal mBlockItem As BlockItem) As Boolean
            Dim CloneMe As Boolean = True
            If ThisDrawingHasBlock(mBlockItem.Name) Then
                If Not mBlockItem.OverRite Then CloneMe = False
            End If
    
            If CloneMe Then
                Dim dm As DocumentCollection = Application.DocumentManager
                Dim ed As Editor = dm.MdiActiveDocument.Editor
                Dim DestDoc As Document = dm.MdiActiveDocument
                Dim DestDb As Database = DestDoc.Database
                Dim sourceDb As New Database(False, True)
                Dim ResultMsg As String = ""
                Try
                    ' Read the DWG into a side database
                    sourceDb.ReadDwgFile(mBlockItem.FileName, System.IO.FileShare.Read, True, "")
                    ' Create a variable to store the list of block identifiers
                    Dim blockIds As New ObjectIdCollection()
                    Dim tm As Autodesk.AutoCAD.DatabaseServices.TransactionManager = sourceDb.TransactionManager
                    Using myT As Transaction = tm.StartTransaction()
                        ' Open the block table
                        Dim bt As BlockTable = DirectCast(tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, False), BlockTable)
                        ' Check each block in the block table
                        blockIds.Add(FindMyBlockID(mBlockItem.Name, bt, tm))
                    End Using
    
                    ' Copy blocks from source to destination database
                    If blockIds.Count > 0 Then
                        Dim mapping As New IdMapping()
                        Using DestLock As DocumentLock = DestDoc.LockDocument
                            sourceDb.WblockCloneObjects(blockIds, DestDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, False)
                        End Using
                    End If
                    ' ResultMsg = vbLf & "Copied block definitions from " + mBlockItem.FileName + " to the current drawing."
                Catch ex As Autodesk.AutoCAD.Runtime.Exception
                    ResultMsg = vbLf & "Error during copy: " + ex.Message
                End Try
                sourceDb.Dispose()
                '' Set the new document current (very important)
                dm.MdiActiveDocument = DestDoc
                ed.WriteMessage(ResultMsg)
                Return True
            End If
    
            Return False
        End Function

  3. #3
    Active Member
    Join Date
    2009-08
    Posts
    93
    Login to Give a bone
    0

    Default Re: Insert dwg as block

    This one is like the INSERT command


    Code:
        <CommandMethod("InsertDwg")> _
            Public Sub InsertDwg()
                Dim doc As Document = DocumentManager.MdiActiveDocument
                Dim db As Database = doc.Database
                Dim ed As Editor = doc.Editor
                Dim fname As String = "C:\Users\Jeff\Documents\Drawing1.dwg"
                Dim ObjId As ObjectId
                Using trx As Transaction = db.TransactionManager.StartTransaction
                    Dim bt As BlockTable = db.BlockTableId.GetObject(OpenMode.ForRead)
                    Dim btrMs As BlockTableRecord = bt(BlockTableRecord.ModelSpace).GetObject(OpenMode.ForWrite)
                    Using dbInsert As New Database(False, True)
                        dbInsert.ReadDwgFile(fname, IO.FileShare.Read, True, "")
                        ObjId = db.Insert(Path.GetFileNameWithoutExtension(fname), dbInsert, True)
                    End Using
                    Dim ppo As New PromptPointOptions(vbCrLf & "Insertion Point")
                    Dim ppr As PromptPointResult
                    ppr = ed.GetPoint(ppo)
                    If ppr.Status <> PromptStatus.OK Then
                        ed.WriteMessage(vbCrLf & "You decided to QUIT!")
                        Exit Sub
                    End If
                    Dim insertPt As Point3d = ppr.Value
                    Dim bref As New BlockReference(insertPt, ObjId)
                    btrMs.AppendEntity(bref)
                    trx.AddNewlyCreatedDBObject(bref, True)
                    trx.Commit()
                End Using
    
            End Sub
    Last edited by Jeff H; 2010-11-19 at 07:45 AM.

  4. #4
    Active Member
    Join Date
    2009-08
    Posts
    93
    Login to Give a bone
    0

    Default Re: Insert dwg as block

    It is failing at AcTrans.AddNewlyCreatedDBObject(bref, True) because bref is not in the database, you need to add it using AppendEntity which will add it to the database and BlockTableRecord


    Change the ending of your code to this and it should work

    Code:
                        Dim btr As BlockTableRecord = AcTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite, True)
                        Dim bref As BlockReference = New BlockReference(insPt, id)
                        bref.ScaleFactors = s3d
                        bref.Rotation = rot
                        btr.AppendEntity(bref) ''''''Add this one Line and should work
                        AcTrans.AddNewlyCreatedDBObject(bref, True)
                        AcTrans.Commit()
                    Catch ex As System.Exception
                        MsgBox(ex.ToString)
                    End Try
                End Using
    
            End Sub

  5. #5
    AUGI Addict fixo's Avatar
    Join Date
    2005-05
    Location
    Pietari, Venäjä
    Posts
    1,269
    Login to Give a bone
    0

    Default Re: Insert dwg as block

    Quote Originally Posted by matthew.proud View Post
    Ok - stuck again!! how do you insert an unopend drawing into an open drawing as a block.

    This is the code I have so far, mostly obtained from the .net discussion groups .. but it fails at the AddNewlyCreatedObject line with an 'eNotInDatabase' exception. Any ideas greatfully recieved!!

    Code:
    Imports Autodesk.AutoCAD.ApplicationServices
    Imports Autodesk.AutoCAD.EditorInput
    Imports Autodesk.AutoCAD.Runtime
    Imports Autodesk.AutoCAD.DatabaseServices
    Imports Autodesk.AutoCAD.Geometry
    Imports System.IO
     
    <CommandMethod("mmm")> _
            Public Sub InsertDrawing()
                Dim DwgNm As String = "c:\abc.dwg"
                Dim blkNm As String = "abc"
                Dim insPt As New Point3d(2, 2, 0)
                Dim s3d As New Scale3d(1)
                Dim rot As Double = 0
                Dim AcDoc As Document = Application.DocumentManager.MdiActiveDocument
                Dim acCurDb As Database = AcDoc.Database
                Dim AcTrans As Transaction = AcDoc.TransactionManager.StartTransaction
                Using AcTrans
                    Try
                        Dim id As ObjectId = Nothing
                        Dim bt As BlockTable = AcTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead, True)
                        If Not bt.Has(blkNm) Then
                            Dim srcDB As Database = New Database(False, True)
                            srcDB.ReadDwgFile(DwgNm, FileShare.Read, False, vbNullString)
                            id = acCurDb.Insert(DwgNm, srcDB, False)
                            Dim blk As BlockTableRecord = AcTrans.GetObject(id, OpenMode.ForWrite, False, True)
                            blk.Name = blkNm
                        Else
                            id = bt.Item(blkNm)
                        End If
                        Dim btr As BlockTableRecord = AcTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite, True)
                        Dim bref As BlockReference = New BlockReference(insPt, id)
                        bref.ScaleFactors = s3d
                        bref.Rotation = rot
                        AcTrans.AddNewlyCreatedDBObject(bref, True)
                        AcTrans.Commit()
                    Catch ex As Exception
                        MsgBox(ex.ToString)
                    End Try
                End Using
     
            End Sub

    Regards Matt
    In case you have attributes in the source drawing
    it may helps:
    Code:
        <CommandMethod("IBB", CommandFlags.Session And CommandFlags.Redraw)> _
        Public Sub test()
            Dim DwgNm As String = "c:\abc.dwg"
            Dim blkNm As String = "abc"
            Dim insPt As New Point3d(300.0, 300.0, 0.0)
            'Dim s3d As New Scale3d(2)
            'Dim rot As Double = Math.pi/4
            Dim AcDoc As Document = Application.DocumentManager.MdiActiveDocument
            Dim acCurDb As Database = AcDoc.Database
            InsertDrawingAsBlock(AcDoc, DwgNm, blkNm, insPt)
        End Sub
        Public Sub InsertDrawingAsBlock(ByVal doc As Document, ByVal filepath As String, ByVal blockname As String, ByVal ipt As Point3d)
            Dim curdb As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Dim loc As DocumentLock = doc.LockDocument()
            Using loc
                Dim tr As Transaction = doc.TransactionManager.StartTransaction
                Using tr
                    Try
                        Dim blkid As ObjectId
                        Dim bt As BlockTable = CType(tr.GetObject(curdb.BlockTableId, OpenMode.ForRead, False), BlockTable)
                        If bt.Has(blockname) Then
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(String.Format("Block ""{0}"" does already exist" & vbLf & "Try another name", blockname))
                            Return
                        End If
                        Dim btr As BlockTableRecord = CType(tr.GetObject(curdb.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                        Dim db As Database = New Database(False, True)
                        Using db
                            db.ReadDwgFile(filepath, System.IO.FileShare.Read, False, "")
                            blkid = curdb.Insert(blockname, db, True)
                        End Using
                        If (Not bt.Has(blockname)) Then
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(String.Format("Block ""{0}"" does not added to block table" & vbLf & "Exit on Error", blockname))
                            Return
                        End If
                        Dim btrec As BlockTableRecord = CType(tr.GetObject(blkid, OpenMode.ForRead, False), BlockTableRecord)
                        If String.IsNullOrEmpty(btrec.Name) Then
                            btrec.UpgradeOpen()
                            btrec.Name = blockname
                            btrec.DowngradeOpen()
                        End If
                        Dim bref As BlockReference = New BlockReference(ipt, blkid)
                        Dim mat As Matrix3d = Matrix3d.Identity
                        bref.TransformBy(mat)
                        bref.ScaleFactors = New Scale3d(2)
                        bref.Rotation = Math.PI / 4
                        btr.AppendEntity(bref)
                        tr.AddNewlyCreatedDBObject(bref, True)
     
                        If btrec.HasAttributeDefinitions Then
                            Dim atcoll As Autodesk.AutoCAD.DatabaseServices.AttributeCollection = bref.AttributeCollection
                            For Each subid As ObjectId In btrec
                                Dim ent As Entity = DirectCast(subid.GetObject(OpenMode.ForRead), Entity)
                                Dim attDef As AttributeDefinition = TryCast(ent, AttributeDefinition)
                                If attDef IsNot Nothing Then
                                    ed.WriteMessage(vbLf & "Value: " + attDef.TextString)
                                    Dim attRef As New AttributeReference()
                                    attRef.SetPropertiesFrom(attDef)
                                    attRef.Visible = attDef.Visible
                                    attRef.SetAttributeFromBlock(attDef, bref.BlockTransform)
                                    attRef.HorizontalMode = attDef.HorizontalMode
                                    attRef.VerticalMode = attDef.VerticalMode
                                    attRef.Rotation = attDef.Rotation
                                    attRef.TextStyle = attDef.TextStyle
                                    attRef.Position = attDef.Position + ipt.GetAsVector()
                                    attRef.Tag = attDef.Tag
                                    attRef.FieldLength = attDef.FieldLength
                                    attRef.TextString = attDef.TextString
                                    attRef.AdjustAlignment(curdb)
                                    atcoll.AppendAttribute(attRef)
                                    tr.AddNewlyCreatedDBObject(attRef, True)
                                End If
                            Next
                        End If
                        ed.UpdateScreen()
                        tr.Commit()
                    Catch ex As Autodesk.AutoCAD.Runtime.Exception
                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.ToString & vbCr & ex.Message)
                    End Try
                End Using
            End Using
        End Sub

  6. #6
    Member
    Join Date
    2015-11
    Posts
    38
    Login to Give a bone
    0

    Red face Re: Insert dwg as block

    Thanks very much for your replies!

    I’ve gone with Jeff's solution. =)

    Should have realised what the problem was , same as always, it’s obvious when its pointed out..

    Managed to complete what I was trying to accomplish today and more, so again thank you!!

    Regards

    Matt

Similar Threads

  1. Insert a new block using data from existing block
    By mike.43789 in forum AutoLISP
    Replies: 3
    Last Post: 2015-01-12, 11:50 PM
  2. Insert a Tool Palette Block While Editing a Block or Xref.
    By Wish List System in forum AutoCAD Wish List
    Replies: 1
    Last Post: 2013-10-07, 04:53 PM
  3. Block Insert - Right Click Block Open Drawing
    By Texan1 in forum ACA Wish List
    Replies: 1
    Last Post: 2011-11-26, 04:38 AM
  4. Replies: 19
    Last Post: 2006-03-14, 05:06 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •