Esempio n. 1
0
        public static IEnumerable <ObjectId> InsertSpreadPoints(Document document, IEnumerable <SpreadPoint> spreadPoints,
                                                                SpreadPointSettings settings)
        {
            var result = new List <ObjectId>();

            // Create text style
            var textStyleId = CreateSpreadPointTextStyle(settings, document.Database);
            // Create layer
            var layerId = CreateSpreadPointLayer(settings, document.Database);

            // Insert points
            using (var transaction = document.Database.TransactionManager.StartTransaction())
            {
                var modelspaceId = SymbolUtilityServices.GetBlockModelSpaceId(document.Database);
                var modelspace   = (BlockTableRecord)transaction.GetObject(modelspaceId, OpenMode.ForWrite);
                foreach (var spreadPoint in spreadPoints)
                {
                    var ids = InsertSpreadPoint(spreadPoint, modelspace, transaction, layerId, textStyleId, settings);
                    result.AddRange(ids);
                }
                transaction.Commit();
            }

            return(result);
        }
Esempio n. 2
0
        public ObjectIdCollection GetIdsByTypeCollection()
        {
            ObjectIdCollection collection = new ObjectIdCollection();

            Func <Type, RXClass> getClass = RXObject.GetClass;

            // You can set this anywhere
            var acceptableTypes = new HashSet <RXClass>
            {
                getClass(typeof(Polyline)),
                getClass(typeof(Polyline2d)),
                getClass(typeof(Polyline3d))
            };

            var doc = Application.DocumentManager.MdiActiveDocument;

            using (var trans = doc.TransactionManager.StartOpenCloseTransaction())
            {
                var modelspace = (BlockTableRecord)
                                 trans.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(doc.Database), OpenMode.ForRead);

                var polylineIds = (from id in modelspace.Cast <ObjectId>()
                                   where acceptableTypes.Contains(id.ObjectClass)
                                   select id).ToList();

                foreach (var id in polylineIds)
                {
                    collection.Add(id);
                }


                trans.Commit();
                return(collection);
            }
        }
Esempio n. 3
0
        private void LinkDwgFile(Point3d Position)
        {
            string           ReferenceName = Path.GetFileNameWithoutExtension(this.filePath);
            BlockTable       blockTable    = this.trans.GetObject(currentDwg.BlockTableId, OpenMode.ForWrite) as BlockTable;
            BlockTableRecord modelSpace    = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(currentDwg).GetObject(OpenMode.ForWrite);
            LayerTableRecord currentTable  = this.trans.GetObject(currentDwg.Clayer, OpenMode.ForRead, true) as LayerTableRecord;
            BlockTableRecord btr           = (BlockTableRecord)trans.GetObject(currentDwg.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

            if (!File.Exists(this.filePath))
            {
                this.Ed.WriteMessage("Error404: 文件" + this.filePath + "未找到" + "\n");
                return;
            }
            else
            {
                try
                {
                    ObjectId id = blockTable[ReferenceName];
                    this.Ed.WriteMessage("链接失败,当前已存在名为:" + ReferenceName + "的块参照" + "\n");
                }catch
                {
                    ObjectId       id = btr.Database.AttachXref(this.filePath, ReferenceName + "_L");
                    BlockReference br = new BlockReference(Position, id);
                    br.Color = currentTable.Color;
                    modelSpace.AppendEntity(br);
                    trans.AddNewlyCreatedDBObject(br, true);
                }
            }
        }
Esempio n. 4
0
        protected override void DrawVisuals(List <Entity> ds)
        {
            draws = new List <ObjectId>();
            if (ds != null && ds.Count != 0)
            {
                using (doc.LockDocument())
                    using (var t = doc.TransactionManager.StartTransaction())
                    {
                        var db   = doc.Database;
                        var msId = SymbolUtilityServices.GetBlockModelSpaceId(db);
                        var ms   = msId.GetObject(OpenMode.ForWrite) as BlockTableRecord;

                        // Слой для визуализации
                        var idLayerVisual = GetLayerForVisual(LayerVisualName);

                        foreach (var d in ds)
                        {
                            if (d.Id.IsNull)
                            {
                                if (d.LayerId != idLayerVisual)
                                {
                                    d.LayerId = idLayerVisual;
                                }
                                ms.AppendEntity(d);
                                t.AddNewlyCreatedDBObject(d, true);
                            }
                            draws.Add(d.Id);
                        }
                        t.Commit();
                    }
            }
        }
Esempio n. 5
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);
                }
            });
        }
