Пример #1
0
        public static void EditLine()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            // 事务处理器
            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            // 开始第一个事务处理 tr1
            using (Transaction tr1 = tm.StartTransaction())
            {
                Point3d  ptStart = Point3d.Origin;
                Point3d  ptEnd   = new Point3d(100, 0, 0);
                Line     line1   = new Line(ptStart, ptEnd);
                ObjectId id1     = db.AddToModelSpace(line1); // 添加直线到数据库中
                // 开始第二个事务处理 tr2
                using (Transaction tr2 = tm.StartTransaction())
                {
                    line1.UpgradeOpen();                     // 切换line1的状态为可写
                    line1.ColorIndex = 1;                    // 设置直线的颜色为红色
                    ObjectId id2 = id1.Copy(ptStart, ptEnd); // 复制直线
                    id2.Rotate(ptEnd, Math.PI / 2);
                    // 开始第三个事务处理 tr3
                    using (Transaction tr3 = tm.StartTransaction())
                    {
                        Line line2 = (Line)tr3.GetObject(id2, OpenMode.ForWrite);
                        line2.ColorIndex = 3; // 设置直线的颜色为绿色
                        tr3.Abort();          // 撤销第三个事务处理tr3,line2的颜色不变
                    }
                    // 提交第二个事务处理tr2,line1颜色变为红色,复制line1并旋转90度
                    tr2.Commit();
                }
                tr1.Commit(); // 提交第一个事务处理tr1,添加line1到数据库中
            }
        }
Пример #2
0
        private MassElement[] GetSelectedMassElement()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptSelectionOptions Opts = new PromptSelectionOptions();
            PromptSelectionResult  psr  = ed.GetSelection(Opts);

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

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

                trans.Commit();
                trans.Dispose();
                return(result);
            }
            return(null);
        }
Пример #3
0
        /// <summary>
        /// Inserts all attributreferences
        /// </summary>
        /// <param name="blkRef">Blockreference to append the attributes</param>
        /// <param name="strAttributeTag">The tag to insert the <paramref name="strAttributeText"/></param>
        /// <param name="strAttributeText">The textstring for <paramref name="strAttributeTag"/></param>
        public static void InsertBlockAttibuteRef(this BlockReference blkRef, string strAttributeTag, string strAttributeText)
        {
            Database dbCurrent = HostApplicationServices.WorkingDatabase;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = dbCurrent.TransactionManager;
            using (Transaction tr = tm.StartTransaction())
            {
                BlockTableRecord btAttRec = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead);
                foreach (ObjectId idAtt in btAttRec)
                {
                    Entity ent = (Entity)tr.GetObject(idAtt, OpenMode.ForRead);
                    if (ent is AttributeDefinition)
                    {
                        AttributeDefinition attDef = (AttributeDefinition)ent;
                        AttributeReference  attRef = new AttributeReference();
                        attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform);
                        if (attRef.Tag == strAttributeTag)
                        {
                            attRef.TextString = strAttributeText;
                        }
                        ObjectId idTemp = blkRef.AttributeCollection.AppendAttribute(attRef);
                        tr.AddNewlyCreatedDBObject(attRef, true);
                    }
                }
                tr.Commit();
            }
        }
