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 ... 4 5 [6] 7 8 9
76
Text / Create field by picked point coordinate
« on: July 21, 2012, 09:11:34 AM »
 
Code: [Select]
       [CommandMethod("FieldPointLocation", "fpl", CommandFlags.Redraw | CommandFlags.Modal)]
        public static void SetField()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            // Set snap to whatever you need:
            //  Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 1);
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Point3d pt = ed.GetPoint("\nPick field location: ").Value;
                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("lastpoint", pt);
                Field fieldobj = new Field();
                fieldobj.EvaluationOption = FieldEvaluationOptions.Automatic;
                fieldobj.SetFieldCode("%<\\AcVar lastpoint \\f \"%lu2%pt3%ls59%pr3\">%");// decimal, separator semicolon,presicion 3
                //fieldobj.SetFieldCode("%<\\AcVar lastpoint \\f \"%lu4%pt3\">%");// architectural, separator comma, precision 1/8"
                MText mtextobj = new MText();
                mtextobj.SetDatabaseDefaults();
                mtextobj.SetField("Text", fieldobj);
                fieldobj.Evaluate(0, db);
                mtextobj.Location = pt;
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(mtextobj);
                tr.AddNewlyCreatedDBObject(mtextobj, true);
                tr.Commit();
            }
        }

77
Polylines / Pline / pline intersections
« on: July 19, 2012, 04:01:19 PM »
 
Code: [Select]
       [CommandMethod("gi")]
        public void GetIntersections()
        {
            Database db = HostApplicationServices.WorkingDatabase;

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

            Editor ed = doc.Editor;

            Transaction tr = db.TransactionManager.StartTransaction();

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

                    PromptEntityOptions peo = new PromptEntityOptions("\nSelect a single polyline  >>");

                    peo.SetRejectMessage("\nSelected object might be of type polyline only >>");

                    peo.AddAllowedClass(typeof(Polyline), false);

                    PromptEntityResult res;

                    res = ed.GetEntity(peo);

                    if (res.Status != PromptStatus.OK)

                        return;

                    DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);

                    if (ent == null) return;

                    //Polyline poly = (Polyline)ent as Polyline;
                    Curve curv = ent as Curve;

                    DBObjectCollection pcurves = new DBObjectCollection();

                    curv.Explode(pcurves);
                    TypedValue[] values = new TypedValue[]
                     {
                        new TypedValue(0, "lwpolyline")
                        //might be added layer name to select curve:
                        //, new TypedValue(8, "mylayer")
                     };
                    SelectionFilter filter = new SelectionFilter(values);

                    Point3dCollection fence = new Point3dCollection();

                    double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                    // number of divisions along polyline to create fence selection
                    double step = leng / 256;// set number of steps to your suit

                    int num = Convert.ToInt32(leng / step);

                    int i = 0;

                    for (i = 0; i < num; i++)
                    {
                        Point3d pp = curv.GetPointAtDist(step * i);

                        fence.Add(curv.GetClosestPointTo(pp, false));
                    }

                    PromptSelectionResult selres = ed.SelectFence(fence, filter);

                    if (selres.Status != PromptStatus.OK) return;
                    Point3dCollection intpts = new Point3dCollection();
                   
                    DBObjectCollection qcurves = new DBObjectCollection();

                    foreach (SelectedObject selobj in selres.Value)
                    {
                        DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject;
                        if (selobj.ObjectId != curv.ObjectId)
                        {
                            DBObjectCollection icurves = new DBObjectCollection();
                            Curve icurv = obj as Curve;
                            icurv.Explode(icurves);
                            foreach (DBObject dbo in icurves)
                            {
                                if (!qcurves.Contains(dbo))
                                    qcurves.Add(dbo);
                            }
                        }

                    }
                    ed.WriteMessage("\n{0}", qcurves.Count);



                    int j = 0;
                    Point3dCollection polypts = new Point3dCollection();

                    for (i = 0; i < pcurves.Count; ++i)
                    {
                        for (j = 0; j < qcurves.Count; ++j)
                        {
                            Curve curve1 = pcurves[i] as Curve;

                            Curve curve2 = qcurves[j] as Curve;

                            Point3dCollection pts = new Point3dCollection();

                            curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, (int)IntPtr.Zero, (int)IntPtr.Zero);

                            foreach (Point3d pt in pts)
                            {
                                if (!polypts.Contains(pt))
                                    polypts.Add(pt);
                            }
                        }
                    }

                    Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional
                    // for debug only
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nNumber of Intersections: {0}", polypts.Count));
                    // test for visulization only
                    foreach (Point3d inspt in polypts)
                    {
                        Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt);
                        circ.ColorIndex = 1;
                        btr.AppendEntity(circ);
                        tr.AddNewlyCreatedDBObject(circ, true);

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

        }