Esempio n. 6
0
        public static void TecTest()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (Transaction Tx = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord ms      = (BlockTableRecord)Tx.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForRead);
                RXObject         brClass = RXObject.GetClass(typeof(BlockReference));

                Point3d lastrightpt = new Point3d(0, 0, 0);

                foreach (ObjectId id in ms)
                {
                    if (id.ObjectClass == brClass)
                    {
                        BlockReference br = (BlockReference)Tx.GetObject(id, OpenMode.ForWrite);
                        ed.WriteMessage("NAME:{0}\n", br.Name);
                        Extents3d bounds = br.GeometricExtents;
                        ed.WriteMessage("BOUNDS: {0}\n", bounds.ToString());
                        Vector3d vec = (Vector3d)(lastrightpt - bounds.MinPoint);
                        ed.WriteMessage("VECTOR: {0}\n", vec.ToString());

                        Point3d  rightpt = new Point3d(bounds.MaxPoint.X, bounds.MinPoint.Y, 0);;
                        Vector3d newrp   = (Vector3d)(vec + rightpt.GetAsVector() + (new Vector3d(50, 0, 0)));
                        lastrightpt = new Point3d(newrp.X, newrp.Y, 0);
                        ed.WriteMessage("NEWLASTRIGHT SET to {0}\n", lastrightpt);
                        Matrix3d mat = Matrix3d.Displacement(vec);
                        br.TransformBy(mat);
                    }
                }
                Tx.Commit();
            }
        }
Esempio n. 7
0
        public static IEnumerable <ObjectId> GetIdsByTypeIteration(params Type[] types)
        {
            // We will use this Delegate to return the Class of the RXObject(Entity)
            Func <Type, RXClass> getClass = RXObject.GetClass;

            // Make a HashSet of the Types of Entities we want to get from the modelspace.
            var acceptableTypes = new HashSet <RXClass>(

                // Use a little linq with a method group to iterate through the array
                types.Select(getClass));

            var doc = Application.DocumentManager.MdiActiveDocument;

            // Create a transaction to grab the modelspace. Here you can use a regular transaction
            // "TransactionManager.StartTransaction()". I prefer StartOpenClose out of habit
            // because its a bit faster.
            using (var trans = doc.TransactionManager.StartOpenCloseTransaction())
            {
                var modelspace =
                    // Here we utilize "SymbolUtilityServices" to get the Modelspace id from our database.
                    (BlockTableRecord)
                    trans.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(doc.Database), OpenMode.ForRead);

                // We use a little more linq to cast the IEnumerable object and iterate thru its ObjectIds
                // we will check our hashset contains the RXClass of the ObjectId by accessing the "ObjectClass"
                // property of the RXObject.
                var ids = modelspace.Cast <ObjectId>().Where(id => acceptableTypes.Contains(id.ObjectClass));

                // Commit the transaction.
                trans.Commit();
                return(ids);
            }
        }
Esempio n. 8
0
        private string GetObjectHandlesAsJSON(Type t)
        {
            var handles = new List <long>();
            var db      = BoundDocument.Database;

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var btr = (BlockTableRecord)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForRead);
                var ids =
                    from ObjectId id in btr
                    where id.ObjectClass.GetRuntimeType() == t
                    select id;

                foreach (var id in ids)
                {
                    using (var o = tr.GetObject(id, OpenMode.ForRead))
                    {
                        handles.Add(o.Handle.Value);
                    }
                }

                tr.Commit();
            }

            return(JsonConvert.SerializeObject(handles));
        }
