Author Topic: BlockTesting2011  (Read 19055 times)

0 Members and 1 Guest are viewing this topic.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11653
  • class keyThumper<T>:ILazy<T>
BlockTesting2011
« on: March 30, 2011, 09:26:38 PM »
This will be an ongoing thread with functions added as I get a chance.
Refer to the attached Zip for the full solution.
The routines are noted for functionality.

There are some gotcha's and traps in these incomplete samples.
The intent was to proceed step by step to explore the concepts involved.
//---------------------------------------------------------------
Jeff H has volunteered to convert these Methods to VB.net
Thanks Jeff.

gile has volunteered to convert these Methods to F#
Thanks gile.
//---------------------------------------------------------------

NOTE Solutions updated
//------------------------------- Sample Blocks
3DBlock.dwg  - block with no attibutes is attached to this first post :
 
3DBlock_A.dwg - block with one attibute is attached to this first post :

3DBlock_4A.dwg - block with 4 attibutes is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427676#msg427676

 //------------------------------- C# Solutions
BlockTesting2011 _20110331.1115.zip is attached to this first post :

BlockTesting2011 _20110401.0936.zip is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427348#msg427348

BlockTesting2011 _ 20110405.1206.zip  is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427833#msg427833

//------------------------------- VB Solutions
BlockTesting2011VB_04012011.zip is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427562#msg427562

BlockTesting2011VB_04042011.zip is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427562#msg427562

//------------------------------- F# Solutions
BlockTesting2011FS_20110403.zip is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427619#msg427619

BlockTesting2011FS_20110405.zip   is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427843#msg427843
//---------------------------------------------------------------

Container :
Code: (csharp) [Select]
// CodeHimBelonga kdub@theSwamp 20110331
//
using System;
using System.IO;

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
//
using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using AcUtils = Autodesk.AutoCAD.Internal.Utils;

[assembly: CommandClass(typeof(KdubTesting.BlockTesting2011))]

namespace KdubTesting
{
    public class BlockTesting2011
    {
        Document doc;
        Database db;
        Editor ed;

        public BlockTesting2011()
        {
            ActiveDoc = AcadApp.DocumentManager.MdiActiveDocument;
        }

        Document ActiveDoc
        {
            get { return doc; }
            set
            {
                doc = value;
                if( doc == null ) {
                    db = null;
                    ed = null;
                } else {
                    db = doc.Database;
                    ed = doc.Editor;
                }
            }
        }
        //=======================================================================

        // Methods go here < snip>
        //=======================================================================
    }
}


Code: (csharp) [Select]
        //=======================================================================
        // add the block to the ActiveDrawing blockTable

        [CommandMethod("BI_1")]
        public void BlockInsert_1()
        {
            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg";
            string blockName = "3Dblock_A";
            Database tmpDb = new Database(false, true);
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");

            // add the block to the ActiveDrawing blockTable
            db.Insert(blockName, tmpDb, true);

            // add the block to the ActiveDrawing blockTable with a Temporary Name
            db.Insert("TmpTest", tmpDb, true);
        }
        //=======================================================================

Code: (csharp) [Select]
       //=======================================================================
        // add the block to the current space (Model or Paper).
        // block is exploded IE: copy of original
        // Insert will be at World 0,0,0 and transformed for Scale

        [CommandMethod("BI_2")]
        public void BlockInsert_2()
        {
            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg";
            double scale = 5.0;

            Database tmpDb = new Database(false, true);
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");

            Matrix3d Transform = Matrix3d.Identity;
            Transform = Transform *
                Matrix3d.Scaling(scale, Point3d.Origin);

            db.Insert(Transform, tmpDb, true);
        }
        //=======================================================================

Code: (csharp) [Select]
       //=======================================================================
        // add the block to the current space (Model or Paper).
        // block is exploded IE: copy of original
        // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
        // and transformed for Scale

        [CommandMethod("BI_3")]
        public void BlockInsert_3()
        {
            string blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg";
            double scale = 2.5;

            Database tmpDb = new Database(false, true);
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");

            Matrix3d Transform = ed.CurrentUserCoordinateSystem;
            Transform = Transform *
                Matrix3d.Scaling(scale, Point3d.Origin);

            db.Insert(Transform, tmpDb, true);
        }
        //=======================================================================

Code: (csharp) [Select]
       //=======================================================================
        // add the block to the current space (Model or Paper).
        // block is exploded IE: copy of original
        // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
        // and transformed for Scale
        // and transformed for Displacement
        // note that the nominated displacement will be scaled !!

        [CommandMethod("BI_4")]
        public void BlockInsert_4()
        {
            string blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg";
            double scale = 3.0;
            Vector3d DispacementVector = new Vector3d(20, 50, 0);
            //
            Database tmpDb = new Database(false, true);
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");

            Matrix3d Transform = ed.CurrentUserCoordinateSystem;

            Transform = Transform *
                Matrix3d.Scaling(scale, Point3d.Origin) *
                Matrix3d.Displacement(DispacementVector);

            db.Insert(Transform, tmpDb, true);
        }
        //=======================================================================

