Example #1
0
        public static ResultBuffer GetXrecord(ObjectId id, string key)
        {
            Database     db     = Tools.GetAcadDatabase();
            ResultBuffer result = new ResultBuffer();

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Xrecord xRec = new Xrecord();
                Entity  ent  = tr.GetObject(id, OpenMode.ForRead, false) as Entity;
                if (ent != null)
                {
                    try
                    {
                        DBDictionary xDict = (DBDictionary)tr.GetObject(ent.ExtensionDictionary, OpenMode.ForRead, false);
                        xRec = (Xrecord)tr.GetObject(xDict.GetAt(key), OpenMode.ForRead, false);
                        return(xRec.Data);
                    }
                    catch
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
        }
Example #2
0
        public static ResultBuffer GetXRecord(ObjectId id, string Key)
        {
            Document     doc    = AcadApp.DocumentManager.MdiActiveDocument;
            Database     db     = doc.Database;
            ResultBuffer result = new ResultBuffer();

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Xrecord  xRec = new Xrecord();
                DBObject ent  = tr.GetObject(id, OpenMode.ForRead, false);
                if (ent != null)
                {
                    try
                    {
                        DBDictionary xDict = (DBDictionary)tr.GetObject(ent.ExtensionDictionary, OpenMode.ForRead, false);
                        xRec = (Xrecord)tr.GetObject(xDict.GetAt(Key), OpenMode.ForRead, false);
                        return(xRec.Data);
                    }
                    catch
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
        }
Example #3
0
        private static Xrecord GetValueRecord(this AcTransaction trans, string valName)
        {
            valName = Ac.GetValidName(valName);

            var valDict = trans.GetGeo7Dict("Values");

            if (valDict.Contains(valName))
            {
                var valId = valDict.GetAt(valName);
                return(trans.GetObject <Xrecord>(valId));
            }
            else
            {
                var typedVal = new TypedValue((int)DxfCode.Text, "");
                using (var resBuff = new ResultBuffer(typedVal))
                {
                    var xRec = new Xrecord();
                    xRec.Data = resBuff;
                    valDict.SetAt(valName, xRec);
                    trans.AddNewlyCreatedDBObject(xRec, true);
                    return(xRec);
                }
            }



            //ResultBuffer resbuf = new ResultBuffer(  new TypedValue((int)DxfCode.Text, "HELLO"),
            //     new TypedValue((int)DxfCode.Int16, 256),
            //     new TypedValue((int)DxfCode.Real, 25.4));
        }
        public static string ReadWKT(Database db)
        {
            string text = "";
            string result;

            using (Transaction transaction = db.TransactionManager.StartTransaction())
            {
                DBDictionary dBDictionary = (DBDictionary)transaction.GetObject(db.NamedObjectsDictionaryId, 0, false);
                if (dBDictionary.Contains("ESRI_PRJ"))
                {
                    dBDictionary.GetAt("ESRI_PRJ");
                    Xrecord      xrecord = (Xrecord)transaction.GetObject(dBDictionary.GetAt("ESRI_PRJ"), 0);
                    ResultBuffer data    = xrecord.Data;
                    if (data != null)
                    {
                        TypedValue[] array = data.AsArray();
                        text = array[0].Value.ToString();
                    }
                }
                else
                {
                    text = "";
                }
                transaction.Commit();
                result = text;
            }
            return(result);
        }
Example #5
0
        /// <summary>
        /// 设置指定命名字典中的数据。
        /// </summary>
        /// <param name="name"></param>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="db"></param>
        public static void SetNODData(string name, string key, Xrecord data, Database db = null)
        {
            db = db ?? Application.DocumentManager.MdiActiveDocument.Database;

            using (var trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                var nod = trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead) as DBDictionary;
                if (!nod.Contains(name))
                {
                    using (var innerTrans = db.TransactionManager.StartOpenCloseTransaction())
                    {
                        var nodW = trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite) as DBDictionary;

                        var newDict = new DBDictionary();
                        nodW.SetAt(name, newDict);
                        innerTrans.AddNewlyCreatedDBObject(newDict, true);

                        innerTrans.Commit();
                    }
                }

                var dict = trans.GetObject(nod.GetAt(name), OpenMode.ForWrite) as DBDictionary;
                dict.SetAt(key, data);
                trans.AddNewlyCreatedDBObject(data, true);

                trans.Commit();
            }
        }
