Example #1
0
            public static bool Jig(Point3d p0, int segments)
            {
                ParabolaJig jigger = new ParabolaJig(CreatePolyline(), p0, segments);

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

                PromptResult res = doc.Editor.Drag(jigger);

                if (res.Status == PromptStatus.OK)
                {
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                        using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite))
                        {
                            btr.AppendEntity(jigger.Entity);
                            tr.AddNewlyCreatedDBObject(jigger.Entity, true);

                            tr.Commit();
                        }

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
Example #2
0
            private void UpdatePolyline()
            {
                Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                Matrix3d ucs2wcs  = AcadUtility.AcadGraphics.UcsToWcs;
                Plane    ucsPlane = new Plane(Point3d.Origin, Vector3d.ZAxis);

                // Coordinates in UCS
                Point3dCollection points = new Point3dCollection
                {
                    mp1,
                    mp2,
                    mp3,
                    mp4
                };

                Polyline pline      = Entity as Polyline;
                Plane    plinePlane = new Plane(Point3d.Origin, pline.Normal);

                pline.Reset(false, points.Count);
                int i = 0;

                foreach (Point3d pt in points)
                {
                    Point3d wcsPt = pt.TransformBy(ucs2wcs);       // Convert to WCS
                    Point2d ecsPt = plinePlane.ParameterOf(wcsPt); // Convert to ECS
                    pline.AddVertexAt(i, ecsPt, 0, 0, 0);
                }
                pline.Closed = true;
            }
Example #3
0
        BruteForceFindReferences(TransactionHelper trHelp)
        {
            m_count   = 0;
            m_skipped = 0;

            // since we aren't calculating this in the destructor, we have to re-init every time they
            // do the drill-down.
            m_hardPointerIds.Clear();
            m_softPointerIds.Clear();
            m_hardOwnershipIds.Clear();
            m_softOwnershipIds.Clear();

            AcDb.Database db = m_val.Database;

            // pass in all the root objects
            ProcessObject(trHelp, m_val, db.NamedObjectsDictionaryId);
            ProcessObject(trHelp, m_val, db.BlockTableId);
            ProcessObject(trHelp, m_val, db.DimStyleTableId);
            ProcessObject(trHelp, m_val, db.LayerTableId);
            ProcessObject(trHelp, m_val, db.LinetypeTableId);
            ProcessObject(trHelp, m_val, db.RegAppTableId);
            ProcessObject(trHelp, m_val, db.TextStyleTableId);
            ProcessObject(trHelp, m_val, db.UcsTableId);
            ProcessObject(trHelp, m_val, db.ViewportTableId);
            ProcessObject(trHelp, m_val, db.ViewTableId);

            //string str = string.Format("Visited: {0:d}, Skipped: {1:d}, DB Approx: {2:d}", m_count, m_skipped, db.ApproxNumObjects);
            //MessageBox.Show(str);
        }
Example #4
0
        // Collect the complex DGN linetypes from the linetype table

        private static ObjectIdCollection CollectComplexLinetypeIds(
            ACADDB.Database db, Transaction tr
            )
        {
            var ids = new ObjectIdCollection();

            var lt =
                (LinetypeTable)tr.GetObject(
                    db.LinetypeTableId, OpenMode.ForRead
                    );

            foreach (var ltId in lt)
            {
                // Complex DGN linetypes have an extension dictionary
                // with a certain record inside

                var obj = tr.GetObject(ltId, OpenMode.ForRead);
                if (obj.ExtensionDictionary != ObjectId.Null)
                {
                    var exd =
                        (DBDictionary)tr.GetObject(
                            obj.ExtensionDictionary, OpenMode.ForRead
                            );
                    if (exd.Contains(dgnLsDefName))
                    {
                        ids.Add(ltId);
                    }
                }
            }
            return(ids);
        }