Esempio n. 9
0
        public void cmdImportBlockFromExternalDrawing()
        {
            var doc = AcApp.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;
            var db  = doc.Database;

            var dlg = new Microsoft.Win32.OpenFileDialog();

            dlg.ShowDialog();
            var srcPath = dlg.FileName;
            var srcDb   = new Database();

            srcDb.ReadDwgFile(srcPath, FileOpenMode.OpenForReadAndReadShare, false, "");
            var ids = new ObjectIdCollection();

            using (var tr = srcDb.TransactionManager.StartTransaction())
            {
                var bt = tr.GetObject(srcDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                foreach (ObjectId id in bt)
                {
                    var btr = tr.GetObject(id, OpenMode.ForRead) as BlockTableRecord;
                    if (id != SymbolUtilityServices.GetBlockModelSpaceId(db) &&     //Block must have a Name
                        !SymbolUtilityServices.IsBlockLayoutName(btr.Name))
                    {
                        ids.Add(id);
                    }
                }
            }

            var idmap = new IdMapping();

            db.WblockCloneObjects(ids, db.BlockTableId, idmap, DuplicateRecordCloning.Ignore, false);
        }
Esempio n. 10
0
        public static void TestSearchAllLoops()
        {
            var drawingDb = Application.DocumentManager.MdiActiveDocument.Database;
            var editor    = Application.DocumentManager.MdiActiveDocument.Editor;

            editor.WriteMessage("\n选择一条或几条曲线:\n");
            var result = editor.GetSelection();

            if (result.Status != PromptStatus.OK)
            {
                return;
            }

            var polylineids = result.Value.GetObjectIds();
            var polygons    = MinimalLoopSearcher2.GetAllLoopPolylines(polylineids, editor.Document);

            using (var transaction = drawingDb.TransactionManager.StartTransaction())
            {
                var modelspaceId = SymbolUtilityServices.GetBlockModelSpaceId(drawingDb);
                var modelspace   = transaction.GetObject(modelspaceId, OpenMode.ForWrite) as BlockTableRecord;
                foreach (var polyline in polygons)
                {
                    polyline.Color = Color.FromColorIndex(ColorMethod.ByAci, 3);
                    modelspace.AppendEntity(polyline);
                    transaction.AddNewlyCreatedDBObject(polyline, true);
                }
                transaction.Commit();
            }
        }
Esempio n. 11
0
        private string GetPolylineIdsAsJSON()
        {
            var     pList   = new List <long>();
            RXClass rxClass = RXClass.GetClass(typeof(Polyline));
            var     db      = BoundDocument.Database;

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var btr = (BlockTableRecord)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForRead);
                var ids =
                    from ObjectId id in btr
                    where id.ObjectClass.IsDerivedFrom(rxClass)
                    select id;

                foreach (var id in ids)
                {
                    using (var pLine = (Polyline)tr.GetObject(id, OpenMode.ForRead))
                    {
                        pList.Add(pLine.Handle.Value);
                    }
                }

                tr.Commit();
            }

            return(JsonConvert.SerializeObject(pList));
        }
Esempio n. 12
0
        public static void GetInsObjects(string file, Action <Entity> action)
        {
            var doc   = GetDocumentOrOpen(file);
            var dbIns = doc.Database;

            using (doc.LockDocument())
                using (var t = dbIns.TransactionManager.StartTransaction())
                {
                    var ms = SymbolUtilityServices.GetBlockModelSpaceId(dbIns).GetObject(OpenMode.ForRead) as BlockTableRecord;
                    foreach (var idEnt in ms)
                    {
                        if (!idEnt.IsValidEx())
                        {
                            continue;
                        }

                        var ent = idEnt.GetObject(OpenMode.ForRead) as Entity;

                        if (!InsObjects.IsInsObject(ent) ||
                            ent is Circle || ent is DBPoint || ent is DBText || ent is MText || ent is Dimension)
                        {
                            continue;
                        }

                        action(ent);
                    }
                    t.Commit();
                }
        }
Esempio n. 13
0
        // парсим рабочее пространство, возвращаем массив точек с координатами
        private static List <Dot> FindDots()
        {
            // получаем текущую БД
            Database db = ApUtilities.TakeDB();

            // создаем массив точек
            List <Dot> dots = new List <Dot>();

            // начинаем транзакцию
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // получаем ссылку на пространство модели (ModelSpace)
                BlockTableRecord ms = (BlockTableRecord)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForRead);

                // "пробегаем" по всем объектам в пространстве модели
                foreach (ObjectId id in ms)
                {
                    // приводим каждый из них к типу Entity
                    Entity entity = (Entity)tr.GetObject(id, OpenMode.ForRead);

                    // если это точка - создаем объект Dot
                    if (entity.GetType() == typeof(DBPoint))
                    {
                        dots.Add(new Dot(((DBPoint)entity).Position.X, ((DBPoint)entity).Position.Y));
                    }
                }
            }
            return(dots);
        }
