예제 #1
0
        public void UsingPointOptionsAndResults()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            //Verify GetPoint has been ran once before executing this one
            if (useThisPointOption == null || useThisPointResult == null)
            {
                ed.WriteMessage("Please run GetPoint command first");
                return;
            }
            //Using the stored PromptPointOption.
            PromptPointResult res1 = ed.GetPoint(useThisPointOption);
            //Using the stored PromptPointResult.
            PromptPointResult res2 = useThisPointResult;

            if (res1.Status != PromptStatus.Cancel && res2.Status != PromptStatus.Cancel)
            {
                Point3d  start = res1.Value;
                Point3d  end   = res2.Value;
                Database db    = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
                using (Transaction myT = tm.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                    using (Line myline = new Line(start, end))
                    {
                        myline.ColorIndex = 3;
                        btr.AppendEntity(myline);
                        myT.AddNewlyCreatedDBObject(myline, true);
                    }
                    myT.Commit();
                }
            }
        }
예제 #2
0
        static public void DoIt()
        {
            Editor             ed   = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptPointOptions opts = new PromptPointOptions("\nEnter Ellipse Center Point:");
            PromptPointResult  res  = ed.GetPoint(opts);

            Vector3d x         = Application.DocumentManager.MdiActiveDocument.Database.Ucsxdir;
            Vector3d y         = Application.DocumentManager.MdiActiveDocument.Database.Ucsydir;
            Vector3d NormalVec = x.CrossProduct(y);


            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

            //Create Ellipsejig
            EllipseJig jig = new EllipseJig(res.Value, NormalVec.GetNormal());

            //first call drag to get the major axis
            jig.setPromptCounter(0);
            Application.DocumentManager.MdiActiveDocument.Editor.Drag(jig);
            // Again call drag to get minor axis
            jig.setPromptCounter(1);
            Application.DocumentManager.MdiActiveDocument.Editor.Drag(jig);

            //Append entity.
            using (Transaction myT = tm.StartTransaction())
            {
                BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                btr.AppendEntity(jig.GetEntity());
                tm.AddNewlyCreatedDBObject(jig.GetEntity(), true);
                myT.Commit();
            }
        }
예제 #3
0
        public static ArrayList GetLayoutIdList(Database db)
        {
            ArrayList layoutList = new ArrayList();

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm =
                db.TransactionManager;

            using (Transaction myT = tm.StartTransaction())
            {
                DBDictionary           dic   = (DBDictionary)tm.GetObject(db.LayoutDictionaryId, OpenMode.ForRead, false);
                DbDictionaryEnumerator index = dic.GetEnumerator();

                while (index.MoveNext())
                {
                    Layout acLayout = tm.GetObject(index.Current.Value,
                                                   OpenMode.ForRead) as Layout;
                    if (acLayout.LayoutName.Equals("model", StringComparison.InvariantCultureIgnoreCase) ||
                        acLayout.LayoutName.Equals("modal", StringComparison.InvariantCultureIgnoreCase))
                    {
                        layoutList.Add(index.Current.Value);
                    }
                }
                myT.Commit();
            }

            return(layoutList);
        }
예제 #4
0
        static public void Foo()
        {
            Document document = Application.DocumentManager.MdiActiveDocument;
            Database database = document.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager transactionManager = database.TransactionManager;
            using (Transaction transaction = transactionManager.StartTransaction())
            {
                document.Editor.WriteMessage("HOORAY\n");
                BlockTable       blockTable       = (BlockTable)transactionManager.GetObject(database.BlockTableId, OpenMode.ForRead, openErased: false);
                BlockTableRecord blockTableRecord = (BlockTableRecord)transactionManager.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                foreach (Autodesk.AutoCAD.DatabaseServices.ObjectId objectId in blockTableRecord)
                {
                    DBObject dbObject = objectId.GetObject(OpenMode.ForRead);
                    document.Editor.WriteMessage("type: " + dbObject.GetType() + "\n");
                    if (dbObject.GetType() == typeof(MLeader))
                    {
                        document.Editor.WriteMessage("We found a multileader.\n");
                        MLeader mLeader = (MLeader)dbObject;

                        // damn: the .net api does not expose the functions related to mleader style overrides.
                        //mLeader.isoverride(MLeader.PropertyOverrideType.kLeaderLineType);
                        //MLeader.setOverride(MLeader.PropertyOverrideType.kLeaderLineType, false);
                        //kLeaderLineType

                        //ErrorStatus result = setOverride(mLeader.UnmanagedObject, 16, false);

                        bool result = isOverride(mLeader.UnmanagedObject, 16);
                        document.Editor.WriteMessage("result: " + result + "\n");
                    }
                }
            }
        }