Example #5
0
        public static Polyline GetPolyFromObjId(ObjectId oid, AcadDb.Database db)
        {
            try
            {
                using (var transaction = db.TransactionManager.StartTransaction())
                {
                    DBObject @object;
                    try
                    {
                        @object = transaction.GetObject(oid, OpenMode.ForRead);
                    }
                    catch (NullReferenceException ex)
                    {
                        PGA.MessengerManager.MessengerManager.LogException(ex);

                        return(null);
                    }
                    var polyline = @object as Polyline;
                    if (polyline != null && polyline.Closed)
                    {
                        return(polyline);
                    }
                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                PGA.MessengerManager.MessengerManager.LogException(ex);
            }
            return(null);
        }
Example #6
0
            private void UpdatePolyline()
            {
                Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                Matrix3d ucs2wcs  = AcadUtility.AcadGraphics.UcsToWcs;
                Plane    ucsPlane = new Plane(Point3d.Origin, Vector3d.ZAxis);

                Point3dCollection points = new Point3dCollection();
                double            a      = Math.Abs(mp2.X - mp0.X) > double.Epsilon ? (mp2.Y - mp0.Y) / ((mp2.X - mp0.X) * (mp2.X - mp0.X)) : 0;

                for (int i = 0; i <= mSegments; i++)
                {
                    double t = (double)i / (double)mSegments;
                    // Parabola y = a * x ^ 2
                    double dx = t * (mp2.X - mp0.X);
                    double dy = a * dx * dx;
                    double x  = mp0.X + dx;
                    double y  = mp0.Y + dy;
                    points.Add(new Point3d(x, y, 0)); // Coordinates in UCS
                }

                Polyline pline      = Entity as Polyline;
                Plane    plinePlane = new Plane(Point3d.Origin, pline.Normal);

                pline.Reset(false, points.Count);
                foreach (Point3d pt in points)
                {
                    Point3d wcsPt = pt.TransformBy(ucs2wcs);       // Convert to WCS
                    Point2d ecsPt = plinePlane.ParameterOf(wcsPt); // Convert to ECS
                    pline.AddVertexAt(pline.NumberOfVertices, ecsPt, 0, 0, 0);
                }
            }
Example #7
0
        public ObjectId GetNewSiteId()
        {
            var    site = ObjectId.Null;
            Random rand = new Random();

            try
            {
                using (Application.DocumentManager.MdiActiveDocument.LockDocument())
                {
                    using (Transaction tr = CivilApplicationManager.StartTransaction())
                    {
                        var num = rand.Next(1000, 9999).ToString();

                        Autodesk.AutoCAD.DatabaseServices.Database db = CivilApplicationManager.WorkingDatabase;
                        var doc = CivilDocument.GetCivilDocument(db);

                        site = C3DLandDb.Site.Create(doc, "Site-" + num);

                        tr.Commit();
                    }
                }
            }
            catch (System.ArgumentException)
            {
                GetNewSiteId();
            }

            return(site);
        }
Example #8
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);
        }
Example #9
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Это не примитив!");
                    }
                }
            }
        }
Example #10
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();
            }
        }
Example #11
0
            private void UpdatePolyline()
            {
                Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                Matrix3d ucs2wcs  = AcadUtility.AcadGraphics.UcsToWcs;
                Plane    ucsPlane = new Plane(Point3d.Origin, Vector3d.ZAxis);
                Point2d  p1       = Intersect(mp0.Convert2d(ucsPlane), mt0.Convert2d(ucsPlane), mp2.Convert2d(ucsPlane), mt2.Convert2d(ucsPlane));

                Point3dCollection points = new Point3dCollection();

                for (int i = 0; i <= mSegments; i++)
                {
                    double t = (double)i / (double)mSegments;
                    // Quadratic bezier curve with control vertices p0, p1 and p2
                    double x = (1 - t) * (1 - t) * mp0.X + 2 * (1 - t) * t * p1.X + t * t * mp2.X;
                    double y = (1 - t) * (1 - t) * mp0.Y + 2 * (1 - t) * t * p1.Y + t * t * mp2.Y;
                    points.Add(new Point3d(x, y, 0)); // Coordinates in UCS
                }

                Polyline pline      = Entity as Polyline;
                Plane    plinePlane = new Plane(Point3d.Origin, pline.Normal);

                pline.Reset(false, points.Count);
                foreach (Point3d pt in points)
                {
                    Point3d wcsPt = pt.TransformBy(ucs2wcs);       // Convert to WCS
                    Point2d ecsPt = plinePlane.ParameterOf(wcsPt); // Convert to ECS
                    pline.AddVertexAt(pline.NumberOfVertices, ecsPt, 0, 0, 0);
                }
            }