Пример #4
0
        TestImageAngle()
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            PromptEntityOptions prOpts = new PromptEntityOptions("\nSelect an Image");

            prOpts.SetRejectMessage("\nSelected entity must by of type RasterImage");
            prOpts.AddAllowedClass(typeof(RasterImage), false);

            PromptEntityResult prRes = ed.GetEntity(prOpts);

            if (prRes.Status == PromptStatus.OK)
            {
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = prRes.ObjectId.Database.TransactionManager;
                using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) {
                    RasterImage imgObj = (RasterImage)tr.GetObject(prRes.ObjectId, OpenMode.ForRead);

                    CoordinateSystem3d entEcs = imgObj.Orientation;

                    Vector3d arbXAxis  = Utils.Db.GetEcsXAxis(entEcs.Zaxis);  // get AutoCAD's arbitrary X-Axis
                    double   rotAngle1 = arbXAxis.GetAngleTo(entEcs.Xaxis, entEcs.Zaxis);
                    ed.WriteMessage(string.Format("\nECS rotation angle: {0}", Autodesk.AutoCAD.Runtime.Converter.AngleToString(rotAngle1, AngularUnitFormat.Current, -1)));

                    Plane  ucsPlane  = Utils.Db.GetUcsPlane(prRes.ObjectId.Database);
                    double rotAngle2 = entEcs.Xaxis.AngleOnPlane(ucsPlane);
                    ed.WriteMessage(string.Format("\nRotation angle relative to UCS: {0}", Autodesk.AutoCAD.Runtime.Converter.AngleToString(rotAngle2, AngularUnitFormat.Current, -1)));

                    tr.Commit();
                }
            }
        }
        bool SaveStyleNameToUiData()
        {
            if (textStyleName.Text.Length == 0)
            {
                MessageBox.Show("Please specify a name for the schedule table style.");
                return(false);
            }

            Database db = ScheduleSample.GetDatabase();
            DictionaryScheduleTableStyle dict = new DictionaryScheduleTableStyle(db);
            DBTransactionManager         tm   = db.TransactionManager;

            using (Transaction trans = tm.StartTransaction())
            {
                if (dict.Has(textStyleName.Text, trans))
                {
                    MessageBox.Show("The style name you specified already exists. Please specify a new one.");
                    return(false);
                }
            }

            runtimeData.scheduleTableStyleName = textStyleName.Text;

            return(true);
        }
Пример #6
0
        public static ArrayList GetLayoutIdList(Database db)
        {
            ArrayList layoutList = new ArrayList();

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

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

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

            return(layoutList);
        }
Пример #7
0
        public void DistanceTest()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptDistanceOptions opt1 = new PromptDistanceOptions("Enter the radius of the circle");

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

            PromptDoubleResult res = ed.GetDistance(opt1);

            if (res.Status == PromptStatus.OK)
            {
                Point3d  center = new Point3d(9.0, 3.0, 0.0);
                Vector3d normal = new Vector3d(0.0, 0.0, 1.0);
                Database db     = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
                using (Transaction myT = tm.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                    using (Circle pcirc = new Circle(center, normal, res.Value))
                    {
                        btr.AppendEntity(pcirc);
                        tm.AddNewlyCreatedDBObject(pcirc, true);
                    }
                    myT.Commit();
                }
            }
        }
Пример #8
0
        static public void DoIt()
        {
            Editor             ed   = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptPointOptions opts = new PromptPointOptions("\nEnter Ellipse Center Point:");
            PromptPointResult  res  = ed.GetPoint(opts);

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


            Database db = Application.DocumentManager.MdiActiveDocument.Database;

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

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

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

            //Append entity.
            using (Transaction myT = tm.StartTransaction())
            {
                BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                btr.AppendEntity(jig.GetEntity());
                tm.AddNewlyCreatedDBObject(jig.GetEntity(), true);
                myT.Commit();
            }
        }
Пример #9
0
        public static List <string> ImportBlocks(Database db, Database sourceDb, List <string> blockNames)
        {
            List <string> output = new List <string>();

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

                        btr.Dispose();
                    }
                }

                //copy blocks from source to destination database
                IdMapping mapping = new IdMapping();
                sourceDb.WblockCloneObjects(blockIds, db.BlockTableId, mapping, DuplicateRecordCloning.Ignore, false);
            }
            catch { }
            return(output);
        }
Пример #10
0
        public void UsingEntityOptionsAndResults()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //Using the stored PromptEntityOption.
            PromptEntityResult res1 = ed.GetEntity(useThisEntityOption);
            //Using the stored PromptEntityResult.
            PromptEntityResult res2 = useThisEntityResult;

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

                using (Transaction myT = tm.StartTransaction())
                {
                    Entity Oldentity = (Entity)tm.GetObject(entid, OpenMode.ForWrite, true);
                    Oldentity.ColorIndex = 2;
                    ed.WriteMessage("\nYou Now selected: " + Oldentity.GetType().FullName);
                    myT.Commit();
                }
            }
        }
