/// <summary>
        /// 在AutoCAD图形中插入块参照
        /// </summary>
        /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param>
        /// <param name="layer">块参照要加入的图层名</param>
        /// <param name="blockName">块参照所属的块名</param>
        /// <param name="position">插入点</param>
        /// <param name="scale">缩放比例</param>
        /// <param name="rotateAngle">旋转角度</param>
        /// <param name="attNameValues">属性的名称与取值</param>
        /// <returns>返回块参照的Id</returns>
        public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle)
        {
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            ObjectId     blockRefId;
            Database     db = spaceId.Database;
            BlockTable   bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);

            if (!bt.Has(blockName))
            {
                return(ObjectId.Null);
            }
            BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite);
            BlockReference   br    = new BlockReference(position, bt[blockName]);

            br.ScaleFactors = scale;
            br.Layer        = layer;
            br.Rotation     = rotateAngle;
            ObjectId         btrId  = bt[blockName];
            BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead);

            if (record.Annotative == AnnotativeStates.True)
            {
                ObjectContextCollection contextCollection = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");
                ObjectContexts.AddContext(br, contextCollection.GetContext("1:1"));
            }
            blockRefId = space.AppendEntity(br);
            db.TransactionManager.AddNewlyCreatedDBObject(br, true);
            space.DowngradeOpen();
            docLock.Dispose();
            return(blockRefId);
        }
Пример #2
0
        public BlockReference copyDynamicBlock(BlockTableRecord spaceRecord, ref BlockReference bref, ref BlockTableRecord br, Transaction tr)
        {
            BlockReference newbref = copyBlockReference(ref bref, ref br);

            //newbref.UpgradeOpen();
            //spaceRecord.DowngradeOpen();
            spaceRecord.UpgradeOpen();
            spaceRecord.AppendEntity(newbref);
            tr.AddNewlyCreatedDBObject(newbref, true);
            spaceRecord.DowngradeOpen();

            //newbref.Visible = false;

            for (int i = 0; i < bref.DynamicBlockReferencePropertyCollection.Count; i++)
            {
                for (int j = 0; j < newbref.DynamicBlockReferencePropertyCollection.Count; j++)
                {
                    if (!newbref.DynamicBlockReferencePropertyCollection[j].ReadOnly &&
                        !bref.DynamicBlockReferencePropertyCollection[i].ReadOnly &&
                        newbref.DynamicBlockReferencePropertyCollection[j].PropertyName == bref.DynamicBlockReferencePropertyCollection[i].PropertyName
                        )
                    {
                        newbref.DynamicBlockReferencePropertyCollection[j].Value = bref.DynamicBlockReferencePropertyCollection[i].Value;
                    }
                }
            }
            return(newbref);
        }
Пример #3
0
        public BlockReference createAnonymousBlock(BlockTable bt, List <Entity> entities, BlockTableRecord spaceRecord, Transaction tr, Database db)
        {
            BlockTableRecord btr = new BlockTableRecord();

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

            tr.AddNewlyCreatedDBObject(btr, true);


            ObjectIdCollection obIdCol = new ObjectIdCollection();

            foreach (Entity ent in entities)
            {
                //ent.TransformBy(matrix);
                obIdCol.Add(ent.ObjectId);
            }

            IdMapping mapping = new IdMapping();

            db.DeepCloneObjects(obIdCol, btrId, mapping, false);

            BlockReference bref = new BlockReference(Point3d.Origin, btrId);

            spaceRecord.AppendEntity(bref);
            tr.AddNewlyCreatedDBObject(bref, true);
            spaceRecord.DowngradeOpen();

            foreach (Entity ent in entities)
            {
                ent.Erase();
            }
            return(bref);
        }
Пример #4
0
        /// <summary> 插入一个块参照到CAD图形中 </summary>
        /// <param name="spaceId">模型空间Id</param>
        /// <param name="layer">要插入的图层名</param>
        /// <param name="insertedBlockName">块名</param>
        /// <param name="postion">插入点</param>
        /// <param name="scale">缩放比例</param>
        /// <param name="rotateAngle">旋转角度</param>
        /// <returns> 返回添加的块参照的ID  </returns>
        public static ObjectId InsertBlockRef(ObjectId spaceId, string layer, string insertedBlockName,
                                              Point3d postion, Scale3d scale, double rotateAngle)
        {
            ObjectId blockRefId;            //存储要插入的块参照的Id

            Database db = spaceId.Database; //获取数据库对象

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

            if (!bt.Has(insertedBlockName))
            {
                return(ObjectId.Null); //如果没有blockName的块,程序返回
            }
            //以写的方式打开空间
            BlockTableRecord btr = spaceId.GetObject(OpenMode.ForWrite) as BlockTableRecord;
            //创建块参照的插入点
            BlockReference br = new BlockReference(postion, bt[insertedBlockName]);

            br.ScaleFactors = scale;

            br.Layer = layer;

            br.Rotation = rotateAngle;
            blockRefId  = btr.AppendEntity(br);

            db.TransactionManager.AddNewlyCreatedDBObject(br, true);

            btr.DowngradeOpen();

            return(blockRefId); //返回添加的块参照的ID
        }
Пример #5
0
        /// <summary>
        /// 用于在AutoCAD图形中插入块参照
        /// </summary>
        /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param>
        /// <param name="layer">块参照要加入的图层名</param>
        /// <param name="blockName">块参照所属的块名</param>
        /// <param name="position">块参照的插入点</param>
        /// <param name="scale">块参照的缩放比例</param>
        /// <param name="rotateAngle">块参照的旋转角度</param>
        /// <returns></returns>
        public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle)
        {
            ObjectId blockRefId;
            Database db = spaceId.Database;
            //打开块表
            BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);

            if (!bt.Has(blockName))
            {
                return(ObjectId.Null);
            }
            //以写的方式打开空间(模型空间或图纸空间)
            BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite);
            //创建一个块参照并设置插入点
            BlockReference br = new BlockReference(position, bt[blockName])
            {
                //设置块参照的缩放比例
                ScaleFactors = scale,
                //设置块参照的层名
                Layer = layer,
                //设置块参照的旋转角度
                Rotation = rotateAngle
            };

            //在空间中加入创建的块参照
            blockRefId = space.AppendEntity(br);
            //通知事务处理加入创建的块参照
            db.TransactionManager.AddNewlyCreatedDBObject(br, true);
            space.DowngradeOpen();
            return(blockRefId);
        }
