雪山飞狐_lzh 发表于 2009-6-4 12:45:00

[原创]DBTransaction类

本帖最后由 作者 于 2009-6-6 13:51:44 编辑

其实很早前就在论坛里贴过早期的版本,不算新内容
没有做详细的测试,还希望各位朋友指正:)
简单的注释了下:)
DBTransaction.cs
#define AC2008
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
namespace TlsCad
{
    public class DBTransaction : IDisposable
    {
      private Database m_Database;
      private Transaction m_Transaction;
      private bool m_Commit = false;
      private BlockTableRecord m_BlockTableRecord;
      private BlockTable m_BlockTable;
      private TextStyleTable m_TextStyleTable;
      private LinetypeTable m_LinetypeTable;
      private RegAppTable m_RegAppTable;
      private LayerTable m_LayerTable;
      private UcsTable m_UcsTable;
      private ViewTable m_ViewTable;
      private ViewportTable m_ViewportTable;
      private DrawOrderTable m_DrawOrderTable;
      private DBDictionary m_GroupDictionary;
      //事务相关
      #region Tran
      //事务初始化,并只读方式打开块表
      private void Initialize()
      {
            try
            {
                m_Transaction = m_Database.TransactionManager.StartTransaction();
                m_BlockTable = (BlockTable)m_Transaction.GetObject(m_Database.BlockTableId, OpenMode.ForRead, false);
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                CadHelper.InfoMessageBox(ex.Message);
            }
      }
      //创建当前活动文档的事务(默认提交)
      public DBTransaction()
      {
            m_Database = HostApplicationServices.WorkingDatabase;
            Initialize();
      }
      //创建当前活动文档的事务
      //commit = true 提交事务
      //commit = false 不提交
      public DBTransaction(bool commit)
      {
            m_Commit = !commit;
            m_Database = HostApplicationServices.WorkingDatabase;
            Initialize();
      }
      //创建指定数据库的事务,一般用于临时数据库(默认提交)
      public DBTransaction(Database database)
      {
            m_Database = database;
            Initialize();
      }
      //创建指定数据库的事务
      //commit = true 提交事务
      //commit = false 不提交
      public DBTransaction(Database database, bool commit)
      {
            m_Commit = !commit;
            m_Database = database;
            Initialize();
      }
      //创建临时数据库的事务,并读入指定的文档(默认提交)
      public DBTransaction(string fileName)
      {
            try
            {
                m_Database = new Database(false, true);
                m_Database.ReadDwgFile(fileName, FileShare.Read, true, null);
                Initialize();
            }
            catch
            { }
      }
      //创建临时数据库的事务,并读入指定的文档
      //commit = true 提交事务
      //commit = false 不提交
      public DBTransaction(string DwgFileName, bool commit)
      {
            m_Commit = !commit;
            try
            {
                m_Database = new Database(false, true);
                m_Database.ReadDwgFile(DwgFileName, FileShare.Read, true, null);
                Initialize();
            }
            catch
            { }
      }
      //
      void IDisposable.Dispose()
      {
            Commit();
            m_Transaction.Dispose();
      }
      //按事务初始化参数决定事物是否提交
      public void Commit()
      {
            if (!m_Commit)
            {
                m_Transaction.Commit();
                m_Commit = true;
            }
      }
      //撤销事务
      public void Abort()
      {
            m_Transaction.Abort();
      }
      #endregion
      //在符号表中获取对应键值的记录Id
      //弥补索引器的Bug
      //即会获取已清除并存在符号表的记录
      //但2010版该Bug已消除
      public ObjectId GetIdFromSymbolTable(SymbolTable st, string key)
      {
            if (st.Has(key))
            {
                ObjectId idres = st;
                if (!idres.IsErased)
                  return idres;
#if AC2008
                foreach (ObjectId id in st)
                {
                  if (!id.IsErased)
                  {
                        SymbolTableRecord str = (SymbolTableRecord)m_Transaction.GetObject(id, OpenMode.ForRead);
                        if (str.Name == key)
                            return id;
                  }
                }
#endif
            }
            return ObjectId.Null;
      }
      //属性
      #region Properties
      public Database Database
      {
            get { return m_Database; }
      }
      public Transaction Transaction
      {
            get { return m_Transaction; }
      }
      public BlockTableRecord CurrentBlockTableRecord
      {
            get { return m_BlockTableRecord; }
      }
      public BlockTable BlockTable
      {
            get { return m_BlockTable; }
      }