예제 #5
0
        public void DistanceTest()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptDistanceOptions opt1 = new PromptDistanceOptions("Enter the radius of the circle");

            opt1.AllowNegative = false;
            opt1.AllowZero     = false;
            opt1.AllowNone     = false;
            opt1.UseDashedLine = true;

            PromptDoubleResult res = ed.GetDistance(opt1);

            if (res.Status == PromptStatus.OK)
            {
                Point3d  center = new Point3d(9.0, 3.0, 0.0);
                Vector3d normal = new Vector3d(0.0, 0.0, 1.0);
                Database db     = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
                using (Transaction myT = tm.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                    using (Circle pcirc = new Circle(center, normal, res.Value))
                    {
                        btr.AppendEntity(pcirc);
                        tm.AddNewlyCreatedDBObject(pcirc, true);
                    }
                    myT.Commit();
                }
            }
        }
예제 #6
0
        public static List <string> ImportBlocks(Database db, Database sourceDb, List <string> blockNames)
        {
            List <string> output = new List <string>();

            try
            {
                //create a variable to store the list of block identifiers
                ObjectIdCollection blockIds = new ObjectIdCollection();
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager;
                using (Transaction tr = tm.StartTransaction())
                {
                    //open the block table
                    BlockTable bt = tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false) as BlockTable;
                    //check each block in the block table
                    foreach (ObjectId btrId in bt)
                    {
                        BlockTableRecord btr = tm.GetObject(btrId, OpenMode.ForRead, false) as BlockTableRecord;
                        //only add named & non-layout blocks to the copy list
                        if (blockNames.Contains(btr.Name))
                        {
                            blockIds.Add(btrId);
                            output.Add(btr.Name);
                        }

                        btr.Dispose();
                    }
                }

                //copy blocks from source to destination database
                IdMapping mapping = new IdMapping();
                sourceDb.WblockCloneObjects(blockIds, db.BlockTableId, mapping, DuplicateRecordCloning.Ignore, false);
            }
            catch { }
            return(output);
        }
예제 #7
0
        public void UsingAngleOptionsAndResults()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //Using the stored PromptAngleOption.
            PromptDoubleResult res1 = ed.GetAngle(useThisAngleOption);
            //Using the stored PromptAngleResult.
            PromptDoubleResult res2 = useThisAngleResult;

            if (res1.Status == PromptStatus.OK && res2.Status == PromptStatus.OK)
            {
                Database db = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

                using (Transaction myT = tm.StartTransaction())
                {
                    BlockTable       bt     = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr    = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                    Point3d          center = new Point3d(30.0, 19.0, 0.0);
                    using (Arc arc1 = new Arc(center, res1.Value, res2.Value, 5.0))
                    {
                        arc1.ColorIndex = 3;
                        btr.AppendEntity(arc1);
                        myT.AddNewlyCreatedDBObject(arc1, true);
                    }
                    myT.Commit();
                }
            }
            else
            {
                ed.WriteMessage("Arc cannot be constructed");
            }
        }
예제 #8
0
            //[CommandMethod("IB")]
            public static void ImportBlocks()
            {
                Document doc      = Application.DocumentManager.MdiActiveDocument;
                Editor   ed       = doc.Editor;
                Database destDb   = doc.Database;
                Database sourceDb = new Database(false, true);

                String sourceFileName;

                try
                {
                    //Get name of DWG from which to copy blocks
                    sourceFileName = "C:\\Program Files\\AutoCAD MEP 2010\\DynaPrograms\\TagHgr.dwg";

                    //Read the DWG file into the database
                    sourceDb.ReadDwgFile(sourceFileName.ToString(), System.IO.FileShare.Read, true, "");

                    //Create a variable to store the list of block Identifiers
                    ObjectIdCollection blockIds = new ObjectIdCollection();

                    Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager;

                    using (Transaction myTm = tm.StartTransaction())
                    {
                        //Open the block table
                        BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false);

                        //Check each block in the table
                        foreach (ObjectId btrId in bt)
                        {
                            BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false);

                            //Only add named and non-layout blocks to the copy file if the don't already exist.
                            if (!btr.IsAnonymous && !btr.IsLayout)
                            {
                                blockIds.Add(btrId);
                            }
                            btr.Dispose();
                        }
                    }
                    //Copy blocks from source to dest database
                    IdMapping mapping = new IdMapping();
                    sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
                    //Writes the number of blocks copied to cmd line.
                    //ed.WriteMessage("\nCopied: " + blockIds.Count.ToString() + " block definitions from " + sourceFileName + " to the current drawing.");
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage(ex.Message);
                }
                sourceDb.Dispose();
            } //end ImportBlocks()