~'J'~

78
Blocks / Get the real block name
« on: July 12, 2012, 07:55:14 AM »
    Assume to use transaction in this function as an argument

Code: [Select]
       //      get the real block name.        //
        static public string EffectiveName(Transaction tr, BlockReference bref)
        {
            BlockTableRecord btr = null;

            if ((bref.IsDynamicBlock) | (bref.Name.StartsWith("*U", StringComparison.InvariantCultureIgnoreCase)))
            {
                btr = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
            }
            else
            {
                btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
            }
            return btr.Name;
        }

~'J'~

79
Dimensions / Creating and using Multileader with attributed block
« on: July 08, 2012, 04:34:37 PM »
Code: [Select]
        [CommandMethod("testMleaderAttribute", "tma", CommandFlags.Modal)]
        public void MleaderAttribute()
        {

            object clay = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("clayer");

            object ccolor = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("cecolor");

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

            Editor ed = doc.Editor;

            Database db = doc.Database;
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

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

                    ObjectId blkid = ObjectId.Null;

                    if (!bt.Has("MleaderBlock"))// may have any name
                    {

                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("clayer", "0");

                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("cecolor", "bylayer");
                        BlockTableRecord lbtr = new BlockTableRecord();
                        lbtr.Name = "MleaderBlock";
                        lbtr.Origin = new Point3d(0, 0, 0);
                        lbtr.BlockScaling = BlockScaling.Uniform;
                        lbtr.Explodable = true;
                        lbtr.Units = UnitsValue.Inches;
                        // add BlockTableRecord to BlocTable
                        bt.UpgradeOpen();
                        blkid = bt.Add(lbtr);
                        tr.AddNewlyCreatedDBObject(lbtr, true);
                        // add objects to block
                        // add circle
                        Circle circle = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, 3);
                        lbtr.AppendEntity(circle);
                        tr.AddNewlyCreatedDBObject(circle, true);
                        // add attribute
                        AttributeDefinition attr = new AttributeDefinition();
                        attr.Tag = "NUMBER";// may have any name
                        attr.Prompt = "Axis number:";
                        attr.TextString = "1";

                        //attr.TextStyle = db.Textstyle;//<--   A2009
                        attr.TextStyleId = db.Textstyle;//<--   A2010
                        attr.Height = 1.0;
                        attr.Position = new Point3d(0, 0, 0);
                        attr.HorizontalMode = TextHorizontalMode.TextCenter;
                        attr.VerticalMode = TextVerticalMode.TextVerticalMid;
                        attr.LockPositionInBlock = true;
                        attr.AdjustAlignment(db);
                        lbtr.AppendEntity(attr);
                        tr.AddNewlyCreatedDBObject(attr, true);
                        // commented adding the mtext
                        //MText mText = new MText();
                        //mText.Contents = "test";
                        //Point3d mpt = new Point3d(0, 0, 0);
                        //mText.Location = mpt;
                        //mText.Attachment = AttachmentPoint.MiddleCenter;
                        //lbtr.AppendEntity(mText);
                        //tr.AddNewlyCreatedDBObject(mText, true);
                    }

                    blkid = bt["MleaderBlock"];
                    MLeader leader = new MLeader();
                    // set content type to Block
                    leader.ContentType = ContentType.BlockContent;
                    leader.BlockContentId = blkid;
                    // check if desired arrowblock exist
                    if (!bt.Has("_NONE"))
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", "_NONE");

                    }
                    leader.ArrowSymbolId = bt["_NONE"];
                    leader.ArrowSize = 0;
                    leader.DoglegLength = 0;
                    leader.LeaderLineType = LeaderType.StraightLeader;
                    // you can set coordinates using Getpoint instead
                    Point3d lpt = new Point3d(0, 0, 0);
                    Point3d npt = new Point3d(5, 5, 0);

                    leader.AddLeaderLine(lpt);
                    leader.SetVertex(0, 1, npt);

                    btr.AppendEntity(leader);
                    tr.AddNewlyCreatedDBObject(leader, true);
                    // leader insereted, go to attribute updating
                    if (!leader.IsWriteEnabled) leader.UpgradeOpen();
                    blkid = leader.BlockContentId;
                    BlockTableRecord mbtr = (BlockTableRecord)tr.GetObject(blkid, OpenMode.ForRead);

                    foreach (ObjectId atid in mbtr)
                    {
                        DBObject obj = tr.GetObject(atid, OpenMode.ForRead, false) as DBObject;

                        if (atid.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition))))
                        {
                            AttributeDefinition attdef = (AttributeDefinition)obj as AttributeDefinition;

                            if (attdef.Tag == "NUMBER") // check your existing tag
                            {
                                AttributeReference attref = leader.GetBlockAttribute(attdef.ObjectId);

                                if (!attref.IsWriteEnabled) attref.UpgradeOpen();
                                // add new attribute value
                                attref.TextString = ed.GetString("\nEnter the number: ").StringResult;

                                leader.SetBlockAttribute(attdef.ObjectId, attref);

                            }
                        }
                    }

                    leader.RecordGraphicsModified(true);

                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("clayer", clay);

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("cecolor", ccolor);
            }
        }