Example #6
0
 public static void Delete(ObjectId id, string key)
 {
     try {
         if (id.IsErased == false && id.IsEffectivelyErased == false)
         {
             using (World.Docu.LockDocument()) {
                 using (Database db = World.Docu.Database) {
                     using (Transaction tr = db.TransactionManager.StartTransaction()) {
                         using (DBDictionary dict = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite, false)) {
                             if (dict.Contains(key))
                             {
                                 ObjectId deleteId = dict.GetAt(key);
                                 Xrecord  xRec     = (Xrecord)tr.GetObject(dict.GetAt(key), OpenMode.ForWrite, false);
                                 xRec.Erase();
                                 dict.Remove(deleteId);
                             }
                         }
                         tr.Commit();
                     }
                 }
             }
         }
     }
     catch (System.Exception ex) {
         Err.Log(ex);
     }
 }
        public String[] GetData(ObjectId idD, Transaction tr, String XRecordName)
        {
            DBDictionary dict = idD.GetObject(OpenMode.ForWrite) as DBDictionary;

            try
            {
                ObjectId xRecordId = dict.GetAt(XRecordName);
                if (xRecordId.IsValid)
                {
                    Xrecord xRec = xRecordId.GetObject(OpenMode.ForRead) as Xrecord;
                    if (xRec.Data != null)
                    {
                        TypedValue[] data = xRec.Data.AsArray();
                        return(data.Select(x => x.Value.ToString()).ToArray());
                    }
                    else
                    {
                        return(new String[0]);
                    }
                }
                else
                {
                    return(new String[0]);
                }
            }
            catch (Exception)
            {
                return(new String[0]);
            }
        }
        internal bool CheckDrawingForCivil3D(Document doc)
        {
            using (Transaction trans = doc.TransactionManager.StartTransaction())
            {
                // Find the NOD in the database
                DBDictionary nod = (DBDictionary)trans.GetObject(doc.Database.NamedObjectsDictionaryId, OpenMode.ForRead);
                string       id  = this.GetType().FullName + "Civil3DRequired";

                if (nod.Contains(id))
                {
                    ObjectId objId   = nod.GetAt(id);
                    Xrecord  XRecord = (Xrecord)trans.GetObject(objId, OpenMode.ForRead);
                    foreach (TypedValue value in XRecord.Data)
                    {
                        if (value.TypeCode == (short)DxfCode.Bool)
                        {
                            bool castValue = Convert.ToInt32(value.Value) != 0;
                            if (castValue)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            return(false);
        }
        public void MarkCurrentDrawingAsCivil3D()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;

            using (Transaction trans = doc.TransactionManager.StartTransaction())
            {
                Transaction tr = doc.TransactionManager.TopTransaction;

                // Find the NOD in the database
                DBDictionary nod = (DBDictionary)tr.GetObject(doc.Database.NamedObjectsDictionaryId, OpenMode.ForWrite);

                // We use Xrecord class to store data in Dictionaries
                Xrecord      plotXRecord = new Xrecord();
                ResultBuffer rb          = new ResultBuffer();

                TypedValue tv = new TypedValue((int)DxfCode.Bool, true);
                rb.Add(tv);
                plotXRecord.Data = rb;

                // Create the entry in the Named Object Dictionary
                string id = this.GetType().FullName + "Civil3DRequired";
                nod.SetAt(id, plotXRecord);
                tr.AddNewlyCreatedDBObject(plotXRecord, true);
                trans.Commit();
            }
        }
Example #10
0
        /// <summary>
        /// Remueve un xRecord en el diccionario de extensión de una
        /// entidad.
        /// </summary>
        /// <param name="dictionaryName">El nombre del diccionario</param>
        /// <param name="dicId">El id del diccionario</param>
        public static void RemoveXRecord(ObjectId dicId, String XrecordName)
        {
            Document doc = AcadApp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                using (doc.LockDocument())
                {
                    try
                    {
                        DBDictionary oldD = (DBDictionary)dicId.GetObject(OpenMode.ForWrite);
                        Xrecord      x    = new Xrecord();
                        oldD.Remove(XrecordName);
                        tr.Commit();
                    }
                    catch (AcadExc exc)
                    {
                        ed.WriteMessage(exc.Message);
                        tr.Abort();
                    }
                    catch (System.Exception exc)
                    {
                        ed.WriteMessage(exc.Message);
                        tr.Abort();
                    }
                }
            }
        }
Example #11
0
        /// <summary>Добавление текстовых расширенных данных в именованный словарь</summary>
        /// <param name="dictionaryName">Словарь</param>
        /// <param name="value">Добавляемое значение</param>
        public static void SetStringXData(string dictionaryName, string value)
        {
            var doc = AcApp.DocumentManager.MdiActiveDocument;

            if (doc != null)
            {
                var db = doc.Database;
                try
                {
                    using (doc.LockDocument())
                    {
                        using (var tr = db.TransactionManager.StartTransaction())
                        {
                            var rec = new Xrecord
                            {
                                Data = new ResultBuffer(new TypedValue(Convert.ToInt32(DxfCode.Text), value))
                            };

                            var dict = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite, false);
                            dict.SetAt(dictionaryName, rec);
                            tr.AddNewlyCreatedDBObject(rec, true);
                            tr.Commit();
                        }
                    }
                }
                catch (Exception ex)
                {
                    ExceptionBox.Show(ex);
                }
            }
        }
Example #12
0
        /// <summary>
        /// Agrega un xrecord en un diccionario
        /// </summary>
        /// <param name="dictionaryName">El nombre del diccionario</param>
        /// <param name="dicId">El id del diccionario.</param>
        /// <returns>El object id del xrecord recien creado</returns>
        public static ObjectId AddXRecord(ObjectId dicId, String XrecordName)
        {
            Database db = AcadApp.DocumentManager.MdiActiveDocument.Database;
            ObjectId id = new ObjectId();

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    DBDictionary oldD = (DBDictionary)dicId.GetObject(OpenMode.ForWrite);
                    Xrecord      x    = new Xrecord();
                    oldD.SetAt(XrecordName, x);
                    tr.AddNewlyCreatedDBObject(x, true);
                    id = x.ObjectId;
                    tr.Commit();
                }
                catch (AcadExc exc)
                {
                    ed.WriteMessage(exc.Message);
                    tr.Abort();
                }
                catch (System.Exception exc)
                {
                    ed.WriteMessage(exc.Message);
                    tr.Abort();
                }
            }
            return(id);
        }
Example #13
0
        /// <summary>
        /// Agrega información a un Xrecord
        /// </summary>
        /// <param name="XrecId">El id del Xrecord.</param>
        /// <param name="data">La información que se guardara en el Xrecord</param>
        /// <returns>El object id del xrecord recien creado</returns>
        public static void AddData(ObjectId XrecId, params String[] data)
        {
            Database db = AcadApp.DocumentManager.MdiActiveDocument.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    Xrecord           oldX           = (Xrecord)XrecId.GetObject(OpenMode.ForWrite);
                    List <TypedValue> typedValueData = new List <TypedValue>();
                    for (int i = 0; i < data.Length; i++)
                    {
                        typedValueData.Add(new TypedValue((int)DxfCode.Text, data[i]));
                    }
                    oldX.Data = new ResultBuffer(typedValueData.ToArray());
                    tr.Commit();
                }
                catch (AcadExc exc)
                {
                    ed.WriteMessage(exc.Message);
                    tr.Abort();
                }
                catch (System.Exception exc)
                {
                    ed.WriteMessage(exc.Message);
                    tr.Abort();
                }
            }
        }
Example #14
0
        // Função para gravar os dados no Extension Dictionary do objeto dado.
        public void RecOnXDict(DBObject dbObj, string location, DxfCode dxfC, dynamic data, Transaction tr)
        {
            // Pega o Id do XDic do objeto.
            ObjectId extId = dbObj.ExtensionDictionary;

            // Se não existe um XDic, cria-o
            if (extId == ObjectId.Null)
            {
                dbObj.CreateExtensionDictionary();
                extId = dbObj.ExtensionDictionary;
            }

            // Pega o XDic a partir do seu Id.
            DBDictionary dbExt = (DBDictionary)tr.GetObject(extId, OpenMode.ForWrite);

            // Cria um XRecord, que guardará a informação
            Xrecord      xRec = new Xrecord();
            ResultBuffer rb   = new ResultBuffer();

            rb.Add(new TypedValue((int)dxfC, data));

            xRec.Data = rb;

            // Adiciona a informação no XDic do objeto.
            dbExt.SetAt(location, xRec);
            tr.AddNewlyCreatedDBObject(xRec, true);
        }
Example #15
0
        private static ObjectId getRec(string recName)
        {
            ObjectId idDict = getDict();

            if (idDict.IsNull)
            {
                return(ObjectId.Null);
            }
            ObjectId idRec = ObjectId.Null;

            using (var dic = idDict.Open(OpenMode.ForRead) as DBDictionary)
            {
                if (!dic.Contains(recName))
                {
                    using (var xRec = new Xrecord())
                    {
                        dic.UpgradeOpen();
                        idRec = dic.SetAt(recName, xRec);
                    }
                }
                else
                {
                    idRec = dic.GetAt(recName);
                }
            }
            return(idRec);
        }
