Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - fixo

Pages: 1 ... 7 8 [9]
121
Polylines / Label polyline areas with field
« on: May 18, 2012, 01:50:27 PM »
Code: [Select]
//----------------------------------------------------------------------------------------------//
        [CommandMethod("POLA", CommandFlags.Modal)]
        public void PolyAreas()
        {
            var doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            var db = doc.Database;
            var ed = doc.Editor;
            Matrix3d ucs = ed.CurrentUserCoordinateSystem;
           
            var sf = new SelectionFilter(new TypedValue[] { new TypedValue(0, "LWPOLYLINE"), new TypedValue(70, 1) });
            var pso = new PromptSelectionOptions();
            pso.MessageForAdding = "Select polylines (or enter for all): ";
            pso.AllowDuplicates = false;
            var psr = ed.GetSelection(pso, sf);
            // If nothing selected then select all
            if (psr.Status == PromptStatus.Error) psr = ed.SelectAll(sf);
            // make sure the selection isn't empty
            if (psr.Status == PromptStatus.OK && psr.Value.Count > 0)
            {
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    var btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    foreach (SelectedObject so in psr.Value)
                    {
                        var pline = (Polyline)tr.GetObject(so.ObjectId, OpenMode.ForRead);

                        Point3d cp = GetPseudoCentroid(db, pline).TransformBy(ucs);
                        string strObjId = pline.ObjectId.ToString();
                        strObjId = strObjId.Trim(new char[] { '(', ')' });
                        var mtx = new MText();
                        mtx.Contents = "%<\\AcObjProp Object(%<\\_ObjId " + strObjId + ">%).Area \\f \"%pr3%lu2%ct4%qf1 SQ. FT.\">%";
                        mtx.Location = cp;
                        mtx.Rotation = 0;
                        mtx.Attachment = AttachmentPoint.MiddleCenter;

                        btr.AppendEntity(mtx);
                        tr.AddNewlyCreatedDBObject(mtx, true);
                        tr.TransactionManager.QueueForGraphicsFlush();

                    }
                    doc.TransactionManager.FlushGraphics();
                    tr.Commit();
                    ed.Regen();
                }
            }
        }

        //----------------------------------------------------------------------------------------------//
        public Point3d GetPseudoCentroid(Database db, Polyline pline)
        {
            Point3d cpt = new Point3d();
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            try
            {
                using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction())
                {

                    Point3d maxp = pline.GeometricExtents.MaxPoint;
                    Point3d minp = pline.GeometricExtents.MinPoint;
                    cpt = new Point3d((maxp.X + minp.X) / 2, (maxp.Y + minp.Y) / 2, (maxp.Z + minp.Z) / 2);

                    tr.Commit();
                    return cpt;
                }
            }
            catch
            {
                // ed.WriteMessage("\nError on getting centroid");//debug only
                return cpt;
            }

        }

        //----------------------------------------------------------------------------------------------//

~'J'~

122
Math and Geometry / Circle by 3 points
« on: May 06, 2012, 01:14:55 PM »
Code: [Select]
        [CommandMethod("circ3p")]// This method can have any name
        public static void TestFor3PointCircle()
        {
            // Get the document and database
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            // If we have a valid point selection, get all 3 points
           PromptPointOptions ppo =   new PromptPointOptions("\nPick a point : ");
            ppo.AllowNone = true;
            PromptPointResult ppr;
                ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
            Point3d p1= ppr.Value;
            ppo =   new PromptPointOptions("\nPick a second point : ");
                 ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
            Point3d p2= ppr.Value;
                        ppo =   new PromptPointOptions("\nPick a third point : ");
                 ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
            Point3d p3= ppr.Value;
            // To pass center point by reference
            Point3d pc = new Point3d();
            // Get result
            bool result = CircleCenter(p1, p2, p3, out pc);
            if (result)
                ed.WriteMessage("\nCenter point calculated:\t{0:f3},{1:f3},{2:f3}", pc.X, pc.Y, pc.Z);
            else return;
            // Calculate radius
            double rad = pc.DistanceTo(p1);
            // Open transaction and add circle to the current space
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Circle circ = new Circle(pc, Vector3d.ZAxis, rad);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(circ);
                tr.AddNewlyCreatedDBObject(circ, true);
                // Commit transaction
                tr.Commit();
               
            }
         
        }

        public static bool CircleCenter(Point3d p0, Point3d pm, Point3d p1, out Point3d pc)
        {
            Vector3d v1 = p0 - pm;

            Vector3d v2 = p1 - pm;

            if (v1.IsParallelTo(v2))
            {
                pc = new Point3d();

                return false;
            }

            CircularArc3d crc = new CircularArc3d(p0, pm, p1);

            pc = crc.Center;

            return true;
        }

    }

Regards,

~'J'~