Пример #6
0
        /// <summary>
        /// 在AutoCAD图形中插入块参照
        /// </summary>
        /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param>
        /// <param name="layer">块参照要加入的图层名</param>
        /// <param name="blockName">块参照所属的块名</param>
        /// <param name="position">插入点</param>
        /// <param name="scale">缩放比例</param>
        /// <param name="rotateAngle">旋转角度</param>
        /// <returns>返回块参照的Id</returns>
        public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle)
        {
            ObjectId blockRefId;            //存储要插入的块参照的Id
            Database db = spaceId.Database; //获取数据库对象
            //以读的方式打开块表
            BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);

            //如果没有blockName表示的块,则程序返回
            if (!bt.Has(blockName))
            {
                return(ObjectId.Null);
            }
            //以写的方式打开空间(模型空间或图纸空间)
            BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite);
            //创建一个块参照并设置插入点
            BlockReference br = new BlockReference(position, bt[blockName]);

            br.ScaleFactors = scale;        //设置块参照的缩放比例
            br.Layer        = layer;        //设置块参照的层名
            br.Rotation     = rotateAngle;  //设置块参照的旋转角度
            ObjectId btrId = bt[blockName]; //获取块表记录的Id
            //打开块表记录
            BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead);

            //添加可缩放性支持
            if (record.Annotative == AnnotativeStates.True)
            {
                ObjectContextCollection contextCollection = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");
                ObjectContexts.AddContext(br, contextCollection.GetContext("1:1"));
            }
            blockRefId = space.AppendEntity(br);                     //在空间中加入创建的块参照
            db.TransactionManager.AddNewlyCreatedDBObject(br, true); //通知事务处理加入创建的块参照
            space.DowngradeOpen();                                   //为了安全,将块表状态改为读
            return(blockRefId);                                      //返回添加的块参照的Id
        }
        public void LJX()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            string layerName = db.GetCurrentLayerName();

            ed.WriteMessage("\n百福工具箱——连接两根多段线的顶点");

            PromptEntityOptions peo1 = new PromptEntityOptions("\n请选择第一根多端线");

            peo1.SetRejectMessage("\n选择的多段线!");
            peo1.AddAllowedClass(typeof(Polyline), false);
            PromptEntityResult ent1;

            do
            {
                ent1 = ed.GetEntity(peo1);
            } while (ent1.Status != PromptStatus.OK);

            PromptEntityOptions peo2 = new PromptEntityOptions("\n请选择第一根多端线");

            peo2.SetRejectMessage("\n选择的多段线!");
            peo2.AddAllowedClass(typeof(Polyline), false);
            PromptEntityResult ent2 = ed.GetEntity(peo2);

            if (ent1.Status == PromptStatus.OK)
            {
                db.SetCurrentLayer("BF-细线");
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    BlockTable bt  = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                    Polyline   pl1 = (Polyline)trans.GetObject(ent1.ObjectId, OpenMode.ForRead);
                    Polyline   pl2 = (Polyline)trans.GetObject(ent2.ObjectId, OpenMode.ForRead);

                    int vertexNum = Math.Min(pl1.NumberOfVertices, pl2.NumberOfVertices);

                    for (int i = 0; i < vertexNum; i++)
                    {
                        BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                        Point3d pt1 = pl1.GetPoint3dAt(i);
                        Point3d pt2 = pl2.GetPoint3dAt(i);
                        Line    l1  = new Line(pt1, pt2);
                        btr.AppendEntity(l1);
                        trans.AddNewlyCreatedDBObject(l1, true);
                        btr.DowngradeOpen();
                    }
                    trans.Commit();
                }
                db.SetCurrentLayer(layerName);
            }
            else
            {
                return;
            }
        }
Пример #8
0
        /// <summary>
        /// 将实体添加到当前空间
        /// </summary>
        /// <param name="db">数据库对象</param>
        /// <param name="ent">要添加的实体</param>
        /// <returns>返回添加到当前空间中的实体ObjectId</returns>
        public static ObjectId AddToCurrentSpace(this Database db, Entity ent)
        {
            var trans            = db.TransactionManager;
            BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
            ObjectId         id  = btr.AppendEntity(ent);

            trans.AddNewlyCreatedDBObject(ent, true);
            btr.DowngradeOpen();
            return(id);
        }
Пример #9
0
        public static ObjectId AddToModelSpace(this Database db, Entity ent)
        {
            ObjectId         id    = new ObjectId();
            var              trans = db.TransactionManager;
            BlockTableRecord btr   = (BlockTableRecord)trans.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);

            id = btr.AppendEntity(ent);
            trans.AddNewlyCreatedDBObject(ent, true);
            btr.DowngradeOpen();
            return(id);
        }
Пример #10
0
 /// <summary>
 /// 删除多段线中的多余点并将应闭合的多段线闭合
 /// </summary>
 public static void PLinePurge(this Database db, ObjectId id)
 {
     using (Transaction trans = db.TransactionManager.StartTransaction())
     {
         // 打开块表
         BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
         // 打开块表记录
         BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
         // 获取图形对象
         Entity ent = trans.GetObject(id, OpenMode.ForWrite) as Entity;
         if (ent.GetType() == typeof(Polyline))
         {
             Polyline  pline     = ent as Polyline;
             PLineData plinedata = db.GetPLineData(id);
             /// 删除多段线中的多余点
             if (plinedata.VertexCount > 2)
             {
                 // 为避免下标出现问题, 从下标最大处开始遍历
                 for (int i = plinedata.VertexCount - 2; i > 0; i--)
                 {
                     if (plinedata.Vectors[i - 1] == plinedata.Vectors[i])
                     {
                         btr.UpgradeOpen();
                         pline.RemoveVertexAt(i);
                         btr.DowngradeOpen();
                     }
                 }
             }
             // 重新读取
             plinedata = db.GetPLineData(id);
             if (plinedata.VertexPoints[0] == plinedata.VertexPoints[plinedata.VertexCount - 1])
             {
                 btr.UpgradeOpen();
                 pline.Closed = true;
                 pline.RemoveVertexAt(plinedata.VertexCount - 1);
                 btr.DowngradeOpen();
             }
         }
         trans.Commit();
     }
 }
Пример #11
0
        public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle, ref double xLen)
        {
            ObjectId blockRefId;//存储要插入的块参照的Id
            //Database db = spaceId.Database;//获取数据库对象
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //以读的方式打开块表
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);

                //如果没有blockName表示的块,则程序返回
                if (!bt.Has(blockName))
                {
                    return(ObjectId.Null);
                }
                //以写的方式打开空间(模型空间或图纸空间)
                //打开数据库的模型空间块表记录对象
                BlockTableRecord space = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);


                //创建一个块参照并设置插入点
                BlockReference br = new BlockReference(position, bt[blockName]);
                br.ScaleFactors = scale;        //设置块参照的缩放比例
                br.Layer        = layer;        //设置块参照的层名
                br.Rotation     = rotateAngle;  //设置块参照的旋转角度
                ObjectId btrId = bt[blockName]; //获取块表记录的Id

                //打开块表记录
                //BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead);
                //添加可缩放性支持
                //if (record.Annotative == AnnotativeStates.True)
                {
                    //ObjectContextCollection contextCollection = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");
                    //ObjectContexts.AddContext(br, contextCollection.GetContext("1:1"));
                }
                blockRefId = space.AppendEntity(br);                     //在空间中加入创建的块参照
                db.TransactionManager.AddNewlyCreatedDBObject(br, true); //通知事务处理加入创建的块参照
                space.DowngradeOpen();                                   //为了安全,将块表状态改为读

                Entity entity = (Entity)trans.GetObject(blockRefId, OpenMode.ForRead);
                xLen = entity.GeomExtents.MaxPoint.X - entity.GeomExtents.MinPoint.X;
                entity.Dispose();

                trans.Commit();
            }



            return(blockRefId);//返回添加的块参照的Id
        }
Пример #12
0
        public static ObjectIdCollection AddToModelSpace(this Database db, params Entity[] ents)
        {
            ObjectIdCollection ids = new ObjectIdCollection();
            var trans            = db.TransactionManager;
            BlockTableRecord btr = (BlockTableRecord)trans.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);

            foreach (var ent in ents)
            {
                ids.Add(btr.AppendEntity(ent));
                trans.AddNewlyCreatedDBObject(ent, true);
            }
            btr.DowngradeOpen();
            return(ids);
        }
Пример #13
0
        /// <summary>
        /// 为块表记录添加属性
        /// </summary>
        /// <param name="blockId">块表记录的Id</param>
        /// <param name="atts">要加入的块属性列表</param>
        public static void AddAttsToBlock(this ObjectId blockId, List <AttributeDefinition> atts)
        {
            Database db = blockId.Database;//获取数据库对象
            //打开块表记录为写的状态
            BlockTableRecord btr = (BlockTableRecord)blockId.GetObject(OpenMode.ForWrite);

            //遍历属性定义对象列表
            foreach (AttributeDefinition att in atts)
            {
                btr.AppendEntity(att);                                    //为块表记录添加属性
                db.TransactionManager.AddNewlyCreatedDBObject(att, true); //通知事务处理
            }
            btr.DowngradeOpen();                                          //为了安全,将块表记录的状态改为读
        }