Code: (csharp) [Select]

       //=======================================================================
        // add the block to the current space (Model or Paper).
        // block is exploded IE: copy of original
        // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
        // and transformed for Scale
        // and transformed for Displacement
        // note that the nominated displacement will be honoured

        [CommandMethod("BI_5")]
        public void BlockInsert_5()
        {
            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_a.dwg";
            double scale = 3.0;
            Vector3d DispacementVector = new Vector3d(20, 50, 0);
            //
            Database tmpDb = new Database(false, true);
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");

            Matrix3d Transform = ed.CurrentUserCoordinateSystem;

            Transform = Transform *
                Matrix3d.Scaling(scale, Point3d.Origin) *
                Matrix3d.Displacement(DispacementVector / scale);

            db.Insert(Transform, tmpDb, true);
        }
        //=======================================================================

« Last Edit: December 18, 2011, 12:36:00 AM by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

gile

  • Water Moccasin
  • Posts: 2103
  • Marseille, France
Re: BlockTesting2011
« Reply #1 on: March 31, 2011, 01:45:12 AM »
Hi Kerry,

In the last code (honoured displacement), you can replace:

Code: (csharp) [Select]
Transform = Transform *
                Matrix3d.Scaling(scale, Point3d.Origin) *
                Matrix3d.Displacement(DispacementVector / scale);

with:

Code: (csharp) [Select]
Transform = Transform *
                Matrix3d.Displacement(DispacementVector) *
                Matrix3d.Scaling(scale, Point3d.Origin);

The Matrix3d multiplication operator (*) is equivalent to PostMultiplyBy that means transformations occur in reverse order : Scaling, then Displacement, then UCS rotation(s) and origin displacement.

Maybe it's more 'readable' to use the PreMultiplyBy method to write the transformations the same order they occur:

Code: (csharp) [Select]
Transform = Matrix3d
    .Scaling(scale, Point3d.Origin)
    .PreMultiplyBy(Matrix3d.Displacement(DispacementVector))
    .PreMultiplyBy(Transform);
« Last Edit: December 18, 2011, 12:36:55 AM by Kerry »
Speaking English as a French Frog

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11653
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #2 on: March 31, 2011, 03:09:48 AM »
Thanks gile, that's a better option ... and valuable information.
I had planned on doing some more investigation on the Transform but ran out of time :)

I'll update the Solution next time I post it.

Quote
Maybe it's more 'readable' to use the PreMultiplyBy method to write the transformations the same order they occur:

I think the PreMultiplyBy method will be better also
« Last Edit: March 31, 2011, 03:14:16 AM by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11653
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #3 on: March 31, 2011, 03:31:16 AM »
Thinking about it, this may be better ... but a little more difficult to debug ( if ever necessary) :)

Code: (csharp) [Select]


            // **remove** Matrix3d Transform = ed.CurrentUserCoordinateSystem;

            Matrix3d Transform = Matrix3d
                .Scaling(scale, Point3d.Origin)
                .PreMultiplyBy( Matrix3d.Displacement(DispacementVector))
                .PreMultiplyBy(ed.CurrentUserCoordinateSystem);

            db.Insert(Transform, tmpDb, true);

« Last Edit: December 18, 2011, 12:37:27 AM by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11653
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #4 on: March 31, 2011, 04:58:29 AM »
Next series :
Refer notations.

Transforms use PreMultiplyBy method as suggested by gile :)


Code: (csharp) [Select]
       //=======================================================================
        // add the block to the ActiveDrawing CurrentSpace
        // Expects to find the Block in the BlockTable
        // does not handle Attributes

        [CommandMethod("BI_10")]
        public void BlockInsert_10()
        {
            string blockName = "3Dblock";

            using( Transaction tr = db.TransactionManager.StartTransaction() ) {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                if( !bt.Has(blockName) ) {
                    ed.WriteMessage("\nBlock '{0}' is not available in the current drawing.", blockName);
                    return;
                }
                PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
                if( ppr.Status != PromptStatus.OK )
                    return;

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                BlockReference br = new BlockReference(Point3d.Origin, bt[ blockName ]);

                br.TransformBy(Matrix3d
                    .Displacement(ppr.Value - Point3d.Origin)
                    .PreMultiplyBy(ed.CurrentUserCoordinateSystem));

                btr.AppendEntity(br);
                tr.AddNewlyCreatedDBObject(br, true);
                tr.Commit();
            }
        }
        //=======================================================================

Code: (csharp) [Select]
       //=======================================================================
        // add the block to the ActiveDrawing CurrentSpace
        // Imports the Block if not found in the BlockTable
        // does not handle Attributes

        [CommandMethod("BI_11")]
        public void BlockInsert_11()
        {
            string blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg";
            string blockName = "3Dblock";

            using( Transaction tr = db.TransactionManager.StartTransaction() ) {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                if( !bt.Has(blockName) ) {
                    Database tmpDb = new Database(false, true);
                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
                    // add the block to the ActiveDrawing blockTable
                    db.Insert(blockName, tmpDb, true);
                }

                PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
                if( ppr.Status != PromptStatus.OK )
                    return;

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                BlockReference br = new BlockReference(Point3d.Origin, bt[ blockName ]);

                br.TransformBy(Matrix3d
                    .Displacement(ppr.Value - Point3d.Origin)
                    .PreMultiplyBy(ed.CurrentUserCoordinateSystem));

                btr.AppendEntity(br);
                tr.AddNewlyCreatedDBObject(br, true);
                tr.Commit();
            }
        }
        //=======================================================================
