Skip to content

Commit

Permalink
update sample save central files
Browse files Browse the repository at this point in the history
  • Loading branch information
chuongmep committed Oct 21, 2024
1 parent eae8319 commit 584fe04
Show file tree
Hide file tree
Showing 5 changed files with 286 additions and 0 deletions.
2 changes: 2 additions & 0 deletions AddInManager.sln
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ Global
{1661572C-EF3A-4DD6-83BD-CB4239CE8CDD}.Release R25|Any CPU.ActiveCfg = Release R25|Any CPU
{1661572C-EF3A-4DD6-83BD-CB4239CE8CDD}.Debug R25|Any CPU.ActiveCfg = Release R25|Any CPU
{1661572C-EF3A-4DD6-83BD-CB4239CE8CDD}.Debug R25|Any CPU.Build.0 = Release R25|Any CPU
{1661572C-EF3A-4DD6-83BD-CB4239CE8CDD}.Debug R23|Any CPU.Build.0 = Debug R23|Any CPU
{1661572C-EF3A-4DD6-83BD-CB4239CE8CDD}.Debug R22|Any CPU.Build.0 = Debug R22|Any CPU
{21460D85-C4AD-49D5-963F-CF13C4AE99EB}.Debug R22|Any CPU.ActiveCfg = Debug R22|Any CPU
{21460D85-C4AD-49D5-963F-CF13C4AE99EB}.Debug R22|Any CPU.Build.0 = Debug R22|Any CPU
{21460D85-C4AD-49D5-963F-CF13C4AE99EB}.Installer|Any CPU.ActiveCfg = Debug R22|Any CPU
Expand Down
114 changes: 114 additions & 0 deletions Test/Sample/CreateSolildCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace Test;

[Transaction(TransactionMode.Manual)]
public class CreateSolidCommand : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
// // create a solid

var uidoc = commandData.Application.ActiveUIDocument;
var doc = uidoc.Document;
using Autodesk.Revit.DB.Transaction tran = new Transaction(doc, "zz");
tran.Start();
var solid = SolidFromFace(commandData);
CreateDirectShape(doc,solid);
tran.Commit();

return Result.Succeeded;
}

void CreateDirectShape(Document doc, Solid solid)
{
var ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
ds.ApplicationId = "ApplicationId";
ds.ApplicationDataId = "ApplicationDataId";
ds.SetShape(new GeometryObject[] { solid });
}

Solid? GetSolid(Autodesk.Revit.DB.Element? element)
{
Options options = new Options();
options.ComputeReferences = true;
options.DetailLevel = ViewDetailLevel.Fine;
options.IncludeNonVisibleObjects = false;
GeometryElement geomElem = element.get_Geometry(options);
foreach (GeometryObject geomObj in geomElem)
{
Solid? solid = geomObj as Solid;
if (solid != null)
{
return solid;
}
}
return null;
}

public static Solid SolidFromFace(ExternalCommandData commandData)
{
// pick a face
double height = 1;
var uidoc = commandData.Application.ActiveUIDocument;
Reference reference = uidoc.Selection.PickObject(ObjectType.Face, "Select a face");
var doc = uidoc.Document;
var face = doc.GetElement(reference).GetGeometryObjectFromReference(reference) as Face;
var vertices = face.Triangulate().Vertices.ToList();
return SolidFromVertices(vertices, height);
}
public static Solid SolidFromVertices(List<XYZ> vertices, double height)
{
// create face
List<CurveLoop> curveLoops = new List<CurveLoop>();
CurveLoop curveLoop = new CurveLoop();
for (int i = 0; i < vertices.Count; i++)
{
curveLoop.Append(Line.CreateBound(vertices[i], vertices[(i + 1) % vertices.Count]));
}
curveLoops.Add(curveLoop);
Solid solid = GeometryCreationUtilities.CreateExtrusionGeometry(curveLoops, XYZ.BasisZ, height);
return solid;

}
public Solid SolidFromBoundingBox(ExternalCommandData commandData)
{
var doc = commandData.Application.ActiveUIDocument.Document;
Reference reference =
commandData.Application.ActiveUIDocument.Selection.PickObject(ObjectType.Element,
"Select a extrusion element");
var extrusion = commandData.Application.ActiveUIDocument.Document.GetElement(reference);
Solid? solid = GetSolid(extrusion);
BoundingBoxXYZ bbox = solid.GetBoundingBox();
// corners in BBox coords
XYZ pt0 = new XYZ(bbox.Min.X, bbox.Min.Y, bbox.Min.Z);
XYZ pt1 = new XYZ(bbox.Max.X, bbox.Min.Y, bbox.Min.Z);
XYZ pt2 = new XYZ(bbox.Max.X, bbox.Max.Y, bbox.Min.Z);
XYZ pt3 = new XYZ(bbox.Min.X, bbox.Max.Y, bbox.Min.Z);
//edges in BBox coords
Line edge0 = Line.CreateBound(pt0, pt1);
Line edge1 = Line.CreateBound(pt1, pt2);
Line edge2 = Line.CreateBound(pt2, pt3);
Line edge3 = Line.CreateBound(pt3, pt0);
//create loop, still in BBox coords
List<Curve> edges = new List<Curve>();
edges.Add(edge0);
edges.Add(edge1);
edges.Add(edge2);
edges.Add(edge3);
Double height = bbox.Max.Z - bbox.Min.Z;
CurveLoop baseLoop = CurveLoop.Create(edges);
List<CurveLoop> loopList = new List<CurveLoop>();
loopList.Add(baseLoop);
Solid preTransformBox = GeometryCreationUtilities.CreateExtrusionGeometry(loopList, XYZ.BasisZ, height);
Solid transformBox = SolidUtils.CreateTransformed(preTransformBox, bbox.Transform);
return transformBox;

}
}
File renamed without changes.
File renamed without changes.
170 changes: 170 additions & 0 deletions Test/Sample/UnloadAndSaveModelAsCloudCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.IO;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Application = Autodesk.Revit.ApplicationServices.Application;

