diff --git a/AddinDeployment/RemoveAddinAllVersions.bat b/AddinDeployment/RemoveAddinAllVersions.bat index 9c8150f..940c882 100644 --- a/AddinDeployment/RemoveAddinAllVersions.bat +++ b/AddinDeployment/RemoveAddinAllVersions.bat @@ -2,41 +2,11 @@ pushd %~dp0 -echo. -echo Removing BatchRvt addin for Revit 2015 -call RemoveAddin.bat 2015 - -echo. -echo Removing BatchRvt addin for Revit 2016 -call RemoveAddin.bat 2016 - -echo. -echo Removing BatchRvt addin for Revit 2017 -call RemoveAddin.bat 2017 - -echo. -echo Removing BatchRvt addin for Revit 2018 -call RemoveAddin.bat 2018 - -echo. -echo Removing BatchRvt addin for Revit 2019 -call RemoveAddin.bat 2019 - -echo. -echo Removing BatchRvt addin for Revit 2020 -call RemoveAddin.bat 2020 - -echo. -echo Removing BatchRvt addin for Revit 2021 -call RemoveAddin.bat 2021 - -echo. -echo Removing BatchRvt addin for Revit 2022 -call RemoveAddin.bat 2022 - -echo. -echo Removing BatchRvt addin for Revit 2023 -call RemoveAddin.bat 2023 +for %%i in (2015 2016 2017 2018 2019 2020 2021 2022 2023 2024) do ( + echo. + echo Removing BatchRvt addin for Revit %%i + call RemoveAddin.bat %%i + ) echo Done. echo. diff --git a/BatchRevitDynamo/App.config b/BatchRevitDynamo/App.config new file mode 100644 index 0000000..49206c2 --- /dev/null +++ b/BatchRevitDynamo/App.config @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRevitDynamo/BatchRevitDynamo.csproj b/BatchRevitDynamo/BatchRevitDynamo.csproj index 77878bb..95d1ab4 100644 --- a/BatchRevitDynamo/BatchRevitDynamo.csproj +++ b/BatchRevitDynamo/BatchRevitDynamo.csproj @@ -1,5 +1,6 @@  + Debug @@ -11,6 +12,9 @@ BatchRevitDynamo v4.8 512 + latestmajor + + true @@ -31,6 +35,12 @@ MinimumRecommendedRules.ruleset + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + False ..\References\IronPython-2.7.3\IronPython.dll @@ -51,13 +61,61 @@ False ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + False ..\References\JSON.NET\Newtonsoft.Json.dll + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + @@ -72,5 +130,32 @@ BatchRvtUtil + + + + + + + 6.12.0 + + + 4.20.70 + + + 2.7.0 + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + \ No newline at end of file diff --git a/BatchRevitDynamo/Properties/AssemblyInfo.cs b/BatchRevitDynamo/Properties/AssemblyInfo.cs index 8ba4694..1e3f676 100644 --- a/BatchRevitDynamo/Properties/AssemblyInfo.cs +++ b/BatchRevitDynamo/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -20,7 +19,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("b2fed296-9ea0-41dd-bb2f-951d481f527b")] - - - +[assembly: Guid("b2fed296-9ea0-41dd-bb2f-951d481f527b")] \ No newline at end of file diff --git a/BatchRevitDynamo/RevitBatchProcessor.cs b/BatchRevitDynamo/RevitBatchProcessor.cs index 90fc2aa..87f053a 100644 --- a/BatchRevitDynamo/RevitBatchProcessor.cs +++ b/BatchRevitDynamo/RevitBatchProcessor.cs @@ -17,203 +17,215 @@ // along with this program. If not, see . // // -using System; + using System.Collections.Generic; -using System.Linq; using BatchRvtUtil; -namespace BatchRevitDynamo +namespace BatchRevitDynamo; + +public static class RevitBatchProcessor { - public static class RevitBatchProcessor + public enum CentralFileOpenOption { - /// - /// Runs a Revit Batch Processing task. The Revit file list is provided as a list of strings. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static string RunTask( - bool toggleToExecute, // TODO: reconsider if this is needed here. - string taskScriptFilePath, - IEnumerable revitFileList, - UseRevitVersion useRevitVersion, - CentralFileOpenOption centralFileOpenOption, - bool discardWorksetsOnDetach, - bool deleteLocalAfter, - bool openLogFileWhenDone - ) - { - return BatchRvtTasks.RunTask( - taskScriptFilePath, - revitFileList, // Input is a list of Revit file paths. - (BatchRvtTasks.UseRevitVersion)useRevitVersion, - (BatchRvt.CentralFileOpenOption)centralFileOpenOption, - discardWorksetsOnDetach, - deleteLocalAfter, - openLogFileWhenDone, - taskData: null, - testModeFolderPath: null - ); - } + Detach = 0, + CreateNewLocal = 1 + } - /// - /// Runs a single (non-batch) Revit task. Any file processing is left up to the task script to manage! - /// - /// - /// - /// - /// - /// - public static string RunSingleTask( - bool toggleToExecute, // TODO: reconsider if this is needed here. - string taskScriptFilePath, - UseRevitVersion useRevitVersion, - bool openLogFileWhenDone - ) - { - return BatchRvtTasks.RunSingleTask( - taskScriptFilePath, - (BatchRvtTasks.UseRevitVersion)useRevitVersion, - openLogFileWhenDone, - taskData: null, - testModeFolderPath: null - ); - } + public enum RevitSessionOption + { + UseSeparateSessionPerFile = 0, + UseSameSessionForFilesOfSameVersion = 1 + } - /// - /// Runs a Revit Batch Processing task, with advanced options available. The Revit file list is provided as a list of strings. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static string RunTaskAdvanced( - bool toggleToExecute, // TODO: reconsider if this is needed here. - string taskScriptFilePath, - IEnumerable revitFileList, - UseRevitVersion useRevitVersion, - CentralFileOpenOption centralFileOpenOption, - bool discardWorksetsOnDetach, - bool deleteLocalAfter, - bool openLogFileWhenDone, - string logFolderPath, - int fileProcessingTimeOutInMinutes, - bool fallbackToMinimumAvailableRevitVersion - ) - { - return BatchRvtTasks.RunTaskAdvanced( - taskScriptFilePath, - revitFileList, - (BatchRvtTasks.UseRevitVersion)useRevitVersion, - (BatchRvt.CentralFileOpenOption)centralFileOpenOption, - discardWorksetsOnDetach, - deleteLocalAfter, - openLogFileWhenDone, - logFolderPath, - fileProcessingTimeOutInMinutes, - fallbackToMinimumAvailableRevitVersion, - taskData: null, - testModeFolderPath: null - ); - } + // NOTE: Dynamo scripts are not supported in Revit versions earlier than 2016. + public enum UseRevitVersion + { + RevitFileVersion = 0, + Revit2015 = 1, + Revit2016 = 2, + Revit2017 = 3, + Revit2018 = 4, + Revit2019 = 5, + Revit2020 = 6, + Revit2021 = 7, + Revit2022 = 8, + Revit2023 = 9, + Revit2024 = 10 - /// - /// Runs a Revit Batch Processing task, with settings provided by the specified settings file. - /// - /// - /// - /// - /// - /// - public static string RunTaskFromSettingsFile( - bool toggleToExecute, // TODO: reconsider if this is needed here. - string settingsFilePath, - string logFolderPath, - bool openLogFileWhenDone - ) - { - return BatchRvtTasks.RunTaskFromSettingsFile( - settingsFilePath, - logFolderPath, - openLogFileWhenDone - ); - } + } - /// - /// Runs a Revit Batch Processing task, with advanced options available. The Revit file list is provided by the specified Excel or text file path. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static string RunTaskOnListFile( - bool toggleToExecute, // TODO: reconsider if this is needed here. - string taskScriptFilePath, - string revitFileListFilePath, // Input is a file path to a list of Revit file paths. - UseRevitVersion useRevitVersion, - CentralFileOpenOption centralFileOpenOption, - bool discardWorksetsOnDetach, - bool deleteLocalAfter, - bool openLogFileWhenDone, - string logFolderPath, - int fileProcessingTimeOutInMinutes, - bool fallbackToMinimumAvailableRevitVersion - ) - { - return BatchRvtTasks.RunTask( - taskScriptFilePath, - revitFileListFilePath, - BatchRvt.RevitProcessingOption.BatchRevitFileProcessing, - (BatchRvtTasks.UseRevitVersion)useRevitVersion, - (BatchRvt.CentralFileOpenOption)centralFileOpenOption, - discardWorksetsOnDetach, - deleteLocalAfter, - openLogFileWhenDone, - logFolderPath, - fileProcessingTimeOutInMinutes, - fallbackToMinimumAvailableRevitVersion, - taskData: null, - testModeFolderPath: null - ); - } + /// + /// Runs a Revit Batch Processing task. The Revit file list is provided as a list of strings. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static string RunTask( + bool toggleToExecute, // TODO: reconsider if this is needed here. + string taskScriptFilePath, + IEnumerable revitFileList, + UseRevitVersion useRevitVersion, + CentralFileOpenOption centralFileOpenOption, + bool discardWorksetsOnDetach, + bool deleteLocalAfter, + bool openLogFileWhenDone + ) + { + return BatchRvtTasks.RunTask( + taskScriptFilePath, + revitFileList, // Input is a list of Revit file paths. + (BatchRvtTasks.UseRevitVersion)useRevitVersion, + (BatchRvt.CentralFileOpenOption)centralFileOpenOption, + discardWorksetsOnDetach, + deleteLocalAfter, + openLogFileWhenDone, + null, + null + ); + } - // NOTE: Dynamo scripts are not supported in Revit versions earlier than 2016. - public enum UseRevitVersion { - RevitFileVersion = 0, - Revit2015 = 1, - Revit2016 = 2, - Revit2017 = 3, - Revit2018 = 4, - Revit2019 = 5, - Revit2020 = 6, - Revit2021 = 7, - Revit2022 = 8, - Revit2023 = 9 - } - public enum RevitSessionOption { UseSeparateSessionPerFile = 0, UseSameSessionForFilesOfSameVersion = 1 } - public enum CentralFileOpenOption { Detach = 0, CreateNewLocal = 1 } + /// + /// Runs a single (non-batch) Revit task. Any file processing is left up to the task script to manage! + /// + /// + /// + /// + /// + /// + public static string RunSingleTask( + bool toggleToExecute, // TODO: reconsider if this is needed here. + string taskScriptFilePath, + UseRevitVersion useRevitVersion, + bool openLogFileWhenDone + ) + { + return BatchRvtTasks.RunSingleTask( + taskScriptFilePath, + (BatchRvtTasks.UseRevitVersion)useRevitVersion, + openLogFileWhenDone, + null, + null + ); + } + + /// + /// Runs a Revit Batch Processing task, with advanced options available. The Revit file list is provided as a list of + /// strings. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static string RunTaskAdvanced( + bool toggleToExecute, // TODO: reconsider if this is needed here. + string taskScriptFilePath, + IEnumerable revitFileList, + UseRevitVersion useRevitVersion, + CentralFileOpenOption centralFileOpenOption, + bool discardWorksetsOnDetach, + bool deleteLocalAfter, + bool openLogFileWhenDone, + string logFolderPath, + int fileProcessingTimeOutInMinutes, + bool fallbackToMinimumAvailableRevitVersion + ) + { + return BatchRvtTasks.RunTaskAdvanced( + taskScriptFilePath, + revitFileList, + (BatchRvtTasks.UseRevitVersion)useRevitVersion, + (BatchRvt.CentralFileOpenOption)centralFileOpenOption, + discardWorksetsOnDetach, + deleteLocalAfter, + openLogFileWhenDone, + logFolderPath, + fileProcessingTimeOutInMinutes, + fallbackToMinimumAvailableRevitVersion, + null, + null + ); + } + + /// + /// Runs a Revit Batch Processing task, with settings provided by the specified settings file. + /// + /// + /// + /// + /// + /// + public static string RunTaskFromSettingsFile( + bool toggleToExecute, // TODO: reconsider if this is needed here. + string settingsFilePath, + string logFolderPath, + bool openLogFileWhenDone + ) + { + return BatchRvtTasks.RunTaskFromSettingsFile( + settingsFilePath, + logFolderPath, + openLogFileWhenDone + ); + } + + /// + /// Runs a Revit Batch Processing task, with advanced options available. The Revit file list is provided by the + /// specified Excel or text file path. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static string RunTaskOnListFile( + bool toggleToExecute, // TODO: reconsider if this is needed here. + string taskScriptFilePath, + string revitFileListFilePath, // Input is a file path to a list of Revit file paths. + UseRevitVersion useRevitVersion, + CentralFileOpenOption centralFileOpenOption, + bool discardWorksetsOnDetach, + bool deleteLocalAfter, + bool openLogFileWhenDone, + string logFolderPath, + int fileProcessingTimeOutInMinutes, + bool fallbackToMinimumAvailableRevitVersion + ) + { + return BatchRvtTasks.RunTask( + taskScriptFilePath, + revitFileListFilePath, + BatchRvt.RevitProcessingOption.BatchRevitFileProcessing, + (BatchRvtTasks.UseRevitVersion)useRevitVersion, + (BatchRvt.CentralFileOpenOption)centralFileOpenOption, + discardWorksetsOnDetach, + deleteLocalAfter, + openLogFileWhenDone, + logFolderPath, + fileProcessingTimeOutInMinutes, + fallbackToMinimumAvailableRevitVersion, + null, + null + ); } -} +} \ No newline at end of file diff --git a/BatchRevitDynamo/packages.config b/BatchRevitDynamo/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRevitDynamo/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvt/App.config b/BatchRvt/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvt/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvt/BatchRvt.csproj b/BatchRvt/BatchRvt.csproj index 2a8ea07..3ade107 100644 --- a/BatchRvt/BatchRvt.csproj +++ b/BatchRvt/BatchRvt.csproj @@ -1,95 +1,167 @@  - - - Debug - AnyCPU - {C877620C-DE32-455C-BF21-8F3E73E9DF68} - Exe - Properties - BatchRvt - BatchRvt - v4.8 - 512 - - - BatchRvtCommand.BatchRvtMain - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - prompt - MinimumRecommendedRules.ruleset - true - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - prompt - MinimumRecommendedRules.ruleset - true - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - True - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - True - - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - True - - - - False - ..\References\JSON.NET\Newtonsoft.Json.dll - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - {b880dd15-184b-4ce2-86fc-08bac05e0271} - BatchRvtUtil - - - - + + + + Debug + AnyCPU + {C877620C-DE32-455C-BF21-8F3E73E9DF68} + Exe + Properties + BatchRvt + BatchRvt + v4.8 + 512 + latestmajor + + + BatchRvtCommand.BatchRvtMain + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + true + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + true + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + True + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + True + + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + True + + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + False + ..\References\JSON.NET\Newtonsoft.Json.dll + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + {b880dd15-184b-4ce2-86fc-08bac05e0271} + BatchRvtUtil + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/BatchRvt/BatchRvtMain.cs b/BatchRvt/BatchRvtMain.cs index d754b47..266d3e8 100644 --- a/BatchRvt/BatchRvtMain.cs +++ b/BatchRvt/BatchRvtMain.cs @@ -17,76 +17,68 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.IO; -using System.Windows.Forms; using System.Runtime.InteropServices; +using System.Windows.Forms; +using BatchRvtUtil; -namespace BatchRvtCommand +namespace BatchRvtCommand; + +public class BatchRvtMain { - public class BatchRvtMain - { - private const string BatchRvtConsoleTitle = "Batch Revit File Processor"; + private const string BatchRvtConsoleTitle = "Batch Revit File Processor"; - private const int WindowWidth = 160; - private const int WindowHeight = 60; - private const int BufferWidth = 320; - private const int BufferHeight = WindowHeight * 50; + private const int WindowWidth = 160; + private const int WindowHeight = 60; + private const int BufferWidth = 320; + private const int BufferHeight = WindowHeight * 50; - [STAThread] - private static void Main(string[] args) - { - Application.EnableVisualStyles(); + [STAThread] + private static void Main(string[] args) + { + Application.EnableVisualStyles(); - if (HasConsole()) - { - InitConsole(); - } + if (HasConsole()) InitConsole(); - var batchRvtFolderPath = GetExecutableFolderPath(); - BatchRvtUtil.BatchRvt.ExecuteMonitorScript(batchRvtFolderPath); + var batchRvtFolderPath = GetExecutableFolderPath(); + BatchRvt.ExecuteMonitorScript(batchRvtFolderPath); + } - return; - } + private static void InitConsole() + { + Console.Title = BatchRvtConsoleTitle; - private static void InitConsole() + try { - Console.Title = BatchRvtConsoleTitle; - - try - { - Console.SetWindowSize( - Math.Min(WindowWidth, Console.LargestWindowWidth), - Math.Min(WindowHeight, Console.LargestWindowHeight) - ); + Console.SetWindowSize( + Math.Min(WindowWidth, Console.LargestWindowWidth), + Math.Min(WindowHeight, Console.LargestWindowHeight) + ); - Console.SetBufferSize(BufferWidth, BufferHeight); - } - catch (ArgumentOutOfRangeException e) - { - // Can occur when output has been redirected via the command-line. - } - catch (IOException e) - { - // Can occur when output has been redirected via the command-line. - } - - return; + Console.SetBufferSize(BufferWidth, BufferHeight); } - - private static string GetExecutableFolderPath() + catch (ArgumentOutOfRangeException e) { - return AppDomain.CurrentDomain.BaseDirectory; + // Can occur when output has been redirected via the command-line. } - - [DllImport("kernel32.dll")] - private static extern IntPtr GetConsoleWindow(); - - private static bool HasConsole() + catch (IOException e) { - return (GetConsoleWindow() != IntPtr.Zero); + // Can occur when output has been redirected via the command-line. } } -} + + private static string GetExecutableFolderPath() + { + return AppDomain.CurrentDomain.BaseDirectory; + } + + [DllImport("kernel32.dll")] + private static extern IntPtr GetConsoleWindow(); + + private static bool HasConsole() + { + return GetConsoleWindow() != IntPtr.Zero; + } +} \ No newline at end of file diff --git a/BatchRvt/Properties/AssemblyInfo.cs b/BatchRvt/Properties/AssemblyInfo.cs index 0549e33..27ce0d5 100644 --- a/BatchRvt/Properties/AssemblyInfo.cs +++ b/BatchRvt/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("4dd28256-d644-4b56-9eba-75ee51c11119")] +[assembly: Guid("4dd28256-d644-4b56-9eba-75ee51c11119")] \ No newline at end of file diff --git a/BatchRvt/packages.config b/BatchRvt/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvt/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2015/App.config b/BatchRvtAddin2015/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtAddin2015/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2015/BatchRvtAddin2015.csproj b/BatchRvtAddin2015/BatchRvtAddin2015.csproj index f856aa8..8f79d2b 100644 --- a/BatchRvtAddin2015/BatchRvtAddin2015.csproj +++ b/BatchRvtAddin2015/BatchRvtAddin2015.csproj @@ -1,97 +1,168 @@  - - - Debug - AnyCPU - {5BFED691-8D2B-45F7-B210-96D29840B64E} - Library - Properties - BatchRvt.Addin.Revit2015 - BatchRvtAddin2015 - v4.8 - 512 - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - True - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - True - - - ..\References\Revit\2015\RevitAPI.dll - False - - - ..\References\Revit\2015\RevitAPIUI.dll - False - - - - - - - - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - - - - - - - - call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2015" - - + + + + Debug + AnyCPU + {5BFED691-8D2B-45F7-B210-96D29840B64E} + Library + Properties + BatchRvt.Addin.Revit2015 + BatchRvtAddin2015 + v4.8 + 512 + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + True + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + True + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + ..\References\Revit\2015\RevitAPI.dll + False + + + ..\References\Revit\2015\RevitAPIUI.dll + False + + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + + + + + + + + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2015" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2015/BatchRvtAddinApplication.cs b/BatchRvtAddin2015/BatchRvtAddinApplication.cs index 993aa21..74920b6 100644 --- a/BatchRvtAddin2015/BatchRvtAddinApplication.cs +++ b/BatchRvtAddin2015/BatchRvtAddinApplication.cs @@ -17,18 +17,15 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.ComponentModel; using System.IO; -using WinForms = System.Windows.Forms; - -using Autodesk.Revit.UI; -using Autodesk.Revit.Attributes; using Autodesk.Revit.ApplicationServices; - +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; namespace BatchRvt.Addin.Revit2015 { @@ -38,15 +35,6 @@ namespace BatchRvt.Addin.Revit2015 [Description("BatchRvtAddin")] public class BatchRvtAddinApplication : IExternalApplication { - private static void SetupBatchScriptHost(ControlledApplication controlledApplication) - { - var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); - - var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); - - batchRvtExternalEventHandler.Raise(); - } - public Result OnStartup(UIControlledApplication uiApplication) { SetupBatchScriptHost(uiApplication.ControlledApplication); @@ -58,6 +46,15 @@ public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } } public class BatchRvtExternalEventHandler : IExternalEventHandler @@ -67,15 +64,15 @@ public class BatchRvtExternalEventHandler : IExternalEventHandler public BatchRvtExternalEventHandler(string pluginFolderPath) { - this.externalEvent_ = ExternalEvent.Create(this); - this.pluginFolderPath_ = pluginFolderPath; + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; } public void Execute(UIApplication uiApp) { try { - ScriptHostUtil.ExecuteBatchScriptHost(this.pluginFolderPath_, uiApp); + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); } catch (Exception e) { @@ -90,7 +87,7 @@ public string GetName() public ExternalEventRequest Raise() { - return this.externalEvent_.Raise(); + return externalEvent_.Raise(); } } -} +} \ No newline at end of file diff --git a/BatchRvtAddin2015/Properties/AssemblyInfo.cs b/BatchRvtAddin2015/Properties/AssemblyInfo.cs index 8866bb1..24ada9b 100644 --- a/BatchRvtAddin2015/Properties/AssemblyInfo.cs +++ b/BatchRvtAddin2015/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9226492c-cf44-479b-b2c6-1fa3ea2be6eb")] +[assembly: Guid("9226492c-cf44-479b-b2c6-1fa3ea2be6eb")] \ No newline at end of file diff --git a/BatchRvtAddin2015/Properties/GlobalAssemblyInfo.cs b/BatchRvtAddin2015/Properties/GlobalAssemblyInfo.cs index f559471..330194b 100644 --- a/BatchRvtAddin2015/Properties/GlobalAssemblyInfo.cs +++ b/BatchRvtAddin2015/Properties/GlobalAssemblyInfo.cs @@ -6,6 +6,8 @@ // Revision // -[assembly: System.Reflection.AssemblyVersion("1.8.0.0")] -[assembly: System.Reflection.AssemblyInformationalVersion("1.8.0.0")] -[assembly: System.Reflection.AssemblyFileVersion("1.8.0.0")] \ No newline at end of file +using System.Reflection; + +[assembly: AssemblyVersion("1.8.0.0")] +[assembly: AssemblyInformationalVersion("1.8.0.0")] +[assembly: AssemblyFileVersion("1.8.0.0")] \ No newline at end of file diff --git a/BatchRvtAddin2015/packages.config b/BatchRvtAddin2015/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtAddin2015/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2016/App.config b/BatchRvtAddin2016/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtAddin2016/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2016/BatchRvtAddin2016.csproj b/BatchRvtAddin2016/BatchRvtAddin2016.csproj index a291f67..e761d11 100644 --- a/BatchRvtAddin2016/BatchRvtAddin2016.csproj +++ b/BatchRvtAddin2016/BatchRvtAddin2016.csproj @@ -1,99 +1,170 @@  - - - Debug - AnyCPU - {FE49BFB7-D21D-4B17-9144-D7F2B533EFD2} - Library - Properties - BatchRvt.Addin.Revit2016 - BatchRvtAddin2016 - v4.8 - 512 - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - True - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - True - - - ..\References\Revit\2016\RevitAPI.dll - False - - - ..\References\Revit\2016\RevitAPIUI.dll - False - - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - - - - - - - - call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2016" - - + + + + Debug + AnyCPU + {FE49BFB7-D21D-4B17-9144-D7F2B533EFD2} + Library + Properties + BatchRvt.Addin.Revit2016 + BatchRvtAddin2016 + v4.8 + 512 + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + True + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + True + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + ..\References\Revit\2016\RevitAPI.dll + False + + + ..\References\Revit\2016\RevitAPIUI.dll + False + + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + + + + + + + + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2016" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2016/BatchRvtAddinApplication.cs b/BatchRvtAddin2016/BatchRvtAddinApplication.cs index e9bd64d..db7b260 100644 --- a/BatchRvtAddin2016/BatchRvtAddinApplication.cs +++ b/BatchRvtAddin2016/BatchRvtAddinApplication.cs @@ -17,18 +17,15 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.ComponentModel; using System.IO; -using WinForms = System.Windows.Forms; - -using Autodesk.Revit.UI; -using Autodesk.Revit.Attributes; using Autodesk.Revit.ApplicationServices; - +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; namespace BatchRvt.Addin.Revit2016 { @@ -38,15 +35,6 @@ namespace BatchRvt.Addin.Revit2016 [Description("BatchRvtAddin")] public class BatchRvtAddinApplication : IExternalApplication { - private static void SetupBatchScriptHost(ControlledApplication controlledApplication) - { - var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); - - var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); - - batchRvtExternalEventHandler.Raise(); - } - public Result OnStartup(UIControlledApplication uiApplication) { SetupBatchScriptHost(uiApplication.ControlledApplication); @@ -58,6 +46,15 @@ public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } } public class BatchRvtExternalEventHandler : IExternalEventHandler @@ -67,15 +64,15 @@ public class BatchRvtExternalEventHandler : IExternalEventHandler public BatchRvtExternalEventHandler(string pluginFolderPath) { - this.externalEvent_ = ExternalEvent.Create(this); - this.pluginFolderPath_ = pluginFolderPath; + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; } public void Execute(UIApplication uiApp) { try { - ScriptHostUtil.ExecuteBatchScriptHost(this.pluginFolderPath_, uiApp); + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); } catch (Exception e) { @@ -90,7 +87,7 @@ public string GetName() public ExternalEventRequest Raise() { - return this.externalEvent_.Raise(); + return externalEvent_.Raise(); } } -} +} \ No newline at end of file diff --git a/BatchRvtAddin2016/Properties/AssemblyInfo.cs b/BatchRvtAddin2016/Properties/AssemblyInfo.cs index 669b5ee..aee4776 100644 --- a/BatchRvtAddin2016/Properties/AssemblyInfo.cs +++ b/BatchRvtAddin2016/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("8add8aeb-9baa-47d6-b52d-12e5e0eadacf")] +[assembly: Guid("8add8aeb-9baa-47d6-b52d-12e5e0eadacf")] \ No newline at end of file diff --git a/BatchRvtAddin2016/packages.config b/BatchRvtAddin2016/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtAddin2016/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2017/App.config b/BatchRvtAddin2017/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtAddin2017/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2017/BatchRvtAddin2017.csproj b/BatchRvtAddin2017/BatchRvtAddin2017.csproj index cd6d4a5..1e52dfe 100644 --- a/BatchRvtAddin2017/BatchRvtAddin2017.csproj +++ b/BatchRvtAddin2017/BatchRvtAddin2017.csproj @@ -1,100 +1,171 @@  - - - Debug - AnyCPU - {E4179471-79E6-4E4C-9ECA-62DE7076A486} - Library - Properties - BatchRvt.Addin.Revit2017 - BatchRvtAddin2017 - v4.8 - 512 - - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - True - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - True - - - ..\References\Revit\2017\RevitAPI.dll - False - - - ..\References\Revit\2017\RevitAPIUI.dll - False - - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - - - - - - - - call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2017" - - + + + + Debug + AnyCPU + {E4179471-79E6-4E4C-9ECA-62DE7076A486} + Library + Properties + BatchRvt.Addin.Revit2017 + BatchRvtAddin2017 + v4.8 + 512 + + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + True + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + True + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + ..\References\Revit\2017\RevitAPI.dll + False + + + ..\References\Revit\2017\RevitAPIUI.dll + False + + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + + + + + + + + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2017" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2017/BatchRvtAddinApplication.cs b/BatchRvtAddin2017/BatchRvtAddinApplication.cs index 74aa214..9bf4ad6 100644 --- a/BatchRvtAddin2017/BatchRvtAddinApplication.cs +++ b/BatchRvtAddin2017/BatchRvtAddinApplication.cs @@ -17,18 +17,15 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.ComponentModel; using System.IO; -using WinForms = System.Windows.Forms; - -using Autodesk.Revit.UI; -using Autodesk.Revit.Attributes; using Autodesk.Revit.ApplicationServices; - +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; namespace BatchRvt.Addin.Revit2017 { @@ -38,15 +35,6 @@ namespace BatchRvt.Addin.Revit2017 [Description("BatchRvtAddin")] public class BatchRvtAddinApplication : IExternalApplication { - private static void SetupBatchScriptHost(ControlledApplication controlledApplication) - { - var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); - - var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); - - batchRvtExternalEventHandler.Raise(); - } - public Result OnStartup(UIControlledApplication uiApplication) { SetupBatchScriptHost(uiApplication.ControlledApplication); @@ -58,6 +46,15 @@ public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } } public class BatchRvtExternalEventHandler : IExternalEventHandler @@ -67,15 +64,15 @@ public class BatchRvtExternalEventHandler : IExternalEventHandler public BatchRvtExternalEventHandler(string pluginFolderPath) { - this.externalEvent_ = ExternalEvent.Create(this); - this.pluginFolderPath_ = pluginFolderPath; + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; } public void Execute(UIApplication uiApp) { try { - ScriptHostUtil.ExecuteBatchScriptHost(this.pluginFolderPath_, uiApp); + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); } catch (Exception e) { @@ -90,7 +87,7 @@ public string GetName() public ExternalEventRequest Raise() { - return this.externalEvent_.Raise(); + return externalEvent_.Raise(); } } -} +} \ No newline at end of file diff --git a/BatchRvtAddin2017/Properties/AssemblyInfo.cs b/BatchRvtAddin2017/Properties/AssemblyInfo.cs index 6b420a8..e4ec009 100644 --- a/BatchRvtAddin2017/Properties/AssemblyInfo.cs +++ b/BatchRvtAddin2017/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("a943412b-0760-4e78-8f34-7f1dac012390")] +[assembly: Guid("a943412b-0760-4e78-8f34-7f1dac012390")] \ No newline at end of file diff --git a/BatchRvtAddin2017/packages.config b/BatchRvtAddin2017/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtAddin2017/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2018/App.config b/BatchRvtAddin2018/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtAddin2018/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2018/BatchRvtAddin2018.csproj b/BatchRvtAddin2018/BatchRvtAddin2018.csproj index c7c34f1..220889e 100644 --- a/BatchRvtAddin2018/BatchRvtAddin2018.csproj +++ b/BatchRvtAddin2018/BatchRvtAddin2018.csproj @@ -1,100 +1,171 @@  - - - Debug - AnyCPU - {B546AD64-E309-4498-A839-4A7FC50C14AB} - Library - Properties - BatchRvt.Addin.Revit2018 - BatchRvtAddin2018 - v4.8 - 512 - - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - True - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - True - - - ..\References\Revit\2018\RevitAPI.dll - False - - - ..\References\Revit\2018\RevitAPIUI.dll - False - - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - - - - - - - - call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2018" - - + + + + Debug + AnyCPU + {B546AD64-E309-4498-A839-4A7FC50C14AB} + Library + Properties + BatchRvt.Addin.Revit2018 + BatchRvtAddin2018 + v4.8 + 512 + + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + True + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + True + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + ..\References\Revit\2018\RevitAPI.dll + False + + + ..\References\Revit\2018\RevitAPIUI.dll + False + + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + + + + + + + + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2018" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2018/BatchRvtAddinApplication.cs b/BatchRvtAddin2018/BatchRvtAddinApplication.cs index 0fe200a..ad601af 100644 --- a/BatchRvtAddin2018/BatchRvtAddinApplication.cs +++ b/BatchRvtAddin2018/BatchRvtAddinApplication.cs @@ -17,18 +17,15 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.ComponentModel; using System.IO; -using WinForms = System.Windows.Forms; - -using Autodesk.Revit.UI; -using Autodesk.Revit.Attributes; using Autodesk.Revit.ApplicationServices; - +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; namespace BatchRvt.Addin.Revit2018 { @@ -38,15 +35,6 @@ namespace BatchRvt.Addin.Revit2018 [Description("BatchRvtAddin")] public class BatchRvtAddinApplication : IExternalApplication { - private static void SetupBatchScriptHost(ControlledApplication controlledApplication) - { - var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); - - var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); - - batchRvtExternalEventHandler.Raise(); - } - public Result OnStartup(UIControlledApplication uiApplication) { SetupBatchScriptHost(uiApplication.ControlledApplication); @@ -58,6 +46,15 @@ public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } } public class BatchRvtExternalEventHandler : IExternalEventHandler @@ -67,15 +64,15 @@ public class BatchRvtExternalEventHandler : IExternalEventHandler public BatchRvtExternalEventHandler(string pluginFolderPath) { - this.externalEvent_ = ExternalEvent.Create(this); - this.pluginFolderPath_ = pluginFolderPath; + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; } public void Execute(UIApplication uiApp) { try { - ScriptHostUtil.ExecuteBatchScriptHost(this.pluginFolderPath_, uiApp); + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); } catch (Exception e) { @@ -90,7 +87,7 @@ public string GetName() public ExternalEventRequest Raise() { - return this.externalEvent_.Raise(); + return externalEvent_.Raise(); } } -} +} \ No newline at end of file diff --git a/BatchRvtAddin2018/Properties/AssemblyInfo.cs b/BatchRvtAddin2018/Properties/AssemblyInfo.cs index 0cd3d5a..e089c92 100644 --- a/BatchRvtAddin2018/Properties/AssemblyInfo.cs +++ b/BatchRvtAddin2018/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("4deb0b67-8d04-4b95-8c01-9e26ac036c4f")] +[assembly: Guid("4deb0b67-8d04-4b95-8c01-9e26ac036c4f")] \ No newline at end of file diff --git a/BatchRvtAddin2018/packages.config b/BatchRvtAddin2018/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtAddin2018/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2019/App.config b/BatchRvtAddin2019/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtAddin2019/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2019/BatchRvtAddin2019.csproj b/BatchRvtAddin2019/BatchRvtAddin2019.csproj index 828708e..f8b92d9 100644 --- a/BatchRvtAddin2019/BatchRvtAddin2019.csproj +++ b/BatchRvtAddin2019/BatchRvtAddin2019.csproj @@ -1,89 +1,160 @@  - - - Debug - AnyCPU - {62F91AA6-AC57-451E-A91C-719D5846D247} - Library - Properties - BatchRvt.Addin.Revit2019 - BatchRvtAddin2019 - v4.8 - 512 - true - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - - - ..\References\Revit\2019\RevitAPI.dll - False - - - ..\References\Revit\2019\RevitAPIUI.dll - False - - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - True - - - - - - - - call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2019" - + + + + Debug + AnyCPU + {62F91AA6-AC57-451E-A91C-719D5846D247} + Library + Properties + BatchRvt.Addin.Revit2019 + BatchRvtAddin2019 + v4.8 + 512 + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + ..\References\Revit\2019\RevitAPI.dll + False + + + ..\References\Revit\2019\RevitAPIUI.dll + False + + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + True + + + + + + + + + + + + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2019" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2019/BatchRvtAddinApplication.cs b/BatchRvtAddin2019/BatchRvtAddinApplication.cs index d8fa6f0..77b8ebe 100644 --- a/BatchRvtAddin2019/BatchRvtAddinApplication.cs +++ b/BatchRvtAddin2019/BatchRvtAddinApplication.cs @@ -17,18 +17,15 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.ComponentModel; using System.IO; -using WinForms = System.Windows.Forms; - -using Autodesk.Revit.UI; -using Autodesk.Revit.Attributes; using Autodesk.Revit.ApplicationServices; - +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; namespace BatchRvt.Addin.Revit2019 { @@ -38,15 +35,6 @@ namespace BatchRvt.Addin.Revit2019 [Description("BatchRvtAddin")] public class BatchRvtAddinApplication : IExternalApplication { - private static void SetupBatchScriptHost(ControlledApplication controlledApplication) - { - var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); - - var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); - - batchRvtExternalEventHandler.Raise(); - } - public Result OnStartup(UIControlledApplication uiApplication) { SetupBatchScriptHost(uiApplication.ControlledApplication); @@ -58,6 +46,15 @@ public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } } public class BatchRvtExternalEventHandler : IExternalEventHandler @@ -67,15 +64,15 @@ public class BatchRvtExternalEventHandler : IExternalEventHandler public BatchRvtExternalEventHandler(string pluginFolderPath) { - this.externalEvent_ = ExternalEvent.Create(this); - this.pluginFolderPath_ = pluginFolderPath; + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; } public void Execute(UIApplication uiApp) { try { - ScriptHostUtil.ExecuteBatchScriptHost(this.pluginFolderPath_, uiApp); + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); } catch (Exception e) { @@ -90,8 +87,7 @@ public string GetName() public ExternalEventRequest Raise() { - return this.externalEvent_.Raise(); + return externalEvent_.Raise(); } } -} - +} \ No newline at end of file diff --git a/BatchRvtAddin2019/Properties/AssemblyInfo.cs b/BatchRvtAddin2019/Properties/AssemblyInfo.cs index fa201f8..451e88b 100644 --- a/BatchRvtAddin2019/Properties/AssemblyInfo.cs +++ b/BatchRvtAddin2019/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("62f91aa6-ac57-451e-a91c-719d5846d247")] +[assembly: Guid("62f91aa6-ac57-451e-a91c-719d5846d247")] \ No newline at end of file diff --git a/BatchRvtAddin2019/packages.config b/BatchRvtAddin2019/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtAddin2019/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2020/App.config b/BatchRvtAddin2020/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtAddin2020/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2020/BatchRvtAddin2020.csproj b/BatchRvtAddin2020/BatchRvtAddin2020.csproj index 4638e8f..661e17e 100644 --- a/BatchRvtAddin2020/BatchRvtAddin2020.csproj +++ b/BatchRvtAddin2020/BatchRvtAddin2020.csproj @@ -1,83 +1,154 @@  - - - Debug - AnyCPU - {03CFCDBE-9532-47DD-A84D-8EA9906808BF} - Library - Properties - BatchRvt.Addin.Revit2020 - BatchRvtAddin2020 - v4.8 - 512 - true - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - prompt - MinimumRecommendedRules.ruleset - - - - ..\References\IronPython-2.7.3\IronPython.dll - - - ..\References\IronPython-2.7.3\IronPython.Modules.dll - - - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - - - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - - - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - - - ..\References\Revit\2020\RevitAPI.dll - False - - - ..\References\Revit\2020\RevitAPIUI.dll - False - - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - - - - - - - - call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2020" - + + + + Debug + AnyCPU + {03CFCDBE-9532-47DD-A84D-8EA9906808BF} + Library + Properties + BatchRvt.Addin.Revit2020 + BatchRvtAddin2020 + v4.8 + 512 + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + ..\References\IronPython-2.7.3\IronPython.dll + + + ..\References\IronPython-2.7.3\IronPython.Modules.dll + + + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + + + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + + + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + ..\References\Revit\2020\RevitAPI.dll + False + + + ..\References\Revit\2020\RevitAPIUI.dll + False + + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + + + + + + + + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2020" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2020/BatchRvtAddinApplication.cs b/BatchRvtAddin2020/BatchRvtAddinApplication.cs index c901fb3..0884452 100644 --- a/BatchRvtAddin2020/BatchRvtAddinApplication.cs +++ b/BatchRvtAddin2020/BatchRvtAddinApplication.cs @@ -17,18 +17,15 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.ComponentModel; using System.IO; -using WinForms = System.Windows.Forms; - -using Autodesk.Revit.UI; -using Autodesk.Revit.Attributes; using Autodesk.Revit.ApplicationServices; - +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; namespace BatchRvt.Addin.Revit2020 { @@ -38,15 +35,6 @@ namespace BatchRvt.Addin.Revit2020 [Description("BatchRvtAddin")] public class BatchRvtAddinApplication : IExternalApplication { - private static void SetupBatchScriptHost(ControlledApplication controlledApplication) - { - var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); - - var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); - - batchRvtExternalEventHandler.Raise(); - } - public Result OnStartup(UIControlledApplication uiApplication) { SetupBatchScriptHost(uiApplication.ControlledApplication); @@ -58,6 +46,15 @@ public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } } public class BatchRvtExternalEventHandler : IExternalEventHandler @@ -67,15 +64,15 @@ public class BatchRvtExternalEventHandler : IExternalEventHandler public BatchRvtExternalEventHandler(string pluginFolderPath) { - this.externalEvent_ = ExternalEvent.Create(this); - this.pluginFolderPath_ = pluginFolderPath; + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; } public void Execute(UIApplication uiApp) { try { - ScriptHostUtil.ExecuteBatchScriptHost(this.pluginFolderPath_, uiApp); + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); } catch (Exception e) { @@ -90,8 +87,7 @@ public string GetName() public ExternalEventRequest Raise() { - return this.externalEvent_.Raise(); + return externalEvent_.Raise(); } } -} - +} \ No newline at end of file diff --git a/BatchRvtAddin2020/Properties/AssemblyInfo.cs b/BatchRvtAddin2020/Properties/AssemblyInfo.cs index b5762d7..e38ada9 100644 --- a/BatchRvtAddin2020/Properties/AssemblyInfo.cs +++ b/BatchRvtAddin2020/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,5 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("03cfcdbe-9532-47dd-a84d-8ea9906808bf")] - +[assembly: Guid("03cfcdbe-9532-47dd-a84d-8ea9906808bf")] \ No newline at end of file diff --git a/BatchRvtAddin2020/packages.config b/BatchRvtAddin2020/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtAddin2020/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2021/App.config b/BatchRvtAddin2021/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtAddin2021/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2021/BatchRvtAddin2021.csproj b/BatchRvtAddin2021/BatchRvtAddin2021.csproj index 9d93e49..56c7219 100644 --- a/BatchRvtAddin2021/BatchRvtAddin2021.csproj +++ b/BatchRvtAddin2021/BatchRvtAddin2021.csproj @@ -1,90 +1,161 @@  - - - Debug - AnyCPU - {1A6FE589-4B85-4094-AFB7-48E7637B6ED0} - Library - Properties - BatchRvt.Addin.Revit2021 - BatchRvtAddin2021 - v4.8 - 512 - true - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - 7.3 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - 7.3 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - - - ..\References\Revit\2021\RevitAPI.dll - False - - - ..\References\Revit\2021\RevitAPIUI.dll - False - - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - - - - - - - - call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2021" - + + + + Debug + AnyCPU + {1A6FE589-4B85-4094-AFB7-48E7637B6ED0} + Library + Properties + BatchRvt.Addin.Revit2021 + BatchRvtAddin2021 + v4.8 + 512 + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + 7.3 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + 7.3 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + ..\References\Revit\2021\RevitAPI.dll + False + + + ..\References\Revit\2021\RevitAPIUI.dll + False + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + + + + + + + + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2021" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2021/BatchRvtAddinApplication.cs b/BatchRvtAddin2021/BatchRvtAddinApplication.cs index 319d347..1137714 100644 --- a/BatchRvtAddin2021/BatchRvtAddinApplication.cs +++ b/BatchRvtAddin2021/BatchRvtAddinApplication.cs @@ -17,18 +17,15 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.ComponentModel; using System.IO; -using WinForms = System.Windows.Forms; - -using Autodesk.Revit.UI; -using Autodesk.Revit.Attributes; using Autodesk.Revit.ApplicationServices; - +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; namespace BatchRvt.Addin.Revit2021 { @@ -38,15 +35,6 @@ namespace BatchRvt.Addin.Revit2021 [Description("BatchRvtAddin")] public class BatchRvtAddinApplication : IExternalApplication { - private static void SetupBatchScriptHost(ControlledApplication controlledApplication) - { - var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); - - var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); - - batchRvtExternalEventHandler.Raise(); - } - public Result OnStartup(UIControlledApplication uiApplication) { SetupBatchScriptHost(uiApplication.ControlledApplication); @@ -58,6 +46,15 @@ public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } } public class BatchRvtExternalEventHandler : IExternalEventHandler @@ -67,15 +64,15 @@ public class BatchRvtExternalEventHandler : IExternalEventHandler public BatchRvtExternalEventHandler(string pluginFolderPath) { - this.externalEvent_ = ExternalEvent.Create(this); - this.pluginFolderPath_ = pluginFolderPath; + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; } public void Execute(UIApplication uiApp) { try { - ScriptHostUtil.ExecuteBatchScriptHost(this.pluginFolderPath_, uiApp); + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); } catch (Exception e) { @@ -90,8 +87,7 @@ public string GetName() public ExternalEventRequest Raise() { - return this.externalEvent_.Raise(); + return externalEvent_.Raise(); } } -} - +} \ No newline at end of file diff --git a/BatchRvtAddin2021/Properties/AssemblyInfo.cs b/BatchRvtAddin2021/Properties/AssemblyInfo.cs index e89bded..99d7a2c 100644 --- a/BatchRvtAddin2021/Properties/AssemblyInfo.cs +++ b/BatchRvtAddin2021/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("1a6fe589-4b85-4094-afb7-48e7637b6ed0")] +[assembly: Guid("1a6fe589-4b85-4094-afb7-48e7637b6ed0")] \ No newline at end of file diff --git a/BatchRvtAddin2021/packages.config b/BatchRvtAddin2021/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtAddin2021/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2022/App.config b/BatchRvtAddin2022/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtAddin2022/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2022/BatchRvtAddin2022.csproj b/BatchRvtAddin2022/BatchRvtAddin2022.csproj index 178517b..e1c84fe 100644 --- a/BatchRvtAddin2022/BatchRvtAddin2022.csproj +++ b/BatchRvtAddin2022/BatchRvtAddin2022.csproj @@ -1,90 +1,161 @@  - - - Debug - AnyCPU - {5529D2BF-74BD-47A8-A6DE-37006AC07C0C} - Library - Properties - BatchRvt.Addin.Revit2022 - BatchRvtAddin2022 - v4.8 - 512 - true - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - 7.3 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - 7.3 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - - - ..\References\Revit\2022\RevitAPI.dll - False - - - ..\References\Revit\2022\RevitAPIUI.dll - False - - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - - - - - - - - call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2022" - + + + + Debug + AnyCPU + {5529D2BF-74BD-47A8-A6DE-37006AC07C0C} + Library + Properties + BatchRvt.Addin.Revit2022 + BatchRvtAddin2022 + v4.8 + 512 + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + 7.3 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + 7.3 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + ..\References\Revit\2022\RevitAPI.dll + False + + + ..\References\Revit\2022\RevitAPIUI.dll + False + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + + + + + + + + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2022" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2022/BatchRvtAddinApplication.cs b/BatchRvtAddin2022/BatchRvtAddinApplication.cs index f882ee9..88f69e7 100644 --- a/BatchRvtAddin2022/BatchRvtAddinApplication.cs +++ b/BatchRvtAddin2022/BatchRvtAddinApplication.cs @@ -17,18 +17,15 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.ComponentModel; using System.IO; -using WinForms = System.Windows.Forms; - -using Autodesk.Revit.UI; -using Autodesk.Revit.Attributes; using Autodesk.Revit.ApplicationServices; - +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; namespace BatchRvt.Addin.Revit2022 { @@ -38,15 +35,6 @@ namespace BatchRvt.Addin.Revit2022 [Description("BatchRvtAddin")] public class BatchRvtAddinApplication : IExternalApplication { - private static void SetupBatchScriptHost(ControlledApplication controlledApplication) - { - var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); - - var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); - - batchRvtExternalEventHandler.Raise(); - } - public Result OnStartup(UIControlledApplication uiApplication) { SetupBatchScriptHost(uiApplication.ControlledApplication); @@ -58,6 +46,15 @@ public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } } public class BatchRvtExternalEventHandler : IExternalEventHandler @@ -67,15 +64,15 @@ public class BatchRvtExternalEventHandler : IExternalEventHandler public BatchRvtExternalEventHandler(string pluginFolderPath) { - this.externalEvent_ = ExternalEvent.Create(this); - this.pluginFolderPath_ = pluginFolderPath; + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; } public void Execute(UIApplication uiApp) { try { - ScriptHostUtil.ExecuteBatchScriptHost(this.pluginFolderPath_, uiApp); + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); } catch (Exception e) { @@ -90,8 +87,7 @@ public string GetName() public ExternalEventRequest Raise() { - return this.externalEvent_.Raise(); + return externalEvent_.Raise(); } } -} - +} \ No newline at end of file diff --git a/BatchRvtAddin2022/Properties/AssemblyInfo.cs b/BatchRvtAddin2022/Properties/AssemblyInfo.cs index ddceacc..d63ca0c 100644 --- a/BatchRvtAddin2022/Properties/AssemblyInfo.cs +++ b/BatchRvtAddin2022/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("1a6fe589-4b85-4094-afb7-48e7637b6ed0")] +[assembly: Guid("1a6fe589-4b85-4094-afb7-48e7637b6ed0")] \ No newline at end of file diff --git a/BatchRvtAddin2022/packages.config b/BatchRvtAddin2022/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtAddin2022/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2023/App.config b/BatchRvtAddin2023/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtAddin2023/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2023/BatchRvtAddin2023.csproj b/BatchRvtAddin2023/BatchRvtAddin2023.csproj index acbd421..c31fcf8 100644 --- a/BatchRvtAddin2023/BatchRvtAddin2023.csproj +++ b/BatchRvtAddin2023/BatchRvtAddin2023.csproj @@ -1,90 +1,161 @@  - - - Debug - AnyCPU - {60C3C457-D35A-4343-A906-01CF666DC75E} - Library - Properties - BatchRvt.Addin.Revit2023 - BatchRvtAddin2023 - v4.8 - 512 - true - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - 7.3 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - 7.3 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - - - ..\References\Revit\2023\RevitAPI.dll - False - - - ..\References\Revit\2023\RevitAPIUI.dll - False - - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - - - - - - - - call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2023" - + + + + Debug + AnyCPU + {60C3C457-D35A-4343-A906-01CF666DC75E} + Library + Properties + BatchRvt.Addin.Revit2023 + BatchRvtAddin2023 + v4.8 + 512 + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + 7.3 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + 7.3 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + ..\References\Revit\2023\RevitAPI.dll + False + + + ..\References\Revit\2023\RevitAPIUI.dll + False + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + + + + + + + + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2023" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2023/BatchRvtAddinApplication.cs b/BatchRvtAddin2023/BatchRvtAddinApplication.cs index 2feda7a..da1a39f 100644 --- a/BatchRvtAddin2023/BatchRvtAddinApplication.cs +++ b/BatchRvtAddin2023/BatchRvtAddinApplication.cs @@ -17,17 +17,15 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.ComponentModel; using System.IO; -using WinForms = System.Windows.Forms; -using Autodesk.Revit.UI; -using Autodesk.Revit.Attributes; using Autodesk.Revit.ApplicationServices; - +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; namespace BatchRvt.Addin.Revit2023 { @@ -37,15 +35,6 @@ namespace BatchRvt.Addin.Revit2023 [Description("BatchRvtAddin")] public class BatchRvtAddinApplication : IExternalApplication { - private static void SetupBatchScriptHost(ControlledApplication controlledApplication) - { - var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); - - var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); - - batchRvtExternalEventHandler.Raise(); - } - public Result OnStartup(UIControlledApplication uiApplication) { SetupBatchScriptHost(uiApplication.ControlledApplication); @@ -57,6 +46,15 @@ public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } } public class BatchRvtExternalEventHandler : IExternalEventHandler @@ -66,15 +64,15 @@ public class BatchRvtExternalEventHandler : IExternalEventHandler public BatchRvtExternalEventHandler(string pluginFolderPath) { - this.externalEvent_ = ExternalEvent.Create(this); - this.pluginFolderPath_ = pluginFolderPath; + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; } public void Execute(UIApplication uiApp) { try { - ScriptHostUtil.ExecuteBatchScriptHost(this.pluginFolderPath_, uiApp); + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); } catch (Exception e) { @@ -89,8 +87,7 @@ public string GetName() public ExternalEventRequest Raise() { - return this.externalEvent_.Raise(); + return externalEvent_.Raise(); } } -} - +} \ No newline at end of file diff --git a/BatchRvtAddin2023/Properties/AssemblyInfo.cs b/BatchRvtAddin2023/Properties/AssemblyInfo.cs index 5385856..195cebc 100644 --- a/BatchRvtAddin2023/Properties/AssemblyInfo.cs +++ b/BatchRvtAddin2023/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -20,4 +19,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("60c3c457-d35a-4343-a906-01cf666dc75e")] +[assembly: Guid("60c3c457-d35a-4343-a906-01cf666dc75e")] \ No newline at end of file diff --git a/BatchRvtAddin2023/packages.config b/BatchRvtAddin2023/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtAddin2023/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtAddin2024/BatchRvtAddin2024.addin b/BatchRvtAddin2024/BatchRvtAddin2024.addin new file mode 100644 index 0000000..a478227 --- /dev/null +++ b/BatchRvtAddin2024/BatchRvtAddin2024.addin @@ -0,0 +1,10 @@ + + + + BatchRvtAddin + .\BatchRvt\BatchRvtAddin2024.dll + b57d22c8-5e1f-407a-86ea-a8615fd8df34 + BatchRvt.Addin.Revit2024.BatchRvtAddinApplication + BATCHRVT + + diff --git a/BatchRvtAddin2024/BatchRvtAddin2024.csproj b/BatchRvtAddin2024/BatchRvtAddin2024.csproj new file mode 100644 index 0000000..51b97e8 --- /dev/null +++ b/BatchRvtAddin2024/BatchRvtAddin2024.csproj @@ -0,0 +1,80 @@ + + + + + Debug + AnyCPU + {237EB511-D77C-4142-80F3-C668CA8C83EC} + Library + Properties + BatchRvtAddin2024 + BatchRvtAddin2024 + v4.8 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + x64 + + + pdbonly + true + bin\x64\Release\ + TRACE + prompt + 4 + x64 + + + + + + + + + + + + + + + + + + + + + + 6.8.0 + + + 4.18.3 + + + 2024.0.0 + + + 2024.0.0 + + + 2.4.2 + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + call "$(ProjectDir)..\AddinDeployment\DeployAddin.bat" "$(ProjectDir)" "$(TargetDir)" "2024" + + \ No newline at end of file diff --git a/BatchRvtAddin2024/BatchRvtAddinApplication.cs b/BatchRvtAddin2024/BatchRvtAddinApplication.cs new file mode 100644 index 0000000..385b34d --- /dev/null +++ b/BatchRvtAddin2024/BatchRvtAddinApplication.cs @@ -0,0 +1,93 @@ +// +// Revit Batch Processor +// +// Copyright (c) 2020 Daniel Rumery, BVN +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// + +using System; +using System.ComponentModel; +using System.IO; +using Autodesk.Revit.ApplicationServices; +using Autodesk.Revit.Attributes; +using Autodesk.Revit.UI; +using BatchRvt.ScriptHost; +using WinForms = System.Windows.Forms; + +namespace BatchRvt.Addin.Revit2024 +{ + [Transaction(TransactionMode.Manual)] + [Regeneration(RegenerationOption.Manual)] + [DisplayName("BatchRvtAddin")] + [Description("BatchRvtAddin")] + public class BatchRvtAddinApplication : IExternalApplication + { + public Result OnStartup(UIControlledApplication uiApplication) + { + SetupBatchScriptHost(uiApplication.ControlledApplication); + + return Result.Succeeded; + } + + public Result OnShutdown(UIControlledApplication application) + { + return Result.Succeeded; + } + + private static void SetupBatchScriptHost(ControlledApplication controlledApplication) + { + var pluginFolderPath = Path.GetDirectoryName(typeof(BatchRvtAddinApplication).Assembly.Location); + + var batchRvtExternalEventHandler = new BatchRvtExternalEventHandler(pluginFolderPath); + + batchRvtExternalEventHandler.Raise(); + } + } + + public class BatchRvtExternalEventHandler : IExternalEventHandler + { + private readonly ExternalEvent externalEvent_; + private readonly string pluginFolderPath_; + + public BatchRvtExternalEventHandler(string pluginFolderPath) + { + externalEvent_ = ExternalEvent.Create(this); + pluginFolderPath_ = pluginFolderPath; + } + + public void Execute(UIApplication uiApp) + { + try + { + ScriptHostUtil.ExecuteBatchScriptHost(pluginFolderPath_, uiApp); + } + catch (Exception e) + { + WinForms.MessageBox.Show(e.ToString(), ScriptHostUtil.BATCH_RVT_ERROR_WINDOW_TITLE); + } + } + + public string GetName() + { + return "BatchRvt_ExternalEventHandler"; + } + + public ExternalEventRequest Raise() + { + return externalEvent_.Raise(); + } + } +} \ No newline at end of file diff --git a/BatchRvtAddin2024/Properties/AssemblyInfo.cs b/BatchRvtAddin2024/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7849980 --- /dev/null +++ b/BatchRvtAddin2024/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("BatchRvtAddin2024")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("BatchRvtAddin2024")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("237eb511-d77c-4142-80f3-c668ca8c83ec")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/BatchRvtGUI/App.config b/BatchRvtGUI/App.config new file mode 100644 index 0000000..7d6b141 --- /dev/null +++ b/BatchRvtGUI/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtGUI/BatchRvtGUI.csproj b/BatchRvtGUI/BatchRvtGUI.csproj index a88a748..794a71b 100644 --- a/BatchRvtGUI/BatchRvtGUI.csproj +++ b/BatchRvtGUI/BatchRvtGUI.csproj @@ -1,5 +1,6 @@  + Debug @@ -11,6 +12,9 @@ BatchRvtGUI v4.8 512 + latestmajor + + BVN32NewBrand.ico @@ -36,37 +40,49 @@ true + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + - False - ..\References\IronPython-2.7.3\IronPython.dll - True + False + ..\References\IronPython-2.7.3\IronPython.dll + True - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - True + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + True - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - True + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + True - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - True + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + True - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - True + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + True + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + - False - ..\References\JSON.NET\Newtonsoft.Json.dll - True + False + ..\References\JSON.NET\Newtonsoft.Json.dll + True + + @@ -76,6 +92,53 @@ + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + @@ -120,6 +183,7 @@ RevitFileScanningProgressUI.cs + SettingsSingleFileGenerator Settings.Designer.cs @@ -138,6 +202,7 @@ {b880dd15-184b-4ce2-86fc-08bac05e0271} BatchRvtUtil + False {c877620c-de32-455c-bf21-8f3e73e9df68} @@ -152,12 +217,36 @@ + + + 6.8.0 + + + 4.18.3 + + + 2.4.2 + + + + + + - + + \ No newline at end of file diff --git a/BatchRvtGUI/BatchRvtGuiForm.cs b/BatchRvtGUI/BatchRvtGuiForm.cs index b1425fe..5710317 100644 --- a/BatchRvtGUI/BatchRvtGuiForm.cs +++ b/BatchRvtGUI/BatchRvtGuiForm.cs @@ -17,1243 +17,1186 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.IO; using System.Linq; -using System.Threading.Tasks; using System.Text; +using System.Threading.Tasks; using System.Windows.Forms; -using System.IO; -using System.Diagnostics; using BatchRvtUtil; -namespace BatchRvtGUI +namespace BatchRvtGUI; + +public partial class BatchRvtGuiForm : Form { - public partial class BatchRvtGuiForm : Form - { - public const string WINDOW_TITLE = "Revit Batch Processor"; + private const string WINDOW_TITLE = "Revit Batch Processor"; - private BatchRvtSettings Settings; - private UIConfig UIConfiguration; - private bool isBatchRvtRunning = false; + private const string NEW_TASK_SCRIPT_FILENAME = "new_task_script.py"; + private const string NEW_PREPROCESSING_SCRIPT_FILENAME = "new_pre_processing_script.py"; + private const string NEW_POSTPROCESSING_SCRIPT_FILENAME = "new_post_processing_script.py"; - private const string NEW_TASK_SCRIPT_FILENAME = "new_task_script.py"; - private const string NEW_PREPROCESSING_SCRIPT_FILENAME = "new_pre_processing_script.py"; - private const string NEW_POSTPROCESSING_SCRIPT_FILENAME = "new_post_processing_script.py"; + private const string TEMPLATE_TASK_SCRIPT_FILENAME = "template_task_script.py"; + private const string TEMPLATE_PREPROCESSING_SCRIPT_FILENAME = "template_pre_processing_script.py"; + private const string TEMPLATE_POSTPROCESSING_SCRIPT_FILENAME = "template_post_processing_script.py"; - private enum ScriptType { Python = 0, Dynamo = 1, Any = 2 } - private enum SaveNewScriptType { TaskScript = 0, PreProcessingScript = 1, PostProcessingScript = 2 } + private const string PYTHON_SCRIPT_EXTENSION = ".py"; + private const string PYTHON_SCRIPT_FILTER = "Python files (*.py)|*.py"; + private const string DYNAMO_SCRIPT_EXTENSION = ".dyn"; + private const string DYNAMO_SCRIPT_FILTER = "Dynamo files (*.dyn)|*.dyn"; + private const string ANY_SCRIPTS_FILTER = "Script files (*.py;*.dyn)|*.py;*.dyn"; - private const string TEMPLATE_TASK_SCRIPT_FILENAME = "template_task_script.py"; - private const string TEMPLATE_PREPROCESSING_SCRIPT_FILENAME = "template_pre_processing_script.py"; - private const string TEMPLATE_POSTPROCESSING_SCRIPT_FILENAME = "template_post_processing_script.py"; + private const int INITIAL_WIDTH = 1040; - private const string PYTHON_SCRIPT_EXTENSION = ".py"; - private const string PYTHON_SCRIPT_FILTER = "Python files (*.py)|*.py"; - private const string DYNAMO_SCRIPT_EXTENSION = ".dyn"; - private const string DYNAMO_SCRIPT_FILTER = "Dynamo files (*.dyn)|*.dyn"; - private const string ANY_SCRIPTS_FILTER = "Script files (*.py;*.dyn)|*.py;*.dyn"; + private const int SETUP_HEIGHT = 685; + private const int SETUP_INITIAL_WIDTH = INITIAL_WIDTH; + private const int SETUP_MINIMUM_WIDTH = INITIAL_WIDTH; + private const int SETUP_MAXIMUM_WIDTH = 1600; - private const int INITIAL_WIDTH = 1040; + private const int RUNNING_INITIAL_WIDTH = INITIAL_WIDTH; + private const int RUNNING_INITIAL_HEIGHT = 875; + private const int RUNNING_MINIMUM_HEIGHT = 875; + private const int RUNNING_MINIMUM_WIDTH = INITIAL_WIDTH; - private const int SETUP_HEIGHT = 685; - private const int SETUP_INITIAL_WIDTH = INITIAL_WIDTH; - private const int SETUP_MINIMUM_WIDTH = INITIAL_WIDTH; - private const int SETUP_MAXIMUM_WIDTH = 1600; + private const int ADVANCED_SETTINGS_VISIBLE_SIZE_DIFFERENCE = 275; + private const int READ_OUTPUT_INTERVAL_IN_MS = 10; - private readonly System.Drawing.Size SETUP_INITIAL_SIZE = new System.Drawing.Size(SETUP_INITIAL_WIDTH, SETUP_HEIGHT); - private readonly System.Drawing.Size SETUP_MINIMUM_SIZE = new System.Drawing.Size(SETUP_MINIMUM_WIDTH, SETUP_HEIGHT); - private readonly System.Drawing.Size SETUP_MAXIMUM_SIZE = new System.Drawing.Size(SETUP_MAXIMUM_WIDTH, SETUP_HEIGHT); + private readonly Size RUNNING_INITIAL_SIZE = new(RUNNING_INITIAL_WIDTH, RUNNING_INITIAL_HEIGHT); + private readonly Size RUNNING_MAXIMUM_SIZE = new(0, 0); // no maximum size + private readonly Size RUNNING_MINIMUM_SIZE = new(RUNNING_MINIMUM_WIDTH, RUNNING_MINIMUM_HEIGHT); - private const int RUNNING_INITIAL_WIDTH = INITIAL_WIDTH; - private const int RUNNING_INITIAL_HEIGHT = 875; - private const int RUNNING_MINIMUM_HEIGHT = 875; - private const int RUNNING_MINIMUM_WIDTH = INITIAL_WIDTH; + private readonly Size SETUP_INITIAL_SIZE = new(SETUP_INITIAL_WIDTH, SETUP_HEIGHT); + private readonly Size SETUP_MAXIMUM_SIZE = new(SETUP_MAXIMUM_WIDTH, SETUP_HEIGHT); + private readonly Size SETUP_MINIMUM_SIZE = new(SETUP_MINIMUM_WIDTH, SETUP_HEIGHT); + private readonly UIConfig UIConfiguration; - private const int ADVANCED_SETTINGS_VISIBLE_SIZE_DIFFERENCE = 275; + private Process batchRvtProcess; + private bool isBatchRvtRunning; + private bool isUsingRunningSize; + private Task pendingErrorReadLineTask; - private readonly System.Drawing.Size RUNNING_INITIAL_SIZE = new System.Drawing.Size(RUNNING_INITIAL_WIDTH, RUNNING_INITIAL_HEIGHT); - private readonly System.Drawing.Size RUNNING_MINIMUM_SIZE = new System.Drawing.Size(RUNNING_MINIMUM_WIDTH, RUNNING_MINIMUM_HEIGHT); - private readonly System.Drawing.Size RUNNING_MAXIMUM_SIZE = new System.Drawing.Size(0, 0); // no maximum size - private bool isUsingRunningSize = false; + private Task pendingOutputReadLineTask; + private Timer readBatchRvtOutput_Timer; - private Process batchRvtProcess; - private Timer readBatchRvtOutput_Timer; - private const int READ_OUTPUT_INTERVAL_IN_MS = 250; + private BatchRvtSettings Settings; - private Task pendingOutputReadLineTask; - private Task pendingErrorReadLineTask; + public BatchRvtGuiForm() + { + InitializeComponent(); + Settings = new BatchRvtSettings(); - public BatchRvtGuiForm() + UIConfiguration = new UIConfig(GetUIConfigItems()); + } + + private IEnumerable GetUIConfigItems() + { + var iuConfigItems = new IUIConfigItem[] { - InitializeComponent(); - this.Settings = new BatchRvtSettings(); + // General Task Script settings + new UIConfigItem( + () => + { + UpdateTaskScript(Settings.TaskScriptFilePath.GetValue()); + showMessageBoxOnTaskScriptErrorCheckBox.Checked = + Settings.ShowMessageBoxOnTaskScriptError.GetValue(); + }, + () => + { + Settings.TaskScriptFilePath.SetValue(taskScriptTextBox.Text); + Settings.ShowMessageBoxOnTaskScriptError.SetValue(showMessageBoxOnTaskScriptErrorCheckBox + .Checked); + } + ), - this.UIConfiguration = new UIConfig(GetUIConfigItems()); - } + // Revit File List settings + new UIConfigItem( + () => { revitFileListTextBox.Text = Settings.RevitFileListFilePath.GetValue(); }, + () => { Settings.RevitFileListFilePath.SetValue(revitFileListTextBox.Text); } + ), - private IEnumerable GetUIConfigItems() - { - var iuConfigItems = new IUIConfigItem[] { - - // General Task Script settings - new UIConfigItem( - () => { - UpdateTaskScript(this.Settings.TaskScriptFilePath.GetValue()); - this.showMessageBoxOnTaskScriptErrorCheckBox.Checked = this.Settings.ShowMessageBoxOnTaskScriptError.GetValue(); - }, - () => { - this.Settings.TaskScriptFilePath.SetValue(this.taskScriptTextBox.Text); - this.Settings.ShowMessageBoxOnTaskScriptError.SetValue(this.showMessageBoxOnTaskScriptErrorCheckBox.Checked); - } - ), - - // Revit File List settings - new UIConfigItem( - () => { this.revitFileListTextBox.Text = this.Settings.RevitFileListFilePath.GetValue(); }, - () => { this.Settings.RevitFileListFilePath.SetValue(this.revitFileListTextBox.Text); } - ), - - // Data Export settings - new UIConfigItem( - () => { - this.enableDataExportCheckBox.Checked = this.Settings.EnableDataExport.GetValue(); - this.dataExportFolderTextBox.Text = this.Settings.DataExportFolderPath.GetValue(); - UpdateDataExportControls(); - }, - () => { - this.Settings.EnableDataExport.SetValue(this.enableDataExportCheckBox.Checked); - this.Settings.DataExportFolderPath.SetValue(this.dataExportFolderTextBox.Text); - } - ), - - // Pre-processing Script settings - new UIConfigItem( - () => { - this.executePreProcessingScriptCheckBox.Checked = this.Settings.ExecutePreProcessingScript.GetValue(); - this.preProcessingScriptTextBox.Text = this.Settings.PreProcessingScriptFilePath.GetValue(); - UpdatePreProcessingScriptControls(); - }, - () => { - this.Settings.ExecutePreProcessingScript.SetValue(this.executePreProcessingScriptCheckBox.Checked); - this.Settings.PreProcessingScriptFilePath.SetValue(this.preProcessingScriptTextBox.Text); - } - ), - - // Post-processing Script settings - new UIConfigItem( - () => { - this.executePostProcessingScriptCheckBox.Checked = this.Settings.ExecutePostProcessingScript.GetValue(); - this.postProcessingScriptTextBox.Text = this.Settings.PostProcessingScriptFilePath.GetValue(); - UpdatePostProcessingScriptControls(); - }, - () => { - this.Settings.ExecutePostProcessingScript.SetValue(this.executePostProcessingScriptCheckBox.Checked); - this.Settings.PostProcessingScriptFilePath.SetValue(this.postProcessingScriptTextBox.Text); - } - ), - - // Central File Processing settings - new UIConfigItem( - () => { - this.detachFromCentralRadioButton.Checked = (this.Settings.CentralFileOpenOption.GetValue() == BatchRvt.CentralFileOpenOption.Detach); - this.createNewLocalRadioButton.Checked = (this.Settings.CentralFileOpenOption.GetValue() == BatchRvt.CentralFileOpenOption.CreateNewLocal); - this.deleteLocalAfterCheckBox.Checked = this.Settings.DeleteLocalAfter.GetValue(); - this.discardWorksetsCheckBox.Checked = this.Settings.DiscardWorksetsOnDetach.GetValue(); - this.closeAllWorksetsRadioButton.Checked = (this.Settings.WorksetConfigurationOption.GetValue() == BatchRvt.WorksetConfigurationOption.CloseAllWorksets); - this.openAllWorksetsRadioButton.Checked = (this.Settings.WorksetConfigurationOption.GetValue() == BatchRvt.WorksetConfigurationOption.OpenAllWorksets); - this.openLastViewedWorksetsRadioButton.Checked = (this.Settings.WorksetConfigurationOption.GetValue() == BatchRvt.WorksetConfigurationOption.OpenLastViewed); - UpdateCentralFileProcessingControls(); - }, - () => { - this.Settings.CentralFileOpenOption.SetValue( - this.createNewLocalRadioButton.Checked ? - BatchRvt.CentralFileOpenOption.CreateNewLocal : - BatchRvt.CentralFileOpenOption.Detach - ); - this.Settings.DeleteLocalAfter.SetValue(this.deleteLocalAfterCheckBox.Checked); - this.Settings.DiscardWorksetsOnDetach.SetValue(this.discardWorksetsCheckBox.Checked); - this.Settings.WorksetConfigurationOption.SetValue( - this.closeAllWorksetsRadioButton.Checked ? - BatchRvt.WorksetConfigurationOption.CloseAllWorksets : - ( - this.openAllWorksetsRadioButton.Checked ? - BatchRvt.WorksetConfigurationOption.OpenAllWorksets : - BatchRvt.WorksetConfigurationOption.OpenLastViewed - ) - ); - } - ), - - // Revit Session settings - new UIConfigItem( - () => { - this.useSeparateRevitSessionRadioButton.Checked = (this.Settings.RevitSessionOption.GetValue() == BatchRvt.RevitSessionOption.UseSeparateSessionPerFile); - this.useSameRevitSessionRadioButton.Checked = (this.Settings.RevitSessionOption.GetValue() == BatchRvt.RevitSessionOption.UseSameSessionForFilesOfSameVersion); - var processingTimeOutInMinutes = this.Settings.ProcessingTimeOutInMinutes.GetValue(); - if (processingTimeOutInMinutes < 0) - { - processingTimeOutInMinutes = 0; - } - this.perFileProcessingTimeOutCheckBox.Checked = processingTimeOutInMinutes > 0; - this.timeOutNumericUpDown.Value = processingTimeOutInMinutes; - UpdateRevitSessionControls(); - - // NOTE: This is done so that the Revit session option is updated according to the script file type. - // NOTE: This is a bit hacky! - UpdateTaskScript(this.taskScriptTextBox.Text); - }, - () => { - this.Settings.RevitSessionOption.SetValue( - this.useSameRevitSessionRadioButton.Checked ? - BatchRvt.RevitSessionOption.UseSameSessionForFilesOfSameVersion : - BatchRvt.RevitSessionOption.UseSeparateSessionPerFile - ); - - var processingTimeOutInMinutes = (int)this.timeOutNumericUpDown.Value; - if (processingTimeOutInMinutes < 0) - { - processingTimeOutInMinutes = 0; - } - - this.Settings.ProcessingTimeOutInMinutes.SetValue(this.perFileProcessingTimeOutCheckBox.Checked ? processingTimeOutInMinutes : 0); - } - ), - - // Revit Processing settings - new UIConfigItem( - () => { - this.enableBatchProcessingCheckBox.Checked = (this.Settings.RevitProcessingOption.GetValue() == BatchRvt.RevitProcessingOption.BatchRevitFileProcessing); - this.enableSingleRevitTaskProcessingCheckBox.Checked = (this.Settings.RevitProcessingOption.GetValue() == BatchRvt.RevitProcessingOption.SingleRevitTaskProcessing); - UpdateRevitProcessingControls(); - }, - () => { - this.Settings.RevitProcessingOption.SetValue( - this.enableSingleRevitTaskProcessingCheckBox.Checked ? - BatchRvt.RevitProcessingOption.SingleRevitTaskProcessing : - BatchRvt.RevitProcessingOption.BatchRevitFileProcessing - ); - } - ), - - // Single Revit Task Processing settings - new UIConfigItem( - () => { - Populate( - this.singleRevitTaskRevitVersionComboBox, - RevitVersion.GetInstalledRevitVersions().Select(RevitVersion.GetRevitVersionText), - RevitVersion.GetRevitVersionText(this.Settings.SingleRevitTaskRevitVersion.GetValue()) - ); - }, - () => { - this.Settings.SingleRevitTaskRevitVersion.SetValue( - RevitVersion.GetSupportedRevitVersion(this.singleRevitTaskRevitVersionComboBox.SelectedItem as string) - ); - } - ), - - // Batch Revit File Processing settings - new UIConfigItem( - () => { - this.useFileRevitVersionRadioButton.Checked = (this.Settings.RevitFileProcessingOption.GetValue() == BatchRvt.RevitFileProcessingOption.UseFileRevitVersionIfAvailable); - this.useSpecificRevitVersionRadioButton.Checked = (this.Settings.RevitFileProcessingOption.GetValue() == BatchRvt.RevitFileProcessingOption.UseSpecificRevitVersion); - this.useMinimumAvailableVersionCheckBox.Checked = this.Settings.IfNotAvailableUseMinimumAvailableRevitVersion.GetValue(); - this.auditOnOpeningCheckBox.Checked = this.Settings.AuditOnOpening.GetValue(); - Populate( - this.specificRevitVersionComboBox, - RevitVersion.GetInstalledRevitVersions().Select(RevitVersion.GetRevitVersionText), - RevitVersion.GetRevitVersionText(this.Settings.BatchRevitTaskRevitVersion.GetValue()) - ); - UpdateRevitFileProcessingControls(); - }, - () => { - this.Settings.RevitFileProcessingOption.SetValue( - this.useSpecificRevitVersionRadioButton.Checked ? - BatchRvt.RevitFileProcessingOption.UseSpecificRevitVersion : - BatchRvt.RevitFileProcessingOption.UseFileRevitVersionIfAvailable - ); - this.Settings.IfNotAvailableUseMinimumAvailableRevitVersion.SetValue(this.useMinimumAvailableVersionCheckBox.Checked); - this.Settings.BatchRevitTaskRevitVersion.SetValue( - RevitVersion.GetSupportedRevitVersion(this.specificRevitVersionComboBox.SelectedItem as string) - ); - this.Settings.AuditOnOpening.SetValue(this.auditOnOpeningCheckBox.Checked); - } - ), - - // Show Advanced setting - new UIConfigItem( - () => { - this.showAdvancedSettingsCheckBox.Checked = this.Settings.ShowAdvancedSettings.GetValue(); - UpdateAdvancedSettings(); - }, - () => { - this.Settings.ShowAdvancedSettings.SetValue(this.showAdvancedSettingsCheckBox.Checked); - } - ), - }; - - return iuConfigItems; - } + // Data Export settings + new UIConfigItem( + () => + { + enableDataExportCheckBox.Checked = Settings.EnableDataExport.GetValue(); + dataExportFolderTextBox.Text = Settings.DataExportFolderPath.GetValue(); + UpdateDataExportControls(); + }, + () => + { + Settings.EnableDataExport.SetValue(enableDataExportCheckBox.Checked); + Settings.DataExportFolderPath.SetValue(dataExportFolderTextBox.Text); + } + ), - private void UpdateTaskScript(string scriptFilePath) - { - this.taskScriptTextBox.Text = scriptFilePath; - - var scriptType = GetScriptType(scriptFilePath); + // Pre-processing Script settings + new UIConfigItem( + () => + { + executePreProcessingScriptCheckBox.Checked = Settings.ExecutePreProcessingScript.GetValue(); + preProcessingScriptTextBox.Text = Settings.PreProcessingScriptFilePath.GetValue(); + UpdatePreProcessingScriptControls(); + }, + () => + { + Settings.ExecutePreProcessingScript.SetValue(executePreProcessingScriptCheckBox.Checked); + Settings.PreProcessingScriptFilePath.SetValue(preProcessingScriptTextBox.Text); + } + ), - if (scriptType == ScriptType.Dynamo) - { - this.useSeparateRevitSessionRadioButton.Checked = true; - this.useSameRevitSessionRadioButton.Checked = false; - this.useSeparateRevitSessionRadioButton.Enabled = false; - this.useSameRevitSessionRadioButton.Enabled = false; - } - else - { - this.useSeparateRevitSessionRadioButton.Enabled = true; - this.useSameRevitSessionRadioButton.Enabled = true; - } - } + // Post-processing Script settings + new UIConfigItem( + () => + { + executePostProcessingScriptCheckBox.Checked = Settings.ExecutePostProcessingScript.GetValue(); + postProcessingScriptTextBox.Text = Settings.PostProcessingScriptFilePath.GetValue(); + UpdatePostProcessingScriptControls(); + }, + () => + { + Settings.ExecutePostProcessingScript.SetValue(executePostProcessingScriptCheckBox.Checked); + Settings.PostProcessingScriptFilePath.SetValue(postProcessingScriptTextBox.Text); + } + ), - private double GetDisplaySettingPercentage() - { - var graphics = this.CreateGraphics(); - var dpiX = graphics.DpiX; - return dpiX / 96f; - } + // Central File Processing settings + new UIConfigItem( + () => + { + detachFromCentralRadioButton.Checked = Settings.CentralFileOpenOption.GetValue() == + BatchRvt.CentralFileOpenOption.Detach; + createNewLocalRadioButton.Checked = Settings.CentralFileOpenOption.GetValue() == + BatchRvt.CentralFileOpenOption.CreateNewLocal; + deleteLocalAfterCheckBox.Checked = Settings.DeleteLocalAfter.GetValue(); + discardWorksetsCheckBox.Checked = Settings.DiscardWorksetsOnDetach.GetValue(); + closeAllWorksetsRadioButton.Checked = Settings.WorksetConfigurationOption.GetValue() == + BatchRvt.WorksetConfigurationOption.CloseAllWorksets; + openAllWorksetsRadioButton.Checked = Settings.WorksetConfigurationOption.GetValue() == + BatchRvt.WorksetConfigurationOption.OpenAllWorksets; + openLastViewedWorksetsRadioButton.Checked = Settings.WorksetConfigurationOption.GetValue() == + BatchRvt.WorksetConfigurationOption.OpenLastViewed; + UpdateCentralFileProcessingControls(); + }, + () => + { + Settings.CentralFileOpenOption.SetValue( + createNewLocalRadioButton.Checked + ? BatchRvt.CentralFileOpenOption.CreateNewLocal + : BatchRvt.CentralFileOpenOption.Detach + ); + Settings.DeleteLocalAfter.SetValue(deleteLocalAfterCheckBox.Checked); + Settings.DiscardWorksetsOnDetach.SetValue(discardWorksetsCheckBox.Checked); + Settings.WorksetConfigurationOption.SetValue( + closeAllWorksetsRadioButton.Checked ? BatchRvt.WorksetConfigurationOption.CloseAllWorksets : + openAllWorksetsRadioButton.Checked ? BatchRvt.WorksetConfigurationOption.OpenAllWorksets : + BatchRvt.WorksetConfigurationOption.OpenLastViewed + ); + } + ), - private static int Scale(int value, double scale) - { - return (int)(value * scale); - } + // Revit Session settings + new UIConfigItem( + () => + { + useSeparateRevitSessionRadioButton.Checked = Settings.RevitSessionOption.GetValue() == + BatchRvt.RevitSessionOption + .UseSeparateSessionPerFile; + useSameRevitSessionRadioButton.Checked = Settings.RevitSessionOption.GetValue() == + BatchRvt.RevitSessionOption + .UseSameSessionForFilesOfSameVersion; + var processingTimeOutInMinutes = Settings.ProcessingTimeOutInMinutes.GetValue(); + if (processingTimeOutInMinutes < 0) processingTimeOutInMinutes = 0; + perFileProcessingTimeOutCheckBox.Checked = processingTimeOutInMinutes > 0; + timeOutNumericUpDown.Value = processingTimeOutInMinutes; + UpdateRevitSessionControls(); + + // NOTE: This is done so that the Revit session option is updated according to the script file type. + // NOTE: This is a bit hacky! + UpdateTaskScript(taskScriptTextBox.Text); + }, + () => + { + Settings.RevitSessionOption.SetValue( + useSameRevitSessionRadioButton.Checked + ? BatchRvt.RevitSessionOption.UseSameSessionForFilesOfSameVersion + : BatchRvt.RevitSessionOption.UseSeparateSessionPerFile + ); - private static System.Drawing.Size Scale(System.Drawing.Size size, double scale) - { - return new System.Drawing.Size(Scale(size.Width, scale), Scale(size.Height, scale)); - } + var processingTimeOutInMinutes = (int)timeOutNumericUpDown.Value; + if (processingTimeOutInMinutes < 0) processingTimeOutInMinutes = 0; - private void AdjustWindowSizeForDisplaySetting() - { - var displaySettingPercentage = GetDisplaySettingPercentage(); + Settings.ProcessingTimeOutInMinutes.SetValue(perFileProcessingTimeOutCheckBox.Checked + ? processingTimeOutInMinutes + : 0); + } + ), - this.MinimumSize = Scale(this.MinimumSize, displaySettingPercentage); - this.MaximumSize = Scale(this.MaximumSize, displaySettingPercentage); - this.Size = Scale(this.Size, displaySettingPercentage); - } + // Revit Processing settings + new UIConfigItem( + () => + { + enableBatchProcessingCheckBox.Checked = Settings.RevitProcessingOption.GetValue() == + BatchRvt.RevitProcessingOption.BatchRevitFileProcessing; + enableSingleRevitTaskProcessingCheckBox.Checked = Settings.RevitProcessingOption.GetValue() == + BatchRvt.RevitProcessingOption + .SingleRevitTaskProcessing; + UpdateRevitProcessingControls(); + }, + () => + { + Settings.RevitProcessingOption.SetValue( + enableSingleRevitTaskProcessingCheckBox.Checked + ? BatchRvt.RevitProcessingOption.SingleRevitTaskProcessing + : BatchRvt.RevitProcessingOption.BatchRevitFileProcessing + ); + } + ), - private void BatchRvtGuiForm_Load(object sender, EventArgs e) - { - this.Text = WINDOW_TITLE; + // Single Revit Task Processing settings + new UIConfigItem( + () => + { + Populate( + singleRevitTaskRevitVersionComboBox, + RevitVersion.GetInstalledRevitVersions().Select(RevitVersion.GetRevitVersionText), + RevitVersion.GetRevitVersionText(Settings.SingleRevitTaskRevitVersion.GetValue()) + ); + }, + () => + { + Settings.SingleRevitTaskRevitVersion.SetValue( + RevitVersion.GetSupportedRevitVersion( + singleRevitTaskRevitVersionComboBox.SelectedItem as string) + ); + } + ), - this.TopMost = false; - this.alwaysOnTopCheckbox.Checked = this.TopMost; - this.batchRvtOutputGroupBox.Visible = false; + // Batch Revit File Processing settings + new UIConfigItem( + () => + { + useFileRevitVersionRadioButton.Checked = Settings.RevitFileProcessingOption.GetValue() == + BatchRvt.RevitFileProcessingOption + .UseFileRevitVersionIfAvailable; + useSpecificRevitVersionRadioButton.Checked = Settings.RevitFileProcessingOption.GetValue() == + BatchRvt.RevitFileProcessingOption + .UseSpecificRevitVersion; + useMinimumAvailableVersionCheckBox.Checked = + Settings.IfNotAvailableUseMinimumAvailableRevitVersion.GetValue(); + auditOnOpeningCheckBox.Checked = Settings.AuditOnOpening.GetValue(); + Populate( + specificRevitVersionComboBox, + RevitVersion.GetInstalledRevitVersions().Select(RevitVersion.GetRevitVersionText), + RevitVersion.GetRevitVersionText(Settings.BatchRevitTaskRevitVersion.GetValue()) + ); + UpdateRevitFileProcessingControls(); + }, + () => + { + Settings.RevitFileProcessingOption.SetValue( + useSpecificRevitVersionRadioButton.Checked + ? BatchRvt.RevitFileProcessingOption.UseSpecificRevitVersion + : BatchRvt.RevitFileProcessingOption.UseFileRevitVersionIfAvailable + ); + Settings.IfNotAvailableUseMinimumAvailableRevitVersion.SetValue( + useMinimumAvailableVersionCheckBox.Checked); + Settings.BatchRevitTaskRevitVersion.SetValue( + RevitVersion.GetSupportedRevitVersion(specificRevitVersionComboBox.SelectedItem as string) + ); + Settings.AuditOnOpening.SetValue(auditOnOpeningCheckBox.Checked); + } + ), - this.MinimumSize = SETUP_MINIMUM_SIZE; - this.MaximumSize = SETUP_MAXIMUM_SIZE; - this.Size = SETUP_INITIAL_SIZE; - this.MaximizeBox = false; + // Show Advanced setting + new UIConfigItem( + () => + { + showAdvancedSettingsCheckBox.Checked = Settings.ShowAdvancedSettings.GetValue(); + UpdateAdvancedSettings(); + }, + () => { Settings.ShowAdvancedSettings.SetValue(showAdvancedSettingsCheckBox.Checked); } + ) + }; - AdjustWindowSizeForDisplaySetting(); + return iuConfigItems; + } - bool isLoaded = LoadSettings(); + private void UpdateTaskScript(string scriptFilePath) + { + taskScriptTextBox.Text = scriptFilePath; - // TODO: show error message if load failed!! - } + var scriptType = GetScriptType(scriptFilePath); - private bool LoadSettings(string filePath = null) + if (scriptType == ScriptType.Dynamo) { - var newBatchRvtSettings = new BatchRvtSettings(); + useSeparateRevitSessionRadioButton.Checked = true; + useSameRevitSessionRadioButton.Checked = false; + useSeparateRevitSessionRadioButton.Enabled = false; + useSameRevitSessionRadioButton.Enabled = false; + } + else + { + useSeparateRevitSessionRadioButton.Enabled = true; + useSameRevitSessionRadioButton.Enabled = true; + } + } - bool isLoaded = newBatchRvtSettings.LoadFromFile(filePath); + private double GetDisplaySettingPercentage() + { + var graphics = CreateGraphics(); + var dpiX = graphics.DpiX; + return dpiX / 96f; + } - if (isLoaded) - { - this.Settings = newBatchRvtSettings; - } + private static int Scale(int value, double scale) + { + return (int)(value * scale); + } - this.UIConfiguration.UpdateUI(); + private static Size Scale(Size size, double scale) + { + return new Size(Scale(size.Width, scale), Scale(size.Height, scale)); + } - VerifyExcelInstallation(this.revitFileListTextBox.Text); + private void AdjustWindowSizeForDisplaySetting() + { + var displaySettingPercentage = GetDisplaySettingPercentage(); - return isLoaded; - } + MinimumSize = Scale(MinimumSize, displaySettingPercentage); + MaximumSize = Scale(MaximumSize, displaySettingPercentage); + Size = Scale(Size, displaySettingPercentage); + } - private void VerifyExcelInstallation(string filePath) - { - if (!string.IsNullOrWhiteSpace(filePath)) - { - if (ExcelUtil.HasExcelExtension(filePath) && !ExcelUtil.IsExcelInstalled()) - { - MessageBox.Show( - "WARNING: An Excel installation was not detected! Support for Excel files requires an Excel installation.", - this.Text, - MessageBoxButtons.OK, - MessageBoxIcon.Warning - ); - } - } - } + private void BatchRvtGuiForm_Load(object sender, EventArgs e) + { + Text = WINDOW_TITLE; - private bool SaveSettings(string filePath = null) - { - this.UIConfiguration.UpdateConfig(); + TopMost = false; + alwaysOnTopCheckbox.Checked = TopMost; + batchRvtOutputGroupBox.Visible = false; - bool isSaved = this.Settings.SaveToFile(filePath); + MinimumSize = SETUP_MINIMUM_SIZE; + MaximumSize = SETUP_MAXIMUM_SIZE; + Size = SETUP_INITIAL_SIZE; + MaximizeBox = false; - return isSaved; - } + AdjustWindowSizeForDisplaySetting(); - private void BatchRvtGuiForm_FormClosing(object sender, FormClosingEventArgs e) - { - if (this.isBatchRvtRunning) - { - var message = new StringBuilder(); + var isLoaded = LoadSettings(); - message.AppendLine("Do you want to terminate the currently running task?"); + // TODO: show error message if load failed!! + } - var dialogResult = MessageBox.Show( - message.ToString(), - this.Text, - MessageBoxButtons.YesNoCancel, - MessageBoxIcon.Asterisk, - MessageBoxDefaultButton.Button3 - ); + private bool LoadSettings(string filePath = null) + { + var newBatchRvtSettings = new BatchRvtSettings(); - if (dialogResult == DialogResult.Cancel) - { - e.Cancel = true; - } - else if (dialogResult == DialogResult.Yes) - { - try - { - this.batchRvtProcess.Kill(); - } - catch (Exception) - { - // TODO: report failure to kill the process? - } - } - } + var isLoaded = newBatchRvtSettings.LoadFromFile(filePath); - if (!e.Cancel) - { - var message = new StringBuilder(); + if (isLoaded) Settings = newBatchRvtSettings; - message.AppendLine("Do you want to save the current settings as default?"); + UIConfiguration.UpdateUI(); - var dialogResult = MessageBox.Show( - message.ToString(), - this.Text, - MessageBoxButtons.YesNo, - MessageBoxIcon.Question, - MessageBoxDefaultButton.Button1 - ); + VerifyExcelInstallation(revitFileListTextBox.Text); - if (dialogResult == DialogResult.Yes) - { - bool isSaved = SaveSettings(); + return isLoaded; + } - // TODO: show error message if save failed!! - } + private void VerifyExcelInstallation(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) return; + if (ExcelUtil.HasExcelExtension(filePath) && !ExcelUtil.IsExcelInstalled()) + MessageBox.Show( + "WARNING: An Excel installation was not detected! Support for Excel files requires an Excel installation.", + Text, + MessageBoxButtons.OK, + MessageBoxIcon.Warning + ); + } - if (readBatchRvtOutput_Timer != null) - { - this.readBatchRvtOutput_Timer.Stop(); - this.readBatchRvtOutput_Timer.Dispose(); - } - } - } + private bool SaveSettings(string filePath = null) + { + UIConfiguration.UpdateConfig(); - private void alwaysOnTopCheckbox_CheckedChanged(object sender, EventArgs e) - { - this.TopMost = this.alwaysOnTopCheckbox.Checked; - } + var isSaved = Settings.SaveToFile(filePath); - private void closeButton_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.Cancel; - this.Close(); - } + return isSaved; + } - public static void ShowErrorMessageBox(string errorMessage) - { - MessageBox.Show(errorMessage, BatchRvtGuiForm.WINDOW_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); - } + private void BatchRvtGuiForm_FormClosing(object sender, FormClosingEventArgs e) + { + if (!isBatchRvtRunning) return; - private bool ValidateConfig() - { - bool validated = false; - if (!this.enableSingleRevitTaskProcessingCheckBox.Checked && !this.enableBatchProcessingCheckBox.Checked) - { - ShowErrorMessageBox("ERROR: You must select either Batch Revit File Processing or Single Revit Task Processing!"); - } - else if (!File.Exists(this.Settings.TaskScriptFilePath.GetValue())) - { - ShowErrorMessageBox("ERROR: You must select an existing Task script!"); - } - else if ( - (this.Settings.RevitProcessingOption.GetValue() == BatchRvt.RevitProcessingOption.BatchRevitFileProcessing) - && - !File.Exists(this.Settings.RevitFileListFilePath.GetValue()) - ) - { - ShowErrorMessageBox("ERROR: You must select an existing Revit File List!"); - } - else if ( - this.Settings.EnableDataExport.GetValue() - && - !Directory.Exists(this.Settings.DataExportFolderPath.GetValue()) - ) - { - ShowErrorMessageBox("ERROR: You must select an existing Data Export folder!"); - } - else if ( - this.Settings.ExecutePreProcessingScript.GetValue() - && - !File.Exists(this.Settings.PreProcessingScriptFilePath.GetValue()) - ) - { - ShowErrorMessageBox("ERROR: You must select an existing Pre-Processing Python script!"); - } - else if ( - this.Settings.ExecutePostProcessingScript.GetValue() - && - !File.Exists(this.Settings.PostProcessingScriptFilePath.GetValue()) - ) + var message = new StringBuilder(); + + message.AppendLine("Do you want to terminate the currently running task?"); + + var dialogResult = MessageBox.Show( + message.ToString(), + Text, + MessageBoxButtons.YesNoCancel, + MessageBoxIcon.Asterisk, + MessageBoxDefaultButton.Button3 + ); + + if (dialogResult == DialogResult.Cancel) + e.Cancel = true; + else if (dialogResult == DialogResult.Yes) + try { - ShowErrorMessageBox("ERROR: You must select an existing Post-Processing Python script!"); + batchRvtProcess.Kill(); } - else + catch (Exception) { - validated = true; + // TODO: report failure to kill the process? } + + + if (e.Cancel) return; - return validated; - } - private void startButton_Click(object sender, EventArgs e) + message.AppendLine("Do you want to save the current settings as default?"); + + var dialogResult2 = MessageBox.Show( + message.ToString(), + Text, + MessageBoxButtons.YesNo, + MessageBoxIcon.Question, + MessageBoxDefaultButton.Button1 + ); + + if (dialogResult2 == DialogResult.Yes) { - this.UIConfiguration.UpdateConfig(); + var isSaved = SaveSettings(); - bool validated = ValidateConfig(); + // TODO: show error message if save failed!! + } - if (validated) - { - bool isSaved = SaveSettings(); + if (readBatchRvtOutput_Timer == null) return; + readBatchRvtOutput_Timer.Stop(); + readBatchRvtOutput_Timer.Dispose(); + } - // TODO: show error message if save failed!! + private void alwaysOnTopCheckbox_CheckedChanged(object sender, EventArgs e) + { + TopMost = alwaysOnTopCheckbox.Checked; + } - var settingsFilePath = BatchRvtSettings.GetDefaultSettingsFilePath(); + private void closeButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } - this.batchRvtProcess = BatchRvt.StartBatchRvt(settingsFilePath); + public static void ShowErrorMessageBox(string errorMessage) + { + MessageBox.Show(errorMessage, WINDOW_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); + } - this.readBatchRvtOutput_Timer = new Timer() { Interval = READ_OUTPUT_INTERVAL_IN_MS }; - this.readBatchRvtOutput_Timer.Tick += readBatchRvtOutput_Timer_Tick; + private bool ValidateConfig() + { + var validated = false; + + if (!enableSingleRevitTaskProcessingCheckBox.Checked && !enableBatchProcessingCheckBox.Checked) + ShowErrorMessageBox( + "ERROR: You must select either Batch Revit File Processing or Single Revit Task Processing!"); + else if (!File.Exists(Settings.TaskScriptFilePath.GetValue())) + ShowErrorMessageBox("ERROR: You must select an existing Task script!"); + else if ( + Settings.RevitProcessingOption.GetValue() == BatchRvt.RevitProcessingOption.BatchRevitFileProcessing + && + !File.Exists(Settings.RevitFileListFilePath.GetValue()) + ) + ShowErrorMessageBox("ERROR: You must select an existing Revit File List!"); + else if ( + Settings.EnableDataExport.GetValue() + && + !Directory.Exists(Settings.DataExportFolderPath.GetValue()) + ) + ShowErrorMessageBox("ERROR: You must select an existing Data Export folder!"); + else if ( + Settings.ExecutePreProcessingScript.GetValue() + && + !File.Exists(Settings.PreProcessingScriptFilePath.GetValue()) + ) + ShowErrorMessageBox("ERROR: You must select an existing Pre-Processing Python script!"); + else if ( + Settings.ExecutePostProcessingScript.GetValue() + && + !File.Exists(Settings.PostProcessingScriptFilePath.GetValue()) + ) + ShowErrorMessageBox("ERROR: You must select an existing Post-Processing Python script!"); + else + validated = true; + + return validated; + } - this.isBatchRvtRunning = true; - this.settingsGroupBox.Enabled = false; - this.importSettingsButton.Enabled = false; - this.startButton.Enabled = false; - this.startButton.Text = "Running..."; - this.batchRvtOutputGroupBox.Visible = true; - this.MinimumSize = RUNNING_MINIMUM_SIZE; - this.MaximumSize = RUNNING_MAXIMUM_SIZE; - this.Size = RUNNING_INITIAL_SIZE; - this.MaximizeBox = true; - this.isUsingRunningSize = true; + private void startButton_Click(object sender, EventArgs e) + { + UIConfiguration.UpdateConfig(); - UpdateAdvancedSettings(); + var validated = ValidateConfig(); - readBatchRvtOutput_Timer.Start(); - } - } + if (!validated) return; + var isSaved = SaveSettings(); - private void readBatchRvtOutput_Timer_Tick(object sender, EventArgs e) - { - var linesAndPendingTask = StreamIOUtil.ReadAvailableLines(this.batchRvtProcess.StandardOutput, this.pendingOutputReadLineTask); - this.pendingOutputReadLineTask = linesAndPendingTask.Item2; - var lines = linesAndPendingTask.Item1; + // TODO: show error message if save failed!! - foreach (var line in lines) - { - var fullLine = line + Environment.NewLine; + var settingsFilePath = BatchRvtSettings.GetDefaultSettingsFilePath(); - if (!BatchRvt.IsBatchRvtLine(line)) - { - var timestamp = DateTime.Now.ToString("HH:mm:ss"); + batchRvtProcess = BatchRvt.StartBatchRvt(settingsFilePath); - fullLine = timestamp + " : [ REVIT MESSAGE ] : " + fullLine; - } + readBatchRvtOutput_Timer = new Timer { Interval = READ_OUTPUT_INTERVAL_IN_MS }; + readBatchRvtOutput_Timer.Tick += readBatchRvtOutput_Timer_Tick; - if (BatchRvt.IsBatchRvtLine(line)) // Do not show non-BatchRvt-related output. (TODO: reconsider?) - { - this.batchRvtOutputTextBox.AppendText(fullLine); - } - } + isBatchRvtRunning = true; + settingsGroupBox.Enabled = false; + importSettingsButton.Enabled = false; + startButton.Enabled = false; + startButton.Text = @"Running..."; + batchRvtOutputGroupBox.Visible = true; + MinimumSize = RUNNING_MINIMUM_SIZE; + MaximumSize = RUNNING_MAXIMUM_SIZE; + Size = RUNNING_INITIAL_SIZE; + MaximizeBox = true; + isUsingRunningSize = true; - linesAndPendingTask = StreamIOUtil.ReadAvailableLines(this.batchRvtProcess.StandardError, this.pendingErrorReadLineTask); - this.pendingErrorReadLineTask = linesAndPendingTask.Item2; - lines = linesAndPendingTask.Item1; + UpdateAdvancedSettings(); - foreach (var line in lines) - { - if (line.StartsWith("log4cplus:")) // ignore pesky log4cplus messages (an Autodesk thing?) - { - continue; - } + readBatchRvtOutput_Timer.Start(); + } - if (this.Settings.ShowRevitProcessErrorMessages.GetValue() == true) - { - this.batchRvtOutputTextBox.AppendText("[ REVIT ERROR MESSAGE ] : " + line + Environment.NewLine); - } - } + private void readBatchRvtOutput_Timer_Tick(object sender, EventArgs e) + { + var linesAndPendingTask = + StreamIOUtil.ReadAvailableLines(batchRvtProcess.StandardOutput, pendingOutputReadLineTask); + pendingOutputReadLineTask = linesAndPendingTask.Item2; + var lines = linesAndPendingTask.Item1; + + foreach (var line in lines) + { + var fullLine = line + Environment.NewLine; - if (isBatchRvtRunning) + if (!BatchRvt.IsBatchRvtLine(line)) { - this.batchRvtProcess.Refresh(); - if (this.batchRvtProcess.HasExited) - { - this.isBatchRvtRunning = false; - this.startButton.Text = "Done!"; - } + var timestamp = DateTime.Now.ToString("HH:mm:ss"); + + fullLine = timestamp + " : [ REVIT MESSAGE ] : " + fullLine; } - } - private void browseScriptButton_Click(object sender, EventArgs e) - { - BrowseForExistingScriptFile( - "Select Task script", - scriptFilePath => { UpdateTaskScript(scriptFilePath); }, - ScriptType.Any, - PathUtil.GetExistingFileDirectoryPath(this.taskScriptTextBox.Text) - ); + if (BatchRvt.IsBatchRvtLine(line)) // Do not show non-BatchRvt-related output. (TODO: reconsider?) + batchRvtOutputTextBox.AppendText(fullLine); } - private void BrowseForSave(string dialogTitle, Action fileAction, string defaultExt, string filter, string initialDirectory = null, string initialFileName = null) - { - var saveFileDialog = new SaveFileDialog(); + linesAndPendingTask = + StreamIOUtil.ReadAvailableLines(batchRvtProcess.StandardError, pendingErrorReadLineTask); + pendingErrorReadLineTask = linesAndPendingTask.Item2; + lines = linesAndPendingTask.Item1; - saveFileDialog.DefaultExt = defaultExt; - saveFileDialog.Filter = filter; - saveFileDialog.Title = dialogTitle; + foreach (var line in lines.Where(line => !line.StartsWith("log4cplus:")) + .Where(line => Settings.ShowRevitProcessErrorMessages.GetValue())) + batchRvtOutputTextBox.AppendText("[ REVIT ERROR MESSAGE ] : " + line + Environment.NewLine); - if (!string.IsNullOrWhiteSpace(initialDirectory)) - { - saveFileDialog.InitialDirectory = initialDirectory; - } + if (!isBatchRvtRunning) return; + batchRvtProcess.Refresh(); + if (!batchRvtProcess.HasExited) return; + isBatchRvtRunning = false; + startButton.Text = @"Done!"; + } - if (!string.IsNullOrWhiteSpace(initialFileName)) - { - saveFileDialog.FileName = initialFileName; - } + private void browseScriptButton_Click(object sender, EventArgs e) + { + BrowseForExistingScriptFile( + "Select Task script", + UpdateTaskScript, + ScriptType.Any, + PathUtil.GetExistingFileDirectoryPath(taskScriptTextBox.Text) + ); + } - var dialogResult = saveFileDialog.ShowDialog(this); + private void BrowseForSave(string dialogTitle, Action fileAction, string defaultExt, string filter, + string initialDirectory = null, string initialFileName = null) + { + var saveFileDialog = new SaveFileDialog(); - if (dialogResult == DialogResult.OK) - { - var selectedFilePath = saveFileDialog.FileName; + saveFileDialog.DefaultExt = defaultExt; + saveFileDialog.Filter = filter; + saveFileDialog.Title = dialogTitle; - if (!string.IsNullOrWhiteSpace(selectedFilePath)) - { - fileAction(selectedFilePath); - } - } + if (!string.IsNullOrWhiteSpace(initialDirectory)) saveFileDialog.InitialDirectory = initialDirectory; - return; - } + if (!string.IsNullOrWhiteSpace(initialFileName)) saveFileDialog.FileName = initialFileName; - private void BrowseForFile(string dialogTitle, Action fileAction, string defaultExt, string filter, bool checkFileExists, string initialDirectory = null) - { - var openFileDialog = new OpenFileDialog(); + var dialogResult = saveFileDialog.ShowDialog(this); - openFileDialog.DefaultExt = defaultExt; - openFileDialog.Filter = filter; - openFileDialog.CheckFileExists = checkFileExists; - openFileDialog.ReadOnlyChecked = true; - openFileDialog.Multiselect = false; - openFileDialog.Title = dialogTitle; + if (dialogResult != DialogResult.OK) return; - if (!string.IsNullOrWhiteSpace(initialDirectory)) - { - openFileDialog.InitialDirectory = initialDirectory; - } + var selectedFilePath = saveFileDialog.FileName; - var dialogResult = openFileDialog.ShowDialog(this); + if (!string.IsNullOrWhiteSpace(selectedFilePath)) fileAction(selectedFilePath); + } - if (dialogResult == DialogResult.OK) - { - var selectedFilePath = openFileDialog.FileName; + private void BrowseForFile(string dialogTitle, Action fileAction, string defaultExt, string filter, + bool checkFileExists, string initialDirectory = null) + { + var openFileDialog = new OpenFileDialog(); - if (!string.IsNullOrWhiteSpace(selectedFilePath)) - { - fileAction(selectedFilePath); - } - } + openFileDialog.DefaultExt = defaultExt; + openFileDialog.Filter = filter; + openFileDialog.CheckFileExists = checkFileExists; + openFileDialog.ReadOnlyChecked = true; + openFileDialog.Multiselect = false; + openFileDialog.Title = dialogTitle; - return; - } + if (!string.IsNullOrWhiteSpace(initialDirectory)) openFileDialog.InitialDirectory = initialDirectory; - private void BrowseForExistingScriptFile( - string dialogTitle, - Action scriptFileAction, - ScriptType scriptType, - string initialDirectory = null - ) - { - var scriptDefaultExtension = (scriptType == ScriptType.Dynamo) ? DYNAMO_SCRIPT_EXTENSION : PYTHON_SCRIPT_EXTENSION; - var scriptFilter = ( - (scriptType == ScriptType.Dynamo) ? DYNAMO_SCRIPT_FILTER : - (scriptType == ScriptType.Python) ? PYTHON_SCRIPT_FILTER : - ANY_SCRIPTS_FILTER - ); - - BrowseForFile( - dialogTitle, - scriptFileAction, - scriptDefaultExtension, - scriptFilter, - true, - initialDirectory - ); - } + var dialogResult = openFileDialog.ShowDialog(this); - private void browseRevitFileListButton_Click(object sender, EventArgs e) - { - var openFileDialog = new OpenFileDialog(); + if (dialogResult != DialogResult.OK) return; - openFileDialog.DefaultExt = ".txt"; - openFileDialog.Filter = "Revit File List (*.txt;*.xls;*.xlsx;*.csv)|*.txt;*.xls;*.xlsx;*.csv"; - openFileDialog.CheckFileExists = true; - openFileDialog.ReadOnlyChecked = true; - openFileDialog.Multiselect = false; - openFileDialog.Title = "Select Revit File List"; + var selectedFilePath = openFileDialog.FileName; - string initialDirectory = PathUtil.GetExistingFileDirectoryPath(this.revitFileListTextBox.Text); + if (!string.IsNullOrWhiteSpace(selectedFilePath)) fileAction(selectedFilePath); + } - if (initialDirectory != null) - { - openFileDialog.InitialDirectory = initialDirectory; - } + private void BrowseForExistingScriptFile( + string dialogTitle, + Action scriptFileAction, + ScriptType scriptType, + string initialDirectory = null + ) + { + var scriptDefaultExtension = + scriptType == ScriptType.Dynamo ? DYNAMO_SCRIPT_EXTENSION : PYTHON_SCRIPT_EXTENSION; + var scriptFilter = scriptType == ScriptType.Dynamo ? DYNAMO_SCRIPT_FILTER : + scriptType == ScriptType.Python ? PYTHON_SCRIPT_FILTER : + ANY_SCRIPTS_FILTER; + + BrowseForFile( + dialogTitle, + scriptFileAction, + scriptDefaultExtension, + scriptFilter, + true, + initialDirectory + ); + } - var dialogResult = openFileDialog.ShowDialog(this); + private void browseRevitFileListButton_Click(object sender, EventArgs e) + { + var openFileDialog = new OpenFileDialog(); - if (dialogResult == DialogResult.OK) - { - var selectedFilePath = openFileDialog.FileName; + openFileDialog.DefaultExt = ".txt"; + openFileDialog.Filter = "Revit File List (*.txt;*.xls;*.xlsx;*.csv)|*.txt;*.xls;*.xlsx;*.csv"; + openFileDialog.CheckFileExists = true; + openFileDialog.ReadOnlyChecked = true; + openFileDialog.Multiselect = false; + openFileDialog.Title = "Select Revit File List"; - if (!string.IsNullOrWhiteSpace(selectedFilePath)) - { - this.revitFileListTextBox.Text = selectedFilePath; + var initialDirectory = PathUtil.GetExistingFileDirectoryPath(revitFileListTextBox.Text); - VerifyExcelInstallation(selectedFilePath); - } - } - } + if (initialDirectory != null) openFileDialog.InitialDirectory = initialDirectory; - private void browseDataExportFolderButton_Click(object sender, EventArgs e) - { - var folderBrowserDialog = new FolderBrowserDialog(); + var dialogResult = openFileDialog.ShowDialog(this); - folderBrowserDialog.Description = "Select Data Export folder"; + if (dialogResult != DialogResult.OK) return; + var selectedFilePath = openFileDialog.FileName; - var currentFolderPath = this.dataExportFolderTextBox.Text; + if (string.IsNullOrWhiteSpace(selectedFilePath)) return; - if (Directory.Exists(currentFolderPath)) - { - folderBrowserDialog.SelectedPath = currentFolderPath; - } + revitFileListTextBox.Text = selectedFilePath; - var dialogResult = folderBrowserDialog.ShowDialog(this); + VerifyExcelInstallation(selectedFilePath); + } - if (dialogResult == DialogResult.OK) - { - var selectedFolderPath = folderBrowserDialog.SelectedPath; + private void browseDataExportFolderButton_Click(object sender, EventArgs e) + { + var folderBrowserDialog = new FolderBrowserDialog(); - if (!string.IsNullOrWhiteSpace(selectedFolderPath)) - { - this.dataExportFolderTextBox.Text = selectedFolderPath; - } - } - } + folderBrowserDialog.Description = "Select Data Export folder"; - private void batchRvtOutputTextBox_KeyDown(object sender, KeyEventArgs e) - { - if (e.KeyData == (Keys.Control | Keys.A)) - { - this.batchRvtOutputTextBox.SelectAll(); - e.SuppressKeyPress = true; - } - } + var currentFolderPath = dataExportFolderTextBox.Text; - private void executePreProcessingScriptCheckBox_CheckedChanged(object sender, EventArgs e) - { - UpdatePreProcessingScriptControls(); - } + if (Directory.Exists(currentFolderPath)) folderBrowserDialog.SelectedPath = currentFolderPath; - private void executePostProcessingScriptCheckBox_CheckedChanged(object sender, EventArgs e) - { - UpdatePostProcessingScriptControls(); - } + var dialogResult = folderBrowserDialog.ShowDialog(this); - private void preProcessingScriptBrowseButton_Click(object sender, EventArgs e) - { - BrowseForExistingScriptFile( - "Select Pre-Processing Python script", - scriptFilePath => { this.preProcessingScriptTextBox.Text = scriptFilePath; }, - ScriptType.Python, - PathUtil.GetExistingFileDirectoryPath(this.preProcessingScriptTextBox.Text) - ); - } + if (dialogResult != DialogResult.OK) return; - private void postProcessingScriptBrowseButton_Click(object sender, EventArgs e) - { - BrowseForExistingScriptFile( - "Select Post-Processing Python script", - scriptFilePath => { this.postProcessingScriptTextBox.Text = scriptFilePath; }, - ScriptType.Python, - PathUtil.GetExistingFileDirectoryPath(this.postProcessingScriptTextBox.Text) - ); - } + var selectedFolderPath = folderBrowserDialog.SelectedPath; - private void enableBatchProcessingCheckBox_CheckedChanged(object sender, EventArgs e) - { - if (this.enableBatchProcessingCheckBox.Checked) - { - this.enableSingleRevitTaskProcessingCheckBox.Checked = false; - } + if (!string.IsNullOrWhiteSpace(selectedFolderPath)) dataExportFolderTextBox.Text = selectedFolderPath; + } - UpdateRevitProcessingControls(); - } + private void batchRvtOutputTextBox_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyData != (Keys.Control | Keys.A)) return; - private void enableSingleRevitTaskProcessingCheckBox_CheckedChanged(object sender, EventArgs e) - { - if (this.enableSingleRevitTaskProcessingCheckBox.Checked) - { - this.enableBatchProcessingCheckBox.Checked = false; - } + batchRvtOutputTextBox.SelectAll(); + e.SuppressKeyPress = true; + } - UpdateRevitProcessingControls(); - } + private void executePreProcessingScriptCheckBox_CheckedChanged(object sender, EventArgs e) + { + UpdatePreProcessingScriptControls(); + } - private static ScriptType GetScriptType(string scriptFilePath) - { - return ( - PathUtil.HasExtension(scriptFilePath, PYTHON_SCRIPT_EXTENSION) ? - ScriptType.Python : - PathUtil.HasExtension(scriptFilePath, DYNAMO_SCRIPT_EXTENSION) ? - ScriptType.Dynamo : - ScriptType.Any - ); - } + private void executePostProcessingScriptCheckBox_CheckedChanged(object sender, EventArgs e) + { + UpdatePostProcessingScriptControls(); + } - private void UpdateRevitProcessingControls() - { - bool batchTaskEnabled = this.enableBatchProcessingCheckBox.Checked; - this.revitFileListLabel.Enabled = batchTaskEnabled; - this.revitFileListTextBox.Enabled = batchTaskEnabled; - this.browseRevitFileListButton.Enabled = batchTaskEnabled; - - this.centralFileProcessingGroupBox.Enabled = batchTaskEnabled; - this.revitFileProcessingGroupBox.Enabled = batchTaskEnabled; - this.revitSessionGroupBox.Enabled = batchTaskEnabled; - - bool singleTaskEnabled = this.enableSingleRevitTaskProcessingCheckBox.Checked; - this.singleRevitTaskRevitVersionLabel.Enabled = singleTaskEnabled; - this.singleRevitTaskRevitVersionComboBox.Enabled = singleTaskEnabled; - } + private void preProcessingScriptBrowseButton_Click(object sender, EventArgs e) + { + BrowseForExistingScriptFile( + "Select Pre-Processing Python script", + scriptFilePath => { preProcessingScriptTextBox.Text = scriptFilePath; }, + ScriptType.Python, + PathUtil.GetExistingFileDirectoryPath(preProcessingScriptTextBox.Text) + ); + } - private void perFileProcessingTimeOutCheckBox_CheckedChanged(object sender, EventArgs e) - { - UpdateRevitSessionControls(); - } + private void postProcessingScriptBrowseButton_Click(object sender, EventArgs e) + { + BrowseForExistingScriptFile( + "Select Post-Processing Python script", + scriptFilePath => { postProcessingScriptTextBox.Text = scriptFilePath; }, + ScriptType.Python, + PathUtil.GetExistingFileDirectoryPath(postProcessingScriptTextBox.Text) + ); + } - private void UpdateRevitSessionControls() - { - bool perFileProcessingTimeOutEnabled = this.perFileProcessingTimeOutCheckBox.Checked; + private void enableBatchProcessingCheckBox_CheckedChanged(object sender, EventArgs e) + { + if (enableBatchProcessingCheckBox.Checked) enableSingleRevitTaskProcessingCheckBox.Checked = false; - if (perFileProcessingTimeOutEnabled) - { - // If time-out option is enabled but the current numeric value is 0, set a sensible default / initial value for the time-out. - if (this.timeOutNumericUpDown.Value == 0) - { - this.timeOutNumericUpDown.Value = 15; - } - } - this.timeOutNumericUpDown.Enabled = perFileProcessingTimeOutEnabled; - } + UpdateRevitProcessingControls(); + } - private void UpdatePreProcessingScriptControls() - { - var isChecked = this.executePreProcessingScriptCheckBox.Checked; - this.preProcessingScriptTextBox.Enabled = isChecked; - this.preProcessingScriptBrowseButton.Enabled = isChecked; - this.preProcessingScriptNewScriptButton.Enabled = isChecked; - } + private void enableSingleRevitTaskProcessingCheckBox_CheckedChanged(object sender, EventArgs e) + { + if (enableSingleRevitTaskProcessingCheckBox.Checked) enableBatchProcessingCheckBox.Checked = false; - private void UpdatePostProcessingScriptControls() - { - var isChecked = this.executePostProcessingScriptCheckBox.Checked; - this.postProcessingScriptTextBox.Enabled = isChecked; - this.postProcessingScriptBrowseButton.Enabled = isChecked; - this.postProcessingScriptNewScriptButton.Enabled = isChecked; - } + UpdateRevitProcessingControls(); + } - private static void Populate(ComboBox comboBox, IEnumerable items, T selectedItem) - { - var itemsList = items.ToList(); + private static ScriptType GetScriptType(string scriptFilePath) + { + return PathUtil.HasExtension(scriptFilePath, PYTHON_SCRIPT_EXTENSION) ? ScriptType.Python : + PathUtil.HasExtension(scriptFilePath, DYNAMO_SCRIPT_EXTENSION) ? ScriptType.Dynamo : + ScriptType.Any; + } - comboBox.Items.Clear(); + private void UpdateRevitProcessingControls() + { + var batchTaskEnabled = enableBatchProcessingCheckBox.Checked; + revitFileListLabel.Enabled = batchTaskEnabled; + revitFileListTextBox.Enabled = batchTaskEnabled; + browseRevitFileListButton.Enabled = batchTaskEnabled; + + centralFileProcessingGroupBox.Enabled = batchTaskEnabled; + revitFileProcessingGroupBox.Enabled = batchTaskEnabled; + revitSessionGroupBox.Enabled = batchTaskEnabled; + + var singleTaskEnabled = enableSingleRevitTaskProcessingCheckBox.Checked; + singleRevitTaskRevitVersionLabel.Enabled = singleTaskEnabled; + singleRevitTaskRevitVersionComboBox.Enabled = singleTaskEnabled; + } - foreach (var item in itemsList) - { - comboBox.Items.Add(item); - } + private void perFileProcessingTimeOutCheckBox_CheckedChanged(object sender, EventArgs e) + { + UpdateRevitSessionControls(); + } - int selectedIndex = itemsList.IndexOf(selectedItem); + private void UpdateRevitSessionControls() + { + var perFileProcessingTimeOutEnabled = perFileProcessingTimeOutCheckBox.Checked; - comboBox.SelectedIndex = selectedIndex >= 0 ? selectedIndex : 0; - } + if (perFileProcessingTimeOutEnabled) + // If time-out option is enabled but the current numeric value is 0, set a sensible default / initial value for the time-out. + if (timeOutNumericUpDown.Value == 0) + timeOutNumericUpDown.Value = 15; + timeOutNumericUpDown.Enabled = perFileProcessingTimeOutEnabled; + } - private void createNewLocalRadioButton_CheckedChanged(object sender, EventArgs e) - { - UpdateCentralFileProcessingControls(); - } + private void UpdatePreProcessingScriptControls() + { + var isChecked = executePreProcessingScriptCheckBox.Checked; + preProcessingScriptTextBox.Enabled = isChecked; + preProcessingScriptBrowseButton.Enabled = isChecked; + preProcessingScriptNewScriptButton.Enabled = isChecked; + } - private void detachFromCentralRadioButton_CheckedChanged(object sender, EventArgs e) - { - UpdateCentralFileProcessingControls(); - } + private void UpdatePostProcessingScriptControls() + { + var isChecked = executePostProcessingScriptCheckBox.Checked; + postProcessingScriptTextBox.Enabled = isChecked; + postProcessingScriptBrowseButton.Enabled = isChecked; + postProcessingScriptNewScriptButton.Enabled = isChecked; + } - private void UpdateCentralFileProcessingControls() - { - this.deleteLocalAfterCheckBox.Enabled = this.createNewLocalRadioButton.Checked; - this.discardWorksetsCheckBox.Enabled = this.detachFromCentralRadioButton.Checked; - this.worksetConfigurationGroupBox.Enabled = !(this.detachFromCentralRadioButton.Checked && this.discardWorksetsCheckBox.Checked); - } + private static void Populate(ComboBox comboBox, IEnumerable items, T selectedItem) + { + var itemsList = items.ToList(); - private void useFileRevitVersionRadioButton_CheckedChanged(object sender, EventArgs e) - { - UpdateRevitFileProcessingControls(); - } + comboBox.Items.Clear(); - private void UpdateRevitFileProcessingControls() - { - this.useMinimumAvailableVersionCheckBox.Enabled = this.useFileRevitVersionRadioButton.Checked; - this.specificRevitVersionComboBox.Enabled = this.useSpecificRevitVersionRadioButton.Checked; - } + foreach (var item in itemsList) comboBox.Items.Add(item); - private void enableDataExportCheckBox_CheckedChanged(object sender, EventArgs e) - { - UpdateDataExportControls(); - } + var selectedIndex = itemsList.IndexOf(selectedItem); - private void UpdateDataExportControls() - { - var isChecked = this.enableDataExportCheckBox.Checked; - this.dataExportBaseFolderLabel.Enabled = isChecked; - this.dataExportFolderTextBox.Enabled = isChecked; - this.browseDataExportFolderButton.Enabled = isChecked; - } + comboBox.SelectedIndex = selectedIndex >= 0 ? selectedIndex : 0; + } - private void useSpecificRevitVersionRadioButton_CheckedChanged(object sender, EventArgs e) - { - UpdateRevitFileProcessingControls(); - } + private void createNewLocalRadioButton_CheckedChanged(object sender, EventArgs e) + { + UpdateCentralFileProcessingControls(); + } - private void importSettingsButton_Click(object sender, EventArgs e) - { - BrowseForFile( - "Import BatchRvt Settings file", - scriptFilePath => { this.LoadSettings(scriptFilePath); }, - BatchRvtSettings.SETTINGS_FILE_EXTENSION, - BatchRvtSettings.SETTINGS_FILE_FILTER, - true - ); - } + private void detachFromCentralRadioButton_CheckedChanged(object sender, EventArgs e) + { + UpdateCentralFileProcessingControls(); + } - private void exportSettingsButton_Click(object sender, EventArgs e) - { - BrowseForSave( - "Export BatchRvt Settings file", - scriptFilePath => { this.SaveSettings(scriptFilePath); }, - BatchRvtSettings.SETTINGS_FILE_EXTENSION, - BatchRvtSettings.SETTINGS_FILE_FILTER, - initialFileName: BatchRvtSettings.BATCHRVT_SETTINGS_FILENAME - ); - } + private void UpdateCentralFileProcessingControls() + { + deleteLocalAfterCheckBox.Enabled = createNewLocalRadioButton.Checked; + discardWorksetsCheckBox.Enabled = detachFromCentralRadioButton.Checked; + worksetConfigurationGroupBox.Enabled = + !(detachFromCentralRadioButton.Checked && discardWorksetsCheckBox.Checked); + } - private void taskScriptNewScriptButton_Click(object sender, EventArgs e) - { - BrowseForSaveScriptFile( - "Save New Task Script", - scriptFilePath => { - bool isSaved = this.SaveNewScript(scriptFilePath, SaveNewScriptType.TaskScript ); - - if (isSaved) - { - UpdateTaskScript(scriptFilePath); - } - else - { - ShowErrorMessageBox("ERROR: Failed to Save the new script!"); - } - }, - ScriptType.Python, - PathUtil.GetExistingFileDirectoryPath(this.taskScriptTextBox.Text), - NEW_TASK_SCRIPT_FILENAME - ); - } + private void useFileRevitVersionRadioButton_CheckedChanged(object sender, EventArgs e) + { + UpdateRevitFileProcessingControls(); + } - private void preProcessingScriptNewScriptButton_Click(object sender, EventArgs e) - { - BrowseForSaveScriptFile( - "Save New Pre-Processing Script", - scriptFilePath => { - bool isSaved = this.SaveNewScript(scriptFilePath, SaveNewScriptType.PreProcessingScript ); - - if (isSaved) - { - this.preProcessingScriptTextBox.Text = scriptFilePath; - } - else - { - ShowErrorMessageBox("ERROR: Failed to Save the new script!"); - } - }, - ScriptType.Python, - PathUtil.GetExistingFileDirectoryPath(this.preProcessingScriptTextBox.Text), - NEW_PREPROCESSING_SCRIPT_FILENAME - ); - } + private void UpdateRevitFileProcessingControls() + { + useMinimumAvailableVersionCheckBox.Enabled = useFileRevitVersionRadioButton.Checked; + specificRevitVersionComboBox.Enabled = useSpecificRevitVersionRadioButton.Checked; + } - private void postProcessingScriptNewScriptButton_Click(object sender, EventArgs e) - { - BrowseForSaveScriptFile( - "Save New Post-Processing Script", - scriptFilePath => { - bool isSaved = this.SaveNewScript(scriptFilePath, SaveNewScriptType.PostProcessingScript); - - if (isSaved) - { - this.postProcessingScriptTextBox.Text = scriptFilePath; - } - else - { - ShowErrorMessageBox("ERROR: Failed to Save the new script!"); - } - }, - ScriptType.Python, - PathUtil.GetExistingFileDirectoryPath(this.postProcessingScriptTextBox.Text), - NEW_POSTPROCESSING_SCRIPT_FILENAME - ); - } + private void enableDataExportCheckBox_CheckedChanged(object sender, EventArgs e) + { + UpdateDataExportControls(); + } - private void BrowseForSaveScriptFile( - string dialogTitle, - Action scriptFileAction, - ScriptType scriptType, - string initialDirectory = null, - string initialFileName = null - ) - { - var scriptDefaultExtension = (scriptType == ScriptType.Dynamo) ? DYNAMO_SCRIPT_EXTENSION : PYTHON_SCRIPT_EXTENSION; - var scriptFilter = (scriptType == ScriptType.Dynamo) ? DYNAMO_SCRIPT_FILTER : PYTHON_SCRIPT_FILTER; - - BrowseForSave( - dialogTitle, - scriptFileAction, - scriptDefaultExtension, - scriptFilter, - initialDirectory, - initialFileName - ); - } + private void UpdateDataExportControls() + { + var isChecked = enableDataExportCheckBox.Checked; + dataExportBaseFolderLabel.Enabled = isChecked; + dataExportFolderTextBox.Enabled = isChecked; + browseDataExportFolderButton.Enabled = isChecked; + } - private bool SaveNewScript(string scriptFilePath, SaveNewScriptType saveNewScriptType) - { - bool success = false; + private void useSpecificRevitVersionRadioButton_CheckedChanged(object sender, EventArgs e) + { + UpdateRevitFileProcessingControls(); + } + + private void importSettingsButton_Click(object sender, EventArgs e) + { + BrowseForFile( + "Import BatchRvt Settings file", + scriptFilePath => { LoadSettings(scriptFilePath); }, + BatchRvtSettings.SETTINGS_FILE_EXTENSION, + BatchRvtSettings.SETTINGS_FILE_FILTER, + true + ); + } + + private void exportSettingsButton_Click(object sender, EventArgs e) + { + BrowseForSave( + "Export BatchRvt Settings file", + scriptFilePath => { SaveSettings(scriptFilePath); }, + BatchRvtSettings.SETTINGS_FILE_EXTENSION, + BatchRvtSettings.SETTINGS_FILE_FILTER, + initialFileName: BatchRvtSettings.BATCHRVT_SETTINGS_FILENAME + ); + } - string scriptTemplateFileName = null; - if (saveNewScriptType == SaveNewScriptType.TaskScript) + private void taskScriptNewScriptButton_Click(object sender, EventArgs e) + { + BrowseForSaveScriptFile( + "Save New Task Script", + scriptFilePath => { - scriptTemplateFileName = TEMPLATE_TASK_SCRIPT_FILENAME; - } - else if (saveNewScriptType == SaveNewScriptType.PreProcessingScript) + var isSaved = SaveNewScript(scriptFilePath, SaveNewScriptType.TaskScript); + + if (isSaved) + UpdateTaskScript(scriptFilePath); + else + ShowErrorMessageBox("ERROR: Failed to Save the new script!"); + }, + ScriptType.Python, + PathUtil.GetExistingFileDirectoryPath(taskScriptTextBox.Text), + NEW_TASK_SCRIPT_FILENAME + ); + } + + private void preProcessingScriptNewScriptButton_Click(object sender, EventArgs e) + { + BrowseForSaveScriptFile( + "Save New Pre-Processing Script", + scriptFilePath => { - scriptTemplateFileName = TEMPLATE_PREPROCESSING_SCRIPT_FILENAME; - } - else if (saveNewScriptType == SaveNewScriptType.PostProcessingScript) + var isSaved = SaveNewScript(scriptFilePath, SaveNewScriptType.PreProcessingScript); + + if (isSaved) + preProcessingScriptTextBox.Text = scriptFilePath; + else + ShowErrorMessageBox("ERROR: Failed to Save the new script!"); + }, + ScriptType.Python, + PathUtil.GetExistingFileDirectoryPath(preProcessingScriptTextBox.Text), + NEW_PREPROCESSING_SCRIPT_FILENAME + ); + } + + private void postProcessingScriptNewScriptButton_Click(object sender, EventArgs e) + { + BrowseForSaveScriptFile( + "Save New Post-Processing Script", + scriptFilePath => { - scriptTemplateFileName = TEMPLATE_POSTPROCESSING_SCRIPT_FILENAME; - } + var isSaved = SaveNewScript(scriptFilePath, SaveNewScriptType.PostProcessingScript); + + if (isSaved) + postProcessingScriptTextBox.Text = scriptFilePath; + else + ShowErrorMessageBox("ERROR: Failed to Save the new script!"); + }, + ScriptType.Python, + PathUtil.GetExistingFileDirectoryPath(postProcessingScriptTextBox.Text), + NEW_POSTPROCESSING_SCRIPT_FILENAME + ); + } - var scriptTemplateFilePath = Path.Combine(BatchRvt.GetBatchRvtScriptsFolderPath(), scriptTemplateFileName); + private void BrowseForSaveScriptFile( + string dialogTitle, + Action scriptFileAction, + ScriptType scriptType, + string initialDirectory = null, + string initialFileName = null + ) + { + var scriptDefaultExtension = + scriptType == ScriptType.Dynamo ? DYNAMO_SCRIPT_EXTENSION : PYTHON_SCRIPT_EXTENSION; + var scriptFilter = scriptType == ScriptType.Dynamo ? DYNAMO_SCRIPT_FILTER : PYTHON_SCRIPT_FILTER; + + BrowseForSave( + dialogTitle, + scriptFileAction, + scriptDefaultExtension, + scriptFilter, + initialDirectory, + initialFileName + ); + } - var scriptContents = File.ReadAllText(scriptTemplateFilePath); + private bool SaveNewScript(string scriptFilePath, SaveNewScriptType saveNewScriptType) + { + var success = false; - try - { - File.WriteAllText(scriptFilePath, scriptContents); - success = true; - } - catch (Exception) - { - success = false; - } + string scriptTemplateFileName = null; - return success; - } + if (saveNewScriptType == SaveNewScriptType.TaskScript) + scriptTemplateFileName = TEMPLATE_TASK_SCRIPT_FILENAME; + else if (saveNewScriptType == SaveNewScriptType.PreProcessingScript) + scriptTemplateFileName = TEMPLATE_PREPROCESSING_SCRIPT_FILENAME; + else if (saveNewScriptType == SaveNewScriptType.PostProcessingScript) + scriptTemplateFileName = TEMPLATE_POSTPROCESSING_SCRIPT_FILENAME; + + var scriptTemplateFilePath = Path.Combine(BatchRvt.GetBatchRvtScriptsFolderPath(), scriptTemplateFileName); - private void showAdvancedSettingsCheckBox_CheckedChanged(object sender, EventArgs e) + + var scriptContents = File.ReadAllText(scriptTemplateFilePath); + try { - UpdateAdvancedSettings(); + File.WriteAllText(scriptFilePath, scriptContents); + success = true; } + catch (Exception) + { + success = false; + } + + return success; + } - private void UpdateAdvancedSettings() + private void showAdvancedSettingsCheckBox_CheckedChanged(object sender, EventArgs e) + { + UpdateAdvancedSettings(); + } + + private void UpdateAdvancedSettings() + { + var advancedSettingsIsChecked = showAdvancedSettingsCheckBox.Checked; + singleRevitTaskProcessingGroupBox.Visible = advancedSettingsIsChecked; + dataExportGroupBox.Visible = advancedSettingsIsChecked; + showMessageBoxOnTaskScriptErrorCheckBox.Visible = advancedSettingsIsChecked; + preAndPostProcessingGroupBox.Visible = advancedSettingsIsChecked; + + var displaySettingPercentage = GetDisplaySettingPercentage(); + + var minimumWindowHeight = isUsingRunningSize ? RUNNING_MINIMUM_HEIGHT : SETUP_HEIGHT; + + MinimumSize = Scale( + new Size(Scale(SETUP_MINIMUM_WIDTH, displaySettingPercentage), + advancedSettingsIsChecked + ? minimumWindowHeight + : minimumWindowHeight - ADVANCED_SETTINGS_VISIBLE_SIZE_DIFFERENCE), + displaySettingPercentage + ); + + if (isUsingRunningSize) return; + Size = Size with { - var advancedSettingsIsChecked = this.showAdvancedSettingsCheckBox.Checked; - this.singleRevitTaskProcessingGroupBox.Visible = advancedSettingsIsChecked; - this.dataExportGroupBox.Visible = advancedSettingsIsChecked; - this.showMessageBoxOnTaskScriptErrorCheckBox.Visible = advancedSettingsIsChecked; - this.preAndPostProcessingGroupBox.Visible = advancedSettingsIsChecked; + Height = advancedSettingsIsChecked + ? SETUP_HEIGHT + : SETUP_HEIGHT - ADVANCED_SETTINGS_VISIBLE_SIZE_DIFFERENCE + }; + MaximumSize = Scale( + new Size(SETUP_MAXIMUM_WIDTH, + advancedSettingsIsChecked + ? SETUP_HEIGHT + : SETUP_HEIGHT - ADVANCED_SETTINGS_VISIBLE_SIZE_DIFFERENCE), + displaySettingPercentage + ); + } - var displaySettingPercentage = GetDisplaySettingPercentage(); + private void timeOutNumericUpDown_ValueChanged(object sender, EventArgs e) + { + if (!perFileProcessingTimeOutCheckBox.Checked || timeOutNumericUpDown.Value != 0) return; + perFileProcessingTimeOutCheckBox.Checked = false; + UpdateRevitSessionControls(); + } - int minimumWindowHeight = this.isUsingRunningSize ? RUNNING_MINIMUM_HEIGHT : SETUP_HEIGHT; + private void timeOutNumericUpDown_Leave(object sender, EventArgs e) + { + // Detect if the numeric time-out value was left blank and set it to 0. + if (string.IsNullOrWhiteSpace(timeOutNumericUpDown.Controls[1].Text)) timeOutNumericUpDown.Value = 0; + } - this.MinimumSize = Scale( - new System.Drawing.Size(Scale(SETUP_MINIMUM_WIDTH, displaySettingPercentage), advancedSettingsIsChecked ? minimumWindowHeight : minimumWindowHeight - ADVANCED_SETTINGS_VISIBLE_SIZE_DIFFERENCE), - displaySettingPercentage - ); + private void newRevitFileListButton_Click(object sender, EventArgs e) + { + var folderBrowserDialog = new FolderBrowserDialog + { + Site = null, + Tag = null, + ShowNewFolderButton = false, + SelectedPath = "", + RootFolder = Environment.SpecialFolder.MyComputer, + Description = @"Select a folder containing Revit files" + }; - if (!this.isUsingRunningSize) - { - this.Size = new System.Drawing.Size(this.Size.Width, advancedSettingsIsChecked ? SETUP_HEIGHT : SETUP_HEIGHT - ADVANCED_SETTINGS_VISIBLE_SIZE_DIFFERENCE); - this.MaximumSize = Scale( - new System.Drawing.Size(SETUP_MAXIMUM_WIDTH, advancedSettingsIsChecked ? SETUP_HEIGHT : SETUP_HEIGHT - ADVANCED_SETTINGS_VISIBLE_SIZE_DIFFERENCE), - displaySettingPercentage - ); - } - } - private void timeOutNumericUpDown_ValueChanged(object sender, EventArgs e) + var dialogResult = folderBrowserDialog.ShowDialog(this); + + if (dialogResult != DialogResult.OK) return; + + var selectedFolderPath = folderBrowserDialog.SelectedPath; + + if (string.IsNullOrWhiteSpace(selectedFolderPath)) return; + + RevitFileScanning.RevitFileType selectedRevitFileType; + SearchOption selectedSearchOption; + bool expandNetworkPaths; + bool extractRevitVersionInfo; + bool ignoreRevitBackupFiles; + using (var revitFileScanningOptionsUi = new RevitFileScanningOptionsUI()) { - if (this.perFileProcessingTimeOutCheckBox.Checked && this.timeOutNumericUpDown.Value == 0) - { - this.perFileProcessingTimeOutCheckBox.Checked = false; - UpdateRevitSessionControls(); - } + var optionsDialogResult = revitFileScanningOptionsUi.ShowDialog(this); + + if (optionsDialogResult != DialogResult.OK) return; + + selectedRevitFileType = revitFileScanningOptionsUi.GetSelectedRevitFileType(); + + var includeSubfolders = revitFileScanningOptionsUi.IncludeSubfolders(); + + selectedSearchOption = includeSubfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + + expandNetworkPaths = revitFileScanningOptionsUi.ExpandNetworkPaths(); + extractRevitVersionInfo = revitFileScanningOptionsUi.ExtractRevitVersionInfo(); + ignoreRevitBackupFiles = revitFileScanningOptionsUi.IgnoreRevitBackupFiles(); } - private void timeOutNumericUpDown_Leave(object sender, EventArgs e) + var rows = Enumerable.Empty>(); + + void RevitFileScanningProgressReporter(Func progressReporter) { - // Detect if the numeric time-out value was left blank and set it to 0. - if (string.IsNullOrWhiteSpace(this.timeOutNumericUpDown.Controls[1].Text)) - { - this.timeOutNumericUpDown.Value = 0; - } + rows = RevitFileScanning.FindAndExtractRevitFilesInfoWithProgressReporting( + selectedFolderPath, + selectedSearchOption, + selectedRevitFileType, + expandNetworkPaths, + extractRevitVersionInfo, + ignoreRevitBackupFiles, + progressReporter); } - private void newRevitFileListButton_Click(object sender, EventArgs e) + DialogResult scanningDialogResult; + using (var revitFileScanningProgressUi = new RevitFileScanningProgressUI(RevitFileScanningProgressReporter)) { - var folderBrowserDialog = new FolderBrowserDialog(); - - folderBrowserDialog.Description = "Select a folder containing Revit files"; + scanningDialogResult = revitFileScanningProgressUi.ShowDialog(this); + } - // TODO: remember last folder path and assign it to folderBrowserDialog.SelectedPath + if (scanningDialogResult != DialogResult.OK) return; - var dialogResult = folderBrowserDialog.ShowDialog(this); + var initialDirectory = PathUtil.GetExistingFileDirectoryPath(revitFileListTextBox.Text); - if (dialogResult == DialogResult.OK) + BrowseForSave( + "Save New Revit file list", + revitFileListPath => { - var selectedFolderPath = folderBrowserDialog.SelectedPath; + var isSaved = false; - if (!string.IsNullOrWhiteSpace(selectedFolderPath)) + try { - var revitFileScanningOptionsUI = new RevitFileScanningOptionsUI(); - - var optionsDialogResult = revitFileScanningOptionsUI.ShowDialog(this); - - if (optionsDialogResult == DialogResult.OK) - { - var selectedRevitFileType = revitFileScanningOptionsUI.GetSelectedRevitFileType(); - - bool includeSubfolders = revitFileScanningOptionsUI.IncludeSubfolders(); - - var selectedSearchOption = includeSubfolders ? - SearchOption.AllDirectories : - SearchOption.TopDirectoryOnly; - - bool expandNetworkPaths = revitFileScanningOptionsUI.ExpandNetworkPaths(); - bool extractRevitVersionInfo = revitFileScanningOptionsUI.ExtractRevitVersionInfo(); - bool ignoreRevitBackupFiles = revitFileScanningOptionsUI.IgnoreRevitBackupFiles(); - - var rows = Enumerable.Empty>(); - - Action> revitFileScanningProgressReporter = - (progressReporter) => { - rows = RevitFileScanning.FindAndExtractRevitFilesInfoWithProgressReporting( - selectedFolderPath, - selectedSearchOption, - selectedRevitFileType, - expandNetworkPaths, - extractRevitVersionInfo, - ignoreRevitBackupFiles, - progressReporter - ); - }; - - var revitFileScanningProgressUI = new RevitFileScanningProgressUI(revitFileScanningProgressReporter); - - var scanningDialogResult = revitFileScanningProgressUI.ShowDialog(this); - - if (scanningDialogResult == DialogResult.OK) - { - var initialDirectory = PathUtil.GetExistingFileDirectoryPath(this.revitFileListTextBox.Text); - - BrowseForSave( - "Save New Revit file list", - revitFileListPath => { - - bool isSaved = false; - - try - { - TextFileUtil.WriteToTabDelimitedTxtFile(rows, revitFileListPath); - isSaved = true; - } - catch (Exception) - { - isSaved = false; - } - - if (isSaved) - { - this.revitFileListTextBox.Text = revitFileListPath; - } - else - { - ShowErrorMessageBox("ERROR: Failed to Save the new Revit file list!"); - } - }, - TextFileUtil.TEXT_FILE_EXTENSION, - TextFileUtil.TEXT_FILE_FILTER, - initialDirectory, - initialFileName: "revit_file_list.txt" - ); - } - } + TextFileUtil.WriteToTabDelimitedTxtFile(rows, revitFileListPath); + isSaved = true; + } + catch (Exception) + { + isSaved = false; } - } - } - private void discardWorksetsCheckBox_CheckedChanged(object sender, EventArgs e) - { - UpdateCentralFileProcessingControls(); - } + if (isSaved) + revitFileListTextBox.Text = revitFileListPath; + else + ShowErrorMessageBox("ERROR: Failed to Save the new Revit file list!"); + }, + TextFileUtil.TEXT_FILE_EXTENSION, + TextFileUtil.TEXT_FILE_FILTER, + initialDirectory, + "revit_file_list.txt" + ); + } + + private void discardWorksetsCheckBox_CheckedChanged(object sender, EventArgs e) + { + UpdateCentralFileProcessingControls(); + } + + private enum ScriptType + { + Python = 0, + Dynamo = 1, + Any = 2 + } + + private enum SaveNewScriptType + { + TaskScript = 0, + PreProcessingScript = 1, + PostProcessingScript = 2 } -} +} \ No newline at end of file diff --git a/BatchRvtGUI/BatchRvtGuiForm.resx b/BatchRvtGUI/BatchRvtGuiForm.resx index 8bce93c..f816f33 100644 --- a/BatchRvtGUI/BatchRvtGuiForm.resx +++ b/BatchRvtGUI/BatchRvtGuiForm.resx @@ -1,145 +1,153 @@  - - - - - - - + + + + - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - - AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAA - AP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAANgAAACpAAAA7AAAAP0AAACwAAAA4wAAAP8AAADzAAAAowAA - AP4AAADjAAAAqgAAAMgAAAD/AAAA/wAAAP8AAACJAAAAAAAAAFIAAAD/AAAADwAAANsAAADFAAAA/wAA - AAAAAAD7AAAAqAAAAAAAAACyAAAA/wAAAP8AAAD/AAAAlQAAABMAAACJAAAA/AAAABkAAAD/AAAAUAAA - AP8AAAAiAAAA+wAAAKgAAAAbAAAA/wAAAIAAAAD/AAAA/wAAAP8AAAD/AAAA/wAAALYAAABoAAAA/wAA - AAAAAAD2AAAAVwAAAPoAAACoAAAArwAAALwAAABpAAAA/wAAAP8AAAC6AAAAZAAAAOcAAADMAAAA0QAA - AMwAAAAAAAAA2QAAAKkAAADyAAAApgAAAP0AAABEAAAAawAAAP8AAAD/AAAAhQAAAAAAAABvAAAA+wAA - APoAAACNAAAAAAAAAHUAAAD5AAAA7gAAAP0AAADaAAAAAAAAAGcAAAD/AAAA/wAAAM4AAACUAAAA9QAA - AP8AAAD/AAAAvwAAAJUAAACnAAAA/wAAAP8AAAD/AAAAuwAAAJMAAADCAAAA/wAAAP8AAAD/AAAA/wAA - AP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAA//8AAP//AAD//wAAAAAAAAAAAAA0SAAAJUgAAAVCAAAhBgAAMYYAAAAAAAAAAAAA//8AAP// - AAD//wAA//8AAA== - - + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + + + AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAA + AP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAANgAAACpAAAA7AAAAP0AAACwAAAA4wAAAP8AAADzAAAAowAA + AP4AAADjAAAAqgAAAMgAAAD/AAAA/wAAAP8AAACJAAAAAAAAAFIAAAD/AAAADwAAANsAAADFAAAA/wAA + AAAAAAD7AAAAqAAAAAAAAACyAAAA/wAAAP8AAAD/AAAAlQAAABMAAACJAAAA/AAAABkAAAD/AAAAUAAA + AP8AAAAiAAAA+wAAAKgAAAAbAAAA/wAAAIAAAAD/AAAA/wAAAP8AAAD/AAAA/wAAALYAAABoAAAA/wAA + AAAAAAD2AAAAVwAAAPoAAACoAAAArwAAALwAAABpAAAA/wAAAP8AAAC6AAAAZAAAAOcAAADMAAAA0QAA + AMwAAAAAAAAA2QAAAKkAAADyAAAApgAAAP0AAABEAAAAawAAAP8AAAD/AAAAhQAAAAAAAABvAAAA+wAA + APoAAACNAAAAAAAAAHUAAAD5AAAA7gAAAP0AAADaAAAAAAAAAGcAAAD/AAAA/wAAAM4AAACUAAAA9QAA + AP8AAAD/AAAAvwAAAJUAAACnAAAA/wAAAP8AAAD/AAAAuwAAAJMAAADCAAAA/wAAAP8AAAD/AAAA/wAA + AP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAA//8AAP//AAD//wAAAAAAAAAAAAA0SAAAJUgAAAVCAAAhBgAAMYYAAAAAAAAAAAAA//8AAP// + AAD//wAA//8AAA== + + \ No newline at end of file diff --git a/BatchRvtGUI/Program.cs b/BatchRvtGUI/Program.cs index 768f13e..bf87c2f 100644 --- a/BatchRvtGUI/Program.cs +++ b/BatchRvtGUI/Program.cs @@ -17,39 +17,39 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using BatchRvtUtil; -namespace BatchRvtGUI +namespace BatchRvtGUI; + +internal static class Program { - static class Program + /// + /// The main entry point for the application. + /// + [STAThread] + private static void Main() { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); - if (!RevitVersion.GetInstalledRevitVersions().Any()) - { - var errorMessage = new StringBuilder(); - errorMessage.AppendLine("ERROR: Could not detect the BatchRvt addin for any version of Revit installed on this machine!"); - errorMessage.AppendLine(); - errorMessage.AppendLine("You must first install the BatchRvt addin for at least one version of Revit."); + if (!RevitVersion.GetInstalledRevitVersions().Any()) + { + var errorMessage = new StringBuilder(); + errorMessage.AppendLine( + "ERROR: Could not detect the BatchRvt addin for any version of Revit installed on this machine!"); + errorMessage.AppendLine(); + errorMessage.AppendLine("You must first install the BatchRvt addin for at least one version of Revit."); - BatchRvtGuiForm.ShowErrorMessageBox(errorMessage.ToString()); - } - else - { - Application.Run(new BatchRvtGuiForm()); - } + BatchRvtGuiForm.ShowErrorMessageBox(errorMessage.ToString()); + } + else + { + Application.Run(new BatchRvtGuiForm()); } } -} +} \ No newline at end of file diff --git a/BatchRvtGUI/Properties/AssemblyInfo.cs b/BatchRvtGUI/Properties/AssemblyInfo.cs index 44e6c2e..559d0c1 100644 --- a/BatchRvtGUI/Properties/AssemblyInfo.cs +++ b/BatchRvtGUI/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("68c10075-6ee2-4174-bd4b-dd2518229a82")] +[assembly: Guid("68c10075-6ee2-4174-bd4b-dd2518229a82")] \ No newline at end of file diff --git a/BatchRvtGUI/Properties/Resources.Designer.cs b/BatchRvtGUI/Properties/Resources.Designer.cs index 610bafd..6d7218e 100644 --- a/BatchRvtGUI/Properties/Resources.Designer.cs +++ b/BatchRvtGUI/Properties/Resources.Designer.cs @@ -1,7 +1,6 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. diff --git a/BatchRvtGUI/Properties/Resources.resx b/BatchRvtGUI/Properties/Resources.resx index 1af7de1..d4ad6f2 100644 --- a/BatchRvtGUI/Properties/Resources.resx +++ b/BatchRvtGUI/Properties/Resources.resx @@ -1,120 +1,126 @@  - - - - - - - + + + + - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/BatchRvtGUI/Properties/Settings.settings b/BatchRvtGUI/Properties/Settings.settings index 3964565..796d34b 100644 --- a/BatchRvtGUI/Properties/Settings.settings +++ b/BatchRvtGUI/Properties/Settings.settings @@ -1,7 +1,7 @@  - - - - + + + + diff --git a/BatchRvtGUI/RevitFileScanningOptionsUI.cs b/BatchRvtGUI/RevitFileScanningOptionsUI.cs index 066e3bf..8927c24 100644 --- a/BatchRvtGUI/RevitFileScanningOptionsUI.cs +++ b/BatchRvtGUI/RevitFileScanningOptionsUI.cs @@ -17,64 +17,49 @@ // along with this program. If not, see . // // -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + using System.Windows.Forms; using BatchRvtUtil; -namespace BatchRvtGUI +namespace BatchRvtGUI; + +public partial class RevitFileScanningOptionsUI : Form { - public partial class RevitFileScanningOptionsUI : Form + public RevitFileScanningOptionsUI() { - public RevitFileScanningOptionsUI() - { - InitializeComponent(); - } + InitializeComponent(); + } - public RevitFileScanning.RevitFileType GetSelectedRevitFileType() - { - var revitFileType = RevitFileScanning.RevitFileType.Project; + public RevitFileScanning.RevitFileType GetSelectedRevitFileType() + { + var revitFileType = RevitFileScanning.RevitFileType.Project; - if (this.projectFilesRadioButton.Checked) - { - revitFileType = RevitFileScanning.RevitFileType.Project; - } - else if (this.familyFilesRadioButton.Checked) - { - revitFileType = RevitFileScanning.RevitFileType.Family; - } - else if (this.revitFilesRadioButton.Checked) - { - revitFileType = RevitFileScanning.RevitFileType.ProjectAndFamily; - } + if (projectFilesRadioButton.Checked) + revitFileType = RevitFileScanning.RevitFileType.Project; + else if (familyFilesRadioButton.Checked) + revitFileType = RevitFileScanning.RevitFileType.Family; + else if (revitFilesRadioButton.Checked) revitFileType = RevitFileScanning.RevitFileType.ProjectAndFamily; - return revitFileType; - } + return revitFileType; + } - public bool IncludeSubfolders() - { - return this.includeSubfoldersCheckBox.Checked; - } + public bool IncludeSubfolders() + { + return includeSubfoldersCheckBox.Checked; + } - public bool ExpandNetworkPaths() - { - return this.expandNetworkPathsCheckBox.Checked; - } + public bool ExpandNetworkPaths() + { + return expandNetworkPathsCheckBox.Checked; + } - public bool ExtractRevitVersionInfo() - { - return this.detectRevitFileVersionCheckBox.Checked; - } + public bool ExtractRevitVersionInfo() + { + return detectRevitFileVersionCheckBox.Checked; + } - public bool IgnoreRevitBackupFiles() - { - return this.ignoreBackupFilesCheckBox.Checked; - } + public bool IgnoreRevitBackupFiles() + { + return ignoreBackupFilesCheckBox.Checked; } -} +} \ No newline at end of file diff --git a/BatchRvtGUI/RevitFileScanningOptionsUI.resx b/BatchRvtGUI/RevitFileScanningOptionsUI.resx index 1af7de1..d4ad6f2 100644 --- a/BatchRvtGUI/RevitFileScanningOptionsUI.resx +++ b/BatchRvtGUI/RevitFileScanningOptionsUI.resx @@ -1,120 +1,126 @@  - - - - - - - + + + + - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/BatchRvtGUI/RevitFileScanningProgressUI.cs b/BatchRvtGUI/RevitFileScanningProgressUI.cs index 63a326e..06003ea 100644 --- a/BatchRvtGUI/RevitFileScanningProgressUI.cs +++ b/BatchRvtGUI/RevitFileScanningProgressUI.cs @@ -17,127 +17,111 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; -namespace BatchRvtGUI +namespace BatchRvtGUI; + +public partial class RevitFileScanningProgressUI : Form { - public partial class RevitFileScanningProgressUI : Form + private readonly Action> actionWithProgressReporting_; + private BackgroundWorker backgroundWorker_; + private string currentProgressMessage_ = string.Empty; + private Timer progressUpdateTimer_; + private bool scanningCancelled_; + private bool scanningCompleted_; + + public RevitFileScanningProgressUI(Action> actionWithProgressReporting) { - Action> actionWithProgressReporting_ = null; - BackgroundWorker backgroundWorker_ = null; - bool scanningCancelled_ = false; - bool scanningCompleted_ = false; - string currentProgressMessage_ = string.Empty; - Timer progressUpdateTimer_ = null; - - public RevitFileScanningProgressUI(Action> actionWithProgressReporting) - { - InitializeComponent(); - - this.actionWithProgressReporting_ = actionWithProgressReporting; - } + InitializeComponent(); - private void RevitFileScanningProgressUI_Load(object sender, EventArgs e) - { - this.backgroundWorker_ = new BackgroundWorker(); - this.backgroundWorker_.DoWork += BackgroundWorker__DoWork; - this.backgroundWorker_.ProgressChanged += BackgroundWorker__ProgressChanged; - this.backgroundWorker_.RunWorkerCompleted += BackgroundWorker__RunWorkerCompleted; - this.backgroundWorker_.WorkerReportsProgress = true; - this.backgroundWorker_.RunWorkerAsync(); - - this.progressUpdateTimer_ = new Timer(); - this.progressUpdateTimer_.Interval = 50; - this.progressUpdateTimer_.Tick += ProgressUpdateTimer__Tick; - - this.progressUpdateTimer_.Start(); - } + actionWithProgressReporting_ = actionWithProgressReporting; + } - private void ProgressUpdateTimer__Tick(object sender, EventArgs e) - { - this.progressLabel.Text = this.currentProgressMessage_; - } + private void RevitFileScanningProgressUI_Load(object sender, EventArgs e) + { + backgroundWorker_ = new BackgroundWorker(); + backgroundWorker_.DoWork += BackgroundWorker__DoWork; + backgroundWorker_.ProgressChanged += BackgroundWorker__ProgressChanged; + backgroundWorker_.RunWorkerCompleted += BackgroundWorker__RunWorkerCompleted; + backgroundWorker_.WorkerReportsProgress = true; + backgroundWorker_.RunWorkerAsync(); + + /*progressUpdateTimer_ = new Timer(); + progressUpdateTimer_.Interval = 50; + progressUpdateTimer_.Tick += ProgressUpdateTimer__Tick; + + progressUpdateTimer_.Start();*/ + } - private void BackgroundWorker__RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) - { - // TODO: determine if the work was cancelled or terminated due to an error - // and return an appropriate dialog result. - if (!scanningCancelled_) - { - this.scanningCompleted_ = true; - this.DialogResult = DialogResult.OK; - } - } - private void BackgroundWorker__ProgressChanged(object sender, ProgressChangedEventArgs e) - { - var progressMessage = e.UserState as string; + /*private void ProgressUpdateTimer__Tick(object sender, EventArgs e) + { + progressLabel.Text = currentProgressMessage_; + }*/ - this.currentProgressMessage_ = progressMessage; - } + private void BackgroundWorker__RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + { + // TODO: determine if the work was cancelled or terminated due to an error + // and return an appropriate dialog result. + if (scanningCancelled_) return; + scanningCompleted_ = true; + DialogResult = DialogResult.OK; + } - private void BackgroundWorker__DoWork(object sender, DoWorkEventArgs e) - { - Func progressReporter = (progressMessage) => { - this.backgroundWorker_.ReportProgress(0, progressMessage); - return this.scanningCancelled_; - }; + private void BackgroundWorker__ProgressChanged(object sender, ProgressChangedEventArgs e) + { + var progressMessage = e.UserState as string; - actionWithProgressReporting_(progressReporter); - } + currentProgressMessage_ = progressMessage; + ////Test + progressLabel.Text = currentProgressMessage_; + } - private void cancelButton_Click(object sender, EventArgs e) + private void BackgroundWorker__DoWork(object sender, DoWorkEventArgs e) + { + bool ProgressReporter(string progressMessage) { - CancelWithConfirmationPrompt(); + backgroundWorker_.ReportProgress(0, progressMessage); + return scanningCancelled_; } - private void CancelWithConfirmationPrompt() - { - var dialogResult = MessageBox.Show( - this, - "Are you sure you want to cancel the scan?", - string.Empty, - MessageBoxButtons.YesNo, - MessageBoxIcon.Asterisk, - MessageBoxDefaultButton.Button2 - ); - - if (dialogResult == DialogResult.Yes) - { - // TODO: stop the scanning operation? - this.scanningCancelled_ = true; - this.DialogResult = DialogResult.Cancel; - } - } + actionWithProgressReporting_(ProgressReporter); + } - private void RevitFileScanningProgressUI_FormClosing(object sender, FormClosingEventArgs e) - { - if (e.CloseReason == CloseReason.UserClosing) - { - if (!this.scanningCompleted_ && !this.scanningCancelled_) - { - // NOTE: this scenario occurs when the user closes the progress window using Alt+F4. - CancelWithConfirmationPrompt(); - - if (!this.scanningCancelled_) - { - e.Cancel = true; - } - } - } - - if (!e.Cancel) - { - this.progressUpdateTimer_.Stop(); - } - } + private void cancelButton_Click(object sender, EventArgs e) + { + CancelWithConfirmationPrompt(); + } + + private void CancelWithConfirmationPrompt() + { + var dialogResult = MessageBox.Show( + this, + @"Are you sure you want to cancel the scan?", + string.Empty, + MessageBoxButtons.YesNo, + MessageBoxIcon.Asterisk, + MessageBoxDefaultButton.Button2 + ); + + if (dialogResult != DialogResult.Yes) return; + // TODO: stop the scanning operation? + scanningCancelled_ = true; + DialogResult = DialogResult.Cancel; + } + + private void RevitFileScanningProgressUI_FormClosing(object sender, FormClosingEventArgs e) + { + if (e.CloseReason != CloseReason.UserClosing) return; + if (scanningCompleted_ || scanningCancelled_) return; + // NOTE: this scenario occurs when the user closes the progress window using Alt+F4. + CancelWithConfirmationPrompt(); + + if (!scanningCancelled_) e.Cancel = true; + + //if (!e.Cancel) progressUpdateTimer_.Stop(); } -} +} \ No newline at end of file diff --git a/BatchRvtGUI/RevitFileScanningProgressUI.resx b/BatchRvtGUI/RevitFileScanningProgressUI.resx index 1af7de1..d4ad6f2 100644 --- a/BatchRvtGUI/RevitFileScanningProgressUI.resx +++ b/BatchRvtGUI/RevitFileScanningProgressUI.resx @@ -1,120 +1,126 @@  - - - - - - - + + + + - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/BatchRvtGUI/packages.config b/BatchRvtGUI/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtGUI/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtScriptHost/App.config b/BatchRvtScriptHost/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtScriptHost/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtScriptHost/BatchRvtScriptHost.csproj b/BatchRvtScriptHost/BatchRvtScriptHost.csproj index 4f26cb6..9f80d73 100644 --- a/BatchRvtScriptHost/BatchRvtScriptHost.csproj +++ b/BatchRvtScriptHost/BatchRvtScriptHost.csproj @@ -1,84 +1,155 @@  - - - Debug - AnyCPU - {673D1FB5-CFB2-4BDF-9609-C43979DD7197} - Library - Properties - BatchRvt.ScriptHost - BatchRvtScriptHost - v4.8 - 512 - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - True - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - True - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - True - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - - - - - - + + + + Debug + AnyCPU + {673D1FB5-CFB2-4BDF-9609-C43979DD7197} + Library + Properties + BatchRvt.ScriptHost + BatchRvtScriptHost + v4.8 + 512 + latestmajor + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + True + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + True + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + True + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/BatchRvtScriptHost/Properties/AssemblyInfo.cs b/BatchRvtScriptHost/Properties/AssemblyInfo.cs index 64add6d..ec3e3b9 100644 --- a/BatchRvtScriptHost/Properties/AssemblyInfo.cs +++ b/BatchRvtScriptHost/Properties/AssemblyInfo.cs @@ -17,8 +17,8 @@ // along with this program. If not, see . // // + using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -39,4 +39,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("94ab4ba7-5cc2-40bc-9443-29026730d65f")] +[assembly: Guid("94ab4ba7-5cc2-40bc-9443-29026730d65f")] \ No newline at end of file diff --git a/BatchRvtScriptHost/Util/ScriptHostUtil.cs b/BatchRvtScriptHost/Util/ScriptHostUtil.cs index 38f1804..7686fa3 100644 --- a/BatchRvtScriptHost/Util/ScriptHostUtil.cs +++ b/BatchRvtScriptHost/Util/ScriptHostUtil.cs @@ -17,115 +17,109 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; using System.Collections.Specialized; -using System.Linq; - -using System.IO; using System.Diagnostics; +using System.IO; + +namespace BatchRvt.ScriptHost; -namespace BatchRvt.ScriptHost +public static class ScriptHostUtil { - public static class ScriptHostUtil + // NOTE: must be the same as BATCH_RVT_ERROR_WINDOW_TITLE defined in script_host_error.py. + public const string BATCH_RVT_ERROR_WINDOW_TITLE = "BatchRvt Script Error"; + + private const string BatchScriptHostFilename = "revit_script_host.py"; + private const string BATCHRVT_SCRIPTS_FOLDER_PATH__ENVIRONMENT_VARIABLE_NAME = "BATCHRVT__SCRIPTS_FOLDER_PATH"; + + public static void ExecuteBatchScriptHost( + string pluginFolderPath, + object uiApplicationObject + ) { - // NOTE: must be the same as BATCH_RVT_ERROR_WINDOW_TITLE defined in script_host_error.py. - public const string BATCH_RVT_ERROR_WINDOW_TITLE = "BatchRvt Script Error"; + var environmentVariables = GetEnvironmentVariables(); - private const string BatchScriptHostFilename = "revit_script_host.py"; - private const string BATCHRVT_SCRIPTS_FOLDER_PATH__ENVIRONMENT_VARIABLE_NAME = "BATCHRVT__SCRIPTS_FOLDER_PATH"; + if (environmentVariables == null) return; + var batchRvtScriptsFolderPath = GetBatchRvtScriptsFolderPath(environmentVariables); - public static void ExecuteBatchScriptHost( - string pluginFolderPath, - object uiApplicationObject - ) - { - var environmentVariables = GetEnvironmentVariables(); + if (batchRvtScriptsFolderPath == null) return; + var engine = ScriptUtil.CreatePythonEngine(); - if (environmentVariables != null) + ScriptUtil.AddBuiltinVariables( + engine, + new Dictionary { - var batchRvtScriptsFolderPath = GetBatchRvtScriptsFolderPath(environmentVariables); + { "__revit__", uiApplicationObject } + }); - if (batchRvtScriptsFolderPath != null) - { - var engine = ScriptUtil.CreatePythonEngine(); + var mainModuleScope = ScriptUtil.CreateMainModule(engine); - ScriptUtil.AddBuiltinVariables( - engine, - new Dictionary { - { "__revit__", uiApplicationObject }, - }); + var pluginFullFolderPath = Path.GetFullPath(pluginFolderPath); + var scriptHostFilePath = Path.Combine(batchRvtScriptsFolderPath, BatchScriptHostFilename); + var batchRvtFolderPath = GetBatchRvtFolderPath(environmentVariables); - var mainModuleScope = ScriptUtil.CreateMainModule(engine); + ScriptUtil.AddSearchPaths(engine, new[] + { + batchRvtScriptsFolderPath, + pluginFullFolderPath, + batchRvtFolderPath + }); - var pluginFullFolderPath = Path.GetFullPath(pluginFolderPath); - var scriptHostFilePath = Path.Combine(batchRvtScriptsFolderPath, BatchScriptHostFilename); - var batchRvtFolderPath = GetBatchRvtFolderPath(environmentVariables); + ScriptUtil.AddPythonStandardLibrary(mainModuleScope); - ScriptUtil.AddSearchPaths(engine, new[] { - batchRvtScriptsFolderPath, - pluginFullFolderPath, - batchRvtFolderPath - }); + var scriptSource = ScriptUtil.CreateScriptSourceFromFile(engine, scriptHostFilePath); - ScriptUtil.AddPythonStandardLibrary(mainModuleScope); + scriptSource.Execute(mainModuleScope); + } - var scriptSource = ScriptUtil.CreateScriptSourceFromFile(engine, scriptHostFilePath); + private static string GetParentFolder(string folderPath) + { + return Directory.GetParent(folderPath)?.FullName; + } - scriptSource.Execute(mainModuleScope); - } + private static string RemoveTrailingDirectorySeparators(string folderPath) + { + return folderPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + } - return; - } - } + private static string GetBatchRvtFolderPath(StringDictionary environmentVariables) + { + var batchRvtScriptsFolderPath = GetBatchRvtScriptsFolderPath(environmentVariables); - private static string GetParentFolder(string folderPath) - { - return Directory.GetParent((folderPath)).FullName; - } + return batchRvtScriptsFolderPath != null + ? GetParentFolder(RemoveTrailingDirectorySeparators(batchRvtScriptsFolderPath)) + : null; + } - private static string RemoveTrailingDirectorySeparators(string folderPath) - { - return folderPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - } + private static string GetBatchRvtScriptsFolderPath(StringDictionary environmentVariables) + { + return GetEnvironmentVariable( + environmentVariables, + BATCHRVT_SCRIPTS_FOLDER_PATH__ENVIRONMENT_VARIABLE_NAME + ); + } - public static string GetBatchRvtFolderPath(StringDictionary environmentVariables) - { - var batchRvtScriptsFolderPath = GetBatchRvtScriptsFolderPath(environmentVariables); + private static string GetEnvironmentVariable(StringDictionary environmentVariables, string variableName) + { + return environmentVariables[variableName]; + } - return (batchRvtScriptsFolderPath != null) ? - GetParentFolder(RemoveTrailingDirectorySeparators(batchRvtScriptsFolderPath)) : - null; - } + private static StringDictionary GetEnvironmentVariables() + { + StringDictionary environmentVariables = null; - public static string GetBatchRvtScriptsFolderPath(StringDictionary environmentVariables) + // NOTE: Have encountered (at least once) a NullReferenceException upon accessing the EnvironmentVariables property! + try { - return GetEnvironmentVariable( - environmentVariables, - BATCHRVT_SCRIPTS_FOLDER_PATH__ENVIRONMENT_VARIABLE_NAME - ); + environmentVariables = Process.GetCurrentProcess().StartInfo.EnvironmentVariables; } - - private static string GetEnvironmentVariable(StringDictionary environmentVariables, string variableName) + catch (NullReferenceException e) { - return environmentVariables[variableName]; + environmentVariables = null; } - public static StringDictionary GetEnvironmentVariables() - { - StringDictionary environmentVariables = null; - - // NOTE: Have encountered (at least once) a NullReferenceException upon accessing the EnvironmentVariables property! - try - { - environmentVariables = Process.GetCurrentProcess().StartInfo.EnvironmentVariables; - } - catch (NullReferenceException e) - { - environmentVariables = null; - } - - return environmentVariables; - } + return environmentVariables; } -} +} \ No newline at end of file diff --git a/BatchRvtScriptHost/Util/ScriptUtil.cs b/BatchRvtScriptHost/Util/ScriptUtil.cs index 6eec8b9..9b9669c 100644 --- a/BatchRvtScriptHost/Util/ScriptUtil.cs +++ b/BatchRvtScriptHost/Util/ScriptUtil.cs @@ -17,89 +17,82 @@ // along with this program. If not, see . // // -using System; + using System.Collections.Generic; using System.Linq; - +using BatchRvt.ScriptHost.Util; +using IronPython.Modules; using MSScripting = Microsoft.Scripting; using ScriptingHosting = Microsoft.Scripting.Hosting; using IronPythonHosting = IronPython.Hosting; -namespace BatchRvt.ScriptHost -{ - public static class ScriptUtil - { - private const string PYTHON_LIB_ZIP_NAME = "python_27_lib.zip"; - - public static void AddPythonStandardLibrary(ScriptingHosting.ScriptScope scope) - { - var thisAssembly = typeof(ScriptUtil).Assembly; - var pythonLibResourceName = thisAssembly.GetManifestResourceNames() - .Single(name => name.ToLowerInvariant().EndsWith(PYTHON_LIB_ZIP_NAME.ToLowerInvariant())); - var importer = new IronPython.Modules.ResourceMetaPathImporter(thisAssembly, pythonLibResourceName); - dynamic sysModule = IronPython.Hosting.Python.GetSysModule(scope.Engine); - sysModule.meta_path.append(importer); - - return; - } +namespace BatchRvt.ScriptHost; - public static void AddVariables(ScriptingHosting.ScriptScope scope, IEnumerable> variables) - { - foreach (var kv in variables) - { - scope.SetVariable(kv.Key, kv.Value); - } +public static class ScriptUtil +{ + private const string PYTHON_LIB_ZIP_NAME = "python_27_lib.zip"; - return; - } + public static void AddPythonStandardLibrary(ScriptingHosting.ScriptScope scope) + { + var thisAssembly = typeof(ScriptUtil).Assembly; + var pythonLibResourceName = thisAssembly.GetManifestResourceNames() + .Single(name => name.ToLowerInvariant().EndsWith(PYTHON_LIB_ZIP_NAME.ToLowerInvariant())); + var importer = new ResourceMetaPathImporter(thisAssembly, pythonLibResourceName); + dynamic sysModule = IronPythonHosting.Python.GetSysModule(scope.Engine); + sysModule.meta_path.append(importer); + } - public static void AddBuiltinVariables(ScriptingHosting.ScriptEngine engine, IEnumerable> variables) - { - AddVariables(IronPythonHosting.Python.GetBuiltinModule(engine), variables); + private static void AddVariables(ScriptingHosting.ScriptScope scope, + IEnumerable> variables) + { + foreach (var kv in variables) scope.SetVariable(kv.Key, kv.Value); + } - return; - } + public static void AddBuiltinVariables(ScriptingHosting.ScriptEngine engine, + IEnumerable> variables) + { + AddVariables(IronPythonHosting.Python.GetBuiltinModule(engine), variables); + } - public static void AddSearchPaths(ScriptingHosting.ScriptEngine engine, IEnumerable additionalSearchPaths) - { - var searchPaths = engine.GetSearchPaths(); + public static void AddSearchPaths(ScriptingHosting.ScriptEngine engine, + IEnumerable additionalSearchPaths) + { + var searchPaths = engine.GetSearchPaths(); - foreach (var path in additionalSearchPaths) - { - searchPaths.Add(path); - } + foreach (var path in additionalSearchPaths) searchPaths.Add(path); - engine.SetSearchPaths(searchPaths); - } + engine.SetSearchPaths(searchPaths); + } - public static ScriptingHosting.ScriptEngine CreatePythonEngine() + public static ScriptingHosting.ScriptEngine CreatePythonEngine() + { + var engineOptions = new Dictionary { - var engineOptions = new Dictionary { - { "FullFrames", true }, - /*{ "Debug", true },*/ - }; + { "FullFrames", true } + /*{ "Debug", true },*/ + }; - var engine = IronPythonHosting.Python.CreateEngine(engineOptions); + var engine = IronPythonHosting.Python.CreateEngine(engineOptions); - return engine; - } + return engine; + } - public static ScriptingHosting.ScriptScope CreateMainModule(ScriptingHosting.ScriptEngine engine) - { - var mainModuleScope = IronPythonHosting.Python.CreateModule(engine, "__main__"); + public static ScriptingHosting.ScriptScope CreateMainModule(ScriptingHosting.ScriptEngine engine) + { + var mainModuleScope = IronPythonHosting.Python.CreateModule(engine, "__main__"); - return mainModuleScope; - } + return mainModuleScope; + } - public static ScriptingHosting.ScriptSource CreateScriptSourceFromFile( - ScriptingHosting.ScriptEngine engine, string sourceFilePath - ) - { - var sourceText = TextFileUtil.ReadAllText(sourceFilePath); + public static ScriptingHosting.ScriptSource CreateScriptSourceFromFile( + ScriptingHosting.ScriptEngine engine, string sourceFilePath + ) + { + var sourceText = TextFileUtil.ReadAllText(sourceFilePath); - var scriptSource = engine.CreateScriptSourceFromString(sourceText, sourceFilePath, MSScripting.SourceCodeKind.Statements); + var scriptSource = + engine.CreateScriptSourceFromString(sourceText, sourceFilePath, MSScripting.SourceCodeKind.Statements); - return scriptSource; - } + return scriptSource; } -} +} \ No newline at end of file diff --git a/BatchRvtScriptHost/Util/TextFileUtil.cs b/BatchRvtScriptHost/Util/TextFileUtil.cs index 95437a0..7f1f3b4 100644 --- a/BatchRvtScriptHost/Util/TextFileUtil.cs +++ b/BatchRvtScriptHost/Util/TextFileUtil.cs @@ -17,42 +17,17 @@ // along with this program. If not, see . // // -using System; -using System.Collections.Generic; -using System.Linq; + using System.IO; -namespace BatchRvt.ScriptHost +namespace BatchRvt.ScriptHost.Util; + +public static class TextFileUtil { - public static class TextFileUtil + public static string ReadAllText(string textFilePath) { - public static string ReadAllText(string textFilePath) - { - var text = string.Empty; - - var fileStream = new FileStream(textFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - - try - { - var textReader = new StreamReader(fileStream); - - try - { - text = textReader.ReadToEnd(); - } - finally - { - textReader.Close(); - textReader.Dispose(); - } - } - finally - { - fileStream.Close(); - fileStream.Dispose(); - } - - return text; - } + using var fileStream = new FileStream(textFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var textReader = new StreamReader(fileStream); + return textReader.ReadToEnd(); } -} +} \ No newline at end of file diff --git a/BatchRvtScriptHost/packages.config b/BatchRvtScriptHost/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtScriptHost/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtUtil.Tests/BatchRvtTests.cs b/BatchRvtUtil.Tests/BatchRvtTests.cs new file mode 100644 index 0000000..0973e87 --- /dev/null +++ b/BatchRvtUtil.Tests/BatchRvtTests.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using BatchRvtUtil; +using Xunit; + + +namespace BatchRvtUtil.Tests +{ + public class BatchRvtTests + { + + [Fact] + public void ConstructCommandLineArguments_ShouldReturnArguments() + { + IEnumerable> arguments = new List>(){ new( + "test1", "test2")}; + var result = BatchRvt.ConstructCommandLineArguments(arguments); + Assert.Equal(string.Join(" ", "--" + "test1" + " " + "test2"), result); + + } + + [Theory] + [InlineData(null)] + public void ConstructCommandLineArguments_ShouldFail(List> arguments) + { + Assert.Throws(() => BatchRvt.ConstructCommandLineArguments(arguments)); + } + + [Theory] + [InlineData("16:30:13")] + [InlineData("16:30:13")] + public void IsBatchRvtLine_ShouldReturnTrueOnCorrectLine(string line) + { + Assert.True(BatchRvt.IsBatchRvtLine(line)); + } + + [Theory] + [InlineData("x:x:x")] + [InlineData("")] + + public void IsBatchRvtLine_ShouldReturnFalseOnIncorrectLine(string line) + { + Assert.False(BatchRvt.IsBatchRvtLine(line)); + } + [Theory] + [InlineData(null)] + public void IsBatchRvtLine_ShouldReturnExceptionOnNullArgument(string line) + { + Assert.Throws(() => BatchRvt.IsBatchRvtLine(line)); + } + } +} \ No newline at end of file diff --git a/BatchRvtUtil.Tests/BatchRvtUtil.Tests.csproj b/BatchRvtUtil.Tests/BatchRvtUtil.Tests.csproj new file mode 100644 index 0000000..7e1fa01 --- /dev/null +++ b/BatchRvtUtil.Tests/BatchRvtUtil.Tests.csproj @@ -0,0 +1,87 @@ + + + + + + Debug + AnyCPU + {BFD3D072-42A4-4B86-B225-73139D6C95D9} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + Library + Properties + BatchRvtUtilTests + BatchRvtUtil.Tests + v4.8 + 512 + default + + + + + x64 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + x64 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.7.0\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.7.0\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.7.0\lib\net452\xunit.execution.desktop.dll + + + + + + + + + {b880dd15-184b-4ce2-86fc-08bac05e0271} + BatchRvtUtil + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + \ No newline at end of file diff --git a/BatchRvtUtil.Tests/Properties/AssemblyInfo.cs b/BatchRvtUtil.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6f19d42 --- /dev/null +++ b/BatchRvtUtil.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("BatchRvtUtil.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("BatchRvtUtil.Tests")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("BFD3D072-42A4-4B86-B225-73139D6C95D9")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/BatchRvtUtil.Tests/app.config b/BatchRvtUtil.Tests/app.config new file mode 100644 index 0000000..8d5ec5f --- /dev/null +++ b/BatchRvtUtil.Tests/app.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtUtil.Tests/packages.config b/BatchRvtUtil.Tests/packages.config new file mode 100644 index 0000000..7e8ca86 --- /dev/null +++ b/BatchRvtUtil.Tests/packages.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtUtil/App.config b/BatchRvtUtil/App.config new file mode 100644 index 0000000..e9196ce --- /dev/null +++ b/BatchRvtUtil/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BatchRvtUtil/BatchRvt.cs b/BatchRvtUtil/BatchRvt.cs index e8e8004..68ab544 100644 --- a/BatchRvtUtil/BatchRvt.cs +++ b/BatchRvtUtil/BatchRvt.cs @@ -17,185 +17,217 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; -using System.Linq; using System.Diagnostics; -using System.Threading.Tasks; -using System.IO; using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; using BatchRvt.ScriptHost; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class BatchRvt { - public static class BatchRvt + public enum CentralFileOpenOption { - public const string SCRIPTS_FOLDER_NAME = "Scripts"; + Detach = 0, + CreateNewLocal = 1 + } - public enum CentralFileOpenOption { Detach = 0, CreateNewLocal = 1 } - public enum RevitSessionOption { UseSeparateSessionPerFile = 0, UseSameSessionForFilesOfSameVersion = 1 } - public enum RevitProcessingOption { BatchRevitFileProcessing = 0, SingleRevitTaskProcessing = 1 } - public enum RevitFileProcessingOption { UseFileRevitVersionIfAvailable = 0, UseSpecificRevitVersion = 1 } - public enum WorksetConfigurationOption { CloseAllWorksets = 0, OpenAllWorksets = 1, OpenLastViewed = 2 } + public enum RevitFileProcessingOption + { + UseFileRevitVersionIfAvailable = 0, + UseSpecificRevitVersion = 1 + } - private const string SCRIPT_DATA_FOLDER_NAME = "BatchRvt"; + public enum RevitProcessingOption + { + BatchRevitFileProcessing = 0, + SingleRevitTaskProcessing = 1 + } - private const string MONITOR_SCRIPT_FILE_NAME = "batch_rvt.py"; + public enum RevitSessionOption + { + UseSeparateSessionPerFile = 0, + UseSameSessionForFilesOfSameVersion = 1 + } - private static readonly Dictionary BATCHRVT_ADDIN_FILENAMES = - new Dictionary() - { - { RevitVersion.SupportedRevitVersion.Revit2015, "BatchRvtAddin2015.addin" }, - { RevitVersion.SupportedRevitVersion.Revit2016, "BatchRvtAddin2016.addin" }, - { RevitVersion.SupportedRevitVersion.Revit2017, "BatchRvtAddin2017.addin" }, - { RevitVersion.SupportedRevitVersion.Revit2018, "BatchRvtAddin2018.addin" }, - { RevitVersion.SupportedRevitVersion.Revit2019, "BatchRvtAddin2019.addin" }, - { RevitVersion.SupportedRevitVersion.Revit2020, "BatchRvtAddin2020.addin" }, - { RevitVersion.SupportedRevitVersion.Revit2021, "BatchRvtAddin2021.addin" }, - { RevitVersion.SupportedRevitVersion.Revit2022, "BatchRvtAddin2022.addin" }, - { RevitVersion.SupportedRevitVersion.Revit2023, "BatchRvtAddin2023.addin" } - }; - - private static string ConstructCommandLineArguments(IEnumerable> arguments) - { - return string.Join(" ", arguments.Select(arg => "--" + arg.Key + " " + arg.Value)); - } - public static bool IsBatchRvtLine(string line) + private static readonly Dictionary BATCHRVT_ADDIN_FILENAMES = + new Dictionary() { - var parts = line.Split(); + { RevitVersion.SupportedRevitVersion.Revit2015, "BatchRvtAddin2015.addin" }, + { RevitVersion.SupportedRevitVersion.Revit2016, "BatchRvtAddin2016.addin" }, + { RevitVersion.SupportedRevitVersion.Revit2017, "BatchRvtAddin2017.addin" }, + { RevitVersion.SupportedRevitVersion.Revit2018, "BatchRvtAddin2018.addin" }, + { RevitVersion.SupportedRevitVersion.Revit2019, "BatchRvtAddin2019.addin" }, + { RevitVersion.SupportedRevitVersion.Revit2020, "BatchRvtAddin2020.addin" }, + { RevitVersion.SupportedRevitVersion.Revit2021, "BatchRvtAddin2021.addin" }, + { RevitVersion.SupportedRevitVersion.Revit2022, "BatchRvtAddin2022.addin" }, + { RevitVersion.SupportedRevitVersion.Revit2023, "BatchRvtAddin2023.addin" }, + { RevitVersion.SupportedRevitVersion.Revit2024, "BatchRvtAddin2024.addin" } + }; - var timeSpan = default(TimeSpan); - var success = TimeSpan.TryParseExact(parts.First(), @"hh\:mm\:ss", CultureInfo.InvariantCulture, out timeSpan); - return success; - } + public enum WorksetConfigurationOption + { + CloseAllWorksets = 0, + OpenAllWorksets = 1, + OpenLastViewed = 2 + } - public static Process StartBatchRvt( - string settingsFilePath, - string logFolderPath = null, - string sessionId = null, - string taskData = null, - string testModeFolderPath = null - ) - { - var baseDirectory = GetBatchRvtFolderPath(); + private const string SCRIPTS_FOLDER_NAME = "Scripts"; - var batchRvtOptions = new Dictionary() { - { CommandSettings.SETTINGS_FILE_PATH_OPTION, settingsFilePath }, - }; + private const string SCRIPT_DATA_FOLDER_NAME = "BatchRvt"; - if (!string.IsNullOrWhiteSpace(logFolderPath)) - { - batchRvtOptions[CommandSettings.LOG_FOLDER_PATH_OPTION] = logFolderPath; - } + private const string MONITOR_SCRIPT_FILE_NAME = "batch_rvt.py"; - if (!string.IsNullOrWhiteSpace(sessionId)) - { - batchRvtOptions[CommandSettings.SESSION_ID_OPTION] = sessionId; - } - if (!string.IsNullOrWhiteSpace(taskData)) - { - batchRvtOptions[CommandSettings.TASK_DATA_OPTION] = taskData; - } + public static string ConstructCommandLineArguments(IEnumerable> commandLineArguments) + { + if (commandLineArguments is null or not IEnumerable>) + { + throw new ArgumentException("You passed a wrong argument"); + } + return string.Join(" ", commandLineArguments.Select(arg => "--" + arg.Key + " " + arg.Value)); + } - if (!string.IsNullOrWhiteSpace(testModeFolderPath)) - { - batchRvtOptions[CommandSettings.TEST_MODE_FOLDER_PATH_OPTION] = testModeFolderPath; - } + public static bool IsBatchRvtLine(string line) + { + if (line is null) + { + throw new ArgumentException("Argument can't be null"); + } + var parts = line.Split(); - var psi = new ProcessStartInfo(Path.Combine(baseDirectory, "BatchRvt.exe")); - - psi.UseShellExecute = false; - psi.WorkingDirectory = baseDirectory; - psi.Arguments = ConstructCommandLineArguments(batchRvtOptions); - psi.RedirectStandardInput = false; - psi.RedirectStandardOutput = true; - psi.RedirectStandardError = true; - psi.CreateNoWindow = true; + var success = + TimeSpan.TryParseExact(parts.First(), @"hh\:mm\:ss", CultureInfo.InvariantCulture, out _); - var batchRvtProcess = Process.Start(psi); + return success; + } - return batchRvtProcess; - } + public static Process StartBatchRvt( + string settingsFilePath, + string logFolderPath = null, + string sessionId = null, + string taskData = null, + string testModeFolderPath = null + ) + { + var baseDirectory = GetBatchRvtFolderPath(); - public static void ExecuteMonitorScript( - string batchRvtFolderPath, - CommandSettings.Data commandSettingsData = null - ) + var batchRvtOptions = SetBatchRvtOptions(settingsFilePath, logFolderPath, sessionId, taskData, testModeFolderPath); + + var psi = new ProcessStartInfo(Path.Combine(baseDirectory, "BatchRvt.exe")) + { + UseShellExecute = false, + WorkingDirectory = baseDirectory, + Arguments = ConstructCommandLineArguments(batchRvtOptions), + RedirectStandardInput = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; + if (psi == null) throw new ArgumentNullException(nameof(psi)); + + var batchRvtProcess = Process.Start(psi); + + return batchRvtProcess; + } + + private static Dictionary SetBatchRvtOptions(string settingsFilePath, string logFolderPath, string sessionId, + string taskData, string testModeFolderPath) + { + var batchRvtOptions = new Dictionary { - var engine = ScriptUtil.CreatePythonEngine(); + { CommandSettings.SETTINGS_FILE_PATH_OPTION, settingsFilePath } + }; - var mainModuleScope = ScriptUtil.CreateMainModule(engine); + if (!string.IsNullOrWhiteSpace(logFolderPath)) + batchRvtOptions[CommandSettings.LOG_FOLDER_PATH_OPTION] = logFolderPath; - var scriptsFolderPath = Path.Combine(batchRvtFolderPath, SCRIPTS_FOLDER_NAME); + if (!string.IsNullOrWhiteSpace(sessionId)) batchRvtOptions[CommandSettings.SESSION_ID_OPTION] = sessionId; - var monitorScriptFilePath = Path.Combine( - scriptsFolderPath, - MONITOR_SCRIPT_FILE_NAME - ); + if (!string.IsNullOrWhiteSpace(taskData)) batchRvtOptions[CommandSettings.TASK_DATA_OPTION] = taskData; - ScriptUtil.AddSearchPaths( - engine, - new[] { - scriptsFolderPath, - batchRvtFolderPath - } - ); + if (!string.IsNullOrWhiteSpace(testModeFolderPath)) + batchRvtOptions[CommandSettings.TEST_MODE_FOLDER_PATH_OPTION] = testModeFolderPath; + return batchRvtOptions; + } - ScriptUtil.AddBuiltinVariables( - engine, - new Dictionary { - { "__scope__", mainModuleScope }, - { "__command_settings_data__", commandSettingsData } - } - ); + public static void ExecuteMonitorScript( + string batchRvtFolderPath, + CommandSettings.Data commandSettingsData = null + ) + { + var engine = ScriptUtil.CreatePythonEngine(); - ScriptUtil.AddPythonStandardLibrary(mainModuleScope); + var mainModuleScope = ScriptUtil.CreateMainModule(engine); - var scriptSource = ScriptUtil.CreateScriptSourceFromFile(engine, monitorScriptFilePath); + var scriptsFolderPath = Path.Combine(batchRvtFolderPath, SCRIPTS_FOLDER_NAME); - scriptSource.Execute(mainModuleScope); + var monitorScriptFilePath = Path.Combine( + scriptsFolderPath, + MONITOR_SCRIPT_FILE_NAME + ); - return; - } + ScriptUtil.AddSearchPaths( + engine, + new[] + { + scriptsFolderPath, + batchRvtFolderPath + } + ); - public static string GetDataFolderPath() - { - return Path.Combine(PathUtil.GetLocalAppDataFolderPath(), SCRIPT_DATA_FOLDER_NAME); - } + ScriptUtil.AddBuiltinVariables( + engine, + new Dictionary + { + { "__scope__", mainModuleScope }, + { "__command_settings_data__", commandSettingsData } + } + ); - public static string GetBatchRvtFolderPath() - { - return Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath); - } + ScriptUtil.AddPythonStandardLibrary(mainModuleScope); - public static string GetBatchRvtScriptsFolderPath() - { - return Path.Combine(GetBatchRvtFolderPath(), SCRIPTS_FOLDER_NAME); - } + var scriptSource = ScriptUtil.CreateScriptSourceFromFile(engine, monitorScriptFilePath); - public static bool IsBatchRvtAddinInstalled(RevitVersion.SupportedRevitVersion revitVersion) - { - bool isAddinInstalled = false; - - var revitAddinsBaseFolders = new [] { Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolder.ApplicationData }; + scriptSource.Execute(mainModuleScope); + } - var revitAddinsFolderPaths = revitAddinsBaseFolders.Select(f => RevitVersion.GetRevitAddinsFolderPath(revitVersion, f)).ToList(); + public static string GetDataFolderPath() + { + return Path.Combine(PathUtil.GetLocalAppDataFolderPath(), SCRIPT_DATA_FOLDER_NAME); + } - foreach (var revitAddinsFolderPath in revitAddinsFolderPaths) - { - var batchRvtAddinFilePath = Path.Combine(revitAddinsFolderPath, BATCHRVT_ADDIN_FILENAMES[revitVersion]); + public static string GetBatchRvtFolderPath() + { + return Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath); + } - if (File.Exists(batchRvtAddinFilePath)) - { - isAddinInstalled = true; - } - } + public static string GetBatchRvtScriptsFolderPath() + { + return Path.Combine(GetBatchRvtFolderPath(), SCRIPTS_FOLDER_NAME); + } - return isAddinInstalled; - } - }; -} + public static bool IsBatchRvtAddinInstalled(RevitVersion.SupportedRevitVersion revitVersion) + { + var revitAddinsBaseFolders = new[] + { Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolder.ApplicationData }; + + var revitAddinsFolderPaths = revitAddinsBaseFolders + .Select(f => RevitVersion.GetRevitAddinsFolderPath(revitVersion, f)).ToList(); + + return revitAddinsFolderPaths + .Select(revitAddinsFolderPath => + Path.Combine( + revitAddinsFolderPath, + RevitVersion.GetAddinName(revitVersion))) + .Any(File.Exists); + } +} \ No newline at end of file diff --git a/BatchRvtUtil/BatchRvtSettings.cs b/BatchRvtUtil/BatchRvtSettings.cs index c400d4d..aebffe6 100644 --- a/BatchRvtUtil/BatchRvtSettings.cs +++ b/BatchRvtUtil/BatchRvtSettings.cs @@ -17,273 +17,224 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.IO; using Newtonsoft.Json.Linq; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public class BatchRvtSettings : IPersistent { - public class BatchRvtSettings : IPersistent - { - public const string SETTINGS_FILE_EXTENSION = ".json"; - public const string SETTINGS_FILE_FILTER = "BatchRvt Settings files (*.json)|*.json"; - public const string BATCHRVTGUI_SETTINGS_FILENAME = "BatchRvtGui.Settings" + SETTINGS_FILE_EXTENSION; - public const string BATCHRVT_SETTINGS_FILENAME = "BatchRvt.Settings" + SETTINGS_FILE_EXTENSION; + public const string SETTINGS_FILE_EXTENSION = ".json"; + public const string SETTINGS_FILE_FILTER = "BatchRvt Settings files (*.json)|*.json"; + private const string BATCHRVTGUI_SETTINGS_FILENAME = "BatchRvtGui.Settings" + SETTINGS_FILE_EXTENSION; + public const string BATCHRVT_SETTINGS_FILENAME = "BatchRvt.Settings" + SETTINGS_FILE_EXTENSION; + public readonly BooleanSetting AuditOnOpening = new("auditOnOpening"); - private readonly PersistentSettings persistentSettings; + public readonly EnumSetting BatchRevitTaskRevitVersion = + new("batchRevitTaskRevitVersion"); - // General Task Script settings - public readonly StringSetting TaskScriptFilePath = new StringSetting("taskScriptFilePath"); - public readonly BooleanSetting ShowMessageBoxOnTaskScriptError = new BooleanSetting("showMessageBoxOnTaskScriptError"); - public readonly IntegerSetting ProcessingTimeOutInMinutes = new IntegerSetting("processingTimeOutInMinutes"); - public readonly BooleanSetting ShowRevitProcessErrorMessages = new BooleanSetting("showRevitProcessErrorMessages"); + // Central File Processing settings + public readonly EnumSetting CentralFileOpenOption = new("centralFileOpenOption"); - // Revit File List settings - public readonly StringSetting RevitFileListFilePath = new StringSetting("revitFileListFilePath"); + public readonly StringSetting DataExportFolderPath = new("dataExportFolderPath"); + public readonly BooleanSetting DeleteLocalAfter = new("deleteLocalAfter"); + public readonly BooleanSetting DiscardWorksetsOnDetach = new("discardWorksetsOnDetach"); - // Data Export settings - public readonly BooleanSetting EnableDataExport = new BooleanSetting("enableDataExport"); - public readonly StringSetting DataExportFolderPath = new StringSetting("dataExportFolderPath"); + // Data Export settings + public readonly BooleanSetting EnableDataExport = new("enableDataExport"); - // Pre-processing Script settings - public readonly BooleanSetting ExecutePreProcessingScript = new BooleanSetting("executePreProcessingScript"); - public readonly StringSetting PreProcessingScriptFilePath = new StringSetting("preProcessingScriptFilePath"); - - // Post-processing Script settings - public readonly BooleanSetting ExecutePostProcessingScript = new BooleanSetting("executePostProcessingScript"); - public readonly StringSetting PostProcessingScriptFilePath = new StringSetting("PostProcessingScriptFilePath"); - - // Central File Processing settings - public readonly EnumSetting CentralFileOpenOption = new EnumSetting("centralFileOpenOption"); - public readonly BooleanSetting DeleteLocalAfter = new BooleanSetting("deleteLocalAfter"); - public readonly BooleanSetting DiscardWorksetsOnDetach = new BooleanSetting("discardWorksetsOnDetach"); - public readonly EnumSetting WorksetConfigurationOption = new EnumSetting("worksetConfigurationOption"); + // Post-processing Script settings + public readonly BooleanSetting ExecutePostProcessingScript = new("executePostProcessingScript"); - // Revit Session settings - public readonly EnumSetting RevitSessionOption = new EnumSetting("revitSessionOption"); + // Pre-processing Script settings + public readonly BooleanSetting ExecutePreProcessingScript = new("executePreProcessingScript"); - // Revit Processing settings - public readonly EnumSetting RevitProcessingOption = new EnumSetting("revitProcessingOption"); + public readonly BooleanSetting IfNotAvailableUseMinimumAvailableRevitVersion = + new("ifNotAvailableUseMinimumAvailableRevitVersion"); - // Single Revit Task Processing settings - public readonly EnumSetting SingleRevitTaskRevitVersion = new EnumSetting("singleRevitTaskRevitVersion"); + public readonly BooleanSetting OpenInUI = new("openInUI"); - // Batch Revit File Processing settings - public readonly EnumSetting RevitFileProcessingOption = new EnumSetting("revitFileProcessingOption"); - public readonly BooleanSetting IfNotAvailableUseMinimumAvailableRevitVersion = new BooleanSetting("ifNotAvailableUseMinimumAvailableRevitVersion"); - public readonly EnumSetting BatchRevitTaskRevitVersion = new EnumSetting("batchRevitTaskRevitVersion"); - public readonly BooleanSetting OpenInUI = new BooleanSetting("openInUI"); - public readonly BooleanSetting AuditOnOpening = new BooleanSetting("auditOnOpening"); + public readonly PersistentSettings persistentSettings; + public readonly StringSetting PostProcessingScriptFilePath = new("PostProcessingScriptFilePath"); + public readonly StringSetting PreProcessingScriptFilePath = new("preProcessingScriptFilePath"); + public readonly IntegerSetting ProcessingTimeOutInMinutes = new("processingTimeOutInMinutes"); - // UI settings - public readonly BooleanSetting ShowAdvancedSettings = new BooleanSetting("showAdvancedSettings"); + // Revit File List settings + public readonly StringSetting RevitFileListFilePath = new("revitFileListFilePath"); - public BatchRvtSettings() - { - this.persistentSettings = new PersistentSettings( - new IPersistent[] { - this.TaskScriptFilePath, - this.ShowMessageBoxOnTaskScriptError, - this.ProcessingTimeOutInMinutes, - this.ShowRevitProcessErrorMessages, - this.RevitFileListFilePath, - this.EnableDataExport, - this.DataExportFolderPath, - this.ExecutePreProcessingScript, - this.PreProcessingScriptFilePath, - this.ExecutePostProcessingScript, - this.PostProcessingScriptFilePath, - this.CentralFileOpenOption, - this.DeleteLocalAfter, - this.DiscardWorksetsOnDetach, - this.WorksetConfigurationOption, - this.RevitSessionOption, - this.RevitProcessingOption, - this.SingleRevitTaskRevitVersion, - this.RevitFileProcessingOption, - this.IfNotAvailableUseMinimumAvailableRevitVersion, - this.BatchRevitTaskRevitVersion, - this.OpenInUI, - this.AuditOnOpening, - this.ShowAdvancedSettings - } - ); - } + // Batch Revit File Processing settings + public readonly EnumSetting RevitFileProcessingOption = + new("revitFileProcessingOption"); - public void Load(JObject jobject) - { - this.persistentSettings.Load(jobject); - } + // Revit Processing settings + public readonly EnumSetting RevitProcessingOption = new("revitProcessingOption"); - public void Store(JObject jobject) - { - this.persistentSettings.Store(jobject); - } + // Revit Session settings + public readonly EnumSetting RevitSessionOption = new("revitSessionOption"); - public bool TryLoad(JObject jobject) - { - bool success = false; + // UI settings + public readonly BooleanSetting ShowAdvancedSettings = new("showAdvancedSettings"); - try - { - this.Load(jobject); - success = true; - } - catch (Exception e) - { - success = false; - } + public readonly BooleanSetting ShowMessageBoxOnTaskScriptError = new("showMessageBoxOnTaskScriptError"); - return success; - } + public readonly BooleanSetting ShowRevitProcessErrorMessages = new("showRevitProcessErrorMessages"); - public bool TryStore(JObject jobject) - { - bool success = false; + // Single Revit Task Processing settings + public readonly EnumSetting SingleRevitTaskRevitVersion = + new("singleRevitTaskRevitVersion"); - try - { - this.Store(jobject); - success = true; - } - catch (Exception e) + // General Task Script settings + public readonly StringSetting TaskScriptFilePath = new("taskScriptFilePath"); + + public readonly EnumSetting WorksetConfigurationOption = + new("worksetConfigurationOption"); + + public BatchRvtSettings() + { + persistentSettings = new PersistentSettings( + new IPersistent[] { - success = false; + TaskScriptFilePath, + ShowMessageBoxOnTaskScriptError, + ProcessingTimeOutInMinutes, + ShowRevitProcessErrorMessages, + RevitFileListFilePath, + EnableDataExport, + DataExportFolderPath, + ExecutePreProcessingScript, + PreProcessingScriptFilePath, + ExecutePostProcessingScript, + PostProcessingScriptFilePath, + CentralFileOpenOption, + DeleteLocalAfter, + DiscardWorksetsOnDetach, + WorksetConfigurationOption, + RevitSessionOption, + RevitProcessingOption, + SingleRevitTaskRevitVersion, + RevitFileProcessingOption, + IfNotAvailableUseMinimumAvailableRevitVersion, + BatchRevitTaskRevitVersion, + OpenInUI, + AuditOnOpening, + ShowAdvancedSettings } + ); + } - return success; - } + public void Load(JObject jobject) + { + persistentSettings.Load(jobject); + } - public bool LoadFromFile(string filePath = null) - { - bool success = false; + public void Store(JObject jobject) + { + persistentSettings.Store(jobject); + } - filePath = string.IsNullOrWhiteSpace(filePath) ? GetDefaultSettingsFilePath() : filePath; - if (File.Exists(filePath)) - { - try - { - var text = File.ReadAllText(filePath); - var jobject = JsonUtil.DeserializeFromJson(text); - this.Load(jobject); - success = true; - } - catch (Exception e) - { - success = false; - } - } + public bool LoadFromFile(string filePath = null) + { + + filePath = string.IsNullOrWhiteSpace(filePath) ? GetDefaultSettingsFilePath() : filePath; - return success; + if (!File.Exists(filePath)) return false; + try + { + var text = File.ReadAllText(filePath); + var jobject = JsonUtil.DeserializeFromJson(text); + Load(jobject); + return true; } - - public bool SaveToFile(string filePath = null) + catch (Exception e) { - bool success = false; + return false; + } + + } - filePath = string.IsNullOrWhiteSpace(filePath) ? GetDefaultSettingsFilePath() : filePath; + public bool SaveToFile(string filePath = null) + { + var success = false; - var jobject = new JObject(); + filePath = string.IsNullOrWhiteSpace(filePath) ? GetDefaultSettingsFilePath() : filePath; - try - { - this.Store(jobject); - var settingsText = JsonUtil.SerializeToJson(jobject, true); - var fileInfo = new FileInfo(filePath); - fileInfo.Directory.Create(); - File.WriteAllText(fileInfo.FullName, settingsText); + var jobject = new JObject(); - success = true; - } - catch (Exception e) - { - success = false; - } + try + { + Store(jobject); + var settingsText = JsonUtil.SerializeToJson(jobject, true); + var fileInfo = new FileInfo(filePath); + fileInfo.Directory?.Create(); + File.WriteAllText(fileInfo.FullName, settingsText); - return success; + success = true; } - - public string ToJsonString() + catch (Exception e) { - var jobject = new JObject(); - this.Store(jobject); - return jobject.ToString(); + success = false; } - public static BatchRvtSettings FromJsonString(string batchRvtSettingsJson) - { - BatchRvtSettings batchRvtSettings = null; - - try - { - var jobject = JsonUtil.DeserializeFromJson(batchRvtSettingsJson); - batchRvtSettings = new BatchRvtSettings(); - batchRvtSettings.Load(jobject); - } - catch (Exception e) - { - batchRvtSettings = null; - } + return success; + } - return batchRvtSettings; - } - public static BatchRvtSettings Create( - string taskScriptFilePath, - string revitFileListFilePath, - BatchRvt.RevitProcessingOption revitProcessingOption, - BatchRvt.CentralFileOpenOption centralFileOpenOption, - bool deleteLocalAfter, - bool discardWorksetsOnDetach, - BatchRvt.RevitSessionOption revitSessionOption, - BatchRvt.RevitFileProcessingOption revitFileVersionOption, - RevitVersion.SupportedRevitVersion taskRevitVersion, - int fileProcessingTimeOutInMinutes, - bool fallbackToMinimumAvailableRevitVersion - ) - { - var batchRvtSettings = new BatchRvtSettings(); + public static BatchRvtSettings Create( + string taskScriptFilePath, + string revitFileListFilePath, + BatchRvt.RevitProcessingOption revitProcessingOption, + BatchRvt.CentralFileOpenOption centralFileOpenOption, + bool deleteLocalAfter, + bool discardWorksetsOnDetach, + BatchRvt.RevitSessionOption revitSessionOption, + BatchRvt.RevitFileProcessingOption revitFileVersionOption, + RevitVersion.SupportedRevitVersion taskRevitVersion, + int fileProcessingTimeOutInMinutes, + bool fallbackToMinimumAvailableRevitVersion + ) + { + var batchRvtSettings = new BatchRvtSettings(); - // General Task Script settings - batchRvtSettings.TaskScriptFilePath.SetValue(taskScriptFilePath); - batchRvtSettings.ProcessingTimeOutInMinutes.SetValue(fileProcessingTimeOutInMinutes); + // General Task Script settings + batchRvtSettings.TaskScriptFilePath.SetValue(taskScriptFilePath); + batchRvtSettings.ProcessingTimeOutInMinutes.SetValue(fileProcessingTimeOutInMinutes); - // Revit Processing settings - batchRvtSettings.RevitProcessingOption.SetValue(revitProcessingOption); + // Revit Processing settings + batchRvtSettings.RevitProcessingOption.SetValue(revitProcessingOption); - // Revit File List settings - batchRvtSettings.RevitFileListFilePath.SetValue(revitFileListFilePath); + // Revit File List settings + batchRvtSettings.RevitFileListFilePath.SetValue(revitFileListFilePath); - // Central File Processing settings - batchRvtSettings.CentralFileOpenOption.SetValue(centralFileOpenOption); - batchRvtSettings.DeleteLocalAfter.SetValue(deleteLocalAfter); - batchRvtSettings.DiscardWorksetsOnDetach.SetValue(discardWorksetsOnDetach); + // Central File Processing settings + batchRvtSettings.CentralFileOpenOption.SetValue(centralFileOpenOption); + batchRvtSettings.DeleteLocalAfter.SetValue(deleteLocalAfter); + batchRvtSettings.DiscardWorksetsOnDetach.SetValue(discardWorksetsOnDetach); - // Revit Session settings - batchRvtSettings.RevitSessionOption.SetValue(revitSessionOption); + // Revit Session settings + batchRvtSettings.RevitSessionOption.SetValue(revitSessionOption); - // Single Revit Task Processing settings - batchRvtSettings.SingleRevitTaskRevitVersion.SetValue(taskRevitVersion); + // Single Revit Task Processing settings + batchRvtSettings.SingleRevitTaskRevitVersion.SetValue(taskRevitVersion); - // Batch Revit File Processing settings - batchRvtSettings.RevitFileProcessingOption.SetValue(revitFileVersionOption); - batchRvtSettings.IfNotAvailableUseMinimumAvailableRevitVersion.SetValue(fallbackToMinimumAvailableRevitVersion); - batchRvtSettings.BatchRevitTaskRevitVersion.SetValue(taskRevitVersion); - batchRvtSettings.AuditOnOpening.SetValue(false); // TODO: implement this option for this function? + // Batch Revit File Processing settings + batchRvtSettings.RevitFileProcessingOption.SetValue(revitFileVersionOption); + batchRvtSettings.IfNotAvailableUseMinimumAvailableRevitVersion.SetValue( + fallbackToMinimumAvailableRevitVersion); + batchRvtSettings.BatchRevitTaskRevitVersion.SetValue(taskRevitVersion); + batchRvtSettings.AuditOnOpening.SetValue(false); // TODO: implement this option for this function? - return batchRvtSettings; - } + return batchRvtSettings; + } - public static string GetDefaultSettingsFilePath() - { - return Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "BatchRvt", - BATCHRVTGUI_SETTINGS_FILENAME - ); - } + public static string GetDefaultSettingsFilePath() + { + return Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "BatchRvt", + BATCHRVTGUI_SETTINGS_FILENAME + ); } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/BatchRvtTasks.cs b/BatchRvtUtil/BatchRvtTasks.cs index 9789116..d777ae2 100644 --- a/BatchRvtUtil/BatchRvtTasks.cs +++ b/BatchRvtUtil/BatchRvtTasks.cs @@ -17,301 +17,261 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; -using System.Linq; -using System.IO; using System.Diagnostics; +using System.IO; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class BatchRvtTasks { - public static class BatchRvtTasks + // NOTE: Dynamo scripts are not supported in Revit versions earlier than 2016. + public enum UseRevitVersion { - public static string RunTask( - string taskScriptFilePath, - IEnumerable revitFileList, - UseRevitVersion useRevitVersion, - BatchRvt.CentralFileOpenOption centralFileOpenOption, - bool discardWorksetsOnDetach, - bool deleteLocalAfter, - bool openLogFileWhenDone, - string taskData, - string testModeFolderPath - ) - { - return RunTask( - taskScriptFilePath, - revitFileList, // Input is a list of Revit file paths. - BatchRvt.RevitProcessingOption.BatchRevitFileProcessing, - useRevitVersion, - centralFileOpenOption, - discardWorksetsOnDetach, - deleteLocalAfter, - openLogFileWhenDone, - logFolderPath: null, - fileProcessingTimeOutInMinutes: 0, - fallbackToMinimumAvailableRevitVersion: false, - taskData: taskData, - testModeFolderPath: testModeFolderPath - ); - } + RevitFileVersion = 0, + Revit2015 = 1, + Revit2016 = 2, + Revit2017 = 3, + Revit2018 = 4, + Revit2019 = 5, + Revit2020 = 6, + Revit2021 = 7, + Revit2022 = 8, + Revit2023 = 9 + } - public static string RunSingleTask( - string taskScriptFilePath, - UseRevitVersion useRevitVersion, - bool openLogFileWhenDone, - string taskData, - string testModeFolderPath - ) - { - if (useRevitVersion == UseRevitVersion.RevitFileVersion) - { - throw new ArgumentException("useRevitVersion argument must specify a specific Revit version!"); - } - - return RunTask( - taskScriptFilePath, - null, // Revit File list is N/A for single task processing - BatchRvt.RevitProcessingOption.SingleRevitTaskProcessing, - useRevitVersion, - BatchRvt.CentralFileOpenOption.Detach, // N/A for single task processing - discardWorksetsOnDetach: true, // N/A for single task processing - deleteLocalAfter: true, // N/A for single task processing - openLogFileWhenDone: openLogFileWhenDone, - logFolderPath: null, - fileProcessingTimeOutInMinutes: 0, // N/A for single task processing - fallbackToMinimumAvailableRevitVersion: false, - taskData: taskData, - testModeFolderPath: testModeFolderPath - ); - } + public static string RunTask( + string taskScriptFilePath, + IEnumerable revitFileList, + UseRevitVersion useRevitVersion, + BatchRvt.CentralFileOpenOption centralFileOpenOption, + bool discardWorksetsOnDetach, + bool deleteLocalAfter, + bool openLogFileWhenDone, + string taskData, + string testModeFolderPath + ) + { + return RunTask( + taskScriptFilePath, + revitFileList, // Input is a list of Revit file paths. + BatchRvt.RevitProcessingOption.BatchRevitFileProcessing, + useRevitVersion, + centralFileOpenOption, + discardWorksetsOnDetach, + deleteLocalAfter, + openLogFileWhenDone, + null, + 0, + false, + taskData, + testModeFolderPath + ); + } - public static string RunTaskAdvanced( - string taskScriptFilePath, - IEnumerable revitFileList, - UseRevitVersion useRevitVersion, - BatchRvt.CentralFileOpenOption centralFileOpenOption, - bool discardWorksetsOnDetach, - bool deleteLocalAfter, - bool openLogFileWhenDone, - string logFolderPath, - int fileProcessingTimeOutInMinutes, - bool fallbackToMinimumAvailableRevitVersion, - string taskData, - string testModeFolderPath - ) - { - return RunTask( - taskScriptFilePath, - revitFileList, // Input is a list of Revit file paths. - BatchRvt.RevitProcessingOption.BatchRevitFileProcessing, - useRevitVersion, - centralFileOpenOption, - discardWorksetsOnDetach, - deleteLocalAfter, - openLogFileWhenDone, - logFolderPath, - fileProcessingTimeOutInMinutes, - fallbackToMinimumAvailableRevitVersion, - taskData: taskData, - testModeFolderPath: testModeFolderPath - ); - } + public static string RunSingleTask( + string taskScriptFilePath, + UseRevitVersion useRevitVersion, + bool openLogFileWhenDone, + string taskData, + string testModeFolderPath + ) + { + if (useRevitVersion == UseRevitVersion.RevitFileVersion) + throw new ArgumentException("useRevitVersion argument must specify a specific Revit version!"); + + return RunTask( + taskScriptFilePath, + null, // Revit File list is N/A for single task processing + BatchRvt.RevitProcessingOption.SingleRevitTaskProcessing, + useRevitVersion, + BatchRvt.CentralFileOpenOption.Detach, // N/A for single task processing + true, // N/A for single task processing + true, // N/A for single task processing + openLogFileWhenDone, + null, + 0, // N/A for single task processing + false, + taskData, + testModeFolderPath + ); + } + + public static string RunTaskAdvanced( + string taskScriptFilePath, + IEnumerable revitFileList, + UseRevitVersion useRevitVersion, + BatchRvt.CentralFileOpenOption centralFileOpenOption, + bool discardWorksetsOnDetach, + bool deleteLocalAfter, + bool openLogFileWhenDone, + string logFolderPath, + int fileProcessingTimeOutInMinutes, + bool fallbackToMinimumAvailableRevitVersion, + string taskData, + string testModeFolderPath + ) + { + return RunTask( + taskScriptFilePath, + revitFileList, // Input is a list of Revit file paths. + BatchRvt.RevitProcessingOption.BatchRevitFileProcessing, + useRevitVersion, + centralFileOpenOption, + discardWorksetsOnDetach, + deleteLocalAfter, + openLogFileWhenDone, + logFolderPath, + fileProcessingTimeOutInMinutes, + fallbackToMinimumAvailableRevitVersion, + taskData, + testModeFolderPath + ); + } - public static string RunTaskFromSettingsFile( - string settingsFilePath, - string logFolderPath, - bool openLogFileWhenDone, - string taskData = null, - string testModeFolderPath = null - ) + public static string RunTaskFromSettingsFile( + string settingsFilePath, + string logFolderPath, + bool openLogFileWhenDone, + string taskData = null, + string testModeFolderPath = null + ) + { + var commandSettingsData = new CommandSettings.Data { - var commandSettingsData = new CommandSettings.Data(); + SettingsFilePath = settingsFilePath, + LogFolderPath = logFolderPath, + TaskData = taskData, + TestModeFolderPath = testModeFolderPath + }; - commandSettingsData.SettingsFilePath = settingsFilePath; - commandSettingsData.LogFolderPath = logFolderPath; - commandSettingsData.TaskData = taskData; - commandSettingsData.TestModeFolderPath = testModeFolderPath; + return RunTask(commandSettingsData, openLogFileWhenDone); + } - return RunTask(commandSettingsData, openLogFileWhenDone); - } + public static string RunTask( + string taskScriptFilePath, + object revitFileListInput, + BatchRvt.RevitProcessingOption revitProcessingOption, + UseRevitVersion useRevitVersion, + BatchRvt.CentralFileOpenOption centralFileOpenOption, + bool discardWorksetsOnDetach, + bool deleteLocalAfter, + bool openLogFileWhenDone, + string logFolderPath, + int fileProcessingTimeOutInMinutes, + bool fallbackToMinimumAvailableRevitVersion, + string taskData, + string testModeFolderPath + ) + { + var batchRvtRevitFileProcessingOption = useRevitVersion == UseRevitVersion.RevitFileVersion + ? BatchRvt.RevitFileProcessingOption.UseFileRevitVersionIfAvailable + : BatchRvt.RevitFileProcessingOption.UseSpecificRevitVersion; + + // NOTE: can be any version if useRevitVersion is set to RevitFileVersion. + var taskRevitVersion = GetVersion(useRevitVersion); + + var batchRvtSettings = BatchRvtSettings.Create( + taskScriptFilePath, + revitFileListInput as string ?? string.Empty, + revitProcessingOption, + centralFileOpenOption, + deleteLocalAfter, + discardWorksetsOnDetach, + BatchRvt.RevitSessionOption.UseSeparateSessionPerFile, + batchRvtRevitFileProcessingOption, + taskRevitVersion, + fileProcessingTimeOutInMinutes, + fallbackToMinimumAvailableRevitVersion + ); + + var commandSettingsData = new CommandSettings.Data(); + + commandSettingsData.RevitFileList = revitFileListInput as IEnumerable; + commandSettingsData.Settings = batchRvtSettings; + commandSettingsData.LogFolderPath = logFolderPath; + commandSettingsData.TaskData = taskData; + commandSettingsData.TestModeFolderPath = testModeFolderPath; + + return RunTask(commandSettingsData, openLogFileWhenDone); + } - public static string RunTask( - string taskScriptFilePath, - object revitFileListInput, - BatchRvt.RevitProcessingOption revitProcessingOption, - UseRevitVersion useRevitVersion, - BatchRvt.CentralFileOpenOption centralFileOpenOption, - bool discardWorksetsOnDetach, - bool deleteLocalAfter, - bool openLogFileWhenDone, - string logFolderPath, - int fileProcessingTimeOutInMinutes, - bool fallbackToMinimumAvailableRevitVersion, - string taskData, - string testModeFolderPath - ) - { - var batchRvtRevitFileProcessingOption = ( - useRevitVersion == UseRevitVersion.RevitFileVersion ? - BatchRvt.RevitFileProcessingOption.UseFileRevitVersionIfAvailable : - BatchRvt.RevitFileProcessingOption.UseSpecificRevitVersion - ); - - // NOTE: can be any version if useRevitVersion is set to RevitFileVersion. - var taskRevitVersion = ( - useRevitVersion == UseRevitVersion.Revit2015 ? - RevitVersion.SupportedRevitVersion.Revit2015 : - useRevitVersion == UseRevitVersion.Revit2016 ? - RevitVersion.SupportedRevitVersion.Revit2016 : - useRevitVersion == UseRevitVersion.Revit2017 ? - RevitVersion.SupportedRevitVersion.Revit2017 : - useRevitVersion == UseRevitVersion.Revit2018 ? - RevitVersion.SupportedRevitVersion.Revit2018 : - useRevitVersion == UseRevitVersion.Revit2019 ? - RevitVersion.SupportedRevitVersion.Revit2019 : - useRevitVersion == UseRevitVersion.Revit2020 ? - RevitVersion.SupportedRevitVersion.Revit2020 : - useRevitVersion == UseRevitVersion.Revit2021 ? - RevitVersion.SupportedRevitVersion.Revit2021 : - useRevitVersion == UseRevitVersion.Revit2022 ? - RevitVersion.SupportedRevitVersion.Revit2022 : - RevitVersion.SupportedRevitVersion.Revit2023 - - ); - - var batchRvtSettings = BatchRvtSettings.Create( - taskScriptFilePath, - (revitFileListInput as string) ?? string.Empty, - revitProcessingOption, - centralFileOpenOption, - deleteLocalAfter, - discardWorksetsOnDetach, - BatchRvt.RevitSessionOption.UseSeparateSessionPerFile, - batchRvtRevitFileProcessingOption, - taskRevitVersion, - fileProcessingTimeOutInMinutes, - fallbackToMinimumAvailableRevitVersion - ); - - var commandSettingsData = new CommandSettings.Data(); - - commandSettingsData.RevitFileList = revitFileListInput as IEnumerable; - commandSettingsData.Settings = batchRvtSettings; - commandSettingsData.LogFolderPath = logFolderPath; - commandSettingsData.TaskData = taskData; - commandSettingsData.TestModeFolderPath = testModeFolderPath; - - return RunTask(commandSettingsData, openLogFileWhenDone); - } + private static RevitVersion.SupportedRevitVersion GetVersion(UseRevitVersion useRevitVersion) + { + return (RevitVersion.SupportedRevitVersion)Enum.Parse(typeof(UseRevitVersion), useRevitVersion.ToString()); + } - public static string RunTask( - CommandSettings.Data commandSettingsData, - bool openLogFileWhenDone - ) - { - commandSettingsData = ValidateCommandSettingsData(commandSettingsData); + private static string RunTask( + CommandSettings.Data commandSettingsData, + bool openLogFileWhenDone + ) + { + commandSettingsData = ValidateCommandSettingsData(commandSettingsData); - var batchRvtFolderPath = BatchRvt.GetBatchRvtFolderPath(); + var batchRvtFolderPath = BatchRvt.GetBatchRvtFolderPath(); - BatchRvt.ExecuteMonitorScript(batchRvtFolderPath, commandSettingsData); + BatchRvt.ExecuteMonitorScript(batchRvtFolderPath, commandSettingsData); - var logFilePath = commandSettingsData.GeneratedLogFilePath; + var logFilePath = commandSettingsData.GeneratedLogFilePath; - logFilePath = PostProcessLogFile(logFilePath); + logFilePath = PostProcessLogFile(logFilePath); - if (openLogFileWhenDone) - { - if (!string.IsNullOrWhiteSpace(logFilePath)) - { - Process.Start(logFilePath); - } - } + if (!openLogFileWhenDone) return logFilePath; + if (!string.IsNullOrWhiteSpace(logFilePath)) + Process.Start(logFilePath); - return logFilePath; - } + return logFilePath; + } - private static string PostProcessLogFile(string logFilePath) - { - if (!string.IsNullOrWhiteSpace(logFilePath)) - { - var plainTextLogFilePath = Path.Combine( - Path.GetDirectoryName(logFilePath), - Path.GetFileNameWithoutExtension(logFilePath) + ".txt" - ); - - File.WriteAllLines( - plainTextLogFilePath, - LogFile.ReadLinesAsPlainText(logFilePath) - ); - - logFilePath = plainTextLogFilePath; - } - - return logFilePath; - } + private static string PostProcessLogFile(string logFilePath) + { + if (string.IsNullOrWhiteSpace(logFilePath)) return logFilePath; + var plainTextLogFilePath = Path.Combine( + Path.GetDirectoryName(logFilePath) ?? string.Empty, + Path.GetFileNameWithoutExtension(logFilePath) + ".txt" + ); + + File.WriteAllLines( + plainTextLogFilePath, + LogFile.ReadLinesAsPlainText(logFilePath) + ); + + logFilePath = plainTextLogFilePath; - private static CommandSettings.Data ValidateCommandSettingsData(CommandSettings.Data commandSettingsData) + return logFilePath; + } + + private static CommandSettings.Data ValidateCommandSettingsData(CommandSettings.Data commandSettingsData) + { + if (string.IsNullOrWhiteSpace(commandSettingsData.SettingsFilePath)) + commandSettingsData.SettingsFilePath = null; + + if (string.IsNullOrWhiteSpace(commandSettingsData.LogFolderPath)) commandSettingsData.LogFolderPath = null; + + if (string.IsNullOrWhiteSpace(commandSettingsData.SessionId)) commandSettingsData.SessionId = null; + + if (string.IsNullOrWhiteSpace(commandSettingsData.TaskData)) commandSettingsData.TaskData = null; + + if (string.IsNullOrWhiteSpace(commandSettingsData.TestModeFolderPath)) + commandSettingsData.TestModeFolderPath = null; + + var batchRvtSettings = commandSettingsData.Settings; + + if (batchRvtSettings != null && batchRvtSettings.RevitProcessingOption.GetValue() == + BatchRvt.RevitProcessingOption.BatchRevitFileProcessing + && + string.IsNullOrWhiteSpace(batchRvtSettings.RevitFileListFilePath.GetValue()) + && + commandSettingsData.RevitFileList == null) { - if (string.IsNullOrWhiteSpace(commandSettingsData.SettingsFilePath)) - { - commandSettingsData.SettingsFilePath = null; - } - - if (string.IsNullOrWhiteSpace(commandSettingsData.LogFolderPath)) - { - commandSettingsData.LogFolderPath = null; - } - - if (string.IsNullOrWhiteSpace(commandSettingsData.SessionId)) - { - commandSettingsData.SessionId = null; - } - - if (string.IsNullOrWhiteSpace(commandSettingsData.TaskData)) - { - commandSettingsData.TaskData = null; - } - - if (string.IsNullOrWhiteSpace(commandSettingsData.TestModeFolderPath)) - { - commandSettingsData.TestModeFolderPath = null; - } - - var batchRvtSettings = commandSettingsData.Settings; - - if (batchRvtSettings != null) - { - if (batchRvtSettings.RevitProcessingOption.GetValue() == BatchRvt.RevitProcessingOption.BatchRevitFileProcessing) - { - if ( - string.IsNullOrWhiteSpace(batchRvtSettings.RevitFileListFilePath.GetValue()) - && - commandSettingsData.RevitFileList == null - ) - { - throw new ArgumentNullException("No Revit file list was specified for Batch processing mode."); - } - } - } - - commandSettingsData.GeneratedLogFilePath = null; - - return commandSettingsData; + throw new ArgumentNullException(@"No Revit file list was specified for Batch processing mode."); } + - // NOTE: Dynamo scripts are not supported in Revit versions earlier than 2016. - public enum UseRevitVersion { - RevitFileVersion = 0, - Revit2015 = 1, - Revit2016 = 2, - Revit2017 = 3, - Revit2018 = 4, - Revit2019 = 5, - Revit2020 = 6, - Revit2021 = 7, - Revit2022 = 8, - Revit2023 = 9 - } + commandSettingsData.GeneratedLogFilePath = null; + + return commandSettingsData; } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/BatchRvtUtil.csproj b/BatchRvtUtil/BatchRvtUtil.csproj index 7433e94..f06dfbb 100644 --- a/BatchRvtUtil/BatchRvtUtil.csproj +++ b/BatchRvtUtil/BatchRvtUtil.csproj @@ -1,275 +1,349 @@  - - - Debug - AnyCPU - {B880DD15-184B-4CE2-86FC-08BAC05E0271} - Library - Properties - BatchRvtUtil - BatchRvtUtil - v4.8 - 512 - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - prompt - MinimumRecommendedRules.ruleset - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - prompt - MinimumRecommendedRules.ruleset - - - - False - ..\References\IronPython-2.7.3\IronPython.dll - - - False - ..\References\IronPython-2.7.3\IronPython.Modules.dll - - - - False - ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.dll - - - False - ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll - - - False - ..\References\JSON.NET\Newtonsoft.Json.dll - True - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - - - - - - - - - - - - - - - - {673d1fb5-cfb2-4bdf-9609-c43979dd7197} - BatchRvtScriptHost - - - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - - + + + + Debug + AnyCPU + {B880DD15-184B-4CE2-86FC-08BAC05E0271} + Library + Properties + BatchRvtUtil + BatchRvtUtil + v4.8 + 512 + latestmajor + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Castle.Core.5.1.0\lib\net462\Castle.Core.dll + + + ..\packages\FluentAssertions.6.8.0\lib\net47\FluentAssertions.dll + + + False + ..\References\IronPython-2.7.3\IronPython.dll + + + False + ..\References\IronPython-2.7.3\IronPython.Modules.dll + + + + False + ..\References\IronPython-2.7.3\Microsoft.Dynamic.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.dll + + + False + ..\References\IronPython-2.7.3\Microsoft.Scripting.Metadata.dll + + + ..\packages\Moq.4.18.3\lib\net462\Moq.dll + + + + False + ..\References\JSON.NET\Newtonsoft.Json.dll + True + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll + + + ..\packages\xunit.assert.2.4.2\lib\netstandard1.1\xunit.assert.dll + + + ..\packages\xunit.extensibility.core.2.4.2\lib\net452\xunit.core.dll + + + ..\packages\xunit.extensibility.execution.2.4.2\lib\net452\xunit.execution.desktop.dll + + + + + Properties\GlobalAssemblyInfo.cs + + + + + + + + + + + + + + + + + + + + + + + {673d1fb5-cfb2-4bdf-9609-c43979dd7197} + BatchRvtScriptHost + + + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + + + + + \ No newline at end of file diff --git a/BatchRvtUtil/CommandLineUtil.cs b/BatchRvtUtil/CommandLineUtil.cs index 89c16fe..61a91df 100644 --- a/BatchRvtUtil/CommandLineUtil.cs +++ b/BatchRvtUtil/CommandLineUtil.cs @@ -17,94 +17,73 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; using System.Linq; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class CommandLineUtil { - public static class CommandLineUtil + private const string OPTION_SWITCH_PREFIX = "--"; + + private static int FindArgOptionSwitch(string[] args, string optionSwitch) + { + return Array.FindIndex(args, 1, arg => arg.ToLower() == OPTION_SWITCH_PREFIX + optionSwitch.ToLower()); + } + + private static string GetArgOptionValue(string[] args, string optionSwitch) + { + var optionSwitchIndex = FindArgOptionSwitch(args, optionSwitch); + + if (optionSwitchIndex == -1) return null; + if (optionSwitchIndex + 1 >= args.Length) return null; + var optionValue = args[optionSwitchIndex + 1]; + + if (optionValue is { } && optionValue.StartsWith(OPTION_SWITCH_PREFIX)) optionValue = null; + + return optionValue; + } + + public static bool HaveArguments() + { + var args = Environment.GetCommandLineArgs(); + + return args.Length > 1; + } + + public static string GetCommandLineOption(string optionSwitch, bool expectOptionValue = true) + { + var args = Environment.GetCommandLineArgs(); + + if (args.Length <= 1) return null; + var optionSwitchIndex = FindArgOptionSwitch(args, optionSwitch); + + if (optionSwitchIndex == -1) return null; + var optionValue = + expectOptionValue + ? GetArgOptionValue(args, optionSwitch) + : string.Empty; // Indicates a value-less option exists. + + return optionValue; + } + + public static IEnumerable GetAllCommandLineOptionSwitches() + { + var allOptionSwitches = + Enumerable.Empty(); + + var args = Environment.GetCommandLineArgs(); + + if (args.Length > 1) allOptionSwitches = args.Where(arg => arg.StartsWith(OPTION_SWITCH_PREFIX)); + + return allOptionSwitches + .Select(optionSwitch => optionSwitch.Substring(OPTION_SWITCH_PREFIX.Length).ToLower()).ToList(); + } + + public static bool HasCommandLineOption(string optionSwitch, bool expectOptionValue = true) { - public const string OptionSwitchPrefix = "--"; - - private static int FindArgOptionSwitch(string[] args, string optionSwitch) - { - return Array.FindIndex(args, 1, arg => arg.ToLower() == (OptionSwitchPrefix + optionSwitch.ToLower())); - } - - private static string GetArgOptionValue(string [] args, string optionSwitch) - { - string optionValue = null; - - int optionSwitchIndex = FindArgOptionSwitch(args, optionSwitch); - - if (optionSwitchIndex != -1) - { - if ((optionSwitchIndex + 1) < args.Length) - { - optionValue = args[optionSwitchIndex + 1]; - - if (optionValue.StartsWith(OptionSwitchPrefix)) - { - optionValue = null; - } - } - } - - return optionValue; - } - - public static bool HaveArguments() - { - var args = Environment.GetCommandLineArgs(); - - return (args.Length > 1); - } - - public static string GetCommandLineOption(string optionSwitch, bool expectOptionValue = true) - { - string optionValue = null; - - var args = Environment.GetCommandLineArgs(); - - if (args.Length > 1) - { - var optionSwitchIndex = FindArgOptionSwitch(args, optionSwitch); - - if (optionSwitchIndex != -1) - { - if (expectOptionValue) - { - optionValue = GetArgOptionValue(args, optionSwitch); - } - else - { - optionValue = string.Empty; // Indicates a value-less option exists. - } - - } - } - - return optionValue; - } - - public static IEnumerable GetAllCommandLineOptionSwitches() - { - var allOptionSwitches = Enumerable.Empty(); - - var args = Environment.GetCommandLineArgs(); - - if (args.Length > 1) - { - allOptionSwitches = args.Where(arg => arg.StartsWith(OptionSwitchPrefix)); - } - - return allOptionSwitches.Select(optionSwitch => optionSwitch.Substring(OptionSwitchPrefix.Length).ToLower()).ToList(); - } - - public static bool HasCommandLineOption(string optionSwitch, bool expectOptionValue = true) - { - return GetCommandLineOption(optionSwitch, expectOptionValue) != null; - } + return GetCommandLineOption(optionSwitch, expectOptionValue) != null; } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/CommandSettings.cs b/BatchRvtUtil/CommandSettings.cs index 707af2b..d69e606 100644 --- a/BatchRvtUtil/CommandSettings.cs +++ b/BatchRvtUtil/CommandSettings.cs @@ -17,213 +17,186 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; using System.Linq; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class CommandSettings { - public static class CommandSettings + public const string SETTINGS_FILE_PATH_OPTION = "settings_file"; + public const string LOG_FOLDER_PATH_OPTION = "log_folder"; + public const string SESSION_ID_OPTION = "session_id"; + public const string TASK_DATA_OPTION = "task_data"; + public const string TEST_MODE_FOLDER_PATH_OPTION = "test_mode_folder_path"; + public const string REVIT_FILE_LIST_OPTION = "file_list"; + public const string REVIT_VERSION_OPTION = "revit_version"; + public const string TASK_SCRIPT_FILE_PATH_OPTION = "task_script"; + public const string DETACH_OPTION = "detach"; + public const string CREATE_NEW_LOCAL_OPTION = "create_new_local"; + public const string WORKSETS_OPTION = "worksets"; + public const string CLOSE_ALL_WORKSETS_OPTION_VALUE = "close_all"; + public const string OPEN_ALL_WORKSETS_OPTION_VALUE = "open_all"; + public const string OPEN_LAST_VIEWED_WORKSETS_OPTION_VALUE = "last_viewed"; + public const string AUDIT_ON_OPENING_OPTION = "audit"; + public const string PER_FILE_PROCESSING_TIMEOUT_OPTION = "per_file_timeout"; + public const string HELP_OPTION = "help"; + + private static readonly string[] ALL_VALID_OPTONS = { - public const string SETTINGS_FILE_PATH_OPTION = "settings_file"; - public const string LOG_FOLDER_PATH_OPTION = "log_folder"; - public const string SESSION_ID_OPTION = "session_id"; - public const string TASK_DATA_OPTION = "task_data"; - public const string TEST_MODE_FOLDER_PATH_OPTION = "test_mode_folder_path"; - public const string REVIT_FILE_LIST_OPTION = "file_list"; - public const string REVIT_VERSION_OPTION = "revit_version"; - public const string TASK_SCRIPT_FILE_PATH_OPTION = "task_script"; - public const string DETACH_OPTION = "detach"; - public const string CREATE_NEW_LOCAL_OPTION = "create_new_local"; - public const string WORKSETS_OPTION = "worksets"; - public const string CLOSE_ALL_WORKSETS_OPTION_VALUE = "close_all"; - public const string OPEN_ALL_WORKSETS_OPTION_VALUE = "open_all"; - public const string OPEN_LAST_VIEWED_WORKSETS_OPTION_VALUE = "last_viewed"; - public const string AUDIT_ON_OPENING_OPTION = "audit"; - public const string PER_FILE_PROCESSING_TIMEOUT_OPTION = "per_file_timeout"; - public const string HELP_OPTION = "help"; - public static readonly string[] ALL_VALID_OPTONS = new [] { - SETTINGS_FILE_PATH_OPTION, - LOG_FOLDER_PATH_OPTION, - SESSION_ID_OPTION, - TASK_DATA_OPTION, - TEST_MODE_FOLDER_PATH_OPTION, - REVIT_FILE_LIST_OPTION, - REVIT_VERSION_OPTION, - TASK_SCRIPT_FILE_PATH_OPTION, - DETACH_OPTION, - CREATE_NEW_LOCAL_OPTION, - WORKSETS_OPTION, - AUDIT_ON_OPENING_OPTION, - PER_FILE_PROCESSING_TIMEOUT_OPTION, - HELP_OPTION - }; - - private static readonly Dictionary> OPTION_PARSERS = - new Dictionary>() { - { SETTINGS_FILE_PATH_OPTION, ParseExistingFilePathOptionValue }, - { LOG_FOLDER_PATH_OPTION, ParseExistingFolderPathOptionValue }, - { SESSION_ID_OPTION, ParseTextOptionValue }, - { TASK_DATA_OPTION, ParseTextOptionValue }, - { TEST_MODE_FOLDER_PATH_OPTION, ParseTextOptionValue }, - { REVIT_VERSION_OPTION, optionValue => ParseRevitVersionOptionValue(optionValue) }, - { REVIT_FILE_LIST_OPTION, ParseExistingFilePathOptionValue }, - { TASK_SCRIPT_FILE_PATH_OPTION, ParseExistingFilePathOptionValue }, - { DETACH_OPTION, null }, - { CREATE_NEW_LOCAL_OPTION, null }, - { WORKSETS_OPTION, optionValue => ParseWorksetsOptionValue(optionValue) }, - { AUDIT_ON_OPENING_OPTION, null }, - { PER_FILE_PROCESSING_TIMEOUT_OPTION, optionValue => ParsePositiveIntegerOptionValue(optionValue) }, - { HELP_OPTION, null } - }; - - public static string ParseTextOptionValue(string textOptionValue) + SETTINGS_FILE_PATH_OPTION, + LOG_FOLDER_PATH_OPTION, + SESSION_ID_OPTION, + TASK_DATA_OPTION, + TEST_MODE_FOLDER_PATH_OPTION, + REVIT_FILE_LIST_OPTION, + REVIT_VERSION_OPTION, + TASK_SCRIPT_FILE_PATH_OPTION, + DETACH_OPTION, + CREATE_NEW_LOCAL_OPTION, + WORKSETS_OPTION, + AUDIT_ON_OPENING_OPTION, + PER_FILE_PROCESSING_TIMEOUT_OPTION, + HELP_OPTION + }; + + private static readonly Dictionary> OPTION_PARSERS = + new() { - string parsedValue = null; + { SETTINGS_FILE_PATH_OPTION, ParseExistingFilePathOptionValue }, + { LOG_FOLDER_PATH_OPTION, ParseExistingFolderPathOptionValue }, + { SESSION_ID_OPTION, ParseTextOptionValue }, + { TASK_DATA_OPTION, ParseTextOptionValue }, + { TEST_MODE_FOLDER_PATH_OPTION, ParseTextOptionValue }, + { REVIT_VERSION_OPTION, optionValue => ParseRevitVersionOptionValue(optionValue) }, + { REVIT_FILE_LIST_OPTION, ParseExistingFilePathOptionValue }, + { TASK_SCRIPT_FILE_PATH_OPTION, ParseExistingFilePathOptionValue }, + { DETACH_OPTION, null }, + { CREATE_NEW_LOCAL_OPTION, null }, + { WORKSETS_OPTION, optionValue => ParseWorksetsOptionValue(optionValue) }, + { AUDIT_ON_OPENING_OPTION, null }, + { PER_FILE_PROCESSING_TIMEOUT_OPTION, optionValue => ParsePositiveIntegerOptionValue(optionValue) }, + { HELP_OPTION, null } + }; + + public static string ParseTextOptionValue(string textOptionValue) + { + string parsedValue = null; - if (!string.IsNullOrWhiteSpace(textOptionValue)) - { - parsedValue = textOptionValue.Trim(); - } + if (!string.IsNullOrWhiteSpace(textOptionValue)) parsedValue = textOptionValue.Trim(); - return parsedValue; - } + return parsedValue; + } - public static int? ParsePositiveIntegerOptionValue(string integerOptionValue) - { - int parsedValue; + public static int? ParsePositiveIntegerOptionValue(string integerOptionValue) + { + var parsed = int.TryParse(integerOptionValue, out var parsedValue); - bool parsed = int.TryParse(integerOptionValue, out parsedValue); + return parsed && parsedValue > 0 ? parsedValue : null; + } - return (parsed && parsedValue > 0) ? parsedValue : (int?)null; - } + public static string ParseExistingFilePathOptionValue(string filePathOptionValue) + { + string parsedValue = null; - public static string ParseExistingFilePathOptionValue(string filePathOptionValue) - { - string parsedValue = null; + if (string.IsNullOrWhiteSpace(filePathOptionValue)) return null; + var fullFilePath = PathUtil.GetFullPath(filePathOptionValue); - if (!string.IsNullOrWhiteSpace(filePathOptionValue)) - { - var fullFilePath = PathUtil.GetFullPath(filePathOptionValue); + if (PathUtil.FileExists(fullFilePath)) parsedValue = fullFilePath; - if (PathUtil.FileExists(fullFilePath)) - { - parsedValue = fullFilePath; - } - } + return parsedValue; + } - return parsedValue; - } + public static string ParseExistingFolderPathOptionValue(string folderPathOptionValue) + { + string parsedValue = null; - public static string ParseExistingFolderPathOptionValue(string folderPathOptionValue) - { - string parsedValue = null; + if (string.IsNullOrWhiteSpace(folderPathOptionValue)) return null; + var fullFolderPath = PathUtil.GetFullPath(folderPathOptionValue); - if (!string.IsNullOrWhiteSpace(folderPathOptionValue)) - { - var fullFolderPath = PathUtil.GetFullPath(folderPathOptionValue); + if (PathUtil.DirectoryExists(fullFolderPath)) parsedValue = fullFolderPath; + return parsedValue; + } - if (PathUtil.DirectoryExists(fullFolderPath)) - { - parsedValue = fullFolderPath; - } - } - return parsedValue; - } + public static bool? ParseBooleanOptionValue(string booleanOptionValue) + { + bool? parsedValue = null; + + if (string.IsNullOrWhiteSpace(booleanOptionValue)) return null; + if (new[] { "TRUE", "YES" }.Any(s => + string.Equals(s, booleanOptionValue, StringComparison.CurrentCultureIgnoreCase))) + parsedValue = true; + else if (new[] { "FALSE", "NO" }.Any(s => + string.Equals( + s, booleanOptionValue, + StringComparison.CurrentCultureIgnoreCase))) + parsedValue = false; + + return parsedValue; + } - public static bool? ParseBooleanOptionValue(string booleanOptionValue) - { - bool? parsedValue = null; - - if (!string.IsNullOrWhiteSpace(booleanOptionValue)) - { - if (new[] { "TRUE", "YES" }.Any(s => s.ToUpper() == booleanOptionValue.ToUpper())) - { - parsedValue = true; - } - else if (new[] { "FALSE", "NO" }.Any(s => s.ToUpper() == booleanOptionValue.ToUpper())) - { - parsedValue = false; - } - } - - return parsedValue; - } - - public static RevitVersion.SupportedRevitVersion? ParseRevitVersionOptionValue(string revitVersionOptionValue) - { - RevitVersion.SupportedRevitVersion? revitVersion = null; + private static RevitVersion.SupportedRevitVersion? ParseRevitVersionOptionValue(string revitVersionOptionValue) + { + RevitVersion.SupportedRevitVersion? revitVersion = null; - if (!string.IsNullOrWhiteSpace(revitVersionOptionValue)) - { - if (RevitVersion.IsSupportedRevitVersionNumber(revitVersionOptionValue)) - { - revitVersion = RevitVersion.GetSupportedRevitVersion(revitVersionOptionValue); - } - } + if (string.IsNullOrWhiteSpace(revitVersionOptionValue)) return null; + if (RevitVersion.IsSupportedRevitVersionNumber(revitVersionOptionValue)) + revitVersion = RevitVersion.GetSupportedRevitVersion(revitVersionOptionValue); - return revitVersion; - } + return revitVersion; + } - public static BatchRvt.WorksetConfigurationOption? ParseWorksetsOptionValue(string worksetsOptionValue) - { - BatchRvt.WorksetConfigurationOption? worksetsOption = null; - - var parsedTextOptionValue = ParseTextOptionValue(worksetsOptionValue); - - if (parsedTextOptionValue == OPEN_ALL_WORKSETS_OPTION_VALUE) - { - worksetsOption = BatchRvt.WorksetConfigurationOption.OpenAllWorksets; - } - else if (parsedTextOptionValue == CLOSE_ALL_WORKSETS_OPTION_VALUE) - { - worksetsOption = BatchRvt.WorksetConfigurationOption.CloseAllWorksets; - } - else if (parsedTextOptionValue == OPEN_LAST_VIEWED_WORKSETS_OPTION_VALUE) - { - worksetsOption = BatchRvt.WorksetConfigurationOption.OpenLastViewed; - } - - return worksetsOption; - } - - public static Dictionary GetCommandLineOptions() - { - return OPTION_PARSERS - .Select( - kv => new { Option = kv.Key, Parser = kv.Value } - ).ToDictionary( - optionAndValue => optionAndValue.Option, - optionAndValue => ( - (optionAndValue.Parser != null) ? - optionAndValue.Parser(CommandLineUtil.GetCommandLineOption(optionAndValue.Option, expectOptionValue: true)) : - CommandLineUtil.HasCommandLineOption(optionAndValue.Option, expectOptionValue: false) - ) - ); - } - - public static IEnumerable GetInvalidOptions() - { - return CommandLineUtil.GetAllCommandLineOptionSwitches() - .Where(optionSwitch => !ALL_VALID_OPTONS.Contains(optionSwitch)) - .ToList(); - } + private static BatchRvt.WorksetConfigurationOption? ParseWorksetsOptionValue(string worksetsOptionValue) + { + var parsedTextOptionValue = ParseTextOptionValue(worksetsOptionValue); - public class Data + return parsedTextOptionValue switch { - // Command line options - public string SettingsFilePath = null; - public string LogFolderPath = null; - public string SessionId = null; - public string TaskData = null; - public string TestModeFolderPath = null; - - // Programmatic options - public BatchRvtSettings Settings = null; - public IEnumerable RevitFileList = null; - - // BatchRvt itself will set this to the path of the generated log file. - public string GeneratedLogFilePath = null; - } + OPEN_ALL_WORKSETS_OPTION_VALUE => BatchRvt.WorksetConfigurationOption.OpenAllWorksets, + CLOSE_ALL_WORKSETS_OPTION_VALUE => BatchRvt.WorksetConfigurationOption.CloseAllWorksets, + OPEN_LAST_VIEWED_WORKSETS_OPTION_VALUE => BatchRvt.WorksetConfigurationOption.OpenLastViewed, + _ => null + }; + + + } + + public static Dictionary GetCommandLineOptions() + { + return OPTION_PARSERS + .Select( + kv => new { Option = kv.Key, Parser = kv.Value } + ).ToDictionary( + optionAndValue => optionAndValue.Option, + optionAndValue => optionAndValue.Parser != null + ? optionAndValue.Parser(CommandLineUtil.GetCommandLineOption(optionAndValue.Option)) + : CommandLineUtil.HasCommandLineOption(optionAndValue.Option, false) + ); + } + + public static IEnumerable GetInvalidOptions() + { + return CommandLineUtil.GetAllCommandLineOptionSwitches() + .Where(optionSwitch => !ALL_VALID_OPTONS.Contains(optionSwitch)) + .ToList(); + } + + public class Data + { + // BatchRvt itself will set this to the path of the generated log file. + public string GeneratedLogFilePath = null; + public string LogFolderPath = null; + public IEnumerable RevitFileList = null; + public string SessionId = null; + + // Programmatic options + public BatchRvtSettings Settings = null; + + // Command line options + public string SettingsFilePath = null; + public string TaskData = null; + public string TestModeFolderPath = null; } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/ExcelUtil.cs b/BatchRvtUtil/ExcelUtil.cs index da86ae9..aab1e45 100644 --- a/BatchRvtUtil/ExcelUtil.cs +++ b/BatchRvtUtil/ExcelUtil.cs @@ -17,25 +17,24 @@ // along with this program. If not, see . // // + using System; -using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class ExcelUtil { - public static class ExcelUtil + public static bool IsExcelInstalled() { - public static bool IsExcelInstalled() - { - return Type.GetTypeFromProgID("Excel.Application") != null; - } + return Type.GetTypeFromProgID("Excel.Application") != null; + } - public static bool HasExcelExtension(string filePath) - { - var extension = Path.GetExtension(filePath).ToLower(); + public static bool HasExcelExtension(string filePath) + { + var extension = Path.GetExtension(filePath).ToLower(); - return new[] { ".xls", ".xlsx" }.Any(excelExtension => extension == excelExtension.ToLower()); - } + return new[] { ".xls", ".xlsx" }.Any(excelExtension => extension == excelExtension.ToLower()); } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/JsonUtil.cs b/BatchRvtUtil/JsonUtil.cs index 2f6b0fd..aabb252 100644 --- a/BatchRvtUtil/JsonUtil.cs +++ b/BatchRvtUtil/JsonUtil.cs @@ -17,34 +17,31 @@ // along with this program. If not, see . // // -using System; -using System.Collections.Generic; -using System.Linq; + using Newtonsoft.Json; using Newtonsoft.Json.Linq; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class JsonUtil { - public static class JsonUtil + public static string SerializeToJson(JObject jobject, bool prettyPrint = false) { - public static string SerializeToJson(JObject jobject, bool prettyPrint = false) - { - return prettyPrint ? jobject.ToString() : jobject.ToString(Formatting.None); - } + return prettyPrint ? jobject.ToString() : jobject.ToString(Formatting.None); + } - public static string SerializeToJson(JArray jarray, bool prettyPrint = false) - { - return prettyPrint ? jarray.ToString() : jarray.ToString(Formatting.None); - } + public static string SerializeToJson(JArray jarray, bool prettyPrint = false) + { + return prettyPrint ? jarray.ToString() : jarray.ToString(Formatting.None); + } - public static JObject DeserializeFromJson(string text) - { - return JsonConvert.DeserializeObject(text) as JObject; - } + public static JObject DeserializeFromJson(string text) + { + return JsonConvert.DeserializeObject(text) as JObject; + } - public static JArray DeserializeArrayFromJson(string text) - { - return JsonConvert.DeserializeObject(text) as JArray; - } + public static JArray DeserializeArrayFromJson(string text) + { + return JsonConvert.DeserializeObject(text) as JArray; } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/LogFile.cs b/BatchRvtUtil/LogFile.cs index e24f9fa..8d6738f 100644 --- a/BatchRvtUtil/LogFile.cs +++ b/BatchRvtUtil/LogFile.cs @@ -17,214 +17,201 @@ // along with this program. If not, see . // // + using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Linq; - using Newtonsoft.Json; using Newtonsoft.Json.Linq; -namespace BatchRvtUtil -{ - public class LogFile - { - private static readonly string SessionId = Guid.NewGuid().ToString(); - - private const string DateFormat = "dd/MM/yyyy"; - private const string TimeFormat = "HH:mm:ss"; +namespace BatchRvtUtil; - private readonly string logFolderPath_; - private readonly string logFileName_; - private readonly string logFilePath_; - private readonly string logName_; +public class LogFile +{ + private const string DateFormat = "dd/MM/yyyy"; + private const string TimeFormat = "HH:mm:ss"; + private static readonly string SessionId = Guid.NewGuid().ToString(); + private readonly string logFileName_; + private readonly string logFilePath_; - private StreamWriter appendTextStreamWriter_ = null; + private readonly string logFolderPath_; + private readonly string logName_; - public LogFile(string logName, string logFolderPath, bool includeUsernamePrefix = true) - { - this.logFolderPath_ = logFolderPath; - this.logName_ = logName; + private StreamWriter appendTextStreamWriter_; - var logFilenamePrefix = includeUsernamePrefix ? Environment.UserName : String.Empty; - var separator = (logFilenamePrefix != String.Empty) ? "_" : String.Empty; + public LogFile(string logName, string logFolderPath, bool includeUsernamePrefix = true) + { + logFolderPath_ = logFolderPath; + logName_ = logName; - this.logFileName_ = logFilenamePrefix + separator + logName + ".log"; + var logFilenamePrefix = includeUsernamePrefix ? Environment.UserName : string.Empty; + var separator = logFilenamePrefix != string.Empty ? "_" : string.Empty; - this.logFilePath_ = Path.Combine( - this.logFolderPath_, - this.logFileName_ - ); - } + logFileName_ = logFilenamePrefix + separator + logName + ".log"; - public void Open() - { - Close(); + logFilePath_ = Path.Combine( + logFolderPath_, + logFileName_ + ); + } - try - { - appendTextStreamWriter_ = new FileInfo(this.logFilePath_).AppendText(); - } - catch (Exception) - { - appendTextStreamWriter_ = null; - } - } + private void Open() + { + Close(); - public static string GetSerializedLogEntry(DateTime dateTime, string sessionId, object message) + try { - return SerializeAsJson( - GetLogObject(dateTime, sessionId, message) - ); + appendTextStreamWriter_ = new FileInfo(logFilePath_).AppendText(); } - - public string GetLogFilePath() + catch (Exception) { - return this.logFilePath_; + appendTextStreamWriter_ = null; } + } - private static object GetLogObject(DateTime dateTime, string sessionId, object message) - { - var utcDateTime = dateTime.ToUniversalTime(); + private static string GetSerializedLogEntry(DateTime dateTime, string sessionId, object message) + { + return SerializeAsJson( + GetLogObject(dateTime, sessionId, message) + ); + } - var logEntry = new - { - date = new - { - local = dateTime.ToString(DateFormat), - utc = utcDateTime.ToString(DateFormat) - }, - time = new - { - local = dateTime.ToString(TimeFormat), - utc = utcDateTime.ToString(TimeFormat) - }, - sessionId = sessionId, - message = message - }; - - return logEntry; - } + public string GetLogFilePath() + { + return logFilePath_; + } - private static string SerializeAsJson(object logObject) - { - return JObject.FromObject(logObject).ToString(Formatting.None); - } + private static object GetLogObject(DateTime dateTime, string sessionId, object message) + { + var utcDateTime = dateTime.ToUniversalTime(); - public bool WriteMessage(string sessionId, object message) + var logEntry = new { - bool success = false; - - bool useExistingOpenStream = (appendTextStreamWriter_ != null); - - try + date = new + { + local = dateTime.ToString(DateFormat), + utc = utcDateTime.ToString(DateFormat) + }, + time = new { - var dateTimeNow = DateTime.Now; + local = dateTime.ToString(TimeFormat), + utc = utcDateTime.ToString(TimeFormat) + }, + sessionId, + message + }; + + return logEntry; + } - string logEntry = null; + private static string SerializeAsJson(object logObject) + { + return JObject.FromObject(logObject).ToString(Formatting.None); + } - try - { - logEntry = GetSerializedLogEntry(dateTimeNow, sessionId, message); - } - catch (Exception e) - { - var errorMessage = new - { - error = "FAILED TO PARSE LOG MESSAGE OBJECT", - exceptionType = e.GetType(), - exceptionMessage = e.Message - }; + private bool WriteMessage(string sessionId, object message) + { + var success = false; - logEntry = GetSerializedLogEntry(dateTimeNow, sessionId, errorMessage); - } + var useExistingOpenStream = appendTextStreamWriter_ != null; - if (!useExistingOpenStream) - { - Open(); - } + try + { + var dateTimeNow = DateTime.Now; - appendTextStreamWriter_.WriteLine(logEntry); - appendTextStreamWriter_.Flush(); + string logEntry = null; - success = true; + try + { + logEntry = GetSerializedLogEntry(dateTimeNow, sessionId, message); } - catch (Exception) + catch (Exception e) { - success = false; + var errorMessage = new + { + error = "FAILED TO PARSE LOG MESSAGE OBJECT", + exceptionType = e.GetType(), + exceptionMessage = e.Message + }; + + logEntry = GetSerializedLogEntry(dateTimeNow, sessionId, errorMessage); } - if (!useExistingOpenStream) + if (!useExistingOpenStream) Open(); + + if (appendTextStreamWriter_ != null) { - Close(); + appendTextStreamWriter_.WriteLine(logEntry); + appendTextStreamWriter_.Flush(); } - return success; + success = true; } - - public bool WriteMessage(object message) + catch (Exception) { - return WriteMessage(GetSessionId(), message); + success = false; } - public void Close() - { - if (appendTextStreamWriter_ != null) - { - try - { - appendTextStreamWriter_.Close(); - } - catch (Exception) - { - } - appendTextStreamWriter_ = null; - } + if (!useExistingOpenStream) Close(); - return; - } + return success; + } + + public bool WriteMessage(object message) + { + return WriteMessage(GetSessionId(), message); + } - private static string GetSessionId() + private void Close() + { + if (appendTextStreamWriter_ == null) return; + try { - return SessionId; + appendTextStreamWriter_.Close(); } - - private static string ReadLineAsPlainText(string logLine, bool useUniversalTime) + catch (Exception) { - var plainTextLine = logLine; + // ignored + } - var jobject = JsonUtil.DeserializeFromJson(logLine); + appendTextStreamWriter_ = null; + } - if (jobject != null) - { - var dateString = jobject["date"][useUniversalTime ? "utc" : "local"]; - var timeString = jobject["time"][useUniversalTime ? "utc" : "local"]; - var message = jobject["message"]["message"]; + private static string GetSessionId() + { + return SessionId; + } - plainTextLine = dateString + " " + timeString + " : " + message; - } + private static string ReadLineAsPlainText(string logLine, bool useUniversalTime) + { + var plainTextLine = logLine; - return plainTextLine; - } + var jobject = JsonUtil.DeserializeFromJson(logLine); - public static IEnumerable ReadLinesAsPlainText(string logFilePath, bool useUniversalTime = false) - { - IEnumerable lines = null; + if (jobject == null) return plainTextLine; + var dateString = jobject["date"][useUniversalTime ? "utc" : "local"]; + var timeString = jobject["time"][useUniversalTime ? "utc" : "local"]; + var message = jobject["message"]["message"]; - try - { - lines = ( - File.ReadAllLines(logFilePath) - .Select(line => ReadLineAsPlainText(line, useUniversalTime)) - .ToList() - ); - } - catch (Exception e) - { - lines = null; - } + plainTextLine = dateString + " " + timeString + " : " + message; - return lines; + return plainTextLine; + } + + public static IEnumerable ReadLinesAsPlainText(string logFilePath, bool useUniversalTime = false) + { + try + { + return File.ReadAllLines(logFilePath) + .Select(line => ReadLineAsPlainText(line, useUniversalTime)) + .ToList(); + } + catch (Exception e) + { + return null; } + + } } \ No newline at end of file diff --git a/BatchRvtUtil/Network.cs b/BatchRvtUtil/Network.cs index a53499c..dbcd3c5 100644 --- a/BatchRvtUtil/Network.cs +++ b/BatchRvtUtil/Network.cs @@ -17,76 +17,79 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +/// +/// This class is used by Python scripts +/// +public static class Network { - public static class Network + private static IEnumerable GetGatewayAddresses( + NetworkInterface networkInterface + ) { - public static IEnumerable GetGatewayAddresses( - NetworkInterface networkInterface - ) - { - return networkInterface - .GetIPProperties() - .GatewayAddresses - .Select(ga => ga.Address); - } - - public static IEnumerable GetGatewayAddresses() - { - var gatewayAddresses = Enumerable.Empty(); + return networkInterface + .GetIPProperties() + .GatewayAddresses + .Select(ga => ga.Address); + } - try - { - var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces() - .Where(ni => ni.NetworkInterfaceType != NetworkInterfaceType.Loopback); + public static IEnumerable GetGatewayAddresses() + { + IEnumerable gatewayAddresses; - gatewayAddresses = networkInterfaces - .SelectMany(GetGatewayAddresses) - .ToList(); - } - catch (Exception) - { - gatewayAddresses = Enumerable.Empty(); - } + try + { + var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces() + .Where(ni => ni.NetworkInterfaceType != NetworkInterfaceType.Loopback); - return gatewayAddresses; + gatewayAddresses = networkInterfaces + .SelectMany(GetGatewayAddresses) + .ToList(); } - - public static IEnumerable GetIPAddresses( - NetworkInterface networkInterface - ) + catch (Exception) { - return networkInterface - .GetIPProperties() - .UnicastAddresses - .Select(ua => ua.Address); + gatewayAddresses = Enumerable.Empty(); } - public static IEnumerable GetIPAddresses() - { - var ipAddresses = Enumerable.Empty(); + return gatewayAddresses; + } + + private static IEnumerable GetIPAddresses( + NetworkInterface networkInterface + ) + { + return networkInterface + .GetIPProperties() + .UnicastAddresses + .Select(ua => ua.Address); + } - try - { - var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces() - .Where(ni => ni.NetworkInterfaceType != NetworkInterfaceType.Loopback); + public static IEnumerable GetIPAddresses() + { + IEnumerable ipAddresses; - ipAddresses = networkInterfaces - .SelectMany(GetIPAddresses) - .ToList(); - } - catch (Exception) - { - ipAddresses = Enumerable.Empty(); - } + try + { + var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces() + .Where(ni => ni.NetworkInterfaceType != NetworkInterfaceType.Loopback); - return ipAddresses; + ipAddresses = networkInterfaces + .SelectMany(GetIPAddresses) + .ToList(); } + catch (Exception) + { + ipAddresses = Enumerable.Empty(); + } + + return ipAddresses; } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/PathUtil.cs b/BatchRvtUtil/PathUtil.cs index c914b50..eafd70d 100644 --- a/BatchRvtUtil/PathUtil.cs +++ b/BatchRvtUtil/PathUtil.cs @@ -17,252 +17,221 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; using BatchRvt.ScriptHost; using ScriptingHosting = Microsoft.Scripting.Hosting; using IronPythonHosting = IronPython.Hosting; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class PathUtil { - public static class PathUtil + private static ScriptingHosting.ScriptEngine _engine; + private static ScriptingHosting.ScriptScope _pathUtilModuleScope; + private static ScriptingHosting.ScriptScope _revitFileListModuleScope; + private static ScriptingHosting.ScriptScope _revitFileVersionModuleScope; + private static dynamic _pythonFunctionExpandedFullNetworkPath; + private static dynamic _pythonFunctionRevitFileInfo; + private static dynamic _pythonFunctionGetRevitVersionNumberTextFromRevitVersionText; + + public static bool FileExists(string filePath) { - private static ScriptingHosting.ScriptEngine engine; - private static ScriptingHosting.ScriptScope pathUtilModuleScope; - private static ScriptingHosting.ScriptScope revitFileListModuleScope; - private static ScriptingHosting.ScriptScope revitFileVersionModuleScope; - private static dynamic PYTHON_FUNCTION_ExpandedFullNetworkPath; - private static dynamic PYTHON_FUNCTION_RevitFileInfo; - private static dynamic PYTHON_FUNCTION_GetRevitVersionNumberTextFromRevitVersionText; - - public static bool FileExists(string filePath) - { - return File.Exists(filePath); - } + return File.Exists(filePath); + } - public static bool DirectoryExists(string folderPath) - { - return Directory.Exists(folderPath); - } + public static bool DirectoryExists(string folderPath) + { + return Directory.Exists(folderPath); + } - public static string GetFullPath(string path) - { - return Path.GetFullPath(path); - } + public static string GetFullPath(string path) + { + return Path.GetFullPath(path); + } - public static string GetLocalAppDataFolderPath() - { - return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - } + public static string GetLocalAppDataFolderPath() + { + return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + } - public static string GetExistingFileDirectoryPath(string existingFilePath) - { - string initialDirectory = null; + public static string GetExistingFileDirectoryPath(string existingFilePath) + { + return File.Exists(existingFilePath) ? Path.GetDirectoryName(existingFilePath) : null; + } - if (File.Exists(existingFilePath)) - { - initialDirectory = Path.GetDirectoryName(existingFilePath); - } + public static bool HasExtension(string filePath, string extension) + { + return string.Equals(Path.GetExtension(filePath), extension, StringComparison.CurrentCultureIgnoreCase); + } - return initialDirectory; - } + private static T IgnoringPathExceptions(Func func) + { + var result = default(T); - public static string GetFileDirectoryName(string filePath) + try { - return new FileInfo(filePath).Directory.Name; + result = func(); } - - public static bool HasExtension(string filePath, string extension) + catch (UnauthorizedAccessException e) { - return Path.GetExtension(filePath).ToLower() == extension.ToLower(); + // Do nothing. } - - private static void IgnoringPathExceptions(Action action) + catch (PathTooLongException e) { - IgnoringPathExceptions( - () => { - action(); - return true; // dummy return type/value. - } - ); - - return; + // Do nothing. } - - private static T IgnoringPathExceptions(Func func) + catch (IOException e) { - var result = default(T); + // Do nothing. + } - try - { - result = func(); - } - catch (UnauthorizedAccessException e) - { - // Do nothing. - } - catch (PathTooLongException e) - { - // Do nothing. - } - catch (IOException e) + return result; + } + + public static IEnumerable SafeEnumerateFiles(string root, string pattern, SearchOption searchOption) + { + // NOTE: DirectoryInfo can throw path-related exceptions, hence the use of IgnoringPathExceptions here. + return IgnoringPathExceptions( + () => SafeEnumerateFiles(new DirectoryInfo(root), pattern, searchOption)) ?? Enumerable.Empty(); + } + + // See https://stackoverflow.com/questions/13130052/directoryinfo-enumeratefiles-causes-unauthorizedaccessexception-and-other + private static IEnumerable SafeEnumerateFiles(DirectoryInfo root, string pattern, + SearchOption searchOption) + { + if (root is not { Exists: true }) yield break; + var topLevelFilePaths = IgnoringPathExceptions( + () => { - // Do nothing. + return root + .EnumerateFiles(pattern, SearchOption.TopDirectoryOnly) + .Select(fileInfo => fileInfo.FullName) + .ToList(); // Ensures these are fully enumerate here so any exceptions are caught. } + ); - return result; - } - - public static IEnumerable SafeEnumerateFiles(string root, string pattern, SearchOption searchOption) - { - // NOTE: DirectoryInfo can throw path-related exceptions, hence the use of IgnoringPathExceptions here. - return IgnoringPathExceptions( - () => - { - return SafeEnumerateFiles(new DirectoryInfo(root), pattern, searchOption); - } - ) ?? Enumerable.Empty(); - } + foreach (var filePath in topLevelFilePaths ?? Enumerable.Empty()) yield return filePath; - // See https://stackoverflow.com/questions/13130052/directoryinfo-enumeratefiles-causes-unauthorizedaccessexception-and-other - public static IEnumerable SafeEnumerateFiles(DirectoryInfo root, string pattern, SearchOption searchOption) + if (searchOption != SearchOption.AllDirectories) yield break; { - if (root != null && root.Exists) - { - var topLevelFilePaths = IgnoringPathExceptions( - () => { - return root - .EnumerateFiles(pattern, SearchOption.TopDirectoryOnly) - .Select(fileInfo => fileInfo.FullName) - .ToList(); // Ensures these are fully enumerate here so any exceptions are caught. - } - ); - - foreach (var filePath in (topLevelFilePaths ?? Enumerable.Empty())) + var subFolderFilePaths = IgnoringPathExceptions( + () => { - yield return filePath; - } + var topLevelFolderPaths = root + .EnumerateDirectories("*", SearchOption.TopDirectoryOnly) + .ToList(); // Ensures these are fully enumerate here so any exceptions are caught. - if (searchOption == SearchOption.AllDirectories) - { - var subFolderFilePaths = IgnoringPathExceptions( - () => { - var topLevelFolderPaths = root - .EnumerateDirectories("*", SearchOption.TopDirectoryOnly) - .ToList(); // Ensures these are fully enumerate here so any exceptions are caught. - - return topLevelFolderPaths.SelectMany(dir => SafeEnumerateFiles(dir, pattern, searchOption)); - } - ); - - foreach (var filePath in (subFolderFilePaths ?? Enumerable.Empty())) - { - yield return filePath; - } + return topLevelFolderPaths.SelectMany(dir => + SafeEnumerateFiles(dir, pattern, searchOption)); } - } - } + ); - public static IEnumerable SafeEnumerateFolders(string root, string pattern, SearchOption searchOption) - { - // NOTE: DirectoryInfo can throw path-related exceptions, hence the use of IgnoringPathExceptions here. - return IgnoringPathExceptions( - () => - { - return SafeEnumerateFolders(new DirectoryInfo(root), pattern, searchOption); - } - ) ?? Enumerable.Empty(); + foreach (var filePath in subFolderFilePaths ?? Enumerable.Empty()) yield return filePath; } + } - // See https://stackoverflow.com/questions/13130052/directoryinfo-enumeratefiles-causes-unauthorizedaccessexception-and-other - public static IEnumerable SafeEnumerateFolders(DirectoryInfo root, string pattern, SearchOption searchOption) - { - if (root != null && root.Exists) + public static IEnumerable SafeEnumerateFolders(string root, string pattern, SearchOption searchOption) + { + // NOTE: DirectoryInfo can throw path-related exceptions, hence the use of IgnoringPathExceptions here. + return IgnoringPathExceptions( + () => SafeEnumerateFolders(new DirectoryInfo(root), pattern, searchOption)) ?? Enumerable.Empty(); + } + + // See https://stackoverflow.com/questions/13130052/directoryinfo-enumeratefiles-causes-unauthorizedaccessexception-and-other + private static IEnumerable SafeEnumerateFolders(DirectoryInfo root, string pattern, + SearchOption searchOption) + { + if (root is not { Exists: true }) yield break; + var topLevelFolderPaths = IgnoringPathExceptions( + () => { - var topLevelFolderPaths = IgnoringPathExceptions( - () => { - return root - .EnumerateDirectories(pattern, SearchOption.TopDirectoryOnly) - .Select(folderInfo => folderInfo.FullName) - .ToList(); // Ensures these are fully enumerate here so any exceptions are caught. - } - ); - - foreach (var folderPath in (topLevelFolderPaths ?? Enumerable.Empty())) - { - yield return folderPath; - } + return root + .EnumerateDirectories(pattern, SearchOption.TopDirectoryOnly) + .Select(folderInfo => folderInfo.FullName) + .ToList(); // Ensures these are fully enumerate here so any exceptions are caught. + } + ); + + foreach (var folderPath in topLevelFolderPaths ?? Enumerable.Empty()) yield return folderPath; - if (searchOption == SearchOption.AllDirectories) + if (searchOption != SearchOption.AllDirectories) yield break; + { + var subFolderFolderPaths = IgnoringPathExceptions( + () => { - var subFolderFolderPaths = IgnoringPathExceptions( - () => { - var subFolderPaths = root - .EnumerateDirectories("*", SearchOption.TopDirectoryOnly) - .ToList(); // Ensures these are fully enumerate here so any exceptions are caught. - - return subFolderPaths.SelectMany(dir => SafeEnumerateFolders(dir, pattern, searchOption)); - } - ); - - foreach (var folderPath in (subFolderFolderPaths ?? Enumerable.Empty())) - { - yield return folderPath; - } + var subFolderPaths = root + .EnumerateDirectories("*", SearchOption.TopDirectoryOnly) + .ToList(); // Ensures these are fully enumerate here so any exceptions are caught. + + return subFolderPaths.SelectMany(dir => SafeEnumerateFolders(dir, pattern, searchOption)); } - } + ); + + foreach (var folderPath in subFolderFolderPaths ?? Enumerable.Empty()) + yield return folderPath; } + } - private static void InitPythonFunctions() - { - bool needToAddSearchPath = (engine == null); + private static void InitPythonFunctions() + { + var needToAddSearchPath = _engine == null; - engine = engine ?? ScriptUtil.CreatePythonEngine(); + _engine = _engine ?? ScriptUtil.CreatePythonEngine(); - if (needToAddSearchPath) - { - var scriptsFolderPath = BatchRvt.GetBatchRvtScriptsFolderPath(); + if (needToAddSearchPath) + { + var scriptsFolderPath = BatchRvt.GetBatchRvtScriptsFolderPath(); - ScriptUtil.AddSearchPaths(engine, new[] { scriptsFolderPath }); - } + ScriptUtil.AddSearchPaths(_engine, new[] { scriptsFolderPath }); + } - pathUtilModuleScope = pathUtilModuleScope ?? IronPythonHosting.Python.ImportModule(engine, "path_util"); - PYTHON_FUNCTION_ExpandedFullNetworkPath = PYTHON_FUNCTION_ExpandedFullNetworkPath ?? pathUtilModuleScope.GetVariable("ExpandedFullNetworkPath"); + _pathUtilModuleScope = _pathUtilModuleScope ?? IronPythonHosting.Python.ImportModule(_engine, "path_util"); + _pythonFunctionExpandedFullNetworkPath = _pythonFunctionExpandedFullNetworkPath ?? + _pathUtilModuleScope.GetVariable("ExpandedFullNetworkPath"); - revitFileListModuleScope = revitFileListModuleScope ?? IronPythonHosting.Python.ImportModule(engine, "revit_file_list"); - PYTHON_FUNCTION_RevitFileInfo = PYTHON_FUNCTION_RevitFileInfo ?? revitFileListModuleScope.GetVariable("RevitFileInfo"); + _revitFileListModuleScope = _revitFileListModuleScope ?? + IronPythonHosting.Python.ImportModule(_engine, "revit_file_list"); + _pythonFunctionRevitFileInfo = + _pythonFunctionRevitFileInfo ?? _revitFileListModuleScope.GetVariable("RevitFileInfo"); - revitFileVersionModuleScope = revitFileVersionModuleScope ?? IronPythonHosting.Python.ImportModule(engine, "revit_file_version"); - PYTHON_FUNCTION_GetRevitVersionNumberTextFromRevitVersionText = PYTHON_FUNCTION_GetRevitVersionNumberTextFromRevitVersionText ?? revitFileVersionModuleScope.GetVariable("GetRevitVersionNumberTextFromRevitVersionText"); - } + _revitFileVersionModuleScope = _revitFileVersionModuleScope ?? + IronPythonHosting.Python.ImportModule(_engine, "revit_file_version"); + _pythonFunctionGetRevitVersionNumberTextFromRevitVersionText = + _pythonFunctionGetRevitVersionNumberTextFromRevitVersionText ?? + _revitFileVersionModuleScope.GetVariable("GetRevitVersionNumberTextFromRevitVersionText"); + } - private static string ExpandedFullNetworkPath(string fullPath) - { - return (PYTHON_FUNCTION_ExpandedFullNetworkPath(fullPath) as string) ?? string.Empty; - } + private static string ExpandedFullNetworkPath(string fullPath) + { + return _pythonFunctionExpandedFullNetworkPath(fullPath) as string ?? string.Empty; + } - public static IEnumerable EnumerateExpandedFullNetworkPaths(IEnumerable fullPaths) - { - InitPythonFunctions(); + public static IEnumerable EnumerateExpandedFullNetworkPaths(IEnumerable fullPaths) + { + InitPythonFunctions(); - return fullPaths.Select(ExpandedFullNetworkPath); - } + return fullPaths.Select(ExpandedFullNetworkPath); + } - private static string[] GetRevitVersionTexts(string fullPath) - { - var revitVersionText = (PYTHON_FUNCTION_RevitFileInfo(fullPath).TryGetRevitVersionText() as string) ?? string.Empty; - var revitVersionNumberText = (PYTHON_FUNCTION_GetRevitVersionNumberTextFromRevitVersionText(revitVersionText) as string) ?? string.Empty; + private static string[] GetRevitVersionTexts(string fullPath) + { + var revitVersionText = _pythonFunctionRevitFileInfo(fullPath).TryGetRevitVersionText() as string ?? + string.Empty; + var revitVersionNumberText = + _pythonFunctionGetRevitVersionNumberTextFromRevitVersionText(revitVersionText) as string ?? + string.Empty; - return new[] { revitVersionNumberText, revitVersionText }; - } + return new[] { revitVersionNumberText, revitVersionText }; + } - public static IEnumerable EnumerateRevitVersionTexts(IEnumerable fullPaths) - { - InitPythonFunctions(); + public static IEnumerable EnumerateRevitVersionTexts(IEnumerable fullPaths) + { + InitPythonFunctions(); - return fullPaths.Select(GetRevitVersionTexts); - } + return fullPaths.Select(GetRevitVersionTexts); } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/Properties/AssemblyInfo.cs b/BatchRvtUtil/Properties/AssemblyInfo.cs index e85dca3..274c371 100644 --- a/BatchRvtUtil/Properties/AssemblyInfo.cs +++ b/BatchRvtUtil/Properties/AssemblyInfo.cs @@ -17,6 +17,7 @@ // along with this program. If not, see . // // + using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -39,4 +40,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("c1f72c65-e710-4496-bbb2-40fefaea42c3")] +[assembly: Guid("c1f72c65-e710-4496-bbb2-40fefaea42c3")] \ No newline at end of file diff --git a/BatchRvtUtil/RevitFileScanning.cs b/BatchRvtUtil/RevitFileScanning.cs index 4758af7..d4cef0c 100644 --- a/BatchRvtUtil/RevitFileScanning.cs +++ b/BatchRvtUtil/RevitFileScanning.cs @@ -17,220 +17,167 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; using System.Text.RegularExpressions; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class RevitFileScanning { - public static class RevitFileScanning + public enum RevitFileType { - public enum RevitFileType { Project, Family, ProjectAndFamily } - - private const string ALL_FILES_WITH_AN_EXTENSION_PATTERN = "*.*"; - - private const string REVIT_PROJECT_FILE_EXTENSION = ".rvt"; - private const string REVIT_PROJECT_FILE_PATTERN = "*" + REVIT_PROJECT_FILE_EXTENSION; - private const string REVIT_FAMILY_FILE_EXTENSION = ".rfa"; - private const string REVIT_FAMILY_FILE_PATTERN = "*" + REVIT_FAMILY_FILE_EXTENSION; - - public static List FindAndExtractRevitFilesInfoWithProgressReporting( - string baseFolderPath, - SearchOption searchOption, - RevitFileType revitFileType, - bool expandNetworkPaths, - bool extractRevitVersionInfo, - bool ignoreRevitBackupFiles, - Func progressReporter - ) - { - var infoRows = new List(); - - progressReporter("Scanning for Revit files ..."); + Project, + Family, + ProjectAndFamily + } - var revitFilePaths = FindRevitFiles(baseFolderPath, searchOption, revitFileType, ignoreRevitBackupFiles, progressReporter); + private const string ALL_FILES_WITH_AN_EXTENSION_PATTERN = "*.*"; + + private const string REVIT_PROJECT_FILE_EXTENSION = ".rvt"; + private const string REVIT_PROJECT_FILE_PATTERN = "*" + REVIT_PROJECT_FILE_EXTENSION; + private const string REVIT_FAMILY_FILE_EXTENSION = ".rfa"; + private const string REVIT_FAMILY_FILE_PATTERN = "*" + REVIT_FAMILY_FILE_EXTENSION; + + public static IEnumerable FindAndExtractRevitFilesInfoWithProgressReporting( + string baseFolderPath, + SearchOption searchOption, + RevitFileType revitFileType, + bool expandNetworkPaths, + bool extractRevitVersionInfo, + bool ignoreRevitBackupFiles, + Func progressReporter + ) + { + var infoRows = new List(); - int numberOfRevitFilePaths = revitFilePaths.Count(); + progressReporter("Scanning for Revit files ..."); - bool cancelled = progressReporter(string.Empty); + var revitFilePaths = FindRevitFiles(baseFolderPath, searchOption, revitFileType, ignoreRevitBackupFiles, + progressReporter); - if (!cancelled) - { - if (expandNetworkPaths) - { - string expandingNetworkPathsMessagePrefix = "Expanding network paths"; + var filePaths = revitFilePaths as string[] ?? revitFilePaths.ToArray(); + var numberOfRevitFilePaths = filePaths.Count(); - var indexedExpandedRevitFilePaths = - PathUtil.EnumerateExpandedFullNetworkPaths(revitFilePaths) - .Select((revitFilePath, index) => Tuple.Create(index, revitFilePath)); + var cancelled = progressReporter(string.Empty); - var expandedRevitFilePaths = new List(); + if (cancelled) return infoRows; - foreach (var indexedExpandedRevitFilePath in indexedExpandedRevitFilePaths) - { - int index = indexedExpandedRevitFilePath.Item1; - string expandedRevitFilePath = indexedExpandedRevitFilePath.Item2; + if (expandNetworkPaths) + { + const string expandingNetworkPathsMessagePrefix = "Expanding network paths"; - progressReporter(expandingNetworkPathsMessagePrefix + " (" + (index + 1).ToString() + " of " + numberOfRevitFilePaths.ToString() + ") ..."); + var indexedExpandedRevitFilePaths = + PathUtil.EnumerateExpandedFullNetworkPaths(filePaths) + .Select((revitFilePath, index) => Tuple.Create(index, revitFilePath)); - expandedRevitFilePaths.Add(expandedRevitFilePath); - } + var expandedRevitFilePaths = new List(); - revitFilePaths = expandedRevitFilePaths; - } + foreach (var (index, expandedRevitFilePath) in indexedExpandedRevitFilePaths) + { + progressReporter(expandingNetworkPathsMessagePrefix + " (" + (index + 1) + " of " + + numberOfRevitFilePaths + ") ..."); - infoRows = revitFilePaths.Select(revitFilePath => new[] { revitFilePath }).ToList(); + expandedRevitFilePaths.Add(expandedRevitFilePath); + } - if (extractRevitVersionInfo) - { - string extractingNetworkPathsMessagePrefix = "Extracting Revit files version information"; + revitFilePaths = expandedRevitFilePaths; + } - var indexedRevitVersionTexts = - PathUtil.EnumerateRevitVersionTexts(revitFilePaths) - .Select((revitFilePath, index) => Tuple.Create(index, revitFilePath)); + infoRows = filePaths.Select(revitFilePath => new[] { revitFilePath }).ToList(); - var allRevitVersionTexts = new List(); + if (extractRevitVersionInfo) return infoRows; - foreach (var indexedRevitVersionText in indexedRevitVersionTexts) - { - int index = indexedRevitVersionText.Item1; - string[] revitVersionTexts = indexedRevitVersionText.Item2; + const string extractingNetworkPathsMessagePrefix = "Extracting Revit files version information"; - progressReporter(extractingNetworkPathsMessagePrefix + " (" + (index + 1).ToString() + " of " + numberOfRevitFilePaths.ToString() + ") ..."); + var indexedRevitVersionTexts = + PathUtil.EnumerateRevitVersionTexts(filePaths) + .Select((revitFilePath, index) => Tuple.Create(index, revitFilePath)); - allRevitVersionTexts.Add(revitVersionTexts); - } + var allRevitVersionTexts = new List(); - infoRows = ( - revitFilePaths - .Zip( - allRevitVersionTexts, - (revitFilePath, revitVersionTexts) => new[] { revitFilePath, revitVersionTexts[0], revitVersionTexts[1] } - ) - .ToList() - ); - } - } + foreach (var (index, revitVersionTexts) in indexedRevitVersionTexts) + { + progressReporter(extractingNetworkPathsMessagePrefix + " (" + (index + 1) + " of " + + numberOfRevitFilePaths + ") ..."); - return infoRows; + allRevitVersionTexts.Add(revitVersionTexts); } - public static IEnumerable FindRevitFiles( - string folderPath, - SearchOption searchOption, - RevitFileType revitFileType, - bool ignoreRevitBackups, - Func progressReporter + infoRows = filePaths + .Zip( + allRevitVersionTexts, + (revitFilePath, revitVersionTexts) => + new[] { revitFilePath, revitVersionTexts[0], revitVersionTexts[1] } ) - { - var searchFilePattern = ALL_FILES_WITH_AN_EXTENSION_PATTERN; + .ToList(); - if (revitFileType == RevitFileType.Project) - { - searchFilePattern = REVIT_PROJECT_FILE_PATTERN; - } - else if (revitFileType == RevitFileType.Family) - { - searchFilePattern = REVIT_FAMILY_FILE_PATTERN; - } - else if (revitFileType == RevitFileType.ProjectAndFamily) - { - searchFilePattern = ALL_FILES_WITH_AN_EXTENSION_PATTERN; - } - var foldersToScan = Enumerable.Empty(); - - if (searchOption == SearchOption.AllDirectories) - { - foldersToScan = ( - new[] { folderPath } - .Concat(PathUtil.SafeEnumerateFolders(folderPath, "*", SearchOption.AllDirectories)) - ); - } - else - { - foldersToScan = new[] { folderPath }; - } + return infoRows; + } - var revitFilePaths = new List(); + private static IEnumerable FindRevitFiles( + string folderPath, + SearchOption searchOption, + RevitFileType revitFileType, + bool ignoreRevitBackups, + Func progressReporter + ) + { + var searchFilePattern = ALL_FILES_WITH_AN_EXTENSION_PATTERN; - foreach (var folderToScan in foldersToScan) - { - bool cancelled = progressReporter(folderToScan); + if (revitFileType == RevitFileType.Project) + searchFilePattern = REVIT_PROJECT_FILE_PATTERN; + else if (revitFileType == RevitFileType.Family) + searchFilePattern = REVIT_FAMILY_FILE_PATTERN; + else if (revitFileType == RevitFileType.ProjectAndFamily) + searchFilePattern = ALL_FILES_WITH_AN_EXTENSION_PATTERN; - if (cancelled) - { - break; - } + IEnumerable foldersToScan; - revitFilePaths.AddRange( - PathUtil.SafeEnumerateFiles(folderToScan, searchFilePattern, SearchOption.TopDirectoryOnly) - .Where(filePath => HasRevitFileExtension(filePath, ignoreRevitBackups)) - ); - } + if (searchOption == SearchOption.AllDirectories) + foldersToScan = new[] { folderPath } + .Concat(PathUtil.SafeEnumerateFolders(folderPath, "*", SearchOption.AllDirectories)); + else + foldersToScan = new[] { folderPath }; - return revitFilePaths; - } + var revitFilePaths = new List(); - public static bool HasRevitProjectFileExtension(string filePath, bool ignoreRevitBackups) + foreach (var folderToScan in foldersToScan) { - var extension = Path.GetExtension(filePath).ToLower(); + var cancelled = progressReporter(folderToScan); - if (ignoreRevitBackups && IsBackupFile(filePath)) - { - return false; - } - else - { - return extension.ToLower() == REVIT_PROJECT_FILE_EXTENSION; - } - } + if (cancelled) break; - public static bool HasRevitFamilyFileExtension(string filePath, bool ignoreRevitBackups) - { - var extension = Path.GetExtension(filePath).ToLower(); - - if (ignoreRevitBackups && IsBackupFile(filePath)) - { - return false; - } - else - { - return extension.ToLower() == REVIT_FAMILY_FILE_EXTENSION; - } + revitFilePaths.AddRange( + PathUtil.SafeEnumerateFiles(folderToScan, searchFilePattern, SearchOption.TopDirectoryOnly) + .Where(filePath => HasRevitFileExtension(filePath, ignoreRevitBackups)) + ); } - public static bool HasRevitFileExtension(string filePath, bool ignoreRevitBackups) - { - var extension = Path.GetExtension(filePath).ToLower(); + return revitFilePaths; + } - if (ignoreRevitBackups && IsBackupFile(filePath)) - { - return false; - } - else - { - return new[] { - REVIT_PROJECT_FILE_EXTENSION, - REVIT_FAMILY_FILE_EXTENSION - }.Any(revitExtension => extension == revitExtension.ToLower()); - } - } + private static bool HasRevitFileExtension(string filePath, bool ignoreRevitBackups) + { + var extension = Path.GetExtension(filePath).ToLower(); - private static bool IsBackupFile(string filePath) + if (ignoreRevitBackups && IsBackupFile(filePath)) + return false; + return new[] { - string pattern = "\\.\\d\\d\\d\\d\\.(rvt|rfa)$"; - if (Regex.IsMatch(filePath, pattern)) - { - // This is a backup version of the file (ie. .0001.rvt/rfa) so skip it. - return true; - } - else - { - return false; - } - } + REVIT_PROJECT_FILE_EXTENSION, + REVIT_FAMILY_FILE_EXTENSION + }.Any(revitExtension => extension == revitExtension.ToLower()); + } + + private static bool IsBackupFile(string filePath) + { + const string pattern = "\\.\\d\\d\\d\\d\\.(rvt|rfa)$"; + return Regex.IsMatch(filePath, pattern); + // This is a backup version of the file (ie. .0001.rvt/rfa) so skip it. } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/RevitVersion.cs b/BatchRvtUtil/RevitVersion.cs index 56c41f3..2181c25 100644 --- a/BatchRvtUtil/RevitVersion.cs +++ b/BatchRvtUtil/RevitVersion.cs @@ -17,216 +17,212 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; using Microsoft.Win32; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class RevitVersion { - public static class RevitVersion - { - public enum SupportedRevitVersion { - Revit2015 = 0, - Revit2016 = 1, - Revit2017 = 2, - Revit2018 = 3, - Revit2019 = 4, - Revit2020 = 5, - Revit2021 = 6, - Revit2022 = 7, - Revit2023 = 8 - } + public enum SupportedRevitVersion { + Revit2015 = 0, + Revit2016 = 1, + Revit2017 = 2, + Revit2018 = 3, + Revit2019 = 4, + Revit2020 = 5, + Revit2021 = 6, + Revit2022 = 7, + Revit2023 = 8, + Revit2024 = 9 + } - private const string REVIT_EXECUTABLE_FILE_NAME = "Revit.exe"; + private const string REVIT_EXECUTABLE_FILE_NAME = "Revit.exe"; - private static readonly Dictionary REVIT_ADDINS_RELATIVE_PATHS = - new Dictionary() - { - { SupportedRevitVersion.Revit2015, @".\Autodesk\Revit\Addins\2015" }, - { SupportedRevitVersion.Revit2016, @".\Autodesk\Revit\Addins\2016" }, - { SupportedRevitVersion.Revit2017, @".\Autodesk\Revit\Addins\2017" }, - { SupportedRevitVersion.Revit2018, @".\Autodesk\Revit\Addins\2018" }, - { SupportedRevitVersion.Revit2019, @".\Autodesk\Revit\Addins\2019" }, - { SupportedRevitVersion.Revit2020, @".\Autodesk\Revit\Addins\2020" }, - { SupportedRevitVersion.Revit2021, @".\Autodesk\Revit\Addins\2021" }, - { SupportedRevitVersion.Revit2022, @".\Autodesk\Revit\Addins\2022" }, - { SupportedRevitVersion.Revit2023, @".\Autodesk\Revit\Addins\2023" } - }; - - private static readonly Dictionary SUPPORTED_REVIT_VERSION_NUMBERS = - new Dictionary() - { - { SupportedRevitVersion.Revit2015, "2015" }, - { SupportedRevitVersion.Revit2016, "2016" }, - { SupportedRevitVersion.Revit2017, "2017" }, - { SupportedRevitVersion.Revit2018, "2018" }, - { SupportedRevitVersion.Revit2019, "2019" }, - { SupportedRevitVersion.Revit2020, "2020" }, - { SupportedRevitVersion.Revit2021, "2021" }, - { SupportedRevitVersion.Revit2022, "2022" }, - { SupportedRevitVersion.Revit2023, "2023" } - }; - - private static Dictionary REVIT_EXECUTABLE_FOLDER_PATHS() + private static readonly Dictionary REVIT_ADDINS_RELATIVE_PATHS = + new Dictionary() { - var revitInstallPaths = new Dictionary(); - foreach (var versionName in Enum.GetNames(typeof(SupportedRevitVersion))) - { - SupportedRevitVersion enumOfVersion = (SupportedRevitVersion)Enum.Parse(typeof(SupportedRevitVersion), versionName); - - var installLocation = GetRevitInstallPath(enumOfVersion); - if (installLocation == null) - { - continue; - } - revitInstallPaths.Add(enumOfVersion, GetRevitInstallPath(enumOfVersion)); - } - - return revitInstallPaths; - } - - private static string GetRevitInstallPath(SupportedRevitVersion revitVersion) + { SupportedRevitVersion.Revit2015, @".\Autodesk\Revit\Addins\2015" }, + { SupportedRevitVersion.Revit2016, @".\Autodesk\Revit\Addins\2016" }, + { SupportedRevitVersion.Revit2017, @".\Autodesk\Revit\Addins\2017" }, + { SupportedRevitVersion.Revit2018, @".\Autodesk\Revit\Addins\2018" }, + { SupportedRevitVersion.Revit2019, @".\Autodesk\Revit\Addins\2019" }, + { SupportedRevitVersion.Revit2020, @".\Autodesk\Revit\Addins\2020" }, + { SupportedRevitVersion.Revit2021, @".\Autodesk\Revit\Addins\2021" }, + { SupportedRevitVersion.Revit2022, @".\Autodesk\Revit\Addins\2022" }, + { SupportedRevitVersion.Revit2023, @".\Autodesk\Revit\Addins\2023" }, + { SupportedRevitVersion.Revit2024, @".\Autodesk\Revit\Addins\2024" } + }; + + private static readonly Dictionary SUPPORTED_REVIT_VERSION_NUMBERS = + new Dictionary() { - var versionName = Enum.GetName(typeof(SupportedRevitVersion), revitVersion); - var version = versionName?.Remove(0, 5); - var appPath = $@"SOFTWARE\Autodesk\Revit\{version}"; - if (appPath == null) throw new ArgumentNullException(nameof(appPath)); - using (var sk = Registry.LocalMachine.OpenSubKey(appPath)) - { - if (sk is null) - { - return null; - } - - string revitSubkey = null; - foreach (var revitKey in sk.GetSubKeyNames()) - { - if (!revitKey.Contains("REVIT-")) - { - continue; - } - - revitSubkey = revitKey; - - } - if (revitSubkey == null) - { - return null; - } - - using (var rk = sk.OpenSubKey(revitSubkey)) - { - if (rk is null) - { - return null; - } - var displayName = rk.GetValue("ProductName"); - var installLocation = rk.GetValue("InstallationLocation"); - return installLocation?.ToString(); - } - } - } - - public static string GetRevitExecutableFolderPath(SupportedRevitVersion revitVersion) + { SupportedRevitVersion.Revit2015, "2015" }, + { SupportedRevitVersion.Revit2016, "2016" }, + { SupportedRevitVersion.Revit2017, "2017" }, + { SupportedRevitVersion.Revit2018, "2018" }, + { SupportedRevitVersion.Revit2019, "2019" }, + { SupportedRevitVersion.Revit2020, "2020" }, + { SupportedRevitVersion.Revit2021, "2021" }, + { SupportedRevitVersion.Revit2022, "2022" }, + { SupportedRevitVersion.Revit2023, "2023" }, + { SupportedRevitVersion.Revit2024, "2024" } + }; + + private static Dictionary REVIT_EXECUTABLE_FOLDER_PATHS() + { + var revitInstallPaths = new Dictionary(); + foreach (var versionName in Enum.GetNames(typeof(SupportedRevitVersion))) { + SupportedRevitVersion enumOfVersion = (SupportedRevitVersion)Enum.Parse(typeof(SupportedRevitVersion), versionName); - if (GetRevitInstallPath(revitVersion) == null) + var installLocation = GetRevitInstallPath(enumOfVersion); + if (installLocation == null) { - return null; + continue; } - return File.Exists((Path.Combine(GetRevitInstallPath(revitVersion) ?? string.Empty, REVIT_EXECUTABLE_FILE_NAME))) ? GetRevitInstallPath(revitVersion) : null; + revitInstallPaths.Add(enumOfVersion, GetRevitInstallPath(enumOfVersion)); } - public static List GetInstalledRevitVersions() + return revitInstallPaths; + } + + + public static string GetVersionNumber(SupportedRevitVersion supportedRevitVersion) + { + var versionName = Enum.GetName(typeof(SupportedRevitVersion), supportedRevitVersion); + return versionName?.Remove(0, 5); + } + + public static string GetAddinPath(SupportedRevitVersion supportedRevitVersion) + { + return $".\\Autodesk\\Revit\\Addins\\{GetVersionNumber(supportedRevitVersion)}"; + } + + public static string GetAddinName(SupportedRevitVersion supportedRevitVersion) + { + return $"BatchRvtAddin{GetVersionNumber(supportedRevitVersion)}.addin"; + } + + + private static readonly Dictionary REVIT_LOCAL_FOLDER_PATHS = + new Dictionary() { - return REVIT_EXECUTABLE_FOLDER_PATHS().Keys - .Where(IsRevitVersionInstalled) - .Where(BatchRvt.IsBatchRvtAddinInstalled) - .ToList(); - } + { SupportedRevitVersion.Revit2015, @"C:\REVIT_LOCAL2015" }, + { SupportedRevitVersion.Revit2016, @"C:\REVIT_LOCAL2016" }, + { SupportedRevitVersion.Revit2017, @"C:\REVIT_LOCAL2017" }, + { SupportedRevitVersion.Revit2018, @"C:\REVIT_LOCAL2018" }, + { SupportedRevitVersion.Revit2019, @"C:\REVIT_LOCAL2019" }, + { SupportedRevitVersion.Revit2020, @"C:\REVIT_LOCAL2020" }, + { SupportedRevitVersion.Revit2021, @"C:\REVIT_LOCAL2021" }, + { SupportedRevitVersion.Revit2022, @"C:\REVIT_LOCAL2022" }, + { SupportedRevitVersion.Revit2023, @"C:\REVIT_LOCAL2023" }, + { SupportedRevitVersion.Revit2024, @"C:\REVIT_LOCAL2024" } + }; + + + public static string GetRevitInstallPath(SupportedRevitVersion supportedRevitVersion) + { + var appPath = $@"SOFTWARE\Autodesk\Revit\{GetVersionNumber(supportedRevitVersion)}"; + if (appPath == null) throw new ArgumentNullException(nameof(appPath)); + using var sk = Registry.LocalMachine.OpenSubKey(appPath); + if (sk is null) return null; - private static readonly Dictionary REVIT_LOCAL_FOLDER_PATHS = - new Dictionary() - { - { SupportedRevitVersion.Revit2015, @"C:\REVIT_LOCAL2015" }, - { SupportedRevitVersion.Revit2016, @"C:\REVIT_LOCAL2016" }, - { SupportedRevitVersion.Revit2017, @"C:\REVIT_LOCAL2017" }, - { SupportedRevitVersion.Revit2018, @"C:\REVIT_LOCAL2018" }, - { SupportedRevitVersion.Revit2019, @"C:\REVIT_LOCAL2019" }, - { SupportedRevitVersion.Revit2020, @"C:\REVIT_LOCAL2020" }, - { SupportedRevitVersion.Revit2021, @"C:\REVIT_LOCAL2021" }, - { SupportedRevitVersion.Revit2022, @"C:\REVIT_LOCAL2022" }, - { SupportedRevitVersion.Revit2023, @"C:\REVIT_LOCAL2023" } - }; - - public static string GetRevitExecutableFilePath(SupportedRevitVersion revitVersion) + string revitSubkey = null; + foreach (var revitKey in sk.GetSubKeyNames()) { - var folderPath = GetRevitExecutableFolderPath(revitVersion); + if (!revitKey.Contains("REVIT-")) continue; - return (folderPath != null) ? Path.Combine(folderPath, REVIT_EXECUTABLE_FILE_NAME) : null; + revitSubkey = revitKey; } - public static string GetRevitLocalFolderPath(SupportedRevitVersion revitVersion) - { - return REVIT_LOCAL_FOLDER_PATHS.ContainsKey(revitVersion) ? - REVIT_LOCAL_FOLDER_PATHS[revitVersion] : null; - } + if (revitSubkey == null) return null; - public static string GetRevitLocalFilePath(SupportedRevitVersion revitVersion, string centralFilePath) - { - string localFilePath = null; + using var rk = sk.OpenSubKey(revitSubkey); + var installLocation = rk?.GetValue("InstallationLocation"); + return installLocation?.ToString(); + } - var localFolderPath = GetRevitLocalFolderPath(revitVersion); + public static string GetRevitExecutableFolderPath(SupportedRevitVersion revitVersion) + { + if (GetRevitInstallPath(revitVersion) == null) return null; + return File.Exists(Path.Combine(GetRevitInstallPath(revitVersion) ?? string.Empty, + REVIT_EXECUTABLE_FILE_NAME)) + ? GetRevitInstallPath(revitVersion) + : null; + } - if (localFolderPath != null) - { - var localFileName = Path.GetFileNameWithoutExtension(centralFilePath) + "_" + Environment.UserName + Path.GetExtension(centralFilePath); + public static string GetRevitLocalFolderPath(SupportedRevitVersion revitVersion) + { + return REVIT_LOCAL_FOLDER_PATHS.ContainsKey(revitVersion) ? + REVIT_LOCAL_FOLDER_PATHS[revitVersion] : null; + } - localFilePath = Path.Combine(localFolderPath, localFileName); - } + public static string GetRevitLocalFilePath(SupportedRevitVersion revitVersion, string centralFilePath) + { + string localFilePath = null; - return localFilePath; - } + var localFolderPath = GetRevitLocalFolderPath(revitVersion); - public static bool IsRevitVersionInstalled(SupportedRevitVersion revitVersion) + if (localFolderPath != null) { - return File.Exists(GetRevitExecutableFilePath(revitVersion)); - } + var localFileName = Path.GetFileNameWithoutExtension(centralFilePath) + "_" + Environment.UserName + Path.GetExtension(centralFilePath); - public static SupportedRevitVersion GetMinimumInstalledRevitVersion() - { - return GetInstalledRevitVersions().OrderBy(supportedRevitVersion => supportedRevitVersion).FirstOrDefault(); + localFilePath = Path.Combine(localFolderPath, localFileName); } - //public static List GetInstalledRevitVersions() - //{ - // return REVIT_EXECUTABLE_FOLDER_PATHS.Keys - // .Where(IsRevitVersionInstalled) - // .Where(BatchRvt.IsBatchRvtAddinInstalled) - // .ToList(); - //} + return localFilePath; + } - public static string GetRevitVersionText(SupportedRevitVersion revitVersion) - { - return SUPPORTED_REVIT_VERSION_NUMBERS.ContainsKey(revitVersion) ? - SUPPORTED_REVIT_VERSION_NUMBERS[revitVersion] : "UNSUPPORTED"; - } + public static IEnumerable GetInstalledRevitVersions() + { + return REVIT_EXECUTABLE_FOLDER_PATHS().Keys + .Where(IsRevitVersionInstalled) + .Where(BatchRvt.IsBatchRvtAddinInstalled) + .ToList(); + } - public static bool IsSupportedRevitVersionNumber(string revitVersionNumber) - { - return SUPPORTED_REVIT_VERSION_NUMBERS.ContainsValue(revitVersionNumber); - } + public static string GetRevitExecutableFilePath(SupportedRevitVersion revitVersion) + { + var folderPath = GetRevitExecutableFolderPath(revitVersion); - public static SupportedRevitVersion GetSupportedRevitVersion(string revitVersionNumber) - { - return SUPPORTED_REVIT_VERSION_NUMBERS.Single(keyValue => keyValue.Value == revitVersionNumber).Key; - } + return folderPath != null ? Path.Combine(folderPath, REVIT_EXECUTABLE_FILE_NAME) : null; + } - public static string GetRevitAddinsFolderPath(SupportedRevitVersion revitVersion, Environment.SpecialFolder specialFolder) - { - return Path.Combine(Environment.GetFolderPath(specialFolder), REVIT_ADDINS_RELATIVE_PATHS[revitVersion]); - } + public static bool IsRevitVersionInstalled(SupportedRevitVersion revitVersion) + { + return File.Exists(GetRevitExecutableFilePath(revitVersion)); + } + + public static SupportedRevitVersion GetMinimumInstalledRevitVersion() + { + return GetInstalledRevitVersions().OrderBy(supportedRevitVersion => supportedRevitVersion).FirstOrDefault(); + } + + + public static string GetRevitVersionText(SupportedRevitVersion supportedRevitVersion) + { + return GetVersionNumber(supportedRevitVersion) ?? "UNSUPPORTED"; + } + + public static bool IsSupportedRevitVersionNumber(string revitVersionNumber) + { + return Enum.TryParse($"Revit{revitVersionNumber}", out SupportedRevitVersion _); + } + + public static SupportedRevitVersion GetSupportedRevitVersion(string revitVersionNumber) + { + Enum.TryParse($"Revit{revitVersionNumber}", out SupportedRevitVersion version); + return version; + } + + public static string GetRevitAddinsFolderPath(SupportedRevitVersion revitVersion, + Environment.SpecialFolder specialFolder) + { + return Path.Combine(Environment.GetFolderPath(specialFolder), GetAddinPath(revitVersion)); } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/ScriptDataUtil.cs b/BatchRvtUtil/ScriptDataUtil.cs index 925f4ab..e58c5c2 100644 --- a/BatchRvtUtil/ScriptDataUtil.cs +++ b/BatchRvtUtil/ScriptDataUtil.cs @@ -99,29 +99,26 @@ public void Store(JObject jobject) public bool LoadFromFile(string filePath) { - bool success = false; + - if (File.Exists(filePath)) + if (!File.Exists(filePath)) return false; + try + { + var text = File.ReadAllText(filePath); + var jobject = JsonUtil.DeserializeFromJson(text); + this.persistentSettings.Load(jobject); + } + catch (Exception e) { - try - { - var text = File.ReadAllText(filePath); - var jobject = JsonUtil.DeserializeFromJson(text); - this.persistentSettings.Load(jobject); - success = true; - } - catch (Exception e) - { - success = false; - } + return false; } - return success; + return true; } public bool SaveToFile(string filePath) { - bool success = false; + var success = false; var jobject = new JObject(); @@ -173,37 +170,34 @@ public static IEnumerable LoadManyFromFile(string filePath) { List scriptDatas = null; - if (File.Exists(filePath)) + if (!File.Exists(filePath)) return (List)null; + try { - try - { - var text = File.ReadAllText(filePath); + var text = File.ReadAllText(filePath); - var jarray = JsonUtil.DeserializeArrayFromJson(text); + var jarray = JsonUtil.DeserializeArrayFromJson(text); - scriptDatas = new List(); + scriptDatas = new List(); - foreach (var jtoken in jarray) - { - var jobject = jtoken as JObject; + foreach (var jtoken in jarray) + { + var jobject = jtoken as JObject; - if (jobject != null) - { - var scriptData = new ScriptData(); + if (jobject == null) continue; + var scriptData = new ScriptData(); - scriptData.Load(jobject); + scriptData.Load(jobject); - scriptDatas.Add(scriptData); - } - } - } - catch (Exception e) - { - scriptDatas = null; // null on failure. + scriptDatas.Add(scriptData); } + return scriptDatas; + } + catch (Exception e) + { + return null; } - return scriptDatas; + } public static bool SaveManyToFile(string filePath, IEnumerable scriptDatas) @@ -243,7 +237,7 @@ public static bool SaveManyToFile(string filePath, IEnumerable scrip public static string GetUniqueScriptDataFilePath() { - string uniqueId = Guid.NewGuid().ToString(); + var uniqueId = Guid.NewGuid().ToString(); return Path.Combine( BatchRvt.GetDataFolderPath(), @@ -253,7 +247,7 @@ public static string GetUniqueScriptDataFilePath() public static string GetProgressRecordFilePath(string scriptDataFilePath) { - string uniqueId = ( + var uniqueId = ( Path.GetFileNameWithoutExtension(scriptDataFilePath) .Substring(SCRIPT_DATA_FILENAME_PREFIX.Length) ); diff --git a/BatchRvtUtil/Scripts/batch_rvt_monitor.py b/BatchRvtUtil/Scripts/batch_rvt_monitor.py index a02040d..a25a8a7 100644 --- a/BatchRvtUtil/Scripts/batch_rvt_monitor.py +++ b/BatchRvtUtil/Scripts/batch_rvt_monitor.py @@ -145,24 +145,25 @@ def GetSupportedRevitFiles(batchRvtConfig): unsupportedCount = len(unsupportedRevitFileList) unsupportedRevitFilePathCount = len(unsupportedRevitFilePathRevitFileList) + message = "" if nonExistentCount > 0: - Output() - Output("WARNING: The following Revit Files do not exist (" + str(nonExistentCount) + "):") + message += "\n" + message += "WARNING: The following Revit Files do not exist (" + str(nonExistentCount) + "):" for supportedRevitFileInfo in nonExistentRevitFileList: - batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo, Output) + message += batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo) if unsupportedCount > 0: - Output() - Output("WARNING: The following Revit Files are of an unsupported version (" + str(unsupportedCount) + "):") + message += "\n" + message += "WARNING: The following Revit Files are of an unsupported version (" + str(unsupportedCount) + "):" for supportedRevitFileInfo in unsupportedRevitFileList: - batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo, Output) + message += batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo) if unsupportedRevitFilePathCount > 0: - Output() - Output("WARNING: The following Revit Files have an unsupported file path (" + str(unsupportedRevitFilePathCount) + "):") + message += "\n" + message += "WARNING: The following Revit Files have an unsupported file path (" + str(unsupportedRevitFilePathCount) + "):" for supportedRevitFileInfo in unsupportedRevitFilePathRevitFileList: - batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo, Output) - + message += batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo) + Output(message) return supportedRevitFileList def InitializeScriptUtil(batchRvtConfig): @@ -316,10 +317,10 @@ def ProcessRevitFiles(batchRvtConfig, supportedRevitFileList): " of " + str(totalFilesCount) + ")" + " in Revit " + RevitVersion.GetRevitVersionText(revitVersion) + " session." ) - + message = "" for supportedRevitFileInfo in sessionRevitFiles: - batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo, Output) - + message += batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo) + Output(message) Output() Output("Starting Revit " + RevitVersion.GetRevitVersionText(revitVersion) + " session...") @@ -449,9 +450,10 @@ def RunBatchRevitTasks(batchRvtConfig): if not aborted: Output() Output("Revit Files for processing (" + str(supportedCount) + "):") + message = "" for supportedRevitFileInfo in supportedRevitFileList: - batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo, Output) - + message += batch_rvt_monitor_util.ShowSupportedRevitFileInfo(supportedRevitFileInfo) + Output(message) try: if batchRvtConfig.EnableDataExport: session_data_exporter.ExportSessionFilesData( diff --git a/BatchRvtUtil/Scripts/batch_rvt_monitor_util.py b/BatchRvtUtil/Scripts/batch_rvt_monitor_util.py index 15db960..09f22ce 100644 --- a/BatchRvtUtil/Scripts/batch_rvt_monitor_util.py +++ b/BatchRvtUtil/Scripts/batch_rvt_monitor_util.py @@ -43,32 +43,32 @@ REVIT_PROCESS_BEGIN_PROCESSING_TIMEOUT_IN_SECONDS = 5 * SECONDS_PER_MINUTE -def ShowSupportedRevitFileInfo(supportedRevitFileInfo, output): - output() +def ShowSupportedRevitFileInfo(supportedRevitFileInfo): + message = "\n" if supportedRevitFileInfo.IsCloudModel(): revitCloudModelInfo = supportedRevitFileInfo.GetRevitCloudModelInfo() projectGuidText = revitCloudModelInfo.GetProjectGuid().ToString() modelGuidText = revitCloudModelInfo.GetModelGuid().ToString() - output("\t" + "CLOUD MODEL") - output("\t" + "Project ID: " + projectGuidText) - output("\t" + "Model ID: " + modelGuidText) + message += ("\t" + "CLOUD MODEL\n") + message += ("\t" + "Project ID: " + projectGuidText + "\n") + message += ("\t" + "Model ID: " + modelGuidText + "\n") revitVersionText = supportedRevitFileInfo.TryGetRevitVersionText() revitVersionText = revitVersionText if not str.IsNullOrWhiteSpace(revitVersionText) else "NOT SPECIFIED!" - output("\t" + "Revit version: " + revitVersionText) + message += ("\t" + "Revit version: " + revitVersionText + "\n") else: revitFileInfo = supportedRevitFileInfo.GetRevitFileInfo() revitFilePath = revitFileInfo.GetFullPath() fileExists = revitFileInfo.Exists() fileSize = revitFileInfo.GetFileSize() fileSizeText = str.Format("{0:0.00}MB", fileSize / (1024.0 * 1024.0)) if fileSize is not None else "" - output("\t" + revitFilePath) - output("\t" + "File exists: " + ("YES" if fileExists else "NO")) - output("\t" + "File size: " + fileSizeText) + message += ("\t" + revitFilePath + "\n") + message += ("\t" + "File exists: " + ("YES" if fileExists else "NO") + "\n") + message += ("\t" + "File size: " + fileSizeText + "\n") if fileExists: revitVersionText = revitFileInfo.TryGetRevitVersionText() revitVersionText = revitVersionText if not str.IsNullOrWhiteSpace(revitVersionText) else "NOT DETECTED!" - output("\t" + "Revit version: " + revitVersionText) - return + message += ("\t" + "Revit version: " + revitVersionText + "\n") + return message def UsingClientHandle(serverStream, action): result = None diff --git a/BatchRvtUtil/Scripts/revit_dialog_detection.py b/BatchRvtUtil/Scripts/revit_dialog_detection.py index a049f32..8cfeddc 100644 --- a/BatchRvtUtil/Scripts/revit_dialog_detection.py +++ b/BatchRvtUtil/Scripts/revit_dialog_detection.py @@ -28,53 +28,54 @@ REVIT_DIALOG_MESSAGE_HANDLER_PREFIX = "[ REVIT DIALOG BOX HANDLER ]" -MODEL_UPGRADE_WINDOW_TITLE = "Model Upgrade" -LOAD_LINK_WINDOW_TITLE = "Load Link" -CHANGES_NOT_SAVED_TITLE = "Changes Not Saved" -CLOSE_PROJECT_WITHOUT_SAVING_TITLE = "Close Project Without Saving" -CERRAR_PROYECTO_SIN_GUARDAR = "Cerrar proyecto sin guardar" -SAVE_FILE_WINDOW_TITLE = "Save File" -EDITABLE_ELEMENTS_TITLE = "Editable Elements" AUTODESK_CUSTOMER_INVOLVEMENT_PROGRAM_TITLE = "Autodesk Customer Involvement Program" CAMBIOS_NO_GUARDADOS_TITLE = "Cambios no guardados" -ELEMENTS_LOST_ON_IMPORT_TITLE = "Elements Lost on Import" -REFERENCIAS_TITLE = "Referencias sin resolver" CAMBIOS_TITLE = "Cambios locales no sincronizados con archivo central" +CERRAR_PROYECTO_SIN_GUARDAR = "Cerrar proyecto sin guardar" +CHANGES_NOT_SAVED_TITLE = "Changes Not Saved" CHANGES_TITLE = "Local Changes Not Synchronized with Central" +CLOSE_PROJECT_WITHOUT_SAVING_TITLE = "Close Project Without Saving" +EDITABLE_ELEMENTS_TITLE = "Editable Elements" +ELEMENTS_LOST_ON_IMPORT_TITLE = "Elements Lost on Import" +LOAD_LINK_WINDOW_TITLE = "Load Link" +MODEL_UPGRADE_WINDOW_TITLE = "Model Upgrade" NWC_TITLE = "Navisworks NWC Exporter" +REFERENCIAS_TITLE = "Referencias sin resolver" REVIT_TITLE = "Revit" -OPENING_WORKSETS_TITLES = [ - "Worksets", - "Opening Worksets" - ] +SAVE_FILE_WINDOW_TITLE = "Save File" -DIRECTUI_CLASS_NAME = "DirectUIHWND" -CTRLNOTIFYSINK_CLASS_NAME = "CtrlNotifySink" + +ACEPTAR_BUTTON_TEXT = "Aceptar" +ALWAYS_LOAD_BUTTON_TEXT = "Always Load" BUTTON_CLASS_NAME = "Button" -STATIC_CONTROL_CLASS_NAME = "Static" +CANCEL_LINK_BUTTON_TEXT = "Cancel Link" CANCELAR_BUTTON_TEXT = "Cancelar" -CLOSE_BUTTON_TEXT = "Close" -CERRAR_BUTTON_TEXT = "Cerrar" -ACEPTAR_BUTTON_TEXT = "Aceptar" -CEDER_TODO_BUTTON_TEXT = "Ceder todos los elementos y subproyectos" CEDER_BUTTON_TEXT = "Ceder los elementos y subproyectos" -OK_BUTTON_TEXT = "OK" +CEDER_TODO_BUTTON_TEXT = "Ceder todos los elementos y subproyectos" +CERRAR_ARCHIVO_LOCAL_BUTTON_TEXT = "Cerrar el archivo local" +CERRAR_BUTTON_TEXT = "Cerrar" +CLOSE_BUTTON_TEXT = "Close" +CLOSE_LOCAL_FILE_BUTTON_TEXT = "Close the local file" +CTRLNOTIFYSINK_CLASS_NAME = "CtrlNotifySink" +DIRECTUI_CLASS_NAME = "DirectUIHWND" +DO_NOT_SAVE_THE_PROJECT_TEXT = "Do not save the project" IGNORAR_BUTTON_TEXT = "Ignorar y abrir el proyecto" -NO_GUARDAR_PROYECTO_BUTTON_TEXT = "No guardar el proyecto" NO_BUTTON_TEXT = "No" +NO_GUARDAR_PROYECTO_BUTTON_TEXT = "No guardar el proyecto" +OK_BUTTON_TEXT = "OK" +RHINO_SELECTION_BUTTON_TEXT = "Rhino 7" #Change this to target a different version of Rhino by default +STATIC_CONTROL_CLASS_NAME = "Static" YES_BUTTON_TEXT = "Yes" -ALWAYS_LOAD_BUTTON_TEXT = "Always Load" -CANCEL_LINK_BUTTON_TEXT = "Cancel Link" -DO_NOT_SAVE_THE_PROJECT_TEXT = "Do not save the project" -CERRAR_ARCHIVO_LOCAL_BUTTON_TEXT = "Cerrar el archivo local" -CLOSE_LOCAL_FILE_BUTTON_TEXT = "Close the local file" RELINQUISH_ALL_ELEMENTS_AND_WORKSETS_TEXT = "Relinquish all elements and worksets" RELINQUISH_ELEMENTS_AND_WORKSETS_TEXT = "Relinquish elements and worksets" HAVE_REPORTED_BATCH_RVT_ERROR_WINDOW_DETECTION = [False] - +OPENING_WORKSETS_TITLES = [ + "Worksets", + "Opening Worksets" + ] class RevitDialogInfo: def __init__(self, dialogHwnd): @@ -92,17 +93,18 @@ def __init__(self, dialogHwnd): return def SendButtonClick(buttons, output): - okButtons = ui_automation_util.FilterControlsByText(buttons, OK_BUTTON_TEXT) aceptarButtons = ui_automation_util.FilterControlsByText(buttons, ACEPTAR_BUTTON_TEXT) - ignorarButtons = ui_automation_util.FilterControlsByText(buttons, IGNORAR_BUTTON_TEXT) + alwaysLoadButtons = ui_automation_util.FilterControlsByText(buttons, ALWAYS_LOAD_BUTTON_TEXT) cederButtons = ui_automation_util.FilterControlsByText(buttons, CEDER_BUTTON_TEXT) cerrarButtons = ui_automation_util.FilterControlsByText(buttons, CERRAR_BUTTON_TEXT) - noGuardarButtons = ui_automation_util.FilterControlsByText(buttons, NO_GUARDAR_PROYECTO_BUTTON_TEXT) - closeButtons = ui_automation_util.FilterControlsByText(buttons, CLOSE_BUTTON_TEXT) - noButtons = ui_automation_util.FilterControlsByText(buttons, NO_BUTTON_TEXT) - alwaysLoadButtons = ui_automation_util.FilterControlsByText(buttons, ALWAYS_LOAD_BUTTON_TEXT) cerrarLocalButtons = ui_automation_util.FilterControlsByText(buttons, CERRAR_ARCHIVO_LOCAL_BUTTON_TEXT) + closeButtons = ui_automation_util.FilterControlsByText(buttons, CLOSE_BUTTON_TEXT) closeLocalButtons = ui_automation_util.FilterControlsByText(buttons, CLOSE_LOCAL_FILE_BUTTON_TEXT) + ignorarButtons = ui_automation_util.FilterControlsByText(buttons, IGNORAR_BUTTON_TEXT) + noButtons = ui_automation_util.FilterControlsByText(buttons, NO_BUTTON_TEXT) + noGuardarButtons = ui_automation_util.FilterControlsByText(buttons, NO_GUARDAR_PROYECTO_BUTTON_TEXT) + okButtons = ui_automation_util.FilterControlsByText(buttons, OK_BUTTON_TEXT) + rhino_selection_buttons = ui_automation_util.FilterControlsByText(buttons, RHINO_SELECTION_BUTTON_TEXT) if len(okButtons) == 1: targetButton = okButtons[0] @@ -112,6 +114,8 @@ def SendButtonClick(buttons, output): targetButton = noButtons[0] elif len(alwaysLoadButtons) == 1: targetButton = alwaysLoadButtons[0] + elif len(rhino_selection_buttons) == 1: + targetButton = rhino_selection_buttons[0] elif len(ignorarButtons) == 1: targetButton = ignorarButtons[0] elif len(noGuardarButtons) == 1: diff --git a/BatchRvtUtil/Scripts/revit_file_list.py b/BatchRvtUtil/Scripts/revit_file_list.py index 62ca0ac..1144aac 100644 --- a/BatchRvtUtil/Scripts/revit_file_list.py +++ b/BatchRvtUtil/Scripts/revit_file_list.py @@ -219,6 +219,8 @@ def __init__(self, revitFilePathData): revitVersionNumber = RevitVersion.SupportedRevitVersion.Revit2022 elif any(revitVersionText.StartsWith(prefix) for prefix in revit_file_version.REVIT_VERSION_TEXT_PREFIXES_2023): revitVersionNumber = RevitVersion.SupportedRevitVersion.Revit2023 + elif any(revitVersionText.StartsWith(prefix) for prefix in revit_file_version.REVIT_VERSION_TEXT_PREFIXES_2024): + revitVersionNumber = RevitVersion.SupportedRevitVersion.Revit2024 self.revitVersionText = revitVersionText self.revitVersionNumber = revitVersionNumber return diff --git a/BatchRvtUtil/Scripts/revit_file_version.py b/BatchRvtUtil/Scripts/revit_file_version.py index 97e27c4..890a5c9 100644 --- a/BatchRvtUtil/Scripts/revit_file_version.py +++ b/BatchRvtUtil/Scripts/revit_file_version.py @@ -206,6 +206,7 @@ def GenerateRevitVersionTextPrefixes(revitVersionNumberText, includeDisciplineVe REVIT_VERSION_TEXT_PREFIXES_2021 = GenerateRevitVersionTextPrefixes("2021") REVIT_VERSION_TEXT_PREFIXES_2022 = GenerateRevitVersionTextPrefixes("2022") REVIT_VERSION_TEXT_PREFIXES_2023 = GenerateRevitVersionTextPrefixes("2023") +REVIT_VERSION_TEXT_PREFIXES_2024 = GenerateRevitVersionTextPrefixes("2024") def GetRevitVersionNumberTextFromRevitVersionText(revitVersionText): revitVersionNumberText = None @@ -240,5 +241,7 @@ def StartsWithOneOfPrefixes(text, prefixes): revitVersionNumberText = "2022" elif StartsWithOneOfPrefixes(revitVersionText, REVIT_VERSION_TEXT_PREFIXES_2023): revitVersionNumberText = "2023" + elif StartsWithOneOfPrefixes(revitVersionText, REVIT_VERSION_TEXT_PREFIXES_2024): + revitVersionNumberText = "2024" return revitVersionNumberText diff --git a/BatchRvtUtil/Scripts/std_io_util.py b/BatchRvtUtil/Scripts/std_io_util.py index 7997066..371c0b3 100644 --- a/BatchRvtUtil/Scripts/std_io_util.py +++ b/BatchRvtUtil/Scripts/std_io_util.py @@ -47,10 +47,13 @@ def RestoreScriptOutput(): def Output(m="", msgId=""): timestamp = time_util.GetDateTimeNow().ToString("HH:mm:ss") - message = timestamp + " : " + (("[" + str(msgId) + "]" + " ") if msgId != "" else "") + m + "\n" + message = "" + for line in m.split("\n"): + message += timestamp + " : " + (("[" + str(msgId) + "]" + " ") if msgId != "" else "") + line + "\n" if SHOW_OUTPUT: ORIGINAL_STDOUT.write(message) if logging_util.LOG_FILE[0] is not None: logging_util.LOG_FILE[0].WriteMessage({ "msgId" : msgId, "message" : m }) return + diff --git a/BatchRvtUtil/SettingsUtil.cs b/BatchRvtUtil/SettingsUtil.cs index 8cce604..c0fbbf1 100644 --- a/BatchRvtUtil/SettingsUtil.cs +++ b/BatchRvtUtil/SettingsUtil.cs @@ -17,314 +17,305 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public interface IPersistent +{ + void Load(JObject jobject); + void Store(JObject jobject); +} + +public interface ISetting : IPersistent { - public interface IPersistent + string GetName(); + T GetValue(); + void SetValue(T value); +} + +public class Setting : ISetting +{ + private readonly Func _deserialize; + private readonly string _name; + private readonly Action _serialize; + private T _value; + + protected Setting(string name, Action serialize, Func deserialize, + T defaultValue) { - void Load(JObject jobject); - void Store(JObject jobject); + this._name = name; + this._serialize = serialize; + this._deserialize = deserialize; + _value = defaultValue; } - public interface ISetting : IPersistent + public string GetName() { - string GetName(); - T GetValue(); - void SetValue(T value); + return _name; } - public class Setting : ISetting + public void Load(JObject jobject) { - private readonly string name; - private readonly Action serialize; - private readonly Func deserialize; - private readonly T defaultValue; - private T value; + _value = _deserialize(jobject, _name); + } - public Setting(string name, Action serialize, Func deserialize, T defaultValue) - { - this.name = name; - this.serialize = serialize; - this.deserialize = deserialize; - this.defaultValue = defaultValue; - this.value = defaultValue; - } + public void Store(JObject jobject) + { + _serialize(jobject, _name, _value); + } - public string GetName() - { - return this.name; - } + public virtual T GetValue() + { + return _value; + } - public void Load(JObject jobject) - { - this.value = this.deserialize(jobject, this.name); - } + public virtual void SetValue(T value) + { + this._value = value; + } +} - public void Store(JObject jobject) - { - this.serialize(jobject, this.name, this.value); - } +public class OptionalSetting : Setting +{ + protected OptionalSetting(string name, Action serialize, Func deserialize, + T defaultValue) + : base( + name, + serialize, + (jobject, propertyName) => TryDeserialize(deserialize, jobject, propertyName, defaultValue), + defaultValue + ) + { + } + + private static T TryDeserialize(Func deserialize, JObject jobject, string propertyName, + T defaultValue) + { + var value = defaultValue; - public virtual T GetValue() + try { - return this.value; + value = deserialize(jobject, propertyName); } - - public virtual void SetValue(T value) + catch (Exception e) { - this.value = value; + // ignored } + + return value; } +} - public class OptionalSetting : Setting +public class BooleanSetting : OptionalSetting +{ + public BooleanSetting(string name) + : base(name, SetBooleanPropertyValue, GetBooleanPropertyValue, false) { - public OptionalSetting(string name, Action serialize, Func deserialize, T defaultValue) - : base( - name, - serialize, - (jobject, propertyName) => TryDeserialize(deserialize, jobject, propertyName, defaultValue), - defaultValue - ) - { - } - - private static T TryDeserialize(Func deserialize, JObject jobject, string propertyName, T defaultValue) - { - T value = defaultValue; + } - try - { - value = deserialize(jobject, propertyName); - } - catch (Exception e) - { - } + private static bool GetBooleanPropertyValue(JObject jobject, string propertyName) + { + return ((JValue)jobject[propertyName]).ToObject(); + } - return value; - } + private static void SetBooleanPropertyValue(JObject jobject, string propertyName, bool value) + { + jobject[propertyName] = value; } +} - public class BooleanSetting : OptionalSetting +public class IntegerSetting : OptionalSetting +{ + public IntegerSetting(string name) + : base(name, SetIntegerPropertyValue, GetIntegerPropertyValue, 0) { - public BooleanSetting(string name) - : base(name, SetBooleanPropertyValue, GetBooleanPropertyValue, false) - { - } + } - private static bool GetBooleanPropertyValue(JObject jobject, string propertyName) - { - return (jobject[propertyName] as JValue).ToObject(); - } + private static int GetIntegerPropertyValue(JObject jobject, string propertyName) + { + return ((JValue)jobject[propertyName]).ToObject(); + } - private static void SetBooleanPropertyValue(JObject jobject, string propertyName, bool value) - { - jobject[propertyName] = value; - } + private static void SetIntegerPropertyValue(JObject jobject, string propertyName, int value) + { + jobject[propertyName] = value; } +} - public class IntegerSetting : OptionalSetting +public class StringSetting : OptionalSetting +{ + public StringSetting(string name) + : base(name, SetStringPropertyValue, GetStringPropertyValue, string.Empty) { - public IntegerSetting(string name) - : base(name, SetIntegerPropertyValue, GetIntegerPropertyValue, 0) - { - } + } - private static int GetIntegerPropertyValue(JObject jobject, string propertyName) - { - return (jobject[propertyName] as JValue).ToObject(); - } + public override void SetValue(string value) + { + base.SetValue(InitializeFromString(value)); + } - private static void SetIntegerPropertyValue(JObject jobject, string propertyName, int value) - { - jobject[propertyName] = value; - } + public override string GetValue() + { + return InitializeFromString(base.GetValue()); } - public class StringSetting : OptionalSetting + private static string GetStringPropertyValue(JObject jobject, string propertyName) { - public StringSetting(string name) - : base(name, SetStringPropertyValue, GetStringPropertyValue, string.Empty) - { - } + return InitializeFromString((jobject[propertyName] as JValue)?.Value as string); + } - public override void SetValue(string value) - { - base.SetValue(InitializeFromString((value))); - } + private static void SetStringPropertyValue(JObject jobject, string propertyName, string value) + { + jobject[propertyName] = InitializeFromString(value); + } - public override string GetValue() - { - return InitializeFromString(base.GetValue()); - } + private static string InitializeFromString(string value) + { + return !string.IsNullOrWhiteSpace(value) ? value : string.Empty; + } +} - private static string GetStringPropertyValue(JObject jobject, string propertyName) - { - return InitializeFromString((jobject[propertyName] as JValue).Value as string); - } +public class EnumSetting : OptionalSetting + where T : struct, IConvertible +{ + public EnumSetting(string name) + : base(name, SetEnumPropertyValue, GetEnumPropertyValue, default) + { + } - private static void SetStringPropertyValue(JObject jobject, string propertyName, string value) - { - jobject[propertyName] = InitializeFromString(value); - } + private static T GetEnumPropertyValue(JObject jobject, string propertyName) + { + return StringToEnum((jobject[propertyName] as JValue)?.Value as string); + } - private static string InitializeFromString(string value) - { - return !string.IsNullOrWhiteSpace(value) ? value : string.Empty; - } + private static void SetEnumPropertyValue(JObject jobject, string propertyName, T value) + { + jobject[propertyName] = EnumToString(value); } - public class EnumSetting : OptionalSetting - where T : struct, IConvertible + private static T StringToEnum(string value) { - public EnumSetting(string name) - : base(name, SetEnumPropertyValue, GetEnumPropertyValue, default(T)) - { - } + var enumValue = default(T); - private static T GetEnumPropertyValue(JObject jobject, string propertyName) + if (!string.IsNullOrWhiteSpace(value)) { - return StringToEnum((jobject[propertyName] as JValue).Value as string); + var isParsed = Enum.TryParse(value, true, out enumValue); } - private static void SetEnumPropertyValue(JObject jobject, string propertyName, T value) - { - jobject[propertyName] = EnumToString(value); - } + return enumValue; + } - private static T StringToEnum(string value) - { - var enumValue = default(T); + private static string EnumToString(T value) + { + return Enum.GetName(typeof(T), value); + } +} - if (!string.IsNullOrWhiteSpace(value)) - { - bool isParsed = Enum.TryParse(value, true, out enumValue); - } +public class ListSetting : OptionalSetting> +{ + public ListSetting(string name) + : base(name, SetListPropertyValue, GetListPropertyValue, Enumerable.Empty().ToList()) + { + } - return enumValue; - } + public override void SetValue(List value) + { + base.SetValue(InitializeFromList(value)); + } - private static string EnumToString(T value) - { - return Enum.GetName(typeof(T), value); - } + public override List GetValue() + { + return InitializeFromList(base.GetValue()); } - public class ListSetting : OptionalSetting> + private static List GetListPropertyValue(JObject jobject, string propertyName) { - public ListSetting(string name) - : base(name, SetListPropertyValue, GetListPropertyValue, Enumerable.Empty().ToList()) - { - } + var jarray = jobject[propertyName] as JArray; - public override void SetValue(List value) - { - base.SetValue(InitializeFromList((value))); - } + return InitializeFromList(jarray.Select(jvalue => jvalue.ToObject()).ToList()); + } - public override List GetValue() - { - return InitializeFromList(base.GetValue()); - } + private static void SetListPropertyValue(JObject jobject, string propertyName, List value) + { + jobject[propertyName] = new JArray(InitializeFromList(value)); + } - private static List GetListPropertyValue(JObject jobject, string propertyName) - { - var jarray = (jobject[propertyName] as JArray); + private static List InitializeFromList(IEnumerable value) + { + return (value ?? Enumerable.Empty()).ToList(); + } +} - return InitializeFromList(jarray.Select(jvalue => jvalue.ToObject()).ToList()); - } +public class PersistentSettings : IPersistent +{ + private readonly IEnumerable persistentSettings; - private static void SetListPropertyValue(JObject jobject, string propertyName, List value) - { - jobject[propertyName] = new JArray(InitializeFromList(value)); - } + public PersistentSettings(IEnumerable persistentSettings) + { + this.persistentSettings = persistentSettings.ToList(); + } - private static List InitializeFromList(IEnumerable value) - { - return (value ?? Enumerable.Empty()).ToList(); - } + public void Load(JObject jobject) + { + foreach (var persistent in persistentSettings) persistent.Load(jobject); } - public class PersistentSettings : IPersistent + public void Store(JObject jobject) { - private readonly IEnumerable persistentSettings; + foreach (var persistent in persistentSettings) persistent.Store(jobject); + } +} - public PersistentSettings(IEnumerable persistentSettings) - { - this.persistentSettings = persistentSettings.ToList(); - } +public interface IUIConfigItem +{ + void UpdateUI(); + void UpdateConfig(); +} - public void Load(JObject jobject) - { - foreach (var persistent in this.persistentSettings) - { - persistent.Load(jobject); - } - } +public class UIConfigItem : IUIConfigItem +{ + private readonly Action _updateConfig; - public void Store(JObject jobject) - { - foreach (var persistent in this.persistentSettings) - { - persistent.Store(jobject); - } - } - } + private readonly Action _updateUi; - public interface IUIConfigItem + public UIConfigItem(Action updateUI, Action updateConfig) { - void UpdateUI(); - void UpdateConfig(); + _updateUi = updateUI; + _updateConfig = updateConfig; } - public class UIConfigItem : IUIConfigItem + public void UpdateUI() { - public UIConfigItem(Action updateUI, Action updateConfig) - { - updateUI_ = updateUI; - updateConfig_ = updateConfig; - } + _updateUi(); + } - public void UpdateUI() - { - updateUI_(); - } + public void UpdateConfig() + { + _updateConfig(); + } +} - public void UpdateConfig() - { - updateConfig_(); - } +public class UIConfig : IUIConfigItem +{ + private readonly IEnumerable _uiConfigItems; - private Action updateUI_; - private Action updateConfig_; + public UIConfig(IEnumerable uiConfigItems) + { + this._uiConfigItems = uiConfigItems.ToList(); } - public class UIConfig : IUIConfigItem + public void UpdateUI() { - private readonly IEnumerable uiConfigItems; - - public UIConfig(IEnumerable uiConfigItems) - { - this.uiConfigItems = uiConfigItems.ToList(); - } - - public void UpdateUI() - { - foreach (var uiConfigItem in this.uiConfigItems) - { - uiConfigItem.UpdateUI(); - } - } + foreach (var uiConfigItem in _uiConfigItems) uiConfigItem.UpdateUI(); + } - public void UpdateConfig() - { - foreach (var uiConfigItem in this.uiConfigItems) - { - uiConfigItem.UpdateConfig(); - } - } + public void UpdateConfig() + { + foreach (var uiConfigItem in _uiConfigItems) uiConfigItem.UpdateConfig(); } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/StreamIOUtil.cs b/BatchRvtUtil/StreamIOUtil.cs index b32ccdf..3f95b23 100644 --- a/BatchRvtUtil/StreamIOUtil.cs +++ b/BatchRvtUtil/StreamIOUtil.cs @@ -17,66 +17,62 @@ // along with this program. If not, see . // // + using System; using System.Collections.Generic; -using System.Linq; using System.IO; using System.Threading.Tasks; -namespace BatchRvtUtil +namespace BatchRvtUtil; + +public static class StreamIOUtil { - public static class StreamIOUtil + public static Tuple, Task> ReadAvailableLines(StreamReader streamReader, + Task pendingReadLineTask = null) { - public static Tuple, Task> ReadAvailableLines(StreamReader streamReader, Task pendingReadLineTask = null) - { - Task nextPendingReadLineTask = null; - var lines = new List(); + Task nextPendingReadLineTask; + var lines = new List(); - Task readLineTask = null; + Task readLineTask = null; - if (pendingReadLineTask != null) - { - readLineTask = pendingReadLineTask; - } - else - { - readLineTask = streamReader.ReadLineAsync(); - } + readLineTask = pendingReadLineTask ?? streamReader.ReadLineAsync(); - bool reachedEndOfStream = false; + var reachedEndOfStream = false; - while ((readLineTask.Status == TaskStatus.RanToCompletion) && !reachedEndOfStream) - { - var line = readLineTask.Result; - if (line != null) - { - lines.Add(line); - readLineTask = streamReader.ReadLineAsync(); - } - else - { - reachedEndOfStream = true; - } - } - - if (reachedEndOfStream) - { - nextPendingReadLineTask = null; - } - else if (readLineTask.Status == TaskStatus.Faulted) + while (readLineTask.Status == TaskStatus.RanToCompletion && !reachedEndOfStream) + { + var line = readLineTask.Result; + if (line != null) { - nextPendingReadLineTask = null; + lines.Add(line); + readLineTask = streamReader.ReadLineAsync(); } - else if (readLineTask.Status == TaskStatus.Canceled) + else { - nextPendingReadLineTask = null; + reachedEndOfStream = true; } - else + } + + if (reachedEndOfStream) + nextPendingReadLineTask = null; + else + switch (readLineTask.Status) { - nextPendingReadLineTask = readLineTask; + case TaskStatus.Faulted: + case TaskStatus.Canceled: + nextPendingReadLineTask = null; + break; + case TaskStatus.Created: + case TaskStatus.WaitingForActivation: + case TaskStatus.WaitingToRun: + case TaskStatus.Running: + case TaskStatus.WaitingForChildrenToComplete: + case TaskStatus.RanToCompletion: + default: + nextPendingReadLineTask = readLineTask; + break; } - return Tuple.Create(lines, nextPendingReadLineTask); - } + return Tuple.Create(lines, nextPendingReadLineTask); } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/TextFileUtil.cs b/BatchRvtUtil/TextFileUtil.cs index bf787ea..9769a63 100644 --- a/BatchRvtUtil/TextFileUtil.cs +++ b/BatchRvtUtil/TextFileUtil.cs @@ -17,46 +17,39 @@ // along with this program. If not, see . // // -using System; + using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; using System.Text; -namespace BatchRvtUtil -{ - public static class TextFileUtil - { - public const string TEXT_FILE_EXTENSION = ".txt"; - public const string TEXT_FILE_FILTER = "Text files (*.txt)|*.txt"; - - public static void WriteToCSVFile( - IEnumerable> rows, - string csvFilePath, - string delimiter, - Encoding encoding - ) - { - var lines = ( - rows - .Select(row => string.Join(delimiter, row.Select(value => value.ToString()))) - .ToList() - ); +namespace BatchRvtUtil; - File.WriteAllLines(csvFilePath, lines, encoding); +public static class TextFileUtil +{ + public const string TEXT_FILE_EXTENSION = ".txt"; + public const string TEXT_FILE_FILTER = "Text files (*.txt)|*.txt"; - return; - } + private static void WriteToCsvFile( + IEnumerable> rows, + string csvFilePath, + string delimiter, + Encoding encoding + ) + { + var lines = rows + .Select(row => string.Join(delimiter, row.Select(value => value.ToString()))) + .ToList(); - public static void WriteToTabDelimitedTxtFile( - IEnumerable> rows, - string txtFilePath, - Encoding encoding = null - ) - { - WriteToCSVFile(rows, txtFilePath, "\t", encoding ?? Encoding.UTF8); + File.WriteAllLines(csvFilePath, lines, encoding); + } - return; - } + public static void WriteToTabDelimitedTxtFile( + IEnumerable> rows, + string txtFilePath, + Encoding encoding = null + ) + { + WriteToCsvFile(rows, txtFilePath, "\t", encoding ?? Encoding.UTF8); } -} +} \ No newline at end of file diff --git a/BatchRvtUtil/packages.config b/BatchRvtUtil/packages.config new file mode 100644 index 0000000..e52b120 --- /dev/null +++ b/BatchRvtUtil/packages.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/GlobalAssemblyInfo.cs b/Common/GlobalAssemblyInfo.cs index 034cda8..663195f 100644 --- a/Common/GlobalAssemblyInfo.cs +++ b/Common/GlobalAssemblyInfo.cs @@ -6,6 +6,9 @@ // Revision // -[assembly: System.Reflection.AssemblyVersion("1.9.0.0")] -[assembly: System.Reflection.AssemblyInformationalVersion("1.9.0.0")] -[assembly: System.Reflection.AssemblyFileVersion("1.9.0.0")] \ No newline at end of file +using System.Reflection; + +[assembly: AssemblyVersion("1.10.0.0")] +[assembly: AssemblyInformationalVersion("1.10.0.0")] +[assembly: AssemblyFileVersion("1.10.0.0")] + diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 0000000..0612443 --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 2ffdfa1..1a872e8 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ - ATTENTION: Due to other commitments the original author of Revit Batch Processor (@DanRumery) is unable to support RBP for the future. For questions please seek help from the community such as the Dynamo and Revit API forums. + This fork builds on the great work of Dan Rummery and all original project contributors. +I've created it to implement unit testing, refactor the project to make it a bit cleaner and improve performance. # Revit Batch Processor (RBP) @@ -8,9 +9,7 @@ Fully automated batch processing of Revit files with your own Python or Dynamo t ## Latest version (NEW) -[Installer for Revit Batch Processor v1.9.0 beta](https://github.com/bvn-architecture/RevitBatchProcessor/releases/download/v1.9.0-beta/RevitBatchProcessorSetup_v1.9.0.exe) - -Version 1.9.0 beta release is available, which adds support for Revit 2023. +Version 1.10.0 beta release is available, which adds support for Revit 2024. No installer available, must compile in VS. See the [Releases](https://github.com/bvn-architecture/RevitBatchProcessor/releases) page for more information. diff --git a/RevitBatchProcessor.sln b/RevitBatchProcessor.sln index 1d64c43..efc361a 100644 --- a/RevitBatchProcessor.sln +++ b/RevitBatchProcessor.sln @@ -45,6 +45,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatchRvtAddin2023", "BatchRvtAddin2023\BatchRvtAddin2023.csproj", "{60C3C457-D35A-4343-A906-01CF666DC75E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatchRvtAddin2024", "BatchRvtAddin2024\BatchRvtAddin2024.csproj", "{237EB511-D77C-4142-80F3-C668CA8C83EC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatchRvtUtil.Tests", "BatchRvtUtil.Tests\BatchRvtUtil.Tests.csproj", "{BFD3D072-42A4-4B86-B225-73139D6C95D9}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{9507B984-1FEE-4C24-B8E6-F305588E26DD}" + EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -166,6 +173,22 @@ Global {60C3C457-D35A-4343-A906-01CF666DC75E}.Release|Any CPU.Build.0 = Release|Any CPU {60C3C457-D35A-4343-A906-01CF666DC75E}.Release|x64.ActiveCfg = Release|Any CPU {60C3C457-D35A-4343-A906-01CF666DC75E}.Release|x64.Build.0 = Release|Any CPU + {237EB511-D77C-4142-80F3-C668CA8C83EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {237EB511-D77C-4142-80F3-C668CA8C83EC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {237EB511-D77C-4142-80F3-C668CA8C83EC}.Debug|x64.ActiveCfg = Debug|Any CPU + {237EB511-D77C-4142-80F3-C668CA8C83EC}.Debug|x64.Build.0 = Debug|Any CPU + {237EB511-D77C-4142-80F3-C668CA8C83EC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {237EB511-D77C-4142-80F3-C668CA8C83EC}.Release|Any CPU.Build.0 = Release|Any CPU + {237EB511-D77C-4142-80F3-C668CA8C83EC}.Release|x64.ActiveCfg = Release|Any CPU + {237EB511-D77C-4142-80F3-C668CA8C83EC}.Release|x64.Build.0 = Release|Any CPU + {BFD3D072-42A4-4B86-B225-73139D6C95D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BFD3D072-42A4-4B86-B225-73139D6C95D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BFD3D072-42A4-4B86-B225-73139D6C95D9}.Debug|x64.ActiveCfg = Debug|Any CPU + {BFD3D072-42A4-4B86-B225-73139D6C95D9}.Debug|x64.Build.0 = Debug|Any CPU + {BFD3D072-42A4-4B86-B225-73139D6C95D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BFD3D072-42A4-4B86-B225-73139D6C95D9}.Release|Any CPU.Build.0 = Release|Any CPU + {BFD3D072-42A4-4B86-B225-73139D6C95D9}.Release|x64.ActiveCfg = Release|Any CPU + {BFD3D072-42A4-4B86-B225-73139D6C95D9}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -173,4 +196,7 @@ Global GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1D981AC6-C42D-4297-9B98-43CD6A4C78A3} EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {BFD3D072-42A4-4B86-B225-73139D6C95D9} = {9507B984-1FEE-4C24-B8E6-F305588E26DD} + EndGlobalSection EndGlobal diff --git a/Setup/RevitBatchProcessor.iss b/Setup/RevitBatchProcessor.iss index a73f500..c38de90 100644 --- a/Setup/RevitBatchProcessor.iss +++ b/Setup/RevitBatchProcessor.iss @@ -1,5 +1,5 @@ #define AppName "Revit Batch Processor" -#define AppVersion "1.9.0" +#define AppVersion "1.10.0" [Setup] AppName={#AppName} @@ -35,5 +35,7 @@ Source: "..\BatchRvtAddin2022\bin\x64\Release\*"; DestDir: "{userappdata}\Autode Source: "..\BatchRvtAddin2022\BatchRvtAddin2022.addin"; DestDir: "{userappdata}\Autodesk\Revit\Addins\2022"; Flags: ignoreversion Source: "..\BatchRvtAddin2023\bin\x64\Release\*"; DestDir: "{userappdata}\Autodesk\Revit\Addins\2023\BatchRvt"; Flags: ignoreversion createallsubdirs recursesubdirs Source: "..\BatchRvtAddin2023\BatchRvtAddin2023.addin"; DestDir: "{userappdata}\Autodesk\Revit\Addins\2023"; Flags: ignoreversion +Source: "..\BatchRvtAddin2024\bin\x64\Release\*"; DestDir: "{userappdata}\Autodesk\Revit\Addins\2024\BatchRvt"; Flags: ignoreversion createallsubdirs recursesubdirs +Source: "..\BatchRvtAddin2024\BatchRvtAddin2024.addin"; DestDir: "{userappdata}\Autodesk\Revit\Addins\2024"; Flags: ignoreversion [Icons] Name: "{group}\Revit Batch Processor (GUI)"; Filename: "{app}\BatchRvtGUI.exe"; WorkingDir: "{app}" diff --git a/Setup/RevitBatchProcessor_BVN.iss b/Setup/RevitBatchProcessor_BVN.iss index d849575..7dd682f 100644 --- a/Setup/RevitBatchProcessor_BVN.iss +++ b/Setup/RevitBatchProcessor_BVN.iss @@ -1,11 +1,11 @@ #define AppName "Revit Batch Processor_BVN" -#define AppVersion "1.9.0" +#define AppVersion "1.10.0" [Setup] AppName={#AppName} AppVersion={#AppVersion} AppVerName={#AppName} {#AppVersion} -PrivilegesRequired=lowest +PrivilegesRequired=admin AppId={{B5CA57EA-7BB2-4620-916C-AE98376C1EF1} DisableDirPage=auto DefaultDirName="C:\Program Files\BVN\RevitBatchProcessor" @@ -35,5 +35,7 @@ Source: "..\BatchRvtAddin2022\bin\x64\Release\*"; DestDir: "C:\ProgramData\Autod Source: "..\BatchRvtAddin2022\BatchRvtAddin2022.addin"; DestDir: "C:\ProgramData\Autodesk\Revit\Addins\2022"; Flags: ignoreversion Source: "..\BatchRvtAddin2023\bin\x64\Release\*"; DestDir: "C:\ProgramData\Autodesk\Revit\Addins\2023\BatchRvt"; Flags: ignoreversion createallsubdirs recursesubdirs Source: "..\BatchRvtAddin2023\BatchRvtAddin2023.addin"; DestDir: "C:\ProgramData\Autodesk\Revit\Addins\2023"; Flags: ignoreversion +Source: "..\BatchRvtAddin2024\bin\x64\Release\*"; DestDir: "C:\ProgramData\Autodesk\Revit\Addins\2024\BatchRvt"; Flags: ignoreversion createallsubdirs recursesubdirs +Source: "..\BatchRvtAddin2024\BatchRvtAddin2024.addin"; DestDir: "C:\ProgramData\Autodesk\Revit\Addins\2024"; Flags: ignoreversion [Icons] Name: "{group}\Revit Batch Processor (GUI)"; Filename: "{app}\BatchRvtGUI.exe"; WorkingDir: "{app}"