~'J'~

80
Tables / Change cell text width
« on: July 04, 2012, 03:31:21 PM »
Code: [Select]
        [CommandMethod("CellTextWidth","ctw", CommandFlags.Modal)]
        public static void setCellTextWidth()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            PromptEntityOptions opts = new PromptEntityOptions("\nSelect the table:");
            opts.SetRejectMessage("\nMust be the table only...");
            opts.AddAllowedClass(typeof(Table), true);
            PromptEntityResult res = ed.GetEntity(opts);
            if (res.Status != PromptStatus.OK) return;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBObject obj = tr.GetObject(res.ObjectId, OpenMode.ForRead, false) as DBObject;
                Table tbl = obj as Table;
                if (tbl == null) return;
                int row = 2;
                int colm =1;
                tbl.UpgradeOpen();
                AcadTable actbl = tbl.AcadObject as AcadTable;
                actbl.SetCellValueFromText(row, colm, "{\\W0.5;Text Width = 0.5}", AcParseOption.acPreserveMtextFormat);
                actbl.SetText(row + 1, colm + 1, "Text Width = 0.5");
                tr.Commit();
            }
        }

~'J'~

81
Tables / Change FlowDirection of table
« on: July 04, 2012, 02:14:01 PM »
Code: [Select]
     // By Virupaksha Aithal
        // http://adndevblog.typepad.com/autocad/2012/07/creating-table-with-flow-direction.html
        [CommandMethod("cta")]
        public static void FlowDirectionTest()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            Table table = new Table();
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                //  Get the table style Dictionary
                DBDictionary tsdict = (DBDictionary)tr.GetObject(db.TableStyleDictionaryId, OpenMode.ForRead);
                //  Get the table style ObjectId
                ObjectId styleId;
                styleId = tsdict.GetAt("Standard");
                // Set the table style Id
                table.TableStyle = styleId;
                // 5 row, 6 columns
                table.SetSize(5, 6);
                // Flow direction from bottom to top
                Autodesk.AutoCAD.DatabaseServices.FlowDirection flow = table.FlowDirection;
                flow = Autodesk.AutoCAD.DatabaseServices.FlowDirection.BottomToTop;
                // Generate the table layout based on the table style
                table.GenerateLayout();
                table.Position = Point3d.Origin;
                ObjectId modelId;
                modelId = SymbolUtilityServices.GetBlockModelSpaceId(db);
                BlockTableRecord btr = tr.GetObject(modelId, OpenMode.ForWrite) as BlockTableRecord;
                // Add to Database
                ObjectId objectId;
                objectId = btr.AppendEntity(table);
                tr.AddNewlyCreatedDBObject(table, true);
                // Commit transaction
                tr.Commit();
            }
        }