Esempio n. 14
0
        private void copyPanelToExportFile(Database dbExport)
        {
            Dictionary <ObjectId, PanelBlRefExport> dictPanelsToExport = new Dictionary <ObjectId, PanelBlRefExport>();

            foreach (var panelBtr in CPS.PanelsBtrExport)
            {
                foreach (var panelBlref in panelBtr.Panels)
                {
                    dictPanelsToExport.Add(panelBlref.IdBlRefAkr, panelBlref);
                }
            }

            ObjectIdCollection ids = new ObjectIdCollection(dictPanelsToExport.Keys.ToArray());

            using (IdMapping map = new IdMapping())
            {
                var msExport = SymbolUtilityServices.GetBlockModelSpaceId(dbExport);
                dbExport.WblockCloneObjects(ids, msExport, map, DuplicateRecordCloning.Replace, false);

                // скопированные блоки в экспортированном чертеже
                var idsBtrExport = new HashSet <ObjectId>();
                foreach (var itemDict in dictPanelsToExport)
                {
                    itemDict.Value.IdBlRefExport = map[itemDict.Key].Value;
                    using (var blRef = itemDict.Value.IdBlRefExport.Open(OpenMode.ForRead, false, true) as BlockReference)
                    {
                        idsBtrExport.Add(blRef.BlockTableRecord);
                        itemDict.Value.PanelBtrExport.IdBtrExport = blRef.BlockTableRecord;
                    }
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Получение фасадов из блоков монтажных планов и обозначений стороны фасада в чертеже
        /// </summary>
        /// <returns></returns>
        public static List <FacadeMounting> GetFacadesFromMountingPlans(PanelLibraryLoadService libLoadServ = null)
        {
            List <FacadeMounting> facades = new List <FacadeMounting>();
            var db = HostApplicationServices.WorkingDatabase;

            using (var t = db.TransactionManager.StartTransaction())
            {
                var ms = SymbolUtilityServices.GetBlockModelSpaceId(db).GetObject(OpenMode.ForRead) as BlockTableRecord;
                // Поиск всех блоков монтажных планов в Модели чертежа с соотв обозначением стороны фасада
                List <FloorMounting> floors = FloorMounting.GetMountingBlocks(libLoadServ, ms);
                // блоки сторон фасадов - Фасады
                List <FacadeFrontBlock> facadeFrontBlocks = FacadeFrontBlock.GetFacadeFrontBlocks(ms, floors);

                // Создание фасадов
                foreach (var front in facadeFrontBlocks)
                {
                    FacadeMounting facade = new FacadeMounting(front);
                    facades.Add(facade);
                }

                // определение уровней этажей Storey
                defineFloorStoreys(facades);
                t.Commit();
            }
            return(facades);
        }
Esempio n. 16
0
        public static IEnumerable <EntityInfo> CollectEntitiesInModelSpace(Document dwg)
        {
            var lst = new List <EntityInfo>();

            using (var tran = dwg.TransactionManager.StartTransaction())
            {
                var model = (BlockTableRecord)tran.GetObject(
                    SymbolUtilityServices.GetBlockModelSpaceId(dwg.Database), OpenMode.ForRead);
                foreach (ObjectId id in model)
                {
                    var ent = (Entity)tran.GetObject(id, OpenMode.ForRead);
                    lst.Add(new EntityInfo
                    {
                        EntityId    = id,
                        EntityType  = id.ObjectClass.DxfName,
                        EntityLayer = ent.Layer
                    });
                }

                tran.Commit();
            }

            return(from e in lst
                   orderby
                   e.EntityType ascending,
                   e.EntityLayer ascending,
                   e.EntityId.ToString() ascending
                   select e);
        }
Esempio n. 17
0
 public void SelectSectionBlRefs()
 {
     SectionsBlRefs = new List <ObjectId>();
     using (var ms = SymbolUtilityServices.GetBlockModelSpaceId(_db).Open(OpenMode.ForRead) as BlockTableRecord)
     {
         foreach (ObjectId idEnt in ms)
         {
             if (!idEnt.IsValidEx())
             {
                 continue;
             }
             using (var blRef = idEnt.Open(OpenMode.ForRead, false, true) as BlockReference)
             {
                 if (blRef == null)
                 {
                     continue;
                 }
                 if (string.Equals(blRef.GetEffectiveName(), Settings.Default.BlockSectionName, StringComparison.CurrentCultureIgnoreCase))
                 {
                     SectionsBlRefs.Add(idEnt);
                 }
             }
         }
     }
 }
Esempio n. 18
0
        public static void Clear()
        {
            Database acCurDb = HostApplicationServices.WorkingDatabase;
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Editor   acEdt   = acDoc.Editor;

            /// 让用户选择是否清除块内的图元,Y:清除,N:不清除
            PromptStringOptions optRecurseIn = new PromptStringOptions("是否包括块内和锁定图层内的图元?[是(Y)/否(N)]")
            {
                AllowSpaces  = false,
                DefaultValue = "N"
            };
            PromptResult resStringResult;

            do
            {
                resStringResult = acEdt.GetString(optRecurseIn);
            } while (resStringResult.StringResult.ToUpper() != "Y" && resStringResult.StringResult.ToUpper() != "N");
            bool recurseIn = (resStringResult.StringResult.ToUpper() == "Y");

            //对图形进行修改
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) {
                ulong countTotal   = 0;
                ulong countCleared = 0;
                //遍历模型空间的清零
                BlockTableRecord btRecord = (BlockTableRecord)acTrans.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(acCurDb), OpenMode.ForRead, false, true);
                btRecord.Clear(ref countTotal, ref countCleared, recurseIn);
                acEdt.WriteMessage("共检查了" + countTotal + "个对象,其中" + countCleared + "个对象的Z坐标已经清除。\n");
                //提交执行
                acTrans.Commit();
            }
        }
Esempio n. 19
0
        public static void CreateGroup(string groupName, ObjectIdCollection ids)
        {
            //Document doc =Application.DocumentManager.MdiActiveDocument;
            Database db = HostApplicationServices.WorkingDatabase;
            //Editor ed = doc.Editor;

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                // Get the group dictionary from the drawing
                DBDictionary gd = (DBDictionary)tr.GetObject(db.GroupDictionaryId, OpenMode.ForRead);
                // Check the group name, to see whether it's

                // A variable for the group's name
                string grpName = "";
                try
                {
                    // Validate the provided symbol table name
                    SymbolUtilityServices.ValidateSymbolName(groupName, false);

                    // Only set the block name if it isn't in use
                    if (gd.Contains(groupName))
                    {
                        //ed.WriteMessage("\nA group with this name already exists.");

                        //throw new System.Exception("A group with this name already exists.");
                        AddIds2Group(groupName, ids, tr);
                        return;
                    }
                    else
                    {
                        grpName = groupName;
                    }
                }
                catch
                {
                    // An exception has been thrown, indicating the
                    // name is invalid

                    //ed.WriteMessage("\nInvalid group name.");
                }

                // Create our new group...

                Group grp = new Group("Test group", true);
                // Add the new group to the dictionary
                gd.UpgradeOpen();

                ObjectId grpId = gd.SetAt(grpName, grp);

                tr.AddNewlyCreatedDBObject(grp, true);
                //grp.InsertAt(0, ids);
                AddIds2Group(grp, ids);
                // Commit the transaction
                tr.Commit();
                // Report what we've done
                //ed.WriteMessage("\nCreated group named \"{0}\" containing  entities.",grpName);
            }
        }