Пример #11
0
        public void modified(object sender, EventArgs e)
        {
            Extents3d extents3d   = (Extents3d)_Entity.Bounds;
            Point3d   newPosition = new Point3d(
                (extents3d.MaxPoint.X + extents3d.MinPoint.X) / 2,
                (extents3d.MaxPoint.Y + extents3d.MinPoint.Y) / 2,
                (extents3d.MaxPoint.Z + extents3d.MinPoint.Z) / 2);


            Database db = Application.DocumentManager.MdiActiveDocument.Database;

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


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

            foreach (var v in _BindedRoadways)
            {
                RoadwayWrapper bdrw = (RoadwayWrapper)tm.GetObject(v.roadway.ObjectId, OpenMode.ForWrite, false);
                if (v.whichSide == -1)
                {
                    bdrw.EndPoint = newPosition;
                }
                else if (v.whichSide == 1)
                {
                    bdrw.StartPoint = newPosition;
                }
            }
        }
Пример #12
0
        public void UsingAngleOptionsAndResults()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //Using the stored PromptAngleOption.
            PromptDoubleResult res1 = ed.GetAngle(useThisAngleOption);
            //Using the stored PromptAngleResult.
            PromptDoubleResult res2 = useThisAngleResult;

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

                using (Transaction myT = tm.StartTransaction())
                {
                    BlockTable       bt     = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr    = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                    Point3d          center = new Point3d(30.0, 19.0, 0.0);
                    using (Arc arc1 = new Arc(center, res1.Value, res2.Value, 5.0))
                    {
                        arc1.ColorIndex = 3;
                        btr.AppendEntity(arc1);
                        myT.AddNewlyCreatedDBObject(arc1, true);
                    }
                    myT.Commit();
                }
            }
            else
            {
                ed.WriteMessage("Arc cannot be constructed");
            }
        }
Пример #13
0
Файл: Db.cs Проект: 15831944/EM
        idObjToTypeAndHandleStr(ObjectId objId)
        {
            string str = "";

            if (objId.IsNull)
            {
                str = "(null)";
            }
            else
            {
                // open up even if erased
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = objId.Database.TransactionManager;
                try
                {
                    using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction())
                    {
                        DBObject tmpObj = tr.GetObject(objId, OpenMode.ForRead, true);
                        str = idObjToTypeAndHandleStr(tmpObj);
                        tr.Commit();
                    }
                }
                catch (System.Exception ex)
                {
                    BaseObjs.writeDebug(ex.Message + " Db.cs: line: 388");
                }
            }

            return(str);
        }
Пример #14
0
        Extents()
        {
            m_db = Utils.Db.GetCurDwg();

            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

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

            while (true)
            {
                PromptEntityResult prEntRes = ed.GetEntity("\nSelect entity to show extents");
                if (prEntRes.Status != PromptStatus.OK)
                {
                    break;
                }

                using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) {
                    AcDb.Entity ent = (AcDb.Entity)tr.GetObject(prEntRes.ObjectId, OpenMode.ForRead);

                    Extents3d ext      = ent.GeometricExtents;
                    Point3d   centerPt = Utils.Ge.Midpoint(ext.MinPoint, ext.MaxPoint);

                    Utils.AcadUi.PrintToCmdLine(string.Format("\nEXTMIN:    {0}", Utils.AcadUi.PtToStr(ext.MinPoint)));
                    Utils.AcadUi.PrintToCmdLine(string.Format("\nEXTMAX:    {0}", Utils.AcadUi.PtToStr(ext.MaxPoint)));
                    Utils.AcadUi.PrintToCmdLine(string.Format("\nCENTER PT: {0}", Utils.AcadUi.PtToStr(centerPt)));

                    tr.Commit();

                    MakeExtentsBlock(ext);
                }
            }
        }