Example #12
0
        BruteForceFindReferences(AcDb.Database database)
        {
            //App.Document mdiActiveDocument = App.Application.DocumentManager.MdiActiveDocument;
            //if (mdiActiveDocument == null) return;

            //AcDb.Database database = mdiActiveDocument.Database;

            using (var trHelp = database.TransactionManager.StartTransaction())
            {
                m_count   = 0;
                m_skipped = 0;

                // since we aren't calculating this in the destructor, we have to re-init every time they
                // do the drill-down.
                m_hardPointerIds.Clear();

                AcDb.Database db = m_val.Database;

                // pass in all the root objects
                ProcessObject(trHelp, m_val, db.NamedObjectsDictionaryId);
                ProcessObject(trHelp, m_val, db.BlockTableId);
                ProcessObject(trHelp, m_val, db.DimStyleTableId);
                ProcessObject(trHelp, m_val, db.LayerTableId);
                ProcessObject(trHelp, m_val, db.LinetypeTableId);
                ProcessObject(trHelp, m_val, db.RegAppTableId);
                ProcessObject(trHelp, m_val, db.TextStyleTableId);
                ProcessObject(trHelp, m_val, db.UcsTableId);
                ProcessObject(trHelp, m_val, db.ViewportTableId);
                ProcessObject(trHelp, m_val, db.ViewTableId);

                trHelp.Commit();
            }
        }
Example #13
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();
            }
        }
Example #14
0
            protected override SamplerStatus Sampler(JigPrompts prompts)
            {
                Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                Matrix3d wcs2ucs = AcadUtility.AcadGraphics.WcsToUcs;

                if (mAutoLine)
                {
                    JigPromptPointOptions textOpts = new JigPromptPointOptions("\nYazı yönü: ");
                    textOpts.BasePoint    = mpBase;
                    textOpts.UseBasePoint = true;
                    PromptPointResult textRes = prompts.AcquirePoint(textOpts);
                    if (textRes.Status != PromptStatus.OK)
                    {
                        return(SamplerStatus.Cancel);
                    }
                    Point3d  pt  = textRes.Value.TransformBy(wcs2ucs);
                    Vector3d dir = (pt - mpBase);
                    dir    = dir / dir.Length * mLineLength;
                    mpText = mpBase + dir;
                }
                else
                {
                    JigPromptPointOptions textOpts = new JigPromptPointOptions("\nYazı yeri: ");
                    textOpts.BasePoint    = mpBase;
                    textOpts.UseBasePoint = true;
                    PromptPointResult textRes = prompts.AcquirePoint(textOpts);
                    mpText = textRes.Value.TransformBy(wcs2ucs);
                }

                return(SamplerStatus.OK);
            }
Example #15
0
        CategoryTests()
        {
            db = Utils.Db.GetCurDwg();

            m_testFrameworkFuncs.Add(new MgdDbgTestFuncInfo("Selection Set Options",
                                                            "Various combinations of getting selection sets", "Selection Set",
                                                            new MgdDbgTestFuncInfo.TestFunc(SelectionSet), MgdDbgTestFuncInfo.TestType.Other));
            m_testFrameworkFuncs.Add(new MgdDbgTestFuncInfo("Select Red Circles Only",
                                                            "Use a filter to only allow selection of Red Circles", "Selection Set",
                                                            new MgdDbgTestFuncInfo.TestFunc(SelectRedCircles), MgdDbgTestFuncInfo.TestType.Other));
            m_testFrameworkFuncs.Add(new MgdDbgTestFuncInfo("Select Circles or Arcs",
                                                            "Use a filter to only allow selection of Circles and Arcs", "Selection Set",
                                                            new MgdDbgTestFuncInfo.TestFunc(SelectCirclesAndArcs), MgdDbgTestFuncInfo.TestType.Other));
            m_testFrameworkFuncs.Add(new MgdDbgTestFuncInfo("Diff Entities",
                                                            "Diff between two entities", "Reflection",
                                                            new MgdDbgTestFuncInfo.TestFunc(EntityDiff), MgdDbgTestFuncInfo.TestType.Other));
            m_testFrameworkFuncs.Add(new MgdDbgTestFuncInfo("Diff Objects",
                                                            "Diff between two objects", "Reflection",
                                                            new MgdDbgTestFuncInfo.TestFunc(ObjectDiff), MgdDbgTestFuncInfo.TestType.Other));
            m_testFrameworkFuncs.Add(new MgdDbgTestFuncInfo("Snoop XML Dom Document",
                                                            "Exercise XML Dom API", "Import/Export",
                                                            new MgdDbgTestFuncInfo.TestFunc(SnoopXml), MgdDbgTestFuncInfo.TestType.Other));
            m_testFrameworkFuncs.Add(new MgdDbgTestFuncInfo("Test Prompts",
                                                            "Exercise prompt classes", "Prompts",
                                                            new MgdDbgTestFuncInfo.TestFunc(TestPrompts), MgdDbgTestFuncInfo.TestType.Other));
            m_testFrameworkFuncs.Add(new MgdDbgTestFuncInfo("Drawing Stats",
                                                            "Export database stats to XML file", "Import/Export",
                                                            new MgdDbgTestFuncInfo.TestFunc(DwgStats), MgdDbgTestFuncInfo.TestType.Other));
            m_testFrameworkFuncs.Add(new MgdDbgTestFuncInfo("Drawing Stats Batch",
                                                            "Export batch stats to XML file", "Import/Export",
                                                            new MgdDbgTestFuncInfo.TestFunc(DwgStatsBatch), MgdDbgTestFuncInfo.TestType.Other));
        }