예제 #9
0
        public void ImportBlocks()
        {
            DocumentCollection dm       = Application.DocumentManager;
            Editor             ed       = dm.MdiActiveDocument.Editor;
            Database           destDb   = dm.MdiActiveDocument.Database;
            Database           sourceDb = new Database(false, true);
            PromptResult       sourceFileName;

            try
            {
                // Get name of DWG from which to copy blocks
                sourceFileName = ed.GetString("\nEnter the name of the source drawing: ");
                // Read the DWG into a side database
                sourceDb.ReadDwgFile(sourceFileName.StringResult, System.IO.FileShare.Read, true, "");

                // Create a variable to store the list of block identifiers
                ObjectIdCollection blockIds = new ObjectIdCollection();

                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager;

                using (Transaction myT = tm.StartTransaction())
                {
                    // Open the block table
                    BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false);

                    // Check each block in the block table
                    foreach (ObjectId btrId in bt)
                    {
                        BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false);
                        // Only add named & non-layout blocks to the copy list
                        if (!btr.IsAnonymous && !btr.IsLayout)
                        {
                            blockIds.Add(btrId);
                        }
                        btr.Dispose();
                    }
                }
                // Copy blocks from source to destination database
                IdMapping mapping = new IdMapping();
                sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
                ed.WriteMessage("\nCopied "
                                + blockIds.Count.ToString()
                                + " block definitions from "
                                + sourceFileName.StringResult
                                + " to the current drawing.");
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\nError during copy: " + ex.Message);
            }
            sourceDb.Dispose();
        }
예제 #10
0
        public void ImportBlocks()
        {
            AcadApp.DocumentCollection dm = AcadApp.Application.DocumentManager;
            Editor       ed       = dm.MdiActiveDocument.Editor;
            Database     destDb   = dm.MdiActiveDocument.Database;
            Database     sourceDb = new Database(false, true);
            PromptResult sourceFileName;

            try
            {
                //从命令行要求用户输入以得到要导入的块所在的源DWG文件的名字
                sourceFileName = ed.GetString("\nEnter the name of the source drawing: ");
                //把源DWG读入辅助数据库
                sourceDb.ReadDwgFile(sourceFileName.StringResult, System.IO.FileShare.Write, true, "");
                //用集合变量来存储块ID的列表
                ObjectIdCollection blockIds = new ObjectIdCollection();
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm =
                    sourceDb.TransactionManager;
                using (Transaction myT = tm.StartTransaction())
                {
                    //打开块表
                    BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId,
                                                             OpenMode.ForRead, false);
                    //在块表中检查每个块
                    foreach (ObjectId btrId in bt)
                    {
                        BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId,
                                                                              OpenMode.ForRead, false);
                        //只添加有名块和非layout块(layout块是非MS和非PS的块)
                        if (!btr.IsAnonymous && !btr.IsLayout)
                        {
                            blockIds.Add(btrId);
                        }
                        btr.Dispose(); //释放块表记录引用变量所占用的资源
                    }
                    bt.Dispose();      //释放块表引用变量所占用的资源
                    //没有作改变,不需要提交事务
                    myT.Dispose();
                }

                IdMapping mapping = new IdMapping();
                mapping = sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, DuplicateRecordCloning.Replace, false);

                ed.WriteMessage("\nCopied " + blockIds.Count.ToString() + " block definitions from " + sourceFileName.StringResult + " to the current drawing.");
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\nError during copy: " + ex.Message);
            }
            sourceDb.Dispose();
        }
예제 #11
0
        public static void ImportBlocks()
        {
            using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                DocumentCollection dm       = Application.DocumentManager;
                Editor             ed       = dm.MdiActiveDocument.Editor;
                Database           destDb   = dm.MdiActiveDocument.Database;
                Database           sourceDb = new Database(false, true);
                try
                {
                    // Read the DWG into a side database
#if DEBUG
                    sourceDb.ReadDwgFile("../../88.dwg", System.IO.FileShare.Read, true, "");
#else
                    sourceDb.ReadDwgFile("./Resource/88.dwg", System.IO.FileShare.Read, true, "");
#endif
                    // Create a variable to store the list of block identifiers
                    ObjectIdCollection blockIds = new ObjectIdCollection();
                    Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager;
                    using (Transaction myT = tm.StartTransaction())
                    {
                        // Open the block table
                        BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false);

                        // Check each block in the block table
                        foreach (ObjectId btrId in bt)
                        {
                            BlockTableRecord btr =
                                (BlockTableRecord)tm.GetObject(btrId,
                                                               OpenMode.ForRead,
                                                               false);
                            // Only add named & non-layout blocks to the copy list
                            if (!btr.IsAnonymous && !btr.IsLayout)
                            {
                                blockIds.Add(btrId);
                            }
                            btr.Dispose();
                        }
                    }
                    // Copy blocks from source to destination database
                    IdMapping mapping = new IdMapping();
                    sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage("\nError during copy: " + ex.Message);
                }
                sourceDb.Dispose();
            }
        }