namespace Test
{
[Transaction(TransactionMode.Manual)]
public class UnloadAndSaveModelAsCloudCommand : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIApplication uiApp = commandData.Application;
uiApp.Idling += ApplicationIdling;
string dir = @"D:\_WIP\Download\04-Mechanical_selected_2024-10-21_08-46-43am";
Guid accountId = new Guid("1715cf2b-cc12-46fd-9279-11bbc47e72f6");
Guid projectId = new Guid("58450c0d-394f-41b2-a7e6-7aa53665dfb8");
string folderId = "urn:adsk.wipprod:fs.folder:co.qslf4shtRpOHsZLUmwANiQ";
List<string> revitPaths = GetAllRevitPaths(dir);
List<string> report = new List<string>();

foreach (string revitPath in revitPaths)
{
UnloadRevitLinks(revitPath);
string fileName = System.IO.Path.GetFileNameWithoutExtension(revitPath);

Document? doc = OpenDocument(commandData.Application.Application, revitPath, report);
if (doc == null)
{
continue;
}
// Start transaction and use custom failure preprocessor
using Transaction transaction = new Transaction(doc, "Save As Cloud");
transaction.Start();

// Set the failure handler to suppress warnings
FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
failureOptions.SetFailuresPreprocessor(new IgnoreFailuresPreprocessor());
transaction.SetFailureHandlingOptions(failureOptions);

try
{
doc.SaveAsCloudModel(accountId, projectId, folderId, fileName);
}
catch (Exception e)
{
// Handle the error appropriately
report.Add($"Error saving cloud model: {e.Message}");
}

transaction.Commit();
}

TaskDialog.Show("Done", "Process complete.");
return Result.Succeeded;
}
private void ApplicationIdling(object sender, Autodesk.Revit.UI.Events.IdlingEventArgs e)
{
UIApplication? uiApp = sender as UIApplication;
if (uiApp == null)
{
return;
}
uiApp.Idling -= ApplicationIdling;
uiApp.Application.FailuresProcessing += Application_FailuresProcessing;
}
public void Application_FailuresProcessing(object sender, Autodesk.Revit.DB.Events.FailuresProcessingEventArgs e)
{
FailuresAccessor failuresAccessor = e.GetFailuresAccessor();
IList<FailureMessageAccessor> failureMessages = failuresAccessor.GetFailureMessages();
foreach (FailureMessageAccessor failureMessage in failureMessages)
{
if (failureMessage.GetSeverity() == FailureSeverity.Warning)
{
failuresAccessor.DeleteWarning(failureMessage);
}
}
e.SetProcessingResult(FailureProcessingResult.Continue);
}

public List<string> GetAllRevitPaths(string folderPath)
{
List<string> revitPaths = new List<string>();
string[] files = System.IO.Directory.GetFiles(folderPath, "*.rvt", SearchOption.AllDirectories);
foreach (string file in files)
{
revitPaths.Add(file);
}
return revitPaths;
}

private static string UnloadRevitLinks(string path)
{
ModelPath mPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(path);
TransmissionData tData = TransmissionData.ReadTransmissionData(mPath);

if (tData == null)
{
return path;
}

ICollection<ElementId> externalReferences = tData.GetAllExternalFileReferenceIds();
foreach (ElementId refId in externalReferences)
{
ExternalFileReference extRef = tData.GetLastSavedReferenceData(refId);
if (extRef.ExternalFileReferenceType == ExternalFileReferenceType.RevitLink)
{
tData.SetDesiredReferenceData(refId, extRef.GetPath(), extRef.PathType, false);
}
}

tData.IsTransmitted = true;
TransmissionData.WriteTransmissionData(mPath, tData);

return path;
}

private static Document? OpenDocument(Application app, string filePath, List<string> errorMessages)
{
UnloadRevitLinks(filePath);

ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);
OpenOptions options = new OpenOptions
{
DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets,
AllowOpeningLocalByWrongUser = true,
IgnoreExtensibleStorageSchemaConflict = true,
Audit = false,
};

try
{
Document? doc = app.OpenDocumentFile(modelPath, options);
if (doc == null || doc.IsLinked)
{
throw new Exception("Failed to open document or document is a linked file.");
}
return doc;
}
catch (Exception e)
{
errorMessages.Add($"Error opening Revit document '{System.IO.Path.GetFileName(filePath)}': {e.Message}");
return null;
}
}
}

// Custom IFailuresPreprocessor implementation to ignore warnings
public class IgnoreFailuresPreprocessor : IFailuresPreprocessor
{
public FailureProcessingResult PreprocessFailures(FailuresAccessor failuresAccessor)
{
IList<FailureMessageAccessor> failureMessages = failuresAccessor.GetFailureMessages();

foreach (FailureMessageAccessor failureMessage in failureMessages)
{
// This will delete all warning messages
if (failureMessage.GetSeverity() == FailureSeverity.Warning)
{
failuresAccessor.DeleteWarning(failureMessage);
}
}

return FailureProcessingResult.Continue;
}
}
}

0 comments on commit 584fe04

Please sign in to comment.