Beispiel #1
0
        public List <Db.ObjectId> GetPipeIdByName(string[] pipeNames)
        {
            Ed.Editor         ed     = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Civ.CivilDocument civDoc = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument;
            var pipeIds = new List <Db.ObjectId>();

            // Iterate through each pipe network
            using (Db.Transaction ts = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction()) {
                try {
                    foreach (Db.ObjectId networkId in civDoc.GetPipeNetworkIds())
                    {
                        CivDb.Network oNetwork = ts.GetObject(networkId, Db.OpenMode.ForWrite) as CivDb.Network;
                        foreach (Db.ObjectId pipeId in oNetwork.GetPipeIds())
                        {
                            CivDb.Pipe oPipe = ts.GetObject(pipeId, Db.OpenMode.ForRead) as CivDb.Pipe;
                            foreach (string name in pipeNames)
                            {
                                if (oPipe.Name == name)
                                {
                                    pipeIds.Add(oPipe.Id);
                                }
                            }
                        }
                    }
                    return(pipeIds);
                } catch (Autodesk.AutoCAD.Runtime.Exception ex) {
                    ed.WriteMessage("StructurePipesData: " + ex.Message);
                    return(null);
                }
            }
        }
        private static void SetDrawOrderInBlock(App.Document dwg, Db.ObjectId blkId)
        {
            using (Db.Transaction tran =
                       dwg.TransactionManager.StartTransaction())
            {
                Db.BlockReference bref = (Db.BlockReference)tran.GetObject(
                    blkId, Db.OpenMode.ForRead);

                Db.BlockTableRecord bdef = (Db.BlockTableRecord)tran.GetObject(
                    bref.BlockTableRecord, Db.OpenMode.ForWrite);

                Db.DrawOrderTable doTbl = (Db.DrawOrderTable)tran.GetObject(
                    bdef.DrawOrderTableId, Db.OpenMode.ForWrite);

                Db.ObjectIdCollection col = new Db.ObjectIdCollection();
                foreach (Db.ObjectId id in bdef)
                {
                    if (id.ObjectClass == Rtm.RXObject.GetClass(typeof(Db.Wipeout)))
                    {
                        col.Add(id);
                    }
                }

                if (col.Count > 0)
                {
                    doTbl.MoveToBottom(col);
                }


                tran.Commit();
            }
        }
        public override List <string> GetObjectsInView()
        {
            var objs = new List <string>();

            using (AcadDb.Transaction tr = Doc.Database.TransactionManager.StartTransaction())
            {
                AcadDb.BlockTable       blckTbl     = tr.GetObject(Doc.Database.BlockTableId, AcadDb.OpenMode.ForRead) as AcadDb.BlockTable;
                AcadDb.BlockTableRecord blckTblRcrd = tr.GetObject(blckTbl[AcadDb.BlockTableRecord.ModelSpace], AcadDb.OpenMode.ForRead) as AcadDb.BlockTableRecord;
                foreach (AcadDb.ObjectId id in blckTblRcrd)
                {
                    var dbObj = tr.GetObject(id, AcadDb.OpenMode.ForRead);
                    if (dbObj is AcadDb.BlockReference)
                    {
                        var blckRef = (AcadDb.BlockReference)dbObj; // skip block references for now
                    }
                    else
                    {
                        objs.Add(dbObj.Handle.ToString());
                    }
                }
                // TODO: this returns all the doc objects. Need to check for visibility later.
                tr.Commit();
            }
            return(objs);
        }
Beispiel #4
0
        public void CDS_CreateElevationRanges()
        {
            AcadDb.ObjectId surfaceId = promptForTinSurface();
            if (surfaceId == AcadDb.ObjectId.Null)
            {
                return;
            }

            using (AcadDb.Transaction tr = startTransaction())
            {
                TinSurface surface =
                    surfaceId.GetObject(AcadDb.OpenMode.ForWrite)
                    as TinSurface;

                // Get the existing analysis, if any.
                SurfaceAnalysisElevationData[] data =
                    surface.Analysis.GetElevationData();
                _editor.WriteMessage("\nExisting analysis length: {0}",
                                     data.Length);
                SurfaceAnalysisElevationData[] newData =
                    CreateElevationRegions(surface, 10, 100);
                surface.Analysis.SetElevationData(newData);

                tr.Commit();
            }
        }