Example #16
0
        /// <summary>
        /// Gets the data from an Xrecord.
        /// </summary>
        /// <param name="dictionaryName">Name of Named Objects Dictionary</param>
        /// <param name="xKey">Key of Xrecord</param>
        /// <returns>ResultBuffer with data or Null if nothing found.</returns>
        /// <exception cref="Wrappers.XRecordException"/>
        public ResultBuffer GetXrecord(string dictionaryName, string xKey)
        {
            ResultBuffer result = null;

            try
            {
                if (_document != null)
                {
                    _document.StartTransaction(tr =>
                    {
                        Transaction t = tr.Transaction;
                        using (DBDictionary nod = Dictionaries.GetNamedObjectsDictionary(dictionaryName))
                        {
                            if (nod != null && nod.Contains(xKey))
                            {
                                ObjectId oid = nod.GetAt(xKey);
                                using (Xrecord xrec = t.GetObject <Xrecord>(oid, OpenMode.ForRead))
                                {
                                    result = xrec.Data;
                                }
                            }
                        }
                    });
                }
            }
            catch (XRecordHandlerException) { throw; }
            catch (Exception ex)
            {
                string err_message = string.Format("Unexpected error occured while retrieving xRecord '{0}' from Named Objects Dictionary '{1}'.", xKey, dictionaryName);
                throw new XRecordHandlerException(dictionaryName, xKey, err_message, ex, ErrorCode.XrecordNotFound);
            }

            return(result);
        }
Example #17
0
        /// <summary>
        /// Gets value from 'Geo7.Dictionary.Values' dictionary. If there is no value for 'name' empty string ("") is returned.
        /// </summary>
        public static string GetValue(this AcTransaction trans, string valName)
        {
            Xrecord xRec = trans.GetValueRecord(valName);
            var     val  = xRec.Data.AsArray()[0];

            return(val.Value.ToString());
        }
Example #18
0
        public void ListXrecord()
        {
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //下面的操作用来选择显示扩展记录的对象
                PromptEntityOptions opt = new PromptEntityOptions("请选择要显示扩展记录的对象");
                PromptEntityResult  res = ed.GetEntity(opt);
                if (res.Status != PromptStatus.OK)
                {
                    return;
                }
                Entity ent = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead);
                //打开所选择对象的扩展字典
                DBDictionary entXrecord = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead);
                //在扩展字典中搜索关键字为MyXrecord的扩展记录对象,如果找到则返回它的ObjectId
                ObjectId xrecordId = entXrecord.GetAt("MyXrecord");
                //打开找到的扩展记录对象
                Xrecord xrecord = (Xrecord)trans.GetObject(xrecordId, OpenMode.ForRead);
                //获取扩展记录中包含的数据列表并循环遍历显示它们
                ResultBuffer rb = xrecord.Data;
                foreach (TypedValue value in rb)
                {
                    ed.WriteMessage(string.Format("\nTypeCode={0},Value={1}", value.TypeCode, value.Value));
                }
                trans.Commit();
            }
        }
        /// <summary>
        /// 拡張ディクショナリの 1071 の値に 1 足す
        /// </summary>
        /// <param name="transaction"></param>
        /// <param name="entity"></param>
        private static void ChengeExtensionDictionaryData(Transaction transaction, DBObject entity)
        {
            var extentionId = entity.ExtensionDictionary;

            if (extentionId == ObjectId.Null)
            {
                return;
            }

            var extentionDict = (DBDictionary)transaction.GetObject(extentionId, OpenMode.ForWrite);
            var xRecId        = extentionDict.GetAt("TEST");
            var xRec          = (Xrecord)transaction.GetObject(xRecId, OpenMode.ForRead);
            var resultBuffer  = xRec.Data;
            var data          = resultBuffer.AsArray();

            for (int i = 0; i < data.Length; i++)
            {
                var value = data[i];
                if (value.TypeCode == 1071)
                {
                    data[i] = new TypedValue(1071, (int)value.Value + 1);
                }
            }

            extentionDict.Remove(xRecId);
            var newXrec = new Xrecord {
                Data = new ResultBuffer(data)
            };

            extentionDict.SetAt("TEST", newXrec);
            transaction.AddNewlyCreatedDBObject(newXrec, true);
        }
Example #20
0
 /// <summary> 将<seealso cref="Xrecord"/>对象中的数据刷新到内存中的静态类中 </summary>
 /// <param name="xrec">其值可以为 null,表示集合中一个数据都没有 </param>
 public static void FromXrecord_SortedStations(Xrecord xrec)
 {
     AllSortedStations = new double[0];
     if (xrec != null)
     {
         //
         var buffs = xrec.Data.AsArray();
         if (buffs == null || buffs.Length == 0)
         {
             return;
         }
         //
         try
         {
             var itemsCount = (int)buffs[0].Value;
             AllSortedStations = new double[itemsCount];
             const int baseIndex = 1;
             for (int i = 0; i < itemsCount; i++)
             {
                 var s = (double)buffs[i + baseIndex].Value;
                 //
                 AllSortedStations[i] = s;
                 // AllSortedStations.Add(s);
             }
         }
         catch (Exception ex)
         {
             Debug.Print("提取整条道路中所有的横断面(桩号从小到大排列)信息出错" + ex.AppendMessage());
             //MessageBox.Show($"刷新选项数据“{fields[index].Name}”出错。\r\n{ex.StackTrace}");
         }
     }
 }
        public static ResultBuffer getXrecord(ObjectId extDictObjectId, string key)
        {
            Document acDoc    = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database acCurrDb = acDoc.Database;
            Editor   acEditor = acDoc.Editor;

            using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction())
            {
                try
                {
                    DBDictionary extDict = acTrans.GetObject(extDictObjectId, OpenMode.ForWrite) as DBDictionary;
                    ObjectId     xRecId  = extDict.GetAt(key);
                    Xrecord      xrec    = acTrans.GetObject(xRecId, OpenMode.ForRead) as Xrecord;
                    acTrans.Commit();
                    return(xrec.Data);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception acException)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog
                        ("The following exception was caught: \n" + acException.Message
                        + "\nError retrieving Xrecord data!\n");
                    acTrans.Commit();
                    return(null);
                }
            }
        }
Example #22
0
        public void GetTotalNumbers(List <Polyline> list)
        {
            Document document = Application.DocumentManager.MdiActiveDocument;
            Database database = document.Database;

            for (int i = 0; i < list.Count; i++)
            {
                int numfloor = 0;
                int numbars  = 0;
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    DBObject     databaseObject = transaction.GetObject(list[i].ObjectId, OpenMode.ForRead);
                    ObjectId     extId          = databaseObject.ExtensionDictionary;
                    DBDictionary dbExt          = (DBDictionary)transaction.GetObject(extId, OpenMode.ForRead);

                    if (dbExt.Contains("CustomProp"))
                    {
                        ObjectId recID    = dbExt.GetAt("CustomProp");
                        Xrecord  readBack = (Xrecord)transaction.GetObject(recID, OpenMode.ForRead);
                        numfloor = int.Parse(readBack.Data.AsArray()[0].Value.ToString());
                        numbars  = int.Parse(readBack.Data.AsArray()[1].Value.ToString());
                        Properties.Settings.Default.CounterLength += list[i].Length * numfloor;
                        Properties.Settings.Default.CounterPils   += numfloor * numbars;
                    }
                    transaction.Commit();
                }
            }
        }