« Last Edit: December 18, 2011, 12:44:55 AM by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11653
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #5 on: March 31, 2011, 05:19:18 AM »
Next; Rotations with Displacement and Scale
.
Be carefull with the sequence for the PreMultiplyBy method
We usually do not want the  Displacement rotated.

If you DO want the displacement rotated swap the sequence of the Rotation and Displacement
Like this
Code: (csharp) [Select]

            Matrix3d Transform = Matrix3d
                .Scaling(scale, Point3d.Origin)               
                .PreMultiplyBy(Matrix3d.Displacement(DispacementVector))
                .PreMultiplyBy(Matrix3d.Rotation(rotation, zAxis, Point3d.Origin))               
                .PreMultiplyBy(ed.CurrentUserCoordinateSystem);


Code: (csharp) [Select]

        //=======================================================================
        public const double kPi = 3.14159265358979323846;
        //=======================================================================
        public static double RadiansToDegrees(double radians)
        {
            return (radians * (kPi / 180.0));
        }
        //=======================================================================

Code: (csharp) [Select]
       //=======================================================================
        // add the block to the current space (Model or Paper).
        // block is exploded IE: copy of original
        // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
        // and transformed for Scale
        // and transformed for Rotation
        // and transformed for Displacement
        // does not handle Attributes

        [CommandMethod("BI_6")]
        public void BlockInsert_6()
        {
            string blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg";
            double scale = 3.0;
            Vector3d DispacementVector = new Vector3d(-20, -50, 0);
            Vector3d zAxis = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;
            double rotation = RadiansToDegrees(15.0);
            //
            Database tmpDb = new Database(false, true);
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");

            Matrix3d Transform = Matrix3d
                .Scaling(scale, Point3d.Origin)
                .PreMultiplyBy(Matrix3d.Rotation(rotation, zAxis, Point3d.Origin))
                .PreMultiplyBy(Matrix3d.Displacement(DispacementVector))               
                .PreMultiplyBy(ed.CurrentUserCoordinateSystem);

            db.Insert(Transform, tmpDb, true);
        }
        //=======================================================================
« Last Edit: December 18, 2011, 12:45:34 AM by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11653
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #6 on: March 31, 2011, 07:34:23 PM »
Next Stage :
Inserting Attributes.

Updated Solution Zip added:

Library stuff:
Code: (csharp) [Select]
        //=======================================================================
        /// <summary>
        /// Insert ALL AttributeReferences from BlockTableRecord into BlockReference
        /// </summary>
        /// <param name="blkRef"></param>
        /// <param name="tr"></param>
        public static void InsertAttibuteInBlockRef(
            BlockReference blkRef,
            Transaction tr)
        {
            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead);
            foreach( ObjectId attId in btr ) {
                Entity ent = (Entity)tr.GetObject(attId, OpenMode.ForRead);
                if( ent is AttributeDefinition ) {
                    AttributeDefinition attDef = (AttributeDefinition)ent;
                    AttributeReference attRef = new AttributeReference();
                    attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform);
                    ObjectId id = blkRef.AttributeCollection.AppendAttribute(attRef);
                    tr.AddNewlyCreatedDBObject(attRef, true);
                }
            }
        }
        //=======================================================================
        /// <summary>
        ///  Insert ALL AttributeReferences from BlockTableRecord into BlockReference
        ///  Set the value of Attribute 'attributeTag' to 'attributeText'
        /// </summary>
        /// <param name="blkRef"></param>
        /// <param name="attributeTag"></param>
        /// <param name="attributeText"></param>
        /// <param name="tr"></param>
        public static void InsertAttibuteInBlockRef(
            BlockReference blkRef,
            string attributeTag,
            string attributeText,
            Transaction tr)
        {
            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead);
            foreach( ObjectId attId in btr ) {
                Entity ent = (Entity)tr.GetObject(attId, OpenMode.ForRead);
                if( ent is AttributeDefinition ) {
                    AttributeDefinition attDef = (AttributeDefinition)ent;
                    AttributeReference attRef = new AttributeReference();
                    attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform);
                    if( attRef.Tag == attributeTag )
                        attRef.TextString = attributeText;
                    ObjectId id = blkRef.AttributeCollection.AppendAttribute(attRef);
                    tr.AddNewlyCreatedDBObject(attRef, true);
                }
            }
        }
        //=======================================================================


Test Routines:
Code: (csharp) [Select]
       //=======================================================================
        // add the block to the ActiveDrawing CurrentSpace
        // Imports the Block if not found in the BlockTable
        // Adds ALL AttributeReference to the BlockReference

        [CommandMethod("BI_15")]
        public void BlockInsert_15()
        {
            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg";
            string blockName = "3Dblock_A";

            using( Transaction tr = db.TransactionManager.StartTransaction() ) {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                if( !bt.Has(blockName) ) {
                    Database tmpDb = new Database(false, true);
                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
                    // add the block to the ActiveDrawing blockTable
                    db.Insert(blockName, tmpDb, true);
                }

                PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
                if( ppr.Status != PromptStatus.OK )
                    return;

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                using( BlockReference br = new BlockReference(Point3d.Origin, bt[ blockName ]) ) {
                    br.TransformBy(Matrix3d
                        .Displacement(ppr.Value - Point3d.Origin)
                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem));

                    btr.AppendEntity(br);
                    tr.AddNewlyCreatedDBObject(br, true);
                    //                   
                    InsertAttibuteInBlockRef(br, tr);
                }
                tr.Commit();
            }
        }
        //=======================================================================