Example #16
0
        private void SaveAsDxf(string source, string dest, string drawingName)
        {
            try
            {
                if (drawingName == null)
                {
                    throw new ArgumentNullException(nameof(drawingName));
                }

                _logger.AddLog(String.Format("Drawing to Open: {0}", source));

                Autodesk.AutoCAD.DatabaseServices.Database oldDb = HostApplicationServices.WorkingDatabase;

                using (Autodesk.AutoCAD.DatabaseServices.Database db =
                           new Autodesk.AutoCAD.DatabaseServices.Database(false, true))
                {
                    db.ReadDwgFile(source, FileOpenMode.OpenForReadAndWriteNoShare, true, null);

                    db.CloseInput(true);

                    HostApplicationServices.WorkingDatabase = db;

                    var dxfout = Path.Combine(dest, drawingName.Replace(".DWG", ".DXF"));

                    HostApplicationServices.WorkingDatabase = oldDb;

                    db.DxfOut(dxfout, 16, DwgVersion.Current);
                }
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
        }
Example #17
0
        public static void Rotate90CCW()
        {
            PromptSelectionResult selRes = SelectWithPickFirst();

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

            PromptPointResult ptRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint("\nBase point: ");

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

            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;
            Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs;
            Vector3d zAxis   = ucs2wcs.CoordinateSystem3d.Zaxis;
            Matrix3d trans   = Matrix3d.Rotation(Math.PI / 2, zAxis, ptRes.Value.TransformBy(ucs2wcs));

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId id in selRes.Value.GetObjectIds())
                {
                    Entity en = tr.GetObject(id, OpenMode.ForWrite) as Entity;
                    if (en != null)
                    {
                        en.TransformBy(trans);
                    }
                }
                tr.Commit();
            }
        }
Example #18
0
        public static void ChangeToByLayer()
        {
            PromptSelectionResult selRes = SelectWithPickFirst();

            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                if (selRes.Status == PromptStatus.OK)
                {
                    foreach (ObjectId id in selRes.Value.GetObjectIds())
                    {
                        Entity en = tr.GetObject(id, OpenMode.ForWrite) as Entity;
                        if (en != null)
                        {
                            en.Color      = Color.FromColorIndex(ColorMethod.ByLayer, 256);
                            en.LinetypeId = db.ByLayerLinetype;
                            en.LineWeight = LineWeight.ByLayer;
                        }
                    }
                }

                db.Cecolor   = Color.FromColorIndex(ColorMethod.ByLayer, 256);
                db.Celtype   = db.ByLayerLinetype;
                db.Celweight = LineWeight.ByLayer;

                tr.Commit();
            }
        }
Example #19
0
        public ObjectId GetSiteId(ObjectId surfaceId)
        {
            var site = ObjectId.Null;

            using (Transaction tr = CivilApplicationManager.StartTransaction())

            {
                Autodesk.AutoCAD.DatabaseServices.Database db = CivilApplicationManager.WorkingDatabase;
                var doc = CivilDocument.GetCivilDocument(db);
                ObjectIdCollection siteIds = doc.GetSiteIds();
                if (siteIds != null && siteIds.Count != 0)
                {
                    site = (from s in siteIds.Cast <ObjectId>()
                            select s).FirstOrDefault();
                }

                if (site == ObjectId.Null)
                {
                    site = C3DLandDb.Site.Create(doc, "Site-ALL");
                }

                tr.Commit();
            }
            return(site);
        }