Example #23
0
 //this could be altered to use the typedvalue and retrieve the type from reversing the dxfcode lookup, but we would still need a generic return for the calling function
 public static T Get <T>(string key)
 {
     try {
         if (World.Docu != null)
         {
             if (World.Docu.IsActive == true && World.Docu.IsDisposed == false)
             {
                 using (World.Docu.LockDocument()) {
                     using (Database db = World.Docu.Database) {
                         using (Transaction tr = db.TransactionManager.StartTransaction()) {
                             using (DBDictionary dict = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead, false)) {
                                 if (dict.Contains(key))
                                 {
                                     Xrecord      xRec   = (Xrecord)tr.GetObject(dict.GetAt(key), OpenMode.ForRead);
                                     ResultBuffer resBuf = xRec.Data;
                                     if (resBuf == null)
                                     {
                                         return(default(T));
                                     }
                                     TypedValue[] typ = resBuf.AsArray();
                                     return((T)Convert.ChangeType(typ[0].Value, typeof(T)));
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (System.Exception ex) {
         Err.Log(ex);
     }
     return(default(T));
 }
Example #24
0
        public static ResultBuffer ReadX(ObjectId objId, string xRecordSearchKey)
        {
            ResultBuffer resBuf = new ResultBuffer();

            Document     doc            = Application.DocumentManager.MdiActiveDocument;
            Database     db             = doc.Database;
            DocumentLock m_DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBObject obj = objId.GetObject(OpenMode.ForRead); //以读的方式打开对象

                ObjectId dictId = obj.ExtensionDictionary;        //获取对象的扩展字典的id

                if (!dictId.IsNull)
                {
                    DBDictionary dict = dictId.GetObject(OpenMode.ForRead) as DBDictionary;//获取对象的扩展字典
                    if (!dict.Contains(xRecordSearchKey))
                    {
                        tr.Commit();
                        m_DocumentLock.Dispose();
                        return(null);//如果扩展字典中没有包含指定关键 字的扩展记录,则返回null;
                    }
                    //先要获取对象的扩展字典或图形中的有名对象字典,然后才能在字典中获取要查询的扩展记录
                    ObjectId xrecordId = dict.GetAt(xRecordSearchKey);                     //获取扩展记录对象的id
                    Xrecord  xrecord   = xrecordId.GetObject(OpenMode.ForRead) as Xrecord; //根据id获取扩展记录对象
                    resBuf = xrecord.Data;
                }
                tr.Commit();
            }
            m_DocumentLock.Dispose();
            return(resBuf);
        }
Example #25
0
        public static void AddSpeckleStream(string id, string stream)
        {
            Document Doc = Application.DocumentManager.MdiActiveDocument;

            using (DocumentLock l = Doc.LockDocument())
            {
                using (Transaction tr = Doc.Database.TransactionManager.StartTransaction())
                {
                    var          NOD = (DBDictionary)tr.GetObject(Doc.Database.NamedObjectsDictionaryId, OpenMode.ForRead);
                    DBDictionary speckleDict;
                    if (NOD.Contains(SpeckleExtensionDictionary))
                    {
                        speckleDict = (DBDictionary)tr.GetObject(NOD.GetAt(SpeckleExtensionDictionary), OpenMode.ForWrite);
                    }
                    else
                    {
                        speckleDict = new DBDictionary();
                        NOD.UpgradeOpen();
                        NOD.SetAt(SpeckleExtensionDictionary, speckleDict);
                        tr.AddNewlyCreatedDBObject(speckleDict, true);
                    }
                    var xRec = new Xrecord();
                    xRec.Data = new ResultBuffer(new TypedValue(Convert.ToInt32(DxfCode.Text), stream));
                    speckleDict.SetAt(id, xRec);
                    tr.AddNewlyCreatedDBObject(xRec, true);
                    tr.Commit();
                }
            }
        }
Example #26
0
        public void HighlightSoftPointer()
        {
            using (Transaction tr = AcadFuncs.GetActiveDb().TransactionManager.StartTransaction())
            {
                DBDictionary dict = GetDict(tr);
                if (null == dict)
                {
                    return;
                }

                Xrecord xrec = tr.GetObject(dict.GetAt(XREC_NAME), OpenMode.ForRead) as Xrecord;
                if (null == xrec)
                {
                    return;
                }

                ObjectId obj_id = (ObjectId)xrec.Data.AsArray()[0].Value;

                Entity ent = tr.GetObject(obj_id, OpenMode.ForRead) as Entity;
                if (null == ent)
                {
                    return;
                }

                if (ent is Line)
                {
                    Line line = ent as Line;
                    line.UpgradeOpen();
                    line.ColorIndex = 1;
                }

                tr.Commit();
            }
        }
Example #27
0
        /// <summary>
        /// 添加扩展记录
        /// </summary>
        /// <param name="id">对象的Id</param>
        /// <param name="searchKey">扩展记录名称</param>
        /// <param name="values">扩展记录的内容</param>
        /// <returns>返回添加的扩展记录的Id</returns>
        public static ObjectId AddXrecord(this ObjectId id, string searchKey, TypedValueList values)
        {
            DBObject obj = id.GetObject(OpenMode.ForRead);//打开对象

            // 判断对象是否已经拥有扩展字典,若无扩展字典,则
            if (obj.ExtensionDictionary.IsNull)
            {
                obj.UpgradeOpen();               // 切换对象为写的状态
                obj.CreateExtensionDictionary(); // 为对象创建扩展字典
                obj.DowngradeOpen();             // 为了安全,将对象切换成读的状态
            }
            // 打开对象的扩展字典
            DBDictionary dict = (DBDictionary)obj.ExtensionDictionary.GetObject(OpenMode.ForRead);

            // 如果扩展字典中已包含指定的扩展记录对象,则返回
            if (dict.Contains(searchKey))
            {
                return(ObjectId.Null);
            }
            Xrecord xrec = new Xrecord(); // 为对象新建一个扩展记录

            xrec.Data = values;           // 指定扩展记录的内容
            dict.UpgradeOpen();           // 将扩展字典切换成写的状态
            //在扩展字典中加入新建的扩展记录,并指定它的搜索关键字
            ObjectId idXrec = dict.SetAt(searchKey, xrec);

            id.Database.TransactionManager.AddNewlyCreatedDBObject(xrec, true);
            dict.DowngradeOpen(); // 为了安全,将扩展字典切换成读的状态
            return(idXrec);       // 返回添加的扩展记录的的Id
        }
Example #28
0
        /// <summary>
        /// Записать связь в объект objId с объектом writedId
        /// </summary>
        /// <param name="objId">Объект</param>
        /// <param name="linkIds">Связываемые объекты</param>
        /// <param name="code">Тип связи</param>
        /// /// <param name="replace">Перезаписать существующий словарь LinkCode - true, или добавить если уже существует - false</param>
        public static void WriteLinks(this ObjectId objId, List <ObjectId> linkIds, LinkCode code, bool replace = true)
        {
            var dictId     = GetExtDict(objId);
            var existLinks = ReadLinks(objId, code);
            var addLinkIds = linkIds?.Where(w => !w.IsNull).Except(existLinks).ToList() ?? new List <ObjectId>();
            var dxfCode    = GetDxfCode(code);

            using (var dict = dictId.Open(OpenMode.ForWrite) as DBDictionary)
            {
                var entryName = GetLinkRecordName(code);
                if (dict.Contains(entryName) && replace)
                {
                    dict.Remove(entryName);
                }

                if (!addLinkIds.Any())
                {
                    return;
                }
                using (var xrec = new Xrecord())
                    using (var resBuff = new ResultBuffer())
                    {
                        foreach (var addLinkId in addLinkIds)
                        {
                            resBuff.Add(new TypedValue((int)dxfCode, addLinkId));
                        }

                        xrec.Data = resBuff;
                        dict.SetAt(entryName, xrec);
                    }
            }
        }
        public static string AssignWKT(Document doc, string wktString)
        {
            if (string.IsNullOrEmpty(wktString))
            {
                return(wktString);
            }
            if (wktString == "<Undefined>")
            {
                return(wktString);
            }
            if (MSCPrj.IsWKID(wktString))
            {
                return("");
            }
            string result;

            try
            {
                using (doc.LockDocument((DocumentLockMode)20, null, null, false))
                {
                    using (Transaction transaction = doc.Database.TransactionManager.StartTransaction())
                    {
                        Database   database   = doc.Database;
                        Xrecord    xrecord    = new Xrecord();
                        TypedValue typedValue = new TypedValue(1, wktString);
                        xrecord.Data = (new ResultBuffer(new TypedValue[]
                        {
                            typedValue
                        }));
                        DBDictionary dBDictionary = (DBDictionary)transaction.GetObject(database.NamedObjectsDictionaryId, (OpenMode)1, false);
                        ObjectId     acadId       = dBDictionary.SetAt("ESRI_PRJ", xrecord);
                        xrecord.DisableUndoRecording(true);
                        transaction.AddNewlyCreatedDBObject(xrecord, true);
                        transaction.Commit();
                        AfaDocData.ActiveDocData.DocPRJ.WKT    = wktString;
                        AfaDocData.ActiveDocData.DocPRJ.AcadId = acadId;
                        foreach (MSCMapService current in AfaDocData.ActiveDocData.DocDataset.MapServices.Values)
                        {
                            current.RefreshConnectedService();
                        }
                        foreach (MSCImageService current2 in AfaDocData.ActiveDocData.DocDataset.ImageServices.Values)
                        {
                            current2.RefreshConnectedService();
                        }
                        result = wktString;
                    }
                }
            }
            catch (SystemException ex)
            {
                string arg_186_0 = ex.Message;
                result = "";
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex2)
            {
                string arg_199_0 = ex2.Message;
                result = "";
            }
            return(result);
        }
Example #30
0
        /// <summary>
        /// Retrieve or create an Entry with the given name into the Extension Dictionary of the passed-in object.
        /// </summary>
        /// <param name="id">The object hosting the Extension Dictionary</param>
        /// <param name="entryName">The name of the dictionary entry to get or set</param>
        /// <returns>The ObjectId of the diction entry, old or new</returns>
        public static ObjectId GetSetExtensionDictionaryEntry(ObjectId id, string entryName)
        {
            ObjectId ret = ObjectId.Null;

            using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
            {
                DBObject obj = (DBObject)tr.GetObject(id, OpenMode.ForRead);
                if (obj.ExtensionDictionary == ObjectId.Null)
                {
                    obj.UpgradeOpen();
                    obj.CreateExtensionDictionary();
                    obj.DowngradeOpen();
                }

                DBDictionary dict = (DBDictionary)tr.GetObject(obj.ExtensionDictionary, OpenMode.ForRead);
                if (!dict.Contains(entryName))
                {
                    Xrecord xRecord = new Xrecord();
                    dict.UpgradeOpen();
                    dict.SetAt(entryName, xRecord);
                    tr.AddNewlyCreatedDBObject(xRecord, true);

                    ret = xRecord.ObjectId;
                }
                else
                {
                    ret = dict.GetAt(entryName);
                }

                tr.Commit();
            }

            return(ret);
        }
Example #31
0
        public static ObjectId CreateDivision(String division, String manager)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //Define a corporate level dictionary
                DBDictionary acmeDict;
                //First, get the NOD...
                DBDictionary NOD = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead, false);
                try
                {
                    //if it	exists,	just get it
                    acmeDict = (DBDictionary)trans.GetObject(NOD.GetAt("ACME_DIVISION"), OpenMode.ForRead);
                }
                catch
                {
                    //Doesn//t exist, so create	one
                    NOD.UpgradeOpen();
                    acmeDict = new DBDictionary();
                    NOD.SetAt("ACME_DIVISION", acmeDict);
                    trans.AddNewlyCreatedDBObject(acmeDict, true);
                }

                //Now get the division we want from	acmeDict
                DBDictionary divDict;
                try
                {
                    divDict = (DBDictionary)trans.GetObject(acmeDict.GetAt(division), OpenMode.ForWrite);
                }
                catch
                {
                    acmeDict.UpgradeOpen();
                    divDict = new DBDictionary(); //Division	doesn//t exist,	create one
                    acmeDict.SetAt(division, divDict);
                    trans.AddNewlyCreatedDBObject(divDict, true);
                }

                //Now get the manager info from	the	division
                //We need to add the name of the division supervisor.  We//ll do this with another XRecord.
                Xrecord mgrXRec;
                try
                {
                    mgrXRec = (Xrecord)trans.GetObject(divDict.GetAt("Department	Manager"), OpenMode.ForWrite);
                }
                catch
                {
                    mgrXRec = new Xrecord();
                    mgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, manager));
                    divDict.SetAt("Department Manager", mgrXRec);
                    trans.AddNewlyCreatedDBObject(mgrXRec, true);
                }

                trans.Commit();

                //return the department	manager	XRecord
                return mgrXRec.ObjectId;
            }
        }
Example #32
0
        public void AddExtDict()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("����������չ�ʵ�\n");

            PromptEntityOptions entOps = new PromptEntityOptions("ѡ��Ҫ�����չ���ݵĿ�\n");
            PromptEntityResult entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("ѡ�����ʧ�ܣ��˳�");
                return;
            }
            Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                DBObject obj = trans.GetObject(entRes.ObjectId, OpenMode.ForWrite) as DBObject;
                BlockReference blkRef;
                if (obj is BlockReference)
                {
                    blkRef = obj as BlockReference;
                }
                else
                {
                    return;
                }

                // �����������չ�ʵ�
                blkRef.CreateExtensionDictionary();
                DBDictionary extensionDict = (DBDictionary)trans.GetObject(blkRef.ExtensionDictionary, OpenMode.ForWrite, false);

                // ͨ��Xrecord׼��������������
                Xrecord xRec = new Xrecord();
                xRec.Data = new ResultBuffer(
                  new TypedValue((int)DxfCode.Text, "����"),// ����
                  new TypedValue((int)DxfCode.Real, 1200.0),//нˮ
                  new TypedValue((int)DxfCode.Text, "������"));// ����
               // ����չ�ʵ��������չ��¼
                extensionDict.SetAt("EmployeeInfomation", xRec);
                trans.AddNewlyCreatedDBObject(xRec, true);

                trans.Commit();
            }
        }