      public LayerTable LayerTable
      {
            get { return m_LayerTable; }
      }
      public TextStyleTable TextStyleTable
      {
            get { return m_TextStyleTable; }
      }
      public RegAppTable RegAppTable
      {
            get { return m_RegAppTable; }
      }
      public LinetypeTable LinetypeTable
      {
            get { return m_LinetypeTable; }
      }
      public UcsTable UcsTable
      {
            get { return m_UcsTable; }
      }
      public ViewTable ViewTable
      {
            get { return m_ViewTable; }
      }
      public ViewportTable ViewportTable
      {
            get { return m_ViewportTable; }
      }
      public DrawOrderTable DrawOrderTable
      {
            get { return m_DrawOrderTable; }
      }
      public DBDictionary GroupDictionary
      {
            get { return m_GroupDictionary; }
      }
      #endregion
      //块表记录
      #region BlockTableRecord
      
      public BlockTableRecord OpenBlockTableRecord(ObjectId id, OpenMode openmode)
      {
            m_BlockTableRecord = (BlockTableRecord)m_Transaction.GetObject(
                id,
                openmode,
                false);
            return m_BlockTableRecord;
      }
      public BlockTableRecord OpenBlockTableRecord(ObjectId id)
      {
            return OpenBlockTableRecord(id, OpenMode.ForWrite);
      }
      public BlockTableRecord OpenBlockTableRecord(string name, OpenMode openmode)
      {
            ObjectId id = GetIdFromSymbolTable(m_BlockTable, name);
            if (id == ObjectId.Null)
                return null;
            return OpenBlockTableRecord(id, openmode);
      }
      public BlockTableRecord OpenBlockTableRecord(string name)
      {
            return OpenBlockTableRecord(m_BlockTable, OpenMode.ForWrite);
      }
      public void OpenCurrentSpace(OpenMode openmode)
      {
            OpenBlockTableRecord(m_Database.CurrentSpaceId, openmode);
      }
      public void OpenCurrentSpace()
      {
            OpenCurrentSpace(OpenMode.ForWrite);
      }
      public void OpenPaperSpace(OpenMode openmode)
      {
            OpenBlockTableRecord(BlockTableRecord.PaperSpace, openmode);
      }
      public void OpenPaperSpace()
      {
            OpenPaperSpace(OpenMode.ForWrite);
      }
      public void OpenModelSpace(OpenMode openmode)
      {
            OpenBlockTableRecord(BlockTableRecord.ModelSpace, openmode);
      }

      public void OpenModelSpace()
      {
            OpenModelSpace(OpenMode.ForWrite);
      }
      public DBObject GetObject(ObjectId id, OpenMode openmode)
      {
            return m_Transaction.GetObject(id, openmode, false);
      }
      #endregion
      //层表
      #region LayerTable
      public LayerTable OpenLayerTable(OpenMode openmode)
      {
            m_LayerTable = (LayerTable)m_Transaction.GetObject(
                m_Database.LayerTableId,
                openmode,
                false);
            return m_LayerTable;
      }
      public LayerTable OpenLayerTable()
      {
            return OpenLayerTable(OpenMode.ForWrite);
      }
      public ObjectId AddLayer(string name, Autodesk.AutoCAD.Colors.Color color, ObjectId linetypeid, LineWeight lineweight)
      {
            ObjectId id = GetIdFromSymbolTable(m_LayerTable, name);
            if (id == ObjectId.Null)
            {
                LayerTableRecord layer = new LayerTableRecord();
                layer.Name = name;
                layer.Color = color;
                layer.LinetypeObjectId = linetypeid;
                layer.LineWeight = lineweight;
                m_LayerTable.UpgradeOpen();
                id = m_LayerTable.Add(layer);
                m_Transaction.AddNewlyCreatedDBObject(layer, true);
            }
            return id;
      }
      #endregion
      //文字式样表
      #region TextStyleTable
      public TextStyleTable OpenTextStyleTable(OpenMode openmode)
      {
            m_TextStyleTable = (TextStyleTable)m_Transaction.GetObject(
                m_Database.TextStyleTableId,
                openmode,
                false);
            return m_TextStyleTable;
      }
      public TextStyleTable OpenTextStyleTable()
      {
            return OpenTextStyleTable(OpenMode.ForWrite);
      }
      public ObjectId AddTextStyle(string name, string smallfont, string bigfont, double height, double xscale)
      {
            ObjectId id = GetIdFromSymbolTable(m_TextStyleTable, name);
            if (id == ObjectId.Null)
            {
                TextStyleTableRecord tstr = new TextStyleTableRecord();
                tstr.Name = name;
                tstr.FileName = smallfont;
                tstr.BigFontFileName = bigfont;
                tstr.TextSize = height;
                tstr.XScale = xscale;
                m_TextStyleTable.UpgradeOpen();
                id = m_TextStyleTable.Add(tstr);
                m_Transaction.AddNewlyCreatedDBObject(tstr, true);
            }
            return id;
      }