예제 #12
0
        public void PointTest()
        {
            Editor             ed     = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptPointOptions ptopts = new PromptPointOptions("Enter start point of the line");

            ptopts.BasePoint     = new Point3d(1, 1, 1);
            ptopts.UseDashedLine = true;
            ptopts.Message       = "Enter start point of the line";

            ed.PromptingForPoint += new PromptPointOptionsEventHandler(handle_promptPointOptions);
            ed.PromptedForPoint  += new PromptPointResultEventHandler(handle_promptPointResult);
            PromptPointResult ptRes = ed.GetPoint(ptopts);

            ed.PromptingForPoint -= new PromptPointOptionsEventHandler(handle_promptPointOptions);
            ed.PromptedForPoint  -= new PromptPointResultEventHandler(handle_promptPointResult);


            Point3d start = ptRes.Value;

            if (ptRes.Status == PromptStatus.Cancel)
            {
                ed.WriteMessage("Taking (0,0,0) as the start point");
            }

            ptopts.Message = "Enter end point of the line: ";
            ptRes          = ed.GetPoint(ptopts);
            Point3d end = ptRes.Value;

            if (ptRes.Status == PromptStatus.Cancel)
            {
                ed.WriteMessage("Taking (0,0,0) as the end point");
            }

            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

            using (Transaction myT = tm.StartTransaction())
            {
                BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                using (Line myline = new Line(start, end))
                {
                    btr.AppendEntity(myline);
                    tm.AddNewlyCreatedDBObject(myline, true);
                }
                myT.Commit();
            }
        }
예제 #13
0
        public void AngleTest()
        {
            Editor             ed   = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptAngleOptions opt1 = new PromptAngleOptions("Enter start angle of the arc");

            opt1.AllowNone     = false;
            opt1.UseDashedLine = true;

            //USAGE OF INPUT CONTEXT REACTORS
            ed.PromptingForAngle += new PromptAngleOptionsEventHandler(handle_promptangleOptions);
            ed.PromptedForAngle  += new PromptDoubleResultEventHandler(handle_promptAngleResult);

            PromptDoubleResult startAngle = ed.GetAngle(opt1);

            ed.PromptingForAngle -= new PromptAngleOptionsEventHandler(handle_promptangleOptions);
            ed.PromptedForAngle  -= new PromptDoubleResultEventHandler(handle_promptAngleResult);


            opt1.Message = "Enter end angle of the arc";
            PromptDoubleResult endAngle = ed.GetAngle(opt1);

            PromptDoubleOptions opt2 = new PromptDoubleOptions("Enter the radius of the arc(double)");

            opt2.Message = "Enter the radius of the arc(double)";
            PromptDoubleResult radius = ed.GetDouble(opt2);

            if (startAngle.Status == PromptStatus.OK && endAngle.Status == PromptStatus.OK && radius.Status == PromptStatus.OK)
            {
                Point3d  center = new Point3d(30.0, 19.0, 0.0);
                Database db     = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

                using (Transaction myT = tm.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                    using (Arc arc1 = new Arc(center, radius.Value, startAngle.Value, endAngle.Value))
                    {
                        btr.AppendEntity(arc1);
                        tm.AddNewlyCreatedDBObject(arc1, true);
                    }
                    myT.Commit();
                }
            }
            else
            {
                ed.WriteMessage("Arc cannot be constructed");
            }
        }
        public void ImportBlocksFromDwg(string sourceFileName)
        {
            DocumentCollection dm = Application.DocumentManager;
            Editor             ed = dm.MdiActiveDocument.Editor;
            //获取当前数据库作为目标数据库
            Database destDb = dm.MdiActiveDocument.Database;
            //创建一个新的数据库对象,作为源数据库,以读入外部文件中的对象
            Database sourceDb = new Database(false, true);

            try
            {
                //把DWG文件读入到一个临时的数据库中
                sourceDb.ReadDwgFile(sourceFileName, System.IO.FileShare.Read, true, null);
                //创建一个变量用来存储块的ObjectId列表
                ObjectIdCollection blockIds = new ObjectIdCollection();
                //获取源数据库的事务处理管理器
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager;
                //在源数据库中开始事务处理
                using (Transaction myT = tm.StartTransaction())
                {
                    //打开源数据库中的块表
                    BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false);
                    //遍历每个块
                    foreach (ObjectId btrId in bt)
                    {
                        BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false);
                        //只加入命名块和非布局块到复制列表中
                        if (!btr.IsAnonymous && !btr.IsLayout)
                        {
                            blockIds.Add(btrId);
                        }
                        btr.Dispose();
                    }
                    bt.Dispose();
                }
                //定义一个IdMapping对象
                IdMapping mapping = new IdMapping();
                //从源数据库向目标数据库复制块表记录
                sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
                //'复制完成后,命令行显示复制了多少个块的信息
                ed.WriteMessage("复制了 " + blockIds.Count.ToString() + " 个块,从 " + sourceFileName + " 到当前图形");
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\nError during copy: " + ex.Message);
            }
            //操作完成,销毁源数据库
            sourceDb.Dispose();
        }