Esempio n. 20
0
        public static BlockDrawingObject Create(Database target, string blockName)
        {
            Transaction trans = target.TransactionManager.TopTransaction;
            BlockTable  bt    = (BlockTable)trans.GetObject(target.BlockTableId, OpenMode.ForRead);

            SymbolUtilityServices.ValidateSymbolName(blockName, false);
            if (bt.Has(blockName))
            {
                throw  new InvalidOperationException("Block name exists");
            }

            BlockTableRecord btr = new BlockTableRecord();

            btr.Name = blockName;

            bt.UpgradeOpen();
            ObjectId btrId = bt.Add(btr);

            trans.AddNewlyCreatedDBObject(btr, true);

            BlockDrawingObject blockDrawingObject = new BlockDrawingObject(target);

            blockDrawingObject.BaseObject = btrId;
            return(blockDrawingObject);
        }
Esempio n. 21
0
        public static List <BaseStairObject> GetStairList()
        {
            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            List <BaseStairObject> listStairs = new List <BaseStairObject>();
            RXClass         rxClass           = RXClass.GetClass(typeof(Solid3d));
            BaseStairObject bso;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord btRecord = (BlockTableRecord)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForRead);
                foreach (ObjectId id in btRecord)
                {
                    if (id.ObjectClass.IsDerivedFrom(rxClass))
                    {
                        Solid3d sol = (Solid3d)tr.GetObject(id, OpenMode.ForRead);
                        bso = GetStairPropertiesFromSolid(sol);
                        if (bso != null)
                        {
                            listStairs.Add(bso);
                        }
                    }
                    ;
                }
                tr.Commit();
            }
            return(listStairs);
        }