Beispiel #5
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();
                }
            }
        }
Beispiel #6
0
Datei: Db.cs Projekt: 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);
        }
Beispiel #7
0
        } //WriteResourceToFile

        internal static Db.ObjectId GetIDbyName <T>(Db.Database db, string strName)
        {
            Db.ObjectId RecId = Db.ObjectId.Null;
            using (Db.Transaction tr1 = db.TransactionManager.StartTransaction())
            {
                if (typeof(T) == typeof(Db.MLeaderStyle))
                {
                    Db.DBDictionary mlstyles = (Db.DBDictionary)tr1.GetObject(
                        db.MLeaderStyleDictionaryId,
                        Db.OpenMode.ForRead);

                    RecId = (mlstyles.Contains(strName)) ? mlstyles.GetAt(strName) : Db.ObjectId.Null;
                }
                else if (typeof(T) == typeof(Db.LayerTableRecord))
                {
                    Db.LayerTable layerTable;
                    layerTable = (Db.LayerTable)tr1.GetObject(db.LayerTableId,
                                                              Db.OpenMode.ForRead);

                    RecId = (layerTable.Has(strName)) ? layerTable[strName] : Db.ObjectId.Null;
                }
                tr1.Commit();
            }
            // Все еще можно получить Db.ObjectId.Null для передачи.
            return(RecId);
        }
Beispiel #8
0
        ProcessObject(AcDb.Transaction trHelp, AcDb.ObjectId lookForObjId, AcDb.ObjectId curObjId)
        {
            AcDb.DBObject tmpObj = trHelp.GetObject(curObjId, AcDb.OpenMode.ForRead);
            if (tmpObj != null)
            {
                m_count++;
                ReferenceFiler filer = new ReferenceFiler();
                tmpObj.DwgOut(filer);                          // find out who this object owns

                RecordReferences(lookForObjId, tmpObj, filer); // record references for this object

                // now recursively visit all the objects this one owns
                for (int i = 0; i < filer.m_hardOwnershipIds.Count; i++)
                {
                    ProcessObject(trHelp, lookForObjId, filer.m_hardOwnershipIds[i]);
                }

                for (int i = 0; i < filer.m_softOwnershipIds.Count; i++)
                {
                    ProcessObject(trHelp, lookForObjId, filer.m_softOwnershipIds[i]);
                }
            }
            else
            {
                m_skipped++;
            }
        }
Beispiel #9
0
 public void DeleteAllObjects()
 {
     using (DocumentLock doclock = Document.LockDocument())
     {
         using (AcDb.Transaction trans = TransactionManager.StartTransaction())
         {
             foreach (var obj in (ObjectList.FindAll(p => p.ToolpathCurve != null || p.ProcessActions != null)))
             {
                 if (obj.ToolpathCurve != null)
                 {
                     trans.GetObject(obj.ToolpathCurve.ObjectId, AcDb.OpenMode.ForWrite);
                     obj.ToolpathCurve.Erase();
                 }
                 else
                 {
                     obj.ProcessActions.ForEach(p =>
                     {
                         trans.GetObject(p.Toolpath.ObjectId, AcDb.OpenMode.ForWrite);
                         p.Toolpath.Erase();
                     });
                 }
             }
             trans.Commit();
             Editor.UpdateScreen();
         }
     }
     ObjectList.Clear();
 }
Beispiel #10
0
        private static void AddCircle(Gem.Point2d pnt, string layer)
        {
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                // Открытие таблицы Блоков для чтения
                Db.BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                                           Db.OpenMode.ForRead) as Db.BlockTable;

                // Открытие записи таблицы Блоков пространства Модели для записи
                Db.BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[Db.BlockTableRecord.ModelSpace],
                                                                    Db.OpenMode.ForWrite) as Db.BlockTableRecord;

                Db.Circle acCircle = new Db.Circle();
                acCircle.SetDatabaseDefaults();
                acCircle.Center = new Gem.Point3d(pnt.X, pnt.Y, 0);
                acCircle.Radius = SettingsParser.getInstance()._Scale.Circle;
                acCircle.Layer  = layer;
                // Добавление нового объекта в запись таблицы блоков и в транзакцию
                acBlkTblRec.AppendEntity(acCircle);
                acTrans.AddNewlyCreatedDBObject(acCircle, true);
                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