Example #20
0
        // Collect the DGN stroke entries from the NOD

        private static ObjectIdCollection CollectStrokeIds(
            ACADDB.Database db, Transaction tr
            )
        {
            var ids = new ObjectIdCollection();

            var nod =
                (DBDictionary)tr.GetObject(
                    db.NamedObjectsDictionaryId, OpenMode.ForRead
                    );

            // Strokes are stored in a particular dictionary

            if (nod.Contains(dgnLsDictName))
            {
                var dgnDict =
                    (DBDictionary)tr.GetObject(
                        (ObjectId)nod[dgnLsDictName],
                        OpenMode.ForRead
                        );

                foreach (var item in dgnDict)
                {
                    ids.Add(item.Value);
                }
            }

            return(ids);
        }
Example #21
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();
            }
        }
        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();
            }
        }
Example #23
0
        PurgeLinetypesReferencedNotByAnonBlocks(
            ACADDB.Database db, Transaction tr, ObjectIdCollection ids
            )
        {
            var keepers = new ObjectIdCollection();

            // Open the block table record

            var bt =
                (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

            foreach (var btrId in bt)
            {
                // Open each block definition in the drawing

                var btr =
                    (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead);

                // And open each entity in each block

                foreach (var id in btr)
                {
                    // Open the object and check its linetype

                    var obj = tr.GetObject(id, OpenMode.ForRead, true);
                    var ent = obj as Entity;
                    if (ent != null && !ent.IsErased)
                    {
                        if (ids.Contains(ent.LinetypeId))
                        {
                            // If the owner does not belong to an anonymous
                            // block, then we take it seriously as a reference

                            var owner =
                                (BlockTableRecord)tr.GetObject(
                                    ent.OwnerId, OpenMode.ForRead
                                    );
                            if (
                                !owner.Name.StartsWith("*") ||
                                owner.Name.ToUpper() == BlockTableRecord.ModelSpace ||
                                owner.Name.ToUpper().StartsWith(
                                    BlockTableRecord.PaperSpace
                                    )
                                )
                            {
                                // Move the linetype ID from the "to remove" list
                                // to the "to keep" list

                                ids.Remove(ent.LinetypeId);
                                keepers.Add(ent.LinetypeId);
                            }
                        }
                    }
                }
            }
            return(keepers);
        }
Example #24
0
        /// <summary>
        /// Поиск квартир в вфбранных блоках
        /// </summary>
        public static List <Apartment> GetApartments(IEnumerable <ObjectId> idsBlRef)
        {
            List <Apartment> apartments = new List <Apartment>();

            // Импользование базы для проверки категории элементов и их параметров
            using (var entities = BaseApartments.ConnectEntities())
            {
                entities.F_nn_Category_Parameters.Load();
                BaseCategoryParameters = entities.F_nn_Category_Parameters.Local.GroupBy(cp => cp.F_S_Categories).Select(p =>
                                                                                                                         new KeyValuePair <string, List <F_S_Parameters> >(p.Key.NAME_RUS_CATEGORY, p.Select(i => i.F_S_Parameters).ToList())).ToList();
            }

            Autodesk.AutoCAD.DatabaseServices.Database db = HostApplicationServices.WorkingDatabase;
            using (var t = db.TransactionManager.StartTransaction())
            {
                ProgressMeter progress = new ProgressMeter();
                progress.Start("Считывание квартир с чертежа...");

                foreach (ObjectId idEnt in idsBlRef)
                {
                    progress.MeterProgress();

                    var blRefApart = idEnt.GetObject(OpenMode.ForRead, false, true) as BlockReference;
                    if (blRefApart != null)
                    {
                        string blName = blRefApart.GetEffectiveName();
                        if (IsBlockNameApartment(blName))
                        {
                            // Не добавлять одну и ту же квартиру в список
                            if (!apartments.Exists(a => a.Name.Equals(blName, StringComparison.OrdinalIgnoreCase)))
                            {
                                try
                                {
                                    var apartment = new Apartment(blRefApart, blName);
                                    apartments.Add(apartment);
                                }
                                catch (System.Exception ex)
                                {
                                    Inspector.AddError($"Ошибка считывания блока квартиры '{blName}' - {ex.Message}.",
                                                       blRefApart, icon: SystemIcons.Error);
                                }
                            }
                        }
                        else
                        {
                            Inspector.AddError($"Отфильтрован блок квартиры '{blName}', имя не соответствует " +
                                               $"'{Options.Instance.BlockApartmentNameMatch}",
                                               blRefApart, icon: System.Drawing.SystemIcons.Information);
                        }
                    }
                }
                progress.Stop();
                t.Commit();
            }
            apartments.Sort((a1, a2) => a1.Name.CompareTo(a2.Name));
            return(apartments);
        }
Example #25
0
        private void dodaj_arc_Click(object sender, EventArgs e)
        {
            Document document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            DB_AC.Database db     = document.Database;
            Editor         editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            document.LockDocument();
            Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView();
            PromptEntityOptions kom = new PromptEntityOptions("Wskaż luk do zapisu: ");
            PromptEntityResult  rez = editor.GetEntity(kom);

            if (rez.Status == PromptStatus.OK)
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        Arc arc = trans.GetObject(rez.ObjectId, OpenMode.ForWrite) as Arc;
                        trans.Commit();

                        string GUID       = Guid.NewGuid().ToString();
                        double centerX    = arc.Center.X;
                        double centerY    = arc.Center.Y;
                        double centerZ    = arc.Center.Z;
                        double radius     = arc.Radius;
                        double startAngle = arc.StartAngle;
                        double endAngle   = arc.EndAngle;

                        string cConnectiongSting = @"Data Source =" + data_src.Text + "; Initial Catalog =" + tabela.Text + "; User ID =" + user.Text + ";Password ="******"; Integrated Security = true";

                        SQL_CLIENT.SqlConnection con = new SQL_CLIENT.SqlConnection(cConnectiongSting);
                        string cZapytanie            = "INSERT INTO ARC (GUID, centerX, centerY, centerZ, radius, startAngle, endAngle) VALUES (@GUID, @centerX, @centerY, @centerZ, @radius, @startAngle, @endAngle)";

                        SQL_CLIENT.SqlCommand cmd = new SQL_CLIENT.SqlCommand(cZapytanie, con);
                        cmd.Parameters.AddWithValue("@GUID", GUID);
                        cmd.Parameters.AddWithValue("@centerX", centerX);
                        cmd.Parameters.AddWithValue("@centerY", centerY);
                        cmd.Parameters.AddWithValue("@centerZ", centerZ);
                        cmd.Parameters.AddWithValue("@radius", radius);
                        cmd.Parameters.AddWithValue("@startAngle", startAngle);
                        cmd.Parameters.AddWithValue("@endAngle", endAngle);

                        con.Open();
                        int cIle = cmd.ExecuteNonQuery();
                        con.Close();

                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Ilość zapisanych łuków: " + cIle.ToString());
                    }
                    catch (System.Exception ex)
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Błąd zapisu: " + ex.Message);
                    }
                }
            }
        }
        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);
            }
        }