123
Dimensions / Some basic dimensions function
« on: May 01, 2012, 07:49:36 AM »
Code: [Select]
        Public Sub DrawRotDimension(ByVal db As Database, ByVal tr As Transaction, ByVal pt1 As Point3d, ByVal pt2 As Point3d, ByVal offset As Double, ByVal dimStyleName As String)

            Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
            Dim dtb As DimStyleTable = CType(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
            If Not dtb.Has(dimStyleName) Then Return
            Dim dtr As DimStyleTableRecord = CType(tr.GetObject(dtb(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)
            Dim ang As Double = AngleFromXAxis(pt1, pt2)
            Dim pt3 As Point3d = PolarPoint(pt2, ang + Math.PI / 2, offset)
            Dim odim As RotatedDimension = New RotatedDimension(ang, pt1, pt2, pt3, "<>", dtr.ObjectId)
            odim.SetDatabaseDefaults()
            ''change some properties of the dimension if it is needs here
            ''..........................................
            btr.AppendEntity(odim)
            tr.AddNewlyCreatedDBObject(odim, True)
            ' commit transaction or do it in the main program
            ' tr.Commit()
        End Sub

        Public Sub DrawAlignDimension(ByVal db As Database, ByVal tr As Transaction, ByVal pt1 As Point3d, ByVal pt2 As Point3d, ByVal pt3 As Point3d, ByVal dimStyleName As String)

            Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
            Dim dtb As DimStyleTable = CType(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
            If Not dtb.Has(dimStyleName) Then Return

            Dim dtr As DimStyleTableRecord = CType(tr.GetObject(dtb(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)
            Dim odim As AlignedDimension = New AlignedDimension(pt1, pt2, pt3, "", dtr.ObjectId)
            odim.SetDatabaseDefaults()
            ''change some properties of the dimension if it is needs here
            ''..........................................
            btr.AppendEntity(odim)
            tr.AddNewlyCreatedDBObject(odim, True)
            ' commit transaction or do it in the main program
            ' tr.Commit()
        End Sub

        Public Sub DrawLineAngDimension(ByVal db As Database, ByVal tr As Transaction, ByVal pt1 As Point3d, ByVal pt2 As Point3d, ByVal pt3 As Point3d, ByVal pt4 As Point3d, ByVal pt5 As Point3d, ByVal dimStyleName As String)

            Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
            Dim dtb As DimStyleTable = CType(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
            If Not dtb.Has(dimStyleName) Then Return

            Dim dtr As DimStyleTableRecord = CType(tr.GetObject(dtb(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)
            Dim adim As LineAngularDimension2 = New LineAngularDimension2(pt1, pt2, pt3, pt4, pt5, "", dtr.ObjectId)

            adim.SetDatabaseDefaults()
            ''change some properties of the dimension if it is needs here
            ''..........................................
            btr.AppendEntity(adim)
            tr.AddNewlyCreatedDBObject(adim, True)
            ' commit transaction or do it in the main program
            ' tr.Commit()
        End Sub

        Public Sub DrawOrdinateDimension(ByVal db As Database, ByVal tr As Transaction, isAxis As Boolean, ByVal pt1 As Point3d, ByVal pt2 As Point3d, ByVal dimStyleName As String)

            Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
            Dim dtb As DimStyleTable = CType(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
            If Not dtb.Has(dimStyleName) Then Return
            Dim dtr As DimStyleTableRecord = CType(tr.GetObject(dtb(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)

            Dim strdim As String = String.Format("{0:f3}\P{1:f3}", pt1.X, pt1.Y)
            Dim adim As OrdinateDimension = New OrdinateDimension(isAxis, pt1, pt2, strdim, dtr.ObjectId)

            adim.SetDatabaseDefaults()
            ''change some properties of the dimension if it is needs here
            ''..........................................
            btr.AppendEntity(adim)
            tr.AddNewlyCreatedDBObject(adim, True)
            ' commit transaction or do it in the main program
            ' tr.Commit()
        End Sub

        Public Sub DrawArcDimension(ByVal db As Database, ByVal tr As Transaction, ByVal cpt As Point3d, ByVal pt1 As Point3d, ByVal pt2 As Point3d, ByVal pt3 As Point3d, ByVal dimStyleName As String)

            Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
            Dim dtb As DimStyleTable = CType(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
            If Not dtb.Has(dimStyleName) Then Return

            Dim dtr As DimStyleTableRecord = CType(tr.GetObject(dtb(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)

            Dim adim As ArcDimension = New ArcDimension(cpt, pt1, pt2, pt3, "", dtr.ObjectId)
            adim.SetDatabaseDefaults()
            ''change some properties of the dimension if it is needs here
            ''..........................................
            btr.AppendEntity(adim)
            tr.AddNewlyCreatedDBObject(adim, True)
            ' commit transaction or do it in the main program
            ' tr.Commit()
        End Sub

        Public Sub DrawDiametricDimension(ByVal db As Database, ByVal tr As Transaction, ByVal pt1 As Point3d, ByVal pt2 As Point3d, ByVal leg As Double, ByVal dimStyleName As String)

            Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
            Dim dtb As DimStyleTable = CType(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
            If Not dtb.Has(dimStyleName) Then Return

            Dim dtr As DimStyleTableRecord = CType(tr.GetObject(dtb(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)
            Dim odim As DiametricDimension = New DiametricDimension(pt1, pt2, leg, "", dtr.ObjectId)
            odim.SetDatabaseDefaults()
            ''change some properties of the dimension if it is needs here
            ''..........................................
            btr.AppendEntity(odim)
            tr.AddNewlyCreatedDBObject(odim, True)
            ' commit transaction or do it in the main program
            ' tr.Commit()
        End Sub

        Public Sub DrawRadialDimension(ByVal db As Database, ByVal tr As Transaction, ByVal cpt As Point3d, ByVal pt1 As Point3d, ByVal leg As Double, ByVal dimStyleName As String)

            Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
            Dim dtb As DimStyleTable = CType(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
            If Not dtb.Has(dimStyleName) Then Return

            Dim dtr As DimStyleTableRecord = CType(tr.GetObject(dtb(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)
            Dim odim As RadialDimension = New RadialDimension(cpt, pt1, leg, "", dtr.ObjectId)

            odim.SetDatabaseDefaults()
            ''change some properties of the dimension if it is needs here
            ''..........................................
            btr.AppendEntity(odim)
            tr.AddNewlyCreatedDBObject(odim, True)
            ' commit transaction or do it in the main program
            ' tr.Commit()
        End Sub

        Public Sub DrawRadialDimensionLarge(ByVal db As Database, ByVal tr As Transaction, ByVal cpt As Point3d, ByVal pt1 As Point3d, ByVal pt2 As Point3d, ByVal pt3 As Point3d, ByVal ang As Double, ByVal dimStyleName As String)

            Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
            Dim dtb As DimStyleTable = CType(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
            If Not dtb.Has(dimStyleName) Then Return

            Dim dtr As DimStyleTableRecord = CType(tr.GetObject(dtb(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)
            Dim odim As RadialDimensionLarge = New RadialDimensionLarge(cpt, pt1, pt2, pt3, ang, "", dtr.ObjectId)

            odim.SetDatabaseDefaults()
            ''change some properties of the dimension if it is needs here
            ''..........................................
            btr.AppendEntity(odim)
            tr.AddNewlyCreatedDBObject(odim, True)
            ' commit transaction or do it in the main program
            ' tr.Commit()
        End Sub

        Public Sub DrawPoint3AngularDimension(ByVal db As Database, ByVal tr As Transaction, ByVal cpt As Point3d, ByVal pt1 As Point3d, ByVal pt2 As Point3d, ByVal pt3 As Point3d, ByVal dimStyleName As String)

            Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
            Dim dtb As DimStyleTable = CType(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
            If Not dtb.Has(dimStyleName) Then Return

            Dim dtr As DimStyleTableRecord = CType(tr.GetObject(dtb(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)
            Dim odim As Point3AngularDimension = New Point3AngularDimension(cpt, pt1, pt2, pt3, "", dtr.ObjectId)

            odim.SetDatabaseDefaults()
            ''change some properties of the dimension if it is needs here
            ''..........................................
            btr.AppendEntity(odim)
            tr.AddNewlyCreatedDBObject(odim, True)
            ' commit transaction or do it in the main program
            ' tr.Commit()
        End Sub


        '' published by Irvin on May 12, 2009 1:25 PM
        '' http://forums.autodesk.com/t5/NET/Set-current-textstyle/m-p/2485015/highlight/true#M14423
        '' (slightly edited)
        <CommandMethod("SetDimStlye")> _     
        Public Sub SetDimStyle(ByVal dimStyleName As String)
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Using trans As Transaction = db.TransactionManager.StartTransaction()
                Dim DimTbl As DimStyleTable = CType(trans.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
                If DimTbl.Has(dimStyleName) Then
                    Dim DimRecord As DimStyleTableRecord = CType(trans.GetObject(DimTbl(dimStyleName), OpenMode.ForRead), DimStyleTableRecord)
                    If DimRecord.ObjectId <> db.Dimstyle Then
                        db.Dimstyle = DimRecord.ObjectId
                        db.SetDimstyleData(DimRecord)
                    End If
                End If
                trans.Commit()
            End Using
            Dim dimstyleStr As String = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("dimstyle").ToString()
            ed.WriteMessage(vbCr & "Current Dimstyle now: {0}", dimstyleStr)
        End Sub

        <CommandMethod("GetDimStlye")> _
        Public Sub GetCurrDimStyle()
            Dim dimstyleStr As String = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("dimstyle").ToString()
            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("First method: " & dimstyleStr)
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim ed As Editor = doc.Editor
            Dim db As Database = doc.Database
            Using tr As Transaction = db.TransactionManager.StartTransaction()
                Dim dt As DimStyleTable = DirectCast(tr.GetObject(db.DimStyleTableId, OpenMode.ForRead), DimStyleTable)
                Dim id As ObjectId = db.Dimstyle
                Dim dr As DimStyleTableRecord = DirectCast(tr.GetObject(id, OpenMode.ForRead), DimStyleTableRecord)
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Second method: " & dr.Name)
            End Using
        End Sub


        <CommandMethod("ChangeDimStlye")> _
        Public Sub ChangeDimStlye()

            Dim doc As Document = Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Using tr As Transaction = db.TransactionManager.StartTransaction()

                Dim dimTbl As DimStyleTable = tr.GetObject(db.DimStyleTableId, OpenMode.ForRead)
                Dim dimDtr As DimStyleTableRecord = tr.GetObject(dimTbl("DimStyle1"), OpenMode.ForRead)
                Dim ids As ObjectIdCollection = dimDtr.GetPersistentReactorIds()
                For Each objId As ObjectId In ids

                    If objId.ObjectClass.IsDerivedFrom(RXClass.GetClass(GetType(Dimension))) Then

                        Dim dimen As Dimension = tr.GetObject(objId, OpenMode.ForWrite)
                        dimen.DimensionStyle = dimTbl("DimStyle2")
                        ''''' or
                        ''''''dimen.DimensionStyleName = "DimStyle2"
                    End If
                Next
                tr.Commit()
            End Using
        End Sub

        Public Shared Function GetPlineCoordinates(ByVal ent As Polyline) As Point3dCollection

            Dim pts As Point3dCollection = New Point3dCollection()
            Dim coord As Point3d
            Dim i As Integer = 0
            For i = 0 To ent.NumberOfVertices - 1
                coord = ent.GetPoint3dAt(i)
                pts.Add(coord)
            Next
            Return pts
        End Function

        Public Function Distance(ByVal fPoint As Point3d, ByVal sPoint As Point3d) As Double
            Dim x1, x2 As Double
            Dim y1, y2 As Double
            Dim z1, z2 As Double
            Dim cDist As Double
            x1 = fPoint.X : y1 = fPoint.Y : z1 = fPoint.Z
            x2 = sPoint.X : y2 = sPoint.Y : z2 = sPoint.Z
            cDist = Math.Sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2))
            Return cDist
        End Function

        '' by Tony Tanzillo
        Public Function AngleFromXAxis(ByVal p1 As Point3d, ByVal p2 As Point3d) As Double

            Return New Vector2d(p2.X - p1.X, p2.Y - p1.Y).Angle

        End Function

        '' by Tony Tanzillo
        Public Function PolarPoint(ByVal basepoint As Point3d, ByVal angle As Double, ByVal distance As Double) As Point3d
            Return New Point3d( _
            basepoint.X + (distance * Math.Cos(angle)), _
            basepoint.Y + (distance * Math.Sin(angle)), _
            basepoint.Z)
        End Function

        Public Shared Function GetFirstPoint(ed As Editor, msg As String, ByRef pt As Point3d) As Boolean
            pt = New Point3d()

            Dim opt As New PromptPointOptions(vbLf & msg)

            Dim res As PromptPointResult = ed.GetPoint(opt)

            If res.Status = PromptStatus.OK Then
                pt = res.Value

                Return True
            Else
                Return False
            End If
        End Function
     
        Public Shared Function GetNextPoint(ed As Editor, msg As String, frompt As Point3d, ByRef pt As Point3d) As Boolean

            Dim opt As New PromptPointOptions(vbLf & msg)

            opt.UseBasePoint = True

            opt.AllowNone = True

            opt.BasePoint = frompt

            Dim res As PromptPointResult = ed.GetPoint(opt)

            If res.Status = PromptStatus.OK Then
                pt = res.Value
                Return True
            Else
                Return False
            End If
        End Function

124
Blocks / Create block with attributes
« on: April 28, 2012, 09:59:25 AM »
Tested on A2009 only
Code: [Select]
         [CommandMethod("STATION")]
        public static void CreateStation()
        {
            // Get the current document and database
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;
            // Start a transaction
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);
                    string blkName = "STATION";
                    if (bt.Has(blkName))
                    {
                        ed.WriteMessage("\nBlock \"STATION\" already exist.");
                        return;
                    }
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    Point3d inspt = new Point3d(0, 0, 0);
                    BlockTableRecord newBtr = new BlockTableRecord();
                    bt.Add(newBtr);
                    newBtr.Name = blkName;
                    newBtr.Origin = inspt;
                    newBtr.BlockScaling = BlockScaling.Uniform;
                    newBtr.Units = UnitsValue.Inches;
                    newBtr.Explodable = true;
                    tr.AddNewlyCreatedDBObject(newBtr, true);
                    Line ln = new Line();
                    ln.StartPoint = new Point3d(0.5, 0, 0);
                    ln.EndPoint = new Point3d(12, 0, 0);

                    Circle circ = new Circle();
                    circ.Center = inspt;
                    circ.Radius = 0.5;

                    AttributeDefinition attr = new AttributeDefinition();
                    attr.Tag = "NUMBER";
                    attr.Prompt = "Station number:";
                    attr.TextString = "1";
                    attr.Verifiable = true;
                    attr.LockPositionInBlock = true;
                    //attr.TextStyle = db.Textstyle;//<--   A2009
                    attr.TextStyleId = db.Textstyle;//<--   A2010
                    attr.Height = 1.0;
                    attr.Position = new Point3d(6.0, 0.5, 0);
                    attr.AdjustAlignment(db);

                    newBtr.AppendEntity(ln);
                    tr.AddNewlyCreatedDBObject(ln, true);

                    newBtr.AppendEntity(circ);
                    tr.AddNewlyCreatedDBObject(circ, true);

                    newBtr.AppendEntity(attr);
                    tr.AddNewlyCreatedDBObject(attr, true);


                    tr.Commit();
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
                }
            }
        }

~'J'~

125
Blocks / Re: how can i redefine a block
« on: April 16, 2012, 08:34:48 PM »
See if this is working for you
Code: [Select]
        [CommandMethod("BlockReplaceTest", "breplace", CommandFlags.Session | CommandFlags.Modal | CommandFlags.UsePickSet | CommandFlags.Redraw)]

        public void TestBlockReplaceByName()
        {
            // objects initializing
            Document doc = acadApp.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            try
            {
                using (doc.LockDocument())
                {
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        PromptStringOptions psto =
                            new PromptStringOptions("\nEnter a replacement block name: ");

                        psto.AllowSpaces = true;

                        psto.DefaultValue = "MyBlock";//old block

                        PromptResult stres;

                        stres = ed.GetString(psto);

                        if (stres.Status != PromptStatus.OK)
                            return;

                        string oldblock = stres.StringResult;

                        ed.WriteMessage("\nText Entered\t{0}", oldblock);

                        psto = new PromptStringOptions("\nEnter a block name to be replaced: ");

                        psto.AllowSpaces = true;

                        psto.DefaultValue = "NewBlock";//new block

                        stres = ed.GetString(psto);

                        if (stres.Status != PromptStatus.OK)

                            return;

                        string newblock = stres.StringResult;

                        BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                        if (!bt.Has(newblock)) return;

                        ObjectId newblkId = bt[newblock];

                        acadApp.SetSystemVariable("nomutt", 0);

                        TypedValue[] tvs = { new TypedValue(0, "insert"), new TypedValue(2, oldblock) };

                        SelectionFilter filt = new SelectionFilter(tvs);

                        PromptSelectionOptions pso = new PromptSelectionOptions();

                        pso.MessageForRemoval = "You must select the blocks only";

                        pso.MessageForAdding = "\nSelect replacement blocks: ";

                        ed.SelectionAdded += new SelectionAddedEventHandler(ed_SelectionAdded);

                        PromptSelectionResult res = ed.GetSelection(pso, filt);

                        if (res.Status != PromptStatus.OK) return;

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

                        SelectionSet sset = res.Value;

                        foreach (SelectedObject obj in sset)
                        {
                            Entity ent = (Entity)obj.ObjectId.GetObject(OpenMode.ForRead) as Entity;

                            BlockReference oldblk = ent as BlockReference;

                            Point3d ip = oldblk.Position;

                            Scale3d scl = oldblk.ScaleFactors;

                            double rot = oldblk.Rotation;

                            BlockReference newblk = new BlockReference(ip, newblkId);

                            newblk.SetPropertiesFrom(ent);

                            newblk.Rotation = rot;

                            newblk.ScaleFactors = scl;

                            btr.AppendEntity(newblk);

                            tr.AddNewlyCreatedDBObject(newblk, true);

                            ApplyAttributes(db, tr, newblk);

                            oldblk.UpgradeOpen();

                            oldblk.Erase();

                            oldblk.Dispose();

                        }

                        tr.Commit();
                    }

                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                acadApp.SetSystemVariable("nomutt", 1);

                ed.SelectionAdded -= ed_SelectionAdded;

            }

        }


        void ed_SelectionAdded(object sender, SelectionAddedEventArgs e)
        {
            ((Editor)sender).WriteMessage("\n\t{0} blocks to selection added", e.AddedObjects.Count);
        }


        public void ApplyAttributes(Database db, Transaction tr, BlockReference bref)
        {
            BlockTableRecord btrec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;

            if (btrec.HasAttributeDefinitions)
            {
                Autodesk.AutoCAD.DatabaseServices.AttributeCollection atcoll = bref.AttributeCollection;

                foreach (ObjectId subid in btrec)
                {
                    Entity ent = (Entity)subid.GetObject(OpenMode.ForRead);

                    AttributeDefinition attDef = ent as AttributeDefinition;

                    if (attDef != null)
                    {

                        AttributeReference attRef = new AttributeReference();

                        attRef.SetDatabaseDefaults();//optional

                        attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);

                        attRef.Position = attDef.Position.TransformBy(bref.BlockTransform);

                        attRef.Justify = attDef.Justify;
                        //must be added all other properties for right position, eg. alignment modes etc
                        attRef.Tag = attDef.Tag;

                        attRef.AdjustAlignment(db);

                        atcoll.AppendAttribute(attRef);

                        tr.AddNewlyCreatedDBObject(attRef, true);

                    }
                }

            }
        }

126
Blocks / Change attribute prompts
« on: March 13, 2012, 11:21:34 AM »
Code: [Select]
        [CommandMethod("CHPROMPTS")]
        static public void ChangePrompts()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockReference bref = tr.GetObject(ed.GetEntity("\nSelect block").ObjectId, OpenMode.ForRead) as BlockReference;

                    if (bref == null)
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Nothing or wrong object selected");
                        return;
                    }
                    BlockTable bt = (BlockTable)(tr.GetObject(db.BlockTableId, OpenMode.ForRead));
                    BlockTableRecord btrec = null;
                    if (bref.IsDynamicBlock)
                    {
                        btrec = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead, false) as BlockTableRecord;
                    }
                    else
                    {
                        btrec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead, false) as BlockTableRecord;
                    }

                    var adeftype = RXObject.GetClass(typeof(AttributeDefinition));

                    var tags =
                        (from ObjectId id in btrec
                         where id.ObjectClass.IsDerivedFrom(adeftype)
                         select (id.GetObject(OpenMode.ForRead, false) as AttributeDefinition).Tag).ToList<string>();

                    var prompts =
                        (from ObjectId id in btrec
                         where id.ObjectClass.IsDerivedFrom(adeftype)
                         select (id.GetObject(OpenMode.ForRead, false) as AttributeDefinition).Prompt).ToList<string>();

                    string info = "  ---   For info   ---\nUsed Tags / Prompts:\n----------------------\n";
                    for (int n = 0; n < tags.Count; n++)
                    {
                        info += tags[n] + "\t" + prompts[n] + "\n";
                    }

                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(info);

                    for (int n = 0; n < tags.Count; n++)
                    {
                        string newprompt = "";

                        string question =
                            ("\nEnter a new Prompt for tag [ " + tags[n] + " ] instead of [ " + prompts[n] + " ] (hit Enter to keep old value): ");
                        PromptStringOptions pso = new PromptStringOptions(question);
                        pso.AllowSpaces = true;

                        // to bypass empty input
                        try
                        {
                            newprompt = ed.GetString(pso).StringResult;
                        }
                        catch
                        {
                        }

                        if (newprompt != string.Empty)
                        {
                            AttributeDefinition attdef =
                                (from ObjectId id in btrec
                                 where ((id.ObjectClass.IsDerivedFrom(adeftype) &&
                                 (id.GetObject(OpenMode.ForRead, false) as AttributeDefinition).Tag == tags[n]))
                                 select id.GetObject(OpenMode.ForWrite, false)).First() as AttributeDefinition;
                            attdef.Prompt = newprompt;
                        }
                    }

                    tr.Commit();
                }

            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\n{0}\n{1}", ex.Message, ex.StackTrace);
            }
        }

~'J'~

127
Layers / Change layer of the selected objects to the target object layer
« on: February 17, 2012, 08:55:05 PM »
Code: [Select]
        <CommandMethod("MatchLayersByTarget", "MHL", CommandFlags.Modal Or CommandFlags.Transparent)> _
        Public Sub MatchLayerTest()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Dim how As Boolean = False
            Dim pso As PromptSelectionOptions = New PromptSelectionOptions()
            pso.MessageForRemoval = vbLf & "Nothing selected, please try again: "
            pso.MessageForAdding = vbLf & "Select objects to be changed"

            Dim psr As PromptSelectionResult = ed.GetSelection(pso)
            If psr.Status <> PromptStatus.OK Then
                Return
            End If

            Dim peo As New PromptEntityOptions(vbLf & "Select an object on the target layer: ")
            peo.AllowObjectOnLockedLayer = True

            Dim per As PromptEntityResult = ed.GetEntity(peo)
            If per.Status <> PromptStatus.OK Then
                Return
            End If
            Try
                Using tr As Transaction = db.TransactionManager.StartTransaction()
                    Dim ent As Entity = TryCast(tr.GetObject(per.ObjectId, OpenMode.ForRead), Entity)
                    If ent Is Nothing Then
                        Return
                    End If
                    Dim lt As LayerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead)
                    Dim ltrIds As New ObjectIdCollection
                    Dim lname As String = ent.Layer
                    Dim lid As ObjectId = lt(lname)
                    Dim ltr As LayerTableRecord = TryCast(tr.GetObject(lid, OpenMode.ForWrite), LayerTableRecord)
                    If ltr.IsLocked Then
                        ltr.IsLocked = False
                        If Not ltrIds.Contains(lid) Then ltrIds.Add(lid)
                    End If
                    Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)


                    For Each selobj As SelectedObject In psr.Value
                        Dim sent As Entity = TryCast(tr.GetObject(selobj.ObjectId, OpenMode.ForRead), Entity)
                        If sent IsNot Nothing Then
                            sent.UpgradeOpen()

                            lid = lt(sent.Layer)
                            ltr = TryCast(tr.GetObject(lid, OpenMode.ForWrite), LayerTableRecord)
                            If ltr.IsLocked Then
                                ltr.IsLocked = False
                                If Not ltrIds.Contains(lid) Then ltrIds.Add(lid)
                            End If
                            sent.Layer = lname
                            sent.DowngradeOpen()
                        End If
                    Next
                    ''restore layer states
                    For Each lid In ltrIds
                        ltr = TryCast(tr.GetObject(lid, OpenMode.ForWrite), LayerTableRecord)
                        If Not ltr.IsLocked Then
                            ltr.IsLocked = True
                        End If
                    Next
                    tr.Commit()
                End Using
                how = True
            Catch ex As Autodesk.AutoCAD.Runtime.Exception
                ed.WriteMessage(ex.Message)
                how = False
            Finally
                Dim result As String = "   ---   The program has ended up with " + IIf(how, "success", "bugs").ToString
                ed.WriteMessage(vbLf + result)
            End Try
        End Sub

~'J'~

128
Tables / Re: Create simple table
« on: January 15, 2012, 02:43:09 PM »
You're quite welcome
Cheers, Gilles :)

129
Tables / Create simple table
« on: January 14, 2012, 09:54:14 PM »
There a few ways how to create table, the following one
is likes me more, probably it will be useful for somebody else
(Code written for AutoCAD 2010)

Code: [Select]
        [CommandMethod("CreatePlainTable")]
        public void CreateMyTable()
        {
            // based on code written by Kean Walmsley
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                Table tbl = new Table();
                tbl.TableStyle = db.Tablestyle;
                tbl.Position = ed.GetPoint("\nPick a point: ").Value;
                TableStyle ts = (TableStyle)tr.GetObject(tbl.TableStyle, OpenMode.ForRead);
                double textht = ts.TextHeight(RowType.DataRow);
                int rows = 10;
                int columns = 4;
                //insert rows
                tbl.InsertRows(1, textht * 2, rows);
                // insert columns
                tbl.InsertColumns(1, textht * 15, columns);// first column is already exist, thus we'll have 5 columns
                //create range to merge the cells in the first row
                CellRange range = CellRange.Create(tbl, 0,0, 0, columns);
                tbl.MergeCells(range);
                // set style for title row
                tbl.Cells[0, 0].Style = "Title";
                tbl.Cells[0, 0].TextString = "Title";

                tbl.Rows[0].Height = textht * 2;
                tbl.InsertRows(1, textht * 2, 1);
                // set style for header row
                tbl.Rows[1].Style = "Header";
                tbl.Rows[1].Height = textht * 1.5;
                //create contents in the first cell and set textstring
                tbl.Cells[1, 0].Contents.Add();
                tbl.Cells[1, 0].Contents[0].TextString = "Header #1";
                for (int c = 1; c <= columns; c++)
                {
                    //for all of the rest cells just set textstring (or value)
                    tbl.Cells[1, c].TextString = "Header  #" + (c + 1).ToString();
                }

                for (int r = 2; r < rows + 2; r++)//exact number of data rows + title row + header row
                {
                    // set style for data row
                    tbl.Rows[r].Style = "Data";
                    tbl.Rows[r].Height = textht * 1.25;
                    //create contents in the first cell and set textstring
                    tbl.Cells[r, 0].Contents.Add();
                    tbl.Cells[r, 0].Contents[0].TextString = "DataRow  #" + (r - 1).ToString() + " Col 1";
                    for (int c = 1; c <= columns; c++)
                    {
                        //for all of the rest cells just set textstring (or value)
                        tbl.Cells[r, c].TextString = "DataRow  #" + (r - 1).ToString() + " Col " + (c + 1).ToString(); ;
                    }
                }
                // set equal column widths
                foreach (Column col in tbl.Columns)
                    col.Width = textht * 15;

                //change last column values just to show data formatting               
                // to set numeric values with precision of 3 decimals:
                // create DataTypeParameter object
                // set data type,set value, then data format for every cell:
               
                DataTypeParameter dtp = new DataTypeParameter();
                dtp.DataType = DataType.Double;
                dtp.UnitType = UnitType.Distance;  // or  UnitType.Unitless

                //populate column with dummy values:
                for (int r = 2; r < rows + 2; r++)//exact number of data rows + title row + header row 
                {
                    tbl.Cells[r, columns].Contents[0].DataType = dtp;
                    tbl.Cells[r, columns].Contents[0].Value = Math.Pow(Math.PI, 1.0 / r);
                    tbl.Cells[r, columns].Contents[0].DataFormat = "%lu2%pr3%th44";//or "%lu2%pr3%"
                }
                tbl.GenerateLayout();
                btr.AppendEntity(tbl);
                tr.AddNewlyCreatedDBObject(tbl, true);
                tr.Commit();
            }
        }

~'J'~

130
Text / Simple numbering suit with prefix
« on: January 07, 2012, 05:47:10 PM »
Code: [Select]
#region Imports

// Microsoft

using System;

using System.Collections.Generic;

using System.Text;

// Autodesk

using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.Geometry;
#endregion

[assembly: CommandClass(typeof(MyTextPlugin.TextCommands))]

namespace MyTextPlugin
{
    public class TextCommands
    {


        [CommandMethod("NumPrefix")]
        static public void NumberingWithPrefix()
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    PromptStringOptions pso = new PromptStringOptions("\nEnter a Prefix : ");
                    pso.AllowSpaces = true;
                    pso.UseDefaultValue = true;
                    pso.DefaultValue = "AB";
                    PromptResult res;
                    string pfx = string.Empty;
                    res = ed.GetString(pso);
                    if (res.Status == PromptStatus.OK)
                    {
                        pfx = res.StringResult;
                    }
                    if (res.Status == PromptStatus.None)
                    {
                        pfx = "AB";
                    }

                    int num = new Int32();
                    PromptIntegerOptions pio = new PromptIntegerOptions("");
                    pio.Message = "\nEnter a Starting Number: ";

                    // Restrict input to positive and non-negative or non-zero values
                    pio.AllowZero = false;
                    pio.AllowNegative = false;
                    // Add default value
                    pio.DefaultValue = 1;
                    // Allow user the empty input by press Enter key
                    pio.AllowNone = true;

                    // Get the value entered by the user
                    PromptIntegerResult ires = ed.GetInteger(pio);
                    if (ires.Status == PromptStatus.OK)
                    {

                        num = ires.Value;

                    }
                    if (ires.Status == PromptStatus.None)
                    {
                        num = 1;
                    }
                    int inc = new Int32();
                    pio = new PromptIntegerOptions("");
                    pio.Message = "\nEnter an Increment Number by: ";
                    // Restrict input to positive and non-negative or non-zero values
                    pio.AllowZero = false;
                    pio.AllowNegative = false;
                    // Add default value
                    pio.DefaultValue = 1;
                    // Allow user the empty input by press Enter key
                    pio.AllowNone = true;
                    // Get the value entered by the user
                    ires = ed.GetInteger(pio);
                    if (ires.Status == PromptStatus.OK)
                    {
                        inc = ires.Value;
                    }
                    if (ires.Status == PromptStatus.None)
                    {
                        inc = 1;
                    }
                    double hgt = new double();
                    PromptDoubleOptions pdo = new PromptDoubleOptions("\nEnter a Text Height: ");
                    pdo.AllowNone = true;
                    // Restrict input to positive and non-negative or non-zero values
                    pdo.AllowZero = false;
                    pdo.AllowNegative = false;
                    pdo.UseDefaultValue = true;
                    pdo.DefaultValue = 1.0; // may be db.Textsize or other default
                    pdo.Message = "\nEnter a text height: ";

                    PromptDoubleResult dres;
                    dres = ed.GetDouble(pdo);
                    if (dres.Status == PromptStatus.None)
                    {
                        hgt = 1.0;
                    }
                    if (dres.Status == PromptStatus.OK)
                    {

                        hgt = dres.Value;
                    }

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

                    Point3d pt = new Point3d();
                    Point3d npt = new Point3d();
                    bool first = GetFirstPoint(ed, "Select text location: ", out pt);
                    DBText txt = new DBText();
                    txt.SetDatabaseDefaults();

                    txt.Position = pt;
                    txt.Height = hgt;
                    txt.TextString = pfx + num.ToString();
                    //Set justification to middle center:
                    txt.VerticalMode = TextVerticalMode.TextVerticalMid;
                    txt.HorizontalMode = TextHorizontalMode.TextMid;
                    txt.AlignmentPoint = pt;
                    btr.AppendEntity(txt);
                    tr.AddNewlyCreatedDBObject(txt, true);
                    tr.TransactionManager.QueueForGraphicsFlush();
                    num += inc;
                    while (GetNextPoint(ed, "Select text location (or press Enter to Exit): ", pt, out npt))
                    {
                        txt = new DBText();
                        txt.SetDatabaseDefaults();

                        txt.Position = npt;
                        txt.Height = hgt;
                        txt.TextString = pfx + num.ToString();
                        //Set justification to middle center:
                        txt.VerticalMode = TextVerticalMode.TextVerticalMid;
                        txt.HorizontalMode = TextHorizontalMode.TextMid;
                        txt.AlignmentPoint = npt;
                        btr.AppendEntity(txt);
                        tr.AddNewlyCreatedDBObject(txt, true);
                        tr.TransactionManager.QueueForGraphicsFlush();
                        pt = npt;
                        num += inc;
                    }

                    tr.Commit();

                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("Error: ==>\n{0}\nTrace: ==>\n{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                //do whatever you need

            }

        }
        /// <summary>
        /// Custom getpoint function without base point
        /// </summary>
        /// <param name="ed">document editor</param>
        /// <param name="pt">Point3d, by reference</param>
        /// <returns>Return true if success</returns>
        public static bool GetFirstPoint(Editor ed, string msg, out Point3d pt)
        {
            pt = new Point3d();

            PromptPointOptions opt = new PromptPointOptions("\n" + msg);

            PromptPointResult res = ed.GetPoint(opt);

            if (res.Status == PromptStatus.OK)
            {
                pt = res.Value;

                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// Custom getpoint function with base point
        /// </summary>
        /// <param name="ed">document editor</param>
        /// <param name="msg">string, user prompt</param>
        /// <param name="frompt">Point3d, by value</param>
        /// <param name="pt">Point3d, by reference</param>
        /// <returns>Return true if succes</returns>
        public static bool GetNextPoint(Editor ed, string msg, Point3d frompt, out Point3d pt)
        {
            pt = new Point3d();

            PromptPointOptions opt = new PromptPointOptions("\n" + msg);

            opt.UseBasePoint = false;

            opt.UseDashedLine = false;

            opt.AllowNone = true;

            opt.BasePoint = frompt;

            PromptPointResult res = ed.GetPoint(opt);

            if (res.Status == PromptStatus.OK)
            {
                pt = res.Value;
                return true;
            }
            else
            {
                return false;
            }
        }
   }
}

131
Blocks / Re: Replace blocks by name
« on: January 04, 2012, 10:01:34 AM »
Glad if this working for you
Thanks,

132
Blocks / Replace blocks by name
« on: January 03, 2012, 10:30:54 PM »
Hope this framework would be useful for beginners

Code: [Select]
#region Imports

// Microsoft

using System;

using System.Collections.Generic;

using System.Text;

// Autodesk

using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.Geometry;
#endregion

[assembly: CommandClass(typeof(BlockCS.ReplaceCommands))]

namespace BlockCS
{
    public class ReplaceCommands
    {
        [CommandMethod("BlockReplaceTest", "breplace", CommandFlags.Session | CommandFlags.Modal | CommandFlags.UsePickSet | CommandFlags.Redraw)]

        public void TestBlockReplaceByName()
        {
            // objects initializing
            Document doc = acadApp.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            try
            {
                using (doc.LockDocument())
                {
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        PromptStringOptions psto =
                            new PromptStringOptions("\nEnter a replacement block name: ");

                        psto.AllowSpaces = true;

                        psto.DefaultValue = "MyBlock";//old block

                        PromptResult stres;

                        stres = ed.GetString(psto);

                        if (stres.Status != PromptStatus.OK)
                            return;

                        string oldblock = stres.StringResult;
                       
                        ed.WriteMessage("\nText Entered\t{0}", oldblock);

                        psto = new PromptStringOptions("\nEnter a block name to be replaced: ");

                        psto.AllowSpaces = true;

                        psto.DefaultValue = "NewBlock";//new block

                        stres = ed.GetString(psto);

                        if (stres.Status != PromptStatus.OK)

                            return;

                        string newblock = stres.StringResult;

                        BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                        if (!bt.Has(newblock)) return;

                        ObjectId newblkId = bt[newblock];

                        acadApp.SetSystemVariable("nomutt", 0);

                        TypedValue[] tvs = { new TypedValue(0, "insert"), new TypedValue(2, oldblock) };

                        SelectionFilter filt = new SelectionFilter(tvs);

                        PromptSelectionOptions pso = new PromptSelectionOptions();

                        pso.MessageForRemoval = "You must select the blocks only";

                        pso.MessageForAdding = "\nSelect replacement blocks: ";

                        ed.SelectionAdded += new SelectionAddedEventHandler(ed_SelectionAdded);

                        PromptSelectionResult res = ed.GetSelection(pso, filt);



                        if (res.Status != PromptStatus.OK) return;

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

                        SelectionSet sset = res.Value;

                        foreach (SelectedObject obj in sset)
                        {
                            Entity ent = (Entity)obj.ObjectId.GetObject(OpenMode.ForRead) as Entity;

                            BlockReference oldblk = ent as BlockReference;

                            Point3d ip = oldblk.Position;

                            Scale3d scl = oldblk.ScaleFactors;

                            double rot = oldblk.Rotation;

                            BlockReference newblk = new BlockReference(ip, newblkId);

                            newblk.SetPropertiesFrom(ent);

                            newblk.Rotation = rot;

                            newblk.ScaleFactors = scl;
                           
                            btr.AppendEntity(newblk);

                            tr.AddNewlyCreatedDBObject(newblk, true);

                            ApplyAttributes(db, tr, newblk);

                            oldblk.UpgradeOpen();

                            oldblk.Erase();

                            oldblk.Dispose();

                        }
                     
                        tr.Commit();
                    }

                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                acadApp.SetSystemVariable("nomutt", 1);

               ed.SelectionAdded -= ed_SelectionAdded;
 
            }

        }


        void ed_SelectionAdded(object sender, SelectionAddedEventArgs e)
        {
            ((Editor)sender).WriteMessage("\n\t{0} blocks to selection added", e.AddedObjects.Count);

        }


        public void ApplyAttributes(Database db, Transaction tr, BlockReference bref)
        {
            BlockTableRecord btrec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;

            if (btrec.HasAttributeDefinitions)
            {
                Autodesk.AutoCAD.DatabaseServices.AttributeCollection atcoll = bref.AttributeCollection;

                foreach (ObjectId subid in btrec)
                {
                    Entity ent = (Entity)subid.GetObject(OpenMode.ForRead);

                    AttributeDefinition attDef = ent as AttributeDefinition;

                    if (attDef != null)
                    {

                        AttributeReference attRef = new AttributeReference();

                        attRef.SetDatabaseDefaults();//optional

                        attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);

                        attRef.Position = attDef.Position.TransformBy(bref.BlockTransform);

                        attRef.Tag = attDef.Tag;

                        attRef.AdjustAlignment(db);

                        atcoll.AppendAttribute(attRef);

                        tr.AddNewlyCreatedDBObject(attRef, true);

                    }
                }

            }
        }
    }
}

133
.NET newbies / Re: Hi. reciving location info about objects
« on: June 23, 2011, 08:58:59 PM »
 Try this code

 
Code: [Select]
      [CommandMethod("txtdata", CommandFlags.Modal | CommandFlags.UsePickSet)]
        public void TextDataExtraction()
          {
              StringBuilder sb = new StringBuilder();
              List<string[]> data = new List<string[]>();
            // get active drawing
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            // get document editor
            Editor ed = doc.Editor;
            // build selection filter , put layers you need, separated by commas
            //SelectionFilter sfilter= new SelectionFilter(new TypedValue[]{new TypedValue(0,"text"),new TypedValue(8,"Layer1,Layer2,Layer999")});
            // to select all text on all alyers you have to elimminate second typedvalue from filter:
            SelectionFilter sfilter = new SelectionFilter(new TypedValue[] { new TypedValue(0, "text") });
            // request for objects to be selected in the whole drawing
            PromptSelectionResult res = ed.SelectAll(sfilter);
            try
            {
                //check on valid selection result
                if (res.Status == PromptStatus.OK)
                {
                    //get object transaction
                    using (Transaction tr = doc.TransactionManager.StartTransaction())
                    {
                        foreach (ObjectId id in res.Value.GetObjectIds())
                        {
                            Entity ent = tr.GetObject(id, OpenMode.ForRead, false) as Entity;

                            DBText txt = ent as DBText;

                            if (txt != null)
                            {
                                //if text has an empty string it will be replaced with "---"
                                string record = string.Format("{0}\t{1:f2}\t{2:f2}\n", txt.TextString == "" ? "---" : txt.TextString, txt.Position.X, txt.Position.Y);
                                //add record to string builder
                                sb.Append(record);
                                string[] item = new string[3];
                                item[0] = txt.TextString == "" ? "---" : txt.TextString;//<--- if text has an empty string it will be replaced with "---"
                                item[1] = string.Format("{0:f3}", txt.Position.X);//<--- precision 3 decimals
                                item[2] = string.Format("{0:f3}", txt.Position.Y);//<--- precision 3 decimals
                                data.Add(item);
                            }
                        }

                        //write data to CSV file
                        using (StreamWriter sw = new StreamWriter(@"C:\Test\TextRecords.csv")) //<---change file name here
                        {

                                foreach ( string[] record in data)
                            {
                                // create tab delimited string
                                string line = string.Format("{0}\t{1:f2}\t{2:f2}", record[0], record[1], record[2]);
                                sw.WriteLine(line);

                            }
                            sw.Close();
                        }


                        tr.Commit();
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\n" + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
            }
        }

134
Windows forms / Binding ListBox With ComboBox programmaticlly
« on: January 22, 2011, 01:37:28 PM »
Attached is a quick example how to do it easily

Enjoy!

135
This site / Re: Welcome on the AutoCAD .NET developpers forums
« on: December 02, 2010, 11:00:31 PM »
Hi there
my name is Oleg
I'm an old stupid programmer hobbyist nothing else  :sourire:

Pages: 1 ... 7 8 [9]