Beispiel #11
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);
        }
Beispiel #12
0
 public void DeleteObject(ProcessObject obj)
 {
     // TODO удалить обработчики
     //obj.ProcessCurve.Modified -= ProcessCurveModifiedEventHandler;
     //obj.ProcessCurve.Erased -= ProcessCurveErasedEventHandler;
     if (obj.ToolpathCurve != null || obj.ProcessActions != null)
     {
         using (DocumentLock doclock = Document.LockDocument())
         {
             using (AcDb.Transaction trans = TransactionManager.StartTransaction())
             {
                 if (obj.ToolpathCurve != null)
                 {
                     trans.GetObject(obj.ToolpathCurve.ObjectId, AcDb.OpenMode.ForWrite);
                     obj.ToolpathCurve.Erase();
                 }
                 else
                 {
                     obj.ProcessActions.ForEach(p =>
                     {
                         trans.GetObject(p.Toolpath.ObjectId, AcDb.OpenMode.ForWrite);
                         p.Toolpath.Erase();
                     });
                 }
                 trans.Commit();
                 Editor.UpdateScreen();
             }
         }
     }
     RemoveConnect(obj, VertexType.Start);
     RemoveConnect(obj, VertexType.End);
     ObjectList.Remove(obj);
     ObjectForm.RefreshList();
 }
Beispiel #13
0
        public static bool GetPoint(ref AcadGeo.Point3d val, string message, AcadGeo.Point3d bp)
        {
            AcadApp.DocumentManager.MdiActiveDocument.Window.Focus();
            using (AcadApp.DocumentManager.MdiActiveDocument.LockDocument())
            {
                using (AcadDB.Transaction tr = AcadFuncs.GetActiveDoc().TransactionManager.StartTransaction())
                {
                    AcadEd.PromptPointOptions prmpt_pnt = new AcadEd.PromptPointOptions(message);
                    prmpt_pnt.UseBasePoint = true;
                    prmpt_pnt.BasePoint    = bp;
                    AcadEd.PromptPointResult prmpt_ret = AcadFuncs.GetEditor().GetPoint(prmpt_pnt);
                    if (AcadEd.PromptStatus.Cancel == prmpt_ret.Status)
                    {
                        tr.Abort();
                        tr.Dispose();
                        return(false);
                    }

                    val = prmpt_ret.Value;
                    tr.Commit();
                }
            }

            return(true);
        }
Beispiel #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);
                }
            }
        }
Beispiel #15
0
        public IResult GetEntities(Type type)
        {
            var db           = AAAS.Core.Application.DocumentManager.MdiActiveDocument.Database;
            var returnresult = new Result_Model();

            using (AADS.Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    var modelspaceId = AADS.SymbolUtilityServices.GetBlockModelSpaceId(db);
                    var modelspace   = modelspaceId.GetObject(AADS.OpenMode.ForRead, false) as AADS.BlockTableRecord;
                    var rxobjclass   = AAR.RXObject.GetClass(type);
                    var entityids    = modelspace.Cast <AADS.ObjectId>().Where(id => id.ObjectClass == rxobjclass);

                    returnresult.Payload.Clear();
                    entityids.ToList().ForEach(id => returnresult.Payload.Add(id.GetObject(AADS.OpenMode.ForRead, false)));

                    tr.Commit();
                }
                catch
                {
                    tr.Abort();
                    returnresult.ResultType = Core.Enums.ResultTypes.Failed;
                }
            }

            return(returnresult);
        }
        private bool GetOrMakeLayer(string layerName, AcadDb.Transaction tr, out string cleanName)
        {
            cleanName = Utils.RemoveInvalidChars(layerName);
            try
            {
                AcadDb.LayerTable lyrTbl = tr.GetObject(Doc.Database.LayerTableId, AcadDb.OpenMode.ForRead) as AcadDb.LayerTable;
                if (lyrTbl.Has(cleanName))
                {
                    return(true);
                }
                else
                {
                    lyrTbl.UpgradeOpen();
                    var _layer = new AcadDb.LayerTableRecord();

                    // Assign the layer properties
                    _layer.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByColor, 7); // white
                    _layer.Name  = cleanName;

                    // Append the new layer to the layer table and the transaction
                    lyrTbl.Add(_layer);
                    tr.AddNewlyCreatedDBObject(_layer, true);
                }
            }
            catch { return(false); }
            return(true);
        }