      #endregion
      //注册应用程序
      #region RegAppTable
      public RegAppTable OpenRegAppTable(OpenMode openmode)
      {
            m_RegAppTable = (RegAppTable)m_Transaction.GetObject(
                m_Database.RegAppTableId,
                openmode,
                false);
            return m_RegAppTable;
      }
      public RegAppTable OpenRegAppTable()
      {
            return OpenRegAppTable(OpenMode.ForWrite);
      }
      public ObjectId RegApp(string name)
      {
            ObjectId id = GetIdFromSymbolTable(m_RegAppTable, name);
            if (id == ObjectId.Null)
            {
                RegAppTableRecord regapp = new RegAppTableRecord();
                regapp.Name = name;
                id = m_RegAppTable.Add(regapp);
                m_Transaction.AddNewlyCreatedDBObject(regapp, true);
            }
            return id;
      }
      #endregion
      //线型表
      #region LinetypeTable
      public LinetypeTable OpenLinetypeTable(OpenMode openmode)
      {
            m_LinetypeTable = (LinetypeTable)m_Transaction.GetObject(
                m_Database.LinetypeTableId,
                openmode,
                false);
            return m_LinetypeTable;
      }
      public LinetypeTable OpenLinetypeTable()
      {
            return OpenLinetypeTable(OpenMode.ForWrite);
      }
      public SelectionSet SelectByLineWeight(LineWeight lineWeight)
      {
            List<TypedValue> filter = new List<TypedValue>();
            filter.Add(new TypedValue(370, lineWeight));
            OpenLayerTable(OpenMode.ForRead);
            List<string> lays = new List<string>();
            foreach (ObjectId id in LayerTable)
            {
                LayerTableRecord ltr = (LayerTableRecord)GetObject(id, OpenMode.ForRead);
                if (ltr.LineWeight == lineWeight)
                {
                  lays.Add(ltr.Name);
                }
            }
            if (lays.Count > 0)
            {
                string s = string.Join(",", lays.ToArray());
                filter.Insert(0, new TypedValue(-4, "<or"));
                filter.Add(new TypedValue(-4, "<and"));
                filter.Add(new TypedValue(8, s));
                filter.Add(new TypedValue(370, LineWeight.ByLayer));
                filter.Add(new TypedValue(-4, "and>"));
                filter.Add(new TypedValue(-4, "or>"));
            }
            PromptSelectionResult res = CadHelper.Editor.SelectAll(new SelectionFilter(filter.ToArray()));
            return res.Value;
      }
      #endregion
      //用户坐标系
      #region UcsTable
      public UcsTable OpenUcsTable(OpenMode openmode)
      {
            m_UcsTable = (UcsTable)m_Transaction.GetObject(
                m_Database.UcsTableId,
                openmode,
                false);
            return m_UcsTable;
      }
      public UcsTable OpenUcsTable()
      {
            return OpenUcsTable(OpenMode.ForWrite);
      }
      #endregion
      //视图
      #region ViewTable
      public ViewTable OpenViewTable(OpenMode openmode)
      {
            m_ViewTable = (ViewTable)m_Transaction.GetObject(
                m_Database.ViewTableId,
                openmode,
                false);
            return m_ViewTable;
      }
      public ViewTable OpenViewTable()
      {
            return OpenViewTable(OpenMode.ForWrite);
      }
      #endregion
      //视口
      #region ViewportTable
      public ViewportTable OpenViewportTable(OpenMode openmode)
      {
            m_ViewportTable = (ViewportTable)m_Transaction.GetObject(
                m_Database.ViewportTableId,
                openmode,
                false);
            return m_ViewportTable;
      }
      public ViewportTable OpenViewportTable()
      {
            return OpenViewportTable(OpenMode.ForWrite);
      }
      #endregion
      //调整实体显示
      #region DrawOrderTable
      public DrawOrderTable OpenDrawOrderTable(OpenMode openmode)
      {
            m_DrawOrderTable = (DrawOrderTable)m_Transaction.GetObject(
                m_BlockTableRecord.DrawOrderTableId,
                openmode,
                false);
            return m_DrawOrderTable;
      }
      public DrawOrderTable OpenDrawOrderTable()
      {
            return OpenDrawOrderTable(OpenMode.ForWrite);
      }
      #endregion
      //编组字典
      #region GroupDictionary
      public DBDictionary OpenGroupDictionary(OpenMode openmode)
      {
            m_GroupDictionary = (DBDictionary)m_Transaction.GetObject(
                m_Database.GroupDictionaryId,
                openmode,
                false);
            return m_GroupDictionary;
      }
      public DBDictionary OpenGroupDictionary()
      {
            return OpenGroupDictionary(OpenMode.ForWrite);
      }
      public ObjectId AddGroup(string name, ObjectIdCollection ids)
      {
            if (m_GroupDictionary.Contains(name))
            {
                return ObjectId.Null;
            }
            else
            {
                m_GroupDictionary.UpgradeOpen();
                Group g = new Group();
                g.Append(ids);
                m_GroupDictionary.SetAt(name, g);
                m_Transaction.AddNewlyCreatedDBObject(g, true);
                return g.ObjectId;
            }
      }
      public List<Group> GetGroups(Entity ent)
      {
            List<Group> gs = new List<Group>();
            foreach (DBDictionaryEntry obj in m_GroupDictionary)
            {
                Group g =
                  (Group)m_Transaction.GetObject(
                  obj.Value,
                  OpenMode.ForRead,
                  false);
                if (g.Has(ent))
                  gs.Add(g);
            }
            return gs;
      }
      #endregion
      //在当前块表记录中加入实体
      #region Add Entity
      public ObjectId AddEntity(Entity entity)
      {
            ObjectId id = m_BlockTableRecord.AppendEntity(entity);
            m_Transaction.AddNewlyCreatedDBObject(entity, true);
            return id;
      }
      public ObjectId[] AddEntity(DBObjectCollection objs)
      {
            ObjectId[] ids = new ObjectId;
            for (int i = 0; i < objs.Count; i++)
            {
                ids = this.AddEntity((Entity)objs);
            }
            return ids;
      }
      public ObjectId[] AddEntity(DBObject[] objs)
      {
            ObjectId[] ids = new ObjectId;
            for (int i = 0; i < objs.Length; i++)
            {
                ids = this.AddEntity((Entity)objs);
            }
            return ids;
      }
      public ObjectId[] AddEntity(List<DBObject> objs)
      {
            ObjectId[] ids = new ObjectId;
            for (int i = 0; i < objs.Count; i++)
            {
                ids = this.AddEntity((Entity)objs);
            }
            return ids;
      }
      public ObjectId[] AddEntity(List<Entity> objs)
      {
            ObjectId[] ids = new ObjectId;
            for (int i = 0; i < objs.Count; i++)
            {
                ids = this.AddEntity(objs);
            }
            return ids;
      }
      #endregion
      //删除实体
      #region Remove Entity
      public bool Remove(ObjectId id)
      {
            try
            {
                DBObject obj = m_Transaction.GetObject(id, OpenMode.ForWrite);
                obj.Erase(true);
                return true;
            }
            catch
            { }
            return false;
      }
      public bool Remove(ObjectIdCollection ids)
      {
            try
            {
                foreach (ObjectId id in ids)
                {
                  DBObject obj;
                  obj = m_Transaction.GetObject(id, OpenMode.ForWrite);
                  obj.Erase(true);
                }
                return true;
            }
            catch
            { }
            return false;
      }
      public bool Remove(ObjectId[] ids)
      {
            try
            {
                foreach (ObjectId id in ids)
                {
                  DBObject obj;
                  obj = m_Transaction.GetObject(id, OpenMode.ForWrite);
                  obj.Erase(true);
                }
                return true;
            }
            catch
            { }
            return false;
      }
      public void Clear()
      {
            foreach (ObjectId id in m_BlockTableRecord)
            {
                DBObject obj = GetObject(id, OpenMode.ForWrite);
                obj.Erase();
            }
      }
      #endregion
      //块操作相关
      #region Block
      public ObjectId AddBlock(string name)
      {
            ObjectId id = GetIdFromSymbolTable(m_BlockTable, name);
            if (id == ObjectId.Null)
            {
                m_BlockTable.UpgradeOpen();
                BlockTableRecord btr = new BlockTableRecord();
                btr.Name = name;
                id = m_BlockTable.Add(btr);
                m_Transaction.AddNewlyCreatedDBObject(btr, true);
            }
            return id;
      }

