Point3dCollection ReadPoints(IEnumerable <ObjectId> items, double maxSpacing) { Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; HashSet <Point3d> points = new HashSet <Point3d>(new Point3dComparer(new Tolerance(maxSpacing, maxSpacing))); using (Transaction tr = db.TransactionManager.StartTransaction()) { try { foreach (ObjectId id in items) { // Point if (SelectPoints && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(DBPoint)).UnmanagedObject) { DBPoint item = (DBPoint)tr.GetObject(id, OpenMode.ForRead); points.Add(item.Position); } // Line else if (SelectLines && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Line)).UnmanagedObject) { Line item = (Line)tr.GetObject(id, OpenMode.ForRead); points.Add(item.StartPoint); points.Add(item.EndPoint); } // LW Polyline else if (SelectPolylines && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Polyline)).UnmanagedObject) { Polyline item = (Polyline)tr.GetObject(id, OpenMode.ForRead); for (int i = 0; i < item.NumberOfVertices; i++) { points.Add(item.GetPoint3dAt(i)); } } // 2D Polyline else if (SelectPolylines && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Polyline2d)).UnmanagedObject) { Polyline2d item = (Polyline2d)tr.GetObject(id, OpenMode.ForRead); foreach (ObjectId vId in item) { Vertex2d vertex = (Vertex2d)tr.GetObject(vId, OpenMode.ForRead); points.Add(vertex.Position); } } // 3D Polyline else if (SelectPolylines && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Polyline3d)).UnmanagedObject) { Polyline3d item = (Polyline3d)tr.GetObject(id, OpenMode.ForRead); foreach (ObjectId vId in item) { PolylineVertex3d vertex = (PolylineVertex3d)tr.GetObject(vId, OpenMode.ForRead); points.Add(vertex.Position); } } // Text else if (SelectTexts && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(DBText)).UnmanagedObject) { DBText item = (DBText)tr.GetObject(id, OpenMode.ForRead); points.Add(item.Position); } // Text with Z else if (SelectTextsWithZ && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(DBText)).UnmanagedObject) { DBText item = (DBText)tr.GetObject(id, OpenMode.ForRead); if (double.TryParse(item.TextString, out double z)) { Point3d pt = item.Position; points.Add(new Point3d(pt.X, pt.Y, z)); } } // Blocks else if (SelectBlocks && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(BlockReference)).UnmanagedObject) { BlockReference item = (BlockReference)tr.GetObject(id, OpenMode.ForRead); points.Add(item.Position); } // 3DFace else if (Select3DFace && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Face)).UnmanagedObject) { Face item = (Face)tr.GetObject(id, OpenMode.ForRead); points.Add(item.GetVertexAt(0)); points.Add(item.GetVertexAt(1)); points.Add(item.GetVertexAt(2)); points.Add(item.GetVertexAt(3)); } // PolyFaceMesh else if (SelectPolyfaceMesh && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(PolyFaceMesh)).UnmanagedObject) { PolyFaceMesh item = (PolyFaceMesh)tr.GetObject(id, OpenMode.ForRead); foreach (ObjectId faceId in item) { DBObject obj = tr.GetObject(faceId, OpenMode.ForRead); if (obj is PolyFaceMeshVertex vertex) { points.Add(vertex.Position); } } } // Solid (2D) else if (SelectSolid && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Solid)).UnmanagedObject) { Solid item = (Solid)tr.GetObject(id, OpenMode.ForRead); points.Add(item.GetPointAt(0)); points.Add(item.GetPointAt(1)); points.Add(item.GetPointAt(3)); points.Add(item.GetPointAt(2)); } } } catch (System.Exception ex) { MessageBox.Show("Error: " + ex.ToString(), "XCOM", MessageBoxButtons.OK, MessageBoxIcon.Error); } tr.Commit(); } if (points.Count == 0) { return(new Point3dCollection()); } else { return(new Point3dCollection(points.ToArray())); } }
// The cost of this is high, and will happen every time // a module is loaded and unloaded, but the performance // gain resulting from caching this data is significant // and far outweighs the slight delay imposed whenever // a module is loaded or unloaded. It should be pointed // out that the above event handlers are not added until // the first use of code that uses IsTypeOf<T>, for each // distinct type used as the generic argument. static void Initialize() { instance = RXClass.GetClass(typeof(T)); unmanagedObject = instance.UnmanagedObject; hasChildren = HasChildren(); }
doCleanup1() { //unload xrefs ObjectIdCollection xrefBTRs = xRef.getXRefBlockTableRecords(); BaseObjs._db.UnloadXrefs(xrefBTRs); //unload CIVIL3D2015.dvb try{ acadApp.UnloadDVB(@"C:\TSet\VBA2015\CIVIL3D2015.dvb"); } catch {} Extents3d ext3d = BaseObjs._getExtents; //change view to all VPort.zoomWindow(ext3d); TypedValue[] tvs = new TypedValue[4] { new TypedValue((int)DxfCode.Operator, "<OR"), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(MText)).DxfName), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Leader)).DxfName), new TypedValue((int)DxfCode.Operator, "OR>") }; SelectionSet ss = Select.buildSSet(tvs); ObjectId[] ids = null; if (ss != null) { ids = ss.GetObjectIds(); for (int i = 0; i < ids.Length; i++) { ids[i].clearAllXdata(); } } //explode tvs = new TypedValue[17] { new TypedValue((int)DxfCode.Operator, "<NOT"), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Polyline3d)).DxfName), new TypedValue((int)DxfCode.Operator, "NOT>"), new TypedValue((int)DxfCode.Operator, "<NOT"), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(CogoPoint)).DxfName), new TypedValue((int)DxfCode.Operator, "NOT>"), new TypedValue((int)DxfCode.Operator, "<NOT"), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(MText)).DxfName), new TypedValue((int)DxfCode.Operator, "NOT>"), new TypedValue((int)DxfCode.Operator, "<NOT"), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Leader)).DxfName), new TypedValue((int)DxfCode.Operator, "NOT>"), new TypedValue((int)DxfCode.Operator, "<NOT"), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Wipeout)).DxfName), new TypedValue((int)DxfCode.Operator, "NOT>"), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(BlockReference)).DxfName), new TypedValue((int)DxfCode.Operator, "NOT>") }; ss = Select.buildSSet(tvs, ext3d.MinPoint, ext3d.MaxPoint); if (ss != null) { ids = ss.GetObjectIds(); ObjectIdCollection idsExp = ids.explode(); } //delete breaklines and points //DELETE BREAKLINES tvs = new TypedValue[2] { new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Polyline3d)).DxfName), new TypedValue((int)DxfCode.LayerName, "CPNT-BRKLINE") }; ss = Select.buildSSet(tvs); if (ss != null) { ids = ss.GetObjectIds(); ids.deleteObjs(); } //DELETE COGO POINTS tvs = new TypedValue[1] { new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(CogoPoint)).DxfName), }; ss = Select.buildSSet(tvs); if (ss != null) { ids = ss.GetObjectIds(); ids.deleteObjs(); } //load CIVIL3D2015.dvb try { acadApp.LoadDVB(@"C:\TSet\VBA2015\CIVIL3D2015.dvb"); } catch { } }
doCleanup2() { //unload xrefs ObjectIdCollection xrefBTRs = xRef.getXRefBlockTableRecords(); BaseObjs._db.UnloadXrefs(xrefBTRs); //unload CIVIL3D2015.dvb try { acadApp.UnloadDVB(@"C:\TSet\VBA2015\CIVIL3D2015.dvb"); } catch { } //clear XData on MText and Leaders TypedValue[] tvs = new TypedValue[4] { new TypedValue((int)DxfCode.Operator, "<OR"), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(MText)).DxfName), new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Leader)).DxfName), new TypedValue((int)DxfCode.Operator, "OR>") }; SelectionSet ss = Select.buildSSet(tvs); ObjectId[] ids = ss.GetObjectIds(); for (int i = 0; i < ids.Length; i++) { ids[i].clearAllXdata(); } //idList of MText and Leaders List <ObjectId> idsList = new List <ObjectId>(); for (int i = 0; i < ids.Length; i++) { idsList.Add(ids[i]); } //get all objects PromptSelectionResult psr = BaseObjs._editor.SelectAll(); SelectionSet ssAll = psr.Value; ObjectId[] idsAll = ssAll.GetObjectIds(); //idList of all objects List <ObjectId> idsAllList = new List <ObjectId>(); //all objects for (int i = 0; i < idsAll.Length; i++) { idsAllList.Add(idsAll[i]); } //remove MText and Leaders foreach (ObjectId id in idsList) { idsAllList.Remove(id); //remove MText and Leaders } tvs = new TypedValue[2] { new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Polyline3d)).DxfName), new TypedValue((int)DxfCode.LayerName, "CPNT-BRKLINE") }; ss = Select.buildSSet(tvs); ids = ss.GetObjectIds(); idsList = new List <ObjectId>(); for (int i = 0; i < ids.Length; i++) { idsList.Add(ids[i]); } //remove Brklines foreach (ObjectId id in idsList) { idsAllList.Remove(id); //remove breaklines } tvs = new TypedValue[1] { new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(CogoPoint)).DxfName), }; ss = Select.buildSSet(tvs); ids = ss.GetObjectIds(); idsList = new List <ObjectId>(); for (int i = 0; i < ids.Length; i++) { idsList.Add(ids[i]); } //remove CogoPoints foreach (ObjectId id in idsList) { idsAllList.Remove(id); //remove CogoPoints } //explode remaining entities in list foreach (ObjectId id in idsAllList) { id.explode(); //explode } //Layer.manageLayer("CPNT-BRKLINE", layerFrozen: true); //Layer.manageLayer("CPNT-ON", layerFrozen: true); //ForEach<Surface>(extractContours); //ForEach<Label>(explodeEnt); //ForEach<LabelGroup>(explodeEnt); //ForEach<Surface>(explodeEnt); //ForEach<Surface>(deleteSurface); //ObjectIdCollection idsPV = Prof.getProfileViews(); //foreach (ObjectId idPV in idsPV) // idPV.explode(); //ObjectIdCollection idsAlign = BaseObjs._civDoc.GetAlignmentIds(); //foreach (ObjectId idAlign in idsAlign) // idAlign.delete(); //DELETE BREAKLINES tvs = new TypedValue[2] { new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Polyline3d)).DxfName), new TypedValue((int)DxfCode.LayerName, "CPNT-BRKLINE") }; ss = Select.buildSSet(tvs); ids = ss.GetObjectIds(); ids.deleteObjs(); //DELETE COGO POINTS tvs = new TypedValue[1] { new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(CogoPoint)).DxfName), }; ss = Select.buildSSet(tvs); ids = ss.GetObjectIds(); ids.deleteObjs(); //load CIVIL3D2015.dvb try { acadApp.LoadDVB(@"C:\TSet\VBA2015\CIVIL3D2015.dvb"); } catch { } }
/// <summary> /// 添加图元类型,DXF组码缺省为0 /// </summary> /// <param name="entityType">图元类型</param> public void Add(Type entityType) { base.Add(new TypedValue(0, RXClass.GetClass(entityType).DxfName)); }
public void CalculateSchedule() // This method can have any name { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptSelectionResult psr = doc.Editor.GetSelection(); if (psr.Status == PromptStatus.OK) { if (doc != null) { // ed.WriteMessage("We found 3 phases:-\n\tFrom right to left and left to right together: 1 minute" + // "\n\tFrom right to down: 20 second" + // "\n\tFrom down to left: 25"); } Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { bool firstline = true; Line prevLine = null; double distance = 0; BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); RXClass lineClass = RXClass.GetClass(typeof(Line)); int count = 0; List <Line> myLines = new List <Line>(); foreach (SelectedObject so in psr.Value) { if (so.ObjectId.ObjectClass.IsDerivedFrom(lineClass)) { Line line = (Line)tr.GetObject(so.ObjectId, OpenMode.ForRead); myLines.Add(line); if (!firstline) { distance = line.StartPoint.X - prevLine.StartPoint.X; } //ed.WriteMessage("\nStartPoint: {0} \nEndPoint: {1}\nsteps: {2}", line.StartPoint, line.EndPoint, distance); prevLine = line; firstline = false; } } List <Line> arrowsLines = new List <Line>(); bool newLine; //myLines.Sort(); foreach (Line line1 in myLines) { newLine = true; foreach (Line line2 in myLines) { if (line1.EndPoint == line2.EndPoint && !(line1.StartPoint == line2.StartPoint && line1.EndPoint == line2.EndPoint)) { //get the arrows head lines for (int i = 0; i < arrowsLines.Count; i++) { //to prevent head duplicates if (arrowsLines[i].EndPoint == line1.EndPoint) { newLine = false; } } if (newLine) { arrowsLines.Add(line1); count++; } } } } Line curr; int foundLines; List <Line> nearLines; foreach (Line line1 in arrowsLines) { foundLines = 1; curr = new Line(); curr.EndPoint = line1.EndPoint; nearLines = new List <Line>(); foreach (Line line3 in myLines) { curr.StartPoint = line3.StartPoint; if (curr.Length < 4) { nearLines.Add(line3); } } int i = 0; Line line2; while (curr.EndPoint != line1.StartPoint)// checking ajacents { line2 = nearLines[i]; if (curr.EndPoint == line2.StartPoint && line1 != line2) { foundLines++; curr.EndPoint = line2.EndPoint; ed.WriteMessage(foundLines + "\t"); } else if (curr.EndPoint == line2.EndPoint && line1 != line2) { foundLines++; curr.EndPoint = line2.StartPoint; ed.WriteMessage(foundLines + "\t"); } if (foundLines == 100) { ed.WriteMessage("\ninfinite loop"); break; } i = (i + 1) % nearLines.Count; } if (foundLines == 7 || foundLines == 13 || foundLines == 9)// infinite looooooooooooooop do not start { ed.WriteMessage("real arrow\n"); } } //ed.WriteMessage("\n" + arrowsLines.Count); tr.Commit(); } // There are selected entities // Put your command using pickfirst set code here } else { // There are no selected entities // Put your command code here } }
public static void LayerInfoGrab(IEnumerable <string> LayName, string LayerType, string DocName) { //link to the current document and databases Document Doc = Application.DocumentManager.MdiActiveDocument; Database db = Doc.Database; Editor ed = Doc.Editor; using (Transaction Trans = db.TransactionManager.StartTransaction()) { //Open the block table open for read BlockTable Btr = Trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; //Open the model space database for read BlockTableRecord BtrModel = Trans.GetObject(Btr[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; //Step through the objects and find any on the layer we want foreach (ObjectId ReadObject in BtrModel) { foreach (string LayerName in LayName) { var rxClassline = RXClass.GetClass(typeof(Line)); //Test the object for block type if (ReadObject.ObjectClass.IsDerivedFrom(rxClassline)) { //Open the DBobject Line line = (Line)Trans.GetObject(ReadObject, OpenMode.ForRead); //Check the Dbobject belings to a layer we are intersted in if (line.Layer == LayerName) { //Add data to the table DataCollection.DataConnection.ExcelConnect(line.Handle.Value, line.StartPoint.X, line.EndPoint.X, line.StartPoint.Y, line.EndPoint.Y, double.NaN, double.NaN, "Line", line.Color.Red, line.Color.Blue, line.Color.Green, LayerName, line.Layer, DocName); } } var rxClass_Circle = RXClass.GetClass(typeof(Circle)); //Test the object for block type if (ReadObject.ObjectClass.IsDerivedFrom(rxClass_Circle)) { //Open the DBobject Circle circle = (Circle)Trans.GetObject(ReadObject, OpenMode.ForRead); //Check the Dbobject belings to a layer we are intersted in if (circle.Layer == LayerName) { //Add data to the table //DataCollection.DataConnection.ExcelConnect(circle.Handle.Value, circle.StartPoint.X, circle.EndPoint.X, //double.NaN, double.NaN, circle.Radius, circle., "Circle", circle.Color.Red, circle.Color.Blue, //circle.Color.Green, LayerName, circle.Layer, DocName); } } if (ReadObject is Arc) { //Add data to the table } if (ReadObject is Ellipse) { //Add data to the table } } } //Finalise transaction Trans.Commit(); } }
transferTableData(Document docSrc, Document docTar, Database dbSrc, Database dbTar) { TypedValue[] tvs = new TypedValue[2] { new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Table)).DxfName), new TypedValue((int)DxfCode.LayerName, "ZZ_ZZ-TABLE") }; SelectionFilter filter = new SelectionFilter(tvs); using (var tr = dbTar.TransactionManager.StartOpenCloseTransaction()) { PromptSelectionResult psr = BaseObjs._editor.SelectAll(filter); SelectionSet ss = psr.Value; if (ss == null) { return; } ObjectId[] ids = ss.GetObjectIds(); ObjectId idTableSrc = ids[0]; Table tblSrc = (Table)tr.GetObject(idTableSrc, OpenMode.ForRead); Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument = docTar; psr = BaseObjs._editor.SelectAll(filter); ss = psr.Value; ids = ss.GetObjectIds(); ObjectId idTableTar = ids[0]; Table tblTar = (Table)tr.GetObject(idTableTar, OpenMode.ForWrite); for (int i = 3; i < 14; i++) { for (int j = 0; j < 2; j++) { string val = tblSrc.Cells[i, j].Value.ToString(); if (val != string.Empty) { tblTar.Cells[i, j].Value = val; } } } for (int i = 3; i < 14; i++) { for (int j = 3; j < tblSrc.Columns.Count; j++) { string val = tblSrc.Cells[i, j].Value.ToString(); if (val != string.Empty) { tblTar.Cells[i, j].Value = val; } } } for (int i = 15; i < 23; i++) { string val = tblSrc.Cells[i, 1].Value.ToString(); if (val != string.Empty) { tblTar.Cells[i, 1].Value = val; } } tr.Commit(); } }
/// <summary> /// Let user select a wall and override one display properties of this wall. /// User can see the different display of this wall. /// </summary> public void DisplayPropertiesWallSample() { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("===================================================="); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nDisplay Properties Wall Sample:\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("====================================================\n"); Database db = Application.DocumentManager.MdiActiveDocument.Database; //MaterialUtility. TransactionManager tm = db.TransactionManager; Transaction trans = tm.StartTransaction(); Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; try { PromptEntityOptions optEnt = new PromptEntityOptions("Select an AEC Wall entity"); optEnt.SetRejectMessage("Selected entity is NOT an AEC Wall entity, try again..."); optEnt.AddAllowedClass(typeof(Autodesk.Aec.Arch.DatabaseServices.Wall), false); // Geo is the base class of AEC entities. PromptEntityResult resEnt = ed.GetEntity(optEnt); if (resEnt.Status != PromptStatus.OK) { throw new System.Exception("Selection error - aborting"); } Wall pickedWall = trans.GetObject(resEnt.ObjectId, OpenMode.ForWrite) as Wall; DisplayRepresentationManager displayManager = new DisplayRepresentationManager(db); ObjectIdCollection ids = displayManager.GetDisplayRepresentationIdsFromCurrentViewport(RXClass.GetClass(typeof(Wall))); ObjectId activeDisplayRepId = ids[0]; DisplayPropertiesWallPlan wallProperties = new DisplayPropertiesWallPlan(); wallProperties.SubSetDatabaseDefaults(db); wallProperties.SetToStandard(db); System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection(); DisplayComponent[] components = wallProperties.GetDisplayComponents(out sc); int index = -1; for (int i = 0; i < sc.Count; i++) { string componentName = sc[i]; //Here, we override the display properties for "shrink wrap" and display it on the screen. if (componentName == "Shrink Wrap") { index = i; break; } } if (index == -1) { throw new System.Exception("Lack of display component."); } DisplayComponentEntity component = components[index] as DisplayComponentEntity; component.IsApplicable = true; component.IsVisible = true; component.ByMaterial = false; component.ColorIndex = 30; component.LinetypeScale = 2; component.LineWeight = LineWeight.LineWeight070; ObjectId dispWallId = Override.AddToOverrideExtensionDictionaryAndClose(pickedWall, wallProperties); OverrideDisplayProperties overrideProperties = new OverrideDisplayProperties(); overrideProperties.ViewId = activeDisplayRepId; overrideProperties.DisplayPropertyId = dispWallId; pickedWall.Overrides.Add(overrideProperties); trans.Commit(); } catch (System.Exception e) { trans.Abort(); ed.WriteMessage("\n" + e.Message + "\n"); } }
//Loops through all ODTables in document and creates corresponding PropertySetDefinitions public static void oddatacreatepropertysetsdefs() { DocumentCollection docCol = Application.DocumentManager; Database localDb = docCol.MdiActiveDocument.Database; Editor ed = docCol.MdiActiveDocument.Editor; Document doc = docCol.MdiActiveDocument; CivilDocument civilDoc = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument; //Reference ODTables Tables tables = HostMapApplicationServices.Application.ActiveProject.ODTables; StringCollection tableNames = tables.GetTableNames(); foreach (string name in tableNames) { Table curTable = tables[name]; try { // (1) create prop set def PropertySetDefinition propSetDef = new PropertySetDefinition(); propSetDef.SetToStandard(localDb); propSetDef.SubSetDatabaseDefaults(localDb); // alternatively, you can use dictionary's NewEntry // Dim dictPropSetDef = New DictionaryPropertySetDefinitions(db) // Dim propSetDef As PropertySetDefinition = // dictPropSetDef.NewEntry() // General tab propSetDef.Description = name; // Applies To tab // apply to objects or styles. True if style, False if objects bool isStyle = false; var appliedTo = new StringCollection(); appliedTo.Add("AcDbLine"); appliedTo.Add("AcDbSpline"); appliedTo.Add("AcDbPolyline"); appliedTo.Add("AcDb3dPolyline"); appliedTo.Add(RXClass.GetClass(typeof(BlockReference)).Name); appliedTo.Add(RXClass.GetClass(typeof(DBPoint)).Name); propSetDef.SetAppliesToFilter(appliedTo, isStyle); FieldDefinitions defs = curTable.FieldDefinitions; int defsCount = defs.Count; for (int i = 0; i < defsCount; i++) { FieldDefinition curFd = defs[i]; string fieldDefName = curFd.Name; string fieldDefDescription = curFd.Description; DataType fieldType = curFd.Type; // Definition tab // (2) we can add a set of property definitions. // We first make a container to hold them. // This is the main part. A property set definition can contain // a set of property definition. // (2.1) let's first add manual property. // Here we use text type var propDefManual = new PropertyDefinition(); propDefManual.SetToStandard(localDb); propDefManual.SubSetDatabaseDefaults(localDb); propDefManual.Name = fieldDefName; propDefManual.Description = fieldDefDescription; propDefManual.DataType = GetCorrespondingPropertyDataType(fieldType); propDefManual.DefaultData = ConvertDefaultValue(curFd); // add to the prop set def propSetDef.Definitions.Add(propDefManual); } using (Transaction tx = localDb.TransactionManager.StartTransaction()) { //check if prop set already exists var dictPropSetDef = new DictionaryPropertySetDefinitions(localDb); if (dictPropSetDef.Has(name, tx)) { ed.WriteMessage("\nError - the property set defintion already exists: " + name); tx.Abort(); continue; } dictPropSetDef.AddNewRecord(name, propSetDef); tx.AddNewlyCreatedDBObject(propSetDef, true); tx.Commit(); } } catch (System.Exception ex) { ed.WriteMessage("\nError while creating Property Set definitions: " + ex.ToString()); return; } } ed.WriteMessage("\nFinished!"); }
public static void LayerInfoGrab(IEnumerable <string> LayName, string LayerType, string DocName) { //link to the current document and databases Document Doc = Aapp.DocumentManager.MdiActiveDocument; Database db = Doc.Database; Editor ed = Doc.Editor; using (Transaction Trans = db.TransactionManager.StartTransaction()) { //Open the block table open for read BlockTable Btr = Trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; //Open the model space database for read BlockTableRecord BtrModel = Trans.GetObject(Btr[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; //Open the model space database for write BlockTableRecord BtrModelWrite = Trans.GetObject(Btr[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; /////////////////////////////////////////////////////////////////////////////////// //explode all objects in the model space foreach (ObjectId ReadObject in BtrModel) { //Open the DBobject var dbObj = Trans.GetObject(ReadObject, OpenMode.ForRead); //Check to see if the object is a polyline var rxClassPline = RXClass.GetClass(typeof(Polyline)); //Test the object for entity type if (ReadObject.ObjectClass.IsDerivedFrom(rxClassPline)) { //Open the DBobject Polyline Pline = (Polyline)Trans.GetObject(ReadObject, OpenMode.ForRead); //Collect exploded object parts with this using (DBObjectCollection acDBObjColl = new DBObjectCollection()) { //Explode the object Pline.Explode(acDBObjColl); //save each new entity from the exploded object foreach (Entity acEnt in acDBObjColl) { // Add the new object to the block table record and the transaction BtrModelWrite.AppendEntity(acEnt); Trans.AddNewlyCreatedDBObject(acEnt, true); } } } var rxClassBref = RXClass.GetClass(typeof(BlockReference)); //Test the object for block type if (ReadObject.ObjectClass.IsDerivedFrom(rxClassBref)) { //Open the DBobject BlockReference Bref = (BlockReference)Trans.GetObject(ReadObject, OpenMode.ForRead); //Collect exploded object parts with this using (DBObjectCollection acDBObjColl = new DBObjectCollection()) { Bref.Explode(acDBObjColl); //save each new entity from the exploded object foreach (Entity acEnt in acDBObjColl) { //Add the new objects to the block table record and the transaction BtrModelWrite.AppendEntity(acEnt); Trans.AddNewlyCreatedDBObject(acEnt, true); } } } } /////////////////////////////////////////////////////////////////////// //Step through the objects and find any on the layer we want foreach (ObjectId ReadObject in BtrModel) { foreach (string LayerName in LayName) { var rxClassline = RXClass.GetClass(typeof(Line)); //Test the object for block type if (ReadObject.ObjectClass.IsDerivedFrom(rxClassline)) { //Open the DBobject Line line = (Line)Trans.GetObject(ReadObject, OpenMode.ForRead); //Check the Dbobject belings to a layer we are intersted in if (line.Layer == LayerName) { //Add data to the table DataConnection.ExcelConnect(line.Handle.Value, line.StartPoint.X, line.EndPoint.X, line.StartPoint.Y, line.EndPoint.Y, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, line.Angle, "Line", line.Color.Red, line.Color.Blue, line.Color.Green, LayerName, DocName, line.Thickness, line.Linetype, line.Length); //If the layer type is a property boundary send the info to also confirm the screen shot is near a road if (LayerType == "Pboundary") { Form Psort = new Imaging.SortpBoundaryImages(); } //Else just take screenshots else { Imaging.LineImages.Initiate(db, ed, ReadObject, LayerType, LayerName); } } } var rxClass_Circle = RXClass.GetClass(typeof(Circle)); //Test the object for block type if (ReadObject.ObjectClass.IsDerivedFrom(rxClass_Circle)) { //Open the DBobject Circle circle = (Circle)Trans.GetObject(ReadObject, OpenMode.ForRead); //Check the Dbobject belings to a layer we are intersted in if (circle.Layer == LayerName) { //Add data to the table DataConnection.ExcelConnect(circle.Handle.Value, double.NaN, double.NaN, double.NaN, double.NaN, circle.Center.X, circle.Center.Y, double.NaN, double.NaN, circle.Radius, double.NaN, "Circle", circle.Color.Red, circle.Color.Blue, circle.Color.Green, LayerName, DocName, circle.Thickness, circle.Linetype, double.NaN); } } var rxClass_Arc = RXClass.GetClass(typeof(Arc)); //Test the object for block type if (ReadObject.ObjectClass.IsDerivedFrom(rxClass_Arc)) { //Open the DBobject Arc arc = (Arc)Trans.GetObject(ReadObject, OpenMode.ForRead); //Check the Dbobject belings to a layer we are intersted in if (arc.Layer == LayerName) { //Add data to the table DataConnection.ExcelConnect(arc.Handle.Value, arc.StartPoint.X, arc.EndPoint.X, arc.StartPoint.Y, arc.EndPoint.Y, double.NaN, double.NaN, arc.StartAngle, arc.EndAngle, double.NaN, double.NaN, "Arc", arc.Color.Red, arc.Color.Blue, arc.Color.Green, LayerName, DocName, arc.Thickness, arc.Linetype, arc.Length); } } var rxClass_Ellipse = RXClass.GetClass(typeof(Ellipse)); //Test the object for block type if (ReadObject.ObjectClass.IsDerivedFrom(rxClass_Ellipse)) { //Open the DBobject Ellipse ellipse = (Ellipse)Trans.GetObject(ReadObject, OpenMode.ForRead); //Check the Dbobject belings to a layer we are intersted in if (ellipse.Layer == LayerName) { //Add data to the table DataConnection.ExcelConnect(ellipse.Handle.Value, ellipse.MinorAxis.X, ellipse.MinorAxis.Y, ellipse.MajorAxis.X, ellipse.MajorAxis.Y, ellipse.Center.X, ellipse.Center.Y, ellipse.StartAngle, ellipse.EndAngle, ellipse.MajorRadius, ellipse.MinorRadius, "Ellipse", ellipse.Color.Red, ellipse.Color.Blue, ellipse.Color.Green, LayerName, DocName, double.NaN, ellipse.Linetype, double.NaN); } } } } //Finalise transaction Trans.Commit(); } }
/// <summary> /// Adds the allowed class. /// </summary> /// <param name="type">The type.</param> public void AddAllowedClass(Type type) { ptrs.Add(RXClass.GetClass(type).UnmanagedObject); }
public static void AppendAttributeTest() { Document doc = AcAp.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; try { using (doc.LockDocument()) { using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord currSp = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; PromptNestedEntityOptions pno = new PromptNestedEntityOptions("\nSelect source attribute to append new attribute below this one >>"); PromptNestedEntityResult nres = ed.GetNestedEntity(pno); if (nres.Status != PromptStatus.OK) { return; } ObjectId id = nres.ObjectId; Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead); Point3d pnt = nres.PickedPoint; ObjectId owId = ent.OwnerId; AttributeReference attref = null; if (id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeReference)))) { attref = tr.GetObject(id, OpenMode.ForWrite) as AttributeReference; } BlockTableRecord btr = null; BlockReference bref = null; if (owId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(BlockReference)))) { bref = tr.GetObject(owId, OpenMode.ForWrite) as BlockReference; if (bref.IsDynamicBlock) { btr = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } else { btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } } Point3d insPt = attref.Position.TransformBy(bref.BlockTransform); btr.UpgradeOpen(); ObjectIdCollection bids = new ObjectIdCollection(); AttributeDefinition def = null; foreach (ObjectId defid in btr) { if (defid.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition)))) { def = tr.GetObject(defid, OpenMode.ForRead) as AttributeDefinition; if (def.Tag == attref.Tag) { def.UpgradeOpen(); bids.Add(defid); break; } } } IdMapping map = new IdMapping(); db.DeepCloneObjects(bids, btr.ObjectId, map, true); ObjectIdCollection coll = new ObjectIdCollection(); AttributeDefinition attDef = null; foreach (IdPair pair in map) { if (pair.IsPrimary) { Entity oent = (Entity)tr.GetObject(pair.Value, OpenMode.ForWrite); if (oent != null) { if (pair.Value.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition)))) { attDef = oent as AttributeDefinition; attDef.UpgradeOpen(); attDef.SetPropertiesFrom(def as Entity); // add other properties from source attribute definition to suit here: attDef.Justify = def.Justify; attDef.Position = btr.Origin.Add( new Vector3d(attDef.Position.X, attDef.Position.Y - attDef.Height * 1.25, attDef.Position.Z)).TransformBy(Matrix3d.Identity ); attDef.Tag = "NEW_TAG"; attDef.TextString = "New Prompt"; attDef.TextString = "New Textstring"; coll.Add(oent.ObjectId); } } } } btr.AssumeOwnershipOf(coll); btr.DowngradeOpen(); attDef.Dispose();//optional bref.RecordGraphicsModified(true); tr.TransactionManager.QueueForGraphicsFlush(); doc.TransactionManager.FlushGraphics();//optional ed.UpdateScreen(); tr.Commit(); } } } catch (System.Exception ex) { ed.WriteMessage(ex.Message + "\n" + ex.StackTrace); } finally { AcAp.ShowAlertDialog("Call command \"ATTSYNC\" manually"); } }
public void CreateLerData() { #region Catch no pipelines switch (this.type) { case GraveforespoergselssvartypeType.ingenledningerigraveområde: throw new System.Exception("INGEN ledninger i graveområde!"); case GraveforespoergselssvartypeType.ledningsoplysningerudleveresikke: throw new System.Exception("Leningsoplysninger udleveres ikke!"); case GraveforespoergselssvartypeType.ledningsoplysningerudleveret: break; case GraveforespoergselssvartypeType.udtagettilmanuelbehandling: break; case GraveforespoergselssvartypeType.udtagettilpåvisningledningsoplysningerudleveresikke: break; case GraveforespoergselssvartypeType.udtagettilpåvisningledningsoplysningerudleveret: break; default: break; } #endregion if (this.ledningMember == null) { this.ledningMember = new GraveforespoergselssvarTypeLedningMember[0]; } if (this.ledningstraceMember == null) { this.ledningstraceMember = new GraveforespoergselssvarTypeLedningstraceMember[0]; } if (this.ledningskomponentMember == null) { this.ledningskomponentMember = new GraveforespoergselssvarTypeLedningskomponentMember[0]; } Log.log($"Number of ledningMember -> {this.ledningMember?.Length.ToString()}"); Log.log($"Number of ledningstraceMember -> {this.ledningstraceMember?.Length.ToString()}"); Log.log($"Number of ledningskomponentMember -> {this.ledningskomponentMember?.Length.ToString()}"); #region Create property sets //Dictionary to translate between type name and psName Dictionary <string, string> psDict = new Dictionary <string, string>(); //Create property sets HashSet <Type> allUniqueTypes = ledningMember.Select(x => x.Item.GetType()).Distinct().ToHashSet(); allUniqueTypes.UnionWith(ledningstraceMember.Select(x => x.Ledningstrace.GetType()).Distinct().ToHashSet()); allUniqueTypes.UnionWith(ledningskomponentMember.Select(x => x.Item.GetType()).Distinct().ToHashSet()); foreach (Type type in allUniqueTypes) { string psName = type.Name.Replace("Type", ""); //Store the ps name in dictionary referenced by the type name //PS name is not goood! It becomes Elledning which is not unique //But it is unique!! //Data with different files will still follow the class definition in code //Which assures that all pssets are the same psDict.Add(type.Name, psName); PropertySetDefinition propSetDef = new PropertySetDefinition(); propSetDef.SetToStandard(WorkingDatabase); propSetDef.SubSetDatabaseDefaults(WorkingDatabase); propSetDef.Description = type.FullName; bool isStyle = false; var appliedTo = new StringCollection() { RXClass.GetClass(typeof(Polyline)).Name, RXClass.GetClass(typeof(Polyline3d)).Name, RXClass.GetClass(typeof(DBPoint)).Name, RXClass.GetClass(typeof(Hatch)).Name, }; propSetDef.SetAppliesToFilter(appliedTo, isStyle); var properties = type.GetProperties(); foreach (PropertyInfo prop in properties) { bool include = prop.CustomAttributes.Any(x => x.AttributeType == typeof(Schema.PsInclude)); if (include) { var propDefManual = new PropertyDefinition(); propDefManual.SetToStandard(WorkingDatabase); propDefManual.SubSetDatabaseDefaults(WorkingDatabase); propDefManual.Name = prop.Name; propDefManual.Description = prop.Name; switch (prop.PropertyType.Name) { case nameof(String): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Text; propDefManual.DefaultData = ""; break; case nameof(Boolean): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.TrueFalse; propDefManual.DefaultData = false; break; case nameof(Double): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Real; propDefManual.DefaultData = 0.0; break; case nameof(Int32): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Integer; propDefManual.DefaultData = 0; break; default: propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Text; propDefManual.DefaultData = ""; break; } propSetDef.Definitions.Add(propDefManual); } } using (Transaction tx = WorkingDatabase.TransactionManager.StartTransaction()) { //check if prop set already exists DictionaryPropertySetDefinitions dictPropSetDef = new DictionaryPropertySetDefinitions(WorkingDatabase); if (dictPropSetDef.Has(psName, tx)) { tx.Abort(); continue; } dictPropSetDef.AddNewRecord(psName, propSetDef); tx.AddNewlyCreatedDBObject(propSetDef, true); tx.Commit(); } } #endregion //Debug list of all types in collections HashSet <string> names = new HashSet <string>(); //List of all (new) layers of new entities HashSet <string> layerNames = new HashSet <string>(); foreach (GraveforespoergselssvarTypeLedningMember member in ledningMember) { if (member.Item == null) { Log.log($"ledningMember is null! Some enity has not been deserialized correct!"); continue; } string psName = psDict[member.Item.GetType().Name]; ILerLedning ledning = member.Item as ILerLedning; Oid entityId = ledning.DrawEntity2D(WorkingDatabase); Entity ent = entityId.Go <Entity>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); layerNames.Add(ent.Layer); //Attach the property set PropertySetManager.AttachNonDefinedPropertySet(WorkingDatabase, ent, psName); //Populate the property set var psData = GmlToPropertySet.TranslateGmlToPs(member.Item); PropertySetManager.PopulateNonDefinedPropertySet(WorkingDatabase, ent, psName, psData); //names.Add(member.Item.ToString()); } foreach (GraveforespoergselssvarTypeLedningstraceMember member in ledningstraceMember) { if (member.Ledningstrace == null) { Log.log($"ledningstraceMember is null! Some enity has not been deserialized correct!"); continue; } string psName = psDict[member.Ledningstrace.GetType().Name]; ILerLedning ledning = member.Ledningstrace as ILerLedning; Oid entityId = ledning.DrawEntity2D(WorkingDatabase); Entity ent = entityId.Go <Entity>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); layerNames.Add(ent.Layer); //Attach the property set PropertySetManager.AttachNonDefinedPropertySet(WorkingDatabase, ent, psName); //Populate the property set var psData = GmlToPropertySet.TranslateGmlToPs(member.Ledningstrace); PropertySetManager.PopulateNonDefinedPropertySet(WorkingDatabase, ent, psName, psData); //names.Add(item.Ledningstrace.ToString()); //prdDbg(ObjectDumper.Dump(item.Ledningstrace)); } foreach (GraveforespoergselssvarTypeLedningskomponentMember member in ledningskomponentMember) { if (member.Item == null) { Log.log($"ledningskomponentMember is null! Some enity has not been deserialized correct!"); continue; } string psName = psDict[member.Item.GetType().Name]; ILerKomponent creator = member.Item as ILerKomponent; Oid entityId = creator.DrawComponent(WorkingDatabase); Entity ent = entityId.Go <Entity>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); //Layer names are not analyzed for components currently //layerNames.Add(ent.Layer); //Attach the property set PropertySetManager.AttachNonDefinedPropertySet(WorkingDatabase, ent, psName); //Populate the property set var psData = GmlToPropertySet.TranslateGmlToPs(member.Item); PropertySetManager.PopulateNonDefinedPropertySet(WorkingDatabase, ent, psName, psData); //names.Add(member.Item.ToString()); } foreach (string name in names) { prdDbg(name); } #region Read and assign layer's color //Regex to parse the color information Regex colorRegex = new Regex(@"^(?<R>\d+)\*(?<G>\d+)\*(?<B>\d+)"); //Cache layer table LayerTable lt = WorkingDatabase.LayerTableId.Go <LayerTable>(WorkingDatabase.TransactionManager.TopTransaction); //Set up all LER layers foreach (string layerName in layerNames) { string colorString = ReadStringParameterFromDataTable(layerName, DtKrydsninger, "Farve", 0); Color color; if (colorString.IsNoE()) { Log.log($"Ledning with layer name {layerName} could not get a color!"); color = Color.FromColorIndex(ColorMethod.ByAci, 0); } else if (colorRegex.IsMatch(colorString)) { Match match = colorRegex.Match(colorString); byte R = Convert.ToByte(int.Parse(match.Groups["R"].Value)); byte G = Convert.ToByte(int.Parse(match.Groups["G"].Value)); byte B = Convert.ToByte(int.Parse(match.Groups["B"].Value)); //prdDbg($"Set layer {name} to color: R: {R.ToString()}, G: {G.ToString()}, B: {B.ToString()}"); color = Color.FromRgb(R, G, B); } else { Log.log($"Ledning layer name {layerName} could not parse colorString {colorString}!"); color = Color.FromColorIndex(ColorMethod.ByAci, 0); } LayerTableRecord ltr = lt[layerName] .Go <LayerTableRecord>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); ltr.Color = color; } #endregion #region Read and assign layer's linetype LinetypeTable ltt = (LinetypeTable)WorkingDatabase.TransactionManager.TopTransaction .GetObject(WorkingDatabase.LinetypeTableId, OpenMode.ForWrite); //Check if all line types are present HashSet <string> missingLineTypes = new HashSet <string>(); foreach (string layerName in layerNames) { string lineTypeName = ReadStringParameterFromDataTable(layerName, DtKrydsninger, "LineType", 0); if (lineTypeName.IsNoE()) { continue; } else if (!ltt.Has(lineTypeName)) { missingLineTypes.Add(lineTypeName); } } if (missingLineTypes.Count > 0) { Database ltDb = new Database(false, true); ltDb.ReadDwgFile("X:\\AutoCAD DRI - 01 Civil 3D\\Projection_styles.dwg", FileOpenMode.OpenForReadAndAllShare, false, null); Transaction ltTx = ltDb.TransactionManager.StartTransaction(); Oid destDbMsId = SymbolUtilityServices.GetBlockModelSpaceId(WorkingDatabase); LinetypeTable sourceLtt = (LinetypeTable)ltDb.TransactionManager.TopTransaction .GetObject(ltDb.LinetypeTableId, OpenMode.ForRead); ObjectIdCollection idsToClone = new ObjectIdCollection(); foreach (string missingName in missingLineTypes) { idsToClone.Add(sourceLtt[missingName]); } IdMapping mapping = new IdMapping(); ltDb.WblockCloneObjects(idsToClone, destDbMsId, mapping, DuplicateRecordCloning.Replace, false); ltTx.Commit(); ltTx.Dispose(); ltDb.Dispose(); } Oid lineTypeId; foreach (string layerName in layerNames) { string lineTypeName = ReadStringParameterFromDataTable(layerName, DtKrydsninger, "LineType", 0); if (lineTypeName.IsNoE()) { Log.log($"WARNING! Layer name {layerName} does not have a line type specified!."); //If linetype string is NoE -> CONTINUOUS linetype must be used lineTypeId = ltt["Continuous"]; } else { //the presence of the linetype is assured in previous foreach. lineTypeId = ltt[lineTypeName]; } LayerTableRecord ltr = lt[layerName] .Go <LayerTableRecord>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); ltr.LinetypeObjectId = lineTypeId; } #endregion }
public void Initialize() { Overrule.AddOverrule(RXClass.GetClass(typeof(BlockReference)), this, true); }
static public void transferObjs(string option) { string defExt = ".dwg"; string title = string.Format("Transfer {0}", option); string filter = "All Drawings (*.dwg)|*.dwg"; string dir = Path.GetDirectoryName(BaseObjs.docFullName); string[] files = FileManager.getFiles(defExt, title, filter, dir); if (files == null || files.Length == 0) { return; } Document docTar = BaseObjs._acadDoc; Database dbTar = docTar.Database; Document docSrc = null; Database dbSrc = null; string nameFile = files[0]; string nameUser = ""; int status = FileManager.getFileStatus(nameFile, out nameUser); switch (status) { case (int)filestatus.isOpenLocalReadOnly: case (int)filestatus.isOpenLocal: //connect to db and make transfer foreach (Document doc in BaseObjs._acadDocs) { if (doc.Name == nameFile) { docSrc = doc; dbSrc = docSrc.Database; } } break; case (int)filestatus.isAvailable: //open and make transfer docSrc = DocumentCollectionExtension.Open(BaseObjs._acadDocs, nameFile, true); dbSrc = docSrc.Database; break; case (int)filestatus.isLocked: //open readonly docSrc = DocumentCollectionExtension.Open(BaseObjs._acadDocs, nameFile, true); dbSrc = docSrc.Database; break; } Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument = docSrc; TypedValue[] tvs = null; switch (option) { case "AREAS": tvs = new TypedValue[5] { new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Polyline)).DxfName), new TypedValue((int)DxfCode.Operator, "<OR"), new TypedValue((int)DxfCode.LayerName, "_XX-*"), new TypedValue((int)DxfCode.LayerName, "YY-*"), new TypedValue((int)DxfCode.Operator, "OR>") }; SelectionSet ss = Select.buildSSet(tvs); ObjectId[] ids = ss.GetObjectIds(); FileManager.transferObjects(ids, dbSrc, dbTar); break; case "TABLE": transferTableData(docSrc, docTar, dbSrc, dbTar); break; } Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument = docTar; switch (status) { case (int)filestatus.isAvailable: case (int)filestatus.isLocked: BaseObjs._closeDoc(docSrc, false); break; default: break; } }
public void Terminate() { Overrule.RemoveOverrule(RXClass.GetClass(typeof(BlockReference)), this); }
/// <summary> /// Добавляет подписи к полилиниям, которые созданы из CSV (названия файлов CSV) /// </summary> /// <param name="drawable"></param> /// <param name="wd"></param> /// <returns></returns> public override bool WorldDraw(Drawable drawable, WorldDraw wd) { // draw the base class bool ret = base.WorldDraw(drawable, wd); try { Polyline3d poly = drawable as Polyline3d; if (poly != null) { //Проверить наличие XData string xdata = Utils.GetCaptionFromXData(poly); if (xdata != null) { //Добавить отображение подписи возле первой точки полилинии //poly.DowngradeOpen(); //poly.Database Point3d position = Point3d.Origin; Database db = poly.Database; if (db != null) { using (Transaction tr = db.TransactionManager.StartTransaction()) { ObjectId[] verts = poly.Cast <ObjectId>().ToArray(); PolylineVertex3d vtStart = tr.GetObject(verts[0], OpenMode.ForRead) as PolylineVertex3d; position = vtStart.Position; tr.Commit(); } } else { try { position = poly.StartPoint; } catch (Autodesk.AutoCAD.Runtime.Exception ex) { } } Vector3d normal = Vector3d.ZAxis; Vector3d direction = Vector3d.XAxis; wd.Geometry.Text(position, normal, direction, 5, 1, 0, xdata); } } } catch (System.Exception ex) { CommonException(ex, "Ошибка PolylineCaptionOverrule"); Overrule.RemoveOverrule(RXClass.GetClass(typeof(Polyline3d)), this);//снять Overrule если возникла ошибка ret = false; } // return the base return(ret); //return base.WorldDraw(drawable, wd); }
public void Test2() { // autoCAD file data var doc = AcAp.DocumentManager.MdiActiveDocument; var db = doc.Database; var ed = doc.Editor; //var json = ""; //ed.WriteMessage("hello world\n"); // 数値の入力 PromptStringOptions pStrOpts = new PromptStringOptions("Test2:数字を入力してください。\n"); pStrOpts.AllowSpaces = true; PromptResult pStrRes = doc.Editor.GetString(pStrOpts); if (pStrRes.StringResult != ("")) { inputNumber = int.Parse(pStrRes.StringResult); } ed.WriteMessage("Test2:入力されたのは" + inputNumber.ToString() + "\n"); using (var tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); var opts = new PromptSelectionOptions(); ed.SelectionAdded += new SelectionAddedEventHandler(OnCurveSelectionAdded); var res = ed.GetSelection(opts); if (res.Status == PromptStatus.OK) { List <Polyline> extPolys = new List <Polyline>(); List <Polyline> intPolys = new List <Polyline>(); var selset = res.Value; foreach (var val in selset) { var selobj = val as SelectedObject; var objid = selobj.ObjectId; var crv = tr.GetObject(objid, OpenMode.ForWrite) as Curve; if (crv.Color.IsByLayer) { var layer = tr.GetObject(crv.LayerId, OpenMode.ForRead) as LayerTableRecord; ed.WriteMessage("選択したオブジェクトはレイヤー色になっています。" + inputNumber.ToString() + "\n"); } else { ed.WriteMessage("選択したオブジェクトはレイヤー色になっていません。" + inputNumber.ToString() + "\n"); } } } else { ed.WriteMessage("部材が選択されていません。\n"); } tr.Commit(); // terminate filter ed.SelectionAdded -= new SelectionAddedEventHandler(OnCurveSelectionAdded); } void OnCurveSelectionAdded(object sender, SelectionAddedEventArgs e) { try { ObjectId[] ids = e.AddedObjects.GetObjectIds(); for (int i = 0; i < ids.Length; i++) { if (!ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Curve))) && !ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Leader))) && !ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Line))) && !ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Ray))) && !ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Xline))) && !ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Arc))) && !ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Polyline))) && !ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Polyline2d))) && !ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Polyline3d))) ) { e.Remove(i); } else if (ids[i] == null) { continue; } else { bool tooSmall = false; if (tooSmall) { ed.WriteMessage("切削不可能な部材を除外しました。\n"); e.Remove(i); } else { continue; } } } } catch (NullReferenceException) { //ed.WriteMessage("Emarf: 部材が選択されていません。\n"); } } }
public void ImportEnvData() { Document doc = AcAp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // Local do arquivo de dados: O diretório do .dwg onde está sendo // executado o programa. string curDwgPath = AcAp.GetSystemVariable("DWGPREFIX").ToString(); // Cria um StreamReader para ler o arquivo 'ida.txt', que contém os // dados para inserir os blocos. var fileData = new StreamReader(curDwgPath + "\\ida.txt"); // Diretório dos arquivos '.dwg' dos blocos. Pois, caso o bloco // não exista no desenho atual, o programa irá procurar os blocos // em arquivos '.dwg' externos. String blkPath = curDwgPath; // Armazenará uma linha que será lida do 'ida.txt' string[] sFileLine; // Informações dos blocos, que serão lidos do 'ida.txt' string sBlkId; string sBlkName; Point3d ptBlkOrigin; double dbBlkRot; string sLayer; string sColor; ObjectId idBlkTblRec = ObjectId.Null; BlockTableRecord blkTblRec = null; string[] sBlkAtts; string[] oneAtt; string blkTag; string blkValue; Dictionary <string, string> dicBlkAtts = new Dictionary <string, string>(); using (var tr = db.TransactionManager.StartTransaction()) { BlockTable acBlkTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; // O ModelSpace será usado para gravar em seu Extension Dictionary os Id's e os handles dos blocos. DBObject dbModelSpace = tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite); using (BlockTableRecord acBlkTblRec = (BlockTableRecord)tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead)) { int contId = 0; while (!fileData.EndOfStream) { // sFileLine é uma array que lê uma linha do 'ida.txt' // tendo como separador de colunas ';' sFileLine = fileData.ReadLine().Split(';'); // Atribui os parâmetros de cada bloco que será inserido // baseado no 'ida.txt' sBlkId = Convert.ToString(contId); // O id não é declarado no 'ida.txt' pois este arquivo vem do matlab. sBlkName = sFileLine[0]; dbBlkRot = (Math.PI / 180) * Convert.ToDouble(sFileLine[1]); // Converte graus para radiano // Aqui é usado um Point3d pois é requisitado para criar um 'BlockReference' e não um Point2d. ptBlkOrigin = new Point3d(Convert.ToDouble(sFileLine[2]), Convert.ToDouble(sFileLine[3]), 0); sLayer = sFileLine[4]; sColor = sFileLine[5]; sBlkAtts = sFileLine[6].Split(new string[] { "//" }, StringSplitOptions.None); foreach (var sBlkAtt in sBlkAtts) { oneAtt = sBlkAtt.Split(new string[] { "::" }, StringSplitOptions.None); blkTag = oneAtt[0]; blkValue = oneAtt[1]; dicBlkAtts.Add(blkTag, blkValue); } // Se o bloco não existe no desenho atual if (!acBlkTbl.Has(sBlkName)) { try { using (var blkDb = new Database(false, true)) { // Lê o '.dwg' do bloco, baseado no diretório especificado. blkDb.ReadDwgFile(blkPath + "/" + sBlkName + ".dwg", FileOpenMode.OpenForReadAndAllShare, true, ""); // E então insere o bloco no banco de dados do desenho atual. // Mas ainda não está inserido no desenho. idBlkTblRec = db.Insert(sBlkName, blkDb, true); // Este método retorna o id do bloco. } } catch // Expressão para pegar erros. { } } else { idBlkTblRec = acBlkTbl[sBlkName]; } if (idBlkTblRec != ObjectId.Null) { blkTblRec = idBlkTblRec.GetObject(OpenMode.ForWrite) as BlockTableRecord; using (var trColor = db.TransactionManager.StartOpenCloseTransaction()) { // Altera a cor para "ByBlock" foreach (ObjectId oId in blkTblRec) { Entity ent = (Entity)trColor.GetObject(oId, OpenMode.ForWrite); ent.ColorIndex = 0; } trColor.Commit(); } // Aqui o bloco será adicionado ao desenho e serão gravados // seu id (identificação dada pelo programa atual, começando em 0 e incrementado 1 a 1) // pareado ao seu handle, para o uso dos outros comandos. using (BlockReference acBlkRef = new BlockReference(ptBlkOrigin, idBlkTblRec)) { BlockTableRecord acCurSpaceBlkTblRec; acCurSpaceBlkTblRec = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acCurSpaceBlkTblRec.AppendEntity(acBlkRef); tr.AddNewlyCreatedDBObject(acBlkRef, true); acBlkRef.Rotation = dbBlkRot; acBlkRef.Layer = sLayer; acBlkRef.ColorIndex = Convert.ToInt32(sColor); // Início: Setar atributos do bloco *********************************************************** if (blkTblRec.HasAttributeDefinitions) { RXClass rxClass = RXClass.GetClass(typeof(AttributeDefinition)); foreach (ObjectId idAttDef in blkTblRec) { if (idAttDef.ObjectClass == rxClass) { DBObject obj = tr.GetObject(idAttDef, OpenMode.ForRead); AttributeDefinition ad = obj as AttributeDefinition; AttributeReference ar = new AttributeReference(); ar.SetAttributeFromBlock(ad, acBlkRef.BlockTransform); if (dicBlkAtts.ContainsKey(ar.Tag)) { ar.TextString = dicBlkAtts[ar.Tag]; } acBlkRef.AttributeCollection.AppendAttribute(ar); tr.AddNewlyCreatedDBObject(ar, true); } } // Setar propriedades dos blocos dinâmicos if (acBlkRef.IsDynamicBlock) { DynamicBlockReferencePropertyCollection pc = acBlkRef.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in pc) { if (dicBlkAtts.ContainsKey(prop.PropertyName)) { // Propriedade de distância if (prop.PropertyTypeCode == 1) { prop.Value = Convert.ToDouble(dicBlkAtts[prop.PropertyName]); } // Propriedade visibilidade else if (prop.PropertyTypeCode == 5) { prop.Value = dicBlkAtts[prop.PropertyName]; } } } } } // Fim: Setar atributos do bloco ************************************************************ Entity eBlk = (Entity)tr.GetObject(acBlkRef.Id, OpenMode.ForRead); DBObject blkDb = (DBObject)tr.GetObject(acBlkRef.Id, OpenMode.ForRead); // Grava o id(dado pelo programa - base 0) e o handle do bloco // no Extension Dictionary do ModelSpace. RecOnXDict(dbModelSpace, sBlkId, DxfCode.Handle, eBlk.Handle, tr); // Grava o id do bloco em seu próprio Extension Dictionary, para fazer // uma 'busca reversa' no XDic do ModelSpace depois. RecOnXDict(blkDb, "id", DxfCode.XTextString, sBlkId, tr); } } contId++; dicBlkAtts.Clear(); } } fileData.Close(); tr.Commit(); } }
void DocumentManager_DocumentDestroyed(object sender, DocumentDestroyedEventArgs e) { ObjectOverrule.RemoveOverrule(RXClass.GetClass(typeof(Entity)), this); }