Пример #14
0
        public Line copyLine(BlockTableRecord spaceRecord, ref Line line, Transaction tr)
        {
            Line newLine = new Line();

            newLine.StartPoint = line.StartPoint;
            newLine.EndPoint   = line.EndPoint;
            newLine.Normal     = line.Normal;
            newLine.Layer      = swallLayer;
            spaceRecord.UpgradeOpen();
            spaceRecord.AppendEntity(newLine);
            tr.AddNewlyCreatedDBObject(newLine, true);
            spaceRecord.DowngradeOpen();

            return(newLine);
        }
Пример #15
0
        internal static void AddingAttributeToBlock(string blkName)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);

                if (!bt.Has(blkName))
                {
                    ed.WriteMessage("\nBlock definition PART does not  exist");
                    return;
                }

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[blkName], OpenMode.ForRead, false);

                // location of the AttributeDefinition in the
                // block definition
                Point3d ptloc = new Point3d(0, 2, 0);

                // create a AttributeDefinition
                // specify the text,tag and prompt
                string attrValue = "NEW VALUE ADDED";
                string attrTag   = "MYTAG";
                string strprompt = "Enter a new value";

                // used current text style
                AttributeDefinition attDef = new AttributeDefinition(ptloc, attrValue, attrTag, strprompt, db.Textstyle);
                attDef.Height     = 0.12;
                attDef.Layer      = "0";
                attDef.Color      = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 0);
                attDef.LinetypeId = db.ContinuousLinetype;

                // append the AttributeDefinition to the definition
                btr.UpgradeOpen();
                btr.AppendEntity(attDef);
                tr.AddNewlyCreatedDBObject(attDef, true);
                btr.DowngradeOpen();
                tr.Commit();
            }
        }
Пример #16
0
 /// <summary>
 /// 修改矩形宽度
 /// </summary>
 public static void SetRectangleWidth(this Database db, ObjectId id, double newWidth)
 {
     if (db.IsRectangle(id))
     {
         RectangleData data      = db.GetRectangleData(id);
         int           baseIndex = data.BasePointIndex;
         Point3d       basePoint = data.BasePoint;
         bool          clockWise = data.IsClockWise;
         double        width     = data.Width;
         double        height    = data.Height;
         using (Transaction trans = db.TransactionManager.StartTransaction())
         {
             // 打开块表
             BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
             // 打开块表记录
             BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
             // 获取图形对象
             Entity ent = trans.GetObject(id, OpenMode.ForWrite) as Entity;
             if (ent.GetType() == typeof(Polyline))
             {
                 Polyline pline = ent as Polyline;
                 btr.UpgradeOpen();
                 pline.SetPointAt(baseIndex, new Point2d(basePoint.X - newWidth / 2, basePoint.Y));
                 if (clockWise)
                 {
                     pline.SetPointAt((baseIndex + 1) % 4, new Point2d(basePoint.X - newWidth / 2, basePoint.Y + height));
                     pline.SetPointAt((baseIndex + 2) % 4, new Point2d(basePoint.X + width + newWidth / 2, basePoint.Y + height));
                     pline.SetPointAt((baseIndex + 3) % 4, new Point2d(basePoint.X + width + newWidth / 2, basePoint.Y));
                 }
                 else
                 {
                     pline.SetPointAt((baseIndex + 1) % 4, new Point2d(basePoint.X + width + newWidth / 2, basePoint.Y));
                     pline.SetPointAt((baseIndex + 2) % 4, new Point2d(basePoint.X + width + newWidth / 2, basePoint.Y + height));
                     pline.SetPointAt((baseIndex + 3) % 4, new Point2d(basePoint.X - newWidth / 2, basePoint.Y + height));
                 }
                 btr.DowngradeOpen();
             }
             trans.Commit();
         }
     }
 }
Пример #17
0
        public Line CopyLine(BlockTableRecord spaceRecord, ref Line line, Transaction tr)
        {
            Line newLine = new Line();

            newLine.StartPoint = line.StartPoint;
            newLine.EndPoint   = line.EndPoint;
            newLine.Normal     = line.Normal;
            //newLine.Layer = line.Layer.Split('|').Last();
            newLine.Layer = frameBlockAboveLayer;
            //newLine.Linetype = line.Linetype;
            newLine.Linetype      = "SWALL";
            newLine.PlotStyleName = line.PlotStyleName;
            newLine.Color         = line.Color;
            newLine.ColorIndex    = line.ColorIndex;

            spaceRecord.UpgradeOpen();
            spaceRecord.AppendEntity(newLine);
            tr.AddNewlyCreatedDBObject(newLine, true);
            spaceRecord.DowngradeOpen();

            return(newLine);
        }
Пример #18
0
 public static void EraseBolckTableRecord(this BlockTableRecord btr)
 {
     Tools.StartTransaction(() =>
     {
         if (btr.Id != ObjectId.Null)
         {
             btr = btr.Id.GetObjectForRead <BlockTableRecord>(false);
             if (!btr.IsErased)
             {
                 btr.UpgradeOpen();
                 using (BlockTableRecordEnumerator enumerator = btr.GetEnumerator())
                 {
                     while (enumerator.MoveNext())
                     {
                         enumerator.Current.GetObject((OpenMode)OpenMode.ForWrite).Erase();
                     }
                 }
                 btr.DowngradeOpen();
             }
         }
     });
 }
Пример #19
0
        private static AttributeDefinition defineAtrDefTypeFlat(BlockTableRecord btrApart, string typeFlatValue)
        {
            // Поиск существующего атрибута типа квартиры
            if (btrApart.HasAttributeDefinitions)
            {
                foreach (var idEnt in btrApart)
                {
                    if (idEnt.ObjectClass.Name != "AcDbAttributeDefinition")
                    {
                        continue;
                    }
                    var atrDef = idEnt.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition;
                    if (atrDef == null || !atrDef.Tag.Equals(Options.Instance.ApartmentTypeFlatParameter))
                    {
                        continue;
                    }
                    atrDef.UpgradeOpen();
                    atrDef.TextString          = typeFlatValue;
                    atrDef.Invisible           = true;
                    atrDef.LockPositionInBlock = true;
                    atrDef.DowngradeOpen();
                    return(atrDef);
                }
            }
            // Создание определения атрибута и добавление в блок
            AttributeDefinition atrDefTypeFlat = new AttributeDefinition(Point3d.Origin, typeFlatValue,
                                                                         Options.Instance.ApartmentTypeFlatParameter,
                                                                         "Параметр типа квартиры - Студия, 1комн, и т.д.", btrApart.Database.GetTextStylePIK());

            atrDefTypeFlat.Invisible           = true;
            atrDefTypeFlat.LockPositionInBlock = true;
            btrApart.UpgradeOpen();
            btrApart.AppendEntity(atrDefTypeFlat);
            btrApart.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(atrDefTypeFlat, true);
            btrApart.DowngradeOpen();
            return(atrDefTypeFlat);
        }
Пример #20
0
        public Polyline CopyPolyline(BlockTableRecord spaceRecord, ref Polyline pline, Transaction tr)
        {
            Polyline newpLine = new Polyline();
            int      max      = pline.NumberOfVertices;

            for (int i = 0; i < max; i++)
            {
                newpLine.AddVertexAt(i, pline.GetPoint2dAt(i), pline.GetBulgeAt(i), pline.GetStartWidthAt(i), pline.GetEndWidthAt(i));
            }

            newpLine.Closed = pline.Closed;
            //newpLine.Layer = pline.Layer.Split('|').Last();
            newpLine.Layer      = frameBlockAboveLayer;
            newpLine.Normal     = pline.Normal;
            newpLine.Color      = pline.Color;
            newpLine.ColorIndex = pline.ColorIndex;

            spaceRecord.UpgradeOpen();
            spaceRecord.AppendEntity(newpLine);
            tr.AddNewlyCreatedDBObject(newpLine, true);
            spaceRecord.DowngradeOpen();

            return(newpLine);
        }