Пример #15
0
        static public void TransactionControl(Action handler)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

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

            doc.LockDocument();
            if (tm.TopTransaction != null)
            {
                handler();
            }
            else
            {
                using (Transaction myT = tm.StartTransaction())
                {
                    handler();
                    try
                    {
                        myT.Commit();
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception exception)
                    {
                        ed.WriteMessage(exception.ToString());
                    }
                    finally
                    {
                        myT.Dispose();
                    }
                }
            }
        }
Пример #16
0
        public static bool IsTemplateEntity(ObjectId entId)
        {
            Database db = HostApplicationServices.WorkingDatabase;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager transactionManager = db.TransactionManager;
            using (Autodesk.AutoCAD.DatabaseServices.Transaction trans = transactionManager.StartTransaction())
            {
                BlockReference block = trans.GetObject(entId, OpenMode.ForRead, false, true) as BlockReference;
                if (null != block)
                {
                    BlockTableRecord blockTab = trans.GetObject(block.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
                    if (null != blockTab)
                    {
                        string blockName = blockTab.Name;

                        string[] s = blockName.Split(new char[] { '_' });
                        if (s.Length == 8 && String.Compare("template", s[s.Length - 1], true) == 0)
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Пример #17
0
        // Property Set Definitions
        public static ObjectId GetPropertySetDefinitionIdByName(string psdName)
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            ObjectId psdId = ObjectId.Null;
            Database db    = Application.DocumentManager.MdiActiveDocument.Database;

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

            using (Transaction tr = tm.StartTransaction())
            {
                try
                {
                    DictionaryPropertySetDefinitions psdDict = new DictionaryPropertySetDefinitions(db);
                    if (psdDict.Has(psdName, tr))
                    {
                        psdId = psdDict.GetAt(psdName);
                    }
                }
                catch
                {
                    ed.WriteMessage("\n GetPropertySetDefinitionIdByName failed");
                }
                tr.Commit();
                return(psdId);
            }
        }
Пример #18
0
        GetSymbolTableRecId(System.Type classType, string symName, Database db)
        {
            ObjectId tblId = GetSymbolTableId(classType, db);
            ObjectId recId = new ObjectId();

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            try
            {
                using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction())
                {
                    SymbolTable tbl = (SymbolTable)tr.GetObject(tblId, OpenMode.ForRead);
                    if (tbl.Has(symName))   // TBD: should indexer return ObjectId.null instead of throwing exception
                    {
                        recId = tbl[symName];
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " SymTbl.cs: line: 276");
            }

            return(recId);
        }
Пример #19
0
        void getJointsWithSelection()
        {
            Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            Database           db    = Application.DocumentManager.MdiActiveDocument.Database;
            TransactionManager tm    = db.TransactionManager;
            Transaction        trans = tm.StartTransaction();

            try
            {
                PromptEntityOptions entopts = new PromptEntityOptions("Select a wall ");
                entopts.SetRejectMessage("Must select a wall, please!");
                entopts.AddAllowedClass(typeof(Wall), true);
                PromptEntityResult ent = null;
                try
                {
                    ent = ed.GetEntity(entopts);
                }
                catch
                {
                    ed.WriteMessage("You did not select a valid entity");
                    return;
                }

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

                    Wall wall = trans.GetObject(entId, OpenMode.ForRead, false) as Wall;
                    if (wall != null)
                    {
                        Manager  mgr      = new Manager(db);
                        Graph    theGraph = mgr.FindGraph(wall);
                        Matrix3d mat      = theGraph.WcsToEcsMatrix.Inverse();
                        for (int i = 0; i < theGraph.WallJointCount; i++)
                        {
                            Joint   joint         = theGraph.GetWallJoint(i);
                            Point3d jointloc      = new Point3d(joint.Location.X, joint.Location.Y, 0);
                            Point3d jointlocTrans = jointloc.TransformBy(mat);
                            DrawBlip(jointloc.TransformBy(mat), 3, 1, false);
                            ed.WriteMessage("\n Joint at (ECS): " + joint.Location.ToString() + " (WCS): " + jointlocTrans.ToString());
                        }
                    }
                    else
                    {
                        ed.WriteMessage("\nSomething bad has happened...");
                    }
                }

                trans.Commit();
            }
            catch (System.Exception e)
            {
                trans.Abort();
                ed.WriteMessage(e.Message);
            }
            finally
            {
                trans.Dispose();
            }
        }
Пример #20
0
        static public void Foo()
        {
            Document document = Application.DocumentManager.MdiActiveDocument;
            Database database = document.Database;

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

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

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

                        bool result = isOverride(mLeader.UnmanagedObject, 16);
                        document.Editor.WriteMessage("result: " + result + "\n");
                    }
                }
            }
        }