      public Dictionary<AttributeDefinition, AttributeReference> AppendAttribToBlock(ObjectId blkrefid, List<string> atts)
      {
            BlockReference blkref = (BlockReference)m_Transaction.GetObject(blkrefid, OpenMode.ForWrite);
            return AppendAttribToBlock(blkref, atts);
      }
      public Dictionary<AttributeDefinition, AttributeReference> AppendAttribToBlock(BlockReference blkref, List<string> atts)
      {
            BlockTableRecord blkdef = (BlockTableRecord)m_Transaction.GetObject(blkref.BlockTableRecord, OpenMode.ForRead);
            int i = 0;
            if (blkdef.HasAttributeDefinitions)
            {
                Dictionary<AttributeDefinition, AttributeReference> attribs = new Dictionary<AttributeDefinition, AttributeReference>();
                foreach (ObjectId id in blkdef)
                {
                  DBObject ent = GetObject(id, OpenMode.ForRead);
                  if (ent is AttributeDefinition)
                  {
                        AttributeDefinition attdef = (AttributeDefinition)ent;
                        AttributeReference attref = new AttributeReference();
                        attref.SetAttributeFromBlock(attdef, blkref.BlockTransform);
                        if (i < atts.Count)
                            attref.TextString = atts;
                        else
                            attref.TextString = attdef.TextString;
                        i++;
                        blkref.AttributeCollection.AppendAttribute(attref);
                        m_Transaction.AddNewlyCreatedDBObject(attref, true);
                        attribs.Add(attdef, attref);
                  }
                }
                return attribs;
            }
            return null;
      }