Code: (csharp) [Select]
        //=======================================================================
        // add the block to the ActiveDrawing CurrentSpace
        // Imports the Block if not found in the BlockTable
        // Adds ALL AttributeReference to the BlockReference
        // Set the attributeText in a nominated

        [CommandMethod("BI_16")]
        public void BlockInsert_16()
        {
            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg";
            string blockName = "3Dblock_A";
            string attTag = "ATTRIBUTETAG";
            string attText = "Yes, we have no bananas";

            using( Transaction tr = db.TransactionManager.StartTransaction() ) {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                if( !bt.Has(blockName) ) {
                    Database tmpDb = new Database(false, true);
                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
                    // add the block to the ActiveDrawing blockTable
                    db.Insert(blockName, tmpDb, true);
                }

                PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
                if( ppr.Status != PromptStatus.OK )
                    return;

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                using( BlockReference br = new BlockReference(Point3d.Origin, bt[ blockName ]) ) {
                    br.TransformBy(Matrix3d
                        .Displacement(ppr.Value - Point3d.Origin)
                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem));

                    btr.AppendEntity(br);
                    tr.AddNewlyCreatedDBObject(br, true);
                    //                   
                    InsertAttibuteInBlockRef(br, attTag, attText, tr);
                }
                tr.Commit();
            }
        }
        //=======================================================================
« Last Edit: December 18, 2011, 12:46:16 AM by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

Jeff H

  • Needs a day job
  • Posts: 5880
Re: BlockTesting2011
« Reply #7 on: April 01, 2011, 07:47:27 PM »
Laying it out the same as Kerry.
You will notice the extra calls to DirectCast because
Option strict is on.

I used http://www.developerfusion.com/tools/convert/csharp-to-vb/ to check and did good job only messed up a couple of things.

I will attach zip in last post and update along with kerry.

Container:
Code: (vbnet) [Select]
'Option strict and explicit are turned on
'Code converted from C#
'Original C# code located  @ http://www.theswamp.org/index.php?topic=37686.0
'Check link in above line as code is posted for learning resource and likely to be updated.
'Please thank Kerry at above link
'If something is wrong it is probably error converting from C#

'CodeHimBelonga kdub@theSwamp 20110331


Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.Geometry
Imports Autodesk.AutoCAD.EditorInput
Imports Autodesk.AutoCAD.ApplicationServices.Application
Imports AcUtils = Autodesk.AutoCAD.Internal.Utils

<Assembly: CommandClass(GetType(KdubTesting.BlockTesting2011))>

    Namespace KdubTesting
        Public Class BlockTesting2011
            Private doc As Document
            Private db As Database
            Private ed As Editor

            Public Sub New()
                ActiveDoc = AcadApp.DocumentManager.MdiActiveDocument
            End Sub

            Private Property ActiveDoc() As Document
                Get
                    Return doc
                End Get

                Set(ByVal value As Document)
                    doc = value

                    If doc = Nothing Then
                        db = Nothing
                        ed = Nothing
                    Else
                        db = doc.Database
                        ed = doc.Editor
                    End If
                End Set

            End Property
            '=======================================================================

            ' Methods go here < snip>
            '=======================================================================
        End Class

    End Namespace

Code: (vbnet) [Select]

        <CommandMethod("BI_1")> _
        Public Sub BlockInsert_1()
            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_A.dwg"
            Dim blockName As String = "3Dblock_A"
            Dim tmpDb As New Database(False, True)
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")

            ' add the block to the ActiveDrawing blockTable
            db.Insert(blockName, tmpDb, True)

            ' add the block to the ActiveDrawing blockTable with a Temporary Name
            db.Insert("TmpTest", tmpDb, True)
        End Sub
Code: (vbnet) [Select]
'=======================================================================
        ' add the block to the current space (Model or Paper).
        ' block is exploded IE: copy of original
        ' Insert will be at World 0,0,0 and transformed for Scale

        <CommandMethod("BI_2")> _
        Public Sub BlockInsert_2()
            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_A.dwg"
            Dim scale As Double = 5.0

            Dim tmpDb As New Database(False, True)
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")

            Dim Transform As Matrix3d = Matrix3d.Scaling(scale, Point3d.Origin).PreMultiplyBy(Matrix3d.Identity)

            db.Insert(Transform, tmpDb, True)
        End Sub

Code: (vbnet) [Select]
'=======================================================================
        ' add the block to the current space (Model or Paper).
        ' block is exploded IE: copy of original
        ' Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
        ' and transformed for Scale

        <CommandMethod("BI_3")> _
        Public Sub BlockInsert_3()
            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock.dwg"
            Dim scale As Double = 2.5

            Dim tmpDb As New Database(False, True)
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")

            Dim Transform As Matrix3d = Matrix3d _
                .Scaling(scale, Point3d.Origin) _
                .PreMultiplyBy(ed.CurrentUserCoordinateSystem)

            db.Insert(Transform, tmpDb, True)
        End Sub