Пример #21
0
        public void UsingPointOptionsAndResults()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

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

            if (res1.Status != PromptStatus.Cancel && res2.Status != PromptStatus.Cancel)
            {
                Point3d  start = res1.Value;
                Point3d  end   = res2.Value;
                Database db    = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
                using (Transaction myT = tm.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                    using (Line myline = new Line(start, end))
                    {
                        myline.ColorIndex = 3;
                        btr.AppendEntity(myline);
                        myT.AddNewlyCreatedDBObject(myline, true);
                    }
                    myT.Commit();
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Creates the whole property sets, schedule table style and schedule table in database.
        /// </summary>
        /// <param name="uiData">The data saved from the wizard.</param>
        /// <returns>Returns the object id of the property set definition, schedule table style and schedule table.</returns>
        public static ScheduleTableCreateResult CreateScheduleTable(UiData uiData)
        {
            ScheduleTableCreateResult result = new ScheduleTableCreateResult();
            Database             db          = ScheduleSample.GetDatabase();
            DBTransactionManager tm          = db.TransactionManager;

            using (Transaction trans = tm.StartTransaction())
            {
                try
                {
                    PropertySetDefinition psd = CreatePropertySetDefinition(uiData, trans);
                    result.PropertySetDefinitionId = psd.Id;
                    if (result.PropertySetDefinitionId == ObjectId.Null)
                    {
                        throw (new System.Exception("Failed to create property set definition."));
                    }

                    ScheduleTableStyle style = CreateStyle(uiData, psd, trans);
                    result.StyleId = style.Id;
                    if (result.StyleId == ObjectId.Null)
                    {
                        throw (new System.Exception("Failed to create property style."));
                    }

                    AddPropertySetToObjects(uiData, result.PropertySetDefinitionId, trans);

                    ScheduleTable table = CreateScheduleTable(uiData, result.PropertySetDefinitionId, result.StyleId, trans);
                    result.ScheduleTableId = table.Id;
                    if (result.ScheduleTableId == ObjectId.Null)
                    {
                        throw (new System.Exception("Failed to create Schedule Table."));
                    }

                    Editor            editor       = ScheduleSample.GetEditor();
                    PromptPointResult editorResult = editor.GetPoint("Please pick a point to insert the schedule table:");
                    if (editorResult.Status == PromptStatus.OK)
                    {
                        table.Location = editorResult.Value;
                        table.Scale    = 10;
                        trans.Commit();
                    }
                    else
                    {
                        trans.Abort();
                    }
                }
                catch (System.Exception)
                {
                    trans.Abort();
                    return(null);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return(result);
        }
Пример #23
0
 AddToCurrentSpaceAndClose(DBObjectCollection ents, Database db)
 {
     Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
     using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) {
         AddToCurrentSpace(ents, db, tr);
         tr.Commit();
     }
 }
Пример #24
0
        void getSectionsWithSelection()
        {
            Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            Database           db    = Application.DocumentManager.MdiActiveDocument.Database;
            TransactionManager tm    = db.TransactionManager;
            Transaction        trans = tm.StartTransaction();

            try
            {
                PromptEntityOptions entopts = new PromptEntityOptions("Select a wall ");
                entopts.SetRejectMessage("Must select a wall, please!");
                entopts.AddAllowedClass(typeof(Wall), true);
                PromptEntityResult ent = null;
                try
                {
                    ent = ed.GetEntity(entopts);
                }
                catch
                {
                    ed.WriteMessage("You did not select a valid entity");
                    return;
                }

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

                    Wall     wall     = trans.GetObject(entId, OpenMode.ForRead, false) as Wall;
                    Manager  mgr      = new Manager(db);
                    Graph    theGraph = mgr.FindGraph(wall);
                    Matrix3d mat      = theGraph.WcsToEcsMatrix.Inverse();
                    for (int i = 0; i < theGraph.WallJointCount; i++)
                    {
                        Joint joint = theGraph.GetWallJoint(i);
                        ConnectionCollection connections = joint.Connections;
                        foreach (Connection connection in connections)
                        {
                            Section section = connection.Section;
                            int     count   = section.ComponentSetCount;
                            ed.WriteMessage("\n  Section in wall system for wall id: " + section.WallId + "\n    component set count = " + count);
                            ed.DrawVector(new Point3d(section.StartPoint.X, section.StartPoint.Y, 0).TransformBy(mat),
                                          new Point3d(section.EndPoint.X, section.EndPoint.Y, 0).TransformBy(mat), 4, true);
                        }
                    }
                }

                trans.Commit();
            }
            catch (System.Exception e)
            {
                trans.Abort();
                ed.WriteMessage(e.Message);
            }
            finally
            {
                trans.Dispose();
            }
        }
Пример #25
0
        /// <summary>
        /// 保存事件使数据库与图纸中的已保存数据相一致
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void db_SaveComplete(object sender, DatabaseIOEventArgs e)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

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

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

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

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

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

            if (SS == null)
            {
                return;
            }

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

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

                foreach (var id in idArray)
                {
                    Entity entity = (Entity)tm.GetObject(id, OpenMode.ForRead, true);
                    if (entity is BaseTunnel)
                    {
                        DBTunnel dbTunnel = new DBTunnel();
                        dbTunnel.SetProperty(entity);
                        dbControl.Insert(dbTunnel, db);
                    }
                    else if (entity is Node)
                    {
                        DBNode dbNode = new DBNode();
                        dbNode.SetProperty(entity);
                        dbControl.Insert(dbNode, db);
                    }
                }
                myT.Commit();
            }
        }