Example #33
0
        public void CreateEmployee()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            using (Transaction trans = db.TransactionManager.StartTransaction())
                try
                {
                    BlockTable bt = (BlockTable)(trans.GetObject(db.BlockTableId, OpenMode.ForWrite));
                    BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    //Create the block reference...use the return from CreateEmployeeDefinition directly!
                    BlockReference br = new BlockReference(new Point3d(10, 10, 0), CreateEmployeeDefinition());
                    btr.AppendEntity(br); //Add the reference to ModelSpace
                    trans.AddNewlyCreatedDBObject(br, true); //Let the transaction know about it

                    //Create the custom per-employee data
                    Xrecord xRec = new Xrecord();
                    //We want to add 'Name', 'Salary' and 'Division' information.  Here is how:
                    xRec.Data = new ResultBuffer(
                        new TypedValue((int)DxfCode.Text, "Earnest Shackleton"),
                        new TypedValue((int)DxfCode.Real, 72000),
                        new TypedValue((int)DxfCode.Text, "Sales"));

                    //Next, we need to add this data to the 'Extension Dictionary' of the employee.
                    br.CreateExtensionDictionary();
                    DBDictionary brExtDict = (DBDictionary)trans.GetObject(br.ExtensionDictionary, OpenMode.ForWrite, false);
                    brExtDict.SetAt("EmployeeData", xRec); //Set our XRecord in the dictionary at 'EmployeeData'.
                    trans.AddNewlyCreatedDBObject(xRec, true);

                    trans.Commit();
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage("Error Creating Employee Block: " + ex.Message);
                }
            // No 'finally' block is required to clean up the transaction
            // since it was declared inside a 'using' statement.
        }