      public Dictionary<AttributeDefinition, AttributeReference> AppendAttribToBlock(ObjectId blkrefid, List<AttributeDefinition> atts)
      {
            BlockReference blkref = (BlockReference)m_Transaction.GetObject(blkrefid, OpenMode.ForWrite);
            return AppendAttribToBlock(blkref, atts);
      }
      public Dictionary<AttributeDefinition, AttributeReference> AppendAttribToBlock(BlockReference blkref, List<AttributeDefinition> atts)
      {
            Dictionary<AttributeDefinition, AttributeReference> attribs = new Dictionary<AttributeDefinition, AttributeReference>();
            for (int i = 0; i < atts.Count; i++)
            {
                AttributeDefinition attdef = atts;
                AttributeReference attref = new AttributeReference();
                attref.SetAttributeFromBlock(attdef, blkref.BlockTransform);
                //attref.TransformBy(blkref.BlockTransform);
                attref.TextString = attdef.TextString;
                blkref.AttributeCollection.AppendAttribute(attref);
                m_Transaction.AddNewlyCreatedDBObject(attref, true);
            }
            return attribs;
      }
      public ObjectId InsertBlock(ObjectId blkdefid, List<string> atts)
      {
            BlockReference blkref = new BlockReference(Point3d.Origin, blkdefid);
            ObjectId id = AddEntity(blkref);
            BlockRefJig jig = new BlockRefJig(blkref, AppendAttribToBlock(blkref, atts));
            jig.SetPromptCounter(0);
            PromptResult res = CadHelper.Editor.Drag(jig);
            if (res.Status == PromptStatus.OK)
            {
                jig.SetPromptCounter(1);
                res = CadHelper.Editor.Drag(jig);
                if (res.Status == PromptStatus.OK)
                {
                  return id;
                }
            }
            blkref.Erase();
            return ObjectId.Null;
      }

