public void AddTest2() { DBObjectArray target = new DBObjectArray(); DBObject a = new DBObject("add", "me"); target.Add(new KeyValuePair<string, object>("0", a)); new Action(() => target.Add(new KeyValuePair<string, object>("a", a))).ShouldThrow<Exception>(); target.Count.Should().Be(1); }
//public OdTable OdTable { get; private set; } public OdRecord(DBObject dbObject) { if (dbObject == null) throw new ArgumentNullException(); DbObject = dbObject; Values = new List<MapValue>(); }
public void AddTest1() { DBObjectArray target = new DBObjectArray(); DBObject a = new DBObject("add", "me"); target.Add("0", a); target.Count.Should().Be(1); new Action(() => target.Add("a", a)).ShouldThrow<ArgumentException>("index/key must be numeric"); }
public void AppendTest() { DBObject target = new DBObject(); target.Count.Should().Be(0); target.Append("a", 1); target.Count.Should().Be(1); target.Append("b", 2); target.Count.Should().Be(2); target["b"].Should().Be(2); }
public void ConstructFromDictionary() { Dictionary<string, object> m = new Dictionary<string, object>(); m["key"] = "value"; m["foo"] = 1; m["bar"] = null; IDBObject obj = new DBObject(m); Assert.AreEqual(obj["key"], "value"); Assert.AreEqual(obj["foo"], 1); Assert.AreEqual(obj["bar"], null); }
// //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion public string WriteToString(object value) { DBObject obj = new DBObject("a", value); string result = string.Empty; using (MemoryStream stream = new MemoryStream()) using (WireProtocolWriter writer = new WireProtocolWriter(stream)) { writer.Write(obj); result = BitConverter.ToString(stream.GetBuffer(), 0, (int)stream.Length); } return result; }
public void PutAll() { IDBObject start = new DBObject() { { "a", 7 }, { "d", 4 } }; Assert.AreEqual(7, start["a"]); Assert.AreEqual(4, start["d"]); start.PutAll(new DBObject() { { "a", 1 }, { "b", 2 }, { "c", 3 } }); Assert.AreEqual(1, start["a"]); //Overwrite Assert.AreEqual(2, start["b"]); //Add Assert.AreEqual(3, start["c"]); //Add Assert.AreEqual(4, start["d"]); //Left alone }
public static DBObject getObjectByID(int ID, DBObject.ObjType type) { string baseTable = DBObject.getBaseTable(type); GetInstance factoryMethod = getFactoryMethod(type); DataTable dtObj = DB_DAL.getTable("SELECT * FROM " + baseTable + " WHERE ID=" + ID.ToString()); if (dtObj.Rows.Count <= 0) return null; return factoryMethod(dtObj.Rows[0]); }
public void TestWriteDocument() { MemoryStream ms = new MemoryStream(); WireProtocolWriter writer = new WireProtocolWriter(ms); string expected = "1400000002746573740005000000746573740000"; DBObject doc = new DBObject("test", "test"); writer.Write(doc); string hexdump = BitConverter.ToString(ms.ToArray()); hexdump = hexdump.Replace("-", ""); Assert.AreEqual(expected, hexdump); }
private void ProcessInstance(DBObject instance) { DataTable dt = new DataTable(); dt.Columns.Add("Fullname"); dt.Columns.Add("Name"); dt.Columns.Add("Template Address"); dt.Columns.Add("Instance Address"); AddDescendants(ref dt, instance, "CSCADAPackMAnalogIn"); AddDescendants(ref dt, instance, "CSCADAPackMAnalogOut"); AddDescendants(ref dt, instance, "CSCADAPackMDigitalIn"); AddDescendants(ref dt, instance, "CSCADAPackMDigitalOut"); dataGridViewResults.DataSource = dt; }
public static DBObject[] getCustomObjects(DBObject.ObjType type, string whereClause) { string baseTable = DBObject.getBaseTable(type); GetInstance factoryMethod = getFactoryMethod(type); DataTable dtObj = DB_DAL.getTable("SELECT * FROM " + baseTable + whereClause); DBObject[] allObj = getArray(type, dtObj.Rows.Count); for (int i = 0; i < dtObj.Rows.Count; ++i) allObj[i] = factoryMethod(dtObj.Rows[i]); return allObj; }
public void EntryOrder() { DBObject o = new DBObject(); o["u"] = 0; o["m"] = 1; o["p"] = 2; o["i"] = 3; o["r"] = 4; o["e"] = 5; o["s"] = 6; string[] keys = new string[7]; o.Keys.CopyTo(keys, 0); Assert.That(string.Join("", keys), Is.EqualTo("umpires"), "keys should be in order added"); List<KeyValuePair<string, object>> pairs = new List<KeyValuePair<string, object>>(o); for (int i = 0; i < 7; i++) { Assert.That(pairs[i].Value, Is.EqualTo(i), "pairs should be in order added"); } }
private void AddDescendants(ref DataTable dt, DBObject dbObj, string dbClass) { DBObjectCollection descendants = dbObj.GetDescendants(dbClass, ""); foreach (DBObject descendant in descendants) { DBObject template = descendant.TemplateObject; string instanceAddress = descendant.GetProperty("Address").ToString(); string templateAddress = template.GetProperty("Address").ToString(); List<string> values = new List<string>(); values.Add(template.FullName); values.Add(template.Name); values.Add(templateAddress); values.Add(instanceAddress); if (!checkBoxShowMismatchesOnly.Checked || (checkBoxShowMismatchesOnly.Checked && templateAddress != instanceAddress)) { dt.Rows.Add(values.ToArray()); } } }
/// <summary> /// Groups data on the server /// </summary> /// <param name="db">The db.</param> /// <param name="collection">The collection.</param> /// <param name="key">The key.</param> /// <param name="cond">The cond.</param> /// <param name="initial">The initial.</param> /// <param name="reduce">The reduce.</param> /// <returns></returns> public static IDBObject group(this IDatabase db, IDBCollection collection, DBFieldSet key, DBQuery cond, IDocument initial, string reduce) { DBObject group = new DBObject() { {"ns", collection.Name}, {"$reduce", reduce}, }; if (key != null) group["key"] = key; if (cond != null) group["cond"] = cond; if (initial != null) group["initial"] = initial; IDBObject ret = db.ExecuteCommand(new DBQuery("group", group)); ret.ThrowIfResponseNotOK("group failed"); return ret.GetAsIDBObject("retval"); }
public static bool DelBlock(Document doc, Transaction transaction, BlockTableRecord BlockTableRecord_) { try { if (BlockTableRecord_.ObjectId != ObjectId.Null) { DBObject obj = transaction.GetObject(BlockTableRecord_.ObjectId, OpenMode.ForWrite); if (obj != null) { obj.Erase(); return(true); } return(false); } return(false); } catch (Autodesk.AutoCAD.Runtime.Exception EX) { return(false); } }
/// <summary> /// This function is used to get the list of those students whose eligibility is kept pending. /// The search will be based on the filtering conditions in the Advanced Search control. /// The Search will be in REG tables. /// </summary> /// <param name="Uni_ID"></param> /// <param name="InstTy_ID"></param> /// <param name="Inst_Name"></param> /// <param name="Inst_State_ID"></param> /// <param name="Inst_District_ID"></param> /// <param name="Inst_Tehsil_ID"></param> /// <param name="FacultyID"></param> /// <param name="CourseID"></param> /// <param name="CrMoLrnPtrnID"></param> /// <param name="CrPrID"></param> /// <param name="DOB"></param> /// <param name="LastName"></param> /// <param name="FirstName"></param> /// <param name="Gender"></param> /// <returns>DataSet</returns> public static DataSet Fetch_Pending_Reg_Student_List(string Uni_ID, string InstTy_ID, string Inst_Name, string Inst_State_ID, string Inst_District_ID, string Inst_Tehsil_ID, string FacultyID, string CourseID, string CrMoLrnPtrnID, string CrPrID, string DOB, string LastName, string FirstName, string Gender) { DataSet ds = new DataSet(); DBObjectPool Pool = null; DBObject oDB = null; try { Pool = DBObjectPool.Instance; oDB = Pool.AcquireDBObject(); Hashtable ht = new Hashtable(); ht.Add("Uni_ID", Uni_ID); ht.Add("InstTy_ID", InstTy_ID); ht.Add("Inst_Name", Inst_Name); ht.Add("Inst_State_ID", Inst_State_ID); ht.Add("Inst_District_ID", Inst_District_ID); ht.Add("Inst_Tehsil_ID", Inst_Tehsil_ID); ht.Add("FacultyID", FacultyID); ht.Add("CrID", CourseID); ht.Add("CrMoLrnPtrnID", CrMoLrnPtrnID); ht.Add("CrPrID", CrPrID); ht.Add("DOB", DOB); ht.Add("LastName", LastName); ht.Add("FirstName", FirstName); ht.Add("Gender", Gender); ds = oDB.getparamdataset("elg_Fetch_Pending_Reg_StudentList", ht); return(ds); } catch (Exception Ex) { Exception e = new Exception(Ex.Message, Ex); throw(e); } finally { Pool.ReleaseDBObject(oDB); } }
public void UpdateXData()//更新扩展数据 { if (isChanged) { //下面2行代码锁住文档 DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.LockDocument(); Document doc = Application.DocumentManager.MdiActiveDocument; Transaction tr = doc.TransactionManager.StartTransaction(); using (tr) { DBObject obj = tr.GetObject(this.id, OpenMode.ForWrite); ResultBuffer rb = new ResultBuffer(); foreach (KeyValuePair <string, Dictionary <string, string> > kp in this.appName2values) { rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, kp.Key)); foreach (KeyValuePair <string, string> pair in kp.Value) { rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, pair.Key)); rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, pair.Value)); } obj.XData = rb;//替换对应appname的扩展数据 rb = new ResultBuffer(); } rb.Dispose(); tr.Commit(); } isChanged = false; //PurgeDatabase(doc.Database);//作为实验,看是否能够清除多余的appname,(暂时不考虑,如果出现问题在考虑这个问题) docLock.Dispose(); } }
public List <PipeLine> SearchConnected(BaseModel model) { List <PipeLine> pipes = new List <PipeLine>(); if (!model.BaseObjectId.IsNull) { try { Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { DBObject obj = tr.GetObject(model.BaseObjectId, OpenMode.ForRead); BlockReference block = (BlockReference)obj; Extents3d bd = block.GeometryExtentsBestFit(); foreach (var item in PipeLines) { Point3d p1 = item.Value.Point(0); Point3d p2 = item.Value.Point(1); if (p1.X >= bd.MinPoint.X - 0.001 && p1.Y >= bd.MinPoint.Y - 0.001 && p1.X <= bd.MaxPoint.X + 0.001 && p1.Y <= bd.MaxPoint.Y + 0.001) { pipes.Add(item.Value); continue; } if (p2.X >= bd.MinPoint.X - 0.001 && p2.Y >= bd.MinPoint.Y - 0.001 && p2.X <= bd.MaxPoint.X + 0.001 && p2.Y <= bd.MaxPoint.Y + 0.001) { pipes.Add(item.Value); continue; } } } } catch (Exception e) { Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(e.Message); } } return(pipes); }
public void ConsumeKeys(Session session) { foreach (KeyValuePair <int, DBRelationshipTargets> pair in LinkTargets) { DBObject linkOb = session.GetObject(Type, pair.Key); foreach (KeyValuePair <PropertyInfo, ConcurrentQueue <DBObject> > target in pair.Value.PropertyTargets) { while (!target.Value.IsEmpty) { if (!target.Value.TryDequeue(out DBObject targetOb)) { continue; } target.Key.SetValue(targetOb, linkOb); } } pair.Value.PropertyTargets.Clear(); } LinkTargets.Clear(); }
public static Point3dCollection GetBoundaryPointCollection(ObjectId objectId, bool allowDuplicate = false) { Point3dCollection boundaryInModelSpace; using (var transaction = objectId.Database.TransactionManager.StartTransaction()) { using (DBObject dbObject = transaction.GetObject(objectId, OpenMode.ForRead)) { boundaryInModelSpace = GetBoundaryPointCollection(transaction, dbObject); // 允许重复 if (!allowDuplicate) { RemoveDuplicatePointFromPoint3DCollection(boundaryInModelSpace); } } transaction.Commit(); } return(boundaryInModelSpace); }
public override EventResult OnMouseUp(MouseEventArgs e) { switch (_step) { case Step.Step1_SpecifyOffsetDistance: break; case Step.Step2_SelectObject: if (e.Button == MouseButtons.Right) { if (this.presenter.selections.Count > 0) { foreach (Selection sel in _mgr.presenter.selections) { DBObject dbobj = this.database.GetObject(sel.objectId); _currEntity = dbobj as Entity; _currOffsetOp = Offset._OffsetOpsMgr.Instance.NewOffsetOperation(_currEntity); break; } this.pointer.mode = Pointer.Mode.Locate; _step = Step.Step3_SpecifyOffsetSide; } else { _mgr.CancelCurrentCommand(); } } break; case Step.Step3_SpecifyOffsetSide: break; default: break; } return(EventResult.Handled); }
public static void writeObject(System.IO.StreamWriter file, DBObject dbo, int id) { if (dbo is Circle) { Circle circle = dbo as Circle; writeCircle(file, circle); } else if (dbo is Arc) { Arc arc = dbo as Arc; writeArc(file, arc); } else if (dbo is Line) { Line line = dbo as Line; writeLine(file, line); } else if (dbo is MText) { MText text = dbo as MText; writeText(file, text); } else if (dbo is DBText) { DBText text = dbo as DBText; writeDBText(file, text); } else if (dbo is Polyline) { Polyline pline = dbo as Polyline; writePolyline(file, pline); } else { file.WriteLine("__type not processed: " + dbo.GetType()); } file.WriteLine("ID: " + id); file.WriteLine("END_OBJ"); }
public static ObjectIdCollection TypeCheckApproach2() { ObjectIdCollection ids = new ObjectIdCollection(); Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId id in btr) { DBObject obj = tr.GetObject(id, OpenMode.ForRead); if (obj.GetType() == typeof(Circle)) { ids.Add(obj.Id); } } tr.Commit(); } return(ids); }
public virtual void Test_Will_Not_Add_Column_To_Table_With_Option_Off() { dstore.SchemaValidator.CanAddColumns = false; DatabaseTypeInfo ti = dstore.TypeInformationParser.GetTypeInfo(typeof(TestItemThreeFields)); IEnumerable <DBObject> tables = dstore.SchemaValidator.TableValidator.GetObjects(); DBObject inserted = tables.Where(R => R.Name.Equals(ti.UnescapedTableName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); Assert.IsTrue(inserted != null); Assert.IsTrue(inserted.Columns.Count == 3); dstore.SchemaValidator.TableValidator.OnObjectModified += (sender, args) => { Assert.IsTrue(false); }; DatabaseTypeInfo t2 = dstore.TypeInformationParser.GetTypeInfo(typeof(TestItemThreeFieldsPlusOne)); tables = dstore.SchemaValidator.TableValidator.GetObjects(); DBObject inserted2 = tables.Where(R => R.Name.Equals(ti.UnescapedTableName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); Assert.IsTrue(inserted2 != null); Assert.IsTrue(inserted2.Columns.Count == 3); }
GetRecursiveDictionaryEntries(ObjectId dictId, ref ObjectIdCollection objIds, ref ArrayList names) { // NOTE: when recursively processing items in a dictionary // we may encounter things that are not derived from DBDictionary. // In that case, the cast to type DBDictionary will fail and // we'll just return without adding any nested items. DBObject tmpObj = m_trHlp.Transaction.GetObject(dictId, OpenMode.ForRead); DBDictionary dbDict = tmpObj as DBDictionary; if (dbDict != null) { foreach (DictionaryEntry curEntry in dbDict) { objIds.Add((ObjectId)curEntry.Value); names.Add((string)curEntry.Key); // if this is a dictionary, it will recursively add // all of its children to the tree GetRecursiveDictionaryEntries((ObjectId)curEntry.Value, ref objIds, ref names); } } }
private CodeClass GetCodeClass(DBObject obj, ProjectItem folder) { string fileName; if (string.IsNullOrEmpty(obj.Schema)) { fileName = string.Format(@"{0}.cs", obj.Name); } else { fileName = string.Format(@"{0}_{1}.cs", obj.Schema, obj.Name); } string template = GetTemplate(); foreach (ProjectItem v in folder.ProjectItems.Cast <ProjectItem>()) { if (v.Name.Equals(fileName, StringComparison.InvariantCultureIgnoreCase)) { v.Delete(); break; } } folder.ProjectItems.AddFromTemplate(template, fileName); ProjectItem pi = folder.ProjectItems.Item(fileName); pi.Open(); while (!pi.IsOpen) { System.Threading.Thread.Sleep(100); } CodeClass newClass = pi.FileCodeModel.CodeElements.OfType <CodeNamespace>().First().Children.OfType <CodeClass>().First(); newClass.Access = vsCMAccess.vsCMAccessPublic; return(newClass); }
public void Insert() { //ed.WriteMessage("Go to Insert \n"); Database db = Application.DocumentManager.MdiActiveDocument.Database; using (DocumentLock docLock = Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = db.TransactionManager.StartTransaction()) { DBObject dbObject = tr.GetObject(SelectedObjectId, OpenMode.ForRead); if (dbObject.ExtensionDictionary == ObjectId.Null) { dbObject.UpgradeOpen(); dbObject.CreateExtensionDictionary(); } //ed.WriteMessage(" AT ParentCode : {0} \n", ParentCode); //ed.WriteMessage(" AT NodeCode : {0} \n", NodeCode); //ed.WriteMessage(" AT NodeType : {0} \n", NodeType); //ed.WriteMessage(" AT ProductCode : {0} \n", ProductCode); //ed.WriteMessage(" AT Angle : {0} \n", Angle); DBDictionary ExtensionDictionary = (DBDictionary)tr.GetObject(dbObject.ExtensionDictionary, OpenMode.ForWrite); Xrecord xrec = new Xrecord(); xrec.Data = new ResultBuffer( new TypedValue((int)DxfCode.Text, ParentCode), new TypedValue((int)DxfCode.Text, NodeCode), new TypedValue((int)DxfCode.Int32, NodeType), new TypedValue((int)DxfCode.Int32, ProductCode), new TypedValue((int)DxfCode.Real, Angle)); ExtensionDictionary.SetAt("AT_INFO", xrec); tr.AddNewlyCreatedDBObject(xrec, true); tr.Commit(); } } }
public static PointSet SubdividePolyline(DBObject obj, Transaction trans, double d) { Polyline polyline = obj as Polyline; if (polyline != null) { return(PointGeneration.SubdivideLWPolyline(polyline, d)); } Polyline2d polyline2d = obj as Polyline2d; if (polyline2d != null) { return(PointGeneration.SubdividePolyline2d(polyline2d, trans, d)); } Polyline3d polyline3d = obj as Polyline3d; if (!(polyline3d != null)) { throw new ArgumentException("Invalid polyline object: " + obj.Handle.ToString() + "\nObject type: " + obj.GetType().ToString()); } return(PointGeneration.SubdividePolyline3d(polyline3d, trans, d)); }
public static void EraseEntities(Database db, IEnumerable <ObjectId> items) { using (CurrentDB curr = new CurrentDB(db)) { using (Transaction tr = db.TransactionManager.StartTransaction()) { try { foreach (ObjectId id in items) { DBObject item = tr.GetObject(id, OpenMode.ForWrite); item.Erase(); } } catch { ; } tr.Commit(); } } }
static void AppendAttributes(Transaction th, BlockReference blockRef, BlockTableRecord blockDef, Dictionary <string, string> dict) { foreach (ObjectId id in blockDef) { DBObject obj = th.GetObject(id, OpenMode.ForRead); if (obj == null) { continue; } if (!(obj is AttributeDefinition)) { continue; } var attDef = obj as AttributeDefinition; if ((attDef != null) && (!attDef.Constant)) { using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attDef, blockRef.BlockTransform); if (dict.ContainsKey(attRef.Tag)) { attRef.TextString = dict[attRef.Tag]; } else { attRef.TextString = " "; } blockRef.AttributeCollection.AppendAttribute(attRef); th.AddNewlyCreatedDBObject(attRef, true); } } } }
private double GetDoubleSelectingObject(string strPrompt) //Функция предлагает выбрать один объект и возвращает из него число { double rslt = 0; //Выбрать объекты ed.WriteMessage(strPrompt); //Выбираем только один: PromptSelectionOptions pso = new PromptSelectionOptions(); pso.SingleOnly = true; PromptSelectionResult sr = ed.GetSelection(pso); //Выбрали первый объект if (sr.Status == PromptStatus.OK) { Transaction tr = acCurDb.TransactionManager.StartTransaction(); try { ObjectId[] objIds = sr.Value.GetObjectIds(); DBObject dbo = tr.GetObject(objIds[0], OpenMode.ForRead); //Получим число из объекта rslt = GetTextFromObject(dbo, objIds[0].ObjectClass.Name); tr.Commit(); } catch (PlatformDb.Runtime.Exception ex) { ed.WriteMessage(ex.Message); tr.Abort(); }; } ; return(rslt); }
public static void TrimFoundation() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; PromptSelectionOptions pso = new PromptSelectionOptions(); pso.SingleOnly = true; PromptSelectionResult psr = acDoc.Editor.GetSelection(pso); if (psr.Status == PromptStatus.OK) { using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { // Open the Block table for read BlockTable acBlkTbl = tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; List <Curve> allLines = new List <Curve>(); foreach (SelectedObject so in psr.Value) { DBObject obj = tr.GetObject(so.ObjectId, OpenMode.ForRead); if (obj is Curve) { Curve c = obj as Curve; c.UpgradeOpen(); allLines.Add(c); } } TrimFoundation(allLines); tr.Commit(); } } }
public void FilterEntsWildCard() { AcadApp.DocumentManager.MdiActiveDocument.Window.Focus(); using (AcadApp.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = AcadFuncs.GetActiveDoc().TransactionManager.StartTransaction()) { TypedValue[] type_var = new TypedValue[2]; type_var.SetValue(new TypedValue((int)DxfCode.Start, "text"), 0); type_var.SetValue(new TypedValue((int)DxfCode.Text, "*abc"), 1); SelectionFilter sel_filter = new SelectionFilter(type_var); PromptSelectionResult prmpt_ret = AcadFuncs.GetEditor().GetSelection(sel_filter); if (PromptStatus.Cancel == prmpt_ret.Status) { tr.Abort(); tr.Dispose(); return; } ObjectId[] ss = prmpt_ret.Value.GetObjectIds(); foreach (ObjectId ent_id in ss) { DBObject obj = tr.GetObject(ent_id, OpenMode.ForRead); if (null == obj) { continue; } if (obj is Line) { MessageBox.Show("Selected a line!"); } } tr.Commit(); } } }
public string Add_EligibilityRights(string pk_Uni_ID, string pk_Fac_ID, string pk_Cr_ID, string pk_MoLrn_ID, string pk_CrPtrn_ID, string Elg_Rights_Flag, string Created_By, string For_All_Coll) { DBObjectPool Pool = null; DBObject oDB = null; Hashtable oHS = new Hashtable(); string sReturnData = ""; SqlCommand cmd; try { Pool = DBObjectPool.Instance; oDB = Pool.AcquireDBObject(); oHS.Add("pk_Uni_ID", pk_Uni_ID); oHS.Add("pk_Fac_ID", pk_Fac_ID); oHS.Add("pk_Cr_ID", pk_Cr_ID); oHS.Add("pk_MoLrn_ID", pk_MoLrn_ID); oHS.Add("pk_CrPtrn_ID", pk_CrPtrn_ID); oHS.Add("Elg_Rights_Flag", Elg_Rights_Flag); oHS.Add("Created_By", Created_By); oHS.Add("For_All_Coll", For_All_Coll); cmd = oDB.GenerateCommand("ELG_Add_Eligibility_Rights", oHS); cmd.ExecuteScalar(); sReturnData = "Y"; } catch (SqlException ex) { sReturnData = "N"; throw (ex); } finally { Pool.ReleaseDBObject(oDB); } return(sReturnData); }
/// <summary> /// 从字典中找对象 /// </summary> /// <param name="keyName">查找的键</param> /// <param name="db">数据库</param> /// <returns>查找的对象</returns> public static DBObject GetObjFromDic(ref ObjectId objId, string keyName, Database db, Editor ed) { DBObject obj = null; DBObject newObj = null; using (Transaction trans = db.TransactionManager.StartTransaction()) { #region 加层 //LayerTable lyrTable = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; //LayerTableRecord lyrTableRec // = trans.GetObject(lyrTable["rectLayer"], OpenMode.ForWrite) as LayerTableRecord; ///// 解开锁 //lyrTableRec.IsLocked = false; #endregion DBDictionary dbDic = trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite) as DBDictionary; objId = dbDic.ObjectId; if (!dbDic.Contains(keyName)) { return(null); } obj = trans.GetObject(dbDic.GetAt(keyName), OpenMode.ForWrite); if (obj == null) { return(null); } newObj = trans.GetObject(obj.Id, OpenMode.ForWrite); trans.Commit(); } return(newObj); }
void zoom_extents(Teigha.GraphicsSystem.View pView, DBObject pVpObj) { // here protocol extension is used again, that provides some helpful functions using (AbstractViewPE pVpPE = new AbstractViewPE(pView)) { BoundBlock3d bbox = new BoundBlock3d(); bool bBboxValid = pVpPE.GetViewExtents(bbox); // paper space overall view if (pVpObj is Teigha.DatabaseServices.Viewport && ((Teigha.DatabaseServices.Viewport)pVpObj).Number == 1) { if (!bBboxValid || !(bbox.GetMinimumPoint().X < bbox.GetMaximumPoint().X&& bbox.GetMinimumPoint().Y < bbox.GetMaximumPoint().Y)) { bBboxValid = get_layout_extents(database, pView, ref bbox); } } else if (!bBboxValid) // model space viewport { bBboxValid = get_layout_extents(database, pView, ref bbox); } if (!bBboxValid) { // set to somewhat reasonable (e.g. paper size) if (database.Measurement == MeasurementValue.Metric) { bbox.Set(Point3d.Origin, new Point3d(297.0, 210.0, 0.0)); // set to papersize ISO A4 (portrait) } else { bbox.Set(Point3d.Origin, new Point3d(11.0, 8.5, 0.0)); // ANSI A (8.50 x 11.00) (landscape) } bbox.TransformBy(pView.ViewingMatrix); } pVpPE.ZoomExtents(bbox); } }
/// <summary> /// Returns true, if the source object has an entry with the given key in the extension dictionary. /// </summary> /// <param name="source">The source object to check.</param> /// <param name="key">If parameter <paramref name="useXData"/> is true, this string is the name of the RegApp to read the data from. If parameter <paramref name="useXData"/> is false, this string acts as the key in the extension dictionary.</param> /// <param name="useXData">True, if data should be read from the source object's XData. False, if data should be read from the source object's extension dictionary.</param> /// <exception cref="System.Exception">Thrown when an AutoCAD error occurs.</exception> /// <returns>True, if the extension dictionary contains an entry with the given key.</returns> public static bool HasData(this DBObject source, string key, bool useXData) { Require.ParameterNotNull(source, nameof(source)); Require.StringNotEmpty(key, nameof(key)); if (useXData) { var resultBuffer = source.GetXDataForApplication(key); if (resultBuffer != null) { resultBuffer.Dispose(); return(true); } else { return(false); } } else { if (source.ExtensionDictionary.IsNull) { return(false); } else { var hasData = false; Helpers.WrapInTransaction(source, tr => { var dict = (DBDictionary)tr.GetObject(source.ExtensionDictionary, OpenMode.ForRead); hasData = dict.Contains(key); }); return(hasData); } } }
public void PickEnts() { AcadApp.DocumentManager.MdiActiveDocument.Window.Focus(); using (AcadApp.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = AcadFuncs.GetActiveDoc().TransactionManager.StartTransaction()) { PromptSelectionResult prmpt_ret = AcadFuncs.GetEditor().GetSelection(); if (PromptStatus.Cancel == prmpt_ret.Status) { tr.Abort(); tr.Dispose(); return; } ObjectId[] ss = prmpt_ret.Value.GetObjectIds(); foreach (ObjectId ent_id in ss) { DBObject obj = tr.GetObject(ent_id, OpenMode.ForRead); if (null == obj) { continue; } if (obj is Line) { MessageBox.Show("Selected a line!"); } else { AcadFuncs.GetEditor().SetImpliedSelection(ss); } } tr.Commit(); } } }
//create a polyline from a given segment private static Polyline makePolyLIne(DBObject dbo) { //convert part to polyline if (dbo is Arc) { Arc arcDat = dbo as Arc; double bulge = getArcBulge(arcDat.EndAngle, arcDat.StartAngle); //convert to polyline Polyline seg = new Polyline(); seg.AddVertexAt(0, new Point2d(arcDat.StartPoint.X, arcDat.StartPoint.Y), bulge, 0, 0); seg.AddVertexAt(1, new Point2d(arcDat.EndPoint.X, arcDat.EndPoint.Y), 0, 0, 0); return(seg); } else if (dbo is Line) { Polyline seg = new Polyline(); Line lDat = dbo as Line; seg.AddVertexAt(0, new Point2d(lDat.StartPoint.X, lDat.StartPoint.Y), 0, 0, 0); seg.AddVertexAt(1, new Point2d(lDat.EndPoint.X, lDat.EndPoint.Y), 0, 0, 0); return(seg); } else if (dbo is Polyline) { return(dbo as Polyline); } else if (dbo is Spline) { Polyline seg = new Polyline(); Spline spDat = dbo as Spline; Curve crv = spDat.ToPolyline(); //something something return(null); } else { return(null); } }
//[TestMethod()] public void Andycow0Delete() { DBObject dbObj = new DBObject() { DataBaseType = DBObject.DataBase.Oracle, ID = "cgh", //"cghopr", Password = "******", //"oprappl", //Node = "lnka2" Node = "jiatest4", IP = "10.31.11.118"// }; var first = testContextInstance.DataRow[0].ToString(); var second = Int32.Parse(testContextInstance.DataRow[1].ToString()); var third = DateTime.ParseExact(testContextInstance.DataRow[2].ToString(), "yyyyMMddHHmmss", null); //var fourth = testContextInstance.DataRow[3].ToString(); ANDYCOW0 andycow0 = new ANDYCOW0() { FIRST = first, SECOND = second, THIRD = third }; DAOFactory factory = new DAOFactory(dbObj); var daoObject = factory.GetDataAccessObjectFactory(); var target = daoObject.Delete(andycow0); bool result = false; if (target.IsSuccess) { result = true; } Assert.AreEqual(true, result); }
//Creates a custom property in object contains number of floors and bars public void SaveToDB(ObjectId objectId, int floorNum, int numBars) { Document document = Application.DocumentManager.MdiActiveDocument; Database database = document.Database; using (Transaction transaction = database.TransactionManager.StartTransaction()) { DBObject databaseObject = transaction.GetObject(objectId, OpenMode.ForRead); ObjectId extId = databaseObject.ExtensionDictionary; if (extId == ObjectId.Null) { databaseObject.UpgradeOpen(); databaseObject.CreateExtensionDictionary(); extId = databaseObject.ExtensionDictionary; } DBDictionary dbExt = (DBDictionary)transaction.GetObject(extId, OpenMode.ForRead); if (!dbExt.Contains("CustomProp")) { dbExt.UpgradeOpen(); Xrecord xRec = new Xrecord(); ResultBuffer rb = new ResultBuffer { new TypedValue((int)DxfCode.ExtendedDataAsciiString, floorNum.ToString()), new TypedValue((int)DxfCode.ExtendedDataAsciiString, numBars.ToString()) }; xRec.Data = rb; dbExt.SetAt("CustomProp", xRec); transaction.AddNewlyCreatedDBObject(xRec, true); } transaction.Commit(); } }
private int Load() { Hashtable oHsTb = new Hashtable(); // Creating Hashtable oHsTb.Add("pk_InstTy_ID", PK_InstTy_ID); DBObjectPool Pool = null; DBObject oDB = null; try { Pool = DBObjectPool.Instance; oDB = Pool.AcquireDBObject(); DT = oDB.getparamdataset("ID_AttributeInstituteType", oHsTb).Tables[0]; if (DT.Rows.Count > 0) { InstTy_Name = DT.Rows[0]["InstTy_Name"].ToString().Trim(); InstTy_Desc = DT.Rows[0]["InstTy_Desc"].ToString().Trim(); Active = DT.Rows[0]["Active"].ToString(); } else { Reset(); } return(DT.Rows.Count); } catch (Exception Ex) { Exception e = new Exception(Ex.Message, Ex); throw(e); } finally { Pool.ReleaseDBObject(oDB); } }
public static AT_SUB SelectBySelectedObjectId(ObjectId SelectedObjectId) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; AT_SUB at_SUB = new AT_SUB(); Database db = Application.DocumentManager.MdiActiveDocument.Database; using (DocumentLock docLock = Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = db.TransactionManager.StartTransaction()) { DBObject ent = tr.GetObject(SelectedObjectId, OpenMode.ForRead); if (ent.ExtensionDictionary != ObjectId.Null) { DBDictionary ExtDict = (DBDictionary)tr.GetObject(ent.ExtensionDictionary, OpenMode.ForRead); if (ExtDict.Contains("AT_SUB")) { at_SUB.SelectedObjectId = SelectedObjectId; Xrecord xrec = (Xrecord)tr.GetObject(ExtDict.GetAt("AT_SUB"), OpenMode.ForRead); foreach (TypedValue tv in xrec.Data) { string Temp = tv.Value.ToString().Substring(1, tv.Value.ToString().Length - 2); //ed.WriteMessage("{0} \n", Temp); at_SUB.SubIdCollection.Add(new ObjectId(new IntPtr(int.Parse(Temp)))); } } else { //ed.WriteMessage("AT_SUB : NOT EXIST \n"); } } } } return(at_SUB); }
/// <summary> /// Load an object from the database, where the objects' values are checked against any record in the table. /// Throws an RecordNotFoundException when no record is found. /// Always returns the first result. /// </summary> /// <param name="dbobject"></param> /// <returns></returns> public override List <DBObject> Get(DBObject dbobject) { Type t = dbobject.GetType(); List <DBObject> result = new List <DBObject>(); string sqlcmd = "Select * From " + dbobject.GetType().Name + " WHERE "; dbobject.GetType().GetProperties().AsParallel().Where(x => WhereNotNull(x, dbobject)).ForAll(x => sqlcmd += x.Name + " = '" + x.GetValue(dbobject, null) + "' AND "); sqlcmd = sqlcmd.Substring(0, sqlcmd.Length - " AND ".Length); Debugger.Break(); SqlCommand cmd = new SqlCommand(sqlcmd, connection_); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { DBObject obj = (DBObject)Activator.CreateInstance(t); obj.GetType().GetProperties().ToList().ForEach(x => x.SetValue(dbobject, reader[x.Name], null)); result.Add(obj); } return(result); }
public void DBObjectConstructorTest() { DBObject target = new DBObject("a", 1); target["a"].Should().Be(1); }
public void RemoveTest() { DBObject obj = new DBObject(); obj["test"] = "y"; obj["y"] = "z"; Assert.IsTrue(obj.ContainsKey("test")); Assert.IsTrue(obj.ContainsKey("y")); obj.Remove("test"); Assert.IsFalse(obj.ContainsKey("test")); Assert.IsTrue(obj.ContainsKey("y")); obj["test"] = "y"; Assert.IsTrue(obj.ContainsKey("test")); Assert.IsTrue(obj.ContainsKey("y")); }
public void PutAllTest() { IDBObject start = new DBObject() { { "a", 7 }, { "d", 4 } }; start.PutAll(new DBObject() { { "a", 1 }, { "b", 2 }, { "c", 3 } }); start["a"].Should().Be(1, "put should have overwritten a"); start["b"].Should().Be(2, "put should have added b"); start["c"].Should().Be(3, "put should have added c"); start["d"].Should().Be(4, "d was not in the put"); }
public ObjectDBException(String aMessage, DBObject aSource) : base(aMessage, null) { source = aSource; }
public void EntryOrder() { DBObject o = new DBObject(); o["u"] = 0; o["m"] = 1; o["p"] = 2; o["i"] = 3; o["r"] = 4; o["e"] = 5; o["s"] = 6; string[] keys = new string[7]; o.Keys.CopyTo(keys, 0); string.Join("", keys).Should().Be("umpires", "keys should be in order added"); List<KeyValuePair<string, object>> pairs = new List<KeyValuePair<string, object>>(o); for (int i = 0; i < 7; i++) { pairs[i].Value.Should().Be(i, "pairs should be in order added"); } }
private static void SetStyleByType(DimStyleTableRecord[] resultStyleName, DBObject item, Dimension y) { if (item is LineAngularDimension2) { Dimension y2 = (LineAngularDimension2)item; y2.DimensionStyleName = resultStyleName[1].Name; } else if (item is DiametricDimension) { Dimension y2 = (DiametricDimension)item; y2.DimensionStyleName = resultStyleName[2].Name; } else if (item is RadialDimension) { Dimension y2 = (RadialDimension)item; y2.DimensionStyleName = resultStyleName[3].Name; } else y.DimensionStyleName = resultStyleName[0].Name; }
public static Type typEnum2Type(DBObject.ObjType type) { return Type.GetType(type.ToString()); }
public void putAll( DBObject o ){ throw new NotSupportedException(); }
public static void RemoveXData(DBObject dbo) { if (dbo.GetXDataForApplication(RegAppNAME) != null) { ResultBuffer rb = rb = new ResultBuffer(new TypedValue(1001, RegAppNAME)); dbo.UpgradeOpen(); dbo.XData = rb; dbo.DowngradeOpen(); } }
public void DBObjectConstructorTest2() { DBObject target = new DBObject(); }
public void DBObjectConstructorTest4() { Dictionary<string, object> m = new Dictionary<string, object>(); m["key"] = "value"; m["foo"] = 1; m["bar"] = null; IDBObject obj = new DBObject(m); obj["key"].Should().Be("value"); obj["foo"].Should().Be(1); obj["bar"].Should().BeNull(); }
public List<Record> GetDataTableRecords(DBObject acadObject) { throw new NotImplementedException(); }
private void SetStyleAnnotative(DimStyleTableRecord[] resultStyleName, DBObject item, Dimension y) { AnnotationScale mainScale = new AnnotationScale(); ObjectContextManager ocm = targetDB.ObjectContextManager; double scale = 2.5 / (y.Dimscale * y.Dimtxt); double difference = 200; if (ocm != null) { ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContext currentContext = occ.CurrentContext; foreach (ObjectContext context in occ) { double currentDifference = 200; AnnotationScale annotScale = (AnnotationScale)context; if (annotScale.Scale == scale) { mainScale = annotScale; break; } else { currentDifference = Math.Abs(scale - annotScale.Scale); if (currentDifference < difference) { difference = currentDifference; mainScale = annotScale; } } } SetStyleByType(resultStyleName, item, y); if (y.HasContext(currentContext)) y.RemoveContext(currentContext); y.AddContext(mainScale); y.Dimtxt = 2.5; } }
private void ProcessTemplate(DBObject template) { DataTable dt = new DataTable(); dt.Columns.Add("Fullname"); dt.Columns.Add("Name"); dt.Columns.Add("Template Address"); //Todo: Find all instances & loop through them adding their addresses to grid dataGridViewResults.DataSource = dt; }
public ObjectDBException(String aMessage, DBObject aSource, Exception aCauseException) : base(aMessage, aCauseException) { source = aSource; }
public List<Record> GetDataTableRecords(DBObject acadObject, Autodesk.Gis.Map.ObjectData.Table oDTable) { throw new NotImplementedException(); }