Skip to content

Commit

Permalink
update sameple code
Browse files Browse the repository at this point in the history
  • Loading branch information
chuongmep committed Nov 12, 2024
1 parent 785f28e commit 7ed820f
Show file tree
Hide file tree
Showing 3 changed files with 180 additions and 34 deletions.
144 changes: 110 additions & 34 deletions Test/Sample/UnloadAndSaveModelAsCloudCommand.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CsvHelper;
using Microsoft.Win32;
using Application = Autodesk.Revit.ApplicationServices.Application;

namespace Test
Expand All @@ -17,39 +22,105 @@ public Result Execute(ExternalCommandData commandData, ref string message, Eleme
{
//UIApplication uiApp = commandData.Application;
//uiApp.Idling += ApplicationIdling;
string dir = @"D:\Development\Revit\Project\F7H-M";
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";
Guid projectId = new Guid("ca790fb5-141d-4ad5-b411-0461af2e9748");
string folderIdMech = "urn:adsk.wipprod:fs.folder:co.kHlWc1ajSHSxey-_bGjKwg";
// string folderIdElec = "urn:adsk.wipprod:fs.folder:co.xm8eECPARESSL00xbO7qLw";
string csvPath = OpenDialogGetPath();
string dir = OpenDirectoryDialog();
if(string.IsNullOrEmpty(csvPath))
{
TaskDialog.Show("Error", "Please select uniformat code a csv file.");
return Result.Failed;
}
List<string> revitPaths = GetAllRevitPaths(dir);
List<string> report = new List<string>();

foreach (string revitPath in revitPaths)
// start write a .txt log file
string logPath = Path.Combine(dir, "log.txt");
using (StreamWriter writer = new StreamWriter(logPath))
{
UnloadRevitLinks(revitPath);
continue;
string fileName = System.IO.Path.GetFileNameWithoutExtension(revitPath);

Document? doc = OpenDocument(commandData.Application.Application, revitPath, report);
if (doc == null)
foreach (string revitPath in revitPaths)
{
continue;
}
try
{
doc.SaveAsCloudModel(accountId, projectId, folderId, fileName);
// sleep for 5 seconds to allow the cloud model to be created
Thread.Sleep(5000);
doc.Close(false);
}
catch (Exception e)
{
Trace.WriteLine(e.Message);
UnloadRevitLinks(revitPath,writer);
string fileName = Path.GetFileNameWithoutExtension(revitPath);

Document? doc = OpenDocument(commandData.Application.Application, revitPath, report,writer);
if (doc == null)
{
continue;
}
try
{

// string csvPath = @"C:\Users\vho2\Downloads\AseemblyCodeUpdate\Uniformat.csv";
// read csv file
var allElements = new FilteredElementCollector(doc).WhereElementIsElementType()
//group by id
.GroupBy(x => x.Id.IntegerValue).Select(x => x.First())
.Where(x => x.Category != null);


using (var reader = new StreamReader(csvPath))
{
using Autodesk.Revit.DB.Transaction tran = new Transaction(doc, "Update Assembly Code");
tran.Start();
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<Uniformat>().ToList();
foreach (var record in records)
{
var type_elements = allElements.Where(x => Math.Abs(x.Category.Id.IntegerValue - record.Category) < 0.001);
foreach (var element in type_elements)
{
Parameter parameter = element.get_Parameter(BuiltInParameter.UNIFORMAT_CODE);
if (parameter != null && !parameter.IsReadOnly)
{
parameter.Set(record.UniformatCode);
}
}
}
}
tran.Commit();
}
// sync to central
//doc.SynchronizeWithCentral(new TransactWithCentralOptions(), new SynchronizeWithCentralOptions());
// publish model by command
doc.SaveAsCloudModel(accountId, projectId, folderIdMech, fileName);
// sleep for 5 seconds to allow the cloud model to be created
Thread.Sleep(5000);
doc.Close(false);
}
catch (Exception e)
{
Trace.WriteLine(e.Message);
}
}
}

TaskDialog.Show("Done", "Process complete.");
Process.Start(logPath);
return Result.Succeeded;
}