Пример #26
0
        GetLineOrTwoPoints(out Point3d pt1, out Point3d pt2)
        {
            m_db = Utils.Db.GetCurDwg();

            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            pt1 = pt2 = Utils.Ge.kOrigin;    // initialize to make compiler happy

            PromptPointOptions prOpts = new PromptPointOptions("\nFirst extension line origin or RETURN to select");

            prOpts.AllowNone = true;

            PromptPointResult prPt1Res = ed.GetPoint(prOpts);

            // user wants to select a line to specify both points
            if (prPt1Res.Status == PromptStatus.None)
            {
                PromptEntityOptions prEntOpts = new PromptEntityOptions("\nSelect a LINE");
                prEntOpts.SetRejectMessage("\nSelected entity must be of type Line");
                prEntOpts.AddAllowedClass(typeof(Line), false);

                PromptEntityResult prEntRes = ed.GetEntity(prEntOpts);
                if (prEntRes.Status != PromptStatus.OK)
                {
                    return(prEntRes.Status);
                }

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

                using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) {
                    Line line = (Line)tr.GetObject(prEntRes.ObjectId, OpenMode.ForRead);

                    pt1 = Utils.Db.WcsToUcs(line.StartPoint);
                    pt2 = Utils.Db.WcsToUcs(line.EndPoint);
                    tr.Commit();

                    return(PromptStatus.OK);
                }
            }
            else if (prPt1Res.Status == PromptStatus.OK)
            {
                PromptPointOptions prPt2Opts = new PromptPointOptions("\nSecond extension line origin");
                prPt2Opts.UseBasePoint = true;
                prPt2Opts.BasePoint    = prPt1Res.Value;
                PromptPointResult prPt2Res = ed.GetPoint(prPt2Opts);
                if (prPt2Res.Status != PromptStatus.OK)
                {
                    return(PromptStatus.Cancel);
                }

                pt1 = prPt1Res.Value;
                pt2 = prPt2Res.Value;
                return(prPt1Res.Status);
            }

            return(prPt1Res.Status);
        }