      public ObjectId InsertBlock(string name, List<string> attribs)
      {
            return InsertBlock(m_BlockTable, attribs);
      }
      public bool GetBlockDefFromFile(string filename, string blkdefname, bool over)
      {
            try
            {
                bool has = m_BlockTable.Has(blkdefname);
                if ((has && over) || !has)
                {
                  using (DBTransaction t = new DBTransaction(filename))
                  {
                        ObjectId id = t.BlockTable;
                        BlockTableRecord btr =
                            (BlockTableRecord)t.GetObject(id, OpenMode.ForRead);
                        if (!btr.IsAnonymous && !btr.IsLayout)
                        {
                            ObjectIdCollection ids = new ObjectIdCollection();
                            ids.Add(t.BlockTable);
                            t.Database.Wblock(
                              m_Database,
                              ids,
                              new Point3d(),
                              DuplicateRecordCloning.Replace
                              );
                        }
                  }
                }
                return true;
            }
            catch
            { }
            return false;
      }
      public bool GetBlockDefFromFile(string filename, bool over)
      {
            try
            {
                FileInfo fi = new FileInfo(filename);
                string blkdefname = fi.Name;
                if (blkdefname.Contains("."))
                {
                  blkdefname = blkdefname.Substring(0, blkdefname.LastIndexOf('.'));
                }
                bool has = m_BlockTable.Has(blkdefname);
                if ((has && over) || !has)
                {
                  Database db = new Database();
                  db.ReadDwgFile(filename, FileShare.Read, true, null);
                  m_Database.Insert(BlockTableRecord.ModelSpace, blkdefname, db, false);
                }
                return true;
            }
            catch
            { }
            return false;
      }
      #endregion
      //字典
      #region XRecord
      public DBDictionary GetSubDict(DBDictionary dict, bool createsubdict, params string[] dictnames)
      {
            if (createsubdict)
            {
                dict.UpgradeOpen();
                dict.TreatElementsAsHard = true;
            }
            for (int i = 0; i < dictnames.Length; i++)
            {
                string name = dictnames;
                if (dict.Contains(name))
                {
                  dict =
                        (DBDictionary)m_Transaction.GetObject(
                            dict.GetAt(name),
                            OpenMode.ForRead,
                            false);
                }
                else
                {
                  if (createsubdict)
                  {
                        dict.UpgradeOpen();
                        DBDictionary subdict = new DBDictionary();
                        dict.SetAt(name, subdict);
                        m_Transaction.AddNewlyCreatedDBObject(subdict, true);
                        dict = subdict;
                        dict.TreatElementsAsHard = true;
                  }
                  else
                  {
                        return null;
                  }
                }
            }
            return dict;
      }
      public DBDictionary GetSubDict(ObjectId dictid, bool createsubdict, params string[] dictnames)
      {
            DBDictionary dict =
                (DBDictionary)m_Transaction.GetObject(
                  dictid,
                  OpenMode.ForRead,
                  false);
            return GetSubDict(dict, createsubdict, dictnames);
      }
      public bool SetXRecord(DBDictionary dict, string key, ResultBuffer rb)
      {
            Xrecord rec;
            if (dict.Contains(key))
            {
                rec =
                  (Xrecord)m_Transaction.GetObject(
                        dict.GetAt(key),
                        OpenMode.ForWrite,
                        false);
            }
            else
            {
                dict.UpgradeOpen();
                rec = new Xrecord();
                dict.SetAt(key, rec);
                m_Transaction.AddNewlyCreatedDBObject(rec, true);
            }
            rec.Data = rb;
            return true;
      }