~'J'~

82
Polylines / Re: Label polyline areas with field
« on: June 30, 2012, 04:53:30 PM »
Mardy, try again please

Code: [Select]
        //----------------------------------------------------------------------------------------------//
                [CommandMethod("POLA", CommandFlags.Modal)]   
        public void PolyAreas()
                { 
                    Document  doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; 
                    Database  db = doc.Database;       
                    Editor  ed = doc.Editor;         
                    Matrix3d ucs = ed.CurrentUserCoordinateSystem;
                    SelectionFilter sf = new SelectionFilter(new TypedValue[] { new TypedValue(0, "LWPOLYLINE"), new TypedValue(70, 1) });
                    PromptSelectionOptions pso = new PromptSelectionOptions();       
                    pso.MessageForAdding = "Select polylines (or enter for all): ";   
                    pso.AllowDuplicates = false;
                    PromptSelectionResult 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 (Transaction tr = db.TransactionManager.StartTransaction()) 
                        {
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); 
                            foreach (SelectedObject so in psr.Value)     
                            {
                                Polyline 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[] { '(', ')' });
                                MText 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'~

83
Polylines / Re: Label polyline areas with field
« on: June 30, 2012, 04:43:13 PM »
Hi, Mardy,

Let my a time to try variables relatively to A2008,

~'J'~

84
Blocks / Insert block from container
« on: June 29, 2012, 10:12:31 PM »
       using System.IO;
------------------------------------
// based on code written by Fenton Webb
Code: [Select]
        [CommandMethod("insFrom")]
        public static void ExtBlockCopyTest()
        {
            ObjectId blkTblRecId = ObjectId.Null;
           // Change path of file and block name here
            InsertBlockFromContainer(@"C:\Test\TitleExample.dwg", "TITLEBLOCK", blkTblRecId);
        }



        public static void InsertBlockFromContainer(string Container, string blkName, ObjectId blkTblRecId)
        {
            // Find the file containing all the blocks

            if (!File.Exists(Container))
            {
                MessageBox.Show("Could not find file !");

                return;

            }

            // Read the database in memory

            Database sourceDb = new Database(false, true);

            sourceDb.ReadDwgFile(Container, FileOpenMode.OpenForReadAndAllShare, false, "");

            using (Transaction sourceTr = sourceDb.TransactionManager.StartTransaction())
            {
                // Find the ObjectId of the block we are interested in.

                BlockTable sourceBt = null;

                sourceBt = sourceTr.GetObject(sourceDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                ObjectId sourceBtId;

                BlockTableRecord sourceBtr = null;

                if (!sourceBt.Has(blkName))
                {

                    MessageBox.Show("Block not found !");

                    return;

                }

                sourceBtr = sourceTr.GetObject(sourceBt[blkName], OpenMode.ForRead) as BlockTableRecord;

                sourceBtId = sourceBtr.ObjectId;

                Database curDoc = HostApplicationServices.WorkingDatabase;

                Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;

                // Create a new block table record in the current database.
                using (Transaction tr = curDoc.TransactionManager.StartTransaction())
                {

                    BlockTable destBt = null;

                    destBt = tr.GetObject(curDoc.BlockTableId, OpenMode.ForRead) as BlockTable;

                    ObjectId destBtId = destBt.ObjectId;

                    // WBlockClone the BlockTable record to the current database

                    ObjectIdCollection idColl = new ObjectIdCollection();

                    idColl.Add(sourceBtId);

                    // ObjectId of the btr that we want to clone

                    IdMapping idMap = new IdMapping();

                    curDoc.WblockCloneObjects(idColl, destBtId, idMap, DuplicateRecordCloning.Ignore, false);

                    // Create an instance of the block

                    BlockTableRecord destBtr = null;

                    destBtr = tr.GetObject(destBt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                    ObjectId destBtrId;

                    destBtrId = destBt[blkName];

                    // Insert an instance of the block in point(0,0,0)
                    BlockReference bref = new BlockReference(Point3d.Origin, destBtrId);

                    destBtr.AppendEntity(bref);

                    tr.AddNewlyCreatedDBObject(bref, true);
                    // Check, then insert the attributes
                    BlockTableRecord btrec = null;

                    btrec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;

                    if (btrec.HasAttributeDefinitions)
                    {
                        foreach (ObjectId id in btrec)
                        {
                            AttributeDefinition atdef = tr.GetObject(id, OpenMode.ForRead) as AttributeDefinition;

                            if (atdef != null)
                            {
                                using (AttributeReference atref = new AttributeReference())
                                {
                                    atref.SetAttributeFromBlock(atdef, bref.BlockTransform);

                                    atref.Position = atdef.Position + bref.Position.GetAsVector();

                                    atref.TextString = atdef.TextString;

                                    bref.AttributeCollection.AppendAttribute(atref);

                                    tr.AddNewlyCreatedDBObject(atref, true);
                                }
                            }
                        }
                    }

                    tr.Commit();
                }

            }
        }

~'J'~

85
Hatching / Scale the hatch
« on: June 29, 2012, 05:45:14 PM »
Code: [Select]
        [CommandMethod("HatchScale","hsc", CommandFlags.Modal)]
        static public void HatchScaleHalf()
        {
            Entity en;

            Database db = acApp.DocumentManager.MdiActiveDocument.Database;

            Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;

            try
            {

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    double cursc = ed.GetDouble("\nEnter Hatch scale: ").Value;

                    ObjectId id = ed.GetEntity("\nSelect Hatch: ").ObjectId;

                    en = tr.GetObject(id, OpenMode.ForWrite, false) as Entity;

                    Hatch hatch = en as Hatch;

                    if (hatch != null)
                    {
                        HatchPatternType hp = hatch.PatternType;

                        string hpn = hatch.PatternName;

                        double scl = hatch.PatternScale;

                        if (!hatch.IsWriteEnabled) hatch.UpgradeOpen();

                        hatch.PatternScale = scl * cursc;

                        hatch.SetHatchPattern(hp, hpn);

                        hatch.EvaluateHatch(true);
                    }
                    else
                    {
                        ed.WriteMessage("\nIt is not hatch!");

                        return;
                    }
                    tr.Commit();

                    ed.UpdateScreen();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage(ex.ToString());
            }
        }

~'J'~

86
       
Code: [Select]
        // based on article by Wayne Brill
        // http://adndevblog.typepad.com/autocad/2012/06/use-getclosestpointto-and-onsegat-to-locate-a-polyline-vertex-near-a-point.html
        [CommandMethod("oseg")]
       public  static void TEST_PointOnPoly()
        {

                Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;

                Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;

                CoordinateSystem3d cs = ed.CurrentUserCoordinateSystem.CoordinateSystem3d;

                Plane plan = new Plane(Point3d.Origin, cs.Zaxis);

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 512);

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        Entity ename;

                        Point3d pt;

                        Point3d ptWcs;

                        PromptEntityOptions peo = new PromptEntityOptions("\nSelect Pline: ");

                        peo.SetRejectMessage("\nYou have to select LWPOLYLINE!");

                        peo.AddAllowedClass(typeof(Polyline), false);

                        PromptEntityResult res = ed.GetEntity(peo);

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

                        ObjectId id = res.ObjectId;

                        // Convert to WCS incase selection was made

                        // while in a UCS.

                        pt = res.PickedPoint;

                        // Transform from UCS to WCS

                        Matrix3d mat =

                          Matrix3d.AlignCoordinateSystem(

                            Point3d.Origin,

                            Vector3d.XAxis,

                            Vector3d.YAxis,

                            Vector3d.ZAxis,

                            cs.Origin,

                            cs.Xaxis,

                            cs.Yaxis,

                            cs.Zaxis

                          );

                        ptWcs = pt.TransformBy(mat);

                        ename = tr.GetObject(id, OpenMode.ForRead) as Entity;

                        Polyline pline = ename as Polyline;

                        if (pline == null)
                        {

                            ed.WriteMessage("\nSelected Entity is not a Polyline");

                            return;

                        }

                        Point3d clickpt = pline.GetClosestPointTo(ptWcs, false);

                        for (int c = 0; c < pline.NumberOfVertices; c++)
                        {

                            double segParam= new double();

                            // This is the test filter here...it uses the

                            // nifty API OnSegmentAt

                            if (pline.OnSegmentAt(c, clickpt.Convert2d(plan), segParam))
                            {

                                ed.WriteMessage("\nSelected Segment: {0} \n", c + 1);

                                break;

                            }

                        }
                        }

                        catch (System.Exception ex)
                        {

                           ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);

                        }

                    }

                }