Пример #27
0
        HatchAssoc()
        {
            m_db = Utils.Db.GetCurDwg();

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = m_db.TransactionManager;
            using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) {
                // make boundary triangle
                Polyline pline1 = new Polyline();
                pline1.ColorIndex = 211;
                pline1.AddVertexAt(0, new Point2d(0.0, 0.0), 0.0, 0.0, 0.0);
                pline1.AddVertexAt(0, new Point2d(30.0, 0.0), 0.0, 0.0, 0.0);
                pline1.AddVertexAt(0, new Point2d(15.0, 30.0), 0.0, 0.0, 0.0);
                pline1.Closed = true;
                Utils.Db.TransformToWcs(pline1, m_db);
                Utils.SymTbl.AddToCurrentSpace(pline1, m_db, tr);

                // offset the triangle and add those entities to the db
                DBObjectCollection offsetCurves = pline1.GetOffsetCurves(5.0);
                Utils.SymTbl.AddToCurrentSpace(offsetCurves, m_db, tr);

                ObjectIdCollection boundaryIds1 = new ObjectIdCollection();
                boundaryIds1.Add(pline1.ObjectId);

                ObjectIdCollection boundaryIds2 = new ObjectIdCollection();
                foreach (Entity tmpEnt in offsetCurves)
                {
                    boundaryIds2.Add(tmpEnt.ObjectId);
                }

                Hatch hatch = new Hatch();
                hatch.ColorIndex = 141;

                Utils.Db.TransformToWcs(hatch, m_db);   // NOTE: need to transform to correct plane *BEFORE* setting pattern and boundary info

                hatch.PatternAngle = Utils.Ge.kRad0;
                hatch.PatternScale = 4.0;
                hatch.SetHatchPattern(HatchPatternType.PreDefined, "STARS");

                hatch.HatchStyle = HatchStyle.Normal;
                Utils.SymTbl.AddToCurrentSpace(hatch, m_db, tr);

                // To make an associative hatch we have to first add it to the database (above).
                // When we call AppendLoop(), it will add the Persistent Reactor that keeps the
                // boundary associative.
                hatch.Associative = true;
                hatch.AppendLoop(HatchLoopTypes.Default, boundaryIds1);
                if (boundaryIds2.Count > 0)
                {
                    hatch.AppendLoop(HatchLoopTypes.Default, boundaryIds2);
                }

                hatch.EvaluateHatch(false);

                tr.Commit();
            }
        }
Пример #28
0
        void RecursiveReferencesToOfSeletedObject()
        {
            //
            // Transaction processing
            //
            Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            Database           db    = Application.DocumentManager.MdiActiveDocument.Database;
            TransactionManager tm    = db.TransactionManager;
            Transaction        trans = tm.StartTransaction();

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

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

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

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

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

                trans.Commit();
            }
            catch (System.Exception e)
            {
                trans.Abort();
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(e.Message);
            }
            finally
            {
                trans.Dispose();
            }
        }