      public bool SetXRecord(ResultBuffer rb, DBObject obj,string key, params string[] dictnames)
      {
            ObjectId id = obj.ExtensionDictionary;
            if (id == ObjectId.Null)
            {
                obj.CreateExtensionDictionary();
                id = obj.ExtensionDictionary;
            }
            DBDictionary dict = GetSubDict(id, true, dictnames);
            return SetXRecord(dict, key, rb);
      }
      public bool SetXRecord(ResultBuffer rb, string key, params string[] dictnames)
      {
            DBDictionary dict = GetSubDict(m_Database.NamedObjectsDictionaryId, true, dictnames);
            return SetXRecord(dict, key, rb);
      }
      public ResultBuffer GetXRecord(DBDictionary dict, string key)
      {
            if (dict != null)
            {
                if (dict.Contains(key))
                {
                  Xrecord rec =
                        (Xrecord)m_Transaction.GetObject(
                            dict.GetAt(key),
                            OpenMode.ForRead);
                  return rec.Data;
                }
            }
            return null;
      }
      public ResultBuffer GetXRecord(DBObject obj, string key, params string[] dictnames)
      {
            ObjectId id = obj.ExtensionDictionary;
            DBDictionary dict = GetSubDict(id, false, dictnames);
            return GetXRecord(dict, key);
      }
      public ResultBuffer GetXRecord(string key, params string[] dictnames)
      {
            DBDictionary dict = GetSubDict(m_Database.NamedObjectsDictionaryId, false, dictnames);
            return GetXRecord(dict, key);
      }
      #endregion
    }
}

雪山飞狐_lzh 发表于 2009-6-4 12:46:00

BlockRefJig.cs
using System;
using System.Collections.Generic;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
namespace TlsCad
{
    public class BlockRefJig : EntityJig
    {
      Point3d m_Position,m_BasePoint;
      double m_Angle;
      int m_PromptCounter;
      Matrix3d m_Ucs;
      Matrix3d m_Mat;
      //键值对集合(属性定义/引用)
      Dictionary<AttributeDefinition, AttributeReference> m_Attribs;
      public BlockRefJig(BlockReference blkref, Dictionary<AttributeDefinition, AttributeReference> attribs)
            : base(blkref)
      {
            m_Position = new Point3d();
            m_Angle = 0;
            m_Ucs = CadHelper.Editor.CurrentUserCoordinateSystem;
            m_Attribs = attribs;
            Update();
      }
      protected override SamplerStatus Sampler(JigPrompts prompts)
      {
            switch (m_PromptCounter)
            {
                case 0:
                  {
                        JigPromptPointOptions jigOpts = new JigPromptPointOptions("\n请输入基点:");
                        jigOpts.UserInputControls =
                            UserInputControls.Accept3dCoordinates |
                            UserInputControls.NoZeroResponseAccepted |
                            UserInputControls.NoNegativeResponseAccepted;
                        PromptPointResult res = prompts.AcquirePoint(jigOpts);
                        Point3d pnt = res.Value;
                        if (pnt != m_Position)
                        {
                            m_Position = pnt;
                            m_BasePoint = m_Position;
                        }
                        else
                            return SamplerStatus.NoChange;
                        if (res.Status == PromptStatus.Cancel)
                            return SamplerStatus.Cancel;
                        else
                            return SamplerStatus.OK;
                  }
                case 1:
                  {
                        JigPromptAngleOptions jigOpts = new JigPromptAngleOptions("\n请输入旋转角度:");
                        jigOpts.UserInputControls =
                            UserInputControls.Accept3dCoordinates |
                            UserInputControls.NoNegativeResponseAccepted |
                            UserInputControls.GovernedByUCSDetect |
                            UserInputControls.UseBasePointElevation;
                        jigOpts.Cursor = CursorType.RubberBand;
                        jigOpts.UseBasePoint = true;
                        jigOpts.BasePoint = m_BasePoint;
                        PromptDoubleResult res = prompts.AcquireAngle(jigOpts);
                        double angleTemp = res.Value;
                        if (angleTemp != m_Angle)
                            m_Angle = angleTemp;
                        else
                            return SamplerStatus.NoChange;
                        if (res.Status == PromptStatus.Cancel)
                            return SamplerStatus.Cancel;
                        else
                            return SamplerStatus.OK;
                  }
                default:
                  return SamplerStatus.NoChange;
            }
      }
      protected override bool Update()
      {
            try
            {
                /*Ucs下Jig的流程:
               * 1.先将图元在Wcs下摆正,即//xy平面
               * 2.将获取点坐标转换到Ucs下
               * 3.将图元在Ucs下摆正
               * 4.矩阵变换到Wcs
               */
                BlockReference blkref = (BlockReference)Entity;
                blkref.Normal = Vector3d.ZAxis;
                blkref.Position = CadHelper.Wcs2Ucs(m_Position);
                blkref.Rotation = m_Angle;
                blkref.TransformBy(m_Ucs);
                //将属性引用按块引用的Ocs矩阵变换
                if (m_Attribs != null)
                {
                  m_Mat = blkref.BlockTransform;
                  foreach (KeyValuePair<AttributeDefinition, AttributeReference> att in m_Attribs)
                  {
                        AttributeReference attref = att.Value;
                        string s = attref.TextString;
                        attref.SetAttributeFromBlock(att.Key, m_Mat);
                        attref.TextString = s;
                  }
                }
               
            }
            catch
            {
                return false;
            }
            return true;
      }
      public void SetPromptCounter(int i)
      {
            if (i == 0 || i == 1)
            {
                m_PromptCounter = i;
            }
      }
    }
}