Beispiel #17
0
        private static void AddText(Gem.Point2d pnt, string layer, string str)
        {
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                // Открытие таблицы Блоков для чтения
                Db.BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, Db.OpenMode.ForRead) as Db.BlockTable;

                // Открытие записи таблицы Блоков пространства Модели для записи
                Db.BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[Db.BlockTableRecord.ModelSpace],
                                                                    Db.OpenMode.ForWrite) as Db.BlockTableRecord;

                Db.MText acMText = new Db.MText();
                acMText.SetDatabaseDefaults();
                acMText.Location = new Gem.Point3d(pnt.X, pnt.Y, 0);
                acMText.Contents = str;
                acMText.Height   = SettingsParser.getInstance()._Scale.Coord;
                acMText.Color    = Autodesk.AutoCAD.Colors.
                                   Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByLayer, 256);
                acMText.Layer = layer;
                acMText.SetDatabaseDefaults();
                // Добавление нового объекта в запись таблицы блоков и в транзакцию
                acBlkTblRec.AppendEntity(acMText);
                acTrans.AddNewlyCreatedDBObject(acMText, true);
                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
Beispiel #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);
        }
Beispiel #19
0
        static public void GetEnt()
        {
            AcEd.Editor  ed = AcAp.Application.DocumentManager.MdiActiveDocument.Editor;
            PromptResult rs = ed.GetString("\nВведите метку примитива (в hex-представлении): ");

            if (rs.Status != PromptStatus.OK)
            {
                return;
            }
            System.Int64  l  = System.Int64.Parse(rs.StringResult, System.Globalization.NumberStyles.HexNumber);
            AcDb.Handle   h  = new AcDb.Handle(l);
            AcDb.Database db = AcDb.HostApplicationServices.WorkingDatabase;
            AcDb.ObjectId id = db.GetObjectId(false, h, 0);
            if (!id.IsValid)
            {
                ed.WriteMessage("\nОшибочная метка примитива {0}", h);
                return;
            }
            using (AcAp.DocumentLock doclock = ed.Document.LockDocument())
            {
                using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
                {
                    AcDb.Entity ent = tr.GetObject(id, AcDb.OpenMode.ForRead) as AcDb.Entity;
                    if (ent != null)
                    {
                        ed.WriteMessage("\nEntity Class: {0}", AcRx.RXClass.GetClass(ent.GetType()).Name);
                        // Ну и так далее - делаешь с примитивом то, что тебе нужно...
                    }
                    else
                    {
                        ed.WriteMessage("\nЭто не примитив!");
                    }
                }
            }
        }
Beispiel #20
0
        public int processObjectId(DB.Transaction tr, DB.ObjectId objId, FindReplacer findReplacer)
        {
            int replaced = 0;
            var ent      = tr.GetObject(objId, DB.OpenMode.ForWrite, false);

            if (ent is DB.Table)
            {
                var tbl = ent as DB.Table;
                if (tbl.NumRows > 0 && tbl.NumColumns > 0)
                {
                    for (var r = 0; r < tbl.NumRows; r++)
                    {
                        for (var c = 0; c < tbl.NumColumns; c++)
                        {
                            var text = tbl.GetTextString(r, c, 0, DB.FormatOption.FormatOptionNone);
                            var textWithoutFormat = tbl.GetTextString(r, c, 0, DB.FormatOption.IgnoreMtextFormat);
                            if (findReplacer.ContainsIn(text, textWithoutFormat))
                            {
                                tbl.SetTextString(r, c, text.Replace(findReplacer.Find, findReplacer.Replace));
                                replaced++;
                            }
                        }
                    }
                }
            }
            else if (ent is DB.MText)
            {
                var mtext             = ent as DB.MText;
                var text              = mtext.Contents;
                var textWithoutFormat = mtext.Text;
                if (findReplacer.ContainsIn(text, textWithoutFormat))
                {
                    mtext.Contents = text.Replace(findReplacer.Find, findReplacer.Replace);
                    replaced++;
                }
            }
            else if (ent is DB.DBText)
            {
                var dbtext = ent as DB.DBText;
                var text   = dbtext.TextString;
                if (findReplacer.ContainsIn(text, text))
                {
                    dbtext.TextString = text.Replace(findReplacer.Find, findReplacer.Replace);
                    replaced++;
                }
            }
            else if (ent is DB.BlockReference)
            {
                var br   = ent as DB.BlockReference;
                var brId = br.IsDynamicBlock ? br.DynamicBlockTableRecord : br.BlockTableRecord;
                var btr  = (DB.BlockTableRecord)tr.GetObject(brId, DB.OpenMode.ForRead, false);
                foreach (DB.ObjectId objId2 in btr)
                {
                    processObjectId(tr, objId2, findReplacer);
                }
            }

            return(replaced);
        }