예제 #15
0
 private void MarkRbs()
 {
     using (Transaction myT = _TransMan.StartTransaction())
     {
         foreach (var oid in _AllRaumBlocks)
         {
             BlockReference ent = _TransMan.GetObject(oid, OpenMode.ForRead) as BlockReference;
             MarkRbIfNumber(ent);
         }
         myT.Commit();
     }
 }
예제 #16
0
        //设置巷道分段温度
        public void setTemperature(int segment)
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            PromptEntityOptions options = new PromptEntityOptions("选择物体");
            PromptEntityResult  res     = ed.GetEntity(options);

            if (res.Status == PromptStatus.Cancel)
            {
                return;
            }

            Autodesk.AutoCAD.DatabaseServices.ObjectId id1 = res.ObjectId;
            Database db = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            Utils.TransactionControl(() =>
            {
                Entity ent = (Entity)tm.GetObject(id1, OpenMode.ForWrite, false);

                if (ent is BaseTunnel)
                {
                    BaseTunnel tunnel = ent as BaseTunnel;
                }
            });
        }
예제 #17
0
        public void Getlayer()
        {
            string dir = null;

            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                dir = foldPath;
            }

            if (dir == null)
            {
                return;
            }

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

            List <string> layersName = LayersToList(db);

            TransactionControl(() =>
            {
                foreach (var layerName in layersName)
                {
                    TypedValue[] filterlist = new TypedValue[1];
                    filterlist[0]           = new TypedValue(8, layerName);
                    SelectionFilter filter  = new SelectionFilter(filterlist);

                    PromptSelectionResult selRes = ed.SelectAll(filter);
                    if (selRes.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage(
                            "\nerror in getting the selectAll");
                        return;
                    }
                    ObjectId[] ids = selRes.Value.GetObjectIds();
                    ObjectIdCollection sourceIds = new ObjectIdCollection();
                    foreach (var id in ids)
                    {
                        Entity entity = (Entity)tm.GetObject(id, OpenMode.ForRead, true);
                        sourceIds.Add(id);
                    }
                    Database destDb = new Database(true, true);

                    ObjectId sourceMsId = SymbolUtilityServices.GetBlockModelSpaceId(db);

                    ObjectId destDbMsId = SymbolUtilityServices.GetBlockModelSpaceId(destDb);

                    IdMapping mapping = new IdMapping();

                    db.WblockCloneObjects(sourceIds, destDbMsId, mapping, DuplicateRecordCloning.Replace, false);

                    destDb.SaveAs(dir + "\\" + layerName + ".dwg", DwgVersion.Current);
                }
            });
        }
예제 #18
0
        /// <summary>
        /// 刷新cad图形对象
        /// </summary>
        /// <param name="idArray">要刷新对象的id数组</param>
        static public void ReflushViewport(ObjectId[] idArray)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            doc.LockDocument();

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            Utils.TransactionControl(() => {
                if (idArray == null)
                {
                    return;
                }

                foreach (ObjectId id in idArray)
                {
                    Entity entity = (Entity)tm.GetObject(id, OpenMode.ForWrite, false);

                    if (entity is BaseTunnel)
                    {
                        BaseTunnel tunnel = (BaseTunnel)entity;
                        tunnel.Reflesh();
                    }
                    else if (entity is Node && Global.AnimateMode == false)
                    {
                        Node node = (Node)entity;
                        node.reflesh();
                    }
                }
            });
        }