Code: (vbnet) [Select]
  '=======================================================================
        ' add the block to the current space (Model or Paper).
        ' block is exploded IE: copy of original
        ' Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
        ' and transformed for Scale
        ' and transformed for Displacement

        <CommandMethod("BI_4")> _
        Public Sub BlockInsert_4()
            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock.dwg"
            Dim scale As Double = 3.0
            Dim DispacementVector As New Vector3d(20, 50, 0)
            '
            Dim tmpDb As New Database(False, True)
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")

            Dim Transform As Matrix3d = Matrix3d _
                                        .Scaling(scale, Point3d.Origin) _
                                        .PreMultiplyBy(Matrix3d.Displacement(DispacementVector)) _
                                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem)

            db.Insert(Transform, tmpDb, True)
        End Sub
Code: (vbnet) [Select]

        '=======================================================================
        ' add the block to the current space (Model or Paper).
        ' block is exploded IE: copy of original
        ' Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
        ' and transformed for Scale
        ' and transformed for Displacement

        <CommandMethod("BI_5")> _
        Public Sub BlockInsert_5()
            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_a.dwg"
            Dim scale As Double = 3.0
            Dim DispacementVector As New Vector3d(20, 50, 0)
            '
            Dim tmpDb As New Database(False, True)
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")

            Dim Transform As Matrix3d = Matrix3d _
                                        .Scaling(scale, Point3d.Origin) _
                                        .PreMultiplyBy(Matrix3d.Displacement(DispacementVector)) _
                                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem)

            db.Insert(Transform, tmpDb, True)
        End Sub
« Last Edit: January 25, 2012, 07:01:31 AM by Kerry »

Jeff H

  • Needs a day job
  • Posts: 5880
Re: BlockTesting2011
« Reply #8 on: April 01, 2011, 07:55:19 PM »
Next series :
Refer notations.

Transforms use PreMultiplyBy method as suggested by gile  :-)


Code: (vbnet) [Select]
  '=======================================================================

        '=======================================================================
        ' add the block to the ActiveDrawing CurrentSpace
        ' Expects to find the Block in the BlockTable
        ' does not handle Attributes

        <CommandMethod("BI_10")> _
        Public Sub BlockInsert_10()
            Dim blockName As String = "3Dblock"

            Using tr As Transaction = db.TransactionManager.StartTransaction()
                Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)

                If Not bt.Has(blockName) Then
                    ed.WriteMessage(vbLf & "Block '{0}' is not available in the current drawing.", blockName)
                    Return
                End If

                Dim ppr As PromptPointResult = ed.GetPoint(vbLf & "Specify insertion point: ")

                If ppr.Status <> PromptStatus.OK Then
                    Return
                End If

                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                Dim br As New BlockReference(Point3d.Origin, bt(blockName))

                br.TransformBy(Matrix3d.Displacement(ppr.Value - Point3d.Origin) _
                               .PreMultiplyBy(ed.CurrentUserCoordinateSystem))

                btr.AppendEntity(br)
                tr.AddNewlyCreatedDBObject(br, True)
                tr.Commit()

            End Using
        End Sub

Code: (vbnet) [Select]
'=======================================================================
        ' add the block to the ActiveDrawing CurrentSpace
        ' Imports the Block if not found in the BlockTable
        ' does not handle Attributes

        <CommandMethod("BI_11")> _
        Public Sub BlockInsert_11()

            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock.dwg"
            Dim blockName As String = "3Dblock"

            Using tr As Transaction = db.TransactionManager.StartTransaction()
                Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)

                If Not bt.Has(blockName) Then
                    Dim tmpDb As New Database(False, True)
                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
                    ' add the block to the ActiveDrawing blockTable
                    db.Insert(blockName, tmpDb, True)
                End If

                Dim ppr As PromptPointResult = ed.GetPoint(vbLf & "Specify insertion point: ")

                If ppr.Status <> PromptStatus.OK Then
                    Return
                End If

                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                Dim br As New BlockReference(Point3d.Origin, bt(blockName))

                br.TransformBy(Matrix3d.Displacement(ppr.Value - Point3d.Origin) _
                               .PreMultiplyBy(ed.CurrentUserCoordinateSystem))

                btr.AppendEntity(br)
                tr.AddNewlyCreatedDBObject(br, True)
                tr.Commit()

            End Using
        End Sub



Rotations with Displacement and Scale
.
Be carefull with the sequence for the PreMultiplyBy method
We usually do not want the  Displacement rotated.

If you DO want the displacement rotated swap the sequence of the Rotation and Displacement
Like this
Code: (vbnet) [Select]
            Dim Transform As Matrix3d = Matrix3d _
                                     .Scaling(scale, Point3d.Origin) _
                                     .PreMultiplyBy(Matrix3d.Displacement(DispacementVector)) _
                                     .PreMultiplyBy(Matrix3d.Rotation(rotation, zAxis, Point3d.Origin)) _
                                     .PreMultiplyBy(ed.CurrentUserCoordinateSystem)

            db.Insert(Transform, tmpDb, True)