Example #27
0
        private void dodaj_line_Click(object sender, EventArgs e)
        {
            Document document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            DB_AC.Database db     = document.Database;
            Editor         editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            document.LockDocument();
            Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView();
            PromptEntityOptions kom = new PromptEntityOptions("Wskaż linie do zapisu: ");
            PromptEntityResult  rez = editor.GetEntity(kom);

            if (rez.Status == PromptStatus.OK)
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        Line line = trans.GetObject(rez.ObjectId, OpenMode.ForWrite) as Line;
                        trans.Commit();

                        string GUID   = Guid.NewGuid().ToString();
                        double startX = line.StartPoint.X;
                        double startY = line.StartPoint.Y;
                        double startZ = line.StartPoint.Z;
                        double endX   = line.EndPoint.X;
                        double endY   = line.EndPoint.Y;
                        double endZ   = line.EndPoint.Z;

                        string cConnectiongSting     = @"Data Source =" + data_src.Text + "; Initial Catalog =" + tabela.Text + "; User ID =" + user.Text + ";Password ="******"; Integrated Security = true";
                        SQL_CLIENT.SqlConnection con = new SQL_CLIENT.SqlConnection(cConnectiongSting);
                        string cZapytanie            = "INSERT INTO LINE (GUID, startX, startY, startZ, endX, endY, endZ) VALUES (@GUID, @startX, @startY, @startZ, @endX, @endY, @endZ)";

                        SQL_CLIENT.SqlCommand cmd = new SQL_CLIENT.SqlCommand(cZapytanie, con);
                        cmd.Parameters.AddWithValue("@GUID", GUID);
                        cmd.Parameters.AddWithValue("@startX", startX);
                        cmd.Parameters.AddWithValue("@startY", startY);
                        cmd.Parameters.AddWithValue("@startZ", startZ);
                        cmd.Parameters.AddWithValue("@endX", endX);
                        cmd.Parameters.AddWithValue("@endY", endY);
                        cmd.Parameters.AddWithValue("@endZ", endZ);

                        con.Open();
                        int cIle = cmd.ExecuteNonQuery();
                        con.Close();

                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Ilość zapisanych linii: " + cIle.ToString());
                    }
                    catch (System.Exception ex)
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Błąd zapisu: " + ex.Message);
                    }
                }
            }
        }