Example #34
0
        //This function creates a new BlockReference to the "EmployeeBlock" object,
        //and adds it to ModelSpace.
        public static ObjectId CreateEmployee(String name, String division, Double salary, Point3d pos)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                //Create the block reference...use the return from CreateEmployeeDefinition directly!
                BlockReference br = new BlockReference(pos, CreateEmployeeDefinition());
                // create a new attribute reference
                AttributeReference attRef = new AttributeReference();

                //Iterate the employee block and find the attribute definition
                BlockTableRecord empBtr = (BlockTableRecord)trans.GetObject(bt["EmployeeBlock"], OpenMode.ForRead);

                foreach (ObjectId id in empBtr)
                {
                    Entity ent = (Entity)trans.GetObject(id, OpenMode.ForRead, false); //Use it to open the current object!
                    if (ent.GetType().FullName.Equals("Autodesk.AutoCAD.DatabaseServices.AttributeDefinition"))  //We use .NET//s RTTI to establish type.
                    {
                        //Set the properties from the attribute definition on our attribute reference
                        AttributeDefinition attDef = (AttributeDefinition)ent;
                        attRef.SetPropertiesFrom(attDef);
                        attRef.Position = new Point3d(attDef.Position.X + br.Position.X,
                        attDef.Position.Y + br.Position.Y,
                        attDef.Position.Z + br.Position.Z);

                        attRef.Height = attDef.Height;
                        attRef.Rotation = attDef.Rotation;
                        attRef.Tag = attDef.Tag;
                        attRef.TextString = name;
                    }
                }
                btr.AppendEntity(br); //Add the reference to ModelSpace

                //Add the attribute reference to the block reference
                br.AttributeCollection.AppendAttribute(attRef);

                //let the transaction know
                trans.AddNewlyCreatedDBObject(attRef, true);
                trans.AddNewlyCreatedDBObject(br, true); //Let the transaction know about it

                //Create the custom per-employee data
                Xrecord xRec = new Xrecord();
                //We want to add //Name//, //Salary// and //Division// information.  Here is how:
                xRec.Data = new ResultBuffer(
                    new TypedValue((int)DxfCode.Text, name),
                    new TypedValue((int)DxfCode.Real, salary),
                    new TypedValue((int)DxfCode.Text, division));

                //Next, we need to add this data to the //Extension Dictionary// of the employee.
                br.CreateExtensionDictionary();
                DBDictionary brExtDict = (DBDictionary)trans.GetObject(br.ExtensionDictionary, OpenMode.ForWrite, false);
                brExtDict.SetAt("EmployeeData", xRec); //Set our XRecord in the dictionary at //EmployeeData//.
                trans.AddNewlyCreatedDBObject(xRec, true);

                trans.Commit();

                //return the objectId of the employee block reference
                return br.ObjectId;
            }
        }
Example #35
0
        // This function creates a new BlockReference to the "EmployeeBlock" object,
        // and adds it to ModelSpace.
        private ObjectId CreateEmployee(string name, string division, double salary, Point3d pos)
        {
            // get the current working database
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)(trans.GetObject(db.BlockTableId, OpenMode.ForWrite));
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                // Create the block reference...use the return from CreateEmployeeDefinition directly!
                BlockReference br = new BlockReference(pos, CreateEmployeeDefinition());

                AttributeReference attRef = new AttributeReference();
                // Iterate the employee block and find the attribute definition
                BlockTableRecord empBtr = (BlockTableRecord)trans.GetObject(bt["EmployeeBlock"], OpenMode.ForRead);
                foreach (ObjectId id in empBtr)
                {
                    Entity ent = (Entity)trans.GetObject(id, OpenMode.ForRead, false);
                    // Use it to open the current object!
                    if (ent is AttributeDefinition)  // We use .NET's RunTimeTypeInformation (RTTI) to establish type.
                    {
                        // Set the properties from the attribute definition on our attribute reference
                        AttributeDefinition attDef = ((AttributeDefinition)(ent));
                        attRef.SetPropertiesFrom(attDef);
                        attRef.Position = new Point3d(attDef.Position.X + br.Position.X, attDef.Position.Y + br.Position.Y, attDef.Position.Z + br.Position.Z);
                        attRef.Height = attDef.Height;
                        attRef.Rotation = attDef.Rotation;
                        attRef.Tag = attDef.Tag;
                        attRef.TextString = name;
                    }
                }
                // Add the reference to ModelSpace
                btr.AppendEntity(br);
                // Add the attribute reference to the block reference
                br.AttributeCollection.AppendAttribute(attRef);
                // let the transaction know
                trans.AddNewlyCreatedDBObject(attRef, true);
                trans.AddNewlyCreatedDBObject(br, true);

                // Create the custom per-employee data
                Xrecord xRec = new Xrecord();
                // We want to add 'Name', 'Salary' and 'Division' information.  Here is how:
                xRec.Data = new ResultBuffer(
                  new TypedValue((int)DxfCode.Text, name),
                  new TypedValue((int)DxfCode.Real, salary),
                  new TypedValue((int)DxfCode.Text, division));

                // Next, we need to add this data to the 'Extension Dictionary' of the employee.
                br.CreateExtensionDictionary();
                DBDictionary brExtDict = (DBDictionary)trans.GetObject(br.ExtensionDictionary, OpenMode.ForWrite, false);
                brExtDict.SetAt("EmployeeData", xRec); //Set our XRecord in the dictionary at 'EmployeeData'.
                trans.AddNewlyCreatedDBObject(xRec, true);

                ObjectId retId = br.ObjectId;
                trans.Commit();

                return retId;
            }
        }