예제 #19
0
        public void modified(object sender, EventArgs e)
        {
            Extents3d extents3d   = (Extents3d)_Entity.Bounds;
            Point3d   newPosition = new Point3d(
                (extents3d.MaxPoint.X + extents3d.MinPoint.X) / 2,
                (extents3d.MaxPoint.Y + extents3d.MinPoint.Y) / 2,
                (extents3d.MaxPoint.Z + extents3d.MinPoint.Z) / 2);


            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;


            if (tm.TopTransaction == null)
            {
                tm.StartTransaction();
            }

            foreach (var v in _BindedRoadways)
            {
                RoadwayWrapper bdrw = (RoadwayWrapper)tm.GetObject(v.roadway.ObjectId, OpenMode.ForWrite, false);
                if (v.whichSide == -1)
                {
                    bdrw.EndPoint = newPosition;
                }
                else if (v.whichSide == 1)
                {
                    bdrw.StartPoint = newPosition;
                }
            }
        }
예제 #20
0
        //通过句柄找到cad对象方法封装
        static public Entity OpenEntityByHandle(Handle handle)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            ObjectId id;

            try
            {
                id = db.GetObjectId(false, handle, 0);
            }
            catch (Autodesk.AutoCAD.Runtime.Exception)
            {
                return(null);
            }
            if (id == null)
            {
                return(null);
            }

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            Entity ent = null;

            TransactionControl(() =>
            {
                try
                {
                    ent = (Entity)tm.GetObject(id, OpenMode.ForWrite, false);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception)
                {
                    ent = null;
                }
            });
            return(ent);
        }
예제 #21
0
        private MassElement[] GetSelectedMassElement()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptSelectionOptions Opts = new PromptSelectionOptions();
            PromptSelectionResult  psr  = ed.GetSelection(Opts);

            if (psr.Status == PromptStatus.OK)
            {
                Autodesk.AutoCAD.EditorInput.SelectionSet    ss   = psr.Value;
                Autodesk.AutoCAD.DatabaseServices.ObjectId[] oids = ss.GetObjectIds();
                int           count  = oids.Length;
                MassElement[] result = new MassElement[count];
                Database      db     = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
                Transaction trans = tm.StartTransaction();

                MassElement me = new MassElement();
                for (int i = 0; i < count; i++)
                {
                    Autodesk.AutoCAD.DatabaseServices.Entity ety = tm.GetObject(oids[i], OpenMode.ForWrite, true) as Autodesk.AutoCAD.DatabaseServices.Entity;
                    result[i] = ety as MassElement;
                }

                trans.Commit();
                trans.Dispose();
                return(result);
            }
            return(null);
        }
예제 #22
0
        public void UsingEntityOptionsAndResults()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //Using the stored PromptEntityOption.
            PromptEntityResult res1 = ed.GetEntity(useThisEntityOption);
            //Using the stored PromptEntityResult.
            PromptEntityResult res2 = useThisEntityResult;

            ed.WriteMessage("\nCHANGING THE ALREADY SELECTED ENTITIES COLORS TO GREEN");
            if (res2.Status != PromptStatus.Error)
            {
                ObjectId entid = res2.ObjectId;
                Database db    = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
                ObjectId nowSelEntid = res1.ObjectId;

                using (Transaction myT = tm.StartTransaction())
                {
                    Entity Oldentity = (Entity)tm.GetObject(entid, OpenMode.ForWrite, true);
                    Oldentity.ColorIndex = 2;
                    ed.WriteMessage("\nYou Now selected: " + Oldentity.GetType().FullName);
                    myT.Commit();
                }
            }
        }
예제 #23
0
        static public void D()
        {
            StandardLineWrapper sl = new StandardLineWrapper();

            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

            using (Transaction myT = tm.StartTransaction())
            {
                BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                btr.AppendEntity(sl);
                tm.AddNewlyCreatedDBObject(sl, true);
                myT.Commit();
            }
        }
예제 #24
0
        static public void AppendEntity(Entity ent)
        {
            if (ent.ObjectId.IsNull == false)
            {
                return;
            }
            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            TransactionControl(() =>
            {
                BlockTable bt        = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                btr.AppendEntity(ent);
                tm.AddNewlyCreatedDBObject(ent, true);
            });
        }