public string OpenDialogGetPath()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "CSV files (*.csv)|*.csv";
if (openFileDialog.ShowDialog() == true)
{
return openFileDialog.FileName;
}
return string.Empty;
}
public string OpenDirectoryDialog()
{
System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
return folderBrowserDialog.SelectedPath;
}
return string.Empty;
}
private void ApplicationIdling(object sender, Autodesk.Revit.UI.Events.IdlingEventArgs e)
{
UIApplication? uiApp = sender as UIApplication;
Expand Down Expand Up @@ -85,34 +156,39 @@ public List<string> GetAllRevitPaths(string folderPath)
return revitPaths;
}

private static string UnloadRevitLinks(string path)
private static string UnloadRevitLinks(string path,StreamWriter writer)
{
var fileName = Path.GetFileNameWithoutExtension(path);
writer.WriteLine($"Model'{fileName}'");
ModelPath mPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(path);
//bool isDocumentTransmitted = TransmissionData.IsDocumentTransmitted(mPath);
// if (!isDocumentTransmitted)
// {
// writer.WriteLine($"Model {fileName} is not transmitted");
// return 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)
LinkedFileStatus status = extRef.GetLinkedFileStatus();
if (status == LinkedFileStatus.Loaded && extRef.ExternalFileReferenceType==ExternalFileReferenceType.RevitLink)
{
tData.SetDesiredReferenceData(refId, extRef.GetPath(), extRef.PathType, false);
string name = ModelPathUtils.ConvertModelPathToUserVisiblePath(extRef.GetPath());
writer.WriteLine($"{extRef.ExternalFileReferenceType.ToString()}:'{name}' Status: {status}");
//tData.SetDesiredReferenceData(elementid, 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)
private static Document? OpenDocument(Application app, string filePath, List<string> errorMessages,StreamWriter writer)
{
UnloadRevitLinks(filePath);
UnloadRevitLinks(filePath,writer);

ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);
OpenOptions options = new OpenOptions
Expand Down
64 changes: 64 additions & 0 deletions Test/Sample/UpdateAssemblyCode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CsvHelper;
using CsvHelper.Configuration;

namespace Test;

[Transaction(TransactionMode.Manual)]
public class UpdateAssemblyCode : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
string csvPath = @"C:\Users\vho2\Downloads\AseemblyCodeUpdate\Uniformat.csv";
var app = commandData.Application.Application;
var uiapp = new UIApplication(app);
var uidoc = uiapp.ActiveUIDocument;
var doc = uidoc.Document;
// read csv file
var allElements = new FilteredElementCollector(doc).WhereElementIsElementType()
//group by id
.GroupBy(x => x.Id.IntegerValue).Select(x => x.First())
.Where(x => x.Category != null);


using (var reader = new StreamReader(csvPath))
{
using Autodesk.Revit.DB.Transaction tran = new Transaction(doc, "Update Assembly Code");
tran.Start();
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<Uniformat>().ToList();
foreach (var record in records)
{
var type_elements = allElements.Where(x => Math.Abs(x.Category.Id.IntegerValue - record.Category) < 0.001);
foreach (var element in type_elements)
{
Parameter parameter = element.get_Parameter(BuiltInParameter.UNIFORMAT_CODE);
if (parameter != null && !parameter.IsReadOnly)
{
parameter.Set(record.UniformatCode);
}
}
}
}
tran.Commit();
}
// sync to central
doc.SynchronizeWithCentral(new TransactWithCentralOptions(), new SynchronizeWithCentralOptions());
// publish model by command

return Result.Succeeded;
}
}
public class Uniformat
{
public double Category { get; set; }
public string UniformatCode { get; set; }
}
6 changes: 6 additions & 0 deletions Test/Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<IsPackable>false</IsPackable>
<UseWindowsForms>true</UseWindowsForms>
<PlatformTarget>x64</PlatformTarget>
<UseWpf>true</UseWpf>
<Configurations>Debug R21;Debug R22;Debug R23;Debug R24;Debug R25;</Configurations>
Expand Down Expand Up @@ -48,7 +49,12 @@
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<Description>A Project Support for developer in revit </Description>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug R23' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CsvHelper" Version="33.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.7" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.7" />
Expand Down

0 comments on commit 7ed820f

Please sign in to comment.