Esempio n. 22
0
 public void PIK_SearchById()
 {
     CommandStart.Start(doc =>
     {
         var ed  = doc.Editor;
         var res = ed.GetString("\nВведи ObjectID, например:8796086050096");
         if (res.Status != PromptStatus.OK)
         {
             return;
         }
         var id = long.Parse(res.StringResult);
         var db = doc.Database;
         using (var t = db.TransactionManager.StartTransaction())
         {
             var ms    = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(db).GetObject(OpenMode.ForRead);
             var entId = ms.Cast <ObjectId>().FirstOrDefault(f => f.OldId == id);
             if (entId.IsNull)
             {
                 "Элемент не найден в Моделе.".WriteToCommandLine();
             }
             else
             {
                 entId.ShowEnt();
             }
             t.Commit();
         }
     });
 }
Esempio n. 23
0
        /// <summary>
        /// Realizá la carga del bloque
        /// </summary>
        /// <param name="tr">La transacción activa.</param>
        /// <param name="localDwg">La base de datos local.</param>
        /// <param name="file">La ruta del bloque a cargar.</param>
        /// <param name="blockName">El nombre del bloque.</param>
        public static void LoadBlock(this Transaction tr, Database localDwg, string file, string blockName)
        {
            BlockTable blkTab = (BlockTable)localDwg.BlockTableId.GetObject(OpenMode.ForRead);

            if (!blkTab.Has(blockName) && File.Exists(file))
            {
                blkTab.UpgradeOpen();
                BlockTableRecord newRecord = new BlockTableRecord();
                newRecord.Name = blockName;
                blkTab.Add(newRecord);
                tr.AddNewlyCreatedDBObject(newRecord, true);
                //3: Se abre la base de datos externa
                Database externalDB = new Database();
                externalDB.ReadDwgFile(file, FileShare.Read, true, null);
                //4: Con una subtransacción se clonán los elementos que esten contenidos en el espcio de modelo de la
                //base de datos externa
                ObjectIdCollection ids;
                using (Transaction subTr = externalDB.TransactionManager.StartTransaction())
                {
                    //4.1: Abrir el espacio de modelo de la base de datos externa
                    ObjectId         modelId = SymbolUtilityServices.GetBlockModelSpaceId(externalDB);
                    BlockTableRecord model   = subTr.GetObject(modelId, OpenMode.ForRead) as BlockTableRecord;
                    //4.2: Se extraen y clonan los elementos mediante la clase IdMapping
                    ids = new ObjectIdCollection(model.OfType <ObjectId>().ToArray());
                    using (IdMapping iMap = new IdMapping())
                        localDwg.WblockCloneObjects(ids, newRecord.Id, iMap, DuplicateRecordCloning.Replace, false);
                }
            }
        }