예제 #25
0
        /// <summary>
        /// 将当前dwg文件中的巷道关系数据导出
        /// </summary>
        static public void OutputRlv()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

            OutRelationship outData = new OutRelationship();

            Utils.SelectAll("TUNNEL_SQUARE,TUNNEL_CYLINDER", (idArray) =>
            {
                foreach (var id in idArray)
                {
                    Entity entity = (Entity)tm.GetObject(id, OpenMode.ForRead, true);
                    if (entity is BaseTunnel)
                    {
                        BaseTunnel tunnel                 = entity as BaseTunnel;
                        List <OutVertice> outVertices     = new List <OutVertice>();
                        List <Edge <OutVertice> > inEdges = new List <Edge <OutVertice> >();

                        for (int i = 0; i < tunnel.BasePoints.Count; i++)
                        {
                            Point3d vt = tunnel.BasePoints[i];
                            outVertices.Add(new OutVertice(vt.X, vt.Y, vt.Z));
                            if (i > 0)
                            {
                                inEdges.Add(new Edge <OutVertice>(outVertices[i - 1], outVertices[i]));
                            }
                        }
                        AdjacencyGraph <OutVertice, Edge <OutVertice> > graph =
                            new AdjacencyGraph <OutVertice, Edge <OutVertice> >();
                        graph.AddVerticesAndEdgeRange(inEdges);
                        List <Tuple <OutVertice, OutVertice> > outEdges = new List <Tuple <OutVertice, OutVertice> >();

                        foreach (var edge in graph.Edges)
                        {
                            outEdges.Add(new Tuple <OutVertice, OutVertice>(edge.Source, edge.Target));
                        }
                        outData.VerticeList.AddRange(outVertices);
                        outData.EdgeList.AddRange(outEdges);
                    }
                }
            });
            string path = Project.Instance.DataPath + "relationship.json";

            if (File.Exists(path))
            {
                try
                {
                    File.Delete(path);
                }
                catch (IOException) { }
            }

            string str = JsonConvert.SerializeObject(outData);

            Fs.WriteStr(str, path);
        }
예제 #26
0
        private void Init()
        {
            Database db = HostApplicationServices.WorkingDatabase;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            Transaction      t   = tm.StartTransaction();
            BlockTable       bt  = tm.GetObject(db.BlockTableId, OpenMode.ForRead, false) as BlockTable;
            BlockTableRecord btr = tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false) as BlockTableRecord;

            Autodesk.Aec.DatabaseServices.MassElement temp = Autodesk.Aec.DatabaseServices.MassElement.Create(ShapeType.BoundaryRepresentation);
            Autodesk.Aec.Modeler.Body body = Autodesk.Aec.Modeler.Body.Cone(new LineSegment3d(new Point3d(0, 0, 0), new Point3d(0, 0, 10)), 3, 3, 10);
            temp.SetBody(body, false);
            btr.AppendEntity(temp);
            tm.AddNewlyCreatedDBObject(temp, true);

            t.Commit();
            t.Dispose();
        }
예제 #27
0
        /// <summary>
        /// 保存事件使数据库与图纸中的已保存数据相一致
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void db_SaveComplete(object sender, DatabaseIOEventArgs e)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            //保存树结构
            DBTreeControl treeControl = Project.Instance.GetMainTreeCol(doc);

            treeControl.StoreTree(Project.Instance.GetProjectTree(doc));

            //保存模型数据
            DBEntityControl dbControl = Project.Instance.GetMainEntCol(doc, true);

            TypedValue[]          value = { new TypedValue((int)DxfCode.Start, "TUNNEL_SQUARE,TUNNEL_CYLINDER,TUNNELNODE") };
            SelectionFilter       sf    = new SelectionFilter(value);
            PromptSelectionResult res   = ed.SelectAll(sf);

            if (res.Status != PromptStatus.OK)
            {
                dbControl.Delete(Query.All(), db);
                return;
            }
            SelectionSet SS = res.Value;

            if (SS == null)
            {
                return;
            }

            Autodesk.AutoCAD.DatabaseServices.ObjectId[] idArray = SS.GetObjectIds();

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            using (Transaction myT = tm.StartTransaction())
            {
                //储存之前先把之前数据的删除干净
                int deleteCounts = dbControl.Delete(Query.All(), db);

                foreach (var id in idArray)
                {
                    Entity entity = (Entity)tm.GetObject(id, OpenMode.ForRead, true);
                    if (entity is BaseTunnel)
                    {
                        DBTunnel dbTunnel = new DBTunnel();
                        dbTunnel.SetProperty(entity);
                        dbControl.Insert(dbTunnel, db);
                    }
                    else if (entity is Node)
                    {
                        DBNode dbNode = new DBNode();
                        dbNode.SetProperty(entity);
                        dbControl.Insert(dbNode, db);
                    }
                }
                myT.Commit();
            }
        }