~'J'~

87
Tables / Insert block in the current table
« on: June 28, 2012, 07:53:24 PM »
Code: [Select]
       <CommandMethod("BlockToTable", "btin", CommandFlags.Modal)> _
        Public Shared Sub TestBlockToTable()

            Dim ver As String = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("acadver").ToString().Substring(0, 2)

            Dim intver As Integer = Convert.ToInt32(ver)

            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

            Try
                Using tr As Transaction = db.TransactionManager.StartTransaction

                    Dim pso As PromptSelectionOptions = New PromptSelectionOptions

                    pso.MessageForRemoval = vbLf + "You have select the table only"

                    pso.MessageForAdding = vbLf + " Select the table: "

                    Dim entres As PromptSelectionResult

                    Dim sset As SelectionSet

                    Dim filt(0) As TypedValue

                    filt(0) = New TypedValue(DxfCode.Start, "ACAD_TABLE")

                    Dim selfilter As New SelectionFilter(filt)

                    entres = ed.GetSelection(pso, selfilter)

                    sset = entres.Value

                    If entres.Status <> PromptStatus.OK Then

                        ed.WriteMessage(vbLf + "Wrong selection!")

                        Return

                    End If

                    Dim tblid As ObjectId = entres.Value.GetObjectIds(0)

                    Dim obj As Entity = tr.GetObject(tblid, OpenMode.ForRead)

                    Dim atable As Table = TryCast(obj, Table)

                    Dim pio As PromptPointOptions = New PromptPointOptions(vbLf + "Pick a cell to insert block: ")

                    Dim pres As PromptPointResult = ed.GetPoint(pio)

                    If pres.Status <> PromptStatus.OK Then

                        ed.WriteMessage(vbLf + "Invalid point specification!")

                        Return

                    End If

                    Dim pt As Point3d = pres.Value

                    Dim peo As PromptEntityOptions = New PromptEntityOptions(vbLf + "Select the single block: ")

                    Dim res As PromptEntityResult = ed.GetEntity(peo)

                    If res.Status <> PromptStatus.OK Then

                        ed.WriteMessage(vbLf + "Wrong selection!")

                        Return

                    End If

                    Dim id As ObjectId = res.ObjectId

                    Dim ent As Entity = TryCast(tr.GetObject(id, OpenMode.ForRead), Entity)

                    If ent Is Nothing Then

                        ed.WriteMessage(vbLf + "Wrong object type selected!")

                        Return

                    End If

                    Dim bref As BlockReference = TryCast(ent, BlockReference)

                    If bref Is Nothing Then

                        ed.WriteMessage(vbLf + "Impossible to cast BlockReference from entity!")

                        Return

                    End If

                    Dim btrec As BlockTableRecord = DirectCast(tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead), BlockTableRecord)

                    Dim blkid As ObjectId = btrec.ObjectId

                    Dim hit As TableHitTestInfo = atable.HitTest(pt, Vector3d.ZAxis)

                    Dim i As Integer = hit.Row

                    Dim j As Integer = hit.Column

                    If Not atable.IsWriteEnabled Then atable.UpgradeOpen()
                    '' select appropriate syntax from code block below
                    If intver = 17 Then

                        atable.SetBlockTableRecordId(i, j, blkid, True)

                    End If

                    'If intver = 18 Then

                    '    Dim c As Cell = atable.Cells(i, j)
                    '    c.Contents.Add()
                    '  c.Contents.InsertAt(0);
                    '  c.Contents(0).BlockTableRecordId =  blockId;

                    'Else
                    '    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Change a syntax accordingly to the current version")

                    'End If

                    atable.RecomputeTableBlock(True)

                    how = True

                    tr.Commit()

                End Using

            Catch ex As Autodesk.AutoCAD.Runtime.Exception

                ed.WriteMessage(ex.Message + vbLf + ex.StackTrace)

                how = False

            Catch ex As System.Exception

                ed.WriteMessage(ex.Message + vbLf + ex.StackTrace)

                how = False

            Finally

                Dim result As String = "   ---   The program has ended up with " + IIf(how, "success", "bug").ToString

                ed.WriteMessage(vbLf + result)

            End Try

        End Sub