Example #28
0
        /// <summary>
        /// Экспорт блока в файл - файл в корне текущего чертежа с именем блока.
        /// Точка вставки блока - 0,0
        /// </summary>
        public void ExportToFile()
        {
            using (var db = new Autodesk.AutoCAD.DatabaseServices.Database(true, true))
            {
                db.CloseInput(true);

                var ids  = new ObjectIdCollection(new[] { IdBlRef });
                var idMS = SymbolUtilityServices.GetBlockModelSpaceId(db);

                using (IdMapping map = new IdMapping())
                {
                    db.WblockCloneObjects(ids, idMS, map, DuplicateRecordCloning.Replace, false);
                    // перенос блока в ноль
                    var idBlRefMap = map[IdBlRef].Value;
                    if (!idBlRefMap.IsNull)
                    {
                        using (var t = db.TransactionManager.StartTransaction())
                        {
                            var blRef = idBlRefMap.GetObject(OpenMode.ForWrite, false, true) as BlockReference;
                            blRef.Position = Point3d.Origin;

                            // Изменение вида
                            if (blRef.Bounds.HasValue)
                            {
                                try
                                {
                                    zoomDb(db, blRef.Bounds.Value);
                                    // Перенос штриховки на задний план
                                    var btrApart = blRef.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord;
                                    var orders   = btrApart.DrawOrderTableId.GetObject(OpenMode.ForWrite) as DrawOrderTable;
                                    var idsHatch = new ObjectIdCollection();
                                    foreach (var idEnt in btrApart)
                                    {
                                        if (idEnt.ObjectClass == RXClass.GetClass(typeof(Hatch)))
                                        {
                                            idsHatch.Add(idEnt);
                                        }
                                    }
                                    if (idsHatch.Count > 0)
                                    {
                                        orders.MoveToBottom(idsHatch);
                                    }
                                    // Превью чертежа из блока квартиры
                                    db.ThumbnailBitmap = new Bitmap(btrApart.PreviewIcon, new Size(320, 270));
                                }
                                catch { }
                            }
                            t.Commit();
                        }
                        db.SaveAs(File, DwgVersion.Current);
                    }
                }
                //Inspector.AddError($"Экспортирован блок {Name} в файл {File}", IdBlRef, icon: System.Drawing.SystemIcons.Information);
            }
        }
Example #29
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);
 }
Example #30
0
            private static Polyline CreatePolyline()
            {
                Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                Polyline pline = new Polyline(1);

                pline.Normal = AcadUtility.AcadGraphics.UcsToWcs.CoordinateSystem3d.Zaxis;
                pline.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);

                return(pline);
            }
