public static void WriteListInDatabase <T>(List <T> entities, CoordinateSystem acutalCS, DBManager.EntityPropertiesAssignment propertyAssignmentMethod, ObjectId layerID, ObjectId blockID, string layerName) { if (entities != null && entities.Count != 0) { Database workingDatabase = HostApplicationServices.WorkingDatabase; Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; ProgressMeter progressMeter = new ProgressMeter(); MessageFilter messageFilter = new MessageFilter(); System.Windows.Forms.Application.AddMessageFilter(messageFilter); List <Triangle> triList = new List <Triangle>(); try { blockID = SymbolUtilityServices.GetBlockModelSpaceId(workingDatabase); if (layerName != null) { layerID = LayerUtil.CreateLayer(layerName, 127, false); } else { layerID = ObjectId.Null; } if (typeof(T) != typeof(Triangle)) { throw new NotImplementedException("Generic list type not supported: " + typeof(T).ToString()); } triList = (List <Triangle>)Convert.ChangeType(entities, typeof(List <Triangle>)); if (acutalCS != null) { Conversions.ToWCS(acutalCS, triList); } progressMeter.SetLimit(entities.Count); progressMeter.Start("Writing database"); using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction()) { LayerTable layerTable = (LayerTable)transaction.GetObject(workingDatabase.LayerTableId, (OpenMode)0); BlockTable blockTable = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)0); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockID, (OpenMode)1); for (int i = 0; i < entities.Count; i++) { Autodesk.AutoCAD.Colors.Color color = null; short colorIndex = 256; Point3d point3d3 = new Point3d(triList[i].Vertex1.X, triList[i].Vertex1.Y, triList[i].Vertex1.Z); Point3d point3d4 = new Point3d(triList[i].Vertex2.X, triList[i].Vertex2.Y, triList[i].Vertex2.Z); Point3d point3d5 = new Point3d(triList[i].Vertex3.X, triList[i].Vertex3.Y, triList[i].Vertex3.Z); Entity entity = new Autodesk.AutoCAD.DatabaseServices.Face(point3d3, point3d4, point3d5, true, true, true, true); if (layerID != ObjectId.Null) { entity.LayerId = (layerID); } if (color == null) { entity.ColorIndex = ((int)colorIndex); } else { entity.Color = (color); } blockTableRecord.AppendEntity(entity); transaction.AddNewlyCreatedDBObject(entity, true); progressMeter.MeterProgress(); messageFilter.CheckMessageFilter((long)i, 10000); } transaction.Commit(); } progressMeter.Stop(); editor.WriteMessage(Environment.NewLine + entities.Count.ToString() + " entities written to database."); editor.WriteMessage("\n"); editor.Regen(); return; } catch { progressMeter.Stop(); throw; } } throw new System.Exception("No entities written in database."); }
public void restore() { isReStoring = true; if (Application.DocumentManager.MdiActiveDocument == null) { return; } Application.DocumentManager.MdiActiveDocument.Database.ObjectAppended -= Database_ObjectAppended; globalProperty = new GlobalProperty(true); Utility.ImportBlocks(); BindEventListener(); showSolution(); BaseModel.ApplicationBaseModels.Clear(); buildings.Clear(); solutions.Clear(); ToolPanel.changedEntityList.Clear(); currentSolution = null; this.LoadMLineStyle(); if (Application.DocumentManager.MdiActiveDocument == null) { return; } //先将所有注册的对象都清空! using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()) { globalProperty.Initialize(); Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { //首先重建所有的Solution LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForWrite, false); foreach (ObjectId layerId in lt) { //设置图层颜色 LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(layerId, OpenMode.ForWrite); Dictionary <String, String> pairs = BaseModel.Load(layerId); if (pairs != null && pairs.ContainsKey("type") && pairs["type"].CompareTo("solution") == 0) { ChromeTabItem chrometabitem = solutionPanel.chrometabs.RestoreTab(new System.Windows.Controls.Label(), false); chrometabitem.CanDelete = true; solutionPanel.AddCloseHandler(chrometabitem); Solution solution = new Solution(false); solution.ResetAttributes(pairs, layerId); solution.RestoreAttributes(); solution.TabItem = chrometabitem; chrometabitem.Header = solution.SolutionName; solutions.Add(solution); } else if (ltr.Name != "our_outline_layer" && (pairs == null || !pairs.ContainsKey("type"))) { ltr.Color = Autodesk.AutoCAD.Colors.Color.FromColor(System.Drawing.Color.Gray); } } trans.Commit(); trans.Dispose(); } using (Transaction trans1 = db.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForWrite); foreach (var layerid in lt) { LayerTableRecord ltr = (LayerTableRecord)layerid.GetObject(OpenMode.ForRead); if (ltr.Name.Contains("outline_layer") || ltr.Name.Contains("方案")) { TypedValue[] tvs = new TypedValue[1] { new TypedValue((int)DxfCode.LayerName, (ltr.Name)) }; SelectionFilter sf = new SelectionFilter(tvs); PromptSelectionResult psr = ed.SelectAll(sf); if (psr.Value != null) { foreach (var objectid in psr.Value.GetObjectIds()) { Dictionary <String, String> pairs = BaseModel.Load(objectid); if (pairs != null && pairs.ContainsKey("type")) { String type = pairs["type"]; if (type.CompareTo(Building.modelType) == 0) { Building b = new Building(false); b.ResetAttributes(pairs, objectid); buildings.Add(objectid, b); } else if (type.CompareTo(HeatProducer.modelType) == 0) { var b = new HeatProducer(); b.ResetAttributes(pairs, objectid); } else if (type.CompareTo(SubStation.modelType) == 0) { var b = new SubStation(); b.ResetAttributes(pairs, objectid); } else if (type.CompareTo(PipeLine.modelType) == 0) { var b = new PipeLine(); b.ResetAttributes(pairs, objectid); b.RetriveMline(); } else if (type.CompareTo(District.modelType) == 0) { var d = new District(); d.ResetAttributes(pairs, objectid); } } } } } } trans1.Dispose(); } using (Transaction trans2 = db.TransactionManager.StartTransaction()) { //然后遍历所有的管道结头 DBDictionary groups = trans2.GetObject(db.GroupDictionaryId, OpenMode.ForRead) as DBDictionary; foreach (DBDictionaryEntry entry in groups) { ObjectId objId = entry.Value; Dictionary <String, String> pairs = BaseModel.Load(objId); if (pairs != null && pairs.ContainsKey("type")) { string type = pairs["type"]; if (type.CompareTo(SimplePipeJoint.modelType) == 0) { var b = new SimplePipeJoint(); b.ResetAttributes(pairs, objId); b.Retrive(); } if (type.CompareTo(MultiPipeJoint.modelType) == 0) { var b = new MultiPipeJoint(); b.ResetAttributes(pairs, objId); b.Retrive(); } } // } } trans2.Dispose(); } foreach (var item in BaseModel.ApplicationBaseModels) { item.Value.RestoreAttributes(); } if (globalProperty.ActiveTab == -1 || globalProperty.ActiveTab == 0) { solutionPanel.SelectOutLineLayer(); HeatSourceLayoutApp.currentSolution = null; } else { foreach (var i_solution in solutions) { if (i_solution.SId == globalProperty.ActiveTab) { solutionPanel.chrometabs.ChangeSelectedItem(i_solution.TabItem); HeatSourceLayoutApp.currentSolution = i_solution; break; } } } } isReStoring = false; Application.DocumentManager.MdiActiveDocument.Database.ObjectAppended += Database_ObjectAppended; }
public static DBObject Create(this Grevit.Types.Wall w, Transaction tr, Grevit.Types.Point from = null, Grevit.Types.Point to = null) { DictionaryWallStyle ws = new DictionaryWallStyle(Command.Database); try { if (from == null && to == null && w.curve.GetType() == typeof(Grevit.Types.PLine)) { Grevit.Types.PLine pline = (Grevit.Types.PLine)w.curve; for (int i = 0; i < pline.points.Count; i++) { if (i == pline.points.Count - 1) { if (pline.closed) { w.Create(tr, pline.points[i], pline.points[0]); } } else { w.Create(tr, pline.points[i], pline.points[i + 1]); } } } else { Wall wall = new Wall(); LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead); bool newEnt = false; if (Command.existing_objects.ContainsKey(w.GID)) { wall = (Wall)tr.GetObject(Command.existing_objects[w.GID], OpenMode.ForWrite); } else { wall.SetDatabaseDefaults(Command.Database); wall.SetToStandard(Command.Database); newEnt = true; wall.JustificationType = WallJustificationType.Center; } if (w.TypeOrLayer != "") { if (lt.Has(w.TypeOrLayer)) { wall.LayerId = lt[w.TypeOrLayer]; } } if (ws.Has(w.FamilyOrStyle, tr)) { wall.StyleId = ws.GetAt(w.FamilyOrStyle); } if (from != null && to != null) { wall.Set(from.ToPoint3d(), to.ToPoint3d(), Vector3d.ZAxis); } else { if (w.curve.GetType() == typeof(Grevit.Types.Line)) { Grevit.Types.Line baseline = (Grevit.Types.Line)w.curve; wall.Set(baseline.from.ToPoint3d(), baseline.to.ToPoint3d(), Vector3d.ZAxis); } else if (w.curve.GetType() == typeof(Grevit.Types.Arc)) { Grevit.Types.Arc baseline = (Grevit.Types.Arc)w.curve; CircularArc3d arc = new CircularArc3d(baseline.center.ToPoint3d(), Vector3d.ZAxis, Vector3d.ZAxis, baseline.radius, baseline.start, baseline.end); wall.Set(arc, Vector3d.ZAxis); } else if (w.curve.GetType() == typeof(Grevit.Types.Curve3Points)) { Grevit.Types.Curve3Points baseline = (Grevit.Types.Curve3Points)w.curve; wall.Set(baseline.a.ToPoint3d(), baseline.b.ToPoint3d(), baseline.c.ToPoint3d(), Vector3d.ZAxis); } } wall.BaseHeight = w.height; if (newEnt) { BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); ms.AppendEntity(wall); tr.AddNewlyCreatedDBObject(wall, true); } return(wall); } } catch (Autodesk.AutoCAD.Runtime.Exception e) { } return(null); }
public static DBObject Create(this Grevit.Types.Slab s, Transaction tr) { try { BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); // Polyline acPoly = new Polyline(); //acPoly.SetDatabaseDefaults(); //int i = 0; DBObjectCollection objColl = new DBObjectCollection(); Point3dCollection ptcol = new Point3dCollection(); foreach (Grevit.Types.Loop loop in s.surface.profile) { foreach (Grevit.Types.Component p in loop.outline) { ptcol = p.To3dPointCollection(); } //Curve3dCollection collt = parse3dCurve(p); //acPoly.AppendVertex(new PolylineVertex3d(new Point3d(p.x, p.y, p.z))); //acPoly.AddVertexAt(i, new Point2d(p.x, p.y), 0, 0, 0); //i++; //foreach (Curve3d curve in collt) //{ // objColl.Add(Autodesk.AutoCAD.DatabaseServices.Curve.CreateFromGeCurve(curve)); //} } Polyline3d face = new Polyline3d(Poly3dType.SimplePoly, ptcol, true); objColl.Add(face); //Polyline3d face = new Polyline3d(); //ETC... // or from your settings // Polyline3d face = new Polyline3d(Poly3dType.SimplePoly, vertices, true); DBObjectCollection myRegionColl = new DBObjectCollection(); // create a single region Autodesk.AutoCAD.DatabaseServices.Region objreg = new Autodesk.AutoCAD.DatabaseServices.Region(); DBObjectCollection objRegions = new DBObjectCollection(); try { objRegions = Autodesk.AutoCAD.DatabaseServices.Region.CreateFromCurves(objColl); objreg = objRegions[0] as Autodesk.AutoCAD.DatabaseServices.Region; } catch (Autodesk.AutoCAD.Runtime.Exception ex) { // eInvalidInput exception Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Error: unable to create region collection:\n" + ex.Message); } //acPoly.Closed = true; //ms.AppendEntity(acPoly); //tr.AddNewlyCreatedDBObject(acPoly, true); //atrix3d mm = Matrix3d.Displacement(new Vector3d(0, 0, r.outline[0].z)); //acPoly.TransformBy(mm); //Autodesk.Aec.Geometry.Profile myProfile = Autodesk.Aec.Geometry.Profile.CreateFromEntity(acPoly, ed.CurrentUserCoordinateSystem); //Slab slab = new Slab(); //slab.SetDatabaseDefaults(db); //slab.SetToStandard(db); //slab.Location = new Point3d(0, 0, 0); //slab.SetBaseProfile(myProfile, Matrix3d.Identity); //DBObjectCollection col = acPoly.GetOffsetCurves(0); //DBObjectCollection res = Region.CreateFromCurves(coll); //Region reg = res[0] as Region; Solid3d solid = new Solid3d(); solid.Extrude(objreg, s.height, s.slope); LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead); if (s.TypeOrLayer != "") { if (lt.Has(s.TypeOrLayer)) { solid.LayerId = lt[s.TypeOrLayer]; } } //if (ss.Has(r.family, tr)) slab.StyleId = ss.GetAt(r.family); ms.AppendEntity(solid); tr.AddNewlyCreatedDBObject(solid, true); return(solid); } catch (Autodesk.AutoCAD.Runtime.Exception e) { } return(null); }
public override String Process() { Regex pattern1 = new Regex(@"^[ACDFIJKNTVWX][0-9][0-9][0-9][0-9][0-9][0-9][A-Z]?((-|–)[0-9][0-9]?)?$"); Regex pattern2 = new Regex(@"^[ABCDEGHKLNPRUTZ][0-9][0-9][0-9][0-9]?((-|–)[0-9][0-9]?)?$"); Regex pattern3 = new Regex(@"^[0-9][0-9][0-9][0-9][0-9][0-9][A-Z]?((-|–)([0-9]|[A-Z]))?$"); Int32 numErrorsPerDWG = 0, numErrorsTotal = 0; FileInfo textReport; //if (!CheckDirPath()) { return "Invalid path: " + _Path; } try { BeforeProcessing(); } catch (System.Exception se) { return("Layer Checker processing exception: " + se.Message); } try { textReport = new FileInfo(_Path + "\\dwgsource_check_" + DateTime.Now.ToString("ddHHmmss") + ".txt"); writer = new StreamWriter(textReport.FullName); } catch { _Logger.Dispose(); return("Could not open checker log file in: " + _Path); } //try { _Logger = new Logger(_Path + "\\LayerCheckerErrorLog.txt"); } //catch { return "Could not create error log file in: " + _Path; } //StartTimer(); #region Get dwgs and create checked dir if multi dir box is checked if (MultiDir) { try { IEnumerable <String> dirList = Directory.EnumerateDirectories(_Path); Directory.CreateDirectory(_Path + "\\checked\\"); foreach (String dirToCopy in dirList) { if (dirToCopy.Contains("checked")) { continue; } Directory.CreateDirectory(String.Concat(_Path, "\\checked\\", dirToCopy.Substring(dirToCopy.LastIndexOf("\\") + 1))); } } catch (System.Exception se) { _Logger.Log("Error re-creating directory structure in new folder in: " + _Path + " because: " + se.Message); return("Error re-creating directory structure in new folder in: " + _Path); } try { GetDwgList(SearchOption.AllDirectories, (inFileStr) => !inFileStr.Contains("\\checked\\")); } catch (System.Exception se) { _Logger.Log(" Not all .dwg files could be enumerated because: " + se.Message); return("Could not get all DWG files"); } } else { try { GetDwgList(SearchOption.TopDirectoryOnly); } catch (System.Exception se) { _Logger.Log(" Not all DWG files could be enumerated because: " + se.Message); return("Could not get all dwg files in: " + _Path); } } #endregion try { foreach (String currentDWG in DwgList) { Database oldDb = HostApplicationServices.WorkingDatabase; StringBuilder currentDwgErrors = new StringBuilder(); numErrorsPerDWG = 0; String ms = ""; using (Database db = new Database(false, true)) { try { db.ReadDwgFile(currentDWG, FileOpenMode.OpenForReadAndWriteNoShare, true, String.Empty); db.CloseInput(true); } catch (System.Exception se) { _Logger.Log("Could not read DWG: " + currentDWG + " because: " + se.Message); continue; } using (Transaction acTrans = db.TransactionManager.StartTransaction()) { using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable) { if (MakeChanges) { db.Clayer = lt["0"]; } foreach (ObjectId layerId in lt) { LayerTableRecord layer = acTrans.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord; String curLayerName = layer.Name.ToUpper().Trim(); if (curLayerName.Equals("FILENAME")) { ms = Utilities.msText(db, "FILENAME"); } if (curLayerName.Equals("MSNUM")) { ms = Utilities.msText(db, "MSNUM"); } if (MakeChanges) { layer.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255); } if ((String.Equals(curLayerName, "0")) || (String.Equals(curLayerName, "DEFPOINTS")) || (String.Equals(curLayerName, "COLUMN")) || (String.Equals(curLayerName, "ST_TABLE_VISIBLE")) || (String.Equals(curLayerName, "ST_TABLE_INVISIBLE")) || (String.Equals(curLayerName, System.IO.Path.GetFileNameWithoutExtension(currentDWG).ToUpper().Trim())) ) { if (MakeChanges) { layer.IsLocked = false; if (layer.IsFrozen) { layer.IsFrozen = false; } if (String.Equals(curLayerName, "ST_TABLE_INVISIBLE")) { layer.IsOff = true; } else { layer.IsOff = false; } } } else { if ((String.Equals(curLayerName, "IADS_HOTSPOTS")) || (String.Equals(curLayerName, "TEMPLATE")) || (String.Equals(curLayerName, "ST_AUTOCONVERT_MARKERS")) || (String.Equals(curLayerName, "ZONE")) || (String.Equals(curLayerName, "FILENAME")) || (String.Equals(curLayerName, "SCALE")) || (String.Equals(curLayerName, "MSNUM")) || (curLayerName.StartsWith("REF_")) || (((pattern1.IsMatch(curLayerName)) || (pattern2.IsMatch(curLayerName)) || (pattern3.IsMatch(curLayerName))) && (!System.IO.Path.GetFileNameWithoutExtension(currentDWG).ToUpper().Equals(curLayerName)) )) { if (MakeChanges) { layer.IsLocked = false; Utilities.delLayer(db, layer.Name, layer); } } else { currentDwgErrors.Append(layer.Name + "\t\t\t" + ms + Environment.NewLine); numErrorsPerDWG++; } } layer.Dispose(); } } acTrans.Commit(); } if (MultiDir) { try { // Dwg is in subdir if (!String.Equals(Path.GetDirectoryName(currentDWG), _Path)) { //Get subdir path and subdir name String subdir = Path.GetDirectoryName(currentDWG); String subdirName = subdir.Substring(subdir.LastIndexOf("\\")); db.SaveAs(Path.GetDirectoryName(subdir) + "\\checked" + subdirName + "\\" + Path.GetFileName(currentDWG), DwgVersion.Current); } // Dwg is in top dir else { db.SaveAs(_Path + "\\" + Path.GetFileName(currentDWG), DwgVersion.Current); } } catch (System.Exception se) { _Logger.Log(currentDWG + " could not be saved because: " + se.Message); } } else { try { db.SaveAs(currentDWG, DwgVersion.Current); } catch (System.Exception se) { _Logger.Log(currentDWG + " could not be saved because: " + se.Message); } } HostApplicationServices.WorkingDatabase = oldDb; } numErrorsTotal += numErrorsPerDWG; if (numErrorsPerDWG > 0) { currentDwgErrors.Insert(0, Utilities.nl + currentDWG + Utilities.nl + "--------" + Utilities.nl); writer.Write(currentDwgErrors); } DwgCounter++; try { _Bw.ReportProgress(Utilities.GetPercentage(DwgCounter, NumDwgs)); } catch { } if (_Bw.CancellationPending) { _Logger.Log("Layer Checking cancelled by user at dwg " + DwgCounter + " out of " + NumDwgs); break; } } } catch (System.Exception se) { _Logger.Log("Processing Exception: " + se.Message); return("Processing Exception: " + se.Message); } finally { try { writer.Close(); } catch (System.Exception se) { _Logger.Log("Couldn't close layer check file because: " + se.Message); } if (numErrorsTotal < 1) { try { textReport.Delete(); } catch { _Logger.Log("Couldn't delete empty check file"); } } AfterProcessing(); } return(String.Concat(DwgCounter.ToString(), " out of ", NumDwgs.ToString(), " dwgs processed in ", TimePassed, ". ", (_Logger.ErrorCount > 0) ? ("Error Log: " + _Logger.Path) : ("No errors found."))); }
public static void ImportAsXref() { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; bool Aborted = false; SaveFileDialog sfd; ObjectId SurveyTextStyle; //Make all the drawing changes using (DocumentLock dl = acDoc.LockDocument()) { using (Transaction tr = acDoc.Database.TransactionManager.StartTransaction()) { //Remove all sheets ObjectId newLayout = LayoutManager.Current.CreateLayout("Paper"); LayoutManager.Current.SetCurrentLayoutId(newLayout); DBDictionary lays = tr.GetObject(acDoc.Database.LayoutDictionaryId, OpenMode.ForWrite) as DBDictionary; foreach (DBDictionaryEntry item in lays) { string layoutName = item.Key; if (layoutName != "Model" && layoutName != "Paper") { LayoutManager.Current.DeleteLayout(layoutName); // Delete layout. } } //Get or create the survey text style TextStyleTable tst = tr.GetObject(acDoc.Database.TextStyleTableId, OpenMode.ForRead) as TextStyleTable; if (!tst.Has("JPP_Survey")) { tst.UpgradeOpen(); TextStyleTableRecord tstr = new TextStyleTableRecord(); tstr.FileName = "romans.shx"; tstr.Name = "JPP_Survey"; tst.Add(tstr); tr.AddNewlyCreatedDBObject(tstr, true); } SurveyTextStyle = tst["JPP_Survey"]; //Get all model space drawing objects TypedValue[] tv = new TypedValue[1]; tv.SetValue(new TypedValue(67, 0), 0); SelectionFilter sf = new SelectionFilter(tv); PromptSelectionResult psr = acDoc.Editor.SelectAll(sf); //Lengthy operations so show progress bar ProgressMeter pm = new ProgressMeter(); Byte alpha = (Byte)(255 * (1)); Transparency trans = new Transparency(alpha); //Iterate over all layer and set them to color 8, 0 transparency and continuous linetype // Open the Layer table for read LayerTable acLyrTbl = tr.GetObject(acDoc.Database.LayerTableId, OpenMode.ForRead) as LayerTable; int layerCount = 0; foreach (ObjectId id in acLyrTbl) { layerCount++; } pm = new ProgressMeter(); pm.Start("Updating layers..."); pm.SetLimit(layerCount); foreach (ObjectId id in acLyrTbl) { LayerTableRecord ltr = tr.GetObject(id, OpenMode.ForWrite) as LayerTableRecord; ltr.IsLocked = false; ltr.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByColor, 8); ltr.LinetypeObjectId = acDoc.Database.ContinuousLinetype; ltr.LineWeight = acDoc.Database.Celweight; ltr.Transparency = trans; pm.MeterProgress(); System.Windows.Forms.Application.DoEvents(); } pm.Stop(); pm.Start("Updating objects..."); pm.SetLimit(psr.Value.Count); foreach (SelectedObject so in psr.Value) { //For each object set its color, transparency, lineweight and linetype to ByLayer Entity obj = tr.GetObject(so.ObjectId, OpenMode.ForWrite) as Entity; obj.ColorIndex = 256; obj.LinetypeId = acDoc.Database.Celtype; obj.LineWeight = acDoc.Database.Celweight; pm.MeterProgress(); System.Windows.Forms.Application.DoEvents(); if (obj is Polyline) { Polyline pl = obj as Polyline; pl.Elevation = 0; } if (obj is Polyline2d) { Polyline2d pl = obj as Polyline2d; pl.Elevation = 0; } if (obj is Polyline3d) { Polyline3d pl3d = obj as Polyline3d; foreach (ObjectId id in pl3d) { PolylineVertex3d plv3d = tr.GetObject(id, OpenMode.ForWrite) as PolylineVertex3d; Point3d p3d = plv3d.Position; plv3d.Position = new Point3d(p3d.X, p3d.Y, 0); } } //Change all text to Romans if (obj is DBText) { DBText text = obj as DBText; text.Position = new Point3d(text.Position.X, text.Position.Y, 0); text.Height = 0.4; text.TextStyleId = SurveyTextStyle; } if (obj is MText) { MText text = obj as MText; text.Location = new Point3d(text.Location.X, text.Location.Y, 0); text.Height = 0.4; text.TextStyleId = SurveyTextStyle; } } pm.Stop(); //Operate over all blocks BlockTable blkTable = (BlockTable)tr.GetObject(acDoc.Database.BlockTableId, OpenMode.ForRead); int blockCount = 0; foreach (ObjectId id in blkTable) { blockCount++; } pm = new ProgressMeter(); pm.Start("Updating blocks..."); pm.SetLimit(blockCount); foreach (ObjectId id in blkTable) { BlockTableRecord btRecord = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead); if (!btRecord.IsLayout) { foreach (ObjectId childId in btRecord) { //For each object set its color, transparency, lineweight and linetype to ByLayer Entity obj = tr.GetObject(childId, OpenMode.ForWrite) as Entity; obj.ColorIndex = 256; obj.LinetypeId = acDoc.Database.Celtype; obj.LineWeight = acDoc.Database.Celweight; //Adjust Z values } } pm.MeterProgress(); System.Windows.Forms.Application.DoEvents(); } pm.Stop(); //Run the cleanup commands Core.Utilities.Purge(); acDoc.Database.Audit(true, false); //Prompt for the save location sfd = new SaveFileDialog(); sfd.Filter = "Drawing File|*.dwg"; sfd.Title = "Save drawing as"; sfd.ShowDialog(); if (sfd.FileName != "") { tr.Commit(); Aborted = false; } else { tr.Abort(); Aborted = true; } } } if (!Aborted) { acDoc.Database.SaveAs(sfd.FileName, Autodesk.AutoCAD.DatabaseServices.DwgVersion.Current); //Close the original file as its no longer needed acDoc.CloseAndDiscard(); } }
public static void SetAllText() { Database db = HostApplicationServices.WorkingDatabase; List <DBText> dbTextList = new List <DBText>(); Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; using (Transaction trans = db.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead); List <DBText> allText = new List <DBText>(); List <Circle> allCircle = new List <Circle>(); BlockTableRecord ltr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForRead); foreach (ObjectId objId in ltr) { Entity ent = (Entity)trans.GetObject(objId, OpenMode.ForRead); if (ent.GetType().Name == "DBText") { var text = (DBText)ent; if (text.TextString.Contains("A") || text.TextString.Contains("B") || text.TextString.Contains("C") || text.TextString.Contains("K") || text.TextString.Contains("L") || text.TextString.Contains("P") || text.TextString.Contains("T")) { allText.Add(text); } } else if (ent.GetType().Name == "Circle") { allCircle.Add((Circle)ent); } } StringBuilder builder = new StringBuilder(); BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); foreach (var text in allText) { Circle circle = GetClosedCircle(allCircle, text); if (circle != null) { int lineCount = 0; int polylineCount = 0; int circleCount = 0; int hatchCount = 0; int arcCount = 0; string textString = ""; var selectionResult = ed.SelectWindow(circle.GeometricExtents.MinPoint, circle.GeometricExtents.MaxPoint).Value; if (selectionResult != null) { var ids = selectionResult.GetObjectIds(); foreach (var id in ids) { var entity = trans.GetObject(id, OpenMode.ForWrite); if (entity.GetType().Name == "Line") { lineCount++; } else if (entity.GetType().Name == "Circle") { circleCount++; } else if (entity.GetType().Name == "DBText") { var dbText = (DBText)entity; textString += "," + dbText.TextString; } else if (entity.GetType().Name == "Hatch") { hatchCount++; } else if (entity.GetType().Name == "Polyline") { polylineCount++; } else if (entity.GetType().Name == "Arc") { arcCount++; } else { var name = entity.GetType().Name; } } } var type = "无图例"; if (lineCount == 8 && circleCount == 4) { type = "地下室抗拔桩"; } else if (circleCount == 10 && hatchCount == 5) { type = "地下室柱下桩"; } else if (circleCount == 7 && hatchCount == 7) { type = "抗拔桩试桩TP2"; } else if (lineCount == 49 && circleCount == 7) { type = "抗拔桩反力桩AP2"; } else if (circleCount == 1 && hatchCount == 1) { type = "A型桩试桩TP1"; } else if (circleCount == 1 && hatchCount == 4) { type = "主楼抗压桩B型"; } builder.AppendLine(string.Format("{0},{1},{2},{3}", text.TextString, circle.Center.X / 304.8, circle.Center.Y / 304.8, type)); //builder.AppendLine(string.Format("lineCount:{0},circleCount:{1},hatchCount:{2},textString:{3},polylineCount:{4},arcCount:{5}", lineCount, circleCount, hatchCount, textString, polylineCount, arcCount)); //var newText = new DBText(); //newText.Position = circle.Center; //newText.TextString = text.TextString; //newText.Height = text.Height; //dbTextList.Add(newText); //btr.AppendEntity(newText); //try { // trans.AddNewlyCreatedDBObject(newText, true); //} catch (System.Exception ex) { // throw ex; //} } else { builder.AppendLine(string.Format("文字:{0}", text.TextString)); builder.AppendLine("圆点:没有啊"); } } string path = @"C:\acadacad.text"; if (File.Exists(path)) { File.Delete(path); } StreamWriter rw = File.CreateText(path); rw.WriteLine(builder.ToString()); rw.Flush(); rw.Close(); ed.WriteMessage("搞定 收工"); trans.Commit(); } }
public override String Process() { Regex FileFormat = new System.Text.RegularExpressions.Regex(@"^m(\d){6}([a-z]{0,2})?$"); Regex LayerFormat = new System.Text.RegularExpressions.Regex(@"^m(\d){6}([a-z]){0,2}-(\w){1,2}$"); try { BeforeProcessing(); } catch (System.Exception se) { return("RPSTL Delivery processing exception: " + se.Message); } if (String.IsNullOrWhiteSpace(Suffix)) { return("Invalid Suffix"); } // Get all DWG files try { GetDwgList(SearchOption.TopDirectoryOnly); } catch (SystemException se) { _Logger.Log(" DWG files could not be enumerated because: " + se.Message); _Logger.Dispose(); return(" DWG files could not be enumerated because: " + se.Message); } try { foreach (String currentDWG in DwgList) { Boolean found0 = false; Boolean foundGType = false; Boolean foundmx0 = false; ObjectId foundmx0Id = new ObjectId(); Boolean foundmxSuffix = false; String newfi = ""; List <String> LayersForDelete = new List <String>(); if (_Bw.CancellationPending) { _Logger.Log("Processing cancelled at dwg " + currentDWG + " out of " + NumDwgs); return("Processing cancelled at dwg " + DwgCounter.ToString() + " out of " + NumDwgs); } DwgCounter++; try { _Bw.ReportProgress(Utilities.GetPercentage(DwgCounter, NumDwgs)); } catch { _Logger.Log("Progress bar report error"); } using (Database db = new Database(false, true)) { try { db.ReadDwgFile(currentDWG, FileOpenMode.OpenForReadAndWriteNoShare, true, String.Empty); db.CloseInput(true); } catch (Autodesk.AutoCAD.Runtime.Exception e) { _Logger.Log("Could not read DWG: " + currentDWG + " because: " + e.Message); continue; } if (!FileFormat.IsMatch(System.IO.Path.GetFileNameWithoutExtension(db.Filename))) { _Logger.Log("Skipping: " + db.Filename + " because of incorrect name format"); continue; } String dwgMsName = System.IO.Path.GetFileNameWithoutExtension(db.Filename).Trim(); using (Transaction acTrans = db.TransactionManager.StartTransaction()) { using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable) { foreach (ObjectId oid in lt) { using (LayerTableRecord ltr = acTrans.GetObject(oid, OpenMode.ForWrite) as LayerTableRecord) { String layerName = ltr.Name.Trim(); ltr.IsLocked = false; if (String.Equals(layerName, "0")) { found0 = true; db.Clayer = ltr.Id; ltr.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255); continue; } if (String.Equals(layerName, "_GTYPE_RPSTL")) { foundGType = true; LayersForDelete.Add(ltr.Name); continue; } if (Regex.IsMatch(layerName, @"^m(\d){6}([a-z]){0,2}-0") && String.Equals(layerName.Remove(layerName.LastIndexOf('-')), dwgMsName)) { foundmx0 = true; ltr.IsFrozen = false; foundmx0Id = ltr.Id; ltr.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255); continue; } if (Regex.IsMatch(layerName, @"^m(\d){6}([a-z]){0,2}-" + Suffix + "$") && String.Equals(layerName.Remove(layerName.LastIndexOf('-')), dwgMsName)) { foundmxSuffix = true; ltr.IsFrozen = false; ltr.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255); continue; } if (String.Equals(layerName, "FILENAME") || String.Equals(layerName, "SCALE")) { LayersForDelete.Add(ltr.Name); continue; } // myLogger.Log("Deleting Unknown layer: " + ltr.Name + " in: " + currentDWG); LayersForDelete.Add(ltr.Name); } } } if (!foundmx0 && !foundmxSuffix) { _Logger.Log("Could not find mx-0 or mx-suffix layer in: " + currentDWG); } if (!found0) { _Logger.Log("0 Layer not found"); } if (!foundGType) { _Logger.Log("GTYPE Layer not found"); } using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable) { foreach (ObjectId oid in lt) { using (LayerTableRecord ltr = acTrans.GetObject(oid, OpenMode.ForWrite) as LayerTableRecord) { String layerName = ltr.Name.Trim(); if (foundmx0 && LayerFormat.IsMatch(layerName) && ltr.Id != foundmx0Id) { LayersForDelete.Add(ltr.Name); _Logger.Log("Layer: " + layerName + " not allowed in: " + System.IO.Path.GetFileNameWithoutExtension(db.Filename)); continue; } if (!foundmx0 && foundmxSuffix && LayerFormat.IsMatch(layerName)) { ltr.IsFrozen = false; ltr.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 255); continue; } } } } foreach (String LayerForDelete in LayersForDelete) { Utilities.delLayer(acTrans, db, LayerForDelete); } if (foundmx0) { newfi = String.Concat(db.Filename.Remove(db.Filename.LastIndexOf('.')), "-", "0", ".dwg"); } if (!foundmx0) { newfi = String.Concat(db.Filename.Remove(db.Filename.LastIndexOf('.')), "-", Suffix.Trim(), ".dwg"); } acTrans.Commit(); } try { db.SaveAs(newfi, DwgVersion.Current); } catch (System.Exception se) { _Logger.Log("Couldn't save Dwg: " + System.IO.Path.GetFileNameWithoutExtension(db.Filename) + " because: " + se.Message); } } } //if (_Logger.ErrorCount > 0) { return "Log file: " + _Logger.Path; } else { return "No errors found"; } } catch (System.Exception e) { _Logger.Log("Unhandled exception: " + e.Message); return("Unhandled exception: " + e.Message); } finally { AfterProcessing(); } return(String.Concat(DwgCounter, " out of ", NumDwgs, " processed in ", TimePassed, (_Logger.ErrorCount > 0) ? (". Log file: " + _Logger.Path) : ("."))); }
public ACadWorker(Database acCurDb, Transaction acTrans, BlockTableRecord acBlkTblRec, LayerTable acLyrTbl) { _dataBase = acCurDb; _transaction = acTrans; _model = acBlkTblRec; _layers = acLyrTbl; }
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 }
//https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-iterate-through-a-directory-tree public override String Process() { Int32 totalDwgCounter = 0; if (!CheckDirPath()) { //ed.WriteMessage(Environment.NewLine + "Invalid path: " + Path); return("Invalid path: " + _Path); } try { _Logger = new Logger(_Path + "\\LayerListErrors.txt"); } catch (System.Exception se) { //ed.WriteMessage(Environment.NewLine + "Could not write log file because: " + se.Message + Environment.NewLine); return("Could not create log file in: " + _Path + " because: " + se.Message); } StartTimer(); Stack <String> dirs = new Stack <String>(); dirs.Push(_Path); while (dirs.Count > 0) { String currentDir = dirs.Pop(); String[] subDirs; try { subDirs = System.IO.Directory.GetDirectories(currentDir); } catch (System.Exception se) { _Logger.Log("Sub directories in folder: " + _Path + " could not be accessed because: " + se.Message); continue; } try { GetDwgList(SearchOption.TopDirectoryOnly); } catch (System.Exception se) { _Logger.Log("Files could not be accessed in: " + currentDir + " because: " + se.Message); continue; } totalDwgCounter += NumDwgs; foreach (String dwg in DwgList) { if (_Bw.CancellationPending) { _Logger.Log("Processing cancelled by user at dwg " + DwgCounter + " out of " + NumDwgs); _Logger.Dispose(); return("Layer listing cancelled at DWG: " + DwgCounter); } DwgCounter++; try { _Bw.ReportProgress(Utilities.GetPercentage(DwgCounter, NumDwgs)); } catch { _Logger.Log("Progress bar error"); } String dwgName = System.IO.Path.GetFileNameWithoutExtension(dwg); System.IO.StreamWriter sw = null; try { sw = new StreamWriter(currentDir + "\\" + dwgName + ".txt"); } catch (System.Exception se) { _Logger.Log("Could not write layer list file in: " + currentDir + " because: " + se.Message); } using (Database db = new Database(false, true)) { try { db.ReadDwgFile(dwg, FileOpenMode.OpenForReadAndReadShare, true, String.Empty); db.CloseInput(true); } catch (System.Exception se) { _Logger.Log("Could not read DWG: " + dwg + " because : " + se.Message); continue; } using (Transaction acTrans = db.TransactionManager.StartTransaction()) { using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable) { foreach (ObjectId oid in lt) { using (LayerTableRecord ltr = acTrans.GetObject(oid, OpenMode.ForRead) as LayerTableRecord) { sw.WriteLine(ltr.Name.Trim()); } } } } } sw.Flush(); sw.Close(); } foreach (String str in subDirs) { dirs.Push(str); } } StopTimer(); _Logger.Dispose(); if (_Logger.ErrorCount > 0) { return(_Logger.ErrorCount.ToString() + " errors found. Log file: " + _Path); } else { return(String.Concat(totalDwgCounter, " lists made in: ", TimePassed)); } }
manageLayers(string strLayerName, short color = 256) { ObjectId idLayer = ObjectId.Null; Document doc = Application.DocumentManager.MdiActiveDocument; Database DB = doc.Database; bool thawed; try { using (doc.LockDocument()) { using (Transaction tr = BaseObjs.startTransactionDb()) { LayerTable LT = (LayerTable)tr.GetObject(DB.LayerTableId, OpenMode.ForRead); LayerTableRecord Ltr; if (LT.Has(strLayerName) == false) { Ltr = new LayerTableRecord(); Ltr.Name = strLayerName; if (color != 0) { Ltr.Color = Color.FromColorIndex(ColorMethod.ByLayer, color); } LT.UpgradeOpen(); LT.Add(Ltr); tr.AddNewlyCreatedDBObject(Ltr, true); tr.Commit(); idLayer = Ltr.ObjectId; } else { Ltr = tr.GetObject(LT[strLayerName], OpenMode.ForWrite) as LayerTableRecord; Ltr.Color = Color.FromColorIndex(ColorMethod.ByLayer, color); idLayer = Ltr.ObjectId; if (Ltr.IsFrozen) { LT.UpgradeOpen(); Ltr.IsFrozen = false; thawed = true; } else { thawed = false; } if (Ltr.IsOff) { if (thawed == false) { LT.UpgradeOpen(); } Ltr.IsOff = false; } tr.Commit(); } } //end using } //end using } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Layer.cs: line: 307"); } return(idLayer); }
public override void GetAllAttributeInfo(T model) { foreach (AttributeModel am in model.attributes) { foreach (string layerName in GetRealLayer(am.LayerName)) { LayerModel lyModel = new LayerModel(); lyModel.IsHaveAttribute = true; List <BlockInfoModel> list = new List <BlockInfoModel>(); lyModel.Name = layerName; Document doc = Application.DocumentManager.MdiActiveDocument; ObjectIdCollection ids = new ObjectIdCollection(); PromptSelectionResult ProSset = null; TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.LayerName, layerName) }; SelectionFilter sfilter = new SelectionFilter(filList); LayoutManager layoutMgr = LayoutManager.Current; string ss = layoutMgr.CurrentLayout; ProSset = doc.Editor.SelectAll(sfilter); // List<ObjectId> idss= GetEntitiesInModelSpace(); Database db = doc.Database; List <BlockReference> blockTableRecords = new List <BlockReference>(); if (ProSset.Status == PromptStatus.OK) { lyModel.pointFs = new Dictionary <int, List <object> >(); using (Transaction tran = db.TransactionManager.StartTransaction()) { SelectionSet sst = ProSset.Value; ObjectId[] oids = sst.GetObjectIds(); int ad = 0; List <string> aa = new List <string>(); LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForRead); foreach (ObjectId layerId in lt) { LayerTableRecord ltr = (LayerTableRecord)tran.GetObject(layerId, OpenMode.ForRead); if (ltr.Name == layerName) { lyModel.Color = System.Drawing.ColorTranslator.ToHtml(ltr.Color.ColorValue); } } int i = 0; foreach (ObjectId lengGemo in oids) { AttributeModel am2 = new AttributeModel(); foreach (AttributeItemModel att in am.attributeItems) { AttributeItemModel aim2 = new AttributeItemModel(); aim2.TargetName = att.TargetName; aim2.AtItemType = att.AtItemType; aim2.AtGroupType = att.AtGroupType; am2.attributeItems.Add(aim2); } DBObject ob = tran.GetObject(lengGemo, OpenMode.ForRead); BlockInfoModel plModel = MethodCommand.AnalysisBlcokInfo(ob, am2); if (plModel != null) { List <object> obj = new List <object>() { plModel }; lyModel.pointFs.Add(i, obj); i++; } } } if (model.allLines == null) { model.allLines = new List <LayerModel>(); } model.allLines.Add(lyModel); } } } }
public static void _RemoveAllLayersAndObjectsExceptDefaultLayer(this LayerTable docLayers) { if (docLayers == null) { return; } var doc = docLayers.Document; if (doc == null) { return; } //DEBUG //var layers1 = doc.Layers.Where(o => o.ParentLayerId == Guid.Empty).ToList(); //var objs1 = doc.Objects.ToList(); // // unselect all object to be able to delete them and layer that hold this selected object // Layers.HighlightLayer.UnselectAll(); // // delete all objects // foreach (var o in doc.Objects) { if (!doc.Objects._Purge(o)) { //DEBUG //RhinoApp.WriteLine("DEBUG: RhinoFile.Open: Unable to delete object " + o.Name); } } // clear garabage collector - to ensure we will not have issues with memory GC.Collect(); GC.WaitForPendingFinalizers(); // // Set current layer to default to be able to delete others layer that sometimes are default even named different than 'Default' // var defaultLayerIndex = -1; // lets create unique 'Default' layer foreach (var defLayerUniqueName in new[] { "Default", "DefaultLayer", "DefaultLayer0", "DefaultLayer00", "DefaultLayer000" }) { defaultLayerIndex = doc.Layers.FindByFullPath(defLayerUniqueName, true); if (defaultLayerIndex == -1) { doc.Layers.Add(new Layer() { Name = defLayerUniqueName }); defaultLayerIndex = doc.Layers.FindByFullPath(defLayerUniqueName, true); } // if 'Default' layer is not in root - dont use it - better lets create a new layer in next loop-cycle if (doc.Layers[defaultLayerIndex].ParentLayerId != Guid.Empty) { defaultLayerIndex = -1; } // if we found our 'Default' layer - lets break our loop if (defaultLayerIndex != -1) { break; } } // take first layer as default (in case we cannot have 'Default' layer as default) ( this is almost impossible but anyway lets keep this condition) if (defaultLayerIndex == -1 && doc.Layers.Count != 0) { var layersThatCanBeDefault = doc.Layers.Where(o => o.ParentLayerId == Guid.Empty && !o.IsDeleted && !Layers.LayerIndexes.IsLayerIgnored(o)).ToList(); if (layersThatCanBeDefault.Count != 0) { defaultLayerIndex = layersThatCanBeDefault[0].LayerIndex; } } // if we found default layer - set it! if (defaultLayerIndex != -1) { doc.Layers.SetCurrentLayerIndex(defaultLayerIndex, true); } // set 'Default' layer to zero index - very important //if (defaultLayerIndex != 0) //{ // var zeroLayer = doc.Layers.FirstOrDefault(o => o.LayerIndex == 0); // if (zeroLayer != null) // { // zeroLayer.LayerIndex = defaultLayerIndex; // zeroLayer.CommitChanges(); // } // var defLayer = doc.Layers[defaultLayerIndex]; // defLayer.LayerIndex = 0; // defLayer.CommitChanges(); // defaultLayerIndex = defLayer.LayerIndex; //} // // Try to delete all layers except default // foreach (var o in doc.Layers) { // dont delete default layer if (o.LayerIndex == defaultLayerIndex) { continue; } //o.Name = o.Name + o.LayerIndex; //debug o.IsVisible = true; o.IsLocked = false; o.CommitChanges(); } foreach (var o in doc.Layers) { // dont delete default layer if (o.LayerIndex == defaultLayerIndex) { continue; } // try to delete layer if (!doc.Layers.Purge(o.LayerIndex, true)) { //DEBUG //RhinoApp.WriteLine("DEBUG: RhinoFile.Open: Unable to delete layer " + o.Name); } } //DEBUG //var layers2 = doc.Layers.Where(o => o.ParentLayerId == Guid.Empty).ToList(); //var objs2 = doc.Objects.ToList(); // // Clear undo records after we had deleted all object and layers // doc.ClearRedoRecords(); doc.ClearUndoRecords(true); //var layers3 = doc.Layers.Where(o => o.ParentLayerId == Guid.Empty).ToList(); //var objs4 = doc.Objects.ToList(); }
public static void GetEntitiesFromLayer() { Database db = HostApplicationServices.WorkingDatabase; List <DBText> dbTextList = new List <DBText>(); Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; using (Transaction trans = db.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead); Dictionary <int, Dictionary <int, List <DBText> > > allText = new Dictionary <int, Dictionary <int, List <DBText> > >(); Dictionary <int, Dictionary <int, List <Circle> > > allCircle = new Dictionary <int, Dictionary <int, List <Circle> > >(); BlockTableRecord ltr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForRead); foreach (ObjectId objId in ltr) { Entity ent = (Entity)trans.GetObject(objId, OpenMode.ForRead); if (ent.GetType().Name == "DBText") { AddText(allText, ent); } else if (ent.GetType().Name == "Circle") { AddCircle(allCircle, ent); } } StringBuilder builder = new StringBuilder(); BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); foreach (var x in allText) { foreach (var y in x.Value) { foreach (var text in y.Value) { var circle = GetClosestCircle(allCircle, x.Key, y.Key, text, trans, btr); if (circle != null) { builder.AppendLine(string.Format("文字:{0}", text.TextString)); builder.AppendLine(string.Format("圆点:{0},{1},FaceStyleId:{2}", circle.Center.X, circle.Center.Y, circle.FaceStyleId)); var newText = new DBText(); newText.Position = circle.Center; newText.TextString = text.TextString; newText.Height = text.Height; dbTextList.Add(newText); btr.AppendEntity(newText); try { trans.AddNewlyCreatedDBObject(newText, true); } catch (System.Exception ex) { throw ex; } } else { builder.AppendLine(string.Format("文字:{0}", text.TextString)); builder.AppendLine("圆点:没有啊"); } } } } string path = @"C:\acadacad.text"; if (File.Exists(path)) { File.Delete(path); } StreamWriter rw = File.CreateText(path); rw.WriteLine(builder.ToString()); rw.Flush(); rw.Close(); ed.WriteMessage("搞定 收工"); trans.Commit(); } }
public void DrawDelaunay() { //---获取凸包边界 GetEdgeList(); double angleV1V2, angleV2V3, angleMaxV1V2 = 0, angleMaxV2V3 = 0; int newIndex; double[] vector1 = new double[2]; double[] vector2 = new double[2]; double[] vector3 = new double[2]; double lengthV1, lengthV2, lengthV3; bool isTriExist = false; //判断三角形是否存在 mEdge edge; for (int i = 0; i < EdgeList.Count; i++) { edge = new mEdge(); edge = EdgeList[i]; //------------------------------左三角形不存在时 if (edge.LeftTri == -1) { newIndex = -1; angleMaxV1V2 = 0; angleMaxV2V3 = 0; vector1[0] = NodeList[edge.End].X - NodeList[edge.Start].X; vector1[1] = NodeList[edge.End].Y - NodeList[edge.Start].Y; for (int j = 0; j < NodeList.Count; j++) { if (j != edge.Start && j != edge.End) //排除端点 { vector2[0] = NodeList[j].X - NodeList[edge.Start].X; vector2[1] = NodeList[j].Y - NodeList[edge.Start].Y; if (vector1[0] * vector2[1] - vector2[0] * vector1[1] > 0) //点在vector1左侧 { vector3[0] = NodeList[j].X - NodeList[edge.End].X; vector3[1] = NodeList[j].Y - NodeList[edge.End].Y; lengthV1 = Math.Sqrt(vector1[0] * vector1[0] + vector1[1] * vector1[1]); lengthV2 = Math.Sqrt(vector2[0] * vector2[0] + vector2[1] * vector2[1]); lengthV3 = Math.Sqrt(vector3[0] * vector3[0] + vector3[1] * vector3[1]); angleV1V2 = Math.Acos((vector1[0] * vector2[0] + vector1[1] * vector2[1]) / (lengthV1 * lengthV2)); angleV2V3 = Math.Acos((vector2[0] * vector3[0] + vector2[1] * vector3[1]) / (lengthV2 * lengthV3)); if (angleV2V3 > angleMaxV2V3) { angleMaxV2V3 = angleV2V3; angleMaxV1V2 = angleV1V2; newIndex = j; } else if (angleV2V3 == angleMaxV2V3 && angleMaxV1V2 >= angleV1V2) { angleMaxV1V2 = angleV1V2; newIndex = j; } } } } if (newIndex != -1) //找到符合要求的点,然后记录 { mTriangle triangle = new mTriangle(); triangle.NodeA = edge.Start; triangle.NodeB = edge.End; triangle.NodeC = newIndex; edge.LeftTri = TriList.Count; //三角形索引从0开始 isTriExist = false; //记录第一条边 for (int k = 0; k < EdgeList.Count; k++) { mEdge tempEdge = EdgeList[k]; if (tempEdge.Start == edge.Start && tempEdge.End == newIndex) { tempEdge.RightTri = TriList.Count; triangle.EdgeB = k; isTriExist = true; break; } else if (tempEdge.Start == newIndex && tempEdge.End == edge.Start) { tempEdge.LeftTri = TriList.Count; triangle.EdgeB = k; isTriExist = true; break; } } if (isTriExist == false) { mEdge newEdge = new mEdge(); newEdge.Start = newIndex; newEdge.End = edge.Start; newEdge.LeftTri = TriList.Count; triangle.EdgeB = EdgeList.Count; EdgeList.Add(newEdge); } isTriExist = false; //记录第二条边 for (int k = 0; k < EdgeList.Count; k++) { mEdge tempEdge = EdgeList[k]; if (tempEdge.Start == newIndex && tempEdge.End == edge.End) { tempEdge.RightTri = TriList.Count; triangle.EdgeC = k; isTriExist = true; break; } else if (tempEdge.Start == edge.End && tempEdge.End == newIndex) { tempEdge.LeftTri = TriList.Count; triangle.EdgeC = k; isTriExist = true; break; } } if (isTriExist == false) { mEdge newEdge = new mEdge(); newEdge.Start = edge.End; newEdge.End = newIndex; newEdge.LeftTri = TriList.Count; triangle.EdgeC = EdgeList.Count; EdgeList.Add(newEdge); } triangle.EdgeA = i; TriList.Add(triangle); } } ////////////////////////////////////////////////////////////////////////////右三角形不存在时 else if (edge.RightTri == -1) { newIndex = -1; angleMaxV1V2 = 0; angleMaxV2V3 = 0; vector1[0] = NodeList[edge.End].X - NodeList[edge.Start].X; vector1[1] = NodeList[edge.End].Y - NodeList[edge.Start].Y; for (int j = 0; j < NodeList.Count; j++) { if (j != edge.Start && j != edge.End) { vector2[0] = NodeList[j].X - NodeList[edge.Start].X; vector2[1] = NodeList[j].Y - NodeList[edge.Start].Y; if (vector1[0] * vector2[1] - vector2[0] * vector1[1] < 0) { vector3[0] = NodeList[j].X - NodeList[edge.End].X; vector3[1] = NodeList[j].Y - NodeList[edge.End].Y; lengthV1 = Math.Sqrt(vector1[0] * vector1[0] + vector1[1] * vector1[1]); lengthV2 = Math.Sqrt(vector2[0] * vector2[0] + vector2[1] * vector2[1]); lengthV3 = Math.Sqrt(vector3[0] * vector3[0] + vector3[1] * vector3[1]); angleV1V2 = Math.Acos((vector1[0] * vector2[0] + vector1[1] * vector2[1]) / (lengthV1 * lengthV2)); angleV2V3 = Math.Acos((vector2[0] * vector3[0] + vector2[1] * vector3[1]) / (lengthV2 * lengthV3)); if (angleV2V3 > angleMaxV2V3) { angleMaxV2V3 = angleV2V3; angleMaxV1V2 = angleV1V2; newIndex = j; } else if (angleV2V3 == angleMaxV2V3 && angleMaxV1V2 < angleV1V2) { angleMaxV1V2 = angleV1V2; newIndex = j; } } } } if (newIndex != -1) { mTriangle triangle = new mTriangle(); triangle.NodeA = edge.Start; triangle.NodeB = edge.End; triangle.NodeC = newIndex; edge.RightTri = TriList.Count; isTriExist = false; //记录vector2向量边 for (int k = 0; k < EdgeList.Count; k++) { mEdge tempEdge = EdgeList[k]; if (tempEdge.Start == newIndex && tempEdge.End == edge.Start) { tempEdge.RightTri = TriList.Count; triangle.EdgeB = k; isTriExist = true; break; } else if (tempEdge.Start == edge.Start && tempEdge.End == newIndex) { tempEdge.LeftTri = TriList.Count; triangle.EdgeB = k; isTriExist = true; break; } } if (isTriExist == false) { mEdge newEdge = new mEdge(); newEdge.Start = edge.Start; newEdge.End = newIndex; newEdge.LeftTri = TriList.Count; triangle.EdgeB = EdgeList.Count; EdgeList.Add(newEdge); } isTriExist = false; //记录Vector3向量边 for (int k = 0; k < EdgeList.Count; k++) { mEdge tempEdge = EdgeList[k]; if (tempEdge.Start == edge.End && tempEdge.End == newIndex) { tempEdge.RightTri = TriList.Count; triangle.EdgeC = k; isTriExist = true; break; } else if (tempEdge.Start == newIndex && tempEdge.End == edge.End) { tempEdge.LeftTri = TriList.Count; triangle.EdgeC = k; isTriExist = true; break; } } if (isTriExist == false) { mEdge newEdge = new mEdge(); newEdge.Start = newIndex; newEdge.End = edge.End; newEdge.LeftTri = TriList.Count; triangle.EdgeC = EdgeList.Count; EdgeList.Add(newEdge); } triangle.EdgeA = i; TriList.Add(triangle); } } } ////////////////////////////////////////////////////////////////////////// ///绘图 ////////////////////////////////////////////////////////////////////////// Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database acDb = acDoc.Database; using (Transaction acDelaunayTrans = acDb.TransactionManager.StartTransaction()) { string layerName = "LineLayer"; LayerTable acLTable = acDelaunayTrans.GetObject(acDb.LayerTableId, OpenMode.ForRead) as LayerTable; if (acLTable.Has(layerName) == false) { using (Transaction acLayerTrans = acDb.TransactionManager.StartTransaction()) { LayerTable acLTable2 = acLayerTrans.GetObject(acDb.LayerTableId, OpenMode.ForRead) as LayerTable; LayerTableRecord acLTRecord = new LayerTableRecord(); acLTRecord.Name = layerName; acLTRecord.Color = Color.FromColorIndex(ColorMethod.ByAci, 7); acLTable2.UpgradeOpen(); acLTable2.Add(acLTRecord); acLayerTrans.AddNewlyCreatedDBObject(acLTRecord, true); acLayerTrans.Commit(); } } if (acLTable.Has(layerName) == true) { acDb.Clayer = acLTable[layerName]; } BlockTable acBLTable; acBLTable = acDelaunayTrans.GetObject(acDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord acBTRecord; acBTRecord = acDelaunayTrans.GetObject(acBLTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; int i; for (i = 0; i < EdgeList.Count; i++) { Point3d startPoint = new Point3d(NodeList[EdgeList[i].Start].X, NodeList[EdgeList[i].Start].Y, NodeList[EdgeList[i].Start].Z); Point3d endPoint = new Point3d(NodeList[EdgeList[i].End].X, NodeList[EdgeList[i].End].Y, NodeList[EdgeList[i].End].Z); Line acLine = new Line(startPoint, endPoint); acBTRecord.AppendEntity(acLine); acDelaunayTrans.AddNewlyCreatedDBObject(acLine, true); } DocumentCollection acDC = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager; acDC.MdiActiveDocument.Editor.WriteMessage("\n Delaunay三角网绘制完毕!"); acDelaunayTrans.Commit(); } //Zoom(new Point3d(), new Point3d(), new Point3d(), 1.01075); }
/// <summary> /// Загружает в документ новые параметры слоев и фигур. /// </summary> public void Update() { // Получаем текущий документ, доступ к командной строке и БД. Document doc = AcadAS.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; // Блокируем документ для редактирования из вне. using (DocumentLock lc = doc.LockDocument()) { // Начинаем транзакцию. using (Transaction tr = db.TransactionManager.StartTransaction()) { try { // Создаем список имен слоев. string[] layerNames = new string[Layers.Count]; int i = 0; foreach (Layer layer in Layers) { layerNames[i] = layer.Name; i++; } i = 0; // Получаем таблицу слоев. LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForWrite); // Задаем временные имена слоев для избежания конфликтов переименовывания. foreach (ObjectId ltrId in lt) { LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForWrite); if (ltr.Name != "0") { ltr.Name = "_temp_" + ltr.Name + "_temp_"; } } foreach (Layer layer in Layers) { // Проверяем новое имя слоя на дублирование и присваиваем слоям документа новые параметры. if (Array.IndexOf(layerNames, layer.Name) == Array.LastIndexOf(layerNames, layer.Name)) { LayerTableRecord acadLayer = (LayerTableRecord)tr.GetObject(layer.Id, OpenMode.ForWrite); layer.Update(ref acadLayer); } else if (Array.IndexOf(layerNames, layer.Name) == i) { MessageBox.Show("Дублирование имени слоя \"" + layer.Name + "\"."); } i++; // Присваиваем фигурам документа новые параметры. foreach (Model.Point point in layer.Points) { AcadDS.DBPoint acadPoint = (AcadDS.DBPoint)tr.GetObject(point.Id, OpenMode.ForWrite); point.Update(ref acadPoint); } foreach (Model.Line line in layer.Lines) { AcadDS.Line acadLine = (AcadDS.Line)tr.GetObject(line.Id, OpenMode.ForWrite); line.Update(ref acadLine); } foreach (Model.Circle circle in layer.Circles) { AcadDS.Circle acadCircle = (AcadDS.Circle)tr.GetObject(circle.Id, OpenMode.ForWrite); circle.Update(ref acadCircle); } } // Если не все слои переименовались удаляем добавочный преффик и суффикс. foreach (ObjectId ltrId in lt) { LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForWrite); ltr.Name = ltr.Name.Replace("_temp_", ""); } } catch (Autodesk.AutoCAD.Runtime.Exception e) { ed.WriteMessage("Ошибка применения данных. {0}: {1}", e.HResult, e.Message); } tr.Commit(); tr.Dispose(); } //lc.Dispose(); } // Обновляем экземпляр класса после изменения документа. Reload(); }
private static void SetStandartToLayer(Database db, LayerTableRecord stdLayer, Transaction tr, string activeLayerName, string stdLayerName, LayerTable layerTable) { // var stdDatabase = new Database(false, true); // stdDatabase.ReadDwgFile(@"Z:\AutoCAD_server\ShareSettings\КР-сб\КР-сб.dws", FileShare.Read, true, ""); foreach (var layer in layerTable) { LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layer, OpenMode.ForWrite); if (!ltr.Name.Equals(activeLayerName)) continue; ltr.IsLocked = false; ltr.UpgradeOpen(); if (activeLayerName == stdLayerName) { SetLayerProperties(stdLayer, ltr, db, tr); } else if (!layerTable.Has(stdLayerName)) { ltr.Name = stdLayerName; SetLayerProperties(stdLayer, ltr, db, tr); } else { bool isLock = false; foreach (var layerStd in layerTable) { LayerTableRecord ltrstd = (LayerTableRecord)tr.GetObject(layerStd, OpenMode.ForWrite); if (!ltrstd.Name.Equals(stdLayerName)) continue; isLock = ltrstd.IsLocked; ltrstd.IsLocked = false; SetLayerProperties(stdLayer, ltrstd, db, tr); break; } SetLayerToEntity(db, activeLayerName, stdLayerName); ltr.IsLocked = isLock; DeleteLayer(activeLayerName, db); } } }
/// <summary> /// Загружает в объект свойства всех слоев проекта с привязанными /// к ним фигурами типа: точка, отрезок и окружность. /// </summary> private void Load() { // Обнуляем коллекцию слоев. Layers = new ObservableCollection <Layer>(); // Получаем текущий документ, доступ к командной строке и БД. Document doc = AcadAS.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; // Начинаем транзакцию. using (Transaction tr = db.TransactionManager.StartTransaction()) { // Получаем таблицу слоев документа. LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead); // Добавляем в нашу коллекцию все слои с требуемыми параметрами. foreach (ObjectId ltrId in lt) { LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForRead); Layers.Add(new Layer(ltr)); } // Получаем список фигур (точка, отрезок и окружность) каждого слоя, // и сохраняем требуемыме параметры фигур в коллекции каждого слоя. foreach (var layer in Layers) { // Обновляем предствление пользователя. if (Layers[0] == layer) { _selectedLayer = layer; OnPropertyChanged("SelectedLayer"); } // Задание параметров фильтра. TypedValue[] filterlist = new TypedValue[8]; filterlist[0] = new TypedValue((int)DxfCode.Operator, "<AND"); filterlist[1] = new TypedValue((int)DxfCode.LayerName, layer.Name); filterlist[2] = new TypedValue((int)DxfCode.Operator, "<OR"); filterlist[3] = new TypedValue((int)DxfCode.Start, "POINT"); filterlist[4] = new TypedValue((int)DxfCode.Start, "LINE"); filterlist[5] = new TypedValue((int)DxfCode.Start, "CIRCLE"); filterlist[6] = new TypedValue((int)DxfCode.Operator, "OR>"); filterlist[7] = new TypedValue((int)DxfCode.Operator, "AND>"); // Создаем фильтр. SelectionFilter filter = new SelectionFilter(filterlist); // пытаемся получить ссылки на объекты с учетом фильтра PromptSelectionResult selRes = ed.SelectAll(filter); // Получаем массив ID объектов. if (selRes.Value != null) { ObjectId[] ids = selRes.Value.GetObjectIds(); foreach (ObjectId id in ids) { // Приводим каждый из них к типу Entity. Entity entity = (Entity)tr.GetObject(id, OpenMode.ForRead); // Классифицируем по группам. if (entity.GetType() == typeof(AcadDS.DBPoint)) { layer.Points.Add(new Model.Point(entity as AcadDS.DBPoint)); } else if (entity.GetType() == typeof(AcadDS.Line)) { layer.Lines.Add(new Model.Line(entity as AcadDS.Line)); } else if (entity.GetType() == typeof(AcadDS.Circle)) { layer.Circles.Add(new Model.Circle(entity as AcadDS.Circle)); } } } } tr.Commit(); } }
public void Merge() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; LayoutManager lm = LayoutManager.Current; lm.CurrentLayout = "Layout1"; Database db = doc.Database; string dwgName = Path.GetFileNameWithoutExtension(doc.Name); string folderPath = Path.GetDirectoryName(doc.Name); List<SheetObject> sheetObjects = Helpers.SheetsObjectsFromCSV(folderPath, dwgName); using (Transaction transCreateLayers = db.TransactionManager.StartTransaction()) { foreach (SheetObject sheetObject in sheetObjects) { string layerName = $"0-{sheetObject.xrefName}"; Helpers.CreateLayer(db, transCreateLayers, layerName); ed.WriteMessage("======================== Layer created: " + layerName + "\n"); LayerTable layerTable = transCreateLayers.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectId layer = new ObjectId(); foreach (ObjectId layerId in layerTable) { LayerTableRecord currentLayer = transCreateLayers.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord; if (currentLayer.Name == layerName) { layer = layerId; } } //Load Xref #region string PathName = $"{folderPath}\\{sheetObject.xrefName}"; ObjectId acXrefId = db.AttachXref(PathName, sheetObject.xrefName); if (!acXrefId.IsNull) { // Attach the DWG reference to the model space Point3d insPt = new Point3d(0, 0, 0); using (BlockReference blockRef = new BlockReference(insPt, acXrefId)) { blockRef.SetLayerId(layer, true); BlockTable blocktable = transCreateLayers.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord modelSpace = transCreateLayers.GetObject(blocktable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; modelSpace.AppendEntity(blockRef); transCreateLayers.AddNewlyCreatedDBObject(blockRef, true); } ed.WriteMessage("======================== xref loaded\n"); } #endregion } transCreateLayers.Commit(); } //get document name ed.WriteMessage("\n======================== Dwg Name: " + doc.Name + "\n"); //objects to delete List<ObjectId[]> viewportContentList = new List<ObjectId[]>(); foreach (SheetObject sheetObject in sheetObjects) { string layerName = $"0-{sheetObject.xrefName}"; using (Transaction trans = db.TransactionManager.StartTransaction()) { ed.WriteMessage("======================== Xref(s): " + sheetObject.xrefName + "\n"); XYZ currentVpCentre = sheetObject.viewportCentre; Point3d revitViewportCentre = new Point3d(currentVpCentre.x, currentVpCentre.y, 0); XYZ _revitViewCentreWCS = sheetObject.viewCentre; Point3d revitViewCentreWCS = new Point3d(_revitViewCentreWCS.x, _revitViewCentreWCS.y, 0); double degrees = Helpers.DegToRad(sheetObject.angleToNorth); double vpWidht = sheetObject.viewportWidth; double vpHeight = sheetObject.viewportHeight; lm.CurrentLayout = "Layout1"; string currentLo = lm.CurrentLayout; DBDictionary LayoutDict = trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; Layout CurrentLo = trans.GetObject((ObjectId)LayoutDict[currentLo], OpenMode.ForRead) as Layout; Viewport matchingViewport = null; List<ObjectId> layerToFreeze = new List<ObjectId>(); //LayerTable layerTable = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; //foreach (ObjectId layerId in layerTable) //{ // LayerTableRecord currentLayer = trans.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord; // if (currentLayer.Name != layerName) // { // layerToFreeze.Add(layerId); // } //} #region Find the equivalent Revit viewport foreach (ObjectId ID in CurrentLo.GetViewports()) { Viewport VP = trans.GetObject(ID, OpenMode.ForWrite) as Viewport; if (VP != null && CurrentLo.GetViewports().Count == 2 && VP.CenterPoint.X > 20) //by default the Layout is a viewport too...https://forums.autodesk.com/t5/net/layouts-and-viewports/td-p/3128748 { matchingViewport = VP; ed.WriteMessage("======================== Single Viewport on sheet\n"); } if (VP != null && VP.CenterPoint.DistanceTo(revitViewportCentre) < 100) //Should use the closest viewport, not a fixed distance { matchingViewport = VP; ed.WriteMessage("======================== Multiple Viewports on sheet\n"); } else { VP.FreezeLayersInViewport(layerToFreeze.GetEnumerator()); } } ed.WriteMessage("======================== Viewport Name: " + matchingViewport.BlockName + "\n"); ed.WriteMessage("======================== Viewport Center: " + matchingViewport.CenterPoint + "\n"); #endregion #region Delete Viewport Content Point3dCollection vpCorners = GetViewportBoundary(matchingViewport); Matrix3d mt = PaperToModel(matchingViewport); Point3dCollection vpCornersInModel = TransformPaperSpacePointToModelSpace(vpCorners, mt); try { ObjectId[] viewportContent = SelectEntitisInModelSpaceByViewport(doc, vpCornersInModel); viewportContentList.Add(viewportContent); ed.WriteMessage("======================== Viewport objects: " + viewportContent.Length.ToString() + "\n"); } catch (System.Exception ex) { ed.WriteMessage("======================== Error: " + ex.Message + "\n"); } #endregion //Recenter Viewport #region Helpers.UpdateViewport(matchingViewport, revitViewportCentre, revitViewCentreWCS, degrees, vpWidht, vpHeight); ed.WriteMessage("======================== Viewport updated \n"); #endregion trans.Commit(); }//close transaction }//close loop through sheet objects using (Transaction transDeleteObjects = db.TransactionManager.StartTransaction()) { foreach (ObjectId[] itemList in viewportContentList) { if (itemList != null) { foreach (ObjectId item in itemList) { Entity e = (Entity)transDeleteObjects.GetObject(item, OpenMode.ForWrite); //ed.WriteMessage(item.GetType().Name); e.Erase(); } ed.WriteMessage("======================== Viewport content deleted\n"); } else { ed.WriteMessage("======================== viewport content is null!\n"); } } transDeleteObjects.Commit(); } ed.WriteMessage("Switch to Model layout \n"); lm.CurrentLayout = "Model"; //ed.WriteMessage("======================== Run Set by layer\n"); //ed.Command("-setbylayer", "all"," ","y","y"); ed.WriteMessage("======================== Run Audit\n"); ed.Command("audit", "y"); ed.WriteMessage("======================== Run Purge \n"); ed.Command("-purge", "all", " ", "n"); lm.CurrentLayout = "Layout1"; ed.Command("_.zoom", "_extents"); ed.Command("_.zoom", "_scale", "0.9"); ed.WriteMessage("Save file \n"); db.SaveAs(doc.Name, true, DwgVersion.Current, doc.Database.SecurityParameters); ed.WriteMessage("done"); }
public static void delLayer(Transaction acTrans, Database db, String layerName) { // If the layer is locked, unlock it using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable) { if (lt.Has(layerName)) { ObjectId layerOID = lt[layerName]; using (LayerTableRecord ltr = acTrans.GetObject(layerOID, OpenMode.ForWrite) as LayerTableRecord) { if (ltr.IsLocked) { ltr.IsLocked = false; } } } } // Delete all objects on layer ObjectIdCollection coutObjs = new ObjectIdCollection(); using (BlockTable bt = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable) { foreach (ObjectId oid in bt) { using (BlockTableRecord btr = acTrans.GetObject(oid, OpenMode.ForWrite) as BlockTableRecord) { foreach (ObjectId oidEnt in btr) { Entity ent = acTrans.GetObject(oidEnt, OpenMode.ForRead) as Entity; if (ent.Layer == layerName) { ent.UpgradeOpen(); coutObjs.Add(ent.Id); ent.Erase(true); } } } } } db.Purge(coutObjs); // Delete layer using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable) { if (lt.Has(layerName)) { // Check to see if it is safe to erase layer ObjectIdCollection acObjIdColl = new ObjectIdCollection(); acObjIdColl.Add(lt[layerName]); db.Purge(acObjIdColl); if (acObjIdColl.Count > 0) { LayerTableRecord acLyrTblRec = acTrans.GetObject(acObjIdColl[0], OpenMode.ForWrite) as LayerTableRecord; acLyrTblRec.Erase(true); } else { //Wrong: https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2016/ENU/AutoCAD-NET/files/GUID-DF8A64D3-AE09-4BCE-B9E1-1B642DA4FCFF-htm.html LayerTableRecord acLyrTblRec = acTrans.GetObject(acObjIdColl[0], OpenMode.ForWrite) as LayerTableRecord; acLyrTblRec.Erase(true); } db.Purge(acObjIdColl); } } }
public void ExplodeBlockByNameCommand(Editor ed, Document doc, string blockToExplode) { Document bDwg = doc; Database db = bDwg.Database; Database olddb = HostApplicationServices.WorkingDatabase; HostApplicationServices.WorkingDatabase = db; Autodesk.AutoCAD.DatabaseServices.TransactionManager bTransMan = bDwg.TransactionManager; using (Transaction bTrans = bTransMan.StartTransaction()) { try { LayerTable lt = (LayerTable)bTrans.GetObject(db.LayerTableId, OpenMode.ForRead); BlockTable bt = (BlockTable)bTrans.GetObject(db.BlockTableId, OpenMode.ForRead); if (bt.Has(blockToExplode)) { ObjectId blkId = bt[blockToExplode]; BlockTableRecord btr = (BlockTableRecord)bTrans.GetObject(blkId, OpenMode.ForRead); ObjectIdCollection blkRefs = btr.GetBlockReferenceIds(true, true); foreach (ObjectId blkXId in blkRefs) { //create collection for exploded objects DBObjectCollection objs = new DBObjectCollection(); //handle as entity and explode Entity ent = (Entity)bTrans.GetObject(blkXId, OpenMode.ForRead); ent.Explode(objs); //erase Block ent.UpgradeOpen(); ent.Erase(); BlockTableRecord btrCs = (BlockTableRecord)bTrans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); foreach (DBObject obj in objs) { Entity ent2 = (Entity)obj; if (!ent2.Linetype.Equals("ByLayer", StringComparison.CurrentCultureIgnoreCase) && !ent2.Linetype.Equals("Continuous", StringComparison.CurrentCultureIgnoreCase)) { string layer = "EQUIPMENT-" + ent2.Linetype; ObjectId oid; if (!lt.Has(layer)) { using (Transaction bTrans2 = bTransMan.StartTransaction()) { ed.WriteMessage("\nCreating layer {0}", layer); using (LayerTableRecord ltr = new LayerTableRecord()) { LayerTable lt2 = (LayerTable)bTrans2.GetObject(db.LayerTableId, OpenMode.ForWrite); ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 3); ltr.Name = layer; ltr.LinetypeObjectId = ent2.LinetypeId; oid = lt2.Add(ltr); bTrans2.AddNewlyCreatedDBObject(ltr, true); bTrans2.Commit(); } } lt = (LayerTable)bTrans.GetObject(db.LayerTableId, OpenMode.ForRead); } else { oid = lt[layer]; } ed.WriteMessage("\nSetting entity properties."); ent2.LayerId = oid; ent2.Linetype = "ByLayer"; } btrCs.AppendEntity(ent2); bTrans.AddNewlyCreatedDBObject(ent2, true); } } //purge block ObjectIdCollection blockIds = new ObjectIdCollection(); blockIds.Add(btr.ObjectId); db.Purge(blockIds); btr.UpgradeOpen(); btr.Erase(); } else { ed.WriteMessage("\nCould not find block named {0}", blockToExplode); } bTrans.Commit(); } catch (System.Exception err) { ed.WriteMessage("\nSomething went wrong: {0}", blockToExplode); File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\error.log", err.ToString()); } finally { } bTrans.Dispose(); bTransMan.Dispose(); HostApplicationServices.WorkingDatabase = olddb; ed.WriteMessage("\n"); } }
private void method_1(ObjectId[] objectId_0) { Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Database workingDatabase = HostApplicationServices.WorkingDatabase; EntityList entityList = new EntityList(); int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; MessageFilter messageFilter = new MessageFilter(); System.Windows.Forms.Application.AddMessageFilter(messageFilter); ProgressMeter progressMeter = new ProgressMeter(); progressMeter.SetLimit(objectId_0.Length); progressMeter.Start("Serializing XML entities"); try { CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), Conversions.GetUCS()); using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction()) { LayerTable arg_83_0 = (LayerTable)transaction.GetObject(workingDatabase.LayerTableId, (OpenMode)0); for (int i = 0; i < objectId_0.Length; i++) { messageFilter.CheckMessageFilter((long)i, 10000); progressMeter.MeterProgress(); Entity entity = (Entity)transaction.GetObject(objectId_0[i], (OpenMode)0); string name = ((LayerTableRecord)transaction.GetObject(entity.LayerId, (OpenMode)0)).Name; Autodesk.AutoCAD.DatabaseServices.Face face = entity as Autodesk.AutoCAD.DatabaseServices.Face; if (face != null) { Point3d vertexAt = face.GetVertexAt(0); Point3d vertexAt2 = face.GetVertexAt(1); Point3d vertexAt3 = face.GetVertexAt(2); Point3d vertexAt4 = face.GetVertexAt(3); global::TerrainComputeC.XML.Vertex v = new global::TerrainComputeC.XML.Vertex(vertexAt.X, vertexAt.Y, vertexAt.Z); global::TerrainComputeC.XML.Vertex v2 = new global::TerrainComputeC.XML.Vertex(vertexAt2.X, vertexAt2.Y, vertexAt2.Z); global::TerrainComputeC.XML.Vertex v3 = new global::TerrainComputeC.XML.Vertex(vertexAt3.X, vertexAt3.Y, vertexAt3.Z); global::TerrainComputeC.XML.Vertex v4 = new global::TerrainComputeC.XML.Vertex(vertexAt4.X, vertexAt4.Y, vertexAt4.Z); global::TerrainComputeC.XML.Face face2 = new global::TerrainComputeC.XML.Face(v, v2, v3, v4); face2.SetProperties(name, face.Color.ColorIndex); entityList.Faces.Add(face2); coordinateTransformator.Transform(face2); num4++; } else { DBPoint dBPoint = entity as DBPoint; if (dBPoint != null) { global::TerrainComputeC.XML.Point point = new global::TerrainComputeC.XML.Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z); point.SetProperties(name, dBPoint.Color.ColorIndex); entityList.Points.Add(point); coordinateTransformator.Transform(point); num++; } else { Autodesk.AutoCAD.DatabaseServices.Line line = entity as Autodesk.AutoCAD.DatabaseServices.Line; if (line != null) { Point3d startPoint = line.StartPoint; Point3d endPoint = line.EndPoint; global::TerrainComputeC.XML.Vertex startVertex = new global::TerrainComputeC.XML.Vertex(startPoint.X, startPoint.Y, startPoint.Z); global::TerrainComputeC.XML.Vertex endVertex = new global::TerrainComputeC.XML.Vertex(endPoint.X, endPoint.Y, endPoint.Z); global::TerrainComputeC.XML.Line line2 = new global::TerrainComputeC.XML.Line(startVertex, endVertex); line2.SetProperties(name, line.Color.ColorIndex); entityList.Lines.Add(line2); coordinateTransformator.Transform(line2); num2++; } else { Polyline polyline = entity as Polyline; Polyline2d polyline2d = entity as Polyline2d; Polyline3d polyline3d = entity as Polyline3d; if (polyline != null || polyline2d != null || polyline3d != null) { short colorIndex = 256; if (polyline != null) { colorIndex = polyline.Color.ColorIndex; } if (polyline2d != null) { colorIndex = polyline2d.Color.ColorIndex; } if (polyline3d != null) { colorIndex = polyline3d.Color.ColorIndex; } PointSet pointSet = PointGeneration.SubdividePolyline(entity, transaction, 0.0); List <global::TerrainComputeC.XML.Vertex> list = new List <global::TerrainComputeC.XML.Vertex>(); for (int j = 0; j < pointSet.Count; j++) { list.Add(new global::TerrainComputeC.XML.Vertex(pointSet[j].X, pointSet[j].Y, pointSet[j].Z)); } PolyLine polyLine = new PolyLine(list); polyLine.SetProperties(name, colorIndex); entityList.Polylines.Add(polyLine); coordinateTransformator.Transform(polyLine); num3++; } } } } } } progressMeter.Stop(); editor.WriteMessage("\nXML entity list created:"); editor.WriteMessage("\nNumber of points : " + entityList.Points.Count); editor.WriteMessage("\nNumber of lines : " + entityList.Lines.Count); editor.WriteMessage("\nNumber of polylines : " + entityList.Polylines.Count); editor.WriteMessage("\nNumber of faces : " + entityList.Faces.Count); editor.WriteMessage("\nTotal number of entities: " + entityList.Count); editor.WriteMessage("\nWriting xml file " + IO.string_0 + "..."); Serializer.Serialize(IO.string_0, entityList); editor.WriteMessage("OK\n"); } catch (System.Exception ex) { progressMeter.Stop(); throw; } }
public static DBObject Create(this Grevit.Types.Room r, Transaction tr) { DictionarySpaceStyle ss = new DictionarySpaceStyle(Command.Database); try { BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); Polyline acPoly = new Polyline(); acPoly.SetDatabaseDefaults(); int i = 0; foreach (Grevit.Types.Point p in r.points) { acPoly.AddVertexAt(i, new Point2d(p.x, p.y), 0, 0, 0); i++; } acPoly.Closed = true; ms.AppendEntity(acPoly); tr.AddNewlyCreatedDBObject(acPoly, true); Autodesk.Aec.Geometry.Profile myProfile = Autodesk.Aec.Geometry.Profile.CreateFromEntity(acPoly, Command.Editor.CurrentUserCoordinateSystem); Space space; bool newEnt = false; if (Command.existing_objects.ContainsKey(r.GID)) { space = (Space)tr.GetObject(Command.existing_objects[r.GID], OpenMode.ForWrite); } else { newEnt = true; space = new Space(); space.SetDatabaseDefaults(Command.Database); space.SetToStandard(Command.Database); } space.Associative = r.associative; space.Name = r.name; space.GeometryType = SpaceGeometryType.TwoD; space.Location = new Point3d(0, 0, 0); space.SetBaseProfile(myProfile, Matrix3d.Identity); LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead); if (r.TypeOrLayer != "") { if (lt.Has(r.TypeOrLayer)) { space.LayerId = lt[r.TypeOrLayer]; } } if (ss.Has(r.FamilyOrStyle, tr)) { space.StyleId = ss.GetAt(r.FamilyOrStyle); } if (newEnt) { ms.AppendEntity(space); tr.AddNewlyCreatedDBObject(space, true); ms.Dispose(); } return(space); } catch (Autodesk.AutoCAD.Runtime.Exception e) { } return(null); }
private void method_2() { Database workingDatabase = HostApplicationServices.WorkingDatabase; Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; string value = IO.AutoDetermineDelimiter(IO.string_3, true); char c = Convert.ToChar(value); MessageFilter messageFilter = new MessageFilter(); System.Windows.Forms.Application.AddMessageFilter(messageFilter); int num = 0; using (StreamReader streamReader = new StreamReader(IO.string_3)) { while (streamReader.Peek() >= 0) { streamReader.ReadLine(); num++; } } ProgressMeter progressMeter = new ProgressMeter(); progressMeter.SetLimit(num); progressMeter.Start("Reading 3df file"); try { CoordinateTransformator coordinateTransformator = new CoordinateTransformator(Conversions.GetUCS(), CoordinateSystem.Global()); using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)transaction.GetObject(workingDatabase.LayerTableId, (OpenMode)0); BlockTable arg_D1_0 = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)0); ObjectId blockModelSpaceId = SymbolUtilityServices.GetBlockModelSpaceId(workingDatabase); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockModelSpaceId, (OpenMode)1); int num2 = 1; int num3 = 0; using (StreamReader streamReader2 = new StreamReader(IO.string_3)) { while (streamReader2.Peek() >= 0) { string text = streamReader2.ReadLine(); if (!text.StartsWith("C", true, null) && !(text == "")) { try { string[] array = text.Split(new char[] { c }, StringSplitOptions.RemoveEmptyEntries); string text2 = array[0].Trim(); if (!DBManager.ValidateName(text2)) { throw new System.Exception(string.Concat(new object[] { "Invalid layer name in line ", num2, ":\n", text })); } if (text2 == "") { text2 = "0"; } double num4 = Convert.ToDouble(array[1]); double num5 = Convert.ToDouble(array[2]); double num6 = Convert.ToDouble(array[3]); double num7 = Convert.ToDouble(array[4]); double num8 = Convert.ToDouble(array[5]); double num9 = Convert.ToDouble(array[6]); double num10 = Convert.ToDouble(array[7]); double num11 = Convert.ToDouble(array[8]); double num12 = Convert.ToDouble(array[9]); double num13 = Convert.ToDouble(array[10]); double num14 = Convert.ToDouble(array[11]); double num15 = Convert.ToDouble(array[12]); coordinateTransformator.Transform(ref num4, ref num5, ref num6); coordinateTransformator.Transform(ref num7, ref num8, ref num9); coordinateTransformator.Transform(ref num10, ref num11, ref num12); coordinateTransformator.Transform(ref num13, ref num14, ref num15); Point3d point3d = new Point3d(num4, num5, num6); //point3d..ctor(num4, num5, num6); Point3d point3d2 = new Point3d(num7, num8, num9); //point3d2..ctor(num7, num8, num9); Point3d point3d3 = new Point3d(num10, num11, num12); //point3d3..ctor(num10, num11, num12); Point3d point3d4 = new Point3d(num13, num14, num15); //point3d4..ctor(num13, num14, num15); Entity entity = new Autodesk.AutoCAD.DatabaseServices.Face(point3d, point3d2, point3d3, point3d4, true, true, true, true); entity.LayerId = (DBManager.GetLayerId(text2, 7, lt)); entity.ColorIndex = (256); blockTableRecord.AppendEntity(entity); transaction.AddNewlyCreatedDBObject(entity, true); num3++; } catch (System.Exception ex) { if (text.Trim() == "") { text = "Empty line!"; } throw new FormatException(string.Concat(new string[] { "Invalid format in line ", num2.ToString(), ":", Environment.NewLine, text, Environment.NewLine })); } } num2++; progressMeter.MeterProgress(); messageFilter.CheckMessageFilter((long)num2, 1000); } } transaction.Commit(); progressMeter.Stop(); editor.WriteMessage(string.Concat(new object[] { Environment.NewLine, num3, " faces read.", Environment.NewLine })); } DBManager.ZoomExtents(); } catch (System.Exception ex) { progressMeter.Stop(); throw; } }
public override String Process() { try { BeforeProcessing(); } catch (System.Exception se) { return("Keyfile Generation processing exception: " + se.Message); } //if (!CheckDirPath()) { return "Invalid path: " + _Path; } //try //{ // _Logger = new Logger(String.Concat(_Path, "\\KeyfileErrors.txt")); //} //catch (System.Exception se) //{ // // FATAL ERROR // return "Could not create log file in: " + _Path + " because: " + se.Message; //} //StartTimer(); // Get all DWG files try { GetDwgList(SearchOption.TopDirectoryOnly, delegate(String inFile) { return((System.IO.Path.GetFileNameWithoutExtension(inFile).Length < 15)); }); } catch (SystemException se) { _Logger.Log(" DWG files could not be enumerated because: " + se.Message); _Logger.Dispose(); return(" DWG files could not be enumerated because: " + se.Message); } if (NumDwgs == 0) { return("No DWGs found in: " + _Path); } foreach (String currentDWG in DwgList) { DwgCounter++; try { _Bw.ReportProgress(Utilities.GetPercentage(DwgCounter, NumDwgs)); } catch { } if (_Bw.CancellationPending) { _Logger.Log("Keyfile generation cancelled by user at dwg " + DwgCounter.ToString() + " out of " + DwgList.Count); break; } String dwgNameNoExt = System.IO.Path.GetFileNameWithoutExtension(currentDWG); String dwgNameExt = System.IO.Path.GetFileName(currentDWG); String ms = String.Empty; using (Database db = new Database(false, true)) { try { db.ReadDwgFile(currentDWG, FileOpenMode.OpenForReadAndWriteNoShare, true, String.Empty); db.Regenmode = true; db.CloseInput(true); } catch (Autodesk.AutoCAD.Runtime.Exception e) { _Logger.Log(String.Concat("Could not read DWG: ", dwgNameNoExt, " because: ", e.Message, "...Continuing to next DWG")); continue; } using (Transaction acTrans = db.TransactionManager.StartTransaction()) { // Unlock and thaw all layers ToEach.toEachLayer(db, acTrans, delegate(LayerTableRecord ltr) { if (ltr.IsLocked) { ltr.IsLocked = false; } if (ltr.IsFrozen) { ltr.IsFrozen = false; } return(false); }); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.ASCII; settings.Indent = true; XmlWriter xmlW = XmlWriter.Create(_Path + "\\" + dwgNameNoExt + "_key.xml", settings); if (xmlW == null) { _Logger.Log("XML writer could not be initialized."); _Logger.Dispose(); return("XML file could not be initialized."); } try { xmlW.WriteStartDocument(); xmlW.WriteStartElement("rpstl_keyfile"); xmlW.WriteAttributeString("version", "2.0"); xmlW.WriteStartElement("filename"); xmlW.WriteAttributeString("text", dwgNameExt); xmlW.WriteEndElement(); // Write dwg extents xmlW.WriteStartElement("extents"); xmlW.WriteAttributeString("x1", db.Extmin.X.truncstring(3)); xmlW.WriteAttributeString("y1", db.Extmin.Y.truncstring(3)); xmlW.WriteAttributeString("x2", db.Extmax.X.truncstring(3)); xmlW.WriteAttributeString("y2", db.Extmax.Y.truncstring(3)); double height = db.Extmax.Y - db.Extmin.Y; double width = db.Extmax.X - db.Extmin.X; // Write document height and width xmlW.WriteAttributeString("height", height.truncstring(3)); xmlW.WriteAttributeString("width", width.truncstring(3)); xmlW.WriteEndElement(); // Unlock all layers ToEach.toEachLayer(db, acTrans, delegate(LayerTableRecord ltr) { if (ltr.IsLocked) { ltr.IsLocked = false; } return(false); } ); db.Regenmode = true; ObjectIdCollection oidc = new ObjectIdCollection(); ToEach.toEachEntity(db, acTrans, delegate(Entity ent) { oidc.Add(ent.Id); return(false); }); db.Purge(oidc); //Make Dictionary to map layerIds to layer names // Note neccessary because the DBText .Layer property isn't working Dictionary <ObjectId, String> LayerIdToLayerName = new Dictionary <ObjectId, string>(); using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable) { foreach (ObjectId layerOid in lt) { using (LayerTableRecord ltr = acTrans.GetObject(layerOid, OpenMode.ForRead) as LayerTableRecord) { LayerIdToLayerName.Add(ltr.Id, ltr.Name); } } } using (LayerTable lt = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable) { foreach (ObjectId oid in lt) { List <DBText> msNos = new List <DBText>(); List <DBText> callouts = new List <DBText>(); List <DBText> viewLetters = new List <DBText>(); List <DBText> miscTexts = new List <DBText>(); List <BlockReference> cards = new List <BlockReference>(); //IEnumerable<DBText> msnos = new List<DBText>(); StringBuilder prefixString = new StringBuilder(); using (LayerTableRecord ltr = acTrans.GetObject(oid, OpenMode.ForRead) as LayerTableRecord) { List <DBText> linesBelowDesignations = new List <DBText>(); using (BlockTable bt = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable) { using (BlockTableRecord btr = acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord) { foreach (ObjectId oidbtr in btr) { Entity ent = acTrans.GetObject(oidbtr, OpenMode.ForRead) as Entity; if (ent.LayerId == ltr.Id) { if (ent.GetType() == typeof(DBText)) { DBText dbt = ent as DBText; String layerName = LayerIdToLayerName[dbt.LayerId]; // Skip everything on "FILENAME" and "SCALE" layers if (String.Equals(layerName, "FILENAME") || String.Equals(layerName, "SCALE")) { continue; } if (dbt.TextString.Trim().ToUpper().EndsWith("(REF)")) { // Skip old refdess continue; } // P/0 instead of P/O if (String.Equals(dbt.TextString.Trim(), "P/0")) { _Logger.Log("P/0 found instead of P/O on layer: " + dbt.Layer + " in DWG: " + dwgNameNoExt); } if (calloutRegex.IsMatch(dbt.TextString) && !dbt.TextString.Contains("-") && layerName.StartsWith("m")) { callouts.Add(dbt); continue; } // Skip view letters that are on layers that aren't m layers if (viewLetterRegex.IsMatch(dbt.TextString.Trim()) && layerName.StartsWith("m")) { viewLetters.Add(dbt); continue; } // Skip msnos that are on layers that aren't m layers if ((msRegex.IsMatch(dbt.TextString.ToUpper()) || letterRegex.IsMatch(dbt.TextString.ToUpper())) && layerName.StartsWith("m")) { msNos.Add(dbt); continue; } if (refDesRegex.IsMatch(dbt.TextString.ToUpper().Trim())) //&& { // Do nothing // Look for refdess on a per-callout basis because refdes // must be within a certain range of each callout continue; } // Check if text refdes if (dbt.TextString.Contains("DESIGNATIONS")) { // Get prefix from line with Designations prefixString.Append(dbt.TextString.Substring(dbt.TextString.IndexOf("WITH") + 5).Trim()); // Get each line below Designations line and add it to list linesBelowDesignations = ToEach.toEachDBText(db, acTrans, delegate(DBText dbtUnderDes) { double yDiff = dbt.Position.Y - dbtUnderDes.Position.Y; double xDiff = Math.Abs(dbt.Position.X - dbtUnderDes.Position.X); return((dbt.Id != dbtUnderDes.Id) && (dbt.LayerId == dbtUnderDes.LayerId) && (dbt.Position.Y > dbtUnderDes.Position.Y) && (yDiff < .5) && (xDiff < .02)); }); // Append each line to String and format it with spaces and commas foreach (DBText lineBelowDes in linesBelowDesignations) { if (prefixString[prefixString.Length - 1] != ',') { prefixString.Append(String.Concat(", ", lineBelowDes.TextString.Trim())); continue; } if (prefixString[prefixString.Length - 1] == ',') { prefixString.Append(String.Concat(" ", lineBelowDes.TextString.Trim())); continue; } } // Delete trailing comma if it exists if (prefixString[prefixString.Length - 1] == ',') { prefixString.Length--; } // TODO ? continue; } miscTexts.Add(dbt); } if (ent.GetType() == typeof(BlockReference)) { BlockReference br = acTrans.GetObject(oidbtr, OpenMode.ForRead) as BlockReference; if (br.Name.Contains("PRENOTE")) { _Logger.Log("DWG: " + dwgNameExt + ": layer: " + LayerIdToLayerName[br.LayerId] + ": " + "block reference prefix note found"); } if (br.Name.Contains("HCRDTBL")) { cards.Add(br); } } } } } } xmlW.WriteStartElement("layer"); xmlW.WriteAttributeString("text", ltr.Name); if (prefixString.Length > 0) { xmlW.WriteAttributeString("refdes_prefix", prefixString.ToString()); } foreach (BlockReference br in cards) { Autodesk.AutoCAD.DatabaseServices.AttributeCollection attCol = br.AttributeCollection; AttributeReference attRefRefDes = acTrans.GetObject(br.AttributeCollection[0], OpenMode.ForRead) as AttributeReference; AttributeReference attRefItem = acTrans.GetObject(br.AttributeCollection[1], OpenMode.ForRead) as AttributeReference; xmlW.WriteStartElement("callout"); xmlW.WriteAttributeString("text", (String.IsNullOrWhiteSpace(attRefItem.TextString)) ? "no_itemno_for_card_slot" : attRefItem.TextString); xmlW.writeOutAttRefMinMax(attRefItem); xmlW.WriteStartElement("refdes"); xmlW.WriteAttributeString("text", attRefRefDes.TextString); xmlW.writeOutAttRefMinMax(attRefRefDes); xmlW.WriteEndElement(); xmlW.WriteEndElement(); } foreach (DBText viewLetter in viewLetters) { TextEntity tent = new TextEntity(viewLetter); xmlW.WriteStartElement("view_letter"); xmlW.WriteAttributeString("text", tent.text); xmlW.writeOutMinMax(tent, _Logger); xmlW.WriteEndElement(); } foreach (DBText msNo in msNos) { TextEntity tent = new TextEntity(msNo); xmlW.WriteStartElement("msno"); xmlW.WriteAttributeString("text", tent.text); xmlW.writeOutMinMax(tent, _Logger); xmlW.WriteEndElement(); } foreach (DBText callout in callouts) { TextEntity tent = new TextEntity(callout); xmlW.WriteStartElement("callout"); xmlW.writeOutMinMax(tent, _Logger); List <DBText> refDess = new List <DBText>(); refDess = ToEach.toEachDBText(db, acTrans, delegate(DBText possibleRefDes) { const System.Double yRange = .15; const System.Double xRange = .15; return(possibleRefDes.Id != callout.Id && possibleRefDes.LayerId == callout.LayerId && refDesRegex.IsMatch(possibleRefDes.TextString.ToUpper().Trim()) && //!possibleRefDes.TextString.Contains(",") && //!possibleRefDes.TextString.Contains("-") && (possibleRefDes.IsAbove(callout, .1135 /*.5*/) || possibleRefDes.IsInRect(callout.AlignmentPoint.X - xRange, callout.AlignmentPoint.Y, callout.AlignmentPoint.X, callout.AlignmentPoint.Y + yRange) || possibleRefDes.IsInRect(callout.AlignmentPoint.X, callout.AlignmentPoint.Y, callout.AlignmentPoint.X + xRange, callout.AlignmentPoint.Y + yRange)) && !callout.IsRefDesBetween(possibleRefDes, acTrans, db) ); }); if (refDess.Count > 1) { if (callout.Justify != AttachmentPoint.MiddleCenter) { _Logger.Log("DWG: " + dwgNameExt + " layer: " + LayerIdToLayerName[tent.dbText.LayerId] + " callout: " + tent.text + " has an alignment point that isn't middle center" + " (" + tent.dbText.Position.X.truncstring(3) + ", " + tent.dbText.Position.Y.truncstring(3) + ") "); } else { _Logger.Log("DWG: " + dwgNameExt + " layer: " + LayerIdToLayerName[tent.dbText.LayerId] + " has more than one refdes for callout: " + tent.text + " (" + tent.dbText.Position.X.truncstring(3) + ", " + tent.dbText.Position.Y.truncstring(3) + ") "); //tent.dbText.Layer); } } xmlW.WriteAttributeString("text", tent.text); foreach (DBText refdes in refDess) { TextEntity tentRefDes = new TextEntity(refdes); xmlW.WriteStartElement("refdes"); xmlW.WriteAttributeString("text", tentRefDes.text); xmlW.writeOutMinMax(tentRefDes, _Logger); xmlW.WriteEndElement(); } xmlW.WriteEndElement(); } foreach (DBText otherText in miscTexts) { if (!linesBelowDesignations.Contains(otherText)) { TextEntity tent = new TextEntity(otherText); xmlW.WriteStartElement("other_text"); xmlW.WriteAttributeString("text", tent.text); xmlW.writeOutMinMax(tent, _Logger); xmlW.WriteEndElement(); } } xmlW.WriteEndElement(); } } } } catch (System.Exception se) { _Logger.Log("DWG: " + dwgNameExt + ": processing error of type: " + se.GetType().ToString() + " : " + se.Message); } finally { xmlW.WriteEndElement(); xmlW.WriteRaw(Environment.NewLine); xmlW.WriteEndDocument(); xmlW.Flush(); xmlW.Close(); } acTrans.Commit(); } } } AfterProcessing(); return(String.Concat(DwgCounter.ToString(), " out of ", NumDwgs, " DWGs processed in ", TimePassed, ". ", (_Logger.ErrorCount > 0) ? ("Error Log: " + _Logger.Path) : ("No errors found."))); }
/// <summary> /// http://through-the-interface.typepad.com/through_the_interface/2010/01/creating-an-autocad-layer-using-net.html /// </summary> public static void CreateHiddenLayer(string layerName, bool isHidden = false, bool isFrozen = false) { short _colorIndex = 0; Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { LayerTable lt = (LayerTable)tr.GetObject( db.LayerTableId, OpenMode.ForRead ); try { SymbolUtilityServices.ValidateSymbolName( layerName, false ); if (lt.Has(layerName)) { ed.WriteMessage( "\nA layer with this name already exists." ); return; } } catch { ed.WriteMessage( "\nInvalid layer name." ); return; } LayerTableRecord ltr = new LayerTableRecord(); ltr.Name = layerName; ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, _colorIndex); ltr.IsFrozen = isFrozen; ltr.IsHidden = isHidden; lt.UpgradeOpen(); ObjectId ltId = lt.Add(ltr); tr.AddNewlyCreatedDBObject(ltr, true); tr.Commit(); ed.WriteMessage( "\nCreated layer named \"{0}\" with " + "a color index of {1}.", layerName, _colorIndex++ ); } }
public void AP_Przenies() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptStringOptions kom = new PromptStringOptions("Podaj nazwe warstwy pierwszej: "); kom.AllowSpaces = true; PromptResult prompt = ed.GetString(kom); if (prompt.Status != PromptStatus.OK) { return; } string nazwa_warstwy = prompt.StringResult; TypedValue[] tvs = new TypedValue[1]; tvs[0] = new TypedValue((int)DxfCode.LayerName, nazwa_warstwy); SelectionFilter filter = new SelectionFilter(tvs); PromptSelectionResult rez = ed.SelectAll(filter); int zlicz = 0; if (rez.Status == PromptStatus.OK) { zlicz = rez.Value.Count; } if (rez.Status == PromptStatus.OK || rez.Status == PromptStatus.Error) { Application.ShowAlertDialog("Znaleziono " + zlicz + " na warstwie " + nazwa_warstwy); if (zlicz > 0) { kom.Message = "Podaj warstwe docelowa"; prompt = ed.GetString(kom); if (prompt.Status != PromptStatus.OK || prompt.StringResult == "") { return; } string nowa_nazwa_warstwy = prompt.StringResult; Transaction trans = db.TransactionManager.StartTransaction(); using (trans) { LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead); if (!lt.Has(nowa_nazwa_warstwy)) { Application.ShowAlertDialog("Nie znaleziono warstwy."); } else { int zlicz_zmiany = 0; ObjectId lid = lt[nowa_nazwa_warstwy]; foreach (ObjectId id in rez.Value.GetObjectIds()) { Entity ent = (Entity)trans.GetObject(id, OpenMode.ForWrite); ent.LayerId = lid; zlicz_zmiany++; } Application.ShowAlertDialog("Przeniesiono " + zlicz_zmiany + " obietków z warstwy " + nazwa_warstwy + " do warstwy " + nowa_nazwa_warstwy); } trans.Commit(); } } } }
public void MergeDeleteAndBind() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; //https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2017/ENU/AutoCAD-NET/files/GUID-FAC1A5EB-2D9E-497B-8FD9-E11D2FF87B93-htm.html //https://adndevblog.typepad.com/autocad/2012/07/using-readdwgfile-with-net-attachxref-or-objectarx-acdbattachxref.html //Database oldDb = HostApplicationServices.WorkingDatabase; //is it necessary? // User should input the folder where the dwgs are saved PromptResult pr = ed.GetString("\nEnter folder containing DWGs to process: "); if (pr.Status != PromptStatus.OK) { return; } string pathName = pr.StringResult; string[] fileNames = Directory.GetFiles(pathName, "*.dwg"); // We'll use some counters to keep track // of how the processing is going int processed = 0, saved = 0, problem = 0; //var dict = File.ReadLines($"{pathName}\\summary.csv").Select(line => line.Split(',')).ToDictionary(line => line[0], line => line.ToList()); //dict.Remove(dict.Keys.First()); //remove the csv header //using a Sheet Object var logFile = File.ReadAllLines($"{pathName}\\summary.csv").Select(line => line.Split(',')).ToList <string[]>(); logFile.RemoveAt(0); List <SheetObject> sheetsList = new List <SheetObject>(); foreach (string[] item in logFile) { XYZ vc = new XYZ(Convert.ToDouble(item[1]), Convert.ToDouble(item[2]), Convert.ToDouble(item[3])); XYZ vpCentre = new XYZ(Convert.ToDouble(item[5]), Convert.ToDouble(item[6]), Convert.ToDouble(item[7])); sheetsList.Add(new SheetObject(item[0], vc, Convert.ToDouble(item[4]), vpCentre, Convert.ToDouble(item[8]), Convert.ToDouble(item[9]), item[10])); } //foreach (string fileName in dict.Keys) foreach (SheetObject sheetObject in sheetsList) { string name = sheetObject.sheetName; string filePath = $"{pathName}\\{sheetObject.sheetName}.dwg"; string outputPath = $"{pathName}\\{sheetObject.sheetName}.dwg"; //Database db = new Database(false, false); Database db = new Database(false, true); using (db) { try { ed.WriteMessage($"\n\nProcessing file: {filePath} "); db.ReadDwgFile(filePath, FileShare.ReadWrite, true, ""); db.CloseInput(true); LayoutManager lm = LayoutManager.Current; lm.CurrentLayout = "Model"; //is it necessary? string layerName = $"0-{sheetObject.xrefName}"; using (Transaction trans = db.TransactionManager.StartTransaction()) { Helpers.CreateLayer(db, trans, layerName); LayerTable layerTable = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectId layer = new ObjectId(); List <ObjectId> layerToFreeze = new List <ObjectId>(); foreach (ObjectId layerId in layerTable) { LayerTableRecord currentLayer = trans.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord; if (currentLayer.Name == layerName) { layer = layerId; layerToFreeze.Add(layerId); } //else //{ // layerToFreeze.Add(layerId); //} } //Attch Xref string PathName = $"{pathName}\\{sheetObject.xrefName}"; ObjectId acXrefId = db.AttachXref(PathName, sheetObject.xrefName); if (!acXrefId.IsNull) { // Attach the DWG reference to the current space //Point3d insPt = new Point3d(0, 0, sheetObject.viewCentre.z); Point3d insPt = new Point3d(0, 0, 0); using (BlockReference blockRef = new BlockReference(insPt, acXrefId)) { blockRef.SetLayerId(layer, true); BlockTable blocktable = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord modelSpace = trans.GetObject(blocktable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; modelSpace.AppendEntity(blockRef); trans.AddNewlyCreatedDBObject(blockRef, true); } } lm.CurrentLayout = "Layout1"; //forms.MessageBox.Show(lm.CurrentLayout); string currentLo = lm.CurrentLayout; DBDictionary LayoutDict = trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; Layout CurrentLo = trans.GetObject((ObjectId)LayoutDict[currentLo], OpenMode.ForRead) as Layout; foreach (ObjectId ID in CurrentLo.GetViewports()) { Viewport viewPort = trans.GetObject(ID, OpenMode.ForWrite) as Viewport; //Point3d revitViewportCentre = new Point3d(double.Parse(dict[name][5]), double.Parse(dict[name][6]), 0); XYZ vpCentre = sheetObject.viewportCentre; Point3d revitViewportCentre = new Point3d(vpCentre.x, vpCentre.y, 0); //Point3d revitViewCentreWCS = new Point3d(double.Parse(dict[name][1]), double.Parse(dict[name][2]), 0); XYZ _revitViewCentreWCS = sheetObject.viewCentre; //Point3d revitViewCentreWCS = new Point3d(revitViewCentre.x, revitViewCentre.y, 0); Point3d revitViewCentreWCS = new Point3d(_revitViewCentreWCS.x, _revitViewCentreWCS.y, 0); //double degrees = DegToRad(double.Parse(dict[name][4])); double degrees = Helpers.DegToRad(sheetObject.angleToNorth); //double vpWidht = double.Parse(dict[name][8]); double vpWidht = sheetObject.viewportWidth; //double vpHeight = double.Parse(dict[name][9]); double vpHeight = sheetObject.viewportHeight; Viewport viewPortToUpdate = null; if (viewPort != null && CurrentLo.GetViewports().Count == 2) //by default the Layout is a viewport too...https://forums.autodesk.com/t5/net/layouts-and-viewports/td-p/3128748 { viewPortToUpdate = viewPort; } else if (viewPort != null && viewPort.CenterPoint.DistanceTo(revitViewportCentre) < 100) //Should use the closest viewport, not a fixed distance { viewPortToUpdate = viewPort; } else { viewPort.FreezeLayersInViewport(layerToFreeze.GetEnumerator()); } Point3dCollection vpCorners = CadHelper.GetViewportBoundary(viewPortToUpdate); Matrix3d mt = CadHelper.PaperToModel(viewPortToUpdate); Point3dCollection vpCornersInModel = CadHelper.TransformPaperSpacePointToModelSpace(vpCorners, mt); ObjectId[] viewportContent = CadHelper.SelectEntitisInModelSpaceByViewport(doc, vpCornersInModel); if (viewportContent != null) { foreach (ObjectId item in viewportContent) { Entity e = (Entity)trans.GetObject(item, OpenMode.ForWrite); e.Erase(); } } else { ed.WriteMessage("viewport content is null!"); } Helpers.UpdateViewport(viewPortToUpdate, revitViewportCentre, revitViewCentreWCS, degrees, vpWidht, vpHeight); } //Purge unused layers Helpers.PurgeUnusedLayers(trans, db); Helpers.PurgeDatabase(db, trans); trans.Commit(); } Helpers.BindXrefs(db); db.Audit(true, true); ed.WriteMessage("\nSaving to file: {0}", outputPath); db.SaveAs(outputPath, DwgVersion.Current); saved++; processed++; } catch (System.Exception ex) { ed.WriteMessage("\nProblem processing file: {0} - \"{1}\"", sheetObject.sheetName, ex.Message); problem++; } } } ed.WriteMessage( "\n\nSuccessfully processed {0} files, of which {1} had " + "attributes to update and an additional {2} had errors " + "during reading/processing.", processed, saved, problem ); }
public static Alignment CreateAlignmentFromIFC(string ifcFile) { Alignment aln = null; Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; CivilDocument Cdoc = CivilApplication.ActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; ObjectId aln_id = ObjectId.Null; ObjectId layerId = ObjectId.Null; ObjectId aln_styleId = ObjectId.Null; ObjectId profStyleId = ObjectId.Null; ObjectId alnLabelSetId = ObjectId.Null; ObjectId profLabelSetId = ObjectId.Null; using (Transaction CADtrans = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)CADtrans.GetObject(db.BlockTableId, OpenMode.ForRead, false); BlockTableRecord btr = (BlockTableRecord)CADtrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false); LayerTable acLyrTbl = CADtrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; foreach (ObjectId id in acLyrTbl) { layerId = id; break; } AlignmentStyleCollection style_col = Cdoc.Styles.AlignmentStyles; if (style_col.Count > 0) { aln_styleId = style_col[0]; } AlignmentLabelSetStyleCollection alignmentLabelSets = Cdoc.Styles.LabelSetStyles.AlignmentLabelSetStyles; if (alignmentLabelSets.Count > 0) { alnLabelSetId = alignmentLabelSets[0]; } aln_id = Alignment.Create(Cdoc, "Alingment_" + DateTime.Now.ToShortTimeString(), ObjectId.Null, layerId, aln_styleId, alnLabelSetId, AlignmentType.Centerline); aln = CADtrans.GetObject(aln_id, OpenMode.ForRead) as Alignment; int noOfSpiral = 0; string str = string.Empty; using (var model = IfcStore.Open(ifcFile)) { var ifcAlignments = model.Instances.OfType <IfcAlignment>(); try { foreach (IfcAlignment algn in ifcAlignments) { IfcCurve cv = algn.Axis; IfcAlignmentCurve algnCv = cv as IfcAlignmentCurve; if (algnCv != null) { IfcAlignment2DHorizontal algn_hort = algnCv.Horizontal; foreach (IfcAlignment2DHorizontalSegment seg in algn_hort.Segments) { IfcCurveSegment2D seg_2d = seg.CurveGeometry; if (seg_2d.GetType() == typeof(IfcLineSegment2D)) { //get ifc data IfcLineSegment2D line = seg_2d as IfcLineSegment2D; IfcCartesianPoint pt = line.StartPoint; IfcPlaneAngleMeasure dir = line.StartDirection;//this is bearing angle IfcPositiveLengthMeasure len = line.SegmentLength; double angle = bearing2AutocadAngle(dir); ///create civil 3d line entity //create point 1 Point3d pt1 = new Point3d(pt.X, pt.Y, 0); //create point 2 double x = Math.Sin(angle) * len; double y = Math.Cos(angle) * len; Vector3d vector = new Vector3d(x, y, 0); Matrix3d mat = Matrix3d.Displacement(vector); Point3d pt2 = pt1.TransformBy(mat); ed.WriteMessage("Crate line\n"); aln.Entities.AddFixedLine(aln.Entities.Count(), pt1, pt2); } if (seg_2d.GetType() == typeof(IfcTransitionCurveSegment2D)) { noOfSpiral++; IfcTransitionCurveSegment2D tran = seg_2d as IfcTransitionCurveSegment2D; double rad = 0; double startRadius = 0, endRadius = 0; if (tran.StartRadius != null) { startRadius = tran.StartRadius.Value; } if (tran.EndRadius != null) { endRadius = tran.EndRadius.Value; } if (startRadius != 0 && endRadius == 0) { rad = startRadius; } else if (endRadius != 0 && startRadius == 0) { rad = endRadius; } IfcCartesianPoint pt = tran.StartPoint; IfcPositiveLengthMeasure len = tran.SegmentLength; bool IsEndRadiusCCW = false, IsStartRadiusCCW = false, isClockwise = false; if (tran.IsEndRadiusCCW != null) { IsEndRadiusCCW = tran.IsEndRadiusCCW; } if (tran.IsStartRadiusCCW != null) { IsStartRadiusCCW = tran.IsStartRadiusCCW; } if (IsStartRadiusCCW == true) { isClockwise = IsStartRadiusCCW; } double dir = tran.StartDirection; IfcTransitionCurveType tranType = tran.TransitionCurveType; //determine if it in curve or out curve by no? SpiralCurveType spiralCurveType = SpiralCurveType.InCurve; if (noOfSpiral % 2 == 0) { spiralCurveType = SpiralCurveType.OutCurve; } if (tran.TransitionCurveType == IfcTransitionCurveType.CLOTHOIDCURVE) { ed.WriteMessage("Crate Transition Curve\n"); if (rad == 0) { aln.Entities.AddFixedSpiral(aln.Entities.Count(), startRadius, endRadius, len, Autodesk.Civil.SpiralType.Clothoid); } else if (startRadius != 0) { aln.Entities.AddFloatSpiral(aln.Entities.Count(), rad, len, isClockwise, Autodesk.Civil.SpiralType.Clothoid); } //aln.Entities.AddFixedSpiral(aln.Entities.Count(), rad, len, spiralCurveType, Autodesk.Civil.SpiralType.Clothoid); } } if (seg_2d.GetType() == typeof(IfcCircularArcSegment2D)) { IfcCircularArcSegment2D cir = seg_2d as IfcCircularArcSegment2D; IfcPositiveLengthMeasure len = cir.SegmentLength; IfcCartesianPoint pt = cir.StartPoint; IfcPlaneAngleMeasure dir = cir.StartDirection; IfcPositiveLengthMeasure rad = cir.Radius; double angle = bearing2AutocadAngle(dir); bool isCCW = (bool)cir.IsCCW; Point3d startPt = new Point3d(pt.X, pt.Y, 0); double x = Math.Sin(angle) * len; double y = Math.Cos(angle) * len; Vector3d vector = new Vector3d(x, y, 0); //ed.WriteMessage("Crate circle Curve\n"); // aln.Entities.AddFixedCurve(startPt, vector, rad, isCCW); } if (seg_2d.GetType() == typeof(IfcCurveSegment2D)) { IfcCurveSegment2D crv = seg_2d as IfcCurveSegment2D; IfcPositiveLengthMeasure len = crv.SegmentLength; IfcCartesianPoint pt = crv.StartPoint; IfcPlaneAngleMeasure dir = crv.StartDirection; } } #region >>>>=========== Create profile entities // get the standard style and label set // these calls will fail on templates without a style named "Standard" ProfileStyleCollection prof_tyle_col = Cdoc.Styles.ProfileStyles; if (prof_tyle_col.Count > 0) { profStyleId = prof_tyle_col[0]; } ProfileLabelSetStyleCollection profilLabelSets = Cdoc.Styles.LabelSetStyles.ProfileLabelSetStyles; if (profilLabelSets.Count > 0) { profLabelSetId = profilLabelSets[0]; } ObjectId oProfileId = Profile.CreateByLayout("Profile", aln_id, layerId, profStyleId, profLabelSetId); Profile PROF = CADtrans.GetObject(oProfileId, OpenMode.ForWrite) as Profile; //get profile information from ifc IfcAlignment2DVertical algn_vert = algnCv.Vertical; foreach (IfcAlignment2DVerticalSegment seg in algn_vert.Segments) { if (seg.GetType() == typeof(IfcAlignment2DVerSegLine)) { IfcAlignment2DVerSegLine line = seg as IfcAlignment2DVerSegLine; double len = line.HorizontalLength; double z = Convert.ToDouble(line.StartHeight.Value); double slope = Convert.ToDouble(line.StartGradient.Value); } if (seg.GetType() == typeof(IfcAlignment2DVerSegParabolicArc)) { IfcAlignment2DVerSegParabolicArc tran = seg as IfcAlignment2DVerSegParabolicArc; double parabola = Convert.ToDouble(tran.ParabolaConstant); bool isConvex = (bool)tran.IsConvex.Value; double ch = Convert.ToDouble(tran.StartDistAlong); double len = Convert.ToDouble(tran.HorizontalLength); double z = Convert.ToDouble(tran.StartHeight.Value); double slope = Convert.ToDouble(tran.StartGradient.Value); } if (seg.GetType() == typeof(IfcAlignment2DVerSegCircularArc)) { IfcAlignment2DVerSegCircularArc cir = seg as IfcAlignment2DVerSegCircularArc; double radius = Convert.ToDouble(cir.Radius); bool isConvex = (bool)cir.IsConvex.Value; double ch = Convert.ToDouble(cir.StartDistAlong); double len = Convert.ToDouble(cir.HorizontalLength); double z = Convert.ToDouble(cir.StartHeight.Value); double slope = Convert.ToDouble(cir.StartGradient.Value); } //Point2d startPoint = new Point2d(station_start, H_start); //Point2d endPoint = new Point2d(station_end, H_end); //ProfileTangent oTangent = PROF.Entities.AddFixedTangent(startPoint, endPoint); #endregion } } } } catch { } } CADtrans.Commit(); } return(aln); }
/// <summary> /// Создание слоя. /// Слоя не должно быть в таблице слоев. /// </summary> /// <param name="layerInfo">параметры слоя</param> /// <param name="lt">таблица слоев открытая для чтения. Выполняется UpgradeOpen и DowngradeOpen</param> public static ObjectId CreateLayer(this LayerInfo layerInfo, LayerTable lt) { ObjectId idLayer = ObjectId.Null; // Если слоя нет, то он создается. using (var newLayer = new LayerTableRecord()) { layerInfo.SetProp(newLayer, lt.Database); lt.UpgradeOpen(); idLayer = lt.Add(newLayer); lt.DowngradeOpen(); } return idLayer; }
private static void ScanDrawing(BlockTable blockTable, BlockTableRecord modelSpace, LayerTable layerTable) { using (Transaction trans = dataBase.TransactionManager.StartTransaction()) { foreach (ObjectId oid in modelSpace) { var element = oid.GetObject(OpenMode.ForRead); if (element.GetType() == typeof(BlockReference)) { ReplaceBlock((BlockReference)element, blockTable, modelSpace); } else { ChangeLayerToMavat(element, layerTable); } } trans.Commit(); } }
private void LoadLayers(Transaction transaction, LayerTable layerTable) { // Загружаем слои foreach (var layerId in layerTable) { var layer = new DwgLayer(layerId); layer.Initialization(transaction); layers.Add(layerId, layer); } }