~'J'~

89
Text / Convert meters to inches
« on: June 25, 2012, 06:24:36 PM »
Code: [Select]
        [CommandMethod("metinch")]
        public static void ConvertMetersToInches()
        {

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

            var db = doc.Database;

            var ed = doc.Editor;

            var fact = UnitsConverter.GetConversionFactor(UnitsValue.Meters, UnitsValue.Inches);

            int decs = db.Dimdec;

            var sf = new SelectionFilter(new TypedValue[] { new TypedValue(0, "TEXT,MTEXT,INSERT") });

            var pso = new PromptSelectionOptions();

            pso.MessageForAdding = "Select texts / mtexts / blocks : ";

            pso.AllowDuplicates = false;

            var psr = ed.GetSelection(pso, sf);

            // make sure that the selection isn't empty
            if (psr.Status == PromptStatus.OK && psr.Value.Count > 0)
            {
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    foreach (SelectedObject so in psr.Value)
                    {
                        var ent = (Entity)tr.GetObject(so.ObjectId, OpenMode.ForRead);

                        if (ent == null) return;

                        if (ent.GetRXClass().DxfName == "TEXT")
                        {
                            var dtxt = ent as DBText;

                            var strval = dtxt.TextString;

                            double dim;

                            if (double.TryParse(strval, out dim))
                            {
                                dim = dim * fact;

                                if (!dtxt.IsWriteEnabled) dtxt.UpgradeOpen();

                                dtxt.TextString = Math.Round(dim, decs).ToString();
                            }
                        }
                        else if (ent.GetRXClass().DxfName == "MTEXT")
                        {
                            var mtxt = ent as MText;

                            var strval = mtxt.Contents;

                            double dim;

                            if (double.TryParse(strval, out dim))
                            {
                                dim = dim * fact;

                                if (!mtxt.IsWriteEnabled) mtxt.UpgradeOpen();

                                mtxt.Contents = Math.Round(dim, decs).ToString();
                            }
                        }
                        else if (ent.GetRXClass().DxfName == "INSERT")
                        {
                            var bref = ent as BlockReference;

                            if (!bref.IsWriteEnabled) bref.UpgradeOpen();

                            // process attributes here
                            var atts = bref.AttributeCollection;

                            // iterate through the list of attributes
                            foreach (ObjectId aid in atts)
                            {
                                var atref = tr.GetObject(aid, OpenMode.ForRead) as AttributeReference;

                                var strval = atref.TextString;

                                double dim;

                                if (double.TryParse(strval, out dim))
                                {
                                    dim = dim * fact;

                                    if (!atref.IsWriteEnabled) atref.UpgradeOpen();

                                    atref.TextString = Math.Round(dim, decs).ToString();
                                }
                            }
                        }
                    }
                    tr.Commit();
                }
            }
        }