martin416 发表于 2009-6-11 11:15:00

CadHelper 这个类是哪个?我怎么找不到?我用的是CAD2006

雪山飞狐_lzh 发表于 2009-6-11 11:31:00

<p>自定义类,可以直接下这里的类库</p><p><a href="http://bbs.mjtd.com/forum.php?mod=viewthread&tid=75701">http://bbs.mjtd.com/forum.php?mod=viewthread&tid=75701</a></p><p>TlsBasal 会逐渐开源:)</p><p>不支持2006,2005/6的.NetApi是有很多Bug的,做.Net开发应使用2007以上版本</p>

shghe 发表于 2009-11-2 09:14:00

function XML() {
   
}

游天居士 发表于 2009-12-28 23:35:00

好东东。

游天居士 发表于 2009-12-28 23:50:00

<p>飞狐兄太好了。这程序我又要研究几个月了</p>

游天居士 发表于 2009-12-29 00:09:00

飞狐兄。我学C#不久。脑子还是编程。还是以面向过程。我总是把所有功能写成方法。全做成静态的。看了你的代码。我就不知怎么办。做成非静态的有什么好处。方便在那里。BlockRefJig.cs 这个文件。应该怎么用这个JIG。能给出一个代码来不?先谢谢了。

雪山飞狐_lzh 发表于 2009-12-29 08:44:00

<p>BlockRefJig是为<strong>DBTransaction的</strong>InsertBlock函数服务的:),一楼有调用的代码</p><p><strong>DBTransaction本身</strong>是为简化托管代码而实现,</p><p>经常看到就算一个实体加入数据库也要用单个的事务,效率很低,哈哈</p><p>所以就有写该类的想法</p><p>至于静态,非静态,我的理解:类是数据及相关操作的集合</p><p></p><p></p>

游天居士 发表于 2009-12-29 18:08:00

<p>就是加一条直线。也要打开数据库。 另外我试 了。加1000条直线。用一次trans跟用1000次。差别感觉不出来。难道我的机子牛B。</p><p>飞狐兄的最后一句我上班要好好理解一下</p>
页: [1] 2
查看完整版本: [原创]DBTransaction类