Example #36
0
        private ObjectId CreateDivision(string division, string manager)
        {
            ObjectId retId = ObjectId.Null;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                // First, get the Named Objects Dictionary (NOD)...
                DBDictionary NOD = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite);
                // Define a corporate level dictionary
                DBDictionary acmeDict;

                // here's another way to check to see if an entry exists, using try/catch instead of has[]
                try
                {
                    // Just throw if it doesn't exist...do nothing else
                    acmeDict = (DBDictionary)trans.GetObject(NOD.GetAt("ACME_DIVISION"), OpenMode.ForRead);
                }
                catch
                {
                    //Doesn't exist, so create one, and set it in the NOD?/font>
                    acmeDict = new DBDictionary();
                    NOD.SetAt("ACME_DIVISION", acmeDict);
                    trans.AddNewlyCreatedDBObject(acmeDict, true);
                }

                // Now get the division we want from acmeDict
                DBDictionary divDict;
                try
                {
                    divDict = (DBDictionary)trans.GetObject(acmeDict.GetAt(division), OpenMode.ForWrite);
                }
                catch
                {
                    divDict = new DBDictionary();
                    //Division doesn't exist, create one
                    acmeDict.UpgradeOpen();
                    acmeDict.SetAt(division, divDict);
                    trans.AddNewlyCreatedDBObject(divDict, true);
                }

                // Now get the manager info from the division
                // We need to add the name of the division supervisor.  We'll do this with another XRecord.
                Xrecord mgrXRec;
                try
                {
                    mgrXRec = (Xrecord)trans.GetObject(divDict.GetAt("Department Manager"), OpenMode.ForWrite);
                }
                catch
                {
                    mgrXRec = new Xrecord();
                    mgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, manager));
                    divDict.SetAt("Department Manager", mgrXRec);
                    trans.AddNewlyCreatedDBObject(mgrXRec, true);
                }

                // Return the department manager XRecord
                retId = mgrXRec.ObjectId;
                trans.Commit();
            }
            return retId;
        }
        // add attributes to group object
        // <param name="groupId"></param>
        // <param name="pairs"></param>
        public static void addData(ObjectId groupId, Dictionary<String, String> pairs)
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            Transaction trans = ed.Document.Database.TransactionManager.StartTransaction();
            try
            {
                Group ent = (Group)trans.GetObject(groupId, OpenMode.ForRead);
                if (ent.ExtensionDictionary.IsNull)
                {
                    ent.UpgradeOpen();
                    ent.CreateExtensionDictionary();
                }

                DBDictionary extensionDict = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead);
                foreach (KeyValuePair<string, string> item in pairs)
                {
                    String key = item.Key;
                    String value = item.Value;
                    Xrecord myXrecord;
                    if (extensionDict.Contains(key))
                    {
                        // Check to see if the entry we are going to add is already there.
                        ObjectId entryId = extensionDict.GetAt(key);
                        // Extract the Xrecord. Declare an Xrecord variable.
                        myXrecord = default(Xrecord);
                        extensionDict.UpgradeOpen();
                        // Instantiate the Xrecord variable
                        myXrecord = (Xrecord)trans.GetObject(entryId, OpenMode.ForWrite);
                        ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Text, value));
                        myXrecord.Data = data;

                    }
                    else
                    {
                        // If the code gets to here then the data entry does not exist
                        // upgrade the ExtensionDictionary created in step 5 to write
                        extensionDict.UpgradeOpen();
                        //  Create a new XRecord.
                        myXrecord = new Xrecord();
                        // Create the resbuf list.
                        ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Text, value));
                        // Add the ResultBuffer to the Xrecord
                        myXrecord.Data = data;
                        // Create the entry in the ExtensionDictionary.
                        extensionDict.SetAt(key, myXrecord);
                        // Tell the transaction about the newly created Xrecord
                        trans.AddNewlyCreatedDBObject(myXrecord, true);
                    }
                }
                trans.Commit();
            }
            catch (System.Exception ex)
            {
                // a problem occured, lets print it
                ed.WriteMessage("a problem occured because " + ex.Message);
            }
            finally
            {
                trans.Dispose();
            }
        }
Example #38
0
        public static ObjectId CreateEmployee(String name, String division, Double salary, Point3d pos)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                // ����һ��Բ
                Circle cir = new Circle();
                cir.Center = pos;
                cir.Radius = 100;
                cir.ColorIndex = 1;
                btr.AppendEntity(cir);
                trans.AddNewlyCreatedDBObject(cir, true);

                //���������¼
                Xrecord xRec = new Xrecord();
                xRec.Data = new ResultBuffer(
                    new TypedValue((int)DxfCode.Text, name),
                    new TypedValue((int)DxfCode.Real, salary),
                    new TypedValue((int)DxfCode.Text, division));

                cir.CreateExtensionDictionary();
                DBDictionary brExtDict = (DBDictionary)trans.GetObject(cir.ExtensionDictionary, OpenMode.ForWrite, false);
                brExtDict.SetAt("EmpInfor", xRec);
                trans.AddNewlyCreatedDBObject(xRec, true);

                trans.Commit();

                //
                return cir.ObjectId;
            }
        }
        public void Save()
        {
            if(WriteLock == true)
            {
                return;
            }
            if(BaseObjectId == ObjectId.Null)
            {
                return;
            }
            using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                attrs.Clear();
                this.GetAttributes();
                if (attrs.ContainsKey("type"))
                {
                    attrs["type"] = this.ModelType();
                }
                else
                {
                    attrs.Add("type", this.ModelType());
                }
                if(attrs.ContainsKey("modelid"))
                {
                    attrs["modelid"] = Utils.ModelIdManager.toString(this.BaseModelId);
                }
                else
                {
                    attrs.Add("modelid", Utils.ModelIdManager.toString(this.BaseModelId));
                }
                Dictionary<String, String> pairs = attrs;
                Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
                Transaction trans = ed.Document.Database.TransactionManager.StartTransaction();
                try
                {
                    DBObject ent = trans.GetObject(BaseObjectId, OpenMode.ForRead);

                    if (ent.ExtensionDictionary.IsNull)
                    {
                        ent.UpgradeOpen();
                        ent.CreateExtensionDictionary();
                    }

                    DBDictionary extensionDict = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead);
                    foreach (KeyValuePair<string, string> item in pairs)
                    {
                        String key = item.Key;
                        String value = item.Value;
                        Xrecord myXrecord;
                        if (extensionDict.Contains(key))
                        {
                            ObjectId entryId = extensionDict.GetAt(key);
                            myXrecord = default(Xrecord);
                            extensionDict.UpgradeOpen();
                            myXrecord = (Xrecord)trans.GetObject(entryId, OpenMode.ForWrite);
                            ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Text, value));
                            myXrecord.Data = data;
                        }
                        else
                        {
                            extensionDict.UpgradeOpen();
                            myXrecord = new Xrecord();
                            ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Text, value));
                            myXrecord.Data = data;
                            extensionDict.SetAt(key, myXrecord);
                            trans.AddNewlyCreatedDBObject(myXrecord, true);
                        }
                    }
                    trans.Commit();
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage("a problem occured because " + ex.Message);
                }
                finally
                {
                    trans.Dispose();
                }
            }
        }