Esempio n. 24
0
 private void CloneModelSpaceDataFromSourceToTarget(Database SourceDB, Database TargetDB)
 {
     using (Transaction SourceTran = SourceDB.TransactionManager.StartTransaction())
     {
         BlockTableRecord SourceModelSpace = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(SourceDB).GetObject(OpenMode.ForRead);
         BlockTable       SourceBlockTable = SourceTran.GetObject(SourceDB.BlockTableId, OpenMode.ForRead) as BlockTable;
         using (Transaction TargetTran = TargetDB.TransactionManager.StartTransaction())
         {
             BlockTable       TargetBlockTable = TargetTran.GetObject(TargetDB.BlockTableId, OpenMode.ForRead) as BlockTable;
             BlockTableRecord TargetModelSpace = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(TargetDB).GetObject(OpenMode.ForRead);
             foreach (ObjectId item in SourceModelSpace)
             {
                 DBObject Rec = SourceTran.GetObject(item, OpenMode.ForRead);
                 System.Diagnostics.Debug.WriteLine(Rec.GetType());
                 Entity Ent = Rec as Entity;
                 if (Ent != null)
                 {
                     if (!TargetBlockTable.Has(Ent.BlockName))
                     {
                         TargetModelSpace.AppendEntity(Ent);
                         TargetTran.AddNewlyCreatedDBObject(Rec, true);
                     }
                 }
             }
             TargetTran.Commit();
         }
     }
 }
Esempio n. 25
0
        private static void SearchWalls(List <LineSegment3d> outLines, List <LineSegment3d> allLines)
        {
            WallInfor wallInfo = null;

            using (var tolerance = new Utils.SafeToleranceOverride())
            {
                wallInfo = WallRecognizer.getWallinfors(outLines, allLines);
            }
            if (wallInfo == null)
            {
                return;
            }

            // Test Code!
            var visited  = new HashSet <WallInfor>();
            var database = Application.DocumentManager.MdiActiveDocument.Database;

            using (var transaction = database.TransactionManager.StartTransaction())
            {
                var modelspaceId = SymbolUtilityServices.GetBlockModelSpaceId(database);
                var modelspace   = (BlockTableRecord)transaction.GetObject(modelspaceId, OpenMode.ForWrite);

                var      color   = Color.FromColorIndex(ColorMethod.ByAci, 4); // Cyan
                ObjectId layerId = LayerUtils.AddNewLayer(database, "temp-poly2", "Continuous", color);

                var currentInfo = wallInfo;
                var count       = 0;
                while (currentInfo != null && currentInfo.outline != null)
                {
                    if (visited.Contains(currentInfo))
                    {
                        break;
                    }
                    var line = new Line(currentInfo.outline.StartPoint, currentInfo.outline.EndPoint);
                    line.Color   = color;
                    line.LayerId = layerId;
                    modelspace.AppendEntity(line);
                    transaction.AddNewlyCreatedDBObject(line, add: true);

                    foreach (var innerSeg in currentInfo.innerlines)
                    {
                        var innerLine = new Line(innerSeg.StartPoint, innerSeg.EndPoint);
                        innerLine.Color   = color;
                        innerLine.LayerId = layerId;
                        modelspace.AppendEntity(innerLine);
                        transaction.AddNewlyCreatedDBObject(innerLine, add: true);
                    }

                    visited.Add(currentInfo);
                    count++;
                    currentInfo = currentInfo.next;
                    if (currentInfo == wallInfo)
                    {
                        break;
                    }
                }

                transaction.Commit();
            }
        }
Esempio n. 26
0
        public IList <ObjectId> GetIdsByType()
        {
            Func <Type, RXClass> getClass = RXObject.GetClass;

            // You can set this anywhere
            var acceptableTypes = new HashSet <RXClass>
            {
                getClass(typeof(Polyline)),
                getClass(typeof(Polyline2d)),
                getClass(typeof(Polyline3d))
            };

            using (var t = AC.Doc.TransactionManager.StartOpenCloseTransaction())
            {
                var modelspace = t.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(AC.Doc.Database), OpenMode.ForRead) as BlockTableRecord;

                var polylineIds = (from id in modelspace.Cast <ObjectId>()
                                   where acceptableTypes.Contains(id.ObjectClass)
                                   select id).ToList();

                t.Commit();

                return(polylineIds);
            }
        }