Code: (vbnet) [Select]
        '=======================================================================
        Public Const kPi As Double = 3.1415926535897931
        '=======================================================================
        Public Shared Function RadiansToDegrees(ByVal radians As Double) As Double
            Return radians * (kPi / 180.0)
        End Function

Code: (vbnet) [Select]

        '=======================================================================
        '=======================================================================
        ' add the block to the current space (Model or Paper).
        ' block is exploded IE: copy of original
        ' Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
        ' and transformed for Scale
        ' and transformed for Rotation
        ' and transformed for Displacement
        ' does not handle Attributes

        <CommandMethod("BI_6")> _
        Public Sub BlockInsert_6()
            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock.dwg"
            Dim scale As Double = 3.0
            Dim DispacementVector As New Vector3d(-20, -50, 0)
            Dim zAxis As Vector3d = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis
            Dim rotation As Double = RadiansToDegrees(15.0)
            '
            Dim tmpDb As New Database(False, True)
            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")

            Dim Transform As Matrix3d = Matrix3d _
                                        .Scaling(scale, Point3d.Origin) _
                                        .PreMultiplyBy(Matrix3d.Rotation(rotation, zAxis, Point3d.Origin)) _
                                        .PreMultiplyBy(Matrix3d.Displacement(DispacementVector)) _
                                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem)

        End Sub
« Last Edit: January 25, 2012, 07:00:51 AM by Kerry »

Jeff H

  • Needs a day job
  • Posts: 5880
Re: BlockTesting2011
« Reply #9 on: April 01, 2011, 08:03:59 PM »
********************Edit***************
Solution Updated 4/4/2011
********************End Edit***************
Next Stage :
Inserting Attributes.