예제 #28
0
        /// <summary>
        /// 将当前dwg文件中的巷道与节点几何数据导出
        /// </summary>
        public static void OutputGeo()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            List <OutGeometry> outDatas = new List <OutGeometry>();

            Utils.SelectAll("TUNNEL_SQUARE,TUNNEL_CYLINDER,TUNNELNODE", (idArray) =>
            {
                foreach (var id in idArray)
                {
                    Entity entity = (Entity)tm.GetObject(id, OpenMode.ForRead, true);
                    if (entity is BaseTunnel)
                    {
                        BaseTunnel tunnel       = entity as BaseTunnel;
                        List <int> faces        = tunnel.GetAllFaces();
                        List <Point3d> vertices = tunnel.GetAllVertices();

                        OutGeometry outData = new OutGeometry();
                        outData.Type        = "Tunnel";
                        outData.FaceList    = OutGeometry.toOutFace(faces);
                        outData.VerticeList = vertices.ConvertAll(
                            new Converter <Point3d, OutVertice>(OutVertice.Point3dToOutVertice));
                        outData.ColorList = tunnel.GetVerticesColors();

                        outDatas.Add(outData);
                    }
                    else if (entity is Node)
                    {
                        Node node           = entity as Node;
                        OutGeometry outData = new OutGeometry();
                        outData.Type        = "Node";
                        outData.Position    = new OutVertice(node.Position.X, node.Position.Y, node.Position.Z);
                        outData.Radius      = node.Radius;
                        outData.NodeColor   = node.NodeColor;

                        outDatas.Add(outData);
                    }
                }
            });

            string path = Project.Instance.DataPath + "geometry.json";

            if (File.Exists(path))
            {
                try
                {
                    File.Delete(path);
                }
                catch (IOException) { }
            }

            string str = JsonConvert.SerializeObject(outDatas);

            Fs.WriteStr(str, path);
        }
예제 #29
0
        void RecursiveReferencesToOfSeletedObject()
        {
            //
            // Transaction processing
            //
            Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            Database           db    = Application.DocumentManager.MdiActiveDocument.Database;
            TransactionManager tm    = db.TransactionManager;
            Transaction        trans = tm.StartTransaction();

            try
            {
                PromptEntityOptions entopts = new PromptEntityOptions("Select an Aec Entity ");
                entopts.SetRejectMessage("Must select an Aec Entity, please!");
                entopts.AddAllowedClass(typeof(Autodesk.Aec.DatabaseServices.Entity), false);
                PromptEntityResult ent = null;
                try
                {
                    ent = ed.GetEntity(entopts);
                }
                catch
                {
                    ed.WriteMessage("You did not select a valid entity");
                    return;
                }

                if (ent.Status == PromptStatus.OK)
                {
                    ObjectId entId = ent.ObjectId;

                    Autodesk.Aec.DatabaseServices.Entity aecent = tm.GetObject(entId, OpenMode.ForRead, false) as Autodesk.Aec.DatabaseServices.Entity;

                    DBObjectRelationshipManager    mgr    = new DBObjectRelationshipManager();
                    DBObjectRelationshipCollection refsTo = mgr.GetReferencesToThisObjectRecursive(aecent, 0, false);

                    ed.WriteMessage("\n\n");
                    foreach (DBObjectRelationship relTo in refsTo)
                    {
                        ed.WriteMessage("Ent ID = " + entId.ToString() + "  " + entId.ObjectClass.Name.ToString() + " is referenced recursively by: " + relTo.Id.ToString() + "("
                                        + relTo.Id.ObjectClass.Name + ")" + ", whose relationship type is "
                                        + relTo.RelationshipType.ToString() + "\n");
                    }
                }

                trans.Commit();
            }
            catch (System.Exception e)
            {
                trans.Abort();
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(e.Message);
            }
            finally
            {
                trans.Dispose();
            }
        }
예제 #30
0
        static public void ChangeSelection(object sender, SelectionSet set)
        {
            SelectedTunnels = new List <DBTunnel>();
            SelectedNodes   = new List <DBNode>();

            if (set.Count != 0)
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db  = doc.Database;
                Editor   ed  = doc.Editor;

                var ids = set.GetObjectIds();
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

                Utils.TransactionControl(() =>
                {
                    Entity entity = null;
                    foreach (var id in ids)
                    {
                        entity = (Entity)tm.GetObject(id, OpenMode.ForRead, false);
                        if (entity.IsErased == true)
                        {
                            return;
                        }
                        long handleValue = entity.Handle.Value;
                        if (entity is BaseTunnel)
                        {
                            DBTunnel dbTunnel = Utils.GetEntityFromDB(handleValue) as DBTunnel;

                            if (dbTunnel == null)
                            {
                                return;
                            }
                            else
                            {
                                SelectedTunnels.Add(dbTunnel);
                            }
                        }
                        else if (entity is Node)
                        {
                            DBNode dbNode = Utils.GetEntityFromDB(handleValue) as DBNode;
                            if (dbNode == null)
                            {
                                return;
                            }
                            else
                            {
                                SelectedNodes.Add(dbNode);
                            }
                        }
                    }
                });
            }
            SelectedTunnelChanged?.Invoke(sender, SelectedTunnels);
            SelectedNodeChanged?.Invoke(sender, SelectedNodes);
        }