Beispiel #21
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();
     }
 }
Beispiel #22
0
        static public void SpaceOnAttributeName()
        {
            // Получение текущего документа и базы данных
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;
            Ed.Editor    acEd    = acDoc.Editor;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                Db.TypedValue[] acTypValAr = new Db.TypedValue[1];
                acTypValAr.SetValue(new Db.TypedValue((int)Db.DxfCode.Start, "INSERT"), 0);
                Ed.SelectionFilter acSelFtr = new Ed.SelectionFilter(acTypValAr);

                Ed.PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(acSelFtr);
                if (acSSPrompt.Status == Ed.PromptStatus.OK)
                {
                    Ed.SelectionSet acSSet = acSSPrompt.Value;
                    foreach (Ed.SelectedObject acSSObj in acSSet)
                    {
                        if (acSSObj != null)
                        {
                            if (acSSObj.ObjectId.ObjectClass.IsDerivedFrom(Rtm.RXClass.GetClass(typeof(Db.BlockReference))))
                            {
                                Db.BlockReference acEnt = acTrans.GetObject(acSSObj.ObjectId,
                                                                            Db.OpenMode.ForRead) as Db.BlockReference;

                                Db.BlockTableRecord blr = acTrans.GetObject(acEnt.BlockTableRecord,
                                                                            Db.OpenMode.ForRead) as Db.BlockTableRecord;
                                if (acEnt.IsDynamicBlock)
                                {
                                    blr = acTrans.GetObject(acEnt.DynamicBlockTableRecord,
                                                            Db.OpenMode.ForRead) as Db.BlockTableRecord;
                                }

                                if (blr.HasAttributeDefinitions)
                                {
                                    foreach (Db.ObjectId id in blr)
                                    {
                                        if (id.ObjectClass.IsDerivedFrom(Rtm.RXClass.GetClass(typeof(Db.AttributeDefinition))))
                                        {
                                            Db.AttributeDefinition acAttrRef = acTrans.GetObject(id,
                                                                                                 Db.OpenMode.ForWrite) as Db.AttributeDefinition;

                                            if (acAttrRef != null)
                                            {
                                                acAttrRef.Tag = acAttrRef.Tag.Replace('_', ' ');
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                acTrans.Commit();
            }
        }
Beispiel #23
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);
        }
        public static void StatisticsModel123_Steel4(BeamData beam, AcadDB.BlockReference blk_ref)
        {
            AcadDB.Database db = AcadApp.DocumentManager.MdiActiveDocument.Database;
            using (AcadDB.Transaction trans = db.TransactionManager.StartTransaction())
            {
                AcadDB.AttributeCollection atts = blk_ref.AttributeCollection;
                foreach (AcadDB.ObjectId att in atts)
                {
                    AcadDB.AttributeReference att_ref = trans.GetObject(att, AcadDB.OpenMode.ForWrite) as AcadDB.AttributeReference;
                    if (null == att_ref)
                    {
                        continue;
                    }

                    if (ATT_SH == att_ref.Tag)
                    {
                        att_ref.TextString = "4";
                    }
                    if (ATT_DK == att_ref.Tag)
                    {
                        att_ref.TextString = beam.dau_goi_data.first_layer_diameter.ToString();
                    }
                    if (ATT_DAI == att_ref.Tag)
                    {
                        att_ref.TextString = (beam.Length - 2 * Beam.cover).ToString();
                    }
                    if (ATT_L2 == att_ref.Tag)
                    {
                        att_ref.TextString = "2000";
                    }
                    if (ATT_L1 == att_ref.Tag)
                    {
                        att_ref.TextString = (beam.Height - 2 * Beam.cover).ToString();
                    }
                    if (ATT_SL1 == att_ref.Tag)
                    {
                        att_ref.TextString = (beam.dau_goi_data.number_steel_first_layer).ToString();
                    }
                    if (ATT_SLA == att_ref.Tag)
                    {
                        att_ref.TextString = (beam.dau_goi_data.number_steel_first_layer).ToString();
                    }
                    if (ATT_DT == att_ref.Tag)
                    {
                        double total_len = beam.dau_goi_data.number_steel_first_layer * (beam.Length - 2 * Beam.cover);
                        total_len         /= 1000.0;
                        att_ref.TextString = (total_len).ToString();
                    }
                    if (ATT_TL == att_ref.Tag)
                    {
                        att_ref.TextString = "...";
                    }
                }

                trans.Commit();
            }
        }
Beispiel #25
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();
            }
        }
Beispiel #26
0
        public void Draw()
        {
            List <PathInfo> swept_paths = GetSweptPath();

            AcadDB.SweepOptionsBuilder swept_options = new AcadDB.SweepOptionsBuilder();
            swept_options.Align = AcadDB.SweepOptionsAlignOption.NoAlignment;

            using (AcadDB.Transaction tr = AcadFuncs.GetActiveDB().TransactionManager.StartTransaction())
            {
                AcadDB.Solid3d union_sol3d     = null;
                AcadDB.Solid3d union_sub_sol3d = null;
                foreach (var pi in swept_paths)
                {
                    if (null != pi.sub_region)
                    {
                        AcadDB.Solid3d solid = new AcadDB.Solid3d();
                        swept_options.BasePoint = pi.start_position;
                        solid.CreateSweptSolid(pi.sub_region, pi.path, swept_options.ToSweepOptions());
                        if (null == union_sub_sol3d)
                        {
                            union_sub_sol3d = solid;
                        }
                        else
                        {
                            union_sub_sol3d.BooleanOperation(AcadDB.BooleanOperationType.BoolUnite, solid);
                        }
                    }

                    if (null != pi.region)
                    {
                        AcadDB.Solid3d solid = new AcadDB.Solid3d();
                        swept_options.BasePoint = pi.start_position;
                        solid.CreateSweptSolid(pi.region, pi.path, swept_options.ToSweepOptions());
                        if (null == union_sol3d)
                        {
                            union_sol3d = solid;
                        }
                        else
                        {
                            union_sol3d.BooleanOperation(AcadDB.BooleanOperationType.BoolUnite, solid);
                        }
                    }
                }

                union_sol3d.BooleanOperation(AcadDB.BooleanOperationType.BoolSubtract, union_sub_sol3d);

                if (!(this is Straight))
                {
                    union_sol3d.ColorIndex = 1;
                }

                AcadFuncs.AddNewEnt(union_sol3d);

                tr.Commit();
            }
        }
        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);
            }
        }