Solution Zip added for everything posted:
Library stuff:
Code: (vbnet) [Select]
        '=======================================================================
        '=======================================================================
        ''' <summary>
        ''' Insert ALL AttributeReferences from BlockTableRecord into BlockReference
        ''' </summary>
        ''' <param name="blkRef"></param>
        ''' <param name="tr"></param>
        Public Shared Sub InsertAttibuteInBlockRef(blkRef As BlockReference, tr As Transaction)
            Dim btr As BlockTableRecord = DirectCast(tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead), BlockTableRecord)

            For Each attId As ObjectId In btr
                Dim ent As Entity = DirectCast(tr.GetObject(attId, OpenMode.ForRead), Entity)

                If TypeOf ent Is AttributeDefinition Then

                    Dim attDef As AttributeDefinition = DirectCast(ent, AttributeDefinition)
                    Dim attRef As New AttributeReference()

                    attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform)

                    Dim id As ObjectId = blkRef.AttributeCollection.AppendAttribute(attRef)
                    tr.AddNewlyCreatedDBObject(attRef, True)

                End If

            Next

        End Sub

        '=======================================================================
        ''' <summary>
        '''  Insert ALL AttributeReferences from BlockTableRecord into BlockReference
        '''  Set the value of Attribute 'attributeTag' to 'attributeText'
        ''' </summary>
        ''' <param name="blkRef"></param>
        ''' <param name="attributeTag"></param>
        ''' <param name="attributeText"></param>
        ''' <param name="tr"></param>
        Public Shared Sub InsertAttibuteInBlockRef(blkRef As BlockReference, attributeTag As String, attributeText As String, tr As Transaction)

            Dim btr As BlockTableRecord = DirectCast(tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead), BlockTableRecord)

            For Each attId As ObjectId In btr
                Dim ent As Entity = DirectCast(tr.GetObject(attId, OpenMode.ForRead), Entity)

                If TypeOf ent Is AttributeDefinition Then

                    Dim attDef As AttributeDefinition = DirectCast(ent, AttributeDefinition)
                    Dim attRef As New AttributeReference()
                    attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform)

                    If attRef.Tag = attributeTag Then
                        attRef.TextString = attributeText
                    End If

                    Dim id As ObjectId = blkRef.AttributeCollection.AppendAttribute(attRef)
                    tr.AddNewlyCreatedDBObject(attRef, True)

                End If

            Next

        End Sub


Test Routines:
Code: (vbnet) [Select]
        '=======================================================================
        '=======================================================================
        ' add the block to the ActiveDrawing CurrentSpace
        ' Imports the Block if not found in the BlockTable
        ' Adds ALL AttributeReference to the BlockReference

        <CommandMethod("BI_15")> _
        Public Sub BlockInsert_15()

            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_A.dwg"
            Dim blockName As String = "3Dblock_A"

            Using tr As Transaction = db.TransactionManager.StartTransaction()

                Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)

                If Not bt.Has(blockName) Then
                    Dim tmpDb As New Database(False, True)
                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
                    ' add the block to the ActiveDrawing blockTable
                    db.Insert(blockName, tmpDb, True)
                End If

                Dim ppr As PromptPointResult = ed.GetPoint(vbLf & "Specify insertion point: ")

                If ppr.Status <> PromptStatus.OK Then
                    Return
                End If

                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)

                Using br As New BlockReference(Point3d.Origin, bt(blockName))
                    br.TransformBy(Matrix3d.Displacement(ppr.Value - Point3d.Origin).PreMultiplyBy(ed.CurrentUserCoordinateSystem))

                    btr.AppendEntity(br)
                    tr.AddNewlyCreatedDBObject(br, True)
                    '                   
                    InsertAttibuteInBlockRef(br, tr)
                End Using

                tr.Commit()
            End Using
        End Sub

Code: (vbnet) [Select]
        '=======================================================================
        ' add the block to the ActiveDrawing CurrentSpace
        ' Imports the Block if not found in the BlockTable
        ' Adds ALL AttributeReference to the BlockReference
        ' Set the attributeText in a nominated

        <CommandMethod("BI_16")> _
        Public Sub BlockInsert_16()

            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_A.dwg"
            Dim blockName As String = "3Dblock_A"
            Dim attTag As String = "ATTRIBUTETAG"
            Dim attText As String = "Yes, we have no bananas"

            Using tr As Transaction = db.TransactionManager.StartTransaction()

                Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)

                If Not bt.Has(blockName) Then
                    Dim tmpDb As New Database(False, True)
                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
                    ' add the block to the ActiveDrawing blockTable
                    db.Insert(blockName, tmpDb, True)
                End If

                Dim ppr As PromptPointResult = ed.GetPoint(vbLf & "Specify insertion point: ")

                If ppr.Status <> PromptStatus.OK Then
                    Return
                End If

                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)

                Using br As New BlockReference(Point3d.Origin, bt(blockName))
                    br.TransformBy(Matrix3d.Displacement(ppr.Value - Point3d.Origin).PreMultiplyBy(ed.CurrentUserCoordinateSystem))

                    btr.AppendEntity(br)
                    tr.AddNewlyCreatedDBObject(br, True)
                    '                   
                    InsertAttibuteInBlockRef(br, attTag, attText, tr)
                End Using

                tr.Commit()
            End Using

        End Sub
« Last Edit: January 25, 2012, 07:08:56 AM by Kerry »

gile

  • Water Moccasin
  • Posts: 2103
  • Marseille, France
Re: BlockTesting2011
« Reply #10 on: April 02, 2011, 12:34:22 PM »
Should I try a F# translation ?
Speaking English as a French Frog

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11653
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #11 on: April 02, 2011, 05:22:34 PM »

Sure gile.
I'm trying to concentrate on concepts not language so any 'language' questions that arise  can be split off this topic.

Regards,
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

gile

  • Water Moccasin
  • Posts: 2103
  • Marseille, France
Re: BlockTesting2011
« Reply #12 on: April 02, 2011, 06:09:59 PM »
So, here's a F# translation of  the C# code from the 'BlockTesting2011 _20110331.1115' source.
Maybe it's not 'very good' F# coding (I'm newby) but every command seems to work as expected (and it was a fine exercice).

If you don't use VS 2010 pro,
- to run the dll, you have to install the F# runtime.
- to play with F#, you can add F# to Visual Studio 2008 (Standard edition or greater) or use a free Visual Studio Shell (2008 or 2010) see here.

I'll post the code the same way as Kerry and Jeff H to make easier comparisons, just adding some 'off code' comments for F# main differences from C# or VB.

Container
No need to contain all functions in a class
Code: (fsharp) [Select]
// Code translated from C#
// Original C# code located  @ http://www.theswamp.org/index.php?topic=37686.0
// Check link in above line as code is posted for learning resource and likely to be updated.
// Please thank Kerry at above link

module KdubTesting.BlockTesting2011

open System
open System.IO
open Autodesk.AutoCAD.ApplicationServices
open Autodesk.AutoCAD.DatabaseServices
open Autodesk.AutoCAD.EditorInput
open Autodesk.AutoCAD.Geometry
open Autodesk.AutoCAD.Runtime

type AcAp = Autodesk.AutoCAD.ApplicationServices.Application
type AcUt = Autodesk.AutoCAD.Internal.Utils

let doc = AcAp.DocumentManager.MdiActiveDocument
let db = doc.Database
let ed = doc.Editor

// Functions go here
//=======================================================================

Code: (fsharp) [Select]
//=======================================================================
// add the block to the ActiveDrawing blockTable
[<CommandMethod("BI_1")>]
let blockInsert_1 () =
    let blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg"
    let blockName = "3DBlock_a"
   
    use tmpDb = new Database()
    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
   
    // add the block to the ActiveDrawing blockTable
    db.Insert(blockName, tmpDb, true) |> ignore
   
    // add the block to the ActiveDrawing blockTable with a Temporary Name
    db.Insert("TmpTest", tmpDb, true) |> ignore
//=======================================================================

Code: (fsharp) [Select]
//=======================================================================
// add the block to the current space (Model or Paper).
// block is exploded IE: copy of original
// Insert will be at World 0,0,0 and transformed for Scale
[<CommandMethod("BI_2")>]
let blockInsert_2 () =
    let blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg"
    let scale = 5.0
   
    use tmpDb = new Database()
    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
    let transform = Matrix3d.Scaling(scale, Point3d.Origin)
    db.Insert(transform, tmpDb, true)
//=======================================================================

The matrix multiplication uses 'pipe-lining' operator which looks like the PreMultiplyBy method
Code: (fsharp) [Select]
//=======================================================================
// add the block to the current space (Model or Paper).
// block is exploded IE: copy of original
// Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
// and transformed for Scale
[<CommandMethod("BI_3")>]
let blockInsert_3 () =
    let blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg"
    let scale = 2.5
   
    use tmpDb = new Database()
    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
    let transform = Matrix3d.Scaling(scale, Point3d.Origin)
                    |> (*) ed.CurrentUserCoordinateSystem
    db.Insert(transform, tmpDb, true)
//=======================================================================

Code: (fsharp) [Select]
//=======================================================================
// add the block to the current space (Model or Paper).
// block is exploded IE: copy of original
// Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
// and transformed for Scale
// and transformed for Displacement
[<CommandMethod("BI_4")>]
let blockInsert_4 () =
    let blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg"
    let scale = 3.0
    let dispacementVector = new Vector3d(20.0, 50.0, 0.0)
   
    use tmpDb = new Database()
    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
    let transform = Matrix3d.Scaling(scale, Point3d.Origin)
                    |> (*) (Matrix3d.Displacement(dispacementVector))
                    |> (*) ed.CurrentUserCoordinateSystem
    db.Insert(transform, tmpDb, true)
//=======================================================================

« Last Edit: January 25, 2012, 07:12:18 AM by Kerry »
Speaking English as a French Frog

gile

  • Water Moccasin
  • Posts: 2103
  • Marseille, France
Re: BlockTesting2011
« Reply #13 on: April 02, 2011, 06:15:51 PM »
Next; Rotations with Displacement and Scale

renamed RadiansToDegrees into degreesToRadians which seems more correct
Code: (fsharp) [Select]
//=======================================================================
let kPi = 3.14159265358979323846
//=======================================================================
let degreesToRadians degrees =
    degrees * (kPi / 180.0)
//=======================================================================

Code: (fsharp) [Select]
//=======================================================================
// add the block to the current space (Model or Paper).
// block is exploded IE: copy of original
// Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
// and transformed for Scale
// and transformed for Rotation
// and transformed for Displacement
// does not handle Attributes
[<CommandMethod("BI_6")>]
let blockInsert_6 () =
    let blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg"
    let scale = 3.0
    let dispacementVector = new Vector3d(-20.0, -50.0, 0.0)
    let zAxis = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis
    let rotation = degreesToRadians 15.0
   
    use tmpDb = new Database()
    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
    let transform = Matrix3d.Scaling(scale, Point3d.Origin)
                    |> (*) (Matrix3d.Rotation(rotation, zAxis, Point3d.Origin))
                    |> (*) (Matrix3d.Displacement(dispacementVector))
                    |> (*) ed.CurrentUserCoordinateSystem
    db.Insert(transform, tmpDb, true)
//=======================================================================
« Last Edit: January 25, 2012, 07:14:25 AM by Kerry »
Speaking English as a French Frog

gile

  • Water Moccasin
  • Posts: 2103
  • Marseille, France
Re: BlockTesting2011
« Reply #14 on: April 02, 2011, 06:18:21 PM »
Next series

Looking in the BlockTable

Code: (fsharp) [Select]
//=======================================================================
// add the block to the ActiveDrawing CurrentSpace
// Expects to find the Block in the BlockTable
// does not handle Attributes
[<CommandMethod("BI_10")>]
let blockInsert_10 () =
    let blockName = "3Dblock"
   
    use tr = db.TransactionManager.StartTransaction()
    let bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) :?> BlockTable
    if bt.Has(blockName) then
        let ppr = ed.GetPoint("\nSpecify insertion point: ")
        if ppr.Status = PromptStatus.OK then
            let btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) :?> BlockTableRecord
            let br = new BlockReference(Point3d.Origin, bt.[blockName])
            br.TransformBy(Matrix3d.Displacement(ppr.Value.GetAsVector())
                           |> (*) ed.CurrentUserCoordinateSystem)
            btr.AppendEntity(br) |> ignore
            tr.AddNewlyCreatedDBObject(br, true)
            tr.Commit()
    else
        ed.WriteMessage("\nBlock '{0}' is not available in the current drawing.", blockName)
//=======================================================================

Code: (fsharp) [Select]
//=======================================================================
// add the block to the ActiveDrawing CurrentSpace
// Imports the Block if not found in the BlockTable
// does not handle Attributes
[<CommandMethod("BI_11")>]
let blockInsert_11 () =
    let blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg"
    let blockName = "3Dblock"
   
    use tr = db.TransactionManager.StartTransaction()
    let bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) :?> BlockTable
    if not (bt.Has(blockName)) then
        use tmpDb = new Database()
        tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
        // add the block to the ActiveDrawing blockTable
        db.Insert(blockName, tmpDb, true) |> ignore
       
    let ppr = ed.GetPoint("\nSpecify insertion point: ")
    if ppr.Status = PromptStatus.OK then
        let btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) :?> BlockTableRecord
        let br = new BlockReference(Point3d.Origin, bt.[blockName])
        br.TransformBy(Matrix3d.Displacement(ppr.Value.GetAsVector())
                       |> (*) ed.CurrentUserCoordinateSystem)
        btr.AppendEntity(br) |> ignore
        tr.AddNewlyCreatedDBObject(br, true)
        tr.Commit()
//=======================================================================
« Last Edit: January 25, 2012, 07:18:28 AM by Kerry »
Speaking English as a French Frog