Example #40
0
        public void AddInNOD()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("����������ʵ����������\n");
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //��ȡ��������ʵ䣨NOD)
                DBDictionary NOD =trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite) as DBDictionary ;
                // ����һ���µĴʵ�
                DBDictionary copyrightDict;
                // �ж��Ƿ����COPYRIGHT�ʵ䣬û���򴴽�
                try
                {
                    // ��ȡCOPYRIGHT�ʵ�
                    copyrightDict = (DBDictionary)trans.GetObject(NOD.GetAt("COPYRIGHT"), OpenMode.ForRead);
                }
                catch
                {
                    //��NOD�´���COPYRIGHT�ʵ�
                    copyrightDict = new DBDictionary();
                    NOD.SetAt("COPYRIGHT", copyrightDict);
                    trans.AddNewlyCreatedDBObject(copyrightDict, true);
                }

                // ��copyrightDict�У���ȡ�򴴽� "author" �ʵ�
                DBDictionary authorDict;
                try
                {
                    authorDict = (DBDictionary)trans.GetObject(copyrightDict.GetAt("Author"), OpenMode.ForWrite);
                }
                catch
                {
                    authorDict = new DBDictionary();
                    //"author" doesn't exist, create one
                    copyrightDict.UpgradeOpen();
                    copyrightDict.SetAt("Author", authorDict);
                    trans.AddNewlyCreatedDBObject(authorDict, true);
                }

                // ͨ��Xrecord��ResultBuffer�����չ����
                Xrecord authorRec;
                try
                {
                    authorRec = (Xrecord)trans.GetObject(authorDict.GetAt("AuthorInfo"), OpenMode.ForWrite);
                }
                catch
                {
                    authorRec = new Xrecord();
                    authorRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, "����"));
                    authorDict.SetAt("AuthorInfo", authorRec);
                    trans.AddNewlyCreatedDBObject(authorRec, true);
                }
                trans.Commit();
            }
        }
Example #41
0
        private void CreateDivision()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //First, get the NOD...
                DBDictionary NOD = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite);
                //Define a corporate level dictionary
                DBDictionary acmeDict;

                try
                {
                    //Just throw if it doesn't exist...do nothing else
                    acmeDict = (DBDictionary)trans.GetObject(NOD.GetAt("ACME_DIVISION"), OpenMode.ForRead);
                }
                catch
                {
                    //Doesn't exist, so create one, and set it in the NOD?/font>
                    acmeDict = new DBDictionary();
                    NOD.SetAt("ACME_DIVISION", acmeDict);
                    trans.AddNewlyCreatedDBObject(acmeDict, true);
                }

                //Now get the division we want from acmeDict
                DBDictionary divDict;
                try
                {
                    divDict = (DBDictionary)trans.GetObject(acmeDict.GetAt("Sales"), OpenMode.ForWrite);
                }
                catch
                {
                    divDict = new DBDictionary();
                    //Division doesn't exist, create one
                    acmeDict.UpgradeOpen();
                    acmeDict.SetAt("Sales", divDict);
                    trans.AddNewlyCreatedDBObject(divDict, true);
                }

                //Now get the manager info from the division
                //We need to add the name of the division supervisor.  We'll do this with another XRecord.
                Xrecord mgrXRec;

                try
                {
                    mgrXRec = (Xrecord)trans.GetObject(divDict.GetAt("Department Manager"), OpenMode.ForWrite);
                }
                catch
                {
                    mgrXRec = new Xrecord();
                    mgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, "Randolph P. Brokwell"));
                    divDict.SetAt("Department Manager", mgrXRec);
                    trans.AddNewlyCreatedDBObject(mgrXRec, true);
                }

                trans.Commit();
            }
        }
Example #42
0
 private static ObjectId getRec(string recName)
 {
     ObjectId idDict = getDict();
     if (idDict.IsNull)
     {
         return ObjectId.Null;
     }
     ObjectId idRec = ObjectId.Null;
     using (var dic = idDict.Open(OpenMode.ForRead) as DBDictionary)
     {
         if (!dic.Contains(recName))
         {
             using (var xRec = new Xrecord())
             {
                 dic.UpgradeOpen();
                 idRec = dic.SetAt(recName, xRec);
             }
         }
         else idRec = dic.GetAt(recName);
     }
     return idRec;
 }
Example #43
0
 /// <summary>
 /// Agrega un xrecord en un diccionario
 /// </summary>
 /// <param name="xName">El nombre del registro</param>
 /// <param name="dicId">El id del diccionario.</param>
 /// <returns>El object id del nuevo registro</returns>
 public ObjectId AddXRecord(ObjectId dicId, String xName)
 {
     Database db = AcadApp.DocumentManager.MdiActiveDocument.Database;
     ObjectId id = new ObjectId();
     using (Transaction tr = db.TransactionManager.StartTransaction())
     {
         try
         {
             DBDictionary dic = (DBDictionary)dicId.GetObject(OpenMode.ForWrite);
             Xrecord x = new Xrecord();
             dic.SetAt(xName, x);
             tr.AddNewlyCreatedDBObject(x, true);
             id = x.ObjectId;
             tr.Commit();
         }
         catch (System.Exception exc)
         {
             ed.WriteMessage(exc.Message);
             tr.Abort();
         }
     }
     return id;
 }
Example #44
0
            public void AddExtensionDictionary(ObjectId obj)
            {
                DBObject dbObj = tr.openObject(obj, OpenMode.ForRead) as DBObject;

                ObjectId dicObj = dbObj.ExtensionDictionary;

                if (dicObj == ObjectId.Null)
                {
                    dbObj.UpgradeOpen();
                    dbObj.CreateExtensionDictionary();
                    dicObj = dbObj.ExtensionDictionary;
                }

                tr.closeObject();
                tr.start_Transaction();
                DBDictionary dbDic = tr.AC_Tr.GetObject(dicObj,OpenMode.ForRead) as DBDictionary;

                if (!dbDic.Contains("DIMINC_LINE"))
                {
                    dbDic.UpgradeOpen();
                    Xrecord xr = new Xrecord();
                    ResultBuffer rb = new ResultBuffer(new TypedValue((int)DxfCode.ExtendedDataAsciiString,GUID));
                    xr.Data = rb;
                    dbDic.SetAt("DIMINC_LINE", xr);
                    tr.AC_Tr.AddNewlyCreatedDBObject(xr, true);
                }
                tr.AC_Tr.Commit();
                tr.AC_Tr.Dispose();
            }