public void LoadXrefs() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; ed.WriteMessage("\n=== +++ Command Load Xrefs Start +++"); LayoutManager lm = LayoutManager.Current; lm.CurrentLayout = "Layout1"; Database db = doc.Database; try { string dwgName = Path.GetFileNameWithoutExtension(doc.Name); string folderPath = Path.GetDirectoryName(doc.Name); List<SheetObject> sheetObjects = Helpers.SheetsObjectsFromCSV(folderPath, dwgName); List<ObjectId[]> viewportContentList = new List<ObjectId[]>(); //get document name ed.WriteMessage("\n=== Dwg Name: " + doc.Name + "\n"); foreach (SheetObject sheetObject in sheetObjects) { ed.WriteMessage("=== Xref(s): " + sheetObject.xrefName + "\n"); string layerName = $"0-{sheetObject.xrefName}"; using (Transaction trans = db.TransactionManager.StartTransaction()) { LayerTable layerTable = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectId layer = new ObjectId(); foreach (ObjectId layerId in layerTable) { LayerTableRecord currentLayer = trans.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord; if (currentLayer.Name == layerName) { layer = layerId; } } //Load Xref //https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2015/ENU/AutoCAD-NET/files/GUID-D6EE5FE7-C0BC-4E9B-AAE3-3B5A14B870FE-htm.html #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 = 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); } ed.WriteMessage("=== xref loaded\n"); } #endregion trans.Commit(); }//close transaction } ed.WriteMessage("Save file \n"); db.SaveAs(doc.Name, true, DwgVersion.Current, doc.Database.SecurityParameters); ed.WriteMessage("\n=== +++ Command Load Xrefs End +++"); }//close try catch { } finally { } }
public void MergeMerge() { 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); //using a Sheet Object var logFile = File.ReadAllLines($"{folderPath}\\summary.csv").Select(line => line.Split(',')).ToList<string[]>(); logFile.RemoveAt(0); //get csv file content 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],item[11])); } SheetObject sheetObject = sheetsList.Where(x => x.sheetName == dwgName).First(); 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; //get document name ed.WriteMessage("\n======================== Dwg Name: " + doc.Name + "\n"); ed.WriteMessage("======================== Xref(s): " + sheetObject.xrefName + "\n"); //find the xref viewport and delete its content //ed.SwitchToPaperSpace(); using (Transaction trans = db.TransactionManager.StartTransaction()) { 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>(); //Create Layer to store xref #region string layerName = $"0-{sheetObject.xrefName}"; Helpers.CreateLayer(db, trans, layerName); ed.WriteMessage("======================== Layer created: " + layerName + "\n"); LayerTable layerTable = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectId layer = new ObjectId(); foreach (ObjectId layerId in layerTable) { LayerTableRecord currentLayer = trans.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord; if (currentLayer.Name == layerName) { layer = layerId; layerToFreeze.Add(layerId); } } #endregion //Find the equivalent Revit viewport #region 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 //Delete Viewport Content #region Point3dCollection vpCorners = GetViewportBoundary(matchingViewport); Matrix3d mt = PaperToModel(matchingViewport); Point3dCollection vpCornersInModel = TransformPaperSpacePointToModelSpace(vpCorners, mt); ObjectId[] viewportContent = null; try { viewportContent = SelectEntitisInModelSpaceByViewport(doc, vpCornersInModel); ed.WriteMessage("======================== Viewport objects: " + viewportContent.Length.ToString() + "\n"); } catch (System.Exception ex) { ed.WriteMessage("======================== Error: " + ex.Message + "\n"); } if (viewportContent != null) { foreach (ObjectId item in viewportContent) { Entity e = (Entity)trans.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"); } #endregion //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 = 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); } ed.WriteMessage("======================== xref loaded\n"); } #endregion //Recenter Viewport #region Helpers.UpdateViewport(matchingViewport, revitViewportCentre, revitViewCentreWCS, degrees, vpWidht, vpHeight); ed.WriteMessage("======================== Viewport updated \n"); #endregion ed.WriteMessage("Swith 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"); trans.Commit(); } ed.WriteMessage("Switch back to paper space \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 void Merge() { 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); //we will freeze the } //else //{ // layerToFreeze.Add(layerId); //} } //Attch Xref //string PathName = $"{pathName}\\{dict[name][10]}"; string PathName = $"{pathName}\\{sheetObject.xrefName}"; //ObjectId acXrefId = db.AttachXref(PathName, dict[name][10]); 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 VP = 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; if (VP != 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 { Helpers.UpdateViewport(VP, revitViewportCentre, revitViewCentreWCS, degrees, vpWidht, vpHeight); } else if (VP != null && VP.CenterPoint.DistanceTo(revitViewportCentre) < 100) //Should use the closest viewport, not a fixed distance { Helpers.UpdateViewport(VP, revitViewportCentre, revitViewCentreWCS, degrees, vpWidht, vpHeight); } else { //freeze the xref layer on all the other viewports VP.FreezeLayersInViewport(layerToFreeze.GetEnumerator()); } } //Purge unused layers Helpers.PurgeUnusedLayers(trans, db); Helpers.PurgeDatabase(db, trans); trans.Commit(); } 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 ); }