Пример #29
0
        void StreamCollectClipBodiesSample()
        {
            Database db     = GetDatabase();
            Editor   editor = GetEditor();

            editor.WriteMessage("* StreamCollectClipBodies *\n");
            editor.WriteMessage("StreamCollectClipBodies clips all geometry pushed in against the supplied body.\n");
            editor.WriteMessage("Pick some objects in the current drawing and then pick an mass element to define the clipping boundary. The collected graphics will be highlighted in the current view.\n");

            ObjectIdCollection ids = PickObjectSet("Please pick the objects to be clipped");

            if (ids.Count == 0)
            {
                editor.WriteMessage("No object is picked\n");
                return;
            }

            ObjectId massElemId = PickObject(typeof(MassElement), true, "Please pick a mass element to define the clipping boundary");

            if (massElemId.IsNull)
            {
                editor.WriteMessage("A mass element is needed to define the clipping boundary.\n");
                return;
            }

            StreamCollectClipBodies stream = new StreamCollectClipBodies(db);
            // You may tell the stream to retain bodies instead of turning bodies into shells.
            // stream.SetRetainBodies(true);
            // But now we use the default setting, which uses shell as output.
            TransactionManager tm = db.TransactionManager;

            using (Transaction trans = tm.StartTransaction())
            {
                MassElement     masselem = trans.GetObject(massElemId, OpenMode.ForRead) as MassElement;
                AecModeler.Body body     = masselem.Body.Transform(masselem.Ecs);
                stream.SetBodyClipVolume(body);

                stream.PushDisplayParameters(DictionaryDisplayConfiguration.GetStandardDisplayConfiguration(db), trans);

                foreach (ObjectId id in ids)
                {
                    Entity entity = trans.GetObject(id, OpenMode.ForRead) as Entity;
                    stream.Stream(entity);
                }

                stream.PopDisplayParameters();
                trans.Commit();
            }

            GraphicsStorage[] gsCollection = stream.GetCollectedGraphics();
            foreach (GraphicsStorage gs in gsCollection)
            {
                HighlightGraphics(gs);
            }
        }
Пример #30
0
        public static void DrawNewBlock(Point3d InsertionPoint)
        {
            //Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            DocumentCollection dm            = Application.DocumentManager;
            Editor             ed            = dm.MdiActiveDocument.Editor;
            Database           destDb        = dm.MdiActiveDocument.Database;
            Database           sourceDb      = new Database(false, true);
            string             GisFile       = string.Format(@"{0}\GIS\{1}", Atend.Control.Common.DesignFullAddress, "Atend_Gis.dwg");
            string             SourceGisFile = string.Format(@"{0}\GIS\{1}", Atend.Control.Common.fullPath, "Atend_Gis.dwg");

            if (!System.IO.Directory.Exists(Atend.Control.Common.DesignFullAddress + @"\GIS"))
            {
                System.IO.Directory.CreateDirectory(Atend.Control.Common.DesignFullAddress + @"\GIS");
            }
            System.IO.File.Copy(SourceGisFile, GisFile, true);
            using (DocumentLock dLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                try
                {
                    if (System.IO.File.Exists(GisFile))
                    {
                        sourceDb.ReadDwgFile(GisFile, System.IO.FileShare.ReadWrite, true, "");
                        //ObjectIdCollection blockIds = new ObjectIdCollection();
                        Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager;
                        using (Transaction myT = tm.StartTransaction())
                        {
                            string           BlockName = "POINTBLOCK";
                            BlockTable       bt        = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForWrite, false);
                            BlockTableRecord btr       = (BlockTableRecord)myT.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                            ObjectId         bID;
                            if (bt.Has(BlockName))
                            {
                                bID = bt[BlockName];
                                //        //ed.writeMessage("بلاک مورد نظر یافت شد" + " \n");
                                BlockReference br = new BlockReference(InsertionPoint, bID);
                                ed.WriteMessage("BLOCK REFERENCE CREATED \n");

                                btr.AppendEntity(br);
                                ed.WriteMessage("BLOCK APPENDED\n");

                                myT.AddNewlyCreatedDBObject(br, true);
                                ed.WriteMessage("TRANSACTION \n");
                                myT.Commit();
                            }
                        }
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage("\nError during copy: " + ex.Message + "\n");
                }
            }
            sourceDb.Dispose();
        }