~'J'~

90
External databases / Extract data from drawing to xml file
« on: June 25, 2012, 09:35:35 AM »
Code: [Select]
     Imports System
Imports System.Text
Imports System.IO
Imports System.Data
Imports System.Reflection
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Windows.Forms

Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.Geometry
Imports Autodesk.AutoCAD.Colors
Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.EditorInput
Imports Autodesk.AutoCAD.DataExtraction
''----------------------------------------------------------''
Example how to exract data into the .xml file in Debug folder
''----------------------------------------------------------''

  '' based on Kean Walmsley's example from there:
        '' http://through-the-interface.typepad.com/through_the_interface/2008/04/extracting-data.html
        <CommandMethod("exlines")> _
        Public Sub ExtractLines()
            Dim ed As Editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor
            Dim starttime As Double
            Dim endtime As Double

            Dim dialog As New System.Windows.Forms.OpenFileDialog

            With dialog
                .CheckPathExists = True
                .CheckPathExists = True
                .DefaultExt = "dxf"
                .DereferenceLinks = True
                .Multiselect = False
                .Filter = "Drawing (*.dwg)|*.dwg|All files (*.*)|*.*"
                .Title = "Select drawing"
                .FilterIndex = 1

            End With

            If dialog.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
                Return
            End If

            Dim fname As String = dialog.FileName

            starttime = DateAndTime.Timer

            Try

                ''------------------------------------------------------------------------------------------------------''
                ' following datatable easy to write to the any data file (Excel, Access, SQL etc)

                Dim dataTable As System.Data.DataTable = ExtractLines(fname)
                ''------------------------------------------------------------------------------------------------------''
                endtime = DateAndTime.Timer
                '' write data to Lines.xml in the Debug folder
               '' change the full path name of the file if you want to save it in other folder
                dataTable.WriteXml("Lines.xml")

                ed.WriteMessage(vbLf + "Elapsed time: {0:f4} seconds" + vbLf + "Found {1} objects" + vbLf, endtime - starttime, dataTable.Rows.Count)

            Catch ex As System.Exception
                MsgBox(vbCr & ex.ToString & vbCr & ex.StackTrace)
            End Try
            '' Display the  file
            Process.Start("lines.xml", Nothing)
        End Sub

        Public Function extractLines(ByVal fname As String) As System.Data.DataTable
            Dim dataTable As New System.Data.DataTable()
            Dim blkTable As New System.Data.DataTable()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument

            Dim ed As Editor = doc.Editor

            Dim tags As New List(Of String)()
            If Not System.IO.File.Exists(fname) Then
                ed.WriteMessage(vbLf & "Drawing file does not exist.")
                Return Nothing
                Exit Function
            End If
            Dim es As IDxExtractionSettings = New DxExtractionSettings()

            Dim de As IDxDrawingDataExtractor = es.DrawingDataExtractor

            de.Settings.ExtractFlags = ExtractFlags.None Or ExtractFlags.ModelSpaceOnly

            de.Settings.ExtractFlags = ExtractFlags.ExtractBlockOnly ''Or ExtractFlags.ModelSpaceOnly

            Dim fr As IDxFileReference = New DxFileReference(Path.GetDirectoryName(fname), fname)

            de.Settings.DrawingList.AddFile(fr)

            ' Scan the drawing for object types & their properties

            de.DiscoverTypesAndProperties(Path.GetDirectoryName(fname))

            Dim types As List(Of IDxTypeDescriptor) = de.DiscoveredTypesAndProperties

            ' Select all the types and properties for extraction

            ' by adding them one-by-one to these two lists

            Dim selTypes As New List(Of String)()

            Dim selProps As New List(Of String)()

            For Each type As IDxTypeDescriptor In types


                selTypes.Add(type.GlobalName)

                For Each pr As IDxPropertyDescriptor In type.Properties


                    If Not selProps.Contains(pr.GlobalName) Then


                        selProps.Add(pr.GlobalName)
                    End If

                Next
            Next

            de.Settings.SetSelectedTypesAndProperties(types, selTypes, selProps)

            ' Now perform the extraction itself

            de.ExtractData(Path.GetDirectoryName(fname))

            ' Get the results of the extraction

            dataTable = de.ExtractedData

            If dataTable.Rows.Count > 0 Then

                dataTable.TableName = "Lines"

                Dim selrows As DataRow() = dataTable.Select("AcDxObjectTypeGlobalName Like '%Line' Or AcDxObjectTypeGlobalName Like '%Text' Or AcDxObjectTypeGlobalName Like '%MText'")

                blkTable = dataTable.Clone()

                For Each dr As DataRow In selrows
                    blkTable.ImportRow(dr)
                Next
                '' commented lines is just for populating form listbox control
                'Dim columns As String() = New String() {"AcDxObjectTypeName"}

                'Dim dvw As DataView = blkTable.DefaultView
                'distinctTable = dvw.ToTable(False, columns)

                'Dim bnames As New List(Of String)()
                'For Each dr As System.Data.DataRow In distinctTable.Rows
                '    Dim bname As String = dr(0).ToString()
                '    If Not bnames.Contains(bname) Then
                '        bnames.Add(bname)
                '    End If
                'Next

                'Me.lst.DataSource = bnames'' <-- to fill ListBox only

                'lst.SelectedIndex = -1'' <-- set selected items to nothing
            End If

            Return blkTable
        End Function

~'J'~

Pages: 1 ... 4 5 [6] 7 8 9