Esempio n. 27
0
        private void SearchForTopBlocks(string blkName, int targetCount)
        {
            List <ObjectId> blkIds = new List <ObjectId>();

            try
            {
                if (ProcessingStarted != null)
                {
                    string msg = string.Format(
                        "Searching first {0} block refeences: \"{1}\"",
                        targetCount, blkName);
                    LongProcessStartedEventArgs e =
                        new LongProcessStartedEventArgs(msg);

                    ProcessingStarted(this, e);
                }

                using (var tran = _dwg.TransactionManager.StartTransaction())
                {
                    //Get all entities' ID in ModelSpace
                    BlockTableRecord model = (BlockTableRecord)tran.GetObject(
                        SymbolUtilityServices.GetBlockModelSpaceId(
                            _dwg.Database), OpenMode.ForRead);

                    foreach (ObjectId id in model)
                    {
                        if (ProcessingProgressed != null)
                        {
                            string progMsg = string.Format(
                                "{0} found\n" +
                                "Processing entity: {1}",
                                blkIds.Count, id.ObjectClass.DxfName);
                            LongProcessingProgressEventArgs e =
                                new LongProcessingProgressEventArgs(progMsg);
                            ProcessingProgressed(this, e);
                        }

                        if (IsTargetBlock(id, blkName, tran))
                        {
                            blkIds.Add(id);
                            if (blkIds.Count == targetCount)
                            {
                                break;
                            }
                        }
                    }

                    tran.Commit();
                }

                ProcessingEnded?.Invoke(this, EventArgs.Empty);
            }
            finally
            {
                //Make sure the CloseProgressUIRequested event always fires,
                //so that the progress dialog box gets closed because of
                //this event
                CloseProgressUIRequested?.Invoke(this, EventArgs.Empty);
            }
        }
Esempio n. 28
0
        public static ObjectId ContainLayer(String name)
        {
            using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db  = doc.Database;
                Editor   ed  = doc.Editor;

                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                    SymbolUtilityServices.ValidateSymbolName(name, false);
                    if (lt.Has(name))
                    {
                        foreach (ObjectId layerId in lt)
                        {
                            LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;

                            if (layer.Name.CompareTo(name) == 0)
                            {
                                return(layerId);
                            }
                        }
                    }
                }
                return(ObjectId.Null);
            }
        }
Esempio n. 29
0
        private void InsertDwgFile(Point3d Position)
        {
            string           BlockName  = Path.GetFileNameWithoutExtension(this.filePath);
            BlockTable       blockTable = trans.GetObject(currentDwg.BlockTableId, OpenMode.ForWrite) as BlockTable;
            BlockTableRecord modelSpace = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(currentDwg).GetObject(OpenMode.ForWrite);

            if (!File.Exists(this.filePath))
            {
                Ed.WriteMessage("Error404: 文件" + this.filePath + "未找到" + "\n");
                return;
            }
            else
            {
                Database insertDb = this.GetDwgFile(this.filePath);
                try
                {
                    ObjectId id = blockTable[BlockName];
                    //    if (!((BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(currentDwg).GetObject(OpenMode.ForRead)).GetType())
                    Ed.WriteMessage("插入失败,当前已存在名为:" + BlockName + "的块参照" + "\n");
                }
                catch
                {
                    ObjectId id = currentDwg.Insert(Path.GetFileNameWithoutExtension(this.filePath) + "_I", insertDb, true);
                    //ObjectId id = currentDwg.OverlayXref(this.filePath, Path.GetDirectoryName(this.filePath)+"_I");
                    BlockReference br = new BlockReference(Position, id);
                    modelSpace.AppendEntity(br);
                    trans.AddNewlyCreatedDBObject(br, true);
                }
            }
        }
Esempio n. 30
0
        /// <summary>
        /// 객체를 삽입합니다.
        /// </summary>
        /// <param name="entity">삽입할 객체입니다.</param>
        public static ObjectId InsertEntity(Entity entity)
        {
            Document doc      = DatabaseUtil.GetActiveDocument();
            Database db       = doc.Database;
            ObjectId idResult = ObjectId.Null;

            try
            {
                using (doc.LockDocument())
                {
                    using (Transaction tr = DatabaseUtil.GetTransaction(db))
                    {
                        BlockTableRecord oModelSpace = tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite) as BlockTableRecord;
                        idResult = oModelSpace.AppendEntity(entity);
                        tr.AddNewlyCreatedDBObject(entity, true);

                        tr.Commit();
                    }
                }

                return(idResult);
            }
            catch (System.Exception ex)
            {
                return(ObjectId.Null);
            }
        }