Пример #21
0
        public void autoBlockFit(Database db, BlockTableRecord blockTR, Transaction tr)
        {
            Point3d DownLeft_Point = new Point3d();
            Point3d UpRight_Point  = new Point3d();
            string  compareResult  = string.Empty;

            bool started = false;

            try
            {
                blockTR.UpgradeOpen();
                DBObjectCollection EntityInOldBlock = new DBObjectCollection();
                string             blockName        = blockTR.Name;
                foreach (ObjectId entId in blockTR)
                {
                    DBObject objSubBlock = (DBObject)tr.GetObject(entId, OpenMode.ForWrite);
                    EntityInOldBlock.Add(objSubBlock);
                    if (objSubBlock.Bounds == null)
                    {
                        continue;
                    }
                    else
                    {
                        if (started == false)
                        {
                            UpRight_Point  = objSubBlock.Bounds.Value.MaxPoint;
                            DownLeft_Point = objSubBlock.Bounds.Value.MinPoint;
                            started        = true;
                            continue;
                        }
                        else
                        {
                            string compareMaxRes = string.Empty;
                            string compareMinRes = string.Empty;

                            if (objSubBlock.Bounds.Value.MaxPoint.X > UpRight_Point.X)
                            {
                                UpRight_Point = new Point3d(objSubBlock.Bounds.Value.MaxPoint.X, UpRight_Point.Y, UpRight_Point.Z);
                            }
                            if (objSubBlock.Bounds.Value.MaxPoint.Y > UpRight_Point.Y)
                            {
                                UpRight_Point = new Point3d(UpRight_Point.X, objSubBlock.Bounds.Value.MaxPoint.Y, UpRight_Point.Z);
                            }

                            if (objSubBlock.Bounds.Value.MinPoint.X < DownLeft_Point.X)
                            {
                                DownLeft_Point = new Point3d(objSubBlock.Bounds.Value.MinPoint.X, DownLeft_Point.Y, UpRight_Point.Z);
                            }
                            if (objSubBlock.Bounds.Value.MinPoint.Y < DownLeft_Point.Y)
                            {
                                DownLeft_Point = new Point3d(DownLeft_Point.X, objSubBlock.Bounds.Value.MinPoint.Y, UpRight_Point.Z);
                            }
                        }
                    }
                    objSubBlock.DowngradeOpen();
                }
                //CreateBlock(blockTR.Name, EntityInOldBlock, DownLeft_Point);

                objectBound ob = new objectBound(DownLeft_Point, UpRight_Point);
                sizeEntity.Add(blockName, ob);
                blockTR.Origin = DownLeft_Point;
                blockTR.DowngradeOpen();


                //minPoint和maxPoint只差为块的大小.
                //通过缩放解决图形大小的问题.

                //minPoint的位置为块离原点的距离,默认为离基点的距离.
                //通过平移解决插入位置的问题


                /*
                 * Polyline c1 = new Polyline();
                 * c1.CreatePolyCircle(new Point2d(UpRight_Point.X, UpRight_Point.Y), 5);
                 *
                 * Polyline c2 = new Polyline();
                 * c2.CreatePolyCircle(new Point2d(DownLeft_Point.X, DownLeft_Point.Y), 5); ;
                 *
                 * c1.ColorIndex = 200; //upright
                 * c2.ColorIndex = 100;
                 * //db.AddToModelSpace(c1, c2);
                 *
                 * try
                 * {
                 *  blockTR.UpgradeOpen();
                 *  blockTR.AppendEntity(c1);
                 *  blockTR.AppendEntity(c2);
                 *  tr.AddNewlyCreatedDBObject(c1, true);
                 *  tr.AddNewlyCreatedDBObject(c2, true);
                 *  blockTR.DowngradeOpen();
                 *
                 *
                 *
                 * }
                 * catch (Exception ee)
                 * {
                 *  MessageBox.Show(ee + "");
                 * }
                 */
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ee)
            {
            }
        }