Beispiel #28
0
 public CivilObject SetStyle(CivilStyle civilStyle)
 {
     Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
     Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;
     using (Autodesk.AutoCAD.DatabaseServices.Transaction trans = db.TransactionManager.StartTransaction())
     {
         Autodesk.Civil.DatabaseServices.Entity entity = (Autodesk.Civil.DatabaseServices.Entity)trans.GetObject(_curCivilObject.ObjectId, OpenMode.ForWrite);
         entity.StyleId = civilStyle.InternalObjectId;
         trans.Commit();
     }
     return(this);
 }
Beispiel #29
0
        AddToCurrentSpaceAndClose(Entity ent, Database db)
        {
            ObjectId objId;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) {
                objId = AddToCurrentSpace(ent, db, tr);
                tr.Commit();
            }

            return(objId);
        }
Beispiel #30
0
 public Autodesk.Civil.DynamoNodes.CivilObject SetDescription(string description)
 {
     Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
     Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;
     using (Autodesk.AutoCAD.DatabaseServices.Transaction trans = db.TransactionManager.StartTransaction())
     {
         Autodesk.Civil.DatabaseServices.Entity entity = (Autodesk.Civil.DatabaseServices.Entity)trans.GetObject(_curCivilObject.ObjectId, OpenMode.ForWrite);
         entity.Name = description;
         trans.Commit();
     }
     this._description = description;
     return(this);
 }