Example #31
0
        /// <summary>
        /// insert signatures
        /// </summary>
        /// <param name="dwgPath">Signature drawings' path</param>
        /// <param name="dwgNameList">Signature drawing list</param>
        public void InsertSign(string dwgPath, List<string> dwgNameList)
        {
            AdeskAppSvr.Document doc = AdeskAppSvr.Application.DocumentManager.MdiActiveDocument;
            AdeskDBSvr.Database CurrDB = doc.Database;
            AdeskEdIn.Editor ed = doc.Editor;
            AdeskEdIn.PromptPointResult prPointRes_Base = ed.GetPoint(new AdeskEdIn.PromptPointOptions("ѡ�����Ļ���"));
            AdeskEdIn.PromptPointResult prPointRes_opp = ed.GetPoint(new AdeskEdIn.PromptPointOptions("ѡ�����ĶԽǵ�"));
            //In order to make the signs look nicely , calculate the base point and its opposite point
            AdeskGeo.Point3d P_base = CalPoint(prPointRes_Base.Value, prPointRes_opp.Value, 0.1);
            AdeskGeo.Point3d P_opp = CalPoint(prPointRes_Base.Value, prPointRes_opp.Value, 0.9);
            //sign's width and height
            double SignWidth = P_opp.X - P_base.X;
            double SignHeight = P_opp.Y - P_base.Y;
            //distance between each other
            double distanceW = prPointRes_opp.Value.X - prPointRes_Base.Value.X;
            double distanceH = prPointRes_opp.Value.Y - prPointRes_Base.Value.Y;

            //current date
            string date = System.DateTime.Today.ToLocalTime().ToString().Split(' ')[0];

            try
            {
                for (int i = 0; i < dwgNameList.Count; i++)
                {
                    using (AdeskDBSvr.Database tmpdb = new AdeskDBSvr.Database(false, false))
                    {
                        //read drawing
                        tmpdb.ReadDwgFile(dwgPath + dwgNameList[i], FileShare.Read, true, null);
                        //insert Signature drawing as a new block into current drawing
                        AdeskDBSvr.ObjectId idBTR = CurrDB.Insert(this.ICCardList[i], tmpdb, false);
                        //scale of signature. 36 is the width of sign, and 17 is the height. you should adjust them in your condition.
                        double WidthOfSign;
                        double HeightOfSign;
                        double scaleWidth = SignWidth / 36;
                        double scaleHeight = SignHeight / 17;
                        using (AdeskDBSvr.Transaction trans = CurrDB.TransactionManager.StartTransaction())
                        {
                            AdeskDBSvr.BlockTable bt = (AdeskDBSvr.BlockTable)trans.GetObject(CurrDB.BlockTableId, AdeskDBSvr.OpenMode.ForRead);
                            AdeskDBSvr.BlockTableRecord btr = (AdeskDBSvr.BlockTableRecord)trans.GetObject(bt[AdeskDBSvr.BlockTableRecord.ModelSpace], AdeskDBSvr.OpenMode.ForWrite);

                            AdeskDBSvr.BlockTableRecord InBtr = (AdeskDBSvr.BlockTableRecord)trans.GetObject(idBTR, AdeskDBSvr.OpenMode.ForRead);
                            foreach (AdeskDBSvr.ObjectId tmpid in InBtr)
                            {
                                AdeskDBSvr.DBObject dbo = trans.GetObject(tmpid, AdeskDBSvr.OpenMode.ForRead);
                                if (dbo is AdeskDBSvr.Ole2Frame)
                                {
                                    AdeskDBSvr.Ole2Frame mOle = (AdeskDBSvr.Ole2Frame)dbo;
                                    WidthOfSign = mOle.WcsWidth;
                                    HeightOfSign = mOle.WcsHeight;
                                    scaleWidth = SignWidth / WidthOfSign;
                                    scaleHeight = SignHeight / HeightOfSign;
                                    break;
                                }
                            }

                            //insert point of each signature and date from top to bottom
                            AdeskGeo.Point3d inPt = new AdeskGeo.Point3d(P_base.X, P_base.Y - i * distanceH, P_base.Z);

                            #region signature date
                            //signature date
                            AdeskDBSvr.MText SignDate = new AdeskDBSvr.MText();
                            AdeskDBSvr.TextStyleTable TextStyleTB = (AdeskDBSvr.TextStyleTable)trans.GetObject(CurrDB.TextStyleTableId, AdeskDBSvr.OpenMode.ForWrite);
                            AdeskDBSvr.TextStyleTableRecord TextStyleTBRec = new AdeskDBSvr.TextStyleTableRecord();

                            TextStyleTBRec.Font = new AdeskGra.FontDescriptor("����", true, false, 0, 0);
                            TextStyleTB.Add(TextStyleTBRec);
                            trans.AddNewlyCreatedDBObject(TextStyleTBRec, true);
                            SignDate.TextStyle = TextStyleTBRec.Id;
                            SignDate.Contents = date;
                            SignDate.TextHeight = SignHeight / 2;
                            SignDate.Width = SignWidth / 3;
                            //date's location should fit the frame
                            SignDate.Location = new AdeskGeo.Point3d((inPt.X + distanceW), (inPt.Y + 1.5 * SignDate.TextHeight), inPt.Z);
                            btr.AppendEntity(SignDate);
                            trans.AddNewlyCreatedDBObject(SignDate, true);
                            #endregion

                            try
                            {
                                //create a ref to the block
                                using (AdeskDBSvr.BlockReference bref = new AdeskDBSvr.BlockReference(inPt, idBTR))
                                {
                                    bref.ScaleFactors = new AdeskGeo.Scale3d(scaleWidth, scaleHeight, 1.0);
                                    btr.AppendEntity(bref);
                                    trans.AddNewlyCreatedDBObject(bref, true);
                                }
                                trans.Commit();
                            }
                            catch (System.Exception err)
                            {
                                MessageBox.Show("one: " + err.Message);
                            }
                        }
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception err)
            {
                MessageBox.Show("insert: " + err.Message);
            }
        }