Пример #22
0
        addBlockRef(string strName, string strTopNum, string strTopTxt, string strBotNum, string strBotTxt, Point3d pnt3dIns, double dblRotation)
        {
            Database DB = BaseObjs._db;
            Editor   ED = BaseObjs._editor;

            ObjectId         blkID = ObjectId.Null;
            BlockTableRecord Btrx  = null;

            using (Transaction tr = BaseObjs.startTransactionDb())
            {
                BlockTable BT = (BlockTable)DB.BlockTableId.GetObject(OpenMode.ForRead);
                if (!BT.Has(strName))
                {
                    blkID = insBlockRef(@"R:\Tset\Block\", "GradeTag.dwg");
                    Btrx  = (BlockTableRecord)blkID.GetObject(OpenMode.ForRead);
                    Btrx.UpgradeOpen();
                    Btrx.Name = "GradeTag";
                    Btrx.DowngradeOpen();
                }
                else
                {
                    Btrx = (BlockTableRecord)BT[strName].GetObject(OpenMode.ForRead);
                }

                //---> debug only
                foreach (ObjectId objID in Btrx)
                {
                    Entity ENT             = (Entity)objID.GetObject(OpenMode.ForRead);
                    AttributeDefinition AD = ENT as AttributeDefinition;

                    if (AD != null)
                    {
                        ED.WriteMessage(string.Format("\n{0}", AD.Tag));
                    }
                }//<--- debug only

                BlockTableRecord Btr = (BlockTableRecord)DB.CurrentSpaceId.GetObject(OpenMode.ForWrite);

                using (Btr)
                {
                    BlockReference BR = new BlockReference(pnt3dIns, Btrx.ObjectId);
                    using (BR)
                    {
                        Matrix3d           UCSMatrix = ED.CurrentUserCoordinateSystem;
                        CoordinateSystem3d UCS       = UCSMatrix.CoordinateSystem3d;

                        Matrix3d MAT3d = new Matrix3d();
                        MAT3d = Matrix3d.Rotation(dblRotation, UCS.Zaxis, pnt3dIns);

                        BR.TransformBy(MAT3d);
                        BR.ScaleFactors = new Scale3d(1, 1, 1);
                        Btr.AppendEntity(BR);
                        tr.AddNewlyCreatedDBObject(BR, true);

                        BlockTableRecord Btratt = (BlockTableRecord)BR.BlockTableRecord.GetObject(OpenMode.ForRead);
                        using (Btratt)
                        {
                            Autodesk.AutoCAD.DatabaseServices.AttributeCollection ATTcol = BR.AttributeCollection;

                            foreach (ObjectId subID in Btratt)
                            {
                                Entity ENT             = (Entity)subID.GetObject(OpenMode.ForRead);
                                AttributeDefinition AD = ENT as AttributeDefinition;

                                if (AD != null)
                                {
                                    AttributeReference AR = new AttributeReference();
                                    AR.SetPropertiesFrom(AD);
                                    AR.SetAttributeFromBlock(AD, BR.BlockTransform);
                                    AR.Visible = AD.Visible;

                                    AR.HorizontalMode = AD.HorizontalMode;
                                    AR.VerticalMode   = AD.VerticalMode;
                                    AR.Rotation       = AD.Rotation;
                                    AR.TextStyleId    = AD.TextStyleId;
                                    AR.Position       = AD.Position + pnt3dIns.GetAsVector();
                                    AR.Tag            = AD.Tag;
                                    AR.FieldLength    = AD.FieldLength;
                                    AR.AdjustAlignment(DB);

                                    if (AR.Tag == "TOPNUM")
                                    {
                                        AR.TextString = strTopNum;
                                    }

                                    if (AR.Tag == "TOPTXT")
                                    {
                                        AR.TextString = strTopTxt;
                                    }

                                    if (AR.Tag == "BOTNUM")
                                    {
                                        AR.TextString = strBotNum;
                                    }

                                    if (AR.Tag == "BOTTXT")
                                    {
                                        AR.TextString = strBotTxt;
                                    }

                                    AR.Position = AD.Position.TransformBy(BR.BlockTransform);

                                    ATTcol.AppendAttribute(AR);
                                    tr.AddNewlyCreatedDBObject(AR, true);
                                } // end if
                            }     //end foreach
                        }
                        BR.DowngradeOpen();
                    }

                    Btr.DowngradeOpen();
                }

                // BT.DowngradeOpen ();
                tr.Commit();
            }
            return(true);
        }
Пример #23
0
        public void autoBlockScaleFit(Database db, BlockTableRecord blockTR, Transaction tr, Editor ed)
        {
            List <string> entType = new List <string>();

            try
            {
                string testST = blockTR.Name;
                foreach (ObjectId entId in blockTR)
                {
                    Object objSubBlock = (Object)tr.GetObject(entId, OpenMode.ForWrite);
                    Entity entSubBlock = objSubBlock as Entity;
                    if (entSubBlock != null)
                    {
                        //DBObject objSubBlock = (DBObject)tr.GetObject(entId, OpenMode.ForWrite);


                        if (!typeAndNum.ContainsKey(entSubBlock.GetType().Name.ToString()))
                        {
                            typeAndNum.Add(entSubBlock.GetType().Name.ToString(), 1);
                        }
                        else
                        {
                            int numType = typeAndNum[entSubBlock.GetType().Name.ToString()];
                            typeAndNum[entSubBlock.GetType().Name.ToString()] = numType + 1;
                        }

                        //
                        Point3d maxPoint;
                        Point3d minPoint;
                        //Point3d maxPoint1;
                        //Point3d minPoint1;
                        if (true)
                        {
                            maxPoint = entSubBlock.GeometricExtents.MaxPoint;
                            minPoint = entSubBlock.GeometricExtents.MinPoint;


                            //maxPoint1 = entSubBlock.Bounds.Value.MaxPoint;
                            //minPoint1 = entSubBlock.Bounds.Value.MinPoint;

                            /*Polyline c1 = new Polyline();
                             * c1.CreatePolyCircle(new Point2d(maxPoint.X, maxPoint.Y), 5);
                             *
                             * Polyline c2 = new Polyline();
                             * c2.CreatePolyCircle(new Point2d(minPoint.X, minPoint.Y), 5);
                             *
                             * db.AddToModelSpace(c1, c2);*/
                        }
                        else
                        {
                        }


                        //

                        //

                        //

                        string[] temp = entSubBlock.GetType().ToString().ToLower().Split(new[] { "." }, StringSplitOptions.None);
                        string   type = temp[temp.Length - 1];
                        switch (type)
                        {
                        case ("line"):
                            //entSubBlock.GeometricExtents.MaxPoint

                            break;

                        case ("mline"):
                            //entSubBlock
                            break;

                        case ("hatch"):
                            //entSubBlock
                            //entSubBlock.Highlight();
                            break;

                        case ("polyline"):
                            //entSubBlock
                            break;

                        case ("circle"):
                            //entSubBlock
                            maxPoint = entSubBlock.GeometricExtents.MaxPoint;
                            minPoint = entSubBlock.GeometricExtents.MinPoint;

                            Polyline c1 = new Polyline();
                            c1.CreatePolyCircle(new Point2d(maxPoint.X, maxPoint.Y), 5);

                            Polyline c2 = new Polyline();
                            c2.CreatePolyCircle(new Point2d(minPoint.X, minPoint.Y), 5);

                            c1.ColorIndex = entSubBlock.ColorIndex;
                            c2.ColorIndex = entSubBlock.ColorIndex;

                            try
                            {
                                blockTR.UpgradeOpen();
                                blockTR.AppendEntity(c1);
                                blockTR.AppendEntity(c2);
                                blockTR.DowngradeOpen();
                            }
                            catch (Exception)
                            {
                                throw;
                            }

                            //db.AddToModelSpace(c1, c2);
                            break;

                        case ("dbtext"):

                            break;

                        case ("elipse"):

                            break;

                        case ("arc"):

                            break;

                        case ("block reference"):

                            break;

                        case ("aligned dimension"):

                            break;

                        case ("attribute definition"):

                            break;
                        }
                        entSubBlock.DowngradeOpen();
                    }
                    else
                    {
                        //
                    }
                }
            }
            catch (Exception ee)
            {
                //tr.Abort();
                MessageBox.Show("" + ee + System.Environment.NewLine + blockTR.Name, "错误");
                ed.WriteMessage("错误信息: " + ee.Message + System.Environment.NewLine + "块" + blockTR.Name);
            }
        }
Пример #24
0
        // Thêm 1 block chứa bản vẽ của 1 file dwg vào bản vẽ hiện tại (có scale riêng)
        public static bool InsertDrawing(string partDwg, Scale3d scale, Point3d ipt, double angle, out ObjectId objectId)
        {
            Document doc       = AcAp.DocumentManager.MdiActiveDocument;
            Database curdb     = doc.Database; // Biến database của bản vẽ hện tại
            Editor   ed        = doc.Editor;
            string   blockname = Path.GetFileNameWithoutExtension(partDwg);
            bool     result    = false;

            objectId = ObjectId.Null;

            using (DocumentLock loc = doc.LockDocument())
            {
                ObjectId blkid = ObjectId.Null; // Biến lấy ID của file đọc vào
                try
                {
                    using (Database db = new Database(false, true))                  // Biến lấy database của file nạp vào
                    {
                        db.ReadDwgFile(partDwg, System.IO.FileShare.Read, true, ""); // Lấy database
                        blkid = curdb.Insert(partDwg, db, true);                     // Lấy ID
                    }
                }
                catch (IOException)
                {
                    return(false);
                }

                using (Transaction tr = doc.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(curdb.BlockTableId, OpenMode.ForRead);
                    if (!bt.Has(blockname))
                    {
                        bt.UpgradeOpen();
                        BlockTableRecord btrec = blkid.GetObject(OpenMode.ForRead) as BlockTableRecord;
                        btrec.UpgradeOpen();    //nâng cấp để ghi
                        btrec.Name = blockname; //thêm tên
                        btrec.DowngradeOpen();  //hạ cấp, không cho ghi nữa
                        bt.DowngradeOpen();
                    }
                    blkid = bt[blockname];

                    //Thêm các hình vẽ ở bản vẽ cũ vào
                    using (BlockTableRecord btr = (BlockTableRecord)curdb.CurrentSpaceId.GetObject(OpenMode.ForWrite))
                    {
                        //Insert vật thể
                        using (BlockReference bref = new BlockReference(ipt, blkid))
                        {
                            Matrix3d mat = Matrix3d.Identity;
                            bref.TransformBy(mat);
                            bref.ScaleFactors = scale;
                            bref.Rotation     = angle;
                            btr.AppendEntity(bref);
                            tr.AddNewlyCreatedDBObject(bref, true);
                            bref.DowngradeOpen();
                            objectId = bref.ObjectId;
                        }
                    }

                    //Tạo lại bản vẽ???
                    ed.Regen();
                    tr.Commit();
                    result = true;
                }
            }

            return(result);
        }
Пример #25
0
        addBlockRef(string strName, Point3d pnt3dIns, double dblRotation, List <string> attValues)
        {
            Database db = BaseObjs._db;
            Editor   ed = BaseObjs._editor;

            BlockTableRecord btrx = null;
            BlockReference   br   = null;

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);
                    if (!bt.Has(strName))
                    {
                        btrx = addBtr(strName);
                    }
                    else
                    {
                        btrx = (BlockTableRecord)bt[strName].GetObject(OpenMode.ForRead);
                    }

                    //---> debug only
                    foreach (ObjectId idObj in btrx)
                    {
                        Entity ent             = (Entity)idObj.GetObject(OpenMode.ForRead);
                        AttributeDefinition ad = ent as AttributeDefinition;

                        if (ad != null)
                        {
                            ed.WriteMessage(string.Format("\n{0}", ad.Tag));
                        }
                    }//<--- debug only

                    //BlockTableRecord Btr = (BlockTableRecord)DB.CurrentSpaceId.GetObject(OpenMode.ForWrite);

                    btrx.UpgradeOpen();

                    using (btrx)
                    {
                        br = new BlockReference(pnt3dIns, btrx.ObjectId);
                        using (br)
                        {
                            Matrix3d           ucsMatrix = ed.CurrentUserCoordinateSystem;
                            CoordinateSystem3d ucs       = ucsMatrix.CoordinateSystem3d;

                            Matrix3d mat3d = new Matrix3d();
                            mat3d = Matrix3d.Rotation(dblRotation, ucs.Zaxis, pnt3dIns);

                            br.TransformBy(mat3d);
                            br.ScaleFactors = new Scale3d(1, 1, 1);
                            btrx.AppendEntity(br);
                            tr.AddNewlyCreatedDBObject(br, true);

                            BlockTableRecord btratt = (BlockTableRecord)br.BlockTableRecord.GetObject(OpenMode.ForRead);
                            using (btratt)
                            {
                                Autodesk.AutoCAD.DatabaseServices.AttributeCollection ATTcol = br.AttributeCollection;

                                foreach (ObjectId subid in btratt)
                                {
                                    Entity ent             = (Entity)subid.GetObject(OpenMode.ForRead);
                                    AttributeDefinition ad = ent as AttributeDefinition;

                                    if (ad != null)
                                    {
                                        AttributeReference ar = new AttributeReference();
                                        ar.SetPropertiesFrom(ad);
                                        ar.SetAttributeFromBlock(ad, br.BlockTransform);
                                        ar.Visible = ad.Visible;

                                        ar.HorizontalMode = ad.HorizontalMode;
                                        ar.VerticalMode   = ad.VerticalMode;
                                        ar.Rotation       = ad.Rotation;
                                        ar.TextStyleId    = ad.TextStyleId;
                                        ar.Position       = ad.Position + pnt3dIns.GetAsVector();
                                        ar.Tag            = ad.Tag;
                                        ar.FieldLength    = ad.FieldLength;
                                        ar.AdjustAlignment(db);

                                        //if (ar.Tag == "TOPTXT")
                                        //    ar.TextString = strTop;

                                        //if (ar.Tag == "MIDTXT")
                                        //    ar.TextString = strMid;

                                        //if (ar.Tag == "BOTTXT")
                                        //    ar.TextString = strBot;

                                        ar.Position = ad.Position.TransformBy(br.BlockTransform);

                                        ATTcol.AppendAttribute(ar);
                                        tr.AddNewlyCreatedDBObject(ar, true);
                                    }
                                }
                            }
                            br.DowngradeOpen();
                        }

                        btrx.DowngradeOpen();
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " Blocks.cs: line: 194");
            }
            return(br);
        }
Пример #26
0
        /// <summary>
        /// the source drawig should be drawn as number of
        /// separate entites with or without attributes.
        /// Throws NotImplementedException if invoked with .dxf file
        /// </summary>
        /// <param name="sourceDrawing"></param>
        /// <param name="insertionPoint"></param>
        /// <returns>ObjectID of the Block Def that was imported.</returns>
        public void ImportDwgAsBlock(string sourceDrawing, Point3d insertionPoint)
        {
            Matrix3d ucs = _ed.CurrentUserCoordinateSystem;

            string blockname = sourceDrawing.Remove(0, sourceDrawing.LastIndexOf("\\", StringComparison.Ordinal) + 1);

            blockname = blockname.Substring(0, blockname.Length - 4); // remove the extension

            try
            {
                using (_doc.LockDocument())
                {
                    using (var inMemoryDb = new Database(false, true))
                    {
                        #region Load the drawing into temporary inmemory database
                        if (sourceDrawing.LastIndexOf(".dwg", StringComparison.Ordinal) > 0)
                        {
                            inMemoryDb.ReadDwgFile(sourceDrawing, System.IO.FileShare.Read, true, "");
                        }
                        else if (sourceDrawing.LastIndexOf(".dxf", StringComparison.Ordinal) > 0)
                        {
                            _logger.Error(MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + " : Tried to invoke the method with .dxf file.");
                            throw new NotImplementedException("Importing .dxf is not supported in this version.");
                            //inMemoryDb.DxfIn("@" + sourceDrawing, System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\log\\import_block_dxf_log.txt");
                        }
                        else
                        {
                            throw new ArgumentException("This is not a valid drawing.");
                        }
                        #endregion

                        using (var transaction = _db.TransactionManager.StartTransaction())
                        {
                            BlockTable       destDbBlockTable   = (BlockTable)transaction.GetObject(_db.BlockTableId, OpenMode.ForRead);
                            BlockTableRecord destDbCurrentSpace = (BlockTableRecord)_db.CurrentSpaceId.GetObject(OpenMode.ForWrite);

                            // If the destination DWG already contains this block definition
                            // we will create a block reference and not a copy of the same definition
                            ObjectId sourceBlockId;
                            if (destDbBlockTable.Has(blockname))
                            {
                                //BlockTableRecord destDbBlockDefinition = (BlockTableRecord)transaction.GetObject(destDbBlockTable[blockname], OpenMode.ForRead);
                                //sourceBlockId = destDbBlockDefinition.ObjectId;

                                sourceBlockId = transaction.GetObject(destDbBlockTable[blockname], OpenMode.ForRead).ObjectId;

                                // Create a block reference to the existing block definition
                                using (var blockReference = new BlockReference(insertionPoint, sourceBlockId))
                                {
                                    _ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
                                    blockReference.TransformBy(ucs);
                                    _ed.CurrentUserCoordinateSystem = ucs;
                                    var converter   = new MeasurementUnitsConverter();
                                    var scaleFactor = converter.GetScaleRatio(inMemoryDb.Insunits, _db.Insunits);
                                    blockReference.ScaleFactors = new Scale3d(scaleFactor);
                                    destDbCurrentSpace.AppendEntity(blockReference);
                                    transaction.AddNewlyCreatedDBObject(blockReference, true);
                                    _ed.Regen();
                                    transaction.Commit();
                                    // At this point the Bref has become a DBObject and (can be disposed) and will be disposed by the transaction
                                }
                                return;
                            }

                            //else // There is not such block definition, so we are inserting/creating new one

                            sourceBlockId = _db.Insert(blockname, inMemoryDb, true);
                            BlockTableRecord sourceBlock = (BlockTableRecord)sourceBlockId.GetObject(OpenMode.ForRead);
                            sourceBlock.UpgradeOpen();
                            sourceBlock.Name = blockname;
                            destDbCurrentSpace.DowngradeOpen();
                            var sourceBlockMeasurementUnits = inMemoryDb.Insunits;
                            try
                            {
                                CreateBlockReference(sourceBlock.Name, sourceBlockMeasurementUnits,
                                                     insertionPoint,
                                                     destDbCurrentSpace,
                                                     destDbBlockTable);
                            }
                            catch (ArgumentException argumentException)
                            {
                                _logger.Error("Error. Check inner exception.", argumentException);
                            }

                            _ed.Regen();
                            transaction.Commit();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.Error("Error in ImportDrawingAsBlock().", exception);
            }
        }
Пример #27
0
        public BlockReference CopyDynamicBlock(BlockTableRecord spaceRecord, ref BlockReference bref, BlockTableRecord br, Transaction tr)
        {
            BlockReference newbref = new BlockReference(Point3d.Origin, br.ObjectId);

            newbref.TransformBy(bref.BlockTransform);
            newbref.BlockUnit = bref.BlockUnit;
            newbref.Normal    = bref.Normal;
            newbref.Layer     = frameBlockAboveLayer;

            spaceRecord.UpgradeOpen();
            spaceRecord.AppendEntity(newbref);
            //tr.AddNewlyCreatedDBObject(newbref, true);
            spaceRecord.DowngradeOpen();

            //newbref.Visible = false;
            //if (bref.IsDynamicBlock)
            //{
            //    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead);
            //    foreach (ObjectId id in btr)
            //    {
            //        DBObject temp = tr.GetObject(id, OpenMode.ForRead);
            //        if (temp is AttributeDefinition)
            //        {
            //            AttributeDefinition newAttDef = (AttributeDefinition)temp;
            //            AttributeReference attref = new AttributeReference();
            //            attref.SetAttributeFromBlock((AttributeDefinition)temp, bref.BlockTransform);
            //            newbref.AttributeCollection.AppendAttribute(attref);
            //            tr.AddNewlyCreatedDBObject(attref, true);
            //        }
            //    }
            //
            //}

            DynamicBlockReferenceProperty[] array = new DynamicBlockReferenceProperty[100];
            bref.DynamicBlockReferencePropertyCollection.CopyTo(array, 0);

            dynaProps.Add(newbref.ObjectId, array);

            //int i = 0;
            //while(array[i] != null)
            //{
            //    if (!array[i].ReadOnly)
            //    {
            //        newbref.DynamicBlockReferencePropertyCollection[i].Value = array[i].Value;
            //    }
            //    i++;
            //}

            //for (int i = 0; i < bref.DynamicBlockReferencePropertyCollection.Count; i++)
            //{
            //
            //    if (!newbref.DynamicBlockReferencePropertyCollection[i].ReadOnly &&
            //        !bref.DynamicBlockReferencePropertyCollection[i].ReadOnly &&
            //        newbref.DynamicBlockReferencePropertyCollection[i].PropertyName == bref.DynamicBlockReferencePropertyCollection[i].PropertyName
            //        )
            //    {
            //        newbref.DynamicBlockReferencePropertyCollection[i].Value = bref.DynamicBlockReferencePropertyCollection[i];
            //    }
            //}
            return(newbref);
        }
Пример #28
0
        public void Cmd_AutoAtt()
        {
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var objIds = acCurEd.GetFilteredSelection(Enums.DxfNameEnum.Insert, false);

            if (objIds.Length <= 0)
            {
                return;
            }
            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Open the Block table for write
                var acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                if (acBlkTbl == null)
                {
                    acTrans.Abort();
                    return;
                }

                foreach (var obj in objIds)
                {
                    var acBref = acTrans.GetObject(obj, OpenMode.ForRead) as BlockReference;

                    if (acBref == null)
                    {
                        continue;
                    }

                    BlockTableRecord btr = null;

                    if (acBref.IsDynamicBlock)
                    {
                        btr = acTrans.GetObject(acBref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
                    }
                    else
                    {
                        btr = acTrans.GetObject(acBref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
                    }

                    if (btr == null)
                    {
                        continue;
                    }

                    #region TODO replace with xml reading

                    var bName = acBref.Name;

                    //Add attribute definitions
                    //TODO read XML to get attributes to add
                    //For now we'll use a test value

                    var attTag = new AttributeDefinition
                    {
                        Justify             = AttachmentPoint.MiddleCenter,
                        AlignmentPoint      = btr.Origin,
                        Prompt              = "TAG:",
                        Tag                 = "TAG",
                        TextString          = bName,
                        Height              = 1,
                        Invisible           = true,
                        LockPositionInBlock = true
                    };

                    var attCrate = new AttributeDefinition
                    {
                        Justify             = AttachmentPoint.MiddleCenter,
                        AlignmentPoint      = btr.Origin,
                        Prompt              = "CRATE:",
                        Tag                 = "CRATE",
                        TextString          = string.Empty,
                        Height              = 1,
                        Invisible           = true,
                        LockPositionInBlock = true
                    };

                    btr.UpgradeOpen();
                    btr.AppendEntity(attTag);
                    btr.AppendEntity(attCrate);

                    #endregion

                    acBref.UpgradeOpen();
                    acBref.AppendAttributes(btr, acTrans);
                    acBref.DowngradeOpen();
                    btr.DowngradeOpen();
                }

                acTrans.Commit();
            }

            acCurDb.Audit(true, false);
        }
Пример #29
0
        public void drawTable(Database db, Transaction trans, Point3d insertPoint)
        {
            BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);

            bt.UpgradeOpen();
            BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

            Polyline pHorizonline1 = new Polyline();

            pHorizonline1.CreatePolyline(new Point2d(insertPoint.X, insertPoint.Y), new Point2d(insertPoint.X + 30, insertPoint.Y));
            btr.AppendEntity(pHorizonline1);
            trans.AddNewlyCreatedDBObject(pHorizonline1, true);

            Polyline pHorizonline2 = new Polyline();

            pHorizonline2.CreatePolyline(new Point2d(insertPoint.X, insertPoint.Y - 8.5), new Point2d(insertPoint.X + 30, insertPoint.Y - 8.5));
            btr.AppendEntity(pHorizonline2);
            trans.AddNewlyCreatedDBObject(pHorizonline2, true);

            Polyline pHorizonline3 = new Polyline();

            pHorizonline3.CreatePolyline(new Point2d(insertPoint.X, insertPoint.Y - 19), new Point2d(insertPoint.X + 30, insertPoint.Y - 19));
            btr.AppendEntity(pHorizonline3);
            trans.AddNewlyCreatedDBObject(pHorizonline3, true);

            Polyline pHorizonline4 = new Polyline();

            pHorizonline4.CreatePolyline(new Point2d(insertPoint.X, insertPoint.Y - 32.5), new Point2d(insertPoint.X + 247, insertPoint.Y - 32.5));
            btr.AppendEntity(pHorizonline4);
            trans.AddNewlyCreatedDBObject(pHorizonline4, true);

            Polyline pHorizonline5 = new Polyline();

            pHorizonline5.CreatePolyline(new Point2d(insertPoint.X, insertPoint.Y - 41), new Point2d(insertPoint.X + 247, insertPoint.Y - 41));
            btr.AppendEntity(pHorizonline5);
            trans.AddNewlyCreatedDBObject(pHorizonline5, true);

            Polyline pVerticalLine1 = new Polyline();

            pVerticalLine1.CreatePolyline(new Point2d(insertPoint.X, insertPoint.Y), new Point2d(insertPoint.X, insertPoint.Y - 41));
            btr.AppendEntity(pVerticalLine1);
            trans.AddNewlyCreatedDBObject(pVerticalLine1, true);

            Polyline pVerticalLine2 = new Polyline();

            pVerticalLine2.CreatePolyline(new Point2d(insertPoint.X + 30, insertPoint.Y), new Point2d(insertPoint.X + 30, insertPoint.Y - 41));
            btr.AppendEntity(pVerticalLine2);
            trans.AddNewlyCreatedDBObject(pVerticalLine2, true);

            DBText TStationName = new DBText();

            TStationName.TextString     = "站名";
            TStationName.Height         = 3;
            TStationName.VerticalMode   = TextVerticalMode.TextVerticalMid;
            TStationName.HorizontalMode = TextHorizontalMode.TextCenter;
            TStationName.AlignmentPoint = new Point3d(insertPoint.X + 30 / 2, insertPoint.Y - 8.5 / 2, 0);

            DBText TStationmark = new DBText();

            TStationmark.TextString     = "图示";
            TStationmark.Height         = 3;
            TStationmark.VerticalMode   = TextVerticalMode.TextVerticalMid;
            TStationmark.HorizontalMode = TextHorizontalMode.TextCenter;
            TStationmark.AlignmentPoint = new Point3d(insertPoint.X + 30 / 2, insertPoint.Y - 8.5 - 8.5 / 2, 0);

            DBText TStationLocation = new DBText();

            TStationLocation.TextString     = "站中心里程";
            TStationLocation.Height         = 3;
            TStationLocation.VerticalMode   = TextVerticalMode.TextVerticalMid;
            TStationLocation.HorizontalMode = TextHorizontalMode.TextCenter;
            TStationLocation.AlignmentPoint = new Point3d(insertPoint.X + 30 / 2, insertPoint.Y - (19 + (32.5 - 19) / 2), 0);

            DBText TStationDistance = new DBText();

            TStationDistance.TextString     = "站间距离";
            TStationDistance.Height         = 3;
            TStationDistance.VerticalMode   = TextVerticalMode.TextVerticalMid;
            TStationDistance.HorizontalMode = TextHorizontalMode.TextCenter;
            TStationDistance.AlignmentPoint = new Point3d(insertPoint.X + 30 / 2, insertPoint.Y - (32.5 + (41 - 32.5) / 2), 0);

            //db.AddToModelSpace(pHorizonline1, pHorizonline2, pHorizonline3, pHorizonline4, pHorizonline5, pVerticalLine1, pVerticalLine2);
            db.AddToModelSpace(TStationName, TStationmark, TStationLocation, TStationDistance);
            bt.DowngradeOpen();
            btr.DowngradeOpen();
        }
Пример #30
0
        private void click_btn_AddPart(object sender, EventArgs e)
        {
            DocumentLock loc = doc.LockDocument();

            using (loc)
            {
                drawingToAdd.Replace(@"/", @"\");
                string drawingFileName = drawingToAdd.Substring(drawingToAdd.IndexOf(@"/", (drawingToAdd.IndexOf(@"/") + 1)) + 1, drawingToAdd.Length - drawingToAdd.IndexOf(@"/", (drawingToAdd.IndexOf(@"/") + 1)) - 1);

                Database tmpDb = new Database(false, true);
                tmpDb.ReadDwgFile(@"\\thehaskellco.net\Remote\AtlantaData\_Disciplines\Controls\4 Controls Programming\DVBs and DLLs\Footprints\Panel\" + drawingToAdd + ".dwg", System.IO.FileShare.Read, true, "");
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                    if (!bt.Has(drawingFileName))
                    {
                        db.Insert(drawingFileName, tmpDb, true);
                    }
                    tr.Commit();
                }

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                    btr = (BlockTableRecord)bt[drawingFileName].GetObject(OpenMode.ForRead);
                    bool tagFound = false;

                    if (btr != null)
                    {
                        foreach (ObjectId objId in btr)
                        {
                            AttributeDefinition attDef = tr.GetObject(objId, OpenMode.ForRead) as AttributeDefinition;
                            if (attDef != null)
                            {
                                if (attDef.Tag.ToUpper() == "TABLE_PART_NUM")
                                {
                                    tagFound = true;
                                }
                                else if (attDef.Tag.ToUpper() == "TABLE_DESCRIPTION")
                                {
                                    tagFound = true;
                                }
                            }
                        }
                        try
                        {
                            if (!tagFound)
                            {
                                AttributeDefinition acAttDef = new AttributeDefinition();

                                acAttDef.Position  = new Point3d(0, 0, 0);
                                acAttDef.Prompt    = "Part Number?";
                                acAttDef.Tag       = "TABLE_PART_NUM";
                                acAttDef.Invisible = true;
                                acAttDef.Height    = 1;
                                acAttDef.Justify   = AttachmentPoint.MiddleCenter;

                                AttributeDefinition acAttDef2 = new AttributeDefinition();

                                acAttDef2.Position  = new Point3d(0, 0, 0);
                                acAttDef2.Prompt    = "Description?";
                                acAttDef2.Tag       = "TABLE_DESCRIPTION";
                                acAttDef2.Invisible = true;
                                acAttDef2.Height    = 1;
                                acAttDef2.Justify   = AttachmentPoint.MiddleCenter;

                                AttributeDefinition acAttDef3 = new AttributeDefinition();

                                acAttDef3.Position   = new Point3d(0, -10, 0);
                                acAttDef3.Prompt     = "DO NOT CHANGE";
                                acAttDef3.Tag        = "AUTO_UPDATE";
                                acAttDef3.TextString = "1";
                                acAttDef3.Invisible  = true;
                                acAttDef3.Height     = 1;
                                acAttDef3.Justify    = AttachmentPoint.MiddleCenter;

                                btr.UpgradeOpen();
                                btr.AppendEntity(acAttDef);
                                btr.AppendEntity(acAttDef2);
                                btr.AppendEntity(acAttDef3);
                                tr.AddNewlyCreatedDBObject(acAttDef, true);
                                tr.AddNewlyCreatedDBObject(acAttDef2, true);
                                tr.AddNewlyCreatedDBObject(acAttDef3, true);
                                btr.DowngradeOpen();
                                tr.Commit();
                            }
                        }
                        catch
                        {
                            ed.WriteMessage("Could not add attributes to block.");
                        }
                    }
                }

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    if (btr != null)
                    {
                        MyBlockJig   blockJig = new MyBlockJig();
                        Point3d      point;
                        PromptResult res = blockJig.DragMe(btr.ObjectId, out point);

                        if (res.Status == PromptStatus.OK)
                        {
                            BlockTableRecord curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            BlockReference   insert   = new BlockReference(point, btr.ObjectId);

                            curSpace.AppendEntity(insert);
                            tr.AddNewlyCreatedDBObject(insert, true);

                            foreach (ObjectId id in btr)
                            {
                                DBObject            obj    = id.GetObject(OpenMode.ForWrite);
                                AttributeDefinition attDef = obj as AttributeDefinition;
                                if ((attDef != null) && (!attDef.Constant))
                                {
                                    using (AttributeReference attRef = new AttributeReference())
                                    {
                                        attRef.SetAttributeFromBlock(attDef, insert.BlockTransform);
                                        insert.AttributeCollection.AppendAttribute(attRef);
                                        tr.AddNewlyCreatedDBObject(attRef, true);
                                    }
                                }
                            }
                        }
                    }
                    tr.Commit();
                    doc.SendStringToExecute("regenall ", true, false, false);
                }

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    ObjectId msId = bt[BlockTableRecord.ModelSpace];

                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(msId, OpenMode.ForRead);
                    foreach (ObjectId entId in btr)
                    {
                        Entity ent = (Entity)tr.GetObject(entId, OpenMode.ForWrite);
                        if (ent != null)
                        {
                            BlockReference br = ent as BlockReference;
                            if (br != null)
                            {
                                BlockTableRecord bd = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForRead);
                                if (bd.Name.ToUpper() == drawingFileName.ToUpper())
                                {
                                    foreach (ObjectId arId in br.AttributeCollection)
                                    {
                                        DBObject           obj = tr.GetObject(arId, OpenMode.ForWrite);
                                        AttributeReference ar  = obj as AttributeReference;
                                        if (ar != null)
                                        {
                                            if (ar.Tag == "AUTO_UPDATE")
                                            {
                                                if (ar.TextString == "1")
                                                {
                                                    foreach (ObjectId attRefId in br.AttributeCollection)
                                                    {
                                                        DBObject           objRef = tr.GetObject(attRefId, OpenMode.ForWrite);
                                                        AttributeReference aRef   = objRef as AttributeReference;
                                                        if (aRef.Tag == "TABLE_PART_NUM")
                                                        {
                                                            aRef.UpgradeOpen();
                                                            aRef.TextString = partNumberToAdd;
                                                            aRef.DowngradeOpen();
                                                        }
                                                        else if (aRef.Tag == "TABLE_DESCRIPTION")
                                                        {
                                                            aRef.UpgradeOpen();
                                                            aRef.TextString = descriptionToAdd;
                                                            aRef.DowngradeOpen();
                                                        }
                                                    }
                                                }

                                                ar.TextString = "0";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    tr.Commit();
                }
            }
        }