diff --git a/.editorconfig b/.editorconfig
index 8c374dd..99b3941 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -6,147 +6,266 @@ root = true
#### Core EditorConfig Options ####
+# Chars coding
+# https://stackoverflow.com/questions/41335199/how-to-config-visual-studio-to-use-utf-8-as-the-default-encoding-for-all-project
+# https://editorconfig.org/#:~:text=breaks%20are%20represented.-,charset,-%3A%20set%20to%20latin1
+# https://stackoverflow.com/questions/2223882/whats-the-difference-between-utf-8-and-utf-8-with-bom
+charset = utf-8
+
# Indentation and spacing
indent_size = 4
indent_style = space
tab_width = 4
+# Guideline for all files. Sets char position of vertical marker in text editor. https://marketplace.visualstudio.com/items?itemName=PaulHarrington.EditorGuidelinesPreview
+guidelines = 120
+
# New line preferences
end_of_line = crlf
-insert_final_newline = false
+insert_final_newline = true
#### .NET Coding Conventions ####
# Organize usings
+# Add new line between System using and others
dotnet_separate_import_directive_groups = true
+# System usings go first
dotnet_sort_system_directives_first = true
+# Comment message in header of file
file_header_template = unset
# this. and Me. preferences
-dotnet_style_qualification_for_event = false
-dotnet_style_qualification_for_field = false
-dotnet_style_qualification_for_method = false
-dotnet_style_qualification_for_property = false
+# Make "this." bright or not
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0003-ide0009
+dotnet_style_qualification_for_event = false:silent
+dotnet_style_qualification_for_field = false:silent
+dotnet_style_qualification_for_method = false:silent
+dotnet_style_qualification_for_property = false:silent
# Language keywords vs BCL types preferences
-dotnet_style_predefined_type_for_locals_parameters_members = true
-dotnet_style_predefined_type_for_member_access = true
+# Make by default "int" or "Int32" etc.
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0049
+dotnet_style_predefined_type_for_locals_parameters_members = true:none
+dotnet_style_predefined_type_for_member_access = true:silent
# Parentheses preferences
-dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity
-dotnet_style_parentheses_in_other_binary_operators = always_for_clarity
-dotnet_style_parentheses_in_other_operators = never_if_unnecessary
-dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity
+# Make parentheses bright or not in complex operations
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0047-ide0048
+dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:silent
+dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
+dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
+dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
# Modifier preferences
-dotnet_style_require_accessibility_modifiers = for_non_interface_members
+# Underscore all members with missed accessibility modifiers like warning
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0040
+dotnet_style_require_accessibility_modifiers = for_non_interface_members:warning
# Expression-level preferences
-dotnet_style_coalesce_expression = true
-dotnet_style_collection_initializer = true
-dotnet_style_explicit_tuple_names = true
-dotnet_style_namespace_match_folder = true
-dotnet_style_null_propagation = true
-dotnet_style_object_initializer = true
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0029-ide0030-ide0270
+dotnet_style_coalesce_expression = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0028?pivots=dotnet-8-0
+dotnet_style_collection_initializer = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0033
+dotnet_style_explicit_tuple_names = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0130
+dotnet_style_namespace_match_folder = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0031
+dotnet_style_null_propagation = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0017
+dotnet_style_object_initializer = true:suggestion
+# https://learn.microsoft.com/en-us/visualstudio/ide/reference/code-styles-refactoring-options?view=vs-2022
dotnet_style_operator_placement_when_wrapping = beginning_of_line
-dotnet_style_prefer_auto_properties = true
-dotnet_style_prefer_compound_assignment = true
-dotnet_style_prefer_conditional_expression_over_assignment = true
-dotnet_style_prefer_conditional_expression_over_return = true
-dotnet_style_prefer_inferred_anonymous_type_member_names = true
-dotnet_style_prefer_inferred_tuple_names = true
-dotnet_style_prefer_is_null_check_over_reference_equality_method = true
-dotnet_style_prefer_simplified_boolean_expressions = true
-dotnet_style_prefer_simplified_interpolation = true
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0032
+dotnet_style_prefer_auto_properties = true:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0054-ide0074
+dotnet_style_prefer_compound_assignment = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0045
+dotnet_style_prefer_conditional_expression_over_assignment = true:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0046
+dotnet_style_prefer_conditional_expression_over_return = true:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0037
+dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0037
+dotnet_style_prefer_inferred_tuple_names = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0041
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0075
+dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0071
+dotnet_style_prefer_simplified_interpolation = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0300
+dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion
# Field preferences
-dotnet_style_readonly_field = true
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0044
+dotnet_style_readonly_field = true:warning
# Parameter preferences
-dotnet_code_quality_unused_parameters = all
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0060
+dotnet_code_quality_unused_parameters = all:warning
# Suppression preferences
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0079
dotnet_remove_unnecessary_suppression_exclusions = none
# New line preferences
-dotnet_style_allow_multiple_blank_lines_experimental = true
-dotnet_style_allow_statement_immediately_after_block_experimental = true
+# Experimental not documented properties
+# https://github.com/dotnet/roslyn/issues/60539
+# https://github.com/dotnet/roslyn/issues/65770
+dotnet_style_allow_multiple_blank_lines_experimental = true:silent
+dotnet_style_allow_statement_immediately_after_block_experimental = true:silent
#### C# Coding Conventions ####
# var preferences
-csharp_style_var_elsewhere = false
-csharp_style_var_for_built_in_types = false
-csharp_style_var_when_type_is_apparent = false
+# Prefer explicit type over var
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0007-ide0008
+csharp_style_var_elsewhere = true:suggestion
+csharp_style_var_for_built_in_types = false:suggestion
+csharp_style_var_when_type_is_apparent = true:suggestion
# Expression-bodied members
-csharp_style_expression_bodied_accessors = true
-csharp_style_expression_bodied_constructors = false
-csharp_style_expression_bodied_indexers = true
-csharp_style_expression_bodied_lambdas = true
-csharp_style_expression_bodied_local_functions = false
-csharp_style_expression_bodied_methods = false
-csharp_style_expression_bodied_operators = false
-csharp_style_expression_bodied_properties = true
-
-# Pattern matching preferences
-csharp_style_pattern_matching_over_as_with_null_check = true
-csharp_style_pattern_matching_over_is_with_cast_check = true
-csharp_style_prefer_not_pattern = true
-csharp_style_prefer_pattern_matching = true
-csharp_style_prefer_switch_expression = true
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0027
+csharp_style_expression_bodied_accessors = true:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0021
+csharp_style_expression_bodied_constructors = false:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0026
+csharp_style_expression_bodied_indexers = false:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0053
+csharp_style_expression_bodied_lambdas = true:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0061
+csharp_style_expression_bodied_local_functions = true:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0022
+csharp_style_expression_bodied_methods = false:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0023-ide0024
+csharp_style_expression_bodied_operators = false:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0025
+csharp_style_expression_bodied_properties = true:silent
+
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0350
+csharp_style_prefer_implicitly_typed_lambda_expression = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0180
+csharp_style_prefer_tuple_swap = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0340
+csharp_style_prefer_unbound_generic_type_in_nameof = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0230
+csharp_style_prefer_utf8_string_literals = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0250
+csharp_style_prefer_readonly_struct = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0251
+csharp_style_prefer_readonly_struct_member = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0170
+csharp_style_prefer_extended_property_pattern = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0039
+csharp_style_prefer_local_over_anonymous_function = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0150
+csharp_style_prefer_null_check_over_type_check = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0160-ide0161
+csharp_style_namespace_declarations = file_scoped:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0290
+csharp_style_prefer_primary_constructors = false:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0210
+csharp_style_prefer_top_level_statements = true:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0200
+csharp_style_prefer_method_group_conversion = true:silent
+
+# Pattern matching preferences. Applicable not in all C# versions
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0019
+csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0020-ide0038
+csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0083
+csharp_style_prefer_not_pattern = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0078-ide0260
+csharp_style_prefer_pattern_matching = true:silent
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0066
+csharp_style_prefer_switch_expression = true:suggestion
# Null-checking preferences
-csharp_style_conditional_delegate_call = true
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide1005
+csharp_style_conditional_delegate_call = true:suggestion
# Modifier preferences
-csharp_prefer_static_local_function = true
-csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async
+# csharp_prefer_static_local_function is applicable in C# 8.0+
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0062
+csharp_prefer_static_local_function = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0036
+csharp_preferred_modifier_order = public, private, protected, internal, file, new, static, abstract, virtual, sealed, readonly, override, extern, unsafe, volatile, async, required:warning
# Code-block preferences
-csharp_prefer_braces = true
-csharp_prefer_simple_using_statement = true
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0011
+csharp_prefer_braces = true:silent
+# csharp_prefer_simple_using_statement is applicable in C# 8.0+
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0063
+csharp_prefer_simple_using_statement = true:suggestion
+
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0320
+csharp_prefer_static_anonymous_function = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0330
+csharp_prefer_system_threading_lock = true:suggestion
# Expression-level preferences
-csharp_prefer_simple_default_expression = true
-csharp_style_deconstructed_variable_declaration = true
-csharp_style_implicit_object_creation_when_type_is_apparent = true
-csharp_style_inlined_variable_declaration = true
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0034
+csharp_prefer_simple_default_expression = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0042
+csharp_style_deconstructed_variable_declaration = true:suggestion
+# csharp_style_implicit_object_creation_when_type_is_apparent is applicable in C# 9.0+
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0090
+csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0018
+csharp_style_inlined_variable_declaration = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0039
csharp_style_pattern_local_over_anonymous_function = true
-csharp_style_prefer_index_operator = true
-csharp_style_prefer_range_operator = true
-csharp_style_throw_expression = true
-csharp_style_unused_value_assignment_preference = discard_variable
-csharp_style_unused_value_expression_statement_preference = discard_variable
+# csharp_style_prefer_index_operator is applicable in C# 8.0+
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0056
+csharp_style_prefer_index_operator = true:suggestion
+# csharp_style_prefer_range_operator is applicable in C# 8.0+
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0057
+csharp_style_prefer_range_operator = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0016
+csharp_style_throw_expression = true:suggestion
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0059?pivots=lang-csharp-vb
+csharp_style_unused_value_assignment_preference = discard_variable:none
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0058
+csharp_style_unused_value_expression_statement_preference = discard_variable:none
# 'using' directive preferences
-csharp_using_directive_placement = outside_namespace
-
-# New line preferences
-csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true
-csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true
-csharp_style_allow_embedded_statements_on_same_line_experimental = true
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0065
+csharp_using_directive_placement = outside_namespace:silent
+
+# New line preferences. Not documented experimental properties
+# https://github.com/dotnet/roslyn/issues/60539
+# https://github.com/dotnet/roslyn/issues/65770
+csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent
+csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent
+csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent
+csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent
+csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent
#### C# Formatting Rules ####
# New line preferences
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/csharp-formatting-options#new-line-options
csharp_new_line_before_catch = false
csharp_new_line_before_else = false
csharp_new_line_before_finally = false
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = none
-csharp_new_line_between_query_expression_clauses = false
+csharp_new_line_between_query_expression_clauses = true
# Indentation preferences
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/csharp-formatting-options#indentation-options
csharp_indent_block_contents = true
csharp_indent_braces = false
-csharp_indent_case_contents = false
+csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = false
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
# Space preferences
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/csharp-formatting-options#spacing-options
csharp_space_after_cast = true
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
@@ -171,47 +290,98 @@ csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
# Wrapping preferences
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/csharp-formatting-options#wrap-options
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = false
#### Naming styles ####
# Naming rules
-
-dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
-dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
-dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
-
-dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
-dotnet_naming_rule.types_should_be_pascal_case.symbols = types
-dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
-
-dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
-dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
-dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
-
-# Symbol specifications
-
-dotnet_naming_symbols.interface.applicable_kinds = interface
-dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
-dotnet_naming_symbols.interface.required_modifiers =
-
-dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
-dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
-dotnet_naming_symbols.types.required_modifiers =
-
-dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
-dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
-dotnet_naming_symbols.non_field_members.required_modifiers =
-
-# Naming styles
-
-dotnet_naming_style.pascal_case.required_prefix =
-dotnet_naming_style.pascal_case.required_suffix =
-dotnet_naming_style.pascal_case.word_separator =
-dotnet_naming_style.pascal_case.capitalization = pascal_case
-
-dotnet_naming_style.begins_with_i.required_prefix = I
-dotnet_naming_style.begins_with_i.required_suffix =
-dotnet_naming_style.begins_with_i.word_separator =
-dotnet_naming_style.begins_with_i.capitalization = pascal_case
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/naming-rules
+# https://github.com/dotnet/roslyn/blob/main/.editorconfig#L63
+
+# Private and private protected fields are camelCase and start with _
+dotnet_naming_rule.private_fields_should_be_camel_case.severity = warning
+dotnet_naming_rule.private_fields_should_be_camel_case.symbols = private_fields
+dotnet_naming_rule.private_fields_should_be_camel_case.style = private_field_style
+
+dotnet_naming_symbols.private_fields.applicable_kinds = field
+dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, private_protected
+
+dotnet_naming_style.private_field_style.capitalization = camel_case
+dotnet_naming_style.private_field_style.required_prefix = _
+
+# Locals and parameters are camelCase
+dotnet_naming_rule.locals_should_be_camel_case.severity = warning
+dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters
+dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style
+
+dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local
+
+dotnet_naming_style.camel_case_style.capitalization = camel_case
+
+# Interfaces in PascalCase and start with I
+dotnet_naming_rule.interfaces_should_be_pascal_case.severity = warning
+dotnet_naming_rule.interfaces_should_be_pascal_case.symbols = interfaces
+dotnet_naming_rule.interfaces_should_be_pascal_case.style = interfaces_style
+
+dotnet_naming_symbols.interfaces.applicable_kinds = interface
+
+dotnet_naming_style.interfaces_style.capitalization = pascal_case
+dotnet_naming_style.interfaces_style.required_prefix = I
+
+# By default, name items with PascalCase
+dotnet_naming_rule.members_should_be_pascal_case.severity = warning
+dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members
+dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style
+
+dotnet_naming_symbols.all_members.applicable_kinds = *
+
+dotnet_naming_style.pascal_case_style.capitalization = pascal_case
+
+# ReSharper properties
+resharper_csharp_keep_blank_lines_in_code = 1
+resharper_csharp_keep_blank_lines_in_declarations = 1
+resharper_csharp_keep_existing_enum_arrangement = false
+resharper_csharp_max_enum_members_on_line = 1
+resharper_csharp_wrap_after_declaration_lpar = true
+resharper_csharp_wrap_after_invocation_lpar = true
+resharper_csharp_wrap_arguments_style = chop_if_long
+resharper_csharp_wrap_before_binary_opsign = true
+resharper_csharp_wrap_before_first_type_parameter_constraint = true
+resharper_csharp_wrap_parameters_style = chop_if_long
+resharper_force_chop_compound_if_expression = true
+resharper_force_chop_compound_while_expression = true
+resharper_keep_existing_declaration_block_arrangement = false
+resharper_keep_existing_embedded_block_arrangement = false
+resharper_keep_existing_expr_member_arrangement = false
+resharper_keep_existing_list_patterns_arrangement = false
+resharper_keep_existing_primary_constructor_declaration_parens_arrangement = false
+resharper_keep_existing_switch_expression_arrangement = false
+resharper_max_initializer_elements_on_line = 1
+resharper_place_accessorholder_attribute_on_same_line = false
+resharper_place_accessor_attribute_on_same_line = false
+resharper_place_constructor_initializer_on_same_line = false
+resharper_place_field_attribute_on_same_line = false
+resharper_place_simple_embedded_statement_on_same_line = false
+resharper_place_simple_property_pattern_on_single_line = false
+resharper_prefer_separate_deconstructed_variables_declaration = true
+resharper_space_after_operator_keyword = false
+resharper_space_before_trailing_comment_text = true
+resharper_space_within_single_line_array_initializer_braces = true
+resharper_static_members_qualify_with = current_type
+resharper_treat_case_statement_with_break_as_simple = false
+resharper_wrap_array_initializer_style = chop_if_long
+resharper_wrap_before_primary_constructor_declaration_lpar = false
+resharper_wrap_before_primary_constructor_declaration_rpar = false
+resharper_wrap_chained_binary_expressions = chop_if_long
+resharper_wrap_chained_binary_patterns = chop_if_long
+resharper_wrap_chained_method_calls = chop_if_long
+resharper_wrap_enum_declaration = chop_if_long
+resharper_wrap_list_pattern = chop_if_long
+resharper_wrap_property_pattern = chop_always
+
+# ReSharper inspection severities
+resharper_suggest_var_or_type_built_in_types_highlighting = hint
+resharper_suggest_var_or_type_elsewhere_highlighting = hint
+resharper_suggest_var_or_type_simple_types_highlighting = hint
\ No newline at end of file
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..230494c
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,27 @@
+version: 2
+updates:
+ # GitHub Actions
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "weekly"
+ day: "wednesday"
+ open-pull-requests-limit: 10
+ groups:
+ dotnet:
+ patterns:
+ - "*"
+ target-branch: "main"
+
+ # NuGet packages
+ - package-ecosystem: "nuget"
+ directory: "/"
+ schedule:
+ interval: "weekly"
+ day: "wednesday"
+ open-pull-requests-limit: 25
+ groups:
+ dotnet:
+ patterns:
+ - "*"
+ target-branch: "main"
\ No newline at end of file
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000..e71e8bc
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,50 @@
+name: Build
+
+on:
+ push:
+ tags: [ 'v*' ]
+ branches: [ main ]
+ pull_request:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ runs-on: windows-latest
+
+ permissions:
+ contents: write
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
+
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v6
+ with:
+ global-json-file: global.json
+
+ - name: Run pipeline
+ run: dotnet run --project build
+ env:
+ CONFIGURATION: Release
+ REVIT_VERSIONS: 2018,2019,2020,2021,2022,2023,2024,2025,2026,2027
+
+ - name: Upload artifacts
+ if: success()
+ uses: actions/upload-artifact@v7
+ with:
+ name: artifacts
+ path: artifacts/
+
+ - name: Create release
+ if: startsWith(github.ref, 'refs/tags/v')
+ uses: softprops/action-gh-release@v3
+ with:
+ files: artifacts/*
+ generate_release_notes: true
+ fail_on_unmatched_files: true
diff --git a/.gitignore b/.gitignore
index 7094a04..df8054f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -395,4 +395,8 @@ FodyWeavers.xsd
# Rider auto-generates .iml files, and contentModel.xml
**/.idea/**/*.iml
**/.idea/**/contentModel.xml
-**/.idea/**/modules.xml
\ No newline at end of file
+**/.idea/**/modules.xml
+
+
+.idea
+appsettings.*.json
\ No newline at end of file
diff --git a/.idea/.idea.RevitCoreConsole/.idea/.gitignore b/.idea/.idea.RevitCoreConsole/.idea/.gitignore
deleted file mode 100644
index 7974baa..0000000
--- a/.idea/.idea.RevitCoreConsole/.idea/.gitignore
+++ /dev/null
@@ -1,11 +0,0 @@
-# Default ignored files
-/shelf/
-/workspace.xml
-# Rider ignored files
-/projectSettingsUpdater.xml
-/contentModel.xml
-/modules.xml
-/.idea.RevitCoreConsole.iml
-# Datasource local storage ignored files
-/dataSources/
-/dataSources.local.xml
diff --git a/.idea/.idea.RevitCoreConsole/.idea/encodings.xml b/.idea/.idea.RevitCoreConsole/.idea/encodings.xml
deleted file mode 100644
index df87cf9..0000000
--- a/.idea/.idea.RevitCoreConsole/.idea/encodings.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/.idea/.idea.RevitCoreConsole/.idea/indexLayout.xml b/.idea/.idea.RevitCoreConsole/.idea/indexLayout.xml
deleted file mode 100644
index 7b08163..0000000
--- a/.idea/.idea.RevitCoreConsole/.idea/indexLayout.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/.idea.RevitCoreConsole/.idea/vcs.xml b/.idea/.idea.RevitCoreConsole/.idea/vcs.xml
deleted file mode 100644
index 94a25f7..0000000
--- a/.idea/.idea.RevitCoreConsole/.idea/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/.idea.dosymep.Revit.Engine/.idea/.gitignore b/.idea/.idea.dosymep.Revit.Engine/.idea/.gitignore
deleted file mode 100644
index 3934f33..0000000
--- a/.idea/.idea.dosymep.Revit.Engine/.idea/.gitignore
+++ /dev/null
@@ -1,11 +0,0 @@
-# Default ignored files
-/shelf/
-/workspace.xml
-# Rider ignored files
-/modules.xml
-/projectSettingsUpdater.xml
-/contentModel.xml
-/.idea.dosymep.Revit.Engine.iml
-# Datasource local storage ignored files
-/dataSources/
-/dataSources.local.xml
diff --git a/.idea/.idea.dosymep.Revit.Engine/.idea/encodings.xml b/.idea/.idea.dosymep.Revit.Engine/.idea/encodings.xml
deleted file mode 100644
index df87cf9..0000000
--- a/.idea/.idea.dosymep.Revit.Engine/.idea/encodings.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/.idea/.idea.dosymep.Revit.Engine/.idea/indexLayout.xml b/.idea/.idea.dosymep.Revit.Engine/.idea/indexLayout.xml
deleted file mode 100644
index 7b08163..0000000
--- a/.idea/.idea.dosymep.Revit.Engine/.idea/indexLayout.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/.idea.dosymep.Revit.Engine/.idea/vcs.xml b/.idea/.idea.dosymep.Revit.Engine/.idea/vcs.xml
deleted file mode 100644
index 94a25f7..0000000
--- a/.idea/.idea.dosymep.Revit.Engine/.idea/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.nuke/build.schema.json b/.nuke/build.schema.json
deleted file mode 100644
index b372cf7..0000000
--- a/.nuke/build.schema.json
+++ /dev/null
@@ -1,166 +0,0 @@
-{
- "$schema": "http://json-schema.org/draft-04/schema#",
- "$ref": "#/definitions/build",
- "title": "Build Schema",
- "definitions": {
- "build": {
- "type": "object",
- "properties": {
- "CommandName": {
- "type": "string"
- },
- "Configuration": {
- "type": "string",
- "description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)",
- "enum": [
- "Debug",
- "Release"
- ]
- },
- "Continue": {
- "type": "boolean",
- "description": "Indicates to continue a previously failed build attempt"
- },
- "Help": {
- "type": "boolean",
- "description": "Shows the help text for this build assembly"
- },
- "Host": {
- "type": "string",
- "description": "Host for execution. Default is 'automatic'",
- "enum": [
- "AppVeyor",
- "AzurePipelines",
- "Bamboo",
- "Bitbucket",
- "Bitrise",
- "GitHubActions",
- "GitLab",
- "Jenkins",
- "Rider",
- "SpaceAutomation",
- "TeamCity",
- "Terminal",
- "TravisCI",
- "VisualStudio",
- "VSCode"
- ]
- },
- "MaxVersion": {
- "type": "string",
- "description": "Max Revit version",
- "enum": [
- "Rv2016",
- "Rv2017",
- "Rv2018",
- "Rv2019",
- "Rv2020",
- "Rv2021",
- "Rv2022",
- "Rv2023",
- "Rv2024"
- ]
- },
- "MinVersion": {
- "type": "string",
- "description": "Min Revit version",
- "enum": [
- "Rv2016",
- "Rv2017",
- "Rv2018",
- "Rv2019",
- "Rv2020",
- "Rv2021",
- "Rv2022",
- "Rv2023",
- "Rv2024"
- ]
- },
- "NoLogo": {
- "type": "boolean",
- "description": "Disables displaying the NUKE logo"
- },
- "Output": {
- "type": "string"
- },
- "Partition": {
- "type": "string",
- "description": "Partition to use on CI"
- },
- "Plan": {
- "type": "boolean",
- "description": "Shows the execution plan (HTML)"
- },
- "Profile": {
- "type": "array",
- "description": "Defines the profiles to load",
- "items": {
- "type": "string"
- }
- },
- "RevitVersions": {
- "type": "array",
- "description": "Build Revit versions",
- "items": {
- "type": "string",
- "enum": [
- "Rv2016",
- "Rv2017",
- "Rv2018",
- "Rv2019",
- "Rv2020",
- "Rv2021",
- "Rv2022",
- "Rv2023",
- "Rv2024"
- ]
- }
- },
- "Root": {
- "type": "string",
- "description": "Root directory during build execution"
- },
- "Skip": {
- "type": "array",
- "description": "List of targets to be skipped. Empty list skips all dependencies",
- "items": {
- "type": "string",
- "enum": [
- "Clean",
- "Compile",
- "DownloadBim4Everyone",
- "Restore"
- ]
- }
- },
- "Solution": {
- "type": "string",
- "description": "Path to a solution file that is automatically loaded"
- },
- "Target": {
- "type": "array",
- "description": "List of targets to be invoked. Default is '{default_target}'",
- "items": {
- "type": "string",
- "enum": [
- "Clean",
- "Compile",
- "DownloadBim4Everyone",
- "Restore"
- ]
- }
- },
- "Verbosity": {
- "type": "string",
- "description": "Logging verbosity during build execution. Default is 'Normal'",
- "enum": [
- "Minimal",
- "Normal",
- "Quiet",
- "Verbose"
- ]
- }
- }
- }
- }
-}
diff --git a/.nuke/parameters.json b/.nuke/parameters.json
deleted file mode 100644
index 419e7c3..0000000
--- a/.nuke/parameters.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "$schema": "./build.schema.json",
- "Solution": "RevitCoreConsole.sln"
-}
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e69de29..4ecbf26 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -0,0 +1,118 @@
+# Contributing
+
+Thanks for your interest in contributing to **RevitCoreConsole**.
+
+## Before you start
+
+1. Search [existing issues](https://github.com/dosymep/RevitCoreConsole/issues) and pull requests to avoid duplicates.
+2. For larger changes, open an issue first and describe the problem or proposal.
+3. Keep changes focused. Prefer small, reviewable pull requests over large mixed diffs.
+
+## Development setup
+
+### Prerequisites
+
+- Windows x64
+- [.NET SDK](https://dotnet.microsoft.com/download) matching `global.json`
+- Autodesk Revit installed for every version you want to run or debug locally
+- Valid `ApplicationPath` and `LicenseKey` in `src/RevitCoreConsole/appsettings..json`
+
+### Clone and build
+
+```bash
+git clone https://github.com/dosymep/RevitCoreConsole.git
+cd RevitCoreConsole
+dotnet run --project build
+```
+
+By default the pipeline builds Revit **2018–2027** in **Release**. Override with environment variables:
+
+| Variable | Example |
+| :--- | :--- |
+| `CONFIGURATION` | `Release` |
+| `REVIT_VERSIONS` | `2025,2026` |
+| `MAX_PARALLELISM` | `2` |
+
+PowerShell example:
+
+```powershell
+$env:REVIT_VERSIONS = "2025"
+$env:CONFIGURATION = "Debug"
+dotnet run --project build
+```
+
+More details: [README.md](README.md).
+
+## Project layout
+
+| Path | Purpose |
+| :--- | :--- |
+| `src/RevitCoreConsole/` | CLI host |
+| `src/RevitEngine/` | Revit host, bundles, Design Automation runtime |
+| `src/RevitEngine.DBApplications/` | `.addin` parsing and DB application factory |
+| `samples/` | Example `IExternalDBApplication` AppBundles |
+| `build/` | ModularPipelines build, package, test, and run stages |
+| `tests/` | Unit tests |
+
+## Coding guidelines
+
+- Match the existing C# style, naming, and file organization.
+- Prefer small, purposeful types over large catch-all classes.
+- Do not commit secrets, local license keys, or machine-specific absolute paths that are not already part of the sample `appsettings.*.json` pattern.
+- Update both `README.md` and `README.ru.md` when user-facing behavior changes (CLI options, build defaults, samples).
+- Add or update unit tests when changing parsers, options, or engine configuration.
+
+## Samples and AppBundles
+
+If you add or change a sample:
+
+1. Provide `PackageContents.xml`, a `.addin` with `Type="DBApplication"`, and optional `.json` options.
+2. Keep version folders aligned with supported Revit series (`R2018`…`R2027`).
+3. Check `RevitCoreConsole.slnx` build flags if the sample should be included in or excluded from the pipeline.
+
+## Testing
+
+Unit tests run as part of the local ModularPipelines **Tests** stage:
+
+```bash
+dotnet run --project build
+```
+
+To limit scope while iterating:
+
+```powershell
+$env:REVIT_VERSIONS = "2025"
+dotnet run --project build
+```
+
+The **Run** stage launches packaged samples against local Revit and is skipped on GitHub Actions.
+
+## Pull requests
+
+1. Branch from `main`.
+2. Make your changes and ensure the relevant build/tests pass locally.
+3. Write a clear PR title and describe:
+ - what changed
+ - why it changed
+ - how you tested it
+4. Link related issues.
+5. Keep the PR limited to one concern (feature, fix, docs, or refactor).
+
+CI builds all supported Revit versions `2018`–`2027` on pull requests. See `.github/workflows/build.yml`.
+
+## Reporting issues
+
+Include as much of the following as possible:
+
+- Revit version
+- `RevitCoreConsole` version / commit
+- Exact CLI command
+- Expected vs actual behavior
+- Relevant excerpt from `logs/RevitCoreConsole-*.log`
+- Whether the AppBundle was produced by this repo’s samples or a custom plugin
+
+## License
+
+By contributing, you agree that your contributions are licensed under the same [MIT License](LICENSE.md) as the project.
+
+See also [CREDITS.md](CREDITS.md).
diff --git a/CREDITS.md b/CREDITS.md
index e69de29..207f489 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -0,0 +1,39 @@
+# Credits
+
+## Author
+
+**Biseuv Olzhas (dosymep)**
+
+- GitHub: [https://github.com/dosymep](https://github.com/dosymep)
+- Website: [https://dosymep.net](https://dosymep.net)
+- Email: [dosymep@gmail.com](mailto:dosymep@gmail.com)
+
+Copyright (c) 2026 Biseuv Olzhas (dosymep). Released under the [MIT License](LICENSE.md).
+
+## Acknowledgments
+
+This project is inspired by Autodesk Revit Design Automation (Forge) and the local Revit Core Console workflow for running `IExternalDBApplication` plugins without the Revit UI.
+
+Autodesk Revit, Revit API, and Design Automation for Revit are trademarks or products of Autodesk, Inc. This project is not affiliated with or endorsed by Autodesk.
+
+## Third-party libraries
+
+The following open-source libraries are used by this repository (see `Directory.Packages.props` for pinned versions):
+
+| Library | Purpose |
+| :--- | :--- |
+| [System.CommandLine](https://github.com/dotnet/command-line-api) | Command-line parsing |
+| [Microsoft.Extensions.*](https://github.com/dotnet/runtime) | Hosting, configuration, options, DI, logging abstractions |
+| [Serilog](https://github.com/serilog/serilog) (+ Console / File / Hosting sinks) | Structured logging |
+| [Spectre.Console](https://github.com/spectreconsole/spectre.console) | Console UI |
+| [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) | JSON processing in samples / tooling |
+| [ModularPipelines](https://github.com/thomhurst/ModularPipelines) | Build orchestration |
+| [TUnit](https://github.com/thomhurst/TUnit) | Unit testing |
+| [PolyFill](https://github.com/SimonCropp/Polyfill) | API polyfills across target frameworks |
+| [Autodesk.Forge.DesignAutomation.Revit](https://www.nuget.org/packages/Autodesk.Forge.DesignAutomation.Revit) | Design Automation Revit SDK helpers |
+
+## Contributors
+
+Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for how to get involved.
+
+If you contribute, feel free to open a pull request that adds your name here.
diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 0000000..b3a2fb7
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,30 @@
+
+
+ 1701;1702;MSB3246
+
+
+
+ x64
+
+ true
+
+
+
+ dosymep
+ Biseuv Olzhas (dosymep)
+ Copyright (c) 2026 Biseuv Olzhas (dosymep)
+
+ 2.0.0
+ 2.0.0
+
+ Git
+ dosymep, revit, engine, revitcoreconsole, bim360
+ https://github.com/dosymep/RevitCoreConsole
+ https://github.com/dosymep/RevitCoreConsole
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Directory.Builds.targets b/Directory.Builds.targets
new file mode 100644
index 0000000..c1df222
--- /dev/null
+++ b/Directory.Builds.targets
@@ -0,0 +1,2 @@
+
+
\ No newline at end of file
diff --git a/Directory.Packages.props b/Directory.Packages.props
new file mode 100644
index 0000000..643c8b5
--- /dev/null
+++ b/Directory.Packages.props
@@ -0,0 +1,36 @@
+
+
+ true
+ true
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/LICENSE.md b/LICENSE.md
index 808fb3c..aae8e0d 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2021 Biseuv Olzhas (dosymep)
+Copyright (c) 2026 Biseuv Olzhas (dosymep)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/README.md b/README.md
index e8a2063..a4cd763 100644
--- a/README.md
+++ b/README.md
@@ -1,32 +1,240 @@
# RevitCoreConsole
-[](https://www.jetbrains.com/pycharm)
-[](https://www.jetbrains.com/pycharm)
+[](https://www.jetbrains.com/rider)
[](LICENSE.md)
-[](https://www.autodesk.com/products/revit/overview)
+[](https://www.autodesk.com/products/revit/overview)
+A C# command-line utility for processing Autodesk Revit models (`.rvt`, `.rfa`) in a headless, UI-less environment.
-This utility can process revit file in ui-less mode.
+`RevitCoreConsole` mimics the Autodesk Revit Design Automation (Forge) environment locally. It loads an AppBundle with an `IExternalDBApplication`, opens a model, and runs the Design Automation lifecycle without launching the Revit UI — useful for automated pipelines, CI, and local debugging.
-RevitCoreConsole uses program interface like Forge RevitCoreConsole.
+*Читать на другом языке: [Русский](README.ru.md)*
-# Usage
+---
-1. RevitCoreConsole.exe forge /l ENU /i "model_path" /al "bundle_zip_path"
-2. RevitCoreConsole.exe revit /l ENU /i "model_path" /fullClassName RevitDBCommand /assemblyPath "assembly_path" /journalData "[]"
-3. RevitCoreConsole.exe pipeline /l ENU /pipeline "pipeline_path.yaml"
-4. ReviteCoreConsole.exe journal /l ENU /journal "journal_path.txt"
+## Architecture
-# Build
+| Project | Path | Role |
+| :--- | :--- | :--- |
+| **RevitCoreConsole** | `src/RevitCoreConsole/` | CLI host (System.CommandLine, DI, Serilog) |
+| **RevitEngine** | `src/RevitEngine/` | Revit product host, assembly resolver, AppBundle extraction, Design Automation runtime |
+| **RevitEngine.DBApplications** | `src/RevitEngine.DBApplications/` | `.addin` parsing and `IExternalDBApplication` factory |
-Install nuke-build:
+Also included: `build/` (ModularPipelines), `samples/` (DB application examples), `tests/RevitEngine.UnitTests/`.
+---
+
+## Building the Project
+
+The repository includes a ModularPipelines build app in the `build` project. It cleans project `bin`/`obj` plus the root `bin/`, `artifacts/`, and `TestResults/` folders, restores the solution, compiles outputs into `bin//`, packages console builds and sample bundles into `.zip` archives under `artifacts/`, then optionally runs tests and sample console jobs.
+
+Pipeline stages:
+
+1. **Clean** / **Restore**
+2. **Build** — compile `RevitCoreConsole` and samples into `bin//`
+3. **Package** — zip `RevitCoreConsole` per Revit version and each sample bundle with every built version inside
+4. **Tests** — unit tests for each selected Revit version (skipped on GitHub Actions)
+5. **Run** — launch `bin//RevitCoreConsole/RevitCoreConsole.exe` for every sample zip in `artifacts/` (skipped on GitHub Actions; requires a local Revit install). Models are taken from `build/tests_files//` and copied under `bin//runs//`
+
+### Prerequisites
+
+- [.NET SDK](https://dotnet.microsoft.com/download) (the build project targets `net10.0`)
+- Autodesk Revit installed for each version you want to run locally
+- Matching Revit SDK / NuGet packages for the versions you build
+- Valid `LicenseKey` and `ApplicationPath` in `src/RevitCoreConsole/appsettings..json`
+
+### Supported Revit versions
+
+Supported and built by default (local pipeline and GitHub Actions): **2018–2027**.
+
+### Run the build pipeline
+
+From the repository root:
+
+```bash
+dotnet run --project build
+```
+
+By default the pipeline builds Revit versions **2018–2027** using the **Release** configuration.
+
+### Environment variables
+
+| Variable | Default | Description |
+| :--- | :--- | :--- |
+| `CONFIGURATION` | `Release` | MSBuild configuration (`Debug`, `Release`, `D2025`, …). |
+| `REVIT_VERSIONS` | `2018,2019,…,2027` | One or more Revit versions. Separate values with commas, semicolons, or spaces. |
+| `MAX_PARALLELISM` | `max(1, ProcessorCount / 4)` | Max parallel work items for version/project fan-out. |
+
+#### PowerShell
+
+```powershell
+$env:CONFIGURATION = "Release"
+$env:REVIT_VERSIONS = "2025,2026"
+$env:MAX_PARALLELISM = "2"
+dotnet run --project build
+```
+
+#### Bash
+
+```bash
+CONFIGURATION=Release REVIT_VERSIONS=2025,2026 MAX_PARALLELISM=2 dotnet run --project build
+```
+
+#### Command Prompt (cmd)
+
+```cmd
+set CONFIGURATION=Release
+set REVIT_VERSIONS=2025,2026
+set MAX_PARALLELISM=2
+dotnet run --project build
+```
+
+### Build outputs
+
+```text
+bin/
+ 2025/
+ RevitCoreConsole/
+ Sample.CsvExport.bundle/
+artifacts/
+ RevitCoreConsole.2024.zip
+ RevitCoreConsole.2025.zip
+ Sample.CsvExport.zip
+ Sample.IfcExport.zip
+```
+
+- `bin//` — staged binaries for that Revit version
+- `artifacts/RevitCoreConsole..zip` — console package (`RevitCoreConsole/…`)
+- `artifacts/.zip` — one sample AppBundle with every built Revit version inside:
+
+```text
+Sample.CsvExport.bundle/
+ PackageContents.xml
+ 2024/
+ 2025/
+ 2026/
+ 2027/
+```
+
+---
+
+## Command-Line Interface (CLI) Reference
+
+### Options
+
+| Option | Alias | Required | Help Name | Default | Description |
+| :---: | :---: | :---: | :--- | :--- | :--- |
+| `/input` | `/i` | **Yes** | `path/to/model.rvt` | *None* | Path to a local `.rvt` / `.rfa` file, or a remote model path (`RSN://…`, `BIM 360://…`). Local files must exist. |
+| `/app-bundle` | `/al` | **Yes** | `path/to/bundle.zip` | *None* | Path to a Design Automation AppBundle `.zip` (runtime extracts a zip that contains a `*.bundle` folder). |
+| `/lang` | `/l` | No | `language_code` | `appsettings` (`English_USA`) | Three-letter Revit language code for the session locale. |
+| `/audit` | `/a` | No | — | `false` | Audit the document while opening it. |
+| `/worksets` | `/w` | No | `workset_configuration` | `OpenAllWorksets` | Which worksets to open: `OpenAllWorksets`, `CloseAllWorksets`, or `OpenLastViewed`. |
+
+### Session logs
+
+Each run writes a session log to:
+
+```text
+logs/RevitCoreConsole--.log
+```
+
+---
+
+## Supported Language Codes (`/l`)
+
+* **`ENU`** — English (United States)
+* **`ENG`** — English (United Kingdom)
+* **`FRA`** — French
+* **`DEU`** — German
+* **`ITA`** — Italian
+* **`JPN`** — Japanese
+* **`KOR`** — Korean
+* **`PLK`** — Polish
+* **`ESP`** — Spanish
+* **`CHS`** — Chinese (Simplified)
+* **`CHT`** — Chinese (Traditional)
+* **`PTB`** — Portuguese (Brazil)
+* **`RUS`** — Russian (`RU` is also accepted)
+* **`CSY`** — Czech
+* **`HUN`** — Hungarian
+
+---
+
+## Samples
+
+| Sample | Description | Built by pipeline |
+| :--- | :--- | :---: |
+| `Sample.CsvExport` | Export element parameters to CSV | Yes |
+| `Sample.IfcExport` | Export IFC from a 3D view | Yes |
+| `Sample.PurgeUnused` | Purge unused elements | Yes |
+| `Sample.SyncDocument` | Synchronize with central / save | Yes |
+| `Sample.PdfExport` | Export sheets to PDF (Revit 2022+) | No\* |
+| `Sample.NwcExport` | Export NWC from a 3D view | No |
+
+\*Excluded from the ModularPipelines sample build by solution flags in `RevitCoreConsole.slnx`.
+
+Each sample ships with `PackageContents.xml`, a `.addin` manifest, and optional `.json` options copied next to the DLL.
+
+---
+
+## Creating an AppBundle
+
+Typical layout inside the zip:
+
+```text
+MyDbApp.bundle/
+ PackageContents.xml
+ 2025/
+ MyDbApp.addin
+ MyDbApp.dll
+ MyDbApp.json # optional options
+```
+
+`PackageContents.xml` maps Revit series (`R2018`…`R2027`) to version folders and `.addin` modules. The `.addin` must declare `Type="DBApplication"` with `Assembly` and `FullClassName`.
+
+---
+
+## Usage Examples
+
+### 1. Run with English locale
+
+```bash
+RevitCoreConsole.exe /i "C:\Projects\Models\sample_project.rvt" /al "C:\Projects\Bundles\MyDbAppBundle.zip" /l ENU
```
-dotnet tool install Nuke.GlobalTool --global
+
+### 2. Run with Russian locale and audit
+
+```bash
+RevitCoreConsole.exe /i "C:\Projects\Models\sample_project.rvt" /al "C:\Projects\Bundles\MyDbAppBundle.zip" /l RUS /a
```
-Compile:
+### 3. Open with closed worksets
+```bash
+RevitCoreConsole.exe /i "C:\Projects\Models\sample_project.rvt" /al "C:\Projects\Bundles\MyDbAppBundle.zip" /w CloseAllWorksets
```
-nuke compile
-```
\ No newline at end of file
+
+Long option names also work: `/input`, `/app-bundle`, `/lang`, `/audit`, `/worksets`.
+
+---
+
+## How It Works
+
+1. **CLI parse** — resolve `/i`, `/al`, optional `/l`, `/a`, `/w`.
+2. **Host bootstrap** — load `appsettings` / `appsettings..json`, configure DI and logging.
+3. **Revit init** — resolve Revit assemblies, initialize the product with `LicenseKey`.
+4. **Bundle load** — unzip the AppBundle, read `PackageContents.xml`, resolve the `.addin` for the current Revit version, create the `IExternalDBApplication`.
+5. **Document open** — open the model with audit / workset options.
+6. **Lifecycle** — `OnStartup` → `SetDesignAutomationReady` → `OnShutdown`.
+
+---
+
+## Contributing
+
+See [CONTRIBUTING.md](CONTRIBUTING.md). Credits and third-party acknowledgments: [CREDITS.md](CREDITS.md).
+
+---
+
+## License
+
+MIT — see [LICENSE.md](LICENSE.md).
diff --git a/README.ru.md b/README.ru.md
new file mode 100644
index 0000000..efc029a
--- /dev/null
+++ b/README.ru.md
@@ -0,0 +1,240 @@
+# RevitCoreConsole (Русский)
+
+[](https://www.jetbrains.com/rider)
+[](LICENSE.md)
+[](https://www.autodesk.com/products/revit/overview)
+
+Консольная утилита на C# для обработки моделей Autodesk Revit (`.rvt`, `.rfa`) в фоновом (headless, UI-less) режиме.
+
+`RevitCoreConsole` локально имитирует среду Autodesk Revit Design Automation (Forge). Утилита загружает AppBundle с `IExternalDBApplication`, открывает модель и выполняет lifecycle Design Automation без запуска UI Revit — удобно для пайплайнов, CI и локальной отладки.
+
+*Read in another language: [English](README.md)*
+
+---
+
+## Архитектура
+
+| Проект | Путь | Роль |
+| :--- | :--- | :--- |
+| **RevitCoreConsole** | `src/RevitCoreConsole/` | CLI-хост (System.CommandLine, DI, Serilog) |
+| **RevitEngine** | `src/RevitEngine/` | Хост продукта Revit, резолвер сборок, распаковка AppBundle, runtime Design Automation |
+| **RevitEngine.DBApplications** | `src/RevitEngine.DBApplications/` | Парсинг `.addin` и фабрика `IExternalDBApplication` |
+
+Также в репозитории: `build/` (ModularPipelines), `samples/` (примеры DB-приложений), `tests/RevitEngine.UnitTests/`.
+
+---
+
+## Сборка проекта
+
+В репозитории есть сборочное приложение на ModularPipelines в проекте `build`. Оно очищает проектные `bin`/`obj`, а также корневые папки `bin/`, `artifacts/` и `TestResults/`, восстанавливает solution, компилирует вывод в `bin/<версия>/`, упаковывает консоль и бандлы примеров в `.zip` в `artifacts/`, затем при необходимости запускает тесты и прогон семплов.
+
+Этапы пайплайна:
+
+1. **Clean** / **Restore**
+2. **Build** — компиляция `RevitCoreConsole` и семплов в `bin/<версия>/`
+3. **Package** — отдельный zip `RevitCoreConsole` на каждую версию Revit и один zip примера со всеми собранными версиями внутри
+4. **Tests** — unit-тесты для каждой выбранной версии Revit (на GitHub Actions пропускаются)
+5. **Run** — запуск `bin/<версия>/RevitCoreConsole/RevitCoreConsole.exe` для каждого sample zip из `artifacts/` (на GitHub Actions пропускается; нужен установленный Revit). Модели берутся из `build/tests_files/<версия>/` и копируются в `bin/<версия>/runs/<Семпл>/`
+
+### Требования
+
+- [.NET SDK](https://dotnet.microsoft.com/download) (проект сборки рассчитан на `net10.0`)
+- Установленный Autodesk Revit для каждой версии, которую вы хотите запускать локально
+- SDK / NuGet-пакеты Autodesk Revit для собираемых версий
+- Корректные `LicenseKey` и `ApplicationPath` в `src/RevitCoreConsole/appsettings.<версия>.json`
+
+### Поддерживаемые версии Revit
+
+Поддерживаются и собираются по умолчанию (локальный пайплайн и GitHub Actions): **2018–2027**.
+
+### Запуск пайплайна сборки
+
+Из корня репозитория:
+
+```bash
+dotnet run --project build
+```
+
+По умолчанию пайплайн собирает версии Revit **2018–2027** в конфигурации **Release**.
+
+### Переменные окружения
+
+| Переменная | По умолчанию | Описание |
+| :--- | :--- | :--- |
+| `CONFIGURATION` | `Release` | Конфигурация MSBuild (`Debug`, `Release`, `D2025` и т.д.). |
+| `REVIT_VERSIONS` | `2018,2019,…,2027` | Одна или несколько версий Revit. Значения разделяются запятыми, точками с запятой или пробелами. |
+| `MAX_PARALLELISM` | `max(1, ProcessorCount / 4)` | Максимум параллельных задач по версиям/проектам. |
+
+#### PowerShell
+
+```powershell
+$env:CONFIGURATION = "Release"
+$env:REVIT_VERSIONS = "2025,2026"
+$env:MAX_PARALLELISM = "2"
+dotnet run --project build
+```
+
+#### Bash
+
+```bash
+CONFIGURATION=Release REVIT_VERSIONS=2025,2026 MAX_PARALLELISM=2 dotnet run --project build
+```
+
+#### Command Prompt (cmd)
+
+```cmd
+set CONFIGURATION=Release
+set REVIT_VERSIONS=2025,2026
+set MAX_PARALLELISM=2
+dotnet run --project build
+```
+
+### Результаты сборки
+
+```text
+bin/
+ 2025/
+ RevitCoreConsole/
+ Sample.CsvExport.bundle/
+artifacts/
+ RevitCoreConsole.2024.zip
+ RevitCoreConsole.2025.zip
+ Sample.CsvExport.zip
+ Sample.IfcExport.zip
+```
+
+- `bin/<версия>/` — подготовленные бинарники для этой версии Revit
+- `artifacts/RevitCoreConsole.<версия>.zip` — пакет консоли (`RevitCoreConsole/…`)
+- `artifacts/<ИмяСэмпла>.zip` — один AppBundle примера со всеми собранными версиями Revit внутри:
+
+```text
+Sample.CsvExport.bundle/
+ PackageContents.xml
+ 2024/
+ 2025/
+ 2026/
+ 2027/
+```
+
+---
+
+## Справочник по интерфейсу командной строки (CLI)
+
+### Параметры
+
+| Опция | Алиас | Обязательный | Имя в справке | По умолчанию | Описание |
+| :---: | :---: | :---: | :--- | :--- | :--- |
+| `/input` | `/i` | **Да** | `path/to/model.rvt` | *Нет* | Путь к локальному `.rvt` / `.rfa` или удалённой модели (`RSN://…`, `BIM 360://…`). Локальный файл должен существовать. |
+| `/app-bundle` | `/al` | **Да** | `path/to/bundle.zip` | *Нет* | Путь к AppBundle Design Automation в формате `.zip` (runtime распаковывает zip с папкой `*.bundle`). |
+| `/lang` | `/l` | Нет | `language_code` | `appsettings` (`English_USA`) | Трёхбуквенный код языка сессии Revit. |
+| `/audit` | `/a` | Нет | — | `false` | Аудит документа при открытии. |
+| `/worksets` | `/w` | Нет | `workset_configuration` | `OpenAllWorksets` | Какие ворксеты открывать: `OpenAllWorksets`, `CloseAllWorksets` или `OpenLastViewed`. |
+
+### Логи сессии
+
+Каждый запуск пишет лог в:
+
+```text
+logs/RevitCoreConsole--.log
+```
+
+---
+
+## Поддерживаемые коды языков (`/l`)
+
+* **`ENU`** — Английский (США)
+* **`ENG`** — Английский (Великобритания)
+* **`FRA`** — Французский
+* **`DEU`** — Немецкий
+* **`ITA`** — Итальянский
+* **`JPN`** — Японский
+* **`KOR`** — Корейский
+* **`PLK`** — Польский
+* **`ESP`** — Испанский
+* **`CHS`** — Китайский (упрощённый)
+* **`CHT`** — Китайский (традиционный)
+* **`PTB`** — Португальский (Бразилия)
+* **`RUS`** — Русский (также принимается `RU`)
+* **`CSY`** — Чешский
+* **`HUN`** — Венгерский
+
+---
+
+## Примеры (samples)
+
+| Семпл | Описание | Собирается пайплайном |
+| :--- | :--- | :---: |
+| `Sample.CsvExport` | Экспорт параметров элементов в CSV | Да |
+| `Sample.IfcExport` | Экспорт IFC из 3D-вида | Да |
+| `Sample.PurgeUnused` | Очистка неиспользуемых элементов | Да |
+| `Sample.SyncDocument` | Синхронизация с центральной моделью / сохранение | Да |
+| `Sample.PdfExport` | Экспорт листов в PDF (Revit 2022+) | Нет\* |
+| `Sample.NwcExport` | Экспорт NWC из 3D-вида | Нет |
+
+\*Исключён из sample-сборки ModularPipelines флагами в `RevitCoreConsole.slnx`.
+
+У каждого семпла есть `PackageContents.xml`, манифест `.addin` и опциональный `.json` с настройками рядом с DLL.
+
+---
+
+## Создание AppBundle
+
+Типичная структура внутри zip:
+
+```text
+MyDbApp.bundle/
+ PackageContents.xml
+ 2025/
+ MyDbApp.addin
+ MyDbApp.dll
+ MyDbApp.json # опциональные настройки
+```
+
+`PackageContents.xml` сопоставляет серии Revit (`R2018`…`R2027`) с папками версий и модулями `.addin`. В `.addin` нужно указать `Type="DBApplication"`, а также `Assembly` и `FullClassName`.
+
+---
+
+## Практические примеры использования
+
+### 1. Запуск с английской локализацией
+
+```bash
+RevitCoreConsole.exe /i "C:\Projects\Models\sample_project.rvt" /al "C:\Projects\Bundles\MyDbAppBundle.zip" /l ENU
+```
+
+### 2. Запуск с русской локализацией и аудитом
+
+```bash
+RevitCoreConsole.exe /i "C:\Projects\Models\sample_project.rvt" /al "C:\Projects\Bundles\MyDbAppBundle.zip" /l RUS /a
+```
+
+### 3. Открытие с закрытыми ворксетами
+
+```bash
+RevitCoreConsole.exe /i "C:\Projects\Models\sample_project.rvt" /al "C:\Projects\Bundles\MyDbAppBundle.zip" /w CloseAllWorksets
+```
+
+Длинные имена опций тоже поддерживаются: `/input`, `/app-bundle`, `/lang`, `/audit`, `/worksets`.
+
+---
+
+## Принцип работы
+
+1. **Разбор CLI** — `/i`, `/al`, опционально `/l`, `/a`, `/w`.
+2. **Bootstrap хоста** — загрузка `appsettings` / `appsettings..json`, настройка DI и логирования.
+3. **Инициализация Revit** — резолв сборок, инициализация продукта с `LicenseKey`.
+4. **Загрузка бандла** — распаковка AppBundle, чтение `PackageContents.xml`, резолв `.addin` для текущей версии Revit, создание `IExternalDBApplication`.
+5. **Открытие документа** — открытие модели с параметрами аудита / ворксетов.
+6. **Lifecycle** — `OnStartup` → `SetDesignAutomationReady` → `OnShutdown`.
+
+---
+
+## Участие в разработке
+
+См. [CONTRIBUTING.md](CONTRIBUTING.md) (на английском). Авторы и сторонние зависимости: [CREDITS.md](CREDITS.md).
+
+---
+
+## Лицензия
+
+MIT — см. [LICENSE.md](LICENSE.md).
diff --git a/RevitCoreConsole.sln b/RevitCoreConsole.sln
deleted file mode 100644
index 226cf56..0000000
--- a/RevitCoreConsole.sln
+++ /dev/null
@@ -1,146 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Version 16
-VisualStudioVersion = 16.0.31515.178
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RevitCoreConsole", "src/RevitCoreConsole\RevitCoreConsole.csproj", "{1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "dosymep.Revit.Engine", "src/dosymep.Revit.Engine\dosymep.Revit.Engine.csproj", "{FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{83A9CA17-3BD3-4663-AE94-28349EA54D1A}"
- ProjectSection(SolutionItems) = preProject
- .editorconfig = .editorconfig
- CONTRIBUTING.md = CONTRIBUTING.md
- CREDITS.md = CREDITS.md
- LICENSE.md = LICENSE.md
- README.md = README.md
- src\Directory.Build.props = src\Directory.Build.props
- src\Directory.Builds.targets = src\Directory.Builds.targets
- EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RevitCoreDBApplications", "src/RevitCoreDBApplications\RevitCoreDBApplications.csproj", "{8B6B3380-4550-4C15-9E62-4D5624F80C71}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RevitCoreCommands", "src/RevitCoreCommands\RevitCoreCommands.csproj", "{99400D76-1842-4DFC-A3CE-CF9A8D14CD82}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "_build", "build\_build.csproj", "{AB4AAE57-ACA7-46AD-AACC-68DDD47E0FEA}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- D2016|x64 = D2016|x64
- D2017|x64 = D2017|x64
- D2018|x64 = D2018|x64
- D2019|x64 = D2019|x64
- D2020|x64 = D2020|x64
- D2021|x64 = D2021|x64
- D2022|x64 = D2022|x64
- D2023|x64 = D2023|x64
- D2024|x64 = D2024|x64
- Debug|x64 = Debug|x64
- Release|x64 = Release|x64
- D2025|x64 = D2025|x64
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2020|x64.ActiveCfg = D2020|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2020|x64.Build.0 = D2020|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2021|x64.ActiveCfg = D2021|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2021|x64.Build.0 = D2021|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2022|x64.ActiveCfg = D2022|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2022|x64.Build.0 = D2022|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2023|x64.ActiveCfg = D2023|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2023|x64.Build.0 = D2023|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2024|x64.ActiveCfg = D2024|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2024|x64.Build.0 = D2024|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.Release|x64.ActiveCfg = Release|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.Release|x64.Build.0 = Release|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.Debug|x64.ActiveCfg = Debug|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.Debug|x64.Build.0 = Debug|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2025|x64.ActiveCfg = D2025|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2025|x64.Build.0 = D2025|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2016|x64.ActiveCfg = D2016|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2016|x64.Build.0 = D2016|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2017|x64.ActiveCfg = D2017|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2017|x64.Build.0 = D2017|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2018|x64.ActiveCfg = D2018|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2018|x64.Build.0 = D2018|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2019|x64.ActiveCfg = D2019|x64
- {1AB3952D-73EA-42AB-AC5E-6CBFE95D763D}.D2019|x64.Build.0 = D2019|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2020|x64.ActiveCfg = D2020|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2020|x64.Build.0 = D2020|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2021|x64.ActiveCfg = D2021|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2021|x64.Build.0 = D2021|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2022|x64.ActiveCfg = D2022|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2022|x64.Build.0 = D2022|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2023|x64.ActiveCfg = D2023|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2023|x64.Build.0 = D2023|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2024|x64.ActiveCfg = D2024|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2024|x64.Build.0 = D2024|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.Release|x64.ActiveCfg = Release|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.Release|x64.Build.0 = Release|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.Debug|x64.ActiveCfg = Debug|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.Debug|x64.Build.0 = Debug|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2025|x64.ActiveCfg = D2025|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2025|x64.Build.0 = D2025|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2016|x64.ActiveCfg = D2016|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2016|x64.Build.0 = D2016|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2017|x64.ActiveCfg = D2017|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2017|x64.Build.0 = D2017|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2018|x64.ActiveCfg = D2018|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2018|x64.Build.0 = D2018|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2019|x64.ActiveCfg = D2019|x64
- {FAD668F8-BC4F-4E20-AF33-0B6D68D276FA}.D2019|x64.Build.0 = D2019|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2020|x64.ActiveCfg = D2020|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2020|x64.Build.0 = D2020|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2021|x64.ActiveCfg = D2021|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2021|x64.Build.0 = D2021|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2022|x64.ActiveCfg = D2022|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2022|x64.Build.0 = D2022|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2023|x64.ActiveCfg = D2023|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2023|x64.Build.0 = D2023|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2024|x64.ActiveCfg = D2024|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2024|x64.Build.0 = D2024|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.Release|x64.ActiveCfg = Release|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.Release|x64.Build.0 = Release|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.Debug|x64.ActiveCfg = Debug|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.Debug|x64.Build.0 = Debug|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2025|x64.ActiveCfg = D2025|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2025|x64.Build.0 = D2025|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2016|x64.ActiveCfg = D2016|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2016|x64.Build.0 = D2016|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2017|x64.ActiveCfg = D2017|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2017|x64.Build.0 = D2017|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2018|x64.ActiveCfg = D2018|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2018|x64.Build.0 = D2018|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2019|x64.ActiveCfg = D2019|x64
- {8B6B3380-4550-4C15-9E62-4D5624F80C71}.D2019|x64.Build.0 = D2019|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2020|x64.ActiveCfg = D2020|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2020|x64.Build.0 = D2020|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2021|x64.ActiveCfg = D2021|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2021|x64.Build.0 = D2021|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2022|x64.ActiveCfg = D2022|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2022|x64.Build.0 = D2022|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2023|x64.ActiveCfg = D2023|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2023|x64.Build.0 = D2023|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2024|x64.ActiveCfg = D2024|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2024|x64.Build.0 = D2024|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.Release|x64.ActiveCfg = Release|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.Release|x64.Build.0 = Release|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.Debug|x64.ActiveCfg = Debug|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.Debug|x64.Build.0 = Debug|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2025|x64.ActiveCfg = D2025|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2025|x64.Build.0 = D2025|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2016|x64.ActiveCfg = D2016|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2016|x64.Build.0 = D2016|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2017|x64.ActiveCfg = D2017|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2017|x64.Build.0 = D2017|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2018|x64.ActiveCfg = D2018|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2018|x64.Build.0 = D2018|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2019|x64.ActiveCfg = D2019|x64
- {99400D76-1842-4DFC-A3CE-CF9A8D14CD82}.D2019|x64.Build.0 = D2019|x64
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(ExtensibilityGlobals) = postSolution
- SolutionGuid = {DAAB4C3D-FF75-4EED-B549-619FB937302C}
- EndGlobalSection
-EndGlobal
diff --git a/RevitCoreConsole.slnx b/RevitCoreConsole.slnx
new file mode 100644
index 0000000..912ae4a
--- /dev/null
+++ b/RevitCoreConsole.slnx
@@ -0,0 +1,74 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/build.cmd b/build.cmd
deleted file mode 100644
index b08cc59..0000000
--- a/build.cmd
+++ /dev/null
@@ -1,7 +0,0 @@
-:; set -eo pipefail
-:; SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)
-:; ${SCRIPT_DIR}/build.sh "$@"
-:; exit $?
-
-@ECHO OFF
-powershell -ExecutionPolicy ByPass -NoProfile -File "%~dp0build.ps1" %*
diff --git a/build.ps1 b/build.ps1
deleted file mode 100644
index c0c0e61..0000000
--- a/build.ps1
+++ /dev/null
@@ -1,74 +0,0 @@
-[CmdletBinding()]
-Param(
- [Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)]
- [string[]]$BuildArguments
-)
-
-Write-Output "PowerShell $($PSVersionTable.PSEdition) version $($PSVersionTable.PSVersion)"
-
-Set-StrictMode -Version 2.0; $ErrorActionPreference = "Stop"; $ConfirmPreference = "None"; trap { Write-Error $_ -ErrorAction Continue; exit 1 }
-$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
-
-###########################################################################
-# CONFIGURATION
-###########################################################################
-
-$BuildProjectFile = "$PSScriptRoot\build\_build.csproj"
-$TempDirectory = "$PSScriptRoot\\.nuke\temp"
-
-$DotNetGlobalFile = "$PSScriptRoot\\global.json"
-$DotNetInstallUrl = "https://dot.net/v1/dotnet-install.ps1"
-$DotNetChannel = "STS"
-
-$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = 1
-$env:DOTNET_CLI_TELEMETRY_OPTOUT = 1
-$env:DOTNET_MULTILEVEL_LOOKUP = 0
-
-###########################################################################
-# EXECUTION
-###########################################################################
-
-function ExecSafe([scriptblock] $cmd) {
- & $cmd
- if ($LASTEXITCODE) { exit $LASTEXITCODE }
-}
-
-# If dotnet CLI is installed globally and it matches requested version, use for execution
-if ($null -ne (Get-Command "dotnet" -ErrorAction SilentlyContinue) -and `
- $(dotnet --version) -and $LASTEXITCODE -eq 0) {
- $env:DOTNET_EXE = (Get-Command "dotnet").Path
-}
-else {
- # Download install script
- $DotNetInstallFile = "$TempDirectory\dotnet-install.ps1"
- New-Item -ItemType Directory -Path $TempDirectory -Force | Out-Null
- [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
- (New-Object System.Net.WebClient).DownloadFile($DotNetInstallUrl, $DotNetInstallFile)
-
- # If global.json exists, load expected version
- if (Test-Path $DotNetGlobalFile) {
- $DotNetGlobal = $(Get-Content $DotNetGlobalFile | Out-String | ConvertFrom-Json)
- if ($DotNetGlobal.PSObject.Properties["sdk"] -and $DotNetGlobal.sdk.PSObject.Properties["version"]) {
- $DotNetVersion = $DotNetGlobal.sdk.version
- }
- }
-
- # Install by channel or version
- $DotNetDirectory = "$TempDirectory\dotnet-win"
- if (!(Test-Path variable:DotNetVersion)) {
- ExecSafe { & powershell $DotNetInstallFile -InstallDir $DotNetDirectory -Channel $DotNetChannel -NoPath }
- } else {
- ExecSafe { & powershell $DotNetInstallFile -InstallDir $DotNetDirectory -Version $DotNetVersion -NoPath }
- }
- $env:DOTNET_EXE = "$DotNetDirectory\dotnet.exe"
-}
-
-Write-Output "Microsoft (R) .NET SDK version $(& $env:DOTNET_EXE --version)"
-
-if (Test-Path env:NUKE_ENTERPRISE_TOKEN) {
- & $env:DOTNET_EXE nuget remove source "nuke-enterprise" > $null
- & $env:DOTNET_EXE nuget add source "https://f.feedz.io/nuke/enterprise/nuget" --name "nuke-enterprise" --username "PAT" --password $env:NUKE_ENTERPRISE_TOKEN > $null
-}
-
-ExecSafe { & $env:DOTNET_EXE build $BuildProjectFile /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet }
-ExecSafe { & $env:DOTNET_EXE run --project $BuildProjectFile --no-build -- $BuildArguments }
diff --git a/build.sh b/build.sh
deleted file mode 100644
index 2f10dcb..0000000
--- a/build.sh
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/env bash
-
-bash --version 2>&1 | head -n 1
-
-set -eo pipefail
-SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)
-
-###########################################################################
-# CONFIGURATION
-###########################################################################
-
-BUILD_PROJECT_FILE="$SCRIPT_DIR/build/_build.csproj"
-TEMP_DIRECTORY="$SCRIPT_DIR//.nuke/temp"
-
-DOTNET_GLOBAL_FILE="$SCRIPT_DIR//global.json"
-DOTNET_INSTALL_URL="https://dot.net/v1/dotnet-install.sh"
-DOTNET_CHANNEL="STS"
-
-export DOTNET_CLI_TELEMETRY_OPTOUT=1
-export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
-export DOTNET_MULTILEVEL_LOOKUP=0
-
-###########################################################################
-# EXECUTION
-###########################################################################
-
-function FirstJsonValue {
- perl -nle 'print $1 if m{"'"$1"'": "([^"]+)",?}' <<< "${@:2}"
-}
-
-# If dotnet CLI is installed globally and it matches requested version, use for execution
-if [ -x "$(command -v dotnet)" ] && dotnet --version &>/dev/null; then
- export DOTNET_EXE="$(command -v dotnet)"
-else
- # Download install script
- DOTNET_INSTALL_FILE="$TEMP_DIRECTORY/dotnet-install.sh"
- mkdir -p "$TEMP_DIRECTORY"
- curl -Lsfo "$DOTNET_INSTALL_FILE" "$DOTNET_INSTALL_URL"
- chmod +x "$DOTNET_INSTALL_FILE"
-
- # If global.json exists, load expected version
- if [[ -f "$DOTNET_GLOBAL_FILE" ]]; then
- DOTNET_VERSION=$(FirstJsonValue "version" "$(cat "$DOTNET_GLOBAL_FILE")")
- if [[ "$DOTNET_VERSION" == "" ]]; then
- unset DOTNET_VERSION
- fi
- fi
-
- # Install by channel or version
- DOTNET_DIRECTORY="$TEMP_DIRECTORY/dotnet-unix"
- if [[ -z ${DOTNET_VERSION+x} ]]; then
- "$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --channel "$DOTNET_CHANNEL" --no-path
- else
- "$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --version "$DOTNET_VERSION" --no-path
- fi
- export DOTNET_EXE="$DOTNET_DIRECTORY/dotnet"
-fi
-
-echo "Microsoft (R) .NET SDK version $("$DOTNET_EXE" --version)"
-
-if [[ ! -z ${NUKE_ENTERPRISE_TOKEN+x} && "$NUKE_ENTERPRISE_TOKEN" != "" ]]; then
- "$DOTNET_EXE" nuget remove source "nuke-enterprise" &>/dev/null || true
- "$DOTNET_EXE" nuget add source "https://f.feedz.io/nuke/enterprise/nuget" --name "nuke-enterprise" --username "PAT" --password "$NUKE_ENTERPRISE_TOKEN" --store-password-in-clear-text &>/dev/null || true
-fi
-
-"$DOTNET_EXE" build "$BUILD_PROJECT_FILE" /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet
-"$DOTNET_EXE" run --project "$BUILD_PROJECT_FILE" --no-build -- "$@"
diff --git a/build/.editorconfig b/build/.editorconfig
deleted file mode 100644
index 31e43dc..0000000
--- a/build/.editorconfig
+++ /dev/null
@@ -1,11 +0,0 @@
-[*.cs]
-dotnet_style_qualification_for_field = false:warning
-dotnet_style_qualification_for_property = false:warning
-dotnet_style_qualification_for_method = false:warning
-dotnet_style_qualification_for_event = false:warning
-dotnet_style_require_accessibility_modifiers = never:warning
-
-csharp_style_expression_bodied_methods = true:silent
-csharp_style_expression_bodied_properties = true:warning
-csharp_style_expression_bodied_indexers = true:warning
-csharp_style_expression_bodied_accessors = true:warning
diff --git a/build/Build.cs b/build/Build.cs
deleted file mode 100644
index 4d9f0f8..0000000
--- a/build/Build.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-
-using dosymep.Nuke.RevitVersions;
-
-using Nuke.Common;
-using Nuke.Common.IO;
-using Nuke.Common.Tooling;
-using Nuke.Common.Tools.DotNet;
-using Nuke.Components;
-
-using Serilog;
-
-using static Nuke.Common.Tools.DotNet.DotNetTasks;
-using static Nuke.Common.Tools.Git.GitTasks;
-
-using Logger = Serilog.Core.Logger;
-
-class Build : NukeBuild, IHazSolution {
- static readonly AbsolutePath _appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
- static readonly AbsolutePath _bim4EveryonePath = $"{_appData}/pyRevit/Extensions/BIM4Everyone.lib";
-
- /// Support plugins are available for:
- /// - JetBrains ReSharper https://nuke.build/resharper
- /// - JetBrains Rider https://nuke.build/rider
- /// - Microsoft VisualStudio https://nuke.build/visualstudio
- /// - Microsoft VSCode https://nuke.build/vscode
- public static int Main() => Execute(x => x.Compile);
-
- [Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
- readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
-
- [Parameter] readonly string CommandName;
- [Parameter] readonly AbsolutePath Output = RootDirectory / "bin";
-
- ///
- /// Min Revit version.
- ///
- [Parameter("Min Revit version.")]
- readonly RevitVersion MinVersion = RevitVersion.Rv2016;
-
- ///
- /// Max Revit version.
- ///
- [Parameter("Max Revit version.")]
- readonly RevitVersion MaxVersion = RevitVersion.Rv2025;
-
- [Parameter("Build Revit versions.")] readonly RevitVersion[] RevitVersions = new RevitVersion[0];
-
- IEnumerable BuildRevitVersions;
-
- protected override void OnBuildInitialized() {
- base.OnBuildInitialized();
- BuildRevitVersions = RevitVersions.Length > 0
- ? RevitVersions
- : RevitVersion.GetRevitVersions(MinVersion, MaxVersion);
- }
-
- Target Clean => _ => _
- .Executes(() => {
- Output.CreateOrCleanDirectory();
- RootDirectory.GlobDirectories("**/bin", "**/obj")
- .Where(item => item != (RootDirectory / "build" / "bin"))
- .Where(item => item != (RootDirectory / "build" / "obj"))
- .DeleteDirectories();
- });
-
- Target Restore => _ => _
- .DependsOn(Clean)
- .Executes(() => {
- DotNetRestore(s => s
- .SetProjectFile(((IHazSolution) this).Solution));
- });
-
- Target DownloadBim4Everyone => _ => _
- .OnlyWhenStatic(() => !_bim4EveryonePath.DirectoryExists())
- .Executes(() => {
- Git($"clone https://github.com/dosymep/BIM4Everyone.git {_bim4EveryonePath}");
- });
-
- Target Compile => _ => _
- .DependsOn(Restore)
- .DependsOn(DownloadBim4Everyone)
- .Executes(() => {
- DotNetBuild(s => s
- .EnableForce()
- .DisableNoRestore()
- .SetConfiguration(Configuration)
- .SetProjectFile(CommandName)
- .When(IsServerBuild, _ => _
- .EnableContinuousIntegrationBuild())
- .CombineWith(BuildRevitVersions, (settings, version) => {
- return settings
- .SetOutputDirectory(Output / version)
- .SetProperty("RevitVersion", (int) version);
- }));
- });
-}
\ No newline at end of file
diff --git a/build/Build.csproj b/build/Build.csproj
new file mode 100644
index 0000000..424de3e
--- /dev/null
+++ b/build/Build.csproj
@@ -0,0 +1,23 @@
+
+
+
+ Exe
+ net10.0
+ enable
+ enable
+ Build
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/build/Configuration.cs b/build/Configuration.cs
deleted file mode 100644
index 9c08b1a..0000000
--- a/build/Configuration.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Linq;
-using Nuke.Common.Tooling;
-
-[TypeConverter(typeof(TypeConverter))]
-public class Configuration : Enumeration
-{
- public static Configuration Debug = new Configuration { Value = nameof(Debug) };
- public static Configuration Release = new Configuration { Value = nameof(Release) };
-
- public static implicit operator string(Configuration configuration)
- {
- return configuration.Value;
- }
-}
diff --git a/build/Directory.Build.props b/build/Directory.Build.props
deleted file mode 100644
index e147d63..0000000
--- a/build/Directory.Build.props
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/build/Directory.Build.targets b/build/Directory.Build.targets
deleted file mode 100644
index 2532609..0000000
--- a/build/Directory.Build.targets
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/build/Helpers/FileSystemHelpers.cs b/build/Helpers/FileSystemHelpers.cs
new file mode 100644
index 0000000..7235092
--- /dev/null
+++ b/build/Helpers/FileSystemHelpers.cs
@@ -0,0 +1,45 @@
+using System.IO.Compression;
+
+namespace Build.Helpers;
+
+internal static class FileSystemHelpers {
+ public static string EnsureTrailingSlash(string path) {
+ return path.EndsWith(Path.DirectorySeparatorChar)
+ || path.EndsWith(Path.AltDirectorySeparatorChar)
+ ? path
+ : path + Path.DirectorySeparatorChar;
+ }
+
+ public static async Task CreateZipAsync(
+ string sourceDirectory,
+ string zipPath,
+ CancellationToken cancellationToken) {
+ if(File.Exists(zipPath)) {
+ File.Delete(zipPath);
+ }
+
+ await ZipFile.CreateFromDirectoryAsync(
+ sourceDirectory,
+ zipPath,
+ CompressionLevel.Optimal,
+ includeBaseDirectory: true,
+ cancellationToken: cancellationToken);
+ }
+
+ public static void CopyDirectory(string sourceDirectory, string destinationDirectory) {
+ Directory.CreateDirectory(destinationDirectory);
+
+ foreach(string filePath in Directory.GetFiles(sourceDirectory)) {
+ File.Copy(
+ filePath,
+ Path.Combine(destinationDirectory, Path.GetFileName(filePath)),
+ overwrite: true);
+ }
+
+ foreach(string directoryPath in Directory.GetDirectories(sourceDirectory)) {
+ CopyDirectory(
+ directoryPath,
+ Path.Combine(destinationDirectory, Path.GetFileName(directoryPath)));
+ }
+ }
+}
diff --git a/build/Helpers/GitHubActionsSkip.cs b/build/Helpers/GitHubActionsSkip.cs
new file mode 100644
index 0000000..c8a894c
--- /dev/null
+++ b/build/Helpers/GitHubActionsSkip.cs
@@ -0,0 +1,13 @@
+using ModularPipelines.Context;
+using ModularPipelines.Enums;
+using ModularPipelines.Models;
+
+namespace Build.Helpers;
+
+internal static class GitHubActionsSkip {
+ public static SkipDecision WhenRunningOnGitHubActions(IModuleContext context) {
+ return context.IsRunningIn(BuildSystem.GitHubActions)
+ ? SkipDecision.Skip("Requires installed Autodesk Revit; skipped on GitHub Actions.")
+ : SkipDecision.DoNotSkip;
+ }
+}
diff --git a/build/Helpers/ParallelHelpers.cs b/build/Helpers/ParallelHelpers.cs
new file mode 100644
index 0000000..415c293
--- /dev/null
+++ b/build/Helpers/ParallelHelpers.cs
@@ -0,0 +1,17 @@
+namespace Build.Helpers;
+
+internal static class ParallelHelpers {
+ public static Task ForEachAsync(
+ IEnumerable source,
+ CancellationToken cancellationToken,
+ Func body,
+ int maxDegreeOfParallelism) {
+ return Parallel.ForEachAsync(
+ source,
+ new ParallelOptions {
+ CancellationToken = cancellationToken,
+ MaxDegreeOfParallelism = Math.Max(1, maxDegreeOfParallelism),
+ },
+ body);
+ }
+}
diff --git a/build/Helpers/SolutionFileHelpers.cs b/build/Helpers/SolutionFileHelpers.cs
new file mode 100644
index 0000000..6b67e1b
--- /dev/null
+++ b/build/Helpers/SolutionFileHelpers.cs
@@ -0,0 +1,42 @@
+using System.Xml.Linq;
+
+namespace Build.Helpers;
+
+internal static class SolutionFileHelpers {
+ ///
+ /// Returns absolute paths of projects marked with <Build Project="false" /> in an .slnx file.
+ ///
+ public static IReadOnlySet GetExcludedProjectPaths(string solutionPath) {
+ if(!File.Exists(solutionPath)
+ || !string.Equals(Path.GetExtension(solutionPath), ".slnx", StringComparison.OrdinalIgnoreCase)) {
+ return new HashSet(StringComparer.OrdinalIgnoreCase);
+ }
+
+ string solutionDirectory = Path.GetDirectoryName(solutionPath)!;
+ var excluded = new HashSet(StringComparer.OrdinalIgnoreCase);
+ var document = XDocument.Load(solutionPath);
+
+ foreach(var projectElement in document.Descendants("Project")) {
+ string? relativePath = projectElement.Attribute("Path")?.Value;
+ if(string.IsNullOrWhiteSpace(relativePath)) {
+ continue;
+ }
+
+ bool isExcluded = projectElement
+ .Elements("Build")
+ .Any(static build => IsFalse(build.Attribute("Project")?.Value));
+
+ if(!isExcluded) {
+ continue;
+ }
+
+ excluded.Add(Path.GetFullPath(Path.Combine(solutionDirectory, relativePath)));
+ }
+
+ return excluded;
+ }
+
+ private static bool IsFalse(string? value) {
+ return bool.TryParse(value, out bool parsed) && !parsed;
+ }
+}
diff --git a/build/Helpers/SolutionRootLocator.cs b/build/Helpers/SolutionRootLocator.cs
new file mode 100644
index 0000000..d40fa5d
--- /dev/null
+++ b/build/Helpers/SolutionRootLocator.cs
@@ -0,0 +1,17 @@
+namespace Build.Helpers;
+
+public sealed class SolutionRootLocator {
+ public string Find(string solutionFileName, string startDirectory) {
+ for(DirectoryInfo? directory = new(startDirectory);
+ directory is not null;
+ directory = directory.Parent) {
+ string solutionPath = Path.Combine(directory.FullName, solutionFileName);
+ if(File.Exists(solutionPath)) {
+ return directory.FullName;
+ }
+ }
+
+ throw new DirectoryNotFoundException(
+ $"Could not locate {solutionFileName} starting from {startDirectory}.");
+ }
+}
diff --git a/build/Modules/BuildModule.cs b/build/Modules/BuildModule.cs
new file mode 100644
index 0000000..978ebb4
--- /dev/null
+++ b/build/Modules/BuildModule.cs
@@ -0,0 +1,63 @@
+using Build.Helpers;
+using Build.Options;
+using Build.Versioning;
+
+using Microsoft.Extensions.Options;
+
+using ModularPipelines.Attributes;
+using ModularPipelines.Context;
+using ModularPipelines.DotNet.Extensions;
+using ModularPipelines.DotNet.Options;
+using ModularPipelines.Git;
+using ModularPipelines.Git.Extensions;
+using ModularPipelines.Modules;
+
+namespace Build.Modules;
+
+[DependsOn]
+public sealed class BuildModule : Module {
+ private readonly BuildOptions _options;
+ private readonly BuildVersionFactory _versions;
+
+ public BuildModule(IOptions options, BuildVersionFactory versions) {
+ _options = options.Value;
+ _versions = versions;
+ }
+
+ protected override async Task ExecuteModuleAsync(IModuleContext context, CancellationToken cancellationToken) {
+ var git = context.Git().Information;
+ string projectPath = Path.Combine(_options.SrcDirectory, "RevitCoreConsole", "RevitCoreConsole.csproj");
+
+ foreach(string revitVersion in _options.RevitVersions) {
+ await BuildConsoleAsync(context, git, projectPath, revitVersion, cancellationToken);
+ }
+ }
+
+ private async Task BuildConsoleAsync(
+ IModuleContext context,
+ IGitInformation git,
+ string projectPath,
+ string revitVersion,
+ CancellationToken cancellationToken) {
+ string outputDirectory = _options.GetConsoleOutputDirectory(revitVersion);
+ if(Directory.Exists(outputDirectory)) {
+ Directory.Delete(outputDirectory, recursive: true);
+ }
+
+ await context.DotNet()
+ .Build(
+ new DotNetBuildOptions {
+ ProjectSolution = projectPath,
+ Configuration = _options.Configuration,
+ NoRestore = false,
+ NoIncremental = true,
+ Arguments = ["--force"],
+ Properties = [
+ ("RevitVersion", revitVersion),
+ ("OutputPath", FileSystemHelpers.EnsureTrailingSlash(outputDirectory)),
+ .._versions.PropertiesFor(git, revitVersion),
+ ]
+ },
+ cancellationToken: cancellationToken);
+ }
+}
diff --git a/build/Modules/BuildSampleModule.cs b/build/Modules/BuildSampleModule.cs
new file mode 100644
index 0000000..11dcede
--- /dev/null
+++ b/build/Modules/BuildSampleModule.cs
@@ -0,0 +1,106 @@
+using Build.Helpers;
+using Build.Options;
+using Build.Versioning;
+
+using Microsoft.Extensions.Options;
+
+using ModularPipelines.Attributes;
+using ModularPipelines.Context;
+using ModularPipelines.DotNet.Extensions;
+using ModularPipelines.DotNet.Options;
+using ModularPipelines.Git;
+using ModularPipelines.Git.Extensions;
+using ModularPipelines.Modules;
+
+namespace Build.Modules;
+
+[DependsOn]
+public sealed class BuildSampleModule : Module {
+ private readonly BuildOptions _options;
+ private readonly BuildVersionFactory _versions;
+
+ public BuildSampleModule(IOptions options, BuildVersionFactory versions) {
+ _options = options.Value;
+ _versions = versions;
+ }
+
+ protected override Task ExecuteModuleAsync(IModuleContext context, CancellationToken cancellationToken) {
+ var git = context.Git().Information;
+
+ return ParallelHelpers.ForEachAsync(
+ GetSampleProjects(),
+ cancellationToken,
+ (projectPath, token) => new ValueTask(BuildSampleProjectAsync(context, git, projectPath, token)),
+ _options.MaxDegreeOfParallelism);
+ }
+
+ private async Task BuildSampleProjectAsync(
+ IModuleContext context,
+ IGitInformation git,
+ string projectPath,
+ CancellationToken cancellationToken) {
+ string pluginName = Path.GetFileNameWithoutExtension(projectPath);
+ string packageContentsPath = Path.Combine(Path.GetDirectoryName(projectPath)!, "PackageContents.xml");
+
+ foreach(string revitVersion in _options.RevitVersions) {
+ await BuildSampleVersionAsync(
+ context,
+ git,
+ projectPath,
+ pluginName,
+ packageContentsPath,
+ revitVersion,
+ cancellationToken);
+ }
+ }
+
+ private async Task BuildSampleVersionAsync(
+ IModuleContext context,
+ IGitInformation git,
+ string projectPath,
+ string pluginName,
+ string packageContentsPath,
+ string revitVersion,
+ CancellationToken cancellationToken) {
+ string bundleDirectory = _options.GetSampleBundleDirectory(revitVersion, pluginName);
+ string componentDirectory = _options.GetSampleComponentDirectory(revitVersion, pluginName);
+
+ if(Directory.Exists(bundleDirectory)) {
+ Directory.Delete(bundleDirectory, recursive: true);
+ }
+
+ Directory.CreateDirectory(bundleDirectory);
+ File.Copy(packageContentsPath, Path.Combine(bundleDirectory, "PackageContents.xml"));
+
+ await context.DotNet()
+ .Build(
+ new DotNetBuildOptions {
+ ProjectSolution = projectPath,
+ Configuration = _options.Configuration,
+ NoRestore = false,
+ NoIncremental = true,
+ Arguments = ["--force"],
+ Properties = [
+ ("RevitVersion", revitVersion),
+ ("OutputPath", FileSystemHelpers.EnsureTrailingSlash(componentDirectory)),
+ .._versions.PropertiesFor(git, revitVersion),
+ ]
+ },
+ cancellationToken: cancellationToken);
+ }
+
+ private IEnumerable GetSampleProjects() {
+ var excludedProjects = SolutionFileHelpers.GetExcludedProjectPaths(_options.SolutionPath);
+
+ return Directory.GetFiles(_options.SamplesDirectory, "*.csproj", SearchOption.AllDirectories)
+ .Where(projectPath => {
+ string? projectDirectory = Path.GetDirectoryName(projectPath);
+ if(projectDirectory is null
+ || !File.Exists(Path.Combine(projectDirectory, "PackageContents.xml"))) {
+ return false;
+ }
+
+ return !excludedProjects.Contains(Path.GetFullPath(projectPath));
+ });
+ }
+}
diff --git a/build/Modules/CleanModule.cs b/build/Modules/CleanModule.cs
new file mode 100644
index 0000000..f6fe3d8
--- /dev/null
+++ b/build/Modules/CleanModule.cs
@@ -0,0 +1,52 @@
+using Build.Options;
+
+using Microsoft.Extensions.Options;
+
+using ModularPipelines.Context;
+using ModularPipelines.Modules;
+
+namespace Build.Modules;
+
+public sealed class CleanModule : Module {
+ private readonly BuildOptions _options;
+
+ public CleanModule(IOptions options) {
+ _options = options.Value;
+ }
+
+ protected override Task ExecuteModuleAsync(IModuleContext context, CancellationToken cancellationToken) {
+ DeleteDirectory(_options.BinDirectory);
+ DeleteDirectory(_options.ArtifactsDirectory);
+ DeleteDirectory(_options.TestResultsDirectory);
+
+ DeleteBinAndObj(_options.SrcDirectory);
+ DeleteBinAndObj(_options.SamplesDirectory);
+ DeleteBinAndObj(_options.TestsDirectory);
+
+ return Task.CompletedTask;
+ }
+
+ private static void DeleteDirectory(string directoryPath) {
+ if(Directory.Exists(directoryPath)) {
+ Directory.Delete(directoryPath, recursive: true);
+ }
+ }
+
+ private static void DeleteBinAndObj(string rootDirectory) {
+ if(!Directory.Exists(rootDirectory)) {
+ return;
+ }
+
+ var directories = Directory
+ .EnumerateDirectories(rootDirectory, "*", SearchOption.AllDirectories)
+ .Where(static path => Path.GetFileName(path) is "bin" or "obj")
+ .OrderBy(static path => path.Length)
+ .ToList();
+
+ foreach(string directory in directories) {
+ if(Directory.Exists(directory)) {
+ Directory.Delete(directory, recursive: true);
+ }
+ }
+ }
+}
diff --git a/build/Modules/PackageModule.cs b/build/Modules/PackageModule.cs
new file mode 100644
index 0000000..afd2500
--- /dev/null
+++ b/build/Modules/PackageModule.cs
@@ -0,0 +1,36 @@
+using Build.Helpers;
+using Build.Options;
+
+using Microsoft.Extensions.Options;
+
+using ModularPipelines.Attributes;
+using ModularPipelines.Context;
+using ModularPipelines.Modules;
+
+namespace Build.Modules;
+
+[DependsOn]
+public sealed class PackageModule : Module {
+ private readonly BuildOptions _options;
+
+ public PackageModule(IOptions options) {
+ _options = options.Value;
+ }
+
+ protected override Task ExecuteModuleAsync(IModuleContext context, CancellationToken cancellationToken) {
+ Directory.CreateDirectory(_options.ArtifactsDirectory);
+
+ return ParallelHelpers.ForEachAsync(
+ _options.RevitVersions,
+ cancellationToken,
+ (revitVersion, token) => new ValueTask(PackageConsoleAsync(revitVersion, token)),
+ _options.MaxDegreeOfParallelism);
+ }
+
+ private Task PackageConsoleAsync(string revitVersion, CancellationToken cancellationToken) {
+ return FileSystemHelpers.CreateZipAsync(
+ _options.GetConsoleOutputDirectory(revitVersion),
+ _options.GetConsoleArchivePath(revitVersion),
+ cancellationToken);
+ }
+}
diff --git a/build/Modules/PackageSampleModule.cs b/build/Modules/PackageSampleModule.cs
new file mode 100644
index 0000000..d616a81
--- /dev/null
+++ b/build/Modules/PackageSampleModule.cs
@@ -0,0 +1,91 @@
+using Build.Helpers;
+using Build.Options;
+
+using Microsoft.Extensions.Options;
+
+using ModularPipelines.Attributes;
+using ModularPipelines.Context;
+using ModularPipelines.Modules;
+
+namespace Build.Modules;
+
+[DependsOn]
+public sealed class PackageSampleModule : Module {
+ private readonly BuildOptions _options;
+
+ public PackageSampleModule(IOptions options) {
+ _options = options.Value;
+ }
+
+ protected override async Task ExecuteModuleAsync(IModuleContext context, CancellationToken cancellationToken) {
+ Directory.CreateDirectory(_options.ArtifactsDirectory);
+
+ string stagingRoot = Path.Combine(_options.ArtifactsDirectory, ".staging");
+ try {
+ await ParallelHelpers.ForEachAsync(
+ GetBuiltPluginNames(),
+ cancellationToken,
+ (pluginName, token) => new ValueTask(PackagePluginAsync(stagingRoot, pluginName, token)),
+ _options.MaxDegreeOfParallelism);
+ } finally {
+ if(Directory.Exists(stagingRoot)) {
+ Directory.Delete(stagingRoot, recursive: true);
+ }
+ }
+ }
+
+ private async Task PackagePluginAsync(
+ string stagingRoot,
+ string pluginName,
+ CancellationToken cancellationToken) {
+ string bundleDirectory = Path.Combine(stagingRoot, $"{pluginName}.bundle");
+ Directory.CreateDirectory(bundleDirectory);
+
+ foreach(string revitVersion in _options.RevitVersions) {
+ StagePluginVersion(bundleDirectory, pluginName, revitVersion);
+ }
+
+ await FileSystemHelpers.CreateZipAsync(
+ bundleDirectory,
+ _options.GetSampleArchivePath(pluginName),
+ cancellationToken);
+ }
+
+ private void StagePluginVersion(string bundleDirectory, string pluginName, string revitVersion) {
+ string versionBundleDirectory = _options.GetSampleBundleDirectory(revitVersion, pluginName);
+ if(!Directory.Exists(versionBundleDirectory)) {
+ return;
+ }
+
+ string manifestPath = Path.Combine(versionBundleDirectory, "PackageContents.xml");
+ string stagedManifestPath = Path.Combine(bundleDirectory, "PackageContents.xml");
+ if(File.Exists(manifestPath) && !File.Exists(stagedManifestPath)) {
+ File.Copy(manifestPath, stagedManifestPath);
+ }
+
+ string componentDirectory = Path.Combine(versionBundleDirectory, revitVersion);
+ if(Directory.Exists(componentDirectory)) {
+ FileSystemHelpers.CopyDirectory(
+ componentDirectory,
+ Path.Combine(bundleDirectory, revitVersion));
+ }
+ }
+
+ private IEnumerable GetBuiltPluginNames() {
+ var pluginNames = new HashSet(StringComparer.OrdinalIgnoreCase);
+
+ foreach(string revitVersion in _options.RevitVersions) {
+ string versionBinDirectory = Path.Combine(_options.BinDirectory, revitVersion);
+ if(!Directory.Exists(versionBinDirectory)) {
+ continue;
+ }
+
+ foreach(string bundleDirectory in Directory.GetDirectories(versionBinDirectory, "*.bundle")) {
+ string bundleName = Path.GetFileName(bundleDirectory);
+ pluginNames.Add(bundleName[..^".bundle".Length]);
+ }
+ }
+
+ return pluginNames.Order(StringComparer.OrdinalIgnoreCase);
+ }
+}
diff --git a/build/Modules/RestoreModule.cs b/build/Modules/RestoreModule.cs
new file mode 100644
index 0000000..8846a67
--- /dev/null
+++ b/build/Modules/RestoreModule.cs
@@ -0,0 +1,27 @@
+using Build.Options;
+
+using Microsoft.Extensions.Options;
+
+using ModularPipelines.Attributes;
+using ModularPipelines.Context;
+using ModularPipelines.DotNet.Extensions;
+using ModularPipelines.DotNet.Options;
+using ModularPipelines.Modules;
+
+namespace Build.Modules;
+
+[DependsOn]
+public sealed class RestoreModule : Module {
+ private readonly BuildOptions _options;
+
+ public RestoreModule(IOptions options) {
+ _options = options.Value;
+ }
+
+ protected override async Task ExecuteModuleAsync(IModuleContext context, CancellationToken cancellationToken) {
+ await context.DotNet()
+ .Restore(
+ new DotNetRestoreOptions { ProjectSolution = _options.SolutionPath },
+ cancellationToken: cancellationToken);
+ }
+}
diff --git a/build/Modules/RunConsoleModule.cs b/build/Modules/RunConsoleModule.cs
new file mode 100644
index 0000000..24cf2e1
--- /dev/null
+++ b/build/Modules/RunConsoleModule.cs
@@ -0,0 +1,222 @@
+using System.Collections.Concurrent;
+using System.Diagnostics;
+
+using Build.Helpers;
+using Build.Options;
+
+using Microsoft.Extensions.Options;
+
+using ModularPipelines.Attributes;
+using ModularPipelines.Configuration;
+using ModularPipelines.Context;
+using ModularPipelines.Modules;
+
+namespace Build.Modules;
+
+[DependsOn]
+[DependsOn]
+public sealed class RunConsoleModule : Module {
+ private readonly BuildOptions _options;
+
+ public RunConsoleModule(IOptions options) {
+ _options = options.Value;
+ }
+
+ protected override ModuleConfiguration Configure() => ModuleConfiguration.Create()
+ .WithSkipWhen(GitHubActionsSkip.WhenRunningOnGitHubActions)
+ .Build();
+
+ protected override async Task ExecuteModuleAsync(IModuleContext context, CancellationToken cancellationToken) {
+ ConsoleRunJob[] jobs = [.. PrepareJobs()];
+ var runningProcesses = new ConcurrentDictionary();
+
+ await using var registration = cancellationToken.Register(
+ static state => KillAll((ConcurrentDictionary) state!),
+ runningProcesses);
+
+ try {
+ await ParallelHelpers.ForEachAsync(
+ jobs,
+ cancellationToken,
+ (job, token) => new ValueTask(RunConsoleAsync(job, runningProcesses, token)),
+ _options.MaxDegreeOfParallelism);
+ } finally {
+ KillAll(runningProcesses);
+ }
+ }
+
+ private static async Task RunConsoleAsync(
+ ConsoleRunJob job,
+ ConcurrentDictionary runningProcesses,
+ CancellationToken cancellationToken) {
+ string stdoutPath = Path.Combine(job.WorkDirectory, "stdout.log");
+ string stderrPath = Path.Combine(job.WorkDirectory, "stderr.log");
+
+ var startInfo = new ProcessStartInfo {
+ FileName = job.ConsoleExe,
+ WorkingDirectory = Path.GetDirectoryName(job.ConsoleExe),
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ };
+ startInfo.ArgumentList.Add("/i");
+ startInfo.ArgumentList.Add(job.ModelPath);
+ startInfo.ArgumentList.Add("/al");
+ startInfo.ArgumentList.Add(job.BundleZipPath);
+
+ using var process = Process.Start(startInfo)
+ ?? throw new InvalidOperationException($"Failed to start '{job.ConsoleExe}'.");
+
+ runningProcesses[process.Id] = process;
+
+ try {
+ await using FileStream stdoutFile = File.Create(stdoutPath);
+ await using FileStream stderrFile = File.Create(stderrPath);
+
+ Task stdoutCopy = process.StandardOutput.BaseStream.CopyToAsync(stdoutFile, cancellationToken);
+ Task stderrCopy = process.StandardError.BaseStream.CopyToAsync(stderrFile, cancellationToken);
+
+ try {
+ await process.WaitForExitAsync(cancellationToken);
+ await Task.WhenAll(stdoutCopy, stderrCopy);
+ } catch(OperationCanceledException) {
+ TryKill(process);
+ throw;
+ }
+
+ if(process.ExitCode != 0) {
+ throw new InvalidOperationException(
+ $"RevitCoreConsole exited with code {process.ExitCode}. See '{stdoutPath}' and '{stderrPath}'.");
+ }
+ } finally {
+ runningProcesses.TryRemove(process.Id, out _);
+ }
+ }
+
+ private static void KillAll(ConcurrentDictionary runningProcesses) {
+ foreach(var pair in runningProcesses.ToArray()) {
+ if(runningProcesses.TryRemove(pair.Key, out var process)) {
+ TryKill(process);
+ }
+ }
+ }
+
+ private static void TryKill(Process process) {
+ try {
+ if(!process.HasExited) {
+ process.Kill(entireProcessTree: true);
+ process.WaitForExit(milliseconds: 5_000);
+ }
+ } catch(InvalidOperationException) {
+ } catch(NotSupportedException) {
+ } catch(System.ComponentModel.Win32Exception) {
+ }
+ }
+
+ private IEnumerable PrepareJobs() {
+ if(!Directory.Exists(_options.ArtifactsDirectory)) {
+ yield break;
+ }
+
+ string[] bundleZipPaths = Directory.GetFiles(_options.ArtifactsDirectory, "*.zip")
+ .Where(static path => !Path.GetFileName(path)
+ .StartsWith("RevitCoreConsole.", StringComparison.OrdinalIgnoreCase))
+ .ToArray();
+
+ foreach(string revitVersion in _options.RevitVersions) {
+ if(!File.Exists(@$"C:\Program Files\Autodesk\Revit {revitVersion}\Revit.exe")) {
+ continue;
+ }
+
+ string? sourceModelPath = ResolveSourceModelPath(revitVersion);
+ if(sourceModelPath is null) {
+ continue;
+ }
+
+ string consoleExe = Path.Combine(
+ _options.GetConsoleOutputDirectory(revitVersion),
+ "RevitCoreConsole.exe");
+
+ string runsRoot = Path.Combine(_options.BinDirectory, revitVersion, "runs");
+ RecreateDirectory(runsRoot);
+
+ foreach(string bundleZipPath in bundleZipPaths) {
+ yield return PrepareJob(consoleExe, sourceModelPath, bundleZipPath, runsRoot);
+ }
+ }
+ }
+
+ private static ConsoleRunJob PrepareJob(
+ string consoleExe,
+ string sourceModelPath,
+ string sourceBundleZipPath,
+ string runsRoot) {
+ string runName = Path.GetFileNameWithoutExtension(sourceBundleZipPath);
+ string workDirectory = Path.Combine(runsRoot, runName);
+ RecreateDirectory(workDirectory);
+
+ string modelPath = Path.Combine(workDirectory, Path.GetFileName(sourceModelPath));
+ string bundleZipPath = Path.Combine(workDirectory, Path.GetFileName(sourceBundleZipPath));
+
+ File.Copy(sourceModelPath, modelPath, overwrite: true);
+ File.Copy(sourceBundleZipPath, bundleZipPath, overwrite: true);
+
+ return new ConsoleRunJob(consoleExe, workDirectory, modelPath, bundleZipPath);
+ }
+
+ private string? ResolveSourceModelPath(string revitVersion) {
+ string sourceDirectory = Path.Combine(_options.TestsFilesDirectory, revitVersion);
+ if(!Directory.Exists(sourceDirectory)) {
+ return null;
+ }
+
+ string[] sourceFiles = Directory.GetFiles(sourceDirectory, "*.rvt")
+ .Where(static path => !IsBackupFile(path))
+ .ToArray();
+
+ if(sourceFiles.Length == 0) {
+ return null;
+ }
+
+ string? preferredFile =
+ FindPreferredModel(sourceFiles, "rac_basic_sample_project.rvt")
+ ?? FindPreferredModel(sourceFiles, "rac_advanced_sample_project.rvt")
+ ?? Path.GetFileName(sourceFiles[0]);
+
+ return Path.Combine(sourceDirectory, preferredFile!);
+ }
+
+ private static void RecreateDirectory(string directoryPath) {
+ if(Directory.Exists(directoryPath)) {
+ Directory.Delete(directoryPath, recursive: true);
+ }
+
+ Directory.CreateDirectory(directoryPath);
+ }
+
+ private static string? FindPreferredModel(IEnumerable sourceFiles, string fileName) {
+ return sourceFiles
+ .Select(Path.GetFileName)
+ .FirstOrDefault(name =>
+ name is not null
+ && name.Equals(fileName, StringComparison.OrdinalIgnoreCase));
+ }
+
+ private static bool IsBackupFile(string path) {
+ string fileName = Path.GetFileNameWithoutExtension(path);
+ int lastDotIndex = fileName.LastIndexOf('.');
+ if(lastDotIndex < 0) {
+ return false;
+ }
+
+ string suffix = fileName[(lastDotIndex + 1)..];
+ return suffix.Length == 4 && suffix.All(char.IsDigit);
+ }
+
+ private sealed record ConsoleRunJob(
+ string ConsoleExe,
+ string WorkDirectory,
+ string ModelPath,
+ string BundleZipPath);
+}
diff --git a/build/Modules/TestsModule.cs b/build/Modules/TestsModule.cs
new file mode 100644
index 0000000..3f242b4
--- /dev/null
+++ b/build/Modules/TestsModule.cs
@@ -0,0 +1,55 @@
+using Build.Helpers;
+using Build.Options;
+
+using Microsoft.Extensions.Options;
+
+using ModularPipelines.Attributes;
+using ModularPipelines.Configuration;
+using ModularPipelines.Context;
+using ModularPipelines.Modules;
+
+namespace Build.Modules;
+
+[DependsOn]
+public sealed class TestsModule : Module {
+ private readonly BuildOptions _options;
+
+ public TestsModule(IOptions options) {
+ _options = options.Value;
+ }
+
+ protected override ModuleConfiguration Configure() => ModuleConfiguration.Create()
+ .WithSkipWhen(GitHubActionsSkip.WhenRunningOnGitHubActions)
+ .Build();
+
+ protected override async Task ExecuteModuleAsync(IModuleContext context, CancellationToken cancellationToken) {
+ string testProjectPath = Path.Combine(
+ _options.TestsDirectory,
+ "RevitEngine.UnitTests",
+ "RevitEngine.UnitTests.csproj");
+
+ foreach(string revitVersion in _options.RevitVersions) {
+ await RunTestsAsync(context, testProjectPath, revitVersion, cancellationToken);
+ }
+ }
+
+ private async Task RunTestsAsync(
+ IModuleContext context,
+ string testProjectPath,
+ string revitVersion,
+ CancellationToken cancellationToken) {
+ // Use classic `dotnet test ` — ModularPipelines DotNetTestOptions
+ // maps to MTP `--project` and breaks MSBuild `-p:` properties (MSB1001).
+ await context.Shell.Command.ExecuteCommandLineTool(
+ new ExecutableCommandOptions {
+ Tool = "dotnet",
+ Arguments = [
+ "test",
+ testProjectPath,
+ "--configuration", _options.Configuration,
+ $"-p:RevitVersion={revitVersion}",
+ ]
+ },
+ cancellationToken: cancellationToken);
+ }
+}
diff --git a/build/Options/BuildOptions.cs b/build/Options/BuildOptions.cs
new file mode 100644
index 0000000..b2d4344
--- /dev/null
+++ b/build/Options/BuildOptions.cs
@@ -0,0 +1,53 @@
+namespace Build.Options;
+
+public sealed class BuildOptions {
+ public string Configuration { get; set; } = "Release";
+
+ public string[] RevitVersions { get; set; } = [
+ "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027"
+ ];
+
+ ///
+ /// Max parallel work items for version/project fan-out. Default: processor count.
+ ///
+ public int MaxDegreeOfParallelism { get; set; } = Math.Max(1, Environment.ProcessorCount / 4);
+
+ public string SolutionFileName { get; set; } = "RevitCoreConsole.slnx";
+
+ public string SolutionRoot { get; set; } = string.Empty;
+
+ public string SolutionPath => Path.Combine(SolutionRoot, SolutionFileName);
+
+ public string SrcDirectory => Path.Combine(SolutionRoot, "src");
+
+ public string SamplesDirectory => Path.Combine(SolutionRoot, "samples");
+
+ public string TestsDirectory => Path.Combine(SolutionRoot, "tests");
+
+ public string TestsFilesDirectory => Path.Combine(SolutionRoot, "build", "tests_files");
+
+ public string BinDirectory => Path.Combine(SolutionRoot, "bin");
+
+ public string ArtifactsDirectory => Path.Combine(SolutionRoot, "artifacts");
+ public string TestResultsDirectory => Path.Combine(SolutionRoot, "TestResults");
+
+ public string GetConsoleOutputDirectory(string revitVersion) {
+ return Path.Combine(BinDirectory, revitVersion, "RevitCoreConsole");
+ }
+
+ public string GetSampleBundleDirectory(string revitVersion, string pluginName) {
+ return Path.Combine(BinDirectory, revitVersion, $"{pluginName}.bundle");
+ }
+
+ public string GetSampleComponentDirectory(string revitVersion, string pluginName) {
+ return Path.Combine(GetSampleBundleDirectory(revitVersion, pluginName), revitVersion);
+ }
+
+ public string GetConsoleArchivePath(string revitVersion) {
+ return Path.Combine(ArtifactsDirectory, $"RevitCoreConsole.{revitVersion}.zip");
+ }
+
+ public string GetSampleArchivePath(string pluginName) {
+ return Path.Combine(ArtifactsDirectory, $"{pluginName}.zip");
+ }
+}
diff --git a/build/Options/ExecutableCommandOptions.cs b/build/Options/ExecutableCommandOptions.cs
new file mode 100644
index 0000000..3ef3e55
--- /dev/null
+++ b/build/Options/ExecutableCommandOptions.cs
@@ -0,0 +1,5 @@
+using ModularPipelines.Options;
+
+namespace Build.Options;
+
+internal sealed record ExecutableCommandOptions : CommandLineToolOptions;
diff --git a/build/Program.cs b/build/Program.cs
new file mode 100644
index 0000000..1122927
--- /dev/null
+++ b/build/Program.cs
@@ -0,0 +1,51 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Options;
+
+using ModularPipelines;
+using ModularPipelines.Extensions;
+
+using Build;
+using Build.Helpers;
+using Build.Modules;
+using Build.Options;
+using Build.Versioning;
+
+var builder = Pipeline.CreateBuilder(args);
+
+builder.Services.AddOptions()
+ .Configure(options => {
+ options.SolutionRoot = new SolutionRootLocator()
+ .Find(options.SolutionFileName, AppContext.BaseDirectory);
+
+ string? configuration = Environment.GetEnvironmentVariable("CONFIGURATION");
+ if(!string.IsNullOrWhiteSpace(configuration)) {
+ options.Configuration = configuration.Trim();
+ }
+
+ string? revitVersions = Environment.GetEnvironmentVariable("REVIT_VERSIONS");
+ if(!string.IsNullOrWhiteSpace(revitVersions)) {
+ options.RevitVersions = revitVersions
+ .Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+ }
+
+ string? maxParallelism = Environment.GetEnvironmentVariable("MAX_PARALLELISM");
+ if(int.TryParse(maxParallelism, out int degree) && degree > 0) {
+ options.MaxDegreeOfParallelism = degree;
+ }
+ });
+
+builder.Services.AddSingleton(static services => {
+ BuildOptions options = services.GetRequiredService>().Value;
+ return new BuildVersionFactory(options.SolutionRoot);
+});
+
+builder.AddModule();
+builder.AddModule();
+builder.AddModule();
+builder.AddModule();
+builder.AddModule();
+builder.AddModule();
+builder.AddModule();
+builder.AddModule();
+
+await builder.Build().RunAsync();
diff --git a/build/Versioning/BuildVersionFactory.cs b/build/Versioning/BuildVersionFactory.cs
new file mode 100644
index 0000000..14755fc
--- /dev/null
+++ b/build/Versioning/BuildVersionFactory.cs
@@ -0,0 +1,68 @@
+using System.Xml.Linq;
+
+using ModularPipelines.Git;
+
+namespace Build.Versioning;
+
+public sealed class BuildVersionFactory {
+ private readonly string _prefix;
+
+ public BuildVersionFactory(string solutionRoot) {
+ _prefix = ReadPrefix(solutionRoot);
+ }
+
+ public string ForRevit(IGitInformation git, string revitVersion) {
+ string hash = FirstNonEmpty(git.LastCommitShortSha, git.LastCommitSha)
+ ?? throw new InvalidOperationException("Git commit hash is unavailable.");
+
+ return $"{_prefix}-{ToCommitToken(hash)}.{revitVersion}";
+ }
+
+ public (string Name, string Value)[] PropertiesFor(IGitInformation git, string revitVersion) {
+ string version = ForRevit(git, revitVersion);
+ return [
+ ("Version", version),
+ ("InformationalVersion", version),
+ ("IncludeSourceRevisionInInformationalVersion", "false"),
+ ];
+ }
+
+ private static string? FirstNonEmpty(params string?[] values) {
+ return values.FirstOrDefault(value => !string.IsNullOrWhiteSpace(value));
+ }
+
+ private static string ReadPrefix(string solutionRoot) {
+ string propsPath = Path.Combine(solutionRoot, "Directory.Build.props");
+ string? version = XDocument.Load(propsPath)
+ .Descendants("Version")
+ .FirstOrDefault()
+ ?.Value
+ .Trim();
+
+ if(string.IsNullOrWhiteSpace(version)) {
+ throw new InvalidOperationException($"Version element was not found in {propsPath}.");
+ }
+
+ int suffixIndex = version.IndexOf('-');
+ return suffixIndex >= 0 ? version[..suffixIndex] : version;
+ }
+
+ private static string ToCommitToken(string commitHash) {
+ string hash = commitHash.Trim().ToLowerInvariant();
+ if(hash.Length > 7) {
+ hash = hash[..7];
+ }
+
+ if(hash.Length == 0) {
+ throw new InvalidOperationException("Commit hash is empty.");
+ }
+
+ foreach(char character in hash) {
+ if(character is < '0' or > '9') {
+ return hash;
+ }
+ }
+
+ return "g" + hash;
+ }
+}
diff --git a/build/_build.csproj b/build/_build.csproj
deleted file mode 100644
index 31cc92b..0000000
--- a/build/_build.csproj
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
- Exe
- net8.0
-
- CS0649;CS0169;CA1050;CA1822;CA2211;IDE1006
- ..
- ..
- 1
- false
-
-
-
-
-
-
-
-
-
diff --git a/build/_build.csproj.DotSettings b/build/_build.csproj.DotSettings
deleted file mode 100644
index eb3f4c2..0000000
--- a/build/_build.csproj.DotSettings
+++ /dev/null
@@ -1,28 +0,0 @@
-
- DO_NOT_SHOW
- DO_NOT_SHOW
- DO_NOT_SHOW
- DO_NOT_SHOW
- DO_NOT_SHOW
- Implicit
- Implicit
- ExpressionBody
- 0
- NEXT_LINE
- True
- False
- 120
- IF_OWNER_IS_SINGLE_LINE
- WRAP_IF_LONG
- False
- <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" />
- <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" />
- True
- True
- True
- True
- True
- True
- True
- True
- True
diff --git a/build/tests_files/2018/rac_basic_sample_project.rvt b/build/tests_files/2018/rac_basic_sample_project.rvt
new file mode 100644
index 0000000..330ef4c
Binary files /dev/null and b/build/tests_files/2018/rac_basic_sample_project.rvt differ
diff --git a/build/tests_files/2019/rac_advanced_sample_project.rvt b/build/tests_files/2019/rac_advanced_sample_project.rvt
new file mode 100644
index 0000000..7cbd831
Binary files /dev/null and b/build/tests_files/2019/rac_advanced_sample_project.rvt differ
diff --git a/build/tests_files/2020/rac_advanced_sample_project.rvt b/build/tests_files/2020/rac_advanced_sample_project.rvt
new file mode 100644
index 0000000..3da522a
Binary files /dev/null and b/build/tests_files/2020/rac_advanced_sample_project.rvt differ
diff --git a/build/tests_files/2021/rac_basic_sample_project.rvt b/build/tests_files/2021/rac_basic_sample_project.rvt
new file mode 100644
index 0000000..7b8fa56
Binary files /dev/null and b/build/tests_files/2021/rac_basic_sample_project.rvt differ
diff --git a/build/tests_files/2022/rac_basic_sample_project.rvt b/build/tests_files/2022/rac_basic_sample_project.rvt
new file mode 100644
index 0000000..8cf6f61
Binary files /dev/null and b/build/tests_files/2022/rac_basic_sample_project.rvt differ
diff --git a/build/tests_files/2023/rac_basic_sample_project.rvt b/build/tests_files/2023/rac_basic_sample_project.rvt
new file mode 100644
index 0000000..cbd31fe
Binary files /dev/null and b/build/tests_files/2023/rac_basic_sample_project.rvt differ
diff --git a/build/tests_files/2024/rac_basic_sample_project.rvt b/build/tests_files/2024/rac_basic_sample_project.rvt
new file mode 100644
index 0000000..3d846e2
Binary files /dev/null and b/build/tests_files/2024/rac_basic_sample_project.rvt differ
diff --git a/build/tests_files/2025/rac_basic_sample_project.rvt b/build/tests_files/2025/rac_basic_sample_project.rvt
new file mode 100644
index 0000000..ffaa007
Binary files /dev/null and b/build/tests_files/2025/rac_basic_sample_project.rvt differ
diff --git a/build/tests_files/2026/rac_basic_sample_project.0001.rvt b/build/tests_files/2026/rac_basic_sample_project.0001.rvt
new file mode 100644
index 0000000..0d5da4e
Binary files /dev/null and b/build/tests_files/2026/rac_basic_sample_project.0001.rvt differ
diff --git a/build/tests_files/2026/rac_basic_sample_project.0002.rvt b/build/tests_files/2026/rac_basic_sample_project.0002.rvt
new file mode 100644
index 0000000..1059712
Binary files /dev/null and b/build/tests_files/2026/rac_basic_sample_project.0002.rvt differ
diff --git a/build/tests_files/2026/rac_basic_sample_project.rvt b/build/tests_files/2026/rac_basic_sample_project.rvt
new file mode 100644
index 0000000..530841c
Binary files /dev/null and b/build/tests_files/2026/rac_basic_sample_project.rvt differ
diff --git a/build/tests_files/2027/rac_basic_sample_project.rvt b/build/tests_files/2027/rac_basic_sample_project.rvt
new file mode 100644
index 0000000..0effe92
Binary files /dev/null and b/build/tests_files/2027/rac_basic_sample_project.rvt differ
diff --git a/global.json b/global.json
new file mode 100644
index 0000000..a3218f5
--- /dev/null
+++ b/global.json
@@ -0,0 +1,10 @@
+{
+ "sdk": {
+ "version": "10.0.100",
+ "rollForward": "latestFeature",
+ "allowPrerelease": false
+ },
+ "test": {
+ "runner": "Microsoft.Testing.Platform"
+ }
+}
\ No newline at end of file
diff --git a/samples/Sample.CsvExport/CsvExportApp.cs b/samples/Sample.CsvExport/CsvExportApp.cs
new file mode 100644
index 0000000..54078fb
--- /dev/null
+++ b/samples/Sample.CsvExport/CsvExportApp.cs
@@ -0,0 +1,173 @@
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+
+using Autodesk.Revit.ApplicationServices;
+using Autodesk.Revit.DB;
+
+using DesignAutomationFramework;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+
+namespace Sample.CsvExport;
+
+public sealed class CsvExportApp : IExternalDBApplication {
+ public const string CommandName = "CsvExportApp";
+
+ private readonly ILogger _logger;
+ private readonly CsvExportOptions _options;
+
+ public CsvExportApp(ILogger logger, IConfiguration configuration) {
+ _logger = logger;
+ _options = configuration.GetSection(CommandName).Get()
+ ?? throw new InvalidOperationException("CsvExportOptions are required");
+ }
+
+ private Document? Document { get; set; }
+ private List Elements { get; set; } = [];
+ private List Definitions { get; set; } = [];
+
+ public ExternalDBApplicationResult OnStartup(ControlledApplication application) {
+ _logger.LogInformation("OnStartup {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent += DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ public ExternalDBApplicationResult OnShutdown(ControlledApplication application) {
+ _logger.LogInformation("OnShutdown {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent -= DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ private void DesignAutomationReadyEvent(object? sender, DesignAutomationReadyEventArgs e) {
+ if(string.IsNullOrEmpty(_options.CsvPath)) {
+ throw new InvalidOperationException("CsvPath is required");
+ }
+
+ Document = e.DesignAutomationData.RevitDoc;
+
+ FetchElements();
+ FetchDefinitions();
+
+ string csvPath = GetPath(_options.CsvPath);
+ Directory.CreateDirectory(Path.GetDirectoryName(csvPath)!);
+
+ _logger.LogDebug("Create CSV file {@CsvFilePath}", csvPath);
+ using var fileStream = new StreamWriter(File.OpenWrite(csvPath));
+
+ WriteHeader(fileStream);
+ WriteElements(fileStream);
+
+ e.Succeeded = true;
+ }
+
+ private void FetchElements() {
+ _logger.LogDebug("Fetch Elements");
+
+ Elements = new FilteredElementCollector(Document)
+ .WhereElementIsNotElementType()
+ .Where(item => item.Category != null)
+ .OrderBy(item => GetIdValue(item.Category?.Id))
+ .ThenBy(item => GetIdValue(item.Id))
+ .ToList();
+
+ _logger.LogDebug("Finish fetch elements {@CountElements}", Elements.Count);
+ }
+
+ private void FetchDefinitions() {
+ _logger.LogDebug("Fetch Definitions");
+
+ Definitions = Elements
+ .SelectMany(item => item.Parameters
+ .OfType()
+ .Select(param => param.Definition?.Name))
+ .OfType()
+ .OrderBy(item => item)
+ .Distinct()
+ .ToList();
+
+ _logger.LogDebug("Finish fetch definitions {@CountDefinitions}", Definitions.Count);
+ }
+
+ private void WriteHeader(StreamWriter fileStream) {
+ _logger.LogDebug("Start WriteHeader");
+
+ var definitions = Definitions.ToList();
+
+ definitions.Insert(0, "ID");
+ definitions.Insert(1, "Name");
+ definitions.Insert(2, "Category");
+
+ fileStream.WriteLine(string.Join(";", definitions));
+
+ _logger.LogDebug("Finish WriteHeader");
+ }
+
+ private void WriteElements(StreamWriter fileStream) {
+ _logger.LogDebug("Start WriteElements");
+
+ foreach(var element in Elements) {
+ WriteElement(element, fileStream);
+ }
+
+ _logger.LogDebug("Finish WriteElements");
+ }
+
+ private void WriteElement(Element element, StreamWriter fileStream) {
+ var paramValues = Definitions
+ .Select(item => GetParamValueOrDefault(element, item))
+ .ToList();
+
+ paramValues.Insert(0, element.Id.ToString());
+ paramValues.Insert(1, element.Name);
+ paramValues.Insert(2, element.Category.Name);
+
+ fileStream.WriteLine(string.Join(";", paramValues));
+ }
+
+ private static string? GetParamValueOrDefault(Element element, string paramName) {
+ return element.GetParameters(paramName)
+ .Where(param => param.HasValue)
+ .Select(param => param.AsValueString() ?? GetParamValueOrDefault(param))
+ .FirstOrDefault(paramValue => !string.IsNullOrEmpty(paramValue));
+ }
+
+ private static string? GetParamValueOrDefault(Parameter param) {
+ return param.StorageType switch {
+ StorageType.None => null,
+ StorageType.Integer => param.AsInteger().ToString(CultureInfo.CurrentCulture),
+ StorageType.Double => param.AsDouble().ToString(CultureInfo.CurrentCulture),
+ StorageType.String => param.AsString(),
+ StorageType.ElementId => param.AsElementId() == ElementId.InvalidElementId
+ ? null
+ : param.AsElementId().ToString(),
+ _ => throw new ArgumentOutOfRangeException()
+ };
+ }
+
+ private static long? GetIdValue(ElementId? elementId) {
+#if REVIT2024_OR_GREATER
+ return elementId?.Value;
+#else
+ return elementId?.IntegerValue;
+#endif
+ }
+
+ private static string GetPath(string? path) {
+ string assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
+
+ if(string.IsNullOrEmpty(path))
+ return assemblyDirectory;
+
+ string targetDirectoryName = Path.IsPathRooted(path)
+ ? path!
+ : Path.Combine(assemblyDirectory, path!);
+
+ return targetDirectoryName;
+ }
+}
diff --git a/samples/Sample.CsvExport/CsvExportOptions.cs b/samples/Sample.CsvExport/CsvExportOptions.cs
new file mode 100644
index 0000000..afcecd3
--- /dev/null
+++ b/samples/Sample.CsvExport/CsvExportOptions.cs
@@ -0,0 +1,5 @@
+namespace Sample.CsvExport;
+
+public sealed class CsvExportOptions {
+ public string? CsvPath { get; init; }
+}
diff --git a/samples/Sample.CsvExport/PackageContents.xml b/samples/Sample.CsvExport/PackageContents.xml
new file mode 100644
index 0000000..eb0ebaa
--- /dev/null
+++ b/samples/Sample.CsvExport/PackageContents.xml
@@ -0,0 +1,128 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/samples/Sample.CsvExport/Sample.CsvExport.addin b/samples/Sample.CsvExport/Sample.CsvExport.addin
new file mode 100644
index 0000000..c1fce03
--- /dev/null
+++ b/samples/Sample.CsvExport/Sample.CsvExport.addin
@@ -0,0 +1,12 @@
+
+
+
+ Sample.CsvExport
+ .\Sample.CsvExport.dll
+ 5F0AC719-5463-422F-864F-FE055A965140
+ Sample.CsvExport.CsvExportApp
+ Exports Revit element parameters directly to CSV files for quick integration with Excel, Power BI, and external databases without creating schedules.
+ dosymep
+ dosymep, https://dosymep.net
+
+
\ No newline at end of file
diff --git a/samples/Sample.CsvExport/Sample.CsvExport.csproj b/samples/Sample.CsvExport/Sample.CsvExport.csproj
new file mode 100644
index 0000000..22b6a13
--- /dev/null
+++ b/samples/Sample.CsvExport/Sample.CsvExport.csproj
@@ -0,0 +1,27 @@
+
+
+
+ x64
+ D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027
+
+
+
+
+
+
+
+
+
+
+
+ Never
+
+
+ Always
+
+
+ Always
+
+
+
+
\ No newline at end of file
diff --git a/samples/Sample.CsvExport/Sample.CsvExport.json b/samples/Sample.CsvExport/Sample.CsvExport.json
new file mode 100644
index 0000000..a3baaea
--- /dev/null
+++ b/samples/Sample.CsvExport/Sample.CsvExport.json
@@ -0,0 +1,5 @@
+{
+ "CsvExportApp": {
+ "CsvPath": "./result/sample.csv"
+ }
+}
\ No newline at end of file
diff --git a/samples/Sample.IfcExport/IfcExportApp.cs b/samples/Sample.IfcExport/IfcExportApp.cs
new file mode 100644
index 0000000..4d498b3
--- /dev/null
+++ b/samples/Sample.IfcExport/IfcExportApp.cs
@@ -0,0 +1,171 @@
+using System.Reflection;
+
+using Autodesk.Revit.ApplicationServices;
+using Autodesk.Revit.DB;
+
+using DesignAutomationFramework;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+
+using Newtonsoft.Json;
+
+namespace Sample.IfcExport;
+
+public sealed class IfcExportApp : IExternalDBApplication {
+ public const string CommandName = "IfcExportApp";
+
+ private readonly ILogger _logger;
+ private readonly IfcExportOptions _options;
+
+ public IfcExportApp(ILogger logger, IConfiguration configuration) {
+ _logger = logger;
+ _options = configuration.GetSection(CommandName).Get()
+ ?? throw new InvalidOperationException("IfcExportOptions are required");
+ }
+
+ public ExternalDBApplicationResult OnStartup(ControlledApplication application) {
+ _logger.LogInformation("OnStartup {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent += DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ public ExternalDBApplicationResult OnShutdown(ControlledApplication application) {
+ _logger.LogInformation("OnShutdown {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent -= DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ private void DesignAutomationReadyEvent(object? sender, DesignAutomationReadyEventArgs e) {
+ if(!OptionalFunctionalityUtils.IsIFCAvailable()) {
+ throw new InvalidOperationException("Please install the Ifc export plugin.");
+ }
+
+ if(string.IsNullOrEmpty(_options.TargetDirectoryName)) {
+ throw new InvalidOperationException("TargetDirectoryName is required");
+ }
+
+ var document = e.DesignAutomationData.RevitDoc;
+
+ var exportView = new FilteredElementCollector(document)
+ .OfClass(typeof(View3D))
+ .OfType()
+ .Where(item => !item.IsTemplate)
+ .FirstOrDefault(item =>
+ item.Name.Equals(_options.ViewName, StringComparison.CurrentCultureIgnoreCase));
+
+ if(exportView == null) {
+ throw new InvalidOperationException($"The \"{_options.ViewName}\" view is not found.");
+ }
+
+ _logger.LogInformation(
+ "{@CommandName} Found Export View {@ExportView}",
+ CommandName,
+ new {
+ exportView.Id,
+ exportView.Name
+ });
+
+ var options = new Options {
+ ComputeReferences = true,
+ DetailLevel = ViewDetailLevel.Fine
+ };
+ bool hasElements = new FilteredElementCollector(document, exportView.Id)
+ .WhereElementIsNotElementType()
+ .Any(item => item.get_Geometry(options)?.Any() == true);
+
+ if(!hasElements) {
+ throw new InvalidOperationException($"The \"{_options.ViewName}\" view does not contain elements.");
+ }
+
+ string targetFileName = _options.TargetFileName ?? document.Title ?? "Noname";
+ _logger.LogInformation("{@CommandName} Export view file name {@ExportViewName}", CommandName, targetFileName);
+
+ string targetDirectoryName = GetPath(_options.TargetDirectoryName);
+
+ Directory.CreateDirectory(targetDirectoryName);
+
+ var ifcExportOptions = CreateOptions(exportView);
+
+ using(var transaction = new Transaction(document, "IFC Export")) {
+ transaction.Start();
+ document.Export(targetDirectoryName, targetFileName, ifcExportOptions);
+ transaction.Commit();
+ }
+
+ e.Succeeded = true;
+ }
+
+ public IFCExportOptions CreateOptions(View3D view3d, string? siteName = null) {
+ IFCExportOptions options = new() {
+ FileVersion = IFCVersion.IFC4RV,
+ FilterViewId = view3d.Id,
+ FamilyMappingFile = GetPath(_options.IfcExportLayersFilePath)
+ };
+
+ if(!string.IsNullOrEmpty(siteName)) {
+ options.AddOption("SelectedSite", siteName);
+ }
+
+ using JsonTextReader reader =
+ new(new StringReader(File.ReadAllText(GetPath(_options.IfcExportOptionsFilePath))));
+
+ while(reader.Read()) {
+ if(reader.TokenType != JsonToken.PropertyName) {
+ continue;
+ }
+
+ string? optionName = reader.Value?.ToString();
+ if(string.IsNullOrEmpty(optionName)) {
+ continue;
+ }
+
+ if(!reader.Read()) {
+ break;
+ }
+
+ if(reader.TokenType is JsonToken.StartObject or JsonToken.StartArray) {
+ reader.Skip();
+ continue;
+ }
+
+ string? optionValue = reader.Value?.ToString();
+ if(string.IsNullOrEmpty(optionValue)) {
+ continue;
+ }
+
+ switch(optionName) {
+ case "SelectedSite":
+ case "ActiveViewId":
+ case "VisibleElementsOfCurrentView":
+ case "ActivePhaseId":
+ break;
+ case "IFCVersion":
+ options.FileVersion = Enum.IsDefined(typeof(IFCVersion), Convert.ToInt32(optionValue))
+ ? (IFCVersion) Convert.ToInt32(optionValue)
+ : (IFCVersion) Enum.Parse(typeof(IFCVersion), optionValue, ignoreCase: true);
+ break;
+ default:
+ options.AddOption(optionName, optionValue);
+ break;
+ }
+ }
+
+ return options;
+ }
+
+ private static string GetPath(string? path) {
+ string assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
+
+ if(string.IsNullOrEmpty(path))
+ return assemblyDirectory;
+
+ string targetDirectoryName = Path.IsPathRooted(path)
+ ? path!
+ : Path.Combine(assemblyDirectory, path!);
+
+ return targetDirectoryName;
+ }
+}
diff --git a/samples/Sample.IfcExport/IfcExportOptions.cs b/samples/Sample.IfcExport/IfcExportOptions.cs
new file mode 100644
index 0000000..86a0675
--- /dev/null
+++ b/samples/Sample.IfcExport/IfcExportOptions.cs
@@ -0,0 +1,11 @@
+namespace Sample.IfcExport;
+
+public sealed class IfcExportOptions {
+ public string ViewName { get; init; } = "Navisworks";
+
+ public string? TargetFileName { get; init; }
+ public string? TargetDirectoryName { get; init; }
+
+ public string IfcExportLayersFilePath { get; init; } = "ifc_category_mapping.txt";
+ public string IfcExportOptionsFilePath { get; init; } = "ifc_export.json";
+}
diff --git a/samples/Sample.IfcExport/PackageContents.xml b/samples/Sample.IfcExport/PackageContents.xml
new file mode 100644
index 0000000..5d46f08
--- /dev/null
+++ b/samples/Sample.IfcExport/PackageContents.xml
@@ -0,0 +1,128 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/samples/Sample.IfcExport/Sample.IfcExport.addin b/samples/Sample.IfcExport/Sample.IfcExport.addin
new file mode 100644
index 0000000..9b368dc
--- /dev/null
+++ b/samples/Sample.IfcExport/Sample.IfcExport.addin
@@ -0,0 +1,12 @@
+
+
+
+ Sample.IfcExport
+ .\Sample.IfcExport.dll
+ 5F0AC719-5463-422F-864F-FE055A965140
+ Sample.IfcExport.IfcExportApp
+ Exports Revit models to IFC format with custom configuration settings for seamless openBIM collaboration and model exchange.
+ dosymep
+ dosymep, https://dosymep.net
+
+
\ No newline at end of file
diff --git a/samples/Sample.IfcExport/Sample.IfcExport.csproj b/samples/Sample.IfcExport/Sample.IfcExport.csproj
new file mode 100644
index 0000000..65b4904
--- /dev/null
+++ b/samples/Sample.IfcExport/Sample.IfcExport.csproj
@@ -0,0 +1,33 @@
+
+
+
+ x64
+ D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027
+
+
+
+
+
+
+
+
+
+
+
+ Never
+
+
+ Always
+
+
+ Always
+
+
+ Always
+
+
+ Always
+
+
+
+
diff --git a/samples/Sample.IfcExport/Sample.IfcExport.json b/samples/Sample.IfcExport/Sample.IfcExport.json
new file mode 100644
index 0000000..adc9e24
--- /dev/null
+++ b/samples/Sample.IfcExport/Sample.IfcExport.json
@@ -0,0 +1,9 @@
+{
+ "IfcExportApp": {
+ "ViewName": "{3D}",
+ "TargetFileName": "sample.ifc",
+ "TargetDirectoryName": ".\\result",
+ "IfcExportLayersFilePath": ".\\configs\\ifc_category_mapping.txt",
+ "IfcExportOptionsFilePath": ".\\configs\\ifc_export.json"
+ }
+}
diff --git a/samples/Sample.IfcExport/configs/ifc_category_mapping.txt b/samples/Sample.IfcExport/configs/ifc_category_mapping.txt
new file mode 100644
index 0000000..d5b3c98
Binary files /dev/null and b/samples/Sample.IfcExport/configs/ifc_category_mapping.txt differ
diff --git a/samples/Sample.IfcExport/configs/ifc_export.json b/samples/Sample.IfcExport/configs/ifc_export.json
new file mode 100644
index 0000000..bb8a4c0
--- /dev/null
+++ b/samples/Sample.IfcExport/configs/ifc_export.json
@@ -0,0 +1,59 @@
+{
+ "IFCVersion": 25,
+ "ExchangeRequirement": 0,
+ "IFCFileType": 0,
+ "ActivePhaseId": -1,
+ "SpaceBoundaries": 0,
+ "SplitWallsAndColumns": false,
+ "IncludeSteelElements": true,
+ "ProjectAddress": {
+ "UpdateProjectInformation": false,
+ "AssignAddressToSite": false,
+ "AssignAddressToBuilding": true
+ },
+ "Export2DElements": false,
+ "ExportLinkedFiles": 0,
+ "VisibleElementsOfCurrentView": false,
+ "ExportRoomsInView": false,
+ "ExportInternalRevitPropertySets": false,
+ "ExportIFCCommonPropertySets": true,
+ "ExportBaseQuantities": true,
+ "ExportMaterialPsets": false,
+ "ExportSchedulesAsPsets": false,
+ "ExportSpecificSchedules": false,
+ "ExportUserDefinedPsets": false,
+ "ExportUserDefinedPsetsFileName": "C:\\Program Files\\Autodesk\\Revit 2024\\AddIns\\IFCExporterUI\\IFC4 Reference View (связанный вид) [Архитектура].txt",
+ "ExportUserDefinedParameterMapping": false,
+ "ExportUserDefinedParameterMappingFileName": "",
+ "ClassificationSettings": {
+ "ClassificationName": null,
+ "ClassificationEdition": null,
+ "ClassificationSource": null,
+ "ClassificationEditionDate": "\/Date(-62135596800000)\/",
+ "ClassificationLocation": null,
+ "ClassificationFieldName": null
+ },
+ "TessellationLevelOfDetail": 0.5,
+ "ExportPartsAsBuildingElements": false,
+ "ExportSolidModelRep": false,
+ "UseActiveViewGeometry": false,
+ "UseFamilyAndTypeNameForReference": false,
+ "Use2DRoomBoundaryForVolume": false,
+ "IncludeSiteElevation": false,
+ "StoreIFCGUID": false,
+ "ExportBoundingBox": false,
+ "UseOnlyTriangulation": false,
+ "UseTypeNameOnlyForIfcType": false,
+ "UseVisibleRevitNameAsEntityName": false,
+ "SelectedSite": "Default Site",
+ "SitePlacement": 0,
+ "GeoRefCRSName": "",
+ "GeoRefCRSDesc": "",
+ "GeoRefEPSGCode": "",
+ "GeoRefGeodeticDatum": "",
+ "GeoRefMapUnit": "",
+ "ExcludeFilter": "",
+ "COBieCompanyInfo": "",
+ "COBieProjectInfo": "",
+ "Name": "ifc_export"
+}
\ No newline at end of file
diff --git a/samples/Sample.NwcExport/NwcExportApp.cs b/samples/Sample.NwcExport/NwcExportApp.cs
new file mode 100644
index 0000000..128878d
--- /dev/null
+++ b/samples/Sample.NwcExport/NwcExportApp.cs
@@ -0,0 +1,127 @@
+using System.Reflection;
+
+using Autodesk.Revit.ApplicationServices;
+using Autodesk.Revit.DB;
+
+using DesignAutomationFramework;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+
+namespace Sample.NwcExport;
+
+public sealed class NwcExportApp : IExternalDBApplication {
+ public const string CommandName = "NwcExportApp";
+
+ private readonly ILogger _logger;
+ private readonly NwcExportOptions _options;
+
+ public NwcExportApp(ILogger logger, IConfiguration configuration) {
+ _logger = logger;
+ _options = configuration.GetSection(CommandName).Get()
+ ?? throw new InvalidOperationException("NwcExportOptions are required");
+ }
+
+ public ExternalDBApplicationResult OnStartup(ControlledApplication application) {
+ _logger.LogInformation("OnStartup {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent += DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ public ExternalDBApplicationResult OnShutdown(ControlledApplication application) {
+ _logger.LogInformation("OnShutdown {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent -= DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ private void DesignAutomationReadyEvent(object? sender, DesignAutomationReadyEventArgs e) {
+ if(!OptionalFunctionalityUtils.IsNavisworksExporterAvailable()) {
+ throw new InvalidOperationException("Please install Navisworks export plugin.");
+ }
+
+ if(string.IsNullOrEmpty(_options.TargetDirectoryName)) {
+ throw new InvalidOperationException("TargetDirectoryName is required");
+ }
+
+ var document = e.DesignAutomationData.RevitDoc;
+
+ var exportView = new FilteredElementCollector(document)
+ .OfClass(typeof(View3D))
+ .OfType()
+ .Where(item => !item.IsTemplate)
+ .FirstOrDefault(item =>
+ item.Name.Equals(_options.ViewName, StringComparison.CurrentCultureIgnoreCase));
+
+ if(exportView == null) {
+ throw new InvalidOperationException($"The \"{_options.ViewName}\" view is not found.");
+ }
+
+ _logger.LogInformation(
+ "{@CommandName} Found Export View {@ExportView}",
+ CommandName,
+ new {
+ exportView.Id,
+ exportView.Name
+ });
+
+ var options = new Options {
+ ComputeReferences = true,
+ DetailLevel = ViewDetailLevel.Fine
+ };
+ bool hasElements = new FilteredElementCollector(document, exportView.Id)
+ .WhereElementIsNotElementType()
+ .Any(item => item.get_Geometry(options)?.Any() == true);
+
+ if(!hasElements) {
+ throw new InvalidOperationException($"The \"{_options.ViewName}\" view does not contain elements.");
+ }
+
+ string targetFileName = _options.TargetFileName ?? document.Title ?? "Noname";
+ _logger.LogInformation("{@CommandName} Export view file name {@ExportViewName}", CommandName, targetFileName);
+
+
+ string targetDirectoryName = GetPath(_options.TargetDirectoryName);
+ Directory.CreateDirectory(targetDirectoryName);
+
+ var nwcExportOptions = CreateOptions(exportView);
+ document.Export(targetDirectoryName, targetFileName, nwcExportOptions);
+
+ e.Succeeded = true;
+ }
+
+ private NavisworksExportOptions CreateOptions(View exportView) {
+ return new NavisworksExportOptions {
+ ViewId = exportView.Id,
+ ExportScope = NavisworksExportScope.View,
+ FacetingFactor = _options.FacetingFactor,
+ Parameters = _options.Parameters,
+ Coordinates = _options.Coordinates,
+ ExportUrls = _options.ExportUrls,
+ ExportLinks = _options.ExportLinks,
+ ExportParts = _options.ExportParts,
+ ExportElementIds = _options.ExportElementIds,
+ ExportRoomGeometry = _options.ExportRoomGeometry,
+ ExportRoomAsAttribute = _options.ExportRoomAsAttribute,
+ ConvertLights = _options.ConvertLights,
+ ConvertLinkedCADFormats = _options.ConvertLinkedCADFormats,
+ ConvertElementProperties = _options.ConvertElementProperties,
+ FindMissingMaterials = _options.FindMissingMaterials,
+ DivideFileIntoLevels = _options.DivideFileIntoLevels
+ };
+ }
+
+ private static string GetPath(string? path) {
+ string assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
+
+ if(string.IsNullOrEmpty(path))
+ return assemblyDirectory;
+
+ string targetDirectoryName = Path.IsPathRooted(path)
+ ? path!
+ : Path.Combine(assemblyDirectory, path!);
+
+ return targetDirectoryName;
+ }
+}
diff --git a/samples/Sample.NwcExport/NwcExportOptions.cs b/samples/Sample.NwcExport/NwcExportOptions.cs
new file mode 100644
index 0000000..ff7ae2f
--- /dev/null
+++ b/samples/Sample.NwcExport/NwcExportOptions.cs
@@ -0,0 +1,29 @@
+using Autodesk.Revit.DB;
+
+namespace Sample.NwcExport;
+
+public sealed class NwcExportOptions {
+ public string ViewName { get; init; } = "Navisworks";
+
+ public string? TargetFileName { get; init; }
+ public string? TargetDirectoryName { get; init; }
+
+ public double FacetingFactor { get; init; } = 5.0;
+
+ public NavisworksParameters Parameters { get; init; } = NavisworksParameters.All;
+ public NavisworksCoordinates Coordinates { get; init; } = NavisworksCoordinates.Shared;
+
+ public bool ExportUrls { get; init; } = false;
+ public bool ExportLinks { get; init; } = true;
+ public bool ExportParts { get; init; } = false;
+ public bool ExportElementIds { get; init; } = true;
+ public bool ExportRoomGeometry { get; init; } = false;
+ public bool ExportRoomAsAttribute { get; init; } = false;
+
+ public bool ConvertLights { get; init; } = false;
+ public bool ConvertLinkedCADFormats { get; init; } = false;
+ public bool ConvertElementProperties { get; init; } = true;
+
+ public bool FindMissingMaterials { get; init; } = false;
+ public bool DivideFileIntoLevels { get; init; } = true;
+}
diff --git a/samples/Sample.NwcExport/PackageContents.xml b/samples/Sample.NwcExport/PackageContents.xml
new file mode 100644
index 0000000..703c6d6
--- /dev/null
+++ b/samples/Sample.NwcExport/PackageContents.xml
@@ -0,0 +1,128 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/samples/Sample.NwcExport/Sample.NwcExport.addin b/samples/Sample.NwcExport/Sample.NwcExport.addin
new file mode 100644
index 0000000..bdd1a6f
--- /dev/null
+++ b/samples/Sample.NwcExport/Sample.NwcExport.addin
@@ -0,0 +1,12 @@
+
+
+
+ Sample.NwcExport
+ .\Sample.NwcExport.dll
+ 5F0AC719-5463-422F-864F-FE055A965140
+ Sample.NwcExport.NwcExportApp
+ Exports Revit models to Navisworks NWC format with custom export settings for seamless clash detection and model coordination.
+ dosymep
+ dosymep, https://dosymep.net
+
+
\ No newline at end of file
diff --git a/samples/Sample.NwcExport/Sample.NwcExport.csproj b/samples/Sample.NwcExport/Sample.NwcExport.csproj
new file mode 100644
index 0000000..990b32c
--- /dev/null
+++ b/samples/Sample.NwcExport/Sample.NwcExport.csproj
@@ -0,0 +1,27 @@
+
+
+
+ x64
+ D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027
+
+
+
+
+
+
+
+
+
+
+
+ Never
+
+
+ Always
+
+
+ Always
+
+
+
+
diff --git a/samples/Sample.NwcExport/Sample.NwcExport.json b/samples/Sample.NwcExport/Sample.NwcExport.json
new file mode 100644
index 0000000..9ea858e
--- /dev/null
+++ b/samples/Sample.NwcExport/Sample.NwcExport.json
@@ -0,0 +1,21 @@
+{
+ "NwcExportApp": {
+ "ViewName": "{3D}",
+ "TargetFileName": "sample.nwc",
+ "TargetDirectoryName": "./result",
+ "FacetingFactor": 5.0,
+ "Parameters": "All",
+ "Coordinates": "Shared",
+ "ExportUrls": false,
+ "ExportLinks": true,
+ "ExportParts": false,
+ "ExportElementIds": true,
+ "ExportRoomGeometry": false,
+ "ExportRoomAsAttribute": false,
+ "ConvertLights": false,
+ "ConvertLinkedCADFormats": false,
+ "ConvertElementProperties": true,
+ "FindMissingMaterials": false,
+ "DivideFileIntoLevels": true
+ }
+}
diff --git a/samples/Sample.PdfExport/PackageContents.xml b/samples/Sample.PdfExport/PackageContents.xml
new file mode 100644
index 0000000..087039a
--- /dev/null
+++ b/samples/Sample.PdfExport/PackageContents.xml
@@ -0,0 +1,133 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/samples/Sample.PdfExport/PdfExportApp.cs b/samples/Sample.PdfExport/PdfExportApp.cs
new file mode 100644
index 0000000..9ef8f52
--- /dev/null
+++ b/samples/Sample.PdfExport/PdfExportApp.cs
@@ -0,0 +1,162 @@
+using System.Globalization;
+using System.Reflection;
+
+using Autodesk.Revit.ApplicationServices;
+using Autodesk.Revit.DB;
+
+using DesignAutomationFramework;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+
+namespace Sample.PdfExport;
+
+public sealed class PdfExportApp : IExternalDBApplication {
+ public const string CommandName = "PdfExportApp";
+
+ private readonly ILogger _logger;
+ private readonly PdfExportOptions _options;
+
+ public PdfExportApp(ILogger logger, IConfiguration configuration) {
+ _logger = logger;
+ _options = configuration.GetSection(CommandName).Get()
+ ?? throw new InvalidOperationException("PdfExportOptions are required");
+ }
+
+ public ExternalDBApplicationResult OnStartup(ControlledApplication application) {
+ _logger.LogInformation("OnStartup {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent += DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ public ExternalDBApplicationResult OnShutdown(ControlledApplication application) {
+ _logger.LogInformation("OnShutdown {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent -= DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+#if REVIT2022_OR_GREATER
+ private void DesignAutomationReadyEvent(object? sender, DesignAutomationReadyEventArgs e) {
+ if(string.IsNullOrEmpty(_options.FileName)) {
+ throw new InvalidOperationException($"The {nameof(PdfExportOptions.FileName)} is not set.");
+ }
+
+ if(string.IsNullOrEmpty(_options.DirectoryPath)) {
+ throw new InvalidOperationException($"The {nameof(PdfExportOptions.DirectoryPath)} is not set.");
+ }
+
+ var document = e.DesignAutomationData.RevitDoc;
+ List elements = new FilteredElementCollector(document)
+ .WhereElementIsNotElementType()
+ .OfCategory(BuiltInCategory.OST_Sheets)
+ .Select(item => new {
+ View = item,
+ Values = GetParamValues(item, _options.ParamName!)
+ })
+ .Where(item => IsViewSheet(item.Values))
+ .Select(item => item.View)
+ .ToList();
+
+ if(elements.Count == 0) {
+ throw new InvalidOperationException("The export view sheets were not found.");
+ }
+
+ _logger.LogInformation(
+ "{@CommandName} Export view sheets {@ExportViewSheets}",
+ CommandName,
+ elements.Select(item => new {
+ item.Id,
+ item.Name
+ })
+ .ToArray());
+
+ string directoryPath = GetPath(_options.DirectoryPath);
+ Directory.CreateDirectory(directoryPath);
+
+ document.Export(directoryPath, elements.Select(item => item.Id).ToArray(), CreateOptions(document));
+ }
+
+ private bool IsViewSheet(List values) {
+ if(string.IsNullOrEmpty(_options.ParamName)
+ || string.IsNullOrEmpty(_options.ParamValue)) {
+ return true;
+ }
+
+ if(values.Count == 0) {
+ return false;
+ }
+
+ return values.Contains(_options.ParamValue, StringComparer.CurrentCultureIgnoreCase);
+ }
+
+ private static List GetParamValues(Element element, string paramName) {
+ return element.GetParameters(paramName)
+ .Select(item => GetParamValue(item))
+ .Where(item => !string.IsNullOrEmpty(item))
+ .OfType()
+ .ToList();
+ }
+
+ private static string? GetParamValue(Parameter parameter) {
+ string value = parameter.AsValueString();
+ if(string.IsNullOrEmpty(value)) {
+ return parameter.StorageType switch {
+ StorageType.None => null,
+ StorageType.Integer => parameter.AsInteger().ToString(),
+ StorageType.Double => parameter.AsDouble().ToString(CultureInfo.CurrentCulture),
+ StorageType.String => parameter.AsString(),
+ StorageType.ElementId => parameter.AsValueString(),
+ _ => throw new ArgumentOutOfRangeException()
+ };
+ }
+
+ return value;
+ }
+
+ private PDFExportOptions CreateOptions(Document document) {
+ return new PDFExportOptions {
+ FileName = _options.FileName ?? document.Title,
+ ColorDepth = _options.ColorDepth,
+ ExportQuality = _options.ExportQuality,
+ ZoomType = _options.ZoomType,
+ ZoomPercentage = _options.ZoomPercentage,
+ OriginOffsetX = _options.OriginOffsetX,
+ OriginOffsetY = _options.OriginOffsetY,
+ PaperFormat = _options.PaperFormat,
+ PaperPlacement = _options.PaperPlacement,
+ PaperOrientation = _options.PaperOrientation,
+ RasterQuality = _options.RasterQuality,
+ Combine = _options.Combine,
+ AlwaysUseRaster = _options.AlwaysUseRaster,
+ HideScopeBoxes = _options.HideScopeBoxes,
+ ViewLinksInBlue = _options.ViewLinksInBlue,
+ HideCropBoundaries = _options.HideCropBoundaries,
+ HideReferencePlane = _options.HideReferencePlane,
+ HideUnreferencedViewTags = _options.HideUnreferencedViewTags,
+ MaskCoincidentLines = _options.MaskCoincidentLines,
+ ReplaceHalftoneWithThinLines = _options.ReplaceHalftoneWithThinLines,
+ StopOnError = _options.StopOnError
+ };
+ }
+#else
+ private void DesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e)
+ {
+ var application = e.DesignAutomationData.RevitApp;
+ throw new NotSupportedException($"Export to pdf is not supported in {application.VersionName}.");
+ }
+#endif
+
+ private static string GetPath(string? path) {
+ string assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
+
+ if(string.IsNullOrEmpty(path))
+ return assemblyDirectory;
+
+ string targetDirectoryName = Path.IsPathRooted(path)
+ ? path!
+ : Path.Combine(assemblyDirectory, path!);
+
+ return targetDirectoryName;
+ }
+}
diff --git a/samples/Sample.PdfExport/PdfExportOptions.cs b/samples/Sample.PdfExport/PdfExportOptions.cs
new file mode 100644
index 0000000..e8dafeb
--- /dev/null
+++ b/samples/Sample.PdfExport/PdfExportOptions.cs
@@ -0,0 +1,46 @@
+using Autodesk.Revit.DB;
+
+namespace Sample.PdfExport;
+
+public sealed class PdfExportOptions {
+ public ColorDepthType ColorDepth { get; init; } = ColorDepthType.Color;
+#if REVIT2022_OR_GREATER
+ public PDFExportQualityType ExportQuality { get; init; } = PDFExportQualityType.DPI600;
+#endif
+
+
+ public ZoomType ZoomType { get; init; } = ZoomType.FitToPage;
+ public int ZoomPercentage { get; init; } = 100;
+
+ public ExportPaperFormat PaperFormat { get; init; } = ExportPaperFormat.Default;
+ public RasterQualityType RasterQuality { get; init; } = RasterQualityType.Medium;
+
+ public PaperPlacementType PaperPlacement { get; init; } = PaperPlacementType.Center;
+
+#if REVIT2021_OR_GREATER
+ public PageOrientationType PaperOrientation { get; init; } = PageOrientationType.Auto;
+#else
+ public PageOrientationType PaperOrientation { get; init; } = PageOrientationType.Landscape;
+#endif
+
+ public double OriginOffsetY { get; init; } = 0;
+ public double OriginOffsetX { get; init; } = 0;
+
+ public bool Combine { get; init; } = true;
+ public bool AlwaysUseRaster { get; init; } = false;
+ public bool ViewLinksInBlue { get; init; } = false;
+ public bool ReplaceHalftoneWithThinLines { get; init; } = true;
+
+ public bool HideScopeBoxes { get; init; } = true;
+ public bool HideReferencePlane { get; init; } = true;
+ public bool HideCropBoundaries { get; init; } = true;
+ public bool HideUnreferencedViewTags { get; init; } = true;
+ public bool StopOnError { get; init; } = true;
+ public bool MaskCoincidentLines { get; init; } = false;
+
+ public string? FileName { get; init; }
+ public string? DirectoryPath { get; init; }
+
+ public string? ParamName { get; init; }
+ public string? ParamValue { get; init; }
+}
diff --git a/samples/Sample.PdfExport/Sample.PdfExport.addin b/samples/Sample.PdfExport/Sample.PdfExport.addin
new file mode 100644
index 0000000..fa5233a
--- /dev/null
+++ b/samples/Sample.PdfExport/Sample.PdfExport.addin
@@ -0,0 +1,12 @@
+
+
+
+ Sample.PdfExport
+ .\Sample.PdfExport.dll
+ 5F0AC719-5463-422F-864F-FE055A965140
+ Sample.PdfExport.PdfExportApp
+ Exports Revit sheets and views directly to PDF with custom naming rules and batch processing for fast and efficient documentation delivery.
+ dosymep
+ dosymep, https://dosymep.net
+
+
\ No newline at end of file
diff --git a/samples/Sample.PdfExport/Sample.PdfExport.csproj b/samples/Sample.PdfExport/Sample.PdfExport.csproj
new file mode 100644
index 0000000..767ad59
--- /dev/null
+++ b/samples/Sample.PdfExport/Sample.PdfExport.csproj
@@ -0,0 +1,27 @@
+
+
+
+ x64
+ D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027
+
+
+
+
+
+
+
+
+
+
+
+ Always
+
+
+ Always
+
+
+ Never
+
+
+
+
diff --git a/samples/Sample.PdfExport/Sample.PdfExport.json b/samples/Sample.PdfExport/Sample.PdfExport.json
new file mode 100644
index 0000000..343c9ae
--- /dev/null
+++ b/samples/Sample.PdfExport/Sample.PdfExport.json
@@ -0,0 +1,26 @@
+{
+ "PdfExportApp": {
+ "ColorDepth": "Color",
+ "ExportQuality": "DPI600",
+ "ZoomType": "FitToPage",
+ "ZoomPercentage": 100,
+ "PaperFormat": "Default",
+ "RasterQuality": "Medium",
+ "PaperPlacement": "Center",
+ "PaperOrientation": "Auto",
+ "OriginOffsetY": 0,
+ "OriginOffsetX": 0,
+ "Combine": true,
+ "AlwaysUseRaster": false,
+ "ViewLinksInBlue": false,
+ "ReplaceHalftoneWithThinLines": true,
+ "HideScopeBoxes": true,
+ "HideReferencePlane": true,
+ "HideCropBoundaries": true,
+ "HideUnreferencedViewTags": true,
+ "StopOnError": true,
+ "MaskCoincidentLines": false,
+ "FileName": "sample",
+ "DirectoryPath": ".\\result"
+ }
+}
diff --git a/samples/Sample.PurgeUnused/PackageContents.xml b/samples/Sample.PurgeUnused/PackageContents.xml
new file mode 100644
index 0000000..08ad4c2
--- /dev/null
+++ b/samples/Sample.PurgeUnused/PackageContents.xml
@@ -0,0 +1,133 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/samples/Sample.PurgeUnused/PurgeUnusedApp.cs b/samples/Sample.PurgeUnused/PurgeUnusedApp.cs
new file mode 100644
index 0000000..9d2afe0
--- /dev/null
+++ b/samples/Sample.PurgeUnused/PurgeUnusedApp.cs
@@ -0,0 +1,136 @@
+using System.Reflection;
+
+using Autodesk.Revit.ApplicationServices;
+using Autodesk.Revit.DB;
+
+using DesignAutomationFramework;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+
+namespace Sample.PurgeUnused;
+
+public sealed class PurgeUnusedApp : IExternalDBApplication {
+ public const string CommandName = "PurgeUnusedApp";
+
+ private readonly ILogger _logger;
+ private readonly PurgeUnusedOptions _options;
+
+ public PurgeUnusedApp(ILogger logger, IConfiguration configuration) {
+ _logger = logger;
+ _options = configuration.GetSection(CommandName).Get()
+ ?? throw new InvalidOperationException("PurgeUnusedOptions are required");
+ }
+
+ public ExternalDBApplicationResult OnStartup(ControlledApplication application) {
+ _logger.LogInformation("OnStartup {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent += DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ public ExternalDBApplicationResult OnShutdown(ControlledApplication application) {
+ _logger.LogInformation("OnShutdown {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent -= DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ private void DesignAutomationReadyEvent(object? sender, DesignAutomationReadyEventArgs e) {
+ var document = e.DesignAutomationData.RevitDoc;
+
+ for(int i = 1; i <= _options.TryCount; i++) {
+ _logger.LogInformation("{@CommandName} Attempt to remove {@try}", CommandName, i);
+
+ using var transaction = new Transaction(document);
+ transaction.Start($"BIM: Remove unused [{i}].");
+
+ foreach(var elementId in GetElementIds(document)) {
+ try {
+ document.Delete(elementId);
+ } catch {
+ _logger.LogInformation(
+ "{@CommandName} Failed to remove ElementId {@elementId}",
+ CommandName,
+ elementId);
+ }
+ }
+
+ transaction.Commit();
+ }
+
+ e.Succeeded = true;
+ }
+
+ private IEnumerable GetElementIds(Document document) {
+ return GetMethods(document)
+ .Where(item => item is not null)
+ .SelectMany(item => (ICollection) item?.Invoke(document, [])!)
+ .Distinct();
+ }
+
+ private IEnumerable GetMethods(Document document) {
+ if(_options.WithThermals) {
+ yield return document.GetType()
+ .GetMethod(
+ "GetUnusedThermals",
+ BindingFlags.Instance | BindingFlags.NonPublic);
+ }
+
+ if(_options.WithStructures) {
+ yield return document.GetType()
+ .GetMethod(
+ "GetUnusedStructures",
+ BindingFlags.Instance | BindingFlags.NonPublic);
+ }
+
+ if(_options.WithAppearances) {
+ yield return document.GetType()
+ .GetMethod(
+ "GetUnusedAppearances",
+ BindingFlags.Instance | BindingFlags.NonPublic);
+ }
+
+ if(_options.WithMaterials) {
+ yield return document.GetType()
+ .GetMethod(
+ "GetUnusedMaterials",
+ BindingFlags.Instance | BindingFlags.NonPublic);
+ }
+
+ if(_options.WithImportCategories) {
+ yield return document.GetType()
+ .GetMethod(
+ "GetUnusedImportCategories",
+ BindingFlags.Instance | BindingFlags.NonPublic);
+ }
+
+ if(_options.WithNonDeletable) {
+ yield return document.GetType()
+ .GetMethod(
+ "GetNonDeletableUnusedElements",
+ BindingFlags.Instance | BindingFlags.NonPublic);
+ }
+
+ if(_options.WithLinkSymbols) {
+ yield return document.GetType()
+ .GetMethod(
+ "GetUnusedLinkSymbols",
+ BindingFlags.Instance | BindingFlags.NonPublic);
+ }
+
+ if(_options.WithSymbols) {
+ yield return document.GetType()
+ .GetMethod(
+ "GetUnusedSymbols",
+ BindingFlags.Instance | BindingFlags.NonPublic);
+ }
+
+ if(_options.WithFamilies) {
+ yield return document.GetType()
+ .GetMethod(
+ "GetUnusedFamilies",
+ BindingFlags.Instance | BindingFlags.NonPublic);
+ }
+ }
+}
diff --git a/samples/Sample.PurgeUnused/PurgeUnusedOptions.cs b/samples/Sample.PurgeUnused/PurgeUnusedOptions.cs
new file mode 100644
index 0000000..7fa3e84
--- /dev/null
+++ b/samples/Sample.PurgeUnused/PurgeUnusedOptions.cs
@@ -0,0 +1,14 @@
+namespace Sample.PurgeUnused;
+
+public sealed class PurgeUnusedOptions {
+ public int TryCount { get; init; } = 5;
+ public bool WithThermals { get; init; } = true;
+ public bool WithMaterials { get; init; } = true;
+ public bool WithStructures { get; init; } = true;
+ public bool WithAppearances { get; init; } = true;
+ public bool WithSymbols { get; init; } = true;
+ public bool WithLinkSymbols { get; init; } = true;
+ public bool WithFamilies { get; init; } = true;
+ public bool WithNonDeletable { get; init; } = true;
+ public bool WithImportCategories { get; init; } = true;
+}
diff --git a/samples/Sample.PurgeUnused/Sample.PurgeUnused.addin b/samples/Sample.PurgeUnused/Sample.PurgeUnused.addin
new file mode 100644
index 0000000..6af0b66
--- /dev/null
+++ b/samples/Sample.PurgeUnused/Sample.PurgeUnused.addin
@@ -0,0 +1,12 @@
+
+
+
+ Sample.PurgeUnused
+ .\Sample.PurgeUnused.dll
+ 5F0AC719-5463-422F-864F-FE055A965140
+ Sample.PurgeUnused.PurgeUnusedApp
+ Cleans and optimizes Revit models by purging unused families, types, and materials in batch to improve performance and reduce file size.
+ dosymep
+ dosymep, https://dosymep.net
+
+
\ No newline at end of file
diff --git a/samples/Sample.PurgeUnused/Sample.PurgeUnused.csproj b/samples/Sample.PurgeUnused/Sample.PurgeUnused.csproj
new file mode 100644
index 0000000..842b82f
--- /dev/null
+++ b/samples/Sample.PurgeUnused/Sample.PurgeUnused.csproj
@@ -0,0 +1,27 @@
+
+
+
+ x64
+ D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027
+
+
+
+
+
+
+
+
+
+
+
+ Always
+
+
+ Always
+
+
+ Never
+
+
+
+
diff --git a/samples/Sample.PurgeUnused/Sample.PurgeUnused.json b/samples/Sample.PurgeUnused/Sample.PurgeUnused.json
new file mode 100644
index 0000000..edf7520
--- /dev/null
+++ b/samples/Sample.PurgeUnused/Sample.PurgeUnused.json
@@ -0,0 +1,14 @@
+{
+ "PurgeUnusedApp": {
+ "TryCount": 5,
+ "WithThermals": true,
+ "WithMaterials": true,
+ "WithStructures": true,
+ "WithAppearances": true,
+ "WithSymbols": true,
+ "WithLinkSymbols": true,
+ "WithFamilies": true,
+ "WithNonDeletable": true,
+ "WithImportCategories": true
+ }
+}
diff --git a/samples/Sample.SyncDocument/PackageContents.xml b/samples/Sample.SyncDocument/PackageContents.xml
new file mode 100644
index 0000000..af680af
--- /dev/null
+++ b/samples/Sample.SyncDocument/PackageContents.xml
@@ -0,0 +1,133 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/samples/Sample.SyncDocument/Sample.SyncDocument.addin b/samples/Sample.SyncDocument/Sample.SyncDocument.addin
new file mode 100644
index 0000000..145060f
--- /dev/null
+++ b/samples/Sample.SyncDocument/Sample.SyncDocument.addin
@@ -0,0 +1,12 @@
+
+
+
+ Sample.SyncDocument
+ .\Sample.SyncDocument.dll
+ 5F0AC719-5463-422F-864F-FE055A965140
+ Sample.SyncDocument.SyncDocumentApp
+ Synchronizes the active Revit document with the central model, automatically compacting the file and relinquishing borrowed elements to streamline team collaboration.
+ dosymep
+ dosymep, https://dosymep.net
+
+
\ No newline at end of file
diff --git a/samples/Sample.SyncDocument/Sample.SyncDocument.csproj b/samples/Sample.SyncDocument/Sample.SyncDocument.csproj
new file mode 100644
index 0000000..d98f042
--- /dev/null
+++ b/samples/Sample.SyncDocument/Sample.SyncDocument.csproj
@@ -0,0 +1,27 @@
+
+
+
+ x64
+ D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027
+
+
+
+
+
+
+
+
+
+
+
+ Always
+
+
+ Always
+
+
+ Never
+
+
+
+
diff --git a/samples/Sample.SyncDocument/Sample.SyncDocument.json b/samples/Sample.SyncDocument/Sample.SyncDocument.json
new file mode 100644
index 0000000..5138faa
--- /dev/null
+++ b/samples/Sample.SyncDocument/Sample.SyncDocument.json
@@ -0,0 +1,13 @@
+{
+ "SyncDocumentApp": {
+ "Compact": true,
+ "Comment": "Sync central model.",
+ "UserWorksets": false,
+ "ViewWorksets": false,
+ "FamilyWorksets": false,
+ "StandardWorksets": false,
+ "CheckedOutElements": false,
+ "SaveLocalAfter": false,
+ "SaveLocalBefore": false
+ }
+}
diff --git a/samples/Sample.SyncDocument/SyncDocumentApp.cs b/samples/Sample.SyncDocument/SyncDocumentApp.cs
new file mode 100644
index 0000000..f5807eb
--- /dev/null
+++ b/samples/Sample.SyncDocument/SyncDocumentApp.cs
@@ -0,0 +1,89 @@
+using Autodesk.Revit.ApplicationServices;
+using Autodesk.Revit.DB;
+
+using DesignAutomationFramework;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+
+namespace Sample.SyncDocument;
+
+public sealed class SyncDocumentApp : IExternalDBApplication {
+ public const string CommandName = "SyncDocumentApp";
+
+ private readonly ILogger _logger;
+ private readonly SyncDocumentOptions _options;
+
+ public SyncDocumentApp(ILogger logger, IConfiguration configuration) {
+ _logger = logger;
+ _options = configuration.GetSection(CommandName).Get()
+ ?? throw new InvalidOperationException("SyncDocumentOptions are required");
+ }
+
+ public ExternalDBApplicationResult OnStartup(ControlledApplication application) {
+ _logger.LogInformation("OnStartup {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent += DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ public ExternalDBApplicationResult OnShutdown(ControlledApplication application) {
+ _logger.LogInformation("OnShutdown {@CommandName}", CommandName);
+ DesignAutomationBridge.DesignAutomationReadyEvent -= DesignAutomationReadyEvent;
+
+ return ExternalDBApplicationResult.Succeeded;
+ }
+
+ private void DesignAutomationReadyEvent(object? sender, DesignAutomationReadyEventArgs e) {
+ var document = e.DesignAutomationData.RevitDoc;
+ if(document.IsWorkshared) {
+ document.SynchronizeWithCentral(CreateTransactWithCentralOptions(), CreateSynchronizeWithCentralOptions());
+ } else {
+ document.Save(new SaveOptions() { Compact = _options.Compact });
+ }
+
+
+ e.Succeeded = true;
+ }
+
+ private static TransactWithCentralOptions CreateTransactWithCentralOptions() {
+ var options = new TransactWithCentralOptions();
+ options.SetLockCallback(new CentralLockedCallback(true));
+
+ return options;
+ }
+
+ private SynchronizeWithCentralOptions CreateSynchronizeWithCentralOptions() {
+ var options = new SynchronizeWithCentralOptions {
+ SaveLocalAfter = _options.SaveLocalAfter,
+ SaveLocalBefore = _options.SaveLocalBefore,
+ Comment = _options.Comment,
+ Compact = _options.Compact
+ };
+
+ options.SetRelinquishOptions(CreateRelinquishOptions());
+ return options;
+ }
+
+ private RelinquishOptions CreateRelinquishOptions() {
+ return new RelinquishOptions(false) {
+ UserWorksets = _options.UserWorksets,
+ ViewWorksets = _options.ViewWorksets,
+ FamilyWorksets = _options.FamilyWorksets,
+ StandardWorksets = _options.StandardWorksets,
+ CheckedOutElements = _options.CheckedOutElements
+ };
+ }
+}
+
+internal class CentralLockedCallback : ICentralLockedCallback {
+ private readonly bool _waitLock;
+
+ public CentralLockedCallback(bool waitLock) {
+ _waitLock = waitLock;
+ }
+
+ public bool ShouldWaitForLockAvailability() {
+ return _waitLock;
+ }
+}
diff --git a/samples/Sample.SyncDocument/SyncDocumentOptions.cs b/samples/Sample.SyncDocument/SyncDocumentOptions.cs
new file mode 100644
index 0000000..d9fdc71
--- /dev/null
+++ b/samples/Sample.SyncDocument/SyncDocumentOptions.cs
@@ -0,0 +1,15 @@
+namespace Sample.SyncDocument;
+
+public sealed class SyncDocumentOptions {
+ public bool Compact { get; init; } = true;
+ public string Comment { get; init; } = "Sync central model.";
+
+ public bool UserWorksets { get; init; }
+ public bool ViewWorksets { get; init; }
+ public bool FamilyWorksets { get; init; }
+ public bool StandardWorksets { get; init; }
+ public bool CheckedOutElements { get; init; }
+
+ public bool SaveLocalAfter { get; init; }
+ public bool SaveLocalBefore { get; init; }
+}
diff --git a/src/Directory.Build.props b/src/Directory.Build.props
deleted file mode 100644
index f43b11a..0000000
--- a/src/Directory.Build.props
+++ /dev/null
@@ -1,87 +0,0 @@
-
-
-
- x64
- enable
- 11
- 1701;1702;MSB3246
-
-
-
- 2025
- net48
- net8.0-windows
-
-
-
- false
- true
- bin\x64\Debug\$(RevitVersion)
- $(DefineConstants);DEBUG;TRACE
-
-
-
- true
- false
- bin\x64\Release\$(RevitVersion)
- $(DefineConstants);RELEASE
-
-
-
- dosymep
- dosymep
- Copyright © 2023
- dosymep, revit
-
- $(RevitVersion).2.4
- $(RevitVersion).2.4
-
- Git
- https://github.com/dosymep/RevitCoreConsole
- https://github.com/dosymep/RevitCoreConsole
- dosymep, revit, engine, revitcoreconsole, bim360
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- $(AppData)\pyRevit\Extensions\BIM4Everyone.lib\dosymep_libs\libs\dosymep.AutodeskApps.dll
-
-
-
- $(AppData)\pyRevit\Extensions\BIM4Everyone.lib\dosymep_libs\libs\dosymep.AutodeskApps.FileInfo.dll
-
-
-
- $(AppData)\pyRevit\Extensions\BIM4Everyone.lib\dosymep_libs\libs\dosymep.Revit.FileInfo.dll
-
-
-
- $(AppData)\pyRevit\Extensions\BIM4Everyone.lib\dosymep_libs\libs\dosymep.Revit.Journaling.dll
-
-
-
- $(AppData)\pyRevit\Extensions\BIM4Everyone.lib\dosymep_libs\libs\dosymep.Revit.ServerClient.dll
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Directory.Builds.targets b/src/Directory.Builds.targets
deleted file mode 100644
index 173beea..0000000
--- a/src/Directory.Builds.targets
+++ /dev/null
@@ -1,3 +0,0 @@
-
-
-
\ No newline at end of file
diff --git a/src/RevitCoreCommands/BaseCommand.cs b/src/RevitCoreCommands/BaseCommand.cs
deleted file mode 100644
index 0395115..0000000
--- a/src/RevitCoreCommands/BaseCommand.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System.Collections.Generic;
-using System.Security;
-
-using Autodesk.Revit.Attributes;
-using Autodesk.Revit.DB;
-using Autodesk.Revit.UI;
-
-using dosymep.Revit.Engine;
-
-namespace RevitCoreCommands {
- [Transaction(TransactionMode.Manual)]
- [Regeneration(RegenerationOption.Manual)]
- [Journaling(JournalingMode.UsingCommandData)]
- public abstract class BaseCommand : IExternalCommand {
- protected IDictionary _journalData;
-
- public abstract void ExecuteImpl(IRevitContext revitContext);
-
- public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) {
- _journalData = commandData.JournalData;
- ExecuteImpl(new RevitJournalContext(commandData));
-
- return Result.Succeeded;
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreCommands/ForgeCommand.cs b/src/RevitCoreCommands/ForgeCommand.cs
deleted file mode 100644
index 72b725a..0000000
--- a/src/RevitCoreCommands/ForgeCommand.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System;
-
-using dosymep.Revit.Engine;
-using dosymep.Revit.Engine.CoreCommands;
-
-namespace RevitCoreCommands {
- public class ForgeCommand : BaseCommand, IForgeCommand {
- public string ModelPath { get; set; }
- public string BundlePath { get; set; }
-
- public override void ExecuteImpl(IRevitContext revitContext) {
- if(!_journalData.TryGetValue(nameof(ModelPath), out string modelPath)) {
- throw new InvalidOperationException($"The {nameof(ModelPath)} is not set in JournalData.");
- }
-
- if(!_journalData.TryGetValue(nameof(BundlePath), out string bundlePath)) {
- throw new InvalidOperationException($"The {nameof(BundlePath)} is not set in JournalData.");
- }
-
-
- ModelPath = modelPath;
- BundlePath = bundlePath;
- revitContext.ExecuteForgeCommand(this);
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreCommands/PipelineCommand.cs b/src/RevitCoreCommands/PipelineCommand.cs
deleted file mode 100644
index 5551eba..0000000
--- a/src/RevitCoreCommands/PipelineCommand.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-using System.IO;
-
-using Autodesk.Revit.Attributes;
-using Autodesk.Revit.DB;
-using Autodesk.Revit.DB.Plumbing;
-using Autodesk.Revit.UI;
-
-using dosymep.Revit.Engine;
-using dosymep.Revit.Engine.CoreCommands;
-
-namespace RevitCoreCommands {
- [Transaction(TransactionMode.Manual)]
- [Regeneration(RegenerationOption.Manual)]
- [Journaling(JournalingMode.UsingCommandData)]
- public class PipelineCommand : BaseCommand, IPipelineCommand {
- public string PipelineFile { get; set; }
-
- public override void ExecuteImpl(IRevitContext revitContext) {
- if(!_journalData.TryGetValue(nameof(PipelineFile), out string pipelineFile)) {
- throw new InvalidOperationException($"The {nameof(PipelineFile)} is not set in JournalData.");
- }
-
- PipelineFile = pipelineFile;
- revitContext.ExecutePipelineCommand(this);
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreCommands/RevitCommand.cs b/src/RevitCoreCommands/RevitCommand.cs
deleted file mode 100644
index 638cd3c..0000000
--- a/src/RevitCoreCommands/RevitCommand.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using System;
-
-using dosymep.Revit.Engine;
-using dosymep.Revit.Engine.CoreCommands;
-using dosymep.Revit.FileInfo.RevitAddins;
-
-namespace RevitCoreCommands {
- public class RevitCommand : BaseCommand, IRevitCommand {
- public string ModelPath { get; set; }
- public string JournalData { get; set; }
-
- public string AssemblyPath { get; set; }
- public string FullClassName { get; set; }
-
- public RevitAddinItem RevitAddinItem => new RevitAddinDBApplication() {
- AssemblyPath = AssemblyPath, FullClassName = FullClassName
- };
-
- public override void ExecuteImpl(IRevitContext revitContext) {
- if(!_journalData.TryGetValue(nameof(ModelPath), out string modelPath)) {
- throw new InvalidOperationException($"The {nameof(ModelPath)} is not set in JournalData.");
- }
-
- if(!_journalData.TryGetValue(nameof(JournalData), out string journalData)) {
- throw new InvalidOperationException($"The {nameof(JournalData)} is not set in JournalData.");
- }
-
-
- if(!_journalData.TryGetValue(nameof(AssemblyPath), out string assemblyPath)) {
- throw new InvalidOperationException($"The {nameof(AssemblyPath)} is not set in JournalData.");
- }
-
-
- if(!_journalData.TryGetValue(nameof(FullClassName), out string fullClassName)) {
- throw new InvalidOperationException($"The {nameof(FullClassName)} is not set in JournalData.");
- }
-
-
- ModelPath = modelPath;
- JournalData = journalData;
- AssemblyPath = assemblyPath;
- FullClassName = fullClassName;
- revitContext.ExecuteRevitCommand(this);
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreCommands/RevitCoreCommands.csproj b/src/RevitCoreCommands/RevitCoreCommands.csproj
deleted file mode 100644
index 122bb7e..0000000
--- a/src/RevitCoreCommands/RevitCoreCommands.csproj
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
- x64
- Library
- D2016;D2017;D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;
-
-
-
-
-
-
-
-
-
-
diff --git a/src/RevitCoreConsole/App.config b/src/RevitCoreConsole/App.config
deleted file mode 100644
index 8708061..0000000
--- a/src/RevitCoreConsole/App.config
+++ /dev/null
@@ -1,40 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/RevitCoreConsole/CommandLine/CommandLineOptionParsers.cs b/src/RevitCoreConsole/CommandLine/CommandLineOptionParsers.cs
new file mode 100644
index 0000000..2a5acf8
--- /dev/null
+++ b/src/RevitCoreConsole/CommandLine/CommandLineOptionParsers.cs
@@ -0,0 +1,109 @@
+using System.CommandLine;
+using System.CommandLine.Parsing;
+
+using ResourceStrings = RevitCoreConsole.Resources.Resources;
+
+namespace RevitCoreConsole.CommandLine;
+
+///
+/// Provides parsers for strongly typed command-line options.
+///
+internal static class CommandLineOptionParsers {
+ ///
+ /// Parses and validates a local or remote Revit model path.
+ ///
+ /// The command-line argument being parsed.
+ /// The parsed model path.
+ public static string? ParseModelPath(ArgumentResult argumentResult) {
+ string? value = argumentResult.Tokens.SingleOrDefault()?.Value;
+ if(string.IsNullOrWhiteSpace(value)) {
+ argumentResult.AddError(ResourceStrings.ModelPathRequiredError);
+ return value;
+ }
+
+ if(IsRemoteModelPath(value!)) {
+ return value;
+ }
+
+ if(!value!.EndsWith(".rvt", StringComparison.OrdinalIgnoreCase)
+ && !value.EndsWith(".rfa", StringComparison.OrdinalIgnoreCase)) {
+ argumentResult.AddError(ResourceStrings.ModelPathExtensionError);
+ return value;
+ }
+
+ if(!File.Exists(value)) {
+ argumentResult.AddError(ResourceStrings.ModelPathNotFoundError);
+ }
+
+ return value;
+ }
+
+ ///
+ /// Parses and validates an AppBundle file or directory path.
+ ///
+ /// The command-line argument being parsed.
+ /// The parsed AppBundle path.
+ public static FileInfo? ParseBundlePath(ArgumentResult argumentResult) {
+ string? value = argumentResult.Tokens.SingleOrDefault()?.Value;
+ if(string.IsNullOrWhiteSpace(value)) {
+ argumentResult.AddError(ResourceStrings.BundlePathRequiredError);
+ return null;
+ }
+
+ var bundlePath = new FileInfo(value);
+ if(Directory.Exists(bundlePath.FullName)) {
+ return bundlePath;
+ }
+
+ if(!bundlePath.Exists) {
+ argumentResult.AddError(ResourceStrings.BundlePathNotFoundError);
+ return bundlePath;
+ }
+
+ if(!bundlePath.Extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) {
+ argumentResult.AddError(ResourceStrings.BundlePathExtensionError);
+ }
+
+ return bundlePath;
+ }
+
+ ///
+ /// Parses a supported Revit language code.
+ ///
+ /// The command-line argument being parsed.
+ /// The parsed language code, or .
+ public static LanguageCode ParseLanguageCode(ArgumentResult argumentResult) {
+ string? value = argumentResult.Tokens.SingleOrDefault()?.Value;
+ var languageCode = LanguageCode.GetLanguageCode(value ?? string.Empty);
+ if(languageCode == LanguageCode.Unknown) {
+ argumentResult.AddError(ResourceStrings.LanguageCodeError);
+ }
+
+ return languageCode;
+ }
+
+ ///
+ /// Parses a supported workset configuration.
+ ///
+ /// The command-line argument being parsed.
+ /// The parsed workset configuration, or .
+ public static WorksetConfiguration ParseWorksetConfiguration(ArgumentResult argumentResult) {
+ string? value = argumentResult.Tokens.SingleOrDefault()?.Value;
+ var configuration = WorksetConfiguration.Parse(value);
+ if(configuration.Equals(WorksetConfiguration.Unknown)) {
+ argumentResult.AddError(ResourceStrings.WorksetsError);
+ }
+
+ return configuration;
+ }
+
+ ///
+ /// Determines whether a model path refers to a remote Revit model.
+ ///
+ /// The model path.
+ /// for RSN or BIM 360 paths.
+ private static bool IsRemoteModelPath(string modelPath) {
+ return modelPath.StartsWith("RSN://", StringComparison.OrdinalIgnoreCase)
+ || modelPath.StartsWith("BIM 360://", StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/src/RevitCoreConsole/CommandLine/LanguageCode.cs b/src/RevitCoreConsole/CommandLine/LanguageCode.cs
new file mode 100644
index 0000000..633960d
--- /dev/null
+++ b/src/RevitCoreConsole/CommandLine/LanguageCode.cs
@@ -0,0 +1,244 @@
+using System.Globalization;
+using System.Reflection;
+
+namespace RevitCoreConsole.CommandLine;
+
+///
+/// Autodesk language code.
+///
+internal class LanguageCode : IEquatable {
+ ///
+ /// English - United States
+ ///
+ public static readonly LanguageCode ENU = new("ENU", "English_USA", CultureInfo.GetCultureInfo("en-US"));
+
+ ///
+ /// English - United Kingdom
+ ///
+ public static readonly LanguageCode ENG = new("ENG", "English_GB", CultureInfo.GetCultureInfo("en-GB"));
+
+ ///
+ /// French
+ ///
+ public static readonly LanguageCode FRA = new("FRA", "French", CultureInfo.GetCultureInfo("fr-FR"));
+
+ ///
+ /// German
+ ///
+ public static readonly LanguageCode DEU = new("DEU", "German", CultureInfo.GetCultureInfo("de-DE"));
+
+ ///
+ /// Italian
+ ///
+ public static readonly LanguageCode ITA = new("ITA", "Italian", CultureInfo.GetCultureInfo("it-IT"));
+
+ ///
+ /// Japanese
+ ///
+ public static readonly LanguageCode JPN = new("JPN", "Japanese", CultureInfo.GetCultureInfo("ja-JP"));
+
+ ///
+ /// Korean
+ ///
+ public static readonly LanguageCode KOR = new("KOR", "Korean", CultureInfo.GetCultureInfo("ko-KR"));
+
+ ///
+ /// Polish
+ ///
+ public static readonly LanguageCode PLK = new("PLK", "Polish", CultureInfo.GetCultureInfo("pl-PL"));
+
+ ///
+ /// Spanish
+ ///
+ public static readonly LanguageCode ESP = new("ESP", "Spanish", CultureInfo.GetCultureInfo("es"));
+
+ ///
+ /// Simplified Chinese
+ ///
+ public static readonly LanguageCode CHS = new("CHS", "Chinese_Simplified", CultureInfo.GetCultureInfo("zh-CN"));
+
+ ///
+ /// Traditional Chinese
+ ///
+ public static readonly LanguageCode CHT = new("CHT", "Chinese_Traditional", CultureInfo.GetCultureInfo("zh-Hant"));
+
+ ///
+ /// Brazilian Portuguese
+ ///
+ public static readonly LanguageCode PTB = new("PTB", "Brazilian_Portuguese", CultureInfo.GetCultureInfo("pt-BR"));
+
+ ///
+ /// Russian
+ ///
+ public static readonly LanguageCode RUS = new("RUS", "Russian", CultureInfo.GetCultureInfo("ru-RU"));
+
+ ///
+ /// Czech
+ ///
+ public static readonly LanguageCode CSY = new("CSY", "Czech", CultureInfo.GetCultureInfo("cs-CZ"));
+
+ ///
+ /// Hungarian
+ ///
+ public static readonly LanguageCode HUN = new("HUN", "Hungarian", CultureInfo.GetCultureInfo("hu-HU"));
+
+ ///
+ /// Unknown
+ ///
+ public static readonly LanguageCode Unknown = new("Unknown", "Unknown", CultureInfo.CurrentCulture);
+
+ ///
+ /// Creates a language code object.
+ ///
+ /// Language code value.
+ /// Language full code value.
+ /// Culture info.
+ private LanguageCode(string code, string fullCode, CultureInfo cultureInfo) {
+ Code = code;
+ FullCode = fullCode;
+ CultureInfo = cultureInfo;
+ }
+
+ ///
+ /// Language code value.
+ ///
+ public string Code { get; }
+
+ ///
+ /// Language full code value.
+ ///
+ public string FullCode { get; }
+
+ ///
+ /// Current culture info.
+ ///
+ public CultureInfo CultureInfo { get; }
+
+ ///
+ /// Display name.
+ ///
+ public string DisplayName => CultureInfo.DisplayName;
+
+ ///
+ /// English name.
+ ///
+ public string EnglishName => CultureInfo.EnglishName;
+
+ ///
+ /// Returns language code by code or full code.
+ ///
+ /// Language code.
+ /// Returns language code by code or full code.
+ public static LanguageCode GetLanguageCode(string languageCode) {
+ if(string.IsNullOrEmpty(languageCode)) {
+ return Unknown;
+ }
+
+ // some revit libs generate RU instead of RUS in metadata
+ if(languageCode.Equals("RU", StringComparison.CurrentCultureIgnoreCase)) {
+ return RUS;
+ }
+
+ return GetLanguageCodes()
+ .FirstOrDefault(item =>
+ languageCode.Equals(item.Code, StringComparison.CurrentCultureIgnoreCase)
+ || languageCode.Equals(item.FullCode, StringComparison.CurrentCultureIgnoreCase))
+ ?? Unknown;
+ }
+
+ ///
+ /// Returns language code by culture info.
+ ///
+ /// Culture info.
+ /// Returns language code by culture info.
+ public static LanguageCode GetLanguageCode(CultureInfo cultureInfo) {
+ if(cultureInfo == null) {
+ throw new ArgumentNullException(nameof(cultureInfo));
+ }
+
+ return GetLanguageCodes()
+ .FirstOrDefault(item => item.CultureInfo.Equals(cultureInfo))
+ ?? throw new NotSupportedException($"The {cultureInfo} is not supported.");
+ }
+
+ ///
+ /// Returns all supported language codes.
+ ///
+ /// Returns all supported language codes.
+ public static IEnumerable GetLanguageCodes() {
+ return typeof(LanguageCode)
+ .GetFields(BindingFlags.Static | BindingFlags.Public)
+ .Select(item => item.GetValue(null))
+ .OfType();
+ }
+
+ ///
+ public override string ToString() {
+ return DisplayName;
+ }
+
+ #region IEquatable
+
+ ///
+ public bool Equals(LanguageCode? other) {
+ if(ReferenceEquals(null, other)) {
+ return false;
+ }
+
+ if(ReferenceEquals(this, other)) {
+ return true;
+ }
+
+ return string.Equals(Code, other.Code, StringComparison.CurrentCulture)
+ && string.Equals(FullCode, other.FullCode, StringComparison.CurrentCulture);
+ }
+
+ ///
+ public override bool Equals(object? obj) {
+ if(ReferenceEquals(null, obj)) {
+ return false;
+ }
+
+ if(ReferenceEquals(this, obj)) {
+ return true;
+ }
+
+ if(obj.GetType() != GetType()) {
+ return false;
+ }
+
+ return Equals((LanguageCode) obj);
+ }
+
+ ///
+ public override int GetHashCode() {
+ unchecked {
+ return (StringComparer.CurrentCulture.GetHashCode(Code) * 397)
+ ^ StringComparer.CurrentCulture.GetHashCode(FullCode);
+ }
+ }
+
+ ///
+ /// Compares two instances for equality.
+ ///
+ /// The first to compare.
+ /// The second to compare.
+ ///
+ /// true if the specified instances are equal; otherwise, false.
+ ///
+ public static bool operator==(LanguageCode? left, LanguageCode? right) {
+ return Equals(left, right);
+ }
+
+ ///
+ /// Determines whether two instances are not equal.
+ ///
+ /// The first to compare.
+ /// The second to compare.
+ /// Returns true if the two instances are not equal; otherwise, false.
+ public static bool operator!=(LanguageCode? left, LanguageCode? right) {
+ return !Equals(left, right);
+ }
+
+ #endregion
+}
diff --git a/src/RevitCoreConsole/CommandLine/WorksetConfiguration.cs b/src/RevitCoreConsole/CommandLine/WorksetConfiguration.cs
new file mode 100644
index 0000000..4c8026c
--- /dev/null
+++ b/src/RevitCoreConsole/CommandLine/WorksetConfiguration.cs
@@ -0,0 +1,76 @@
+using Autodesk.Revit.DB;
+
+namespace RevitCoreConsole.CommandLine;
+
+///
+/// Represents a supported command-line workset configuration.
+///
+internal sealed class WorksetConfiguration : IEquatable {
+ ///
+ /// Opens all worksets in the document.
+ ///
+ public static readonly WorksetConfiguration OpenAllWorksets = new(nameof(OpenAllWorksets));
+
+ ///
+ /// Closes all worksets in the document.
+ ///
+ public static readonly WorksetConfiguration CloseAllWorksets = new(nameof(CloseAllWorksets));
+
+ ///
+ /// Opens the worksets selected in the last viewed document state.
+ ///
+ public static readonly WorksetConfiguration OpenLastViewed = new(nameof(OpenLastViewed));
+
+ ///
+ /// Represents an unsupported workset configuration value.
+ ///
+ public static readonly WorksetConfiguration Unknown = new(nameof(Unknown));
+
+ private WorksetConfiguration(string name) {
+ Name = name;
+ }
+
+ ///
+ /// Gets the command-line name of the configuration.
+ ///
+ public string Name { get; }
+
+ ///
+ /// Finds a supported configuration by its command-line name.
+ ///
+ /// The command-line value to parse.
+ /// The matching configuration, or .
+ public static WorksetConfiguration Parse(string? name) {
+ if(string.IsNullOrWhiteSpace(name)) {
+ return OpenAllWorksets;
+ }
+
+ return GetConfigurations()
+ .FirstOrDefault(configuration =>
+ name!.Equals(configuration.Name, StringComparison.OrdinalIgnoreCase))
+ ?? Unknown;
+ }
+
+ ///
+ /// Gets all supported command-line workset configurations.
+ ///
+ /// The supported configurations.
+ public static IEnumerable GetConfigurations() {
+ return [OpenAllWorksets, CloseAllWorksets, OpenLastViewed];
+ }
+
+ ///
+ public bool Equals(WorksetConfiguration? other) {
+ return other is not null && Name == other.Name;
+ }
+
+ ///
+ public override bool Equals(object? obj) {
+ return obj is WorksetConfiguration other && Equals(other);
+ }
+
+ ///
+ public override int GetHashCode() {
+ return Name.GetHashCode();
+ }
+}
diff --git a/src/RevitCoreConsole/ConsoleCommands/BaseCommand.cs b/src/RevitCoreConsole/ConsoleCommands/BaseCommand.cs
deleted file mode 100644
index ed6c073..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/BaseCommand.cs
+++ /dev/null
@@ -1,150 +0,0 @@
-using System;
-using System.Collections.Specialized;
-using System.CommandLine;
-using System.Configuration;
-using System.Threading;
-
-using dosymep.AutodeskApps.FileInfo;
-using dosymep.Revit.Engine;
-
-using Serilog;
-
-namespace RevitCoreConsole.ConsoleCommands {
- internal abstract class BaseCommand {
- public static readonly Option AssemblyPathOption
- = new Option(
- name: "/assemblyPath",
- description: "Addin assembly path.") {IsRequired = true};
-
- public static readonly Option FullClassNameOption
- = new Option(
- name: "/fullClassName",
- description: "External command class.") {IsRequired = true};
-
- public static readonly Option JournalDataOption
- = new Option(
- name: "/journalData",
- description: "Journal data.");
-
- public static readonly Option ModelPathOption
- = new Option(
- name: "/i",
- description: "Input file rvt") {IsRequired = false, ArgumentHelpName = "sample.rvt"};
-
- public static readonly Option LanguageCodeOption
- = new Option(
- name: "/l",
- description: "Application language") {ArgumentHelpName = "ENU"}
- .FromAmong("ENU", "ENG", "FRA", "DEU", "ITA", "JPN", "KOR",
- "PLK", "ESP", "CHS", "CHT", "PTB", "RUS", "CSY", "HUN");
-
-
- public ILogger Logger { get; set; }
- public LanguageCode LanguageCode { get; set; }
-
- public abstract void Execute();
-
- protected RevitContext CreateRevitApplication() {
- RevitContext context = new RevitContext() {
- Logger = Logger,
- RevitContextOptions = GetRevitAppInfo(),
- RevitEnginePath = GetAppSettingsValue(nameof(RevitContextOptions),
- nameof(RevitContext.RevitEnginePath), RevitContext.GetDefaultRevitEnginePath()),
- };
-
- context.Open();
- return context;
- }
-
- private RevitContextOptions GetRevitAppInfo() {
- return new RevitContextOptions() {
- StartUpSettings = GetStartUpSettings(),
- Guid = GetAppSettingsValueGuid(nameof(RevitContextOptions),
- nameof(RevitContextOptions.Guid), new Guid("369186E7-1F68-4470-BB4F-89EB6DFF7826")),
- LicenseKey = GetAppSettingsValue(nameof(RevitContextOptions),
- nameof(RevitContextOptions.LicenseKey), "trollface.jpg"),
- VendorName = GetAppSettingsValue(nameof(RevitContextOptions),
- nameof(RevitContextOptions.VendorName), "dosymep"),
- ApplicationName = GetAppSettingsValue(nameof(RevitContextOptions),
- nameof(RevitContextOptions.ApplicationName), "RevitCoreConsole")
- };
- }
-
- private StartUpSettings GetStartUpSettings() {
- return new StartUpSettings() {
- LanguageCode = LanguageCode,
- ApiOptions = GetApiOptions(),
- JournalName = GetAppSettingsValue(nameof(StartUpSettings),
- nameof(StartUpSettings.JournalName), (string) null),
- JournalPath = GetAppSettingsValue(nameof(StartUpSettings),
- nameof(StartUpSettings.JournalPath), StartUpSettings.GetDefaultJournalPath()),
- SettingsFileLocation = GetAppSettingsValue(nameof(StartUpSettings),
- nameof(StartUpSettings.SettingsFileLocation), StartUpSettings.GetDefaultSettingsFileLocation()),
- EnableIfc = GetAppSettingsValue(nameof(StartUpSettings),
- nameof(StartUpSettings.EnableIfc), true),
- UseApiOptions = GetAppSettingsValue(nameof(StartUpSettings),
- nameof(StartUpSettings.UseApiOptions), false),
- };
- }
-
- private static ApiOptions GetApiOptions() {
- return new ApiOptions() {
- IsAcceptForeignFiles = GetAppSettingsValue(nameof(ApiOptions),
- nameof(ApiOptions.IsAcceptForeignFiles), true),
- IsUpdateSharedFamilies = GetAppSettingsValue(nameof(ApiOptions),
- nameof(ApiOptions.IsUpdateSharedFamilies), true),
- IsIgnoreMissingUpdaters = GetAppSettingsValue(nameof(ApiOptions),
- nameof(ApiOptions.IsIgnoreMissingUpdaters), true),
- IsUpdateFamilyParameters = GetAppSettingsValue(nameof(ApiOptions),
- nameof(ApiOptions.IsUpdateFamilyParameters), true),
- IsOverwriteExistingFiles = GetAppSettingsValue(nameof(ApiOptions),
- nameof(ApiOptions.IsOverwriteExistingFiles), true),
- IsReplaceExistingSymbols = GetAppSettingsValue(nameof(ApiOptions),
- nameof(ApiOptions.IsReplaceExistingSymbols), true),
- IsIgnoreLinkedFilesOnSave = GetAppSettingsValue(nameof(ApiOptions),
- nameof(ApiOptions.IsIgnoreLinkedFilesOnSave), true),
- IsForceMultiUndoOperation = GetAppSettingsValue(nameof(ApiOptions),
- nameof(ApiOptions.IsForceMultiUndoOperation), true),
- };
- }
-
- protected static T GetAppSettingsValue(string sectionName, string propertyName, T defaultValue = default) {
- var section = ConfigurationManager.GetSection(sectionName) as NameValueCollection;
- var sectionValue = section?.Get(propertyName);
- return string.IsNullOrEmpty(sectionValue)
- ? defaultValue
- : (T) Convert.ChangeType(sectionValue, typeof(T));
- }
-
- protected static Guid GetAppSettingsValueGuid(string sectionName, string propertyName,
- Guid defaultValue = default) {
- string value = GetAppSettingsValue(sectionName, propertyName);
- return Guid.TryParse(value, out Guid guidValue) ? guidValue : defaultValue;
- }
-
- protected static LanguageCode GetAppSettingsValueLanguageCode(string sectionName, string propertyName,
- LanguageCode defaultValue = default) {
- string value = GetAppSettingsValue(sectionName, propertyName);
- return string.IsNullOrEmpty(value) ? defaultValue : LanguageCode.GetLanguageCode(value);
- }
- }
-
- internal abstract class BaseCommand : BaseCommand
- where T : IDisposable {
- protected abstract void ExecuteImpl(T application);
- protected abstract T CreateApplication();
-
- public override void Execute() {
- LanguageCode = LanguageCode
- ?? GetAppSettingsValueLanguageCode(nameof(StartUpSettings),
- nameof(StartUpSettings.LanguageCode), LanguageCode.ENU);
-
- Thread.CurrentThread.CurrentCulture = LanguageCode.CultureInfo;
- Thread.CurrentThread.CurrentUICulture = LanguageCode.CultureInfo;
-
- using(T application = CreateApplication()) {
- ExecuteImpl(application);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/Binders/BaseCommandBinder.cs b/src/RevitCoreConsole/ConsoleCommands/Binders/BaseCommandBinder.cs
deleted file mode 100644
index 3cee5f8..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/Binders/BaseCommandBinder.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-using System;
-using System.CommandLine;
-using System.CommandLine.Binding;
-using System.IO;
-
-using dosymep.AutodeskApps.FileInfo;
-using dosymep.Revit.Engine;
-
-using Serilog;
-using Serilog.Sinks.SystemConsole.Themes;
-
-namespace RevitCoreConsole.ConsoleCommands.Binders {
- internal abstract class BaseCommandBinder : BinderBase
- where T : BaseCommand, new() {
- protected override T GetBoundValue(BindingContext bindingContext) {
- T value = new T() {
- Logger = CreateLogger(),
- LanguageCode =
- LanguageCode.GetLanguageCode(
- bindingContext.ParseResult.GetValueForOption(BaseCommand.LanguageCodeOption)),
- };
-
- return GetBoundValueImpl(value, bindingContext);
- }
-
- protected abstract T GetBoundValueImpl(T value, BindingContext bindingContext);
-
- private ILogger CreateLogger() {
- var localFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
- "RevitCoreConsole", RevitContext.RevitVersion, "RevitCoreConsole_.log");
-
- RollingInterval rollingInterval = RollingInterval.Infinite;
- int fileSizeLimitBytes = 500000000;
- bool rollOnFileSizeLimit = true;
- int retainedFileCountLimit = 99;
- string outputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level:u3}] {PluginName} "
- + "{{\"RevitVersion\": \"{RevitVersion}\" \"$type\": \"RevitCoreConsole\"}} "
- + "{Message}{NewLine}{Exception}";
-
- var loggerConfiguration = new LoggerConfiguration()
- .Enrich.WithProperty("PluginName", "RevitCoreConsole")
- .Enrich.WithProperty("RevitVersion", RevitContext.RevitVersion)
- .WriteTo.File(localFileName, rollingInterval: rollingInterval,
- fileSizeLimitBytes: fileSizeLimitBytes, rollOnFileSizeLimit: rollOnFileSizeLimit,
- retainedFileCountLimit: retainedFileCountLimit, outputTemplate: outputTemplate)
- .WriteTo.Console(theme: AnsiConsoleTheme.Code)
- .Destructure.ByTransforming(lang => new {lang.Code, lang.FullCode})
-#if DEBUG
- .MinimumLevel.Verbose();
-#else
- .MinimumLevel.Information();
-#endif
-
- return loggerConfiguration.CreateLogger();
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/Binders/ForgeCommandBinder.cs b/src/RevitCoreConsole/ConsoleCommands/Binders/ForgeCommandBinder.cs
deleted file mode 100644
index 5cd8d73..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/Binders/ForgeCommandBinder.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using System.CommandLine.Binding;
-
-namespace RevitCoreConsole.ConsoleCommands.Binders
-{
- internal class ForgeCommandBinder : BaseCommandBinder {
- protected override ForgeCommand GetBoundValueImpl(ForgeCommand value, BindingContext bindingContext) {
- value.ModelPath = bindingContext.ParseResult.GetValueForOption(BaseCommand.ModelPathOption);
- value.BundlePath = bindingContext.ParseResult.GetValueForOption(ForgeCommand.BundlePathOption);
-
- return value;
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/Binders/PipelineCommandBinder.cs b/src/RevitCoreConsole/ConsoleCommands/Binders/PipelineCommandBinder.cs
deleted file mode 100644
index d815705..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/Binders/PipelineCommandBinder.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System.CommandLine.Binding;
-
-namespace RevitCoreConsole.ConsoleCommands.Binders
-{
- internal class PipelineCommandBinder : BaseCommandBinder {
- protected override PipelineCommand GetBoundValueImpl(PipelineCommand value, BindingContext bindingContext) {
- value.PipelineFile = bindingContext.ParseResult.GetValueForOption(PipelineCommand.PipelineFileOption);
- return value;
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/Binders/RevitCommandBinder.cs b/src/RevitCoreConsole/ConsoleCommands/Binders/RevitCommandBinder.cs
deleted file mode 100644
index 31aab1a..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/Binders/RevitCommandBinder.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using System.CommandLine.Binding;
-
-namespace RevitCoreConsole.ConsoleCommands.Binders
-{
- internal class RevitCommandBinder : BaseCommandBinder {
- protected override RevitCommand GetBoundValueImpl(RevitCommand value, BindingContext bindingContext) {
- value.ModelPath = bindingContext.ParseResult.GetValueForOption(BaseCommand.ModelPathOption);
- value.JournalData = bindingContext.ParseResult.GetValueForOption(BaseCommand.JournalDataOption);
- value.AssemblyPath = bindingContext.ParseResult.GetValueForOption(BaseCommand.AssemblyPathOption);
- value.FullClassName = bindingContext.ParseResult.GetValueForOption(BaseCommand.FullClassNameOption);
-
- return value;
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/CommandExtensions.cs b/src/RevitCoreConsole/ConsoleCommands/CommandExtensions.cs
deleted file mode 100644
index f8c025b..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/CommandExtensions.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System;
-using System.CommandLine;
-using System.CommandLine.Binding;
-
-namespace RevitCoreConsole.ConsoleCommands {
- internal static class CommandExtensions {
- public static Command AddParam(this Command command, Option option) {
- command.AddOption(option);
- return command;
- }
-
- public static Command SetDescription(this Command command, string description) {
- command.Description = description;
- return command;
- }
-
- public static Command SetHandler(this Command command, BinderBase binder) where T : BaseCommand {
- command.SetHandler(arg => arg.Execute(), binder);
- return command;
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/ForgeCommand.cs b/src/RevitCoreConsole/ConsoleCommands/ForgeCommand.cs
deleted file mode 100644
index fc0ae31..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/ForgeCommand.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.CommandLine;
-using System.IO;
-using System.IO.Compression;
-using System.Linq;
-
-using dosymep.Revit.Engine;
-using dosymep.Revit.Engine.CoreCommands;
-using dosymep.Revit.Engine.RevitExternals;
-using dosymep.Revit.FileInfo.RevitAddins;
-
-using RevitCoreConsole.ConsoleCommands.Binders;
-
-namespace RevitCoreConsole.ConsoleCommands {
- internal class ForgeCommand : BaseCommand, IForgeCommand {
- public static readonly Option BundlePathOption
- = new Option(
- name: "/al",
- description: "Bundle option.") {IsRequired = true};
-
- public static readonly Command ConsoleCommand
- = new Command("forge")
- .AddParam(ModelPathOption)
- .AddParam(BundlePathOption)
- .SetHandler(new ForgeCommandBinder())
- .SetDescription("Revit forge application (this command works like Forge RevitCoreConsole)");
-
- public string ModelPath { get; set; }
- public string BundlePath { get; set; }
-
- protected override void ExecuteImpl(RevitContext context) {
- Logger.Information("Executing ForgeCommand {@ForgeCommand}", this);
- try {
- context.ExecuteForgeCommand(this);
- } finally {
- Logger.Information("Executed ForgeCommand {@ForgeCommand}", this);
- }
- }
-
- protected override RevitContext CreateApplication() {
- return CreateRevitApplication();
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/JournalCommand.cs b/src/RevitCoreConsole/ConsoleCommands/JournalCommand.cs
deleted file mode 100644
index 0df8206..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/JournalCommand.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-
-using dosymep.Revit.Engine;
-
-using RevitCoreConsole.Utils;
-
-using Timer = System.Timers.Timer;
-
-namespace RevitCoreConsole.ConsoleCommands {
- internal class JournalCommand : BaseCommand {
- public static IDictionary _windowTitles =
- new Dictionary(StringComparer.CurrentCultureIgnoreCase) {
- {"RUS", "Ошибка при работе с журналом"}, {"ENU", "Journal Error"}
- };
-
- private readonly Timer _timer;
- private Process _currentProcess;
-
- private bool _isForceClose;
-
- public JournalCommand() {
- _timer = new Timer() {Interval = 1000};
- }
-
- public string JournalPath { get; set; }
-
- public string WindowTitle {
- get {
- if(_windowTitles.TryGetValue(LanguageCode.Code, out string value)) {
- return value;
- }
-
- return string.Empty;
- }
- }
-
- public override void Execute() {
- var revitEnginePath = GetAppSettingsValue(nameof(RevitContextOptions),
- nameof(RevitContext.RevitEnginePath), RevitContext.GetDefaultRevitEnginePath());
-
- var startInfo = new ProcessStartInfo() {
- UseShellExecute = false,
- RedirectStandardError = true,
- RedirectStandardOutput = true,
- FileName = Path.Combine(revitEnginePath, "Revit.exe"),
- Arguments = $"/language {LanguageCode.Code} \"{JournalPath}\""
- };
-
- _timer.Start();
- _timer.Elapsed += (s, e) => KillAppIfFreeze();
-
- _currentProcess = Process.Start(startInfo);
- Logger.Information("Launch REVIT process: {@RevitProcessId}", _currentProcess?.Id);
-
- _currentProcess?.WaitForExit();
- Logger.Information("Exited REVIT process: {@RevitProcessId}", _currentProcess?.Id);
-
- _timer.Stop();
- _timer.Dispose();
- _currentProcess?.Dispose();
-
- if(_isForceClose) {
- throw new Exception("Revit Journal have error.");
- }
- }
-
- private void KillAppIfFreeze() {
- string[] windows = NativeMethods.GetRootWindowsOfProcess(_currentProcess)
- .Select(item => NativeMethods.GetWindowTitle(item))
- .ToArray();
-
- if(windows.Contains(WindowTitle)) {
- _isForceClose = true;
-
- _currentProcess?.Kill();
- Logger.Information("Force close REVIT process: {@RevitProcessId}", _currentProcess?.Id);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/JournalPipelineCommand.cs b/src/RevitCoreConsole/ConsoleCommands/JournalPipelineCommand.cs
deleted file mode 100644
index 45f7f91..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/JournalPipelineCommand.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace RevitCoreConsole.ConsoleCommands {
- internal class JournalPipelineCommand : BaseCommand {
- public override void Execute() {
- throw new System.NotImplementedException();
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/PipelineCommand.cs b/src/RevitCoreConsole/ConsoleCommands/PipelineCommand.cs
deleted file mode 100644
index 763d1df..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/PipelineCommand.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using System;
-using System.CommandLine;
-using System.IO;
-using System.Linq;
-
-using Autodesk.Revit.DB;
-
-using dosymep.AutodeskApps;
-using dosymep.Revit.Engine;
-using dosymep.Revit.Engine.CoreCommands;
-using dosymep.Revit.Engine.Pipelines;
-using dosymep.Revit.Engine.RevitExternals;
-using dosymep.Revit.FileInfo.RevitAddins;
-
-using RevitCoreConsole.ConsoleCommands.Binders;
-
-namespace RevitCoreConsole.ConsoleCommands {
- internal class PipelineCommand : BaseCommand, IPipelineCommand {
- public static readonly Option PipelineFileOption
- = new Option(
- name: "/pipeline",
- description: "Pipeline file path.") {IsRequired = true};
-
- public static readonly Command ConsoleCommand
- = new Command("pipeline")
- .AddParam(PipelineFileOption)
- .SetHandler(new PipelineCommandBinder())
- .SetDescription("Pipeline command");
-
- public string PipelineFile { get; set; }
-
- protected override void ExecuteImpl(RevitContext context) {
- Logger.Information("Executing PipelineCommand {@PipelineCommand}", this);
- try {
- context.ExecutePipelineCommand(this);
- } finally {
- Logger.Information("Executed PipelineCommand {@PipelineCommand}", this);
- }
- }
-
- protected override RevitContext CreateApplication() {
- return CreateRevitApplication();
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/ConsoleCommands/RevitCommand.cs b/src/RevitCoreConsole/ConsoleCommands/RevitCommand.cs
deleted file mode 100644
index 189913d..0000000
--- a/src/RevitCoreConsole/ConsoleCommands/RevitCommand.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using System.Collections.Generic;
-using System.CommandLine;
-
-using dosymep.Revit.Engine;
-using dosymep.Revit.Engine.CoreCommands;
-using dosymep.Revit.Engine.RevitExternals;
-using dosymep.Revit.FileInfo.RevitAddins;
-
-using RevitCoreConsole.ConsoleCommands.Binders;
-
-namespace RevitCoreConsole.ConsoleCommands {
- internal class RevitCommand : BaseCommand, IRevitCommand {
- public static readonly Command ConsoleCommand
- = new Command("revit")
- .AddParam(ModelPathOption)
- .AddParam(AssemblyPathOption)
- .AddParam(FullClassNameOption)
- .AddParam(JournalDataOption)
- .SetHandler(new RevitCommandBinder())
- .SetDescription("Revit db addin application");
-
- public string ModelPath { get; set; }
-
- public string JournalData { get; set; }
-
- public string AssemblyPath { get; set; }
- public string FullClassName { get; set; }
-
- public RevitAddinItem RevitAddinItem => new RevitAddinDBApplication() {
- AssemblyPath = AssemblyPath, FullClassName = FullClassName
- };
-
- protected override void ExecuteImpl(RevitContext context) {
- Logger.Information("Executing RevitCommand {@RevitCommand}", this);
- try {
- context.ExecuteRevitCommand(this);
- } finally {
- Logger.Information("Executed RevitCommand {@RevitCommand}", this);
- }
- }
-
- protected override RevitContext CreateApplication() {
- return CreateRevitApplication();
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/Program.cs b/src/RevitCoreConsole/Program.cs
index edd11b2..108637d 100644
--- a/src/RevitCoreConsole/Program.cs
+++ b/src/RevitCoreConsole/Program.cs
@@ -1,29 +1,216 @@
-using System;
-using System.Collections.Generic;
-using System.CommandLine;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-using RevitCoreConsole.ConsoleCommands;
-
-namespace RevitCoreConsole {
- internal class Program {
- [STAThread]
- public static void Main(string[] args) {
- RootCommand rootCommand
- = new RootCommand("RevitCoreConsole") {
- ForgeCommand.ConsoleCommand,
- RevitCommand.ConsoleCommand,
- PipelineCommand.ConsoleCommand
- };
-
- rootCommand.AddGlobalOption(BaseCommand.LanguageCodeOption);
- rootCommand.Invoke(args);
- }
+using System.CommandLine;
+using System.Net.Mime;
+using System.Reflection;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+
+using RevitCoreConsole.Resources;
+using RevitCoreConsole.Services;
+using RevitCoreConsole.CommandLine;
+
+using RevitEngine.Abstractions;
+using RevitEngine.AssemblyResolution;
+using RevitEngine.Bundles;
+using RevitEngine.Configuration;
+using RevitEngine.DBApplications.Abstractions;
+using RevitEngine.DBApplications.Manifests;
+using RevitEngine.DBApplications.Runtime;
+using RevitEngine.Documents;
+using RevitEngine.Runtime;
+
+using Serilog;
+using Serilog.Debugging;
+
+using Spectre.Console;
+
+using Color = Spectre.Console.Color;
+
+Thread.CurrentThread.SetApartmentState(ApartmentState.Unknown);
+Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
+
+// Define options for the command-line interface.
+// These options mimic the Autodesk Revit Design Automation (Forge) environment parameters,
+// allowing local testing and execution of DB applications in headless mode.
+
+SelfLog.Enable(Console.Out);
+
+var appName = new FigletText("Console") {
+ Color = Color.Blue,
+ Justification = Justify.Center,
+};
+
+string assVersion = Assembly.GetEntryAssembly()?.GetName().Version?.ToString() ?? "v1.0.0";
+
+var version = new Text(
+ $"Version {assVersion}",
+ new Style(Color.Grey)) { Justification = Justify.Center };
+
+AnsiConsole.Write(appName);
+AnsiConsole.Write(version);
+AnsiConsole.WriteLine();
+
+// One log file per RevitCoreConsole process/session (no rolling).
+string sessionLogPath = Path.Combine(
+ "logs",
+ $"RevitCoreConsole-{DateTime.Now:yyyyMMdd-HHmmss}-{Environment.ProcessId}.log");
+
+Log.Logger = new LoggerConfiguration()
+ .Enrich.FromLogContext()
+ .WriteTo.Console()
+ .WriteTo.File(sessionLogPath)
+ .CreateLogger();
+
+Log.Information("Session log file {SessionLogPath}", Path.GetFullPath(sessionLogPath));
+
+// Option representing the input Revit document path.
+// Maps to the "/i" parameter used by Revit Core Console.
+Option modelPathOption = new(name: "/input", aliases: ["/i"]) {
+ Required = true,
+ HelpName = Resources.ModelPathHelpName,
+ Description = Resources.ModelPathDescription,
+ CustomParser = CommandLineOptionParsers.ParseModelPath,
+};
+
+// Option representing the Design Automation AppBundle or add-in path.
+// Maps to the "/al" parameter, which is required for loading the external DB application.
+Option bundlePathOption = new(name: "/app-bundle", aliases: ["/al"]) {
+ Required = true,
+ HelpName = Resources.BundlePathHelpName,
+ Description = Resources.BundlePathDescription,
+ CustomParser = CommandLineOptionParsers.ParseBundlePath,
+};
+
+// Option representing the Revit session language code.
+// Maps to the "/l" parameter to configure the UI/API locale.
+Option languageCodeOption = new(name: "/lang", aliases: ["/l"]) {
+ Required = false,
+ HelpName = Resources.LanguageCodeHelpName,
+ Description = Resources.LanguageCodeDescription,
+ CustomParser = CommandLineOptionParsers.ParseLanguageCode,
+};
+
+// Option controlling whether Revit audits the input document while opening it.
+// The short alias is intended for compatibility with the Revit Core Console-style CLI.
+Option auditOption = new(name: "/audit", aliases: ["/a"]) {
+ Required = false,
+ Description = Resources.AuditDescription,
+};
+
+// Option selecting which worksets Revit opens in the input document.
+// The parser validates the value against the supported WorksetConfiguration definitions.
+Option worksetsOption = new(name: "/worksets", aliases: ["/w"]) {
+ Required = false,
+ HelpName = Resources.WorksetsHelpName,
+ Description = Resources.WorksetsDescription,
+ DefaultValueFactory = _ => WorksetConfiguration.OpenAllWorksets,
+ CustomParser = CommandLineOptionParsers.ParseWorksetConfiguration,
+};
+
+// Register completion values from the same definitions used by the parser.
+// This keeps suggestions synchronized with the accepted command-line values.
+worksetsOption.CompletionSources.Add(
+ [.. WorksetConfiguration.GetConfigurations().Select(configuration => configuration.Name)]);
+
+// Register auto-completion values for all supported Revit language codes
+languageCodeOption.CompletionSources.Add([.. LanguageCode.GetLanguageCodes().Select(item => item.Code)]);
+
+// Define the root command of the CLI, explaining its purpose as a local Forge RevitCoreConsole equivalent.
+RootCommand rootCommand = new(description: Resources.RootCommandDescription) {
+ modelPathOption,
+ bundlePathOption,
+ languageCodeOption,
+ auditOption,
+ worksetsOption,
+};
+
+// Define the execution handler for the root command.
+rootCommand.SetAction(parseResult => {
+ string? modelPath = parseResult.GetValue(modelPathOption);
+ var bundlePath = parseResult.GetValue(bundlePathOption);
+
+ var languageCode = parseResult.GetValue(languageCodeOption);
+ bool audit = parseResult.GetValue(auditOption);
+ var worksets = parseResult.GetValue(worksetsOption);
+
+ RunApsService(modelPath, bundlePath, languageCode, audit, worksets);
+});
+
+return await rootCommand.Parse(args).InvokeAsync();
+
+void RunApsService(
+ string? modelPath,
+ FileInfo? bundlePath,
+ LanguageCode? languageCode,
+ bool audit,
+ WorksetConfiguration? worksets) {
+ try {
+ Log.Information("Starting host");
+
+ var openDocumentOptions = new OpenDocumentOptions {
+ ModelPath = modelPath,
+ Audit = audit,
+ WorksetConfiguration = worksets?.Name,
+ };
+
+ ExecuteService(args, openDocumentOptions, bundlePath, languageCode);
+
+ Log.Information("Host terminated gracefully");
+ } catch(Exception ex) {
+ Log.Fatal(ex, "Host terminated unexpectedly");
+ throw;
+ } finally {
+ Log.CloseAndFlush();
+ }
+}
+
+void ExecuteService(
+ string[] args,
+ OpenDocumentOptions openDocumentOptions,
+ FileInfo? bundlePath,
+ LanguageCode? languageCode)
+ where T : class, ISyncService {
+ var builder = Host.CreateApplicationBuilder(args);
+
+ var env = builder.Environment;
+
+ builder.Configuration
+ .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
+ .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true);
+
+ if(languageCode is not null && languageCode != LanguageCode.Unknown) {
+ builder.Configuration["RevitApplicationOptions:Startup:LanguageType"] = languageCode.FullCode;
+ }
+
+ builder.Services.AddSerilog(dispose: false);
+ builder.Services.AddSingleton(openDocumentOptions);
+ builder.Services.AddSingleton();
+ builder.Services.AddSingleton();
+ builder.Services.AddSingleton();
+
+ builder.Services.AddSingleton();
+ builder.Services.AddSingleton();
+
+ builder.Services.AddSingleton();
+ builder.Services.AddSingleton();
+
+ builder.Services.AddOptions()
+ .Configure(options => options.BundlePath = bundlePath!.FullName);
+
+ builder.Services.AddOptions()
+ .Bind(builder.Configuration.GetSection(nameof(RevitApplicationOptions)));
+
+ using var host = builder.Build();
+ host.Start();
+
+ var revitAssemblyResolver = host.Services.GetRequiredService();
+ revitAssemblyResolver.Install();
+
+ try {
+ var syncService = host.Services.GetRequiredService();
+ syncService.SyncExecute();
+ } finally {
+ revitAssemblyResolver.Uninstall();
}
-}
\ No newline at end of file
+}
diff --git a/src/RevitCoreConsole/Resources/Resources.Designer.cs b/src/RevitCoreConsole/Resources/Resources.Designer.cs
new file mode 100644
index 0000000..c0e5b73
--- /dev/null
+++ b/src/RevitCoreConsole/Resources/Resources.Designer.cs
@@ -0,0 +1,161 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace RevitCoreConsole.Resources {
+ using System;
+
+
+ ///
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ ///
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources() {
+ }
+
+ ///
+ /// Returns the cached ResourceManager instance used by this class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RevitCoreConsole.Resources.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Path to the AppBundle (.zip) package or directory containing the external DB application and its manifest..
+ ///
+ internal static string BundlePathDescription {
+ get {
+ return ResourceManager.GetString("BundlePathDescription", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to path/to/bundle.zip.
+ ///
+ internal static string BundlePathHelpName {
+ get {
+ return ResourceManager.GetString("BundlePathHelpName", resourceCulture);
+ }
+ }
+
+ internal static string AuditDescription {
+ get {
+ return ResourceManager.GetString("AuditDescription", resourceCulture);
+ }
+ }
+
+ internal static string WorksetsDescription {
+ get {
+ return ResourceManager.GetString("WorksetsDescription", resourceCulture);
+ }
+ }
+
+ internal static string WorksetsHelpName {
+ get {
+ return ResourceManager.GetString("WorksetsHelpName", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Three-letter Revit language code to configure the session locale (e.g., ENU for English, RUS for Russian, DEU for German)..
+ ///
+ internal static string LanguageCodeDescription {
+ get {
+ return ResourceManager.GetString("LanguageCodeDescription", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to language_code.
+ ///
+ internal static string LanguageCodeHelpName {
+ get {
+ return ResourceManager.GetString("LanguageCodeHelpName", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Path to the input Revit project (.rvt) or family (.rfa) file to be processed by the application..
+ ///
+ internal static string ModelPathDescription {
+ get {
+ return ResourceManager.GetString("ModelPathDescription", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to path/to/model.rvt.
+ ///
+ internal static string ModelPathHelpName {
+ get {
+ return ResourceManager.GetString("ModelPathHelpName", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Revit Core Console CLI utility (acts like Autodesk Revit Design Automation / Forge RevitCoreConsole) to run external DB applications in headless mode..
+ ///
+ internal static string RootCommandDescription {
+ get {
+ return ResourceManager.GetString("RootCommandDescription", resourceCulture);
+ }
+ }
+
+ ///
+ /// Value cannot be null or whitespace.
+ ///
+ internal static string ValueCannotBeNullOrWhitespace {
+ get {
+ return ResourceManager.GetString("ValueCannotBeNullOrWhitespace", resourceCulture);
+ }
+ }
+
+ internal static string ModelPathRequiredError => ResourceManager.GetString("ModelPathRequiredError", resourceCulture);
+ internal static string ModelPathExtensionError => ResourceManager.GetString("ModelPathExtensionError", resourceCulture);
+ internal static string ModelPathNotFoundError => ResourceManager.GetString("ModelPathNotFoundError", resourceCulture);
+ internal static string BundlePathRequiredError => ResourceManager.GetString("BundlePathRequiredError", resourceCulture);
+ internal static string BundlePathNotFoundError => ResourceManager.GetString("BundlePathNotFoundError", resourceCulture);
+ internal static string BundlePathExtensionError => ResourceManager.GetString("BundlePathExtensionError", resourceCulture);
+ internal static string LanguageCodeError => ResourceManager.GetString("LanguageCodeError", resourceCulture);
+ internal static string WorksetsError => ResourceManager.GetString("WorksetsError", resourceCulture);
+ }
+}
diff --git a/src/RevitCoreConsole/Resources/Resources.resx b/src/RevitCoreConsole/Resources/Resources.resx
new file mode 100644
index 0000000..d0bf7ed
--- /dev/null
+++ b/src/RevitCoreConsole/Resources/Resources.resx
@@ -0,0 +1,118 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 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
+
+
+ Path to the input Revit project (.rvt) or family (.rfa) file to be processed by the application.
+
+
+ path/to/model.rvt
+
+
+ Path to the AppBundle (.zip) package or directory containing the external DB application and its manifest.
+
+
+ path/to/bundle.zip
+
+
+ Three-letter Revit language code to configure the session locale (e.g., ENU for English, RUS for Russian, DEU for German).
+
+
+ language_code
+
+
+ Revit Core Console CLI utility (acts like Autodesk Revit Design Automation / Forge RevitCoreConsole) to run external DB applications in headless mode.
+
+
+ Open the input Revit document with audit enabled.
+
+
+ Workset configuration used to open the input Revit document.
+
+
+ OpenAllWorksets
+
+
+ Value cannot be null or whitespace.
+
+
+ The input model path is required.
+
+
+ The input model must have an .rvt or .rfa extension.
+
+
+ The input Revit model was not found.
+
+
+ The AppBundle path is required.
+
+
+ The AppBundle path was not found.
+
+
+ The AppBundle file must have a .zip extension.
+
+
+ The specified language code is not supported.
+
+
+ The specified workset configuration is not supported.
+
+
diff --git a/src/RevitCoreConsole/Resources/Resources.ru.resx b/src/RevitCoreConsole/Resources/Resources.ru.resx
new file mode 100644
index 0000000..d20e290
--- /dev/null
+++ b/src/RevitCoreConsole/Resources/Resources.ru.resx
@@ -0,0 +1,118 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 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
+
+
+ Путь к исходному файлу проекта Revit (.rvt) или семейства (.rfa) для открытия и обработки.
+
+
+ путь/к/модели.rvt
+
+
+ Путь к архиву AppBundle (.zip) системы Design Automation, содержащему внешнее DB-приложение и манифест .addin, либо путь к папке с файлами плагина.
+
+
+ путь/к/архиву.zip
+
+
+ Трехбуквенный код локализации для настройки языкового окружения сессии Revit (например, ENU для английского, RUS для русского, DEU для немецкого).
+
+
+ код_языка
+
+
+ Консольная утилита Revit Core Console (работает аналогично Autodesk Revit Design Automation / Forge RevitCoreConsole) для запуска внешних DB-приложений в фоновом режиме.
+
+
+ Открыть исходный документ Revit с включенным аудитом.
+
+
+ Конфигурация рабочих наборов для открытия исходного документа Revit.
+
+
+ OpenAllWorksets
+
+
+ Значение не может быть пустым или содержать пробелы.
+
+
+ Путь к исходной модели обязателен.
+
+
+ Исходная модель должна иметь расширение .rvt или .rfa.
+
+
+ Исходная модель Revit не найдена.
+
+
+ Путь к AppBundle обязателен.
+
+
+ Путь к AppBundle не найден.
+
+
+ Файл AppBundle должен иметь расширение .zip.
+
+
+ Указанный код языка не поддерживается.
+
+
+ Указанная конфигурация рабочих наборов не поддерживается.
+
+
diff --git a/src/RevitCoreConsole/RevitCoreConsole.csproj b/src/RevitCoreConsole/RevitCoreConsole.csproj
index d3eab7c..3d16b64 100644
--- a/src/RevitCoreConsole/RevitCoreConsole.csproj
+++ b/src/RevitCoreConsole/RevitCoreConsole.csproj
@@ -1,42 +1,53 @@
-
+
+
- x64
Exe
- App.D$(RevitVersion).config
- D2016;D2017;D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;
+ D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027
+ x64
-
-
+
+
-
+
-
- App.config
-
-
- App.config
-
-
- App.config
-
-
- App.config
-
-
- App.config
-
-
- App.config
-
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
+
+ appsettings.json
+ Always
+
+
+
+
+
+ <_AppSettingsDefault>$(MSBuildProjectDirectory)\appsettings.json
+ <_AppSettingsVersioned>$(MSBuildProjectDirectory)\appsettings.$(RevitVersion).json
+
+
+
diff --git a/src/RevitCoreConsole/Services/ApsService.cs b/src/RevitCoreConsole/Services/ApsService.cs
new file mode 100644
index 0000000..9dfdcb1
--- /dev/null
+++ b/src/RevitCoreConsole/Services/ApsService.cs
@@ -0,0 +1,47 @@
+using Autodesk.Revit.DB;
+
+using Microsoft.Extensions.Logging;
+
+using RevitEngine.Abstractions;
+using RevitEngine.Documents;
+using RevitEngine.Extensions;
+using RevitEngine.Runtime;
+
+namespace RevitCoreConsole.Services;
+
+internal sealed partial class ApsService : ISyncService {
+ private readonly ILogger _logger;
+ private readonly IDesignAutomation _designAutomation;
+ private readonly OpenDocumentOptions _openDocumentOptions;
+ private readonly IRevitApplicationHost _revitApplicationHost;
+
+ public ApsService(
+ ILogger logger,
+ IDesignAutomation designAutomation,
+ OpenDocumentOptions openDocumentOptions,
+ IRevitApplicationHost revitApplicationHost) {
+ _logger = logger;
+ _designAutomation = designAutomation;
+ _openDocumentOptions = openDocumentOptions;
+ _revitApplicationHost = revitApplicationHost;
+ }
+
+ public void SyncExecute() {
+ LogSyncStarted(_logger);
+
+ try {
+ var application = _revitApplicationHost.Initialize();
+ _designAutomation.ExecuteApsCommand(application, _openDocumentOptions);
+ } finally {
+ _revitApplicationHost.Close();
+ }
+
+ LogSyncStopped(_logger);
+ }
+
+ [LoggerMessage(LogLevel.Information, "ForgeService is running.")]
+ private static partial void LogSyncStarted(ILogger logger);
+
+ [LoggerMessage(LogLevel.Information, "ForgeService is stopped.")]
+ private static partial void LogSyncStopped(ILogger logger);
+}
diff --git a/src/RevitCoreConsole/Services/ISyncService.cs b/src/RevitCoreConsole/Services/ISyncService.cs
new file mode 100644
index 0000000..55ed1fd
--- /dev/null
+++ b/src/RevitCoreConsole/Services/ISyncService.cs
@@ -0,0 +1,5 @@
+namespace RevitCoreConsole.Services;
+
+internal interface ISyncService {
+ void SyncExecute();
+}
diff --git a/src/RevitCoreConsole/Utils/NativeMethods.cs b/src/RevitCoreConsole/Utils/NativeMethods.cs
deleted file mode 100644
index d987047..0000000
--- a/src/RevitCoreConsole/Utils/NativeMethods.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-using System.Text;
-
-namespace RevitCoreConsole.Utils
-{
- public class NativeMethods
- {
- [DllImport("user32.dll")]
- private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
-
- [DllImport("user32.Dll")]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool EnumChildWindows(IntPtr parentHandle, Win32Callback callback, IntPtr lParam);
-
- [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
-
- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
- private static extern int GetWindowTextLength(IntPtr hWnd);
-
- private delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam);
-
- public static string GetWindowTitle(IntPtr hWnd)
- {
- if (hWnd == IntPtr.Zero)
- {
- throw new ArgumentNullException(nameof(hWnd));
- }
-
- int length = GetWindowTextLength(hWnd) + 1;
- var title = new StringBuilder(length);
- GetWindowText(hWnd, title, length);
-
- return title.ToString();
- }
-
- public static IEnumerable GetRootWindowsOfProcess(Process process)
- {
- if (process == null)
- {
- throw new ArgumentNullException(nameof(process));
- }
-
- IEnumerable rootWindows = GetChildWindows(IntPtr.Zero);
- foreach (IntPtr hWnd in rootWindows)
- {
- GetWindowThreadProcessId(hWnd, out uint lpdwProcessId);
- if (lpdwProcessId == process.Id)
- {
- yield return hWnd;
- }
- }
- }
-
- private static IEnumerable GetChildWindows(IntPtr parent)
- {
- var result = new List();
- GCHandle listHandle = GCHandle.Alloc(result);
- try
- {
- var childProc = new Win32Callback(EnumWindow);
- EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
- }
- finally
- {
- if (listHandle.IsAllocated)
- {
- listHandle.Free();
- }
- }
-
- return result;
- }
-
- private static bool EnumWindow(IntPtr handle, IntPtr pointer)
- {
- GCHandle gch = GCHandle.FromIntPtr(pointer);
- var list = gch.Target as List;
- if (list == null)
- {
- throw new InvalidCastException("GCHandle Target could not be cast as List");
- }
-
- list.Add(handle);
- return true;
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreConsole/appsettings.json b/src/RevitCoreConsole/appsettings.json
new file mode 100644
index 0000000..353c49d
--- /dev/null
+++ b/src/RevitCoreConsole/appsettings.json
@@ -0,0 +1,31 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Debug",
+ "Microsoft.AspNetCore": "Debug"
+ }
+ },
+ "RevitApplicationOptions": {
+ "ApplicationGuid": "369186E7-1F68-4470-BB4F-89EB6DFF7826",
+ "ApplicationName": "RevitCoreConsole",
+ "ApplicationPath": "C:\\Program Files\\Autodesk\\Revit 2027",
+ "LicenseKey": "trollface.jpg",
+ "VendorId": "dosymep",
+ "VendorDescription": "dosymep, https://dosymep.net",
+ "Startup": {
+ "EnableIFC": true,
+ "ApplyApiSettings": true,
+ "LanguageType": "English_USA",
+ "Api": {
+ "OverwriteExistingFiles": true,
+ "ReplaceExistingSymbols": true,
+ "IgnoreLinkedFilesOnSave": true,
+ "ForceMultiUndoOperation": true,
+ "UpdateSharedFamilies": true,
+ "UpdateFamilyParameters": true,
+ "IgnoreMissingUpdaters": true,
+ "AcceptForeignFiles": true
+ }
+ }
+ }
+}
diff --git a/src/RevitCoreDBApplications/BaseCommand.cs b/src/RevitCoreDBApplications/BaseCommand.cs
deleted file mode 100644
index eca7ff2..0000000
--- a/src/RevitCoreDBApplications/BaseCommand.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using System.Collections.Generic;
-
-using Autodesk.Revit.ApplicationServices;
-using Autodesk.Revit.DB;
-
-using DesignAutomationFramework;
-
-using Serilog;
-
-namespace RevitCoreDBApplications {
- public abstract class BaseCommand : IExternalDBApplication {
- protected readonly string _commandName;
-
- protected BaseCommand(string commandName) {
- _commandName = commandName;
- }
-
- public ILogger Logger { get; set; }
- public IDictionary JournalData { get; set; }
-
- public virtual ExternalDBApplicationResult OnStartup(ControlledApplication application) {
- Logger.Information("OnStartup {@CommandName}", _commandName);
- DesignAutomationBridge.DesignAutomationReadyEvent += DesignAutomationReadyEvent;
- return ExternalDBApplicationResult.Succeeded;
- }
-
- public virtual ExternalDBApplicationResult OnShutdown(ControlledApplication application) {
- Logger.Information("OnShutdown {@CommandName}", _commandName);
- DesignAutomationBridge.DesignAutomationReadyEvent -= DesignAutomationReadyEvent;
- return ExternalDBApplicationResult.Succeeded;
- }
-
- protected abstract void ExecuteCommand(DesignAutomationData designAutomationData);
-
- private void DesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e) {
- Logger.Information("Executing command {@Command}", this);
- try {
- e.Succeeded = true;
- ExecuteCommand(e.DesignAutomationData);
- } finally {
- Logger.Information("Executed command {@Command}", this);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreDBApplications/ExportCsvCommand.cs b/src/RevitCoreDBApplications/ExportCsvCommand.cs
deleted file mode 100644
index 977b0a4..0000000
--- a/src/RevitCoreDBApplications/ExportCsvCommand.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-
-using Autodesk.Revit.DB;
-
-using DesignAutomationFramework;
-
-namespace RevitCoreDBApplications {
- public class ExportCsvCommand : BaseCommand {
- public ExportCsvCommand()
- : base("Export to CSV") {
- }
-
- public string CsvPath { get; set; }
-
- private Document Document { get; set; }
- private List Elements { get; set; }
- private List Definitions { get; set; }
-
- protected override void ExecuteCommand(DesignAutomationData designAutomationData) {
- Document = designAutomationData.RevitDoc;
- CsvPath = string.IsNullOrEmpty(CsvPath)
- ? Path.ChangeExtension(Document.PathName, ".csv")
- : CsvPath;
-
- FetchElements();
- FetchDefinitions();
-
- Logger.Debug("Create CSV file {@CsvFilePath}", CsvPath);
- using(StreamWriter fileStream = new StreamWriter(File.OpenWrite(CsvPath))) {
- WriteHeader(fileStream);
- WriteElements(fileStream);
- }
- }
-
- private void FetchElements() {
- Logger.Debug("Fetch Elements");
-
- Elements = new FilteredElementCollector(Document)
- .WhereElementIsNotElementType()
- .Where(item => item.Category != null)
- .OrderBy(item => item.Category?.Id.IntegerValue)
- .ThenBy(item => item.Id.IntegerValue)
- .ToList();
-
- Logger.Debug("Finish fetch elements {@CountElements}", Elements.Count);
- }
-
- private void FetchDefinitions() {
- Logger.Debug("Fetch Definitions");
-
- Definitions = Elements
- .SelectMany(item => item.Parameters
- .OfType()
- .Select(param => param.Definition.Name))
- .OrderBy(item => item)
- .Distinct()
- .ToList();
-
- Logger.Debug("Finish fetch definitions {@CountDefinitions}", Definitions.Count);
- }
-
- private void WriteHeader(StreamWriter fileStream) {
- Logger.Debug("Start WriteHeader");
-
- var definitions = Definitions.ToList();
-
- definitions.Insert(0, "ID");
- definitions.Insert(1, "Name");
- definitions.Insert(2, "Category");
-
- fileStream.WriteLine(string.Join(";", definitions));
-
- Logger.Debug("Finish WriteHeader");
- }
-
- private void WriteElements(StreamWriter fileStream) {
- Logger.Debug("Start WriteElements");
-
- foreach(Element element in Elements) {
- WriteElement(element, fileStream);
- }
-
- Logger.Debug("Finish WriteElements");
- }
-
- private void WriteElement(Element element, StreamWriter fileStream) {
- var paramValues = Definitions
- .Select(item => GetParamValueOrDefault(element, item))
- .ToList();
-
- paramValues.Insert(0, element.Id.ToString());
- paramValues.Insert(1, element.Name);
- paramValues.Insert(2, element.Category.Name);
- fileStream.WriteLine(string.Join(";", paramValues));
- }
-
- private string GetParamValueOrDefault(Element element, string paramName) {
- foreach(Parameter param in element.GetParameters(paramName)) {
- if(!param.HasValue) {
- continue;
- }
-
- string paramValue = param.AsValueString()
- ?? GetParamValueOrDefault(param);
- if(string.IsNullOrEmpty(paramValue)) {
- continue;
- }
-
- return paramValue;
- }
-
- return null;
- }
-
- private static string GetParamValueOrDefault(Parameter param) {
- switch(param.StorageType) {
- case StorageType.None:
- return null;
- case StorageType.Integer:
- return param.AsInteger().ToString(CultureInfo.CurrentCulture);
- case StorageType.Double:
- return param.AsDouble().ToString(CultureInfo.CurrentCulture);
- case StorageType.String:
- return param.AsString();
- case StorageType.ElementId:
- return param.AsElementId() == ElementId.InvalidElementId ? null : param.AsElementId().ToString();
- default:
- throw new ArgumentOutOfRangeException();
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreDBApplications/ExportNavisworksCommand.cs b/src/RevitCoreDBApplications/ExportNavisworksCommand.cs
deleted file mode 100644
index 83d76c5..0000000
--- a/src/RevitCoreDBApplications/ExportNavisworksCommand.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using System;
-using System.Linq;
-
-using Autodesk.Revit.DB;
-
-using DesignAutomationFramework;
-
-namespace RevitCoreDBApplications {
- public class ExportNavisworksCommand : BaseCommand {
- public ExportNavisworksCommand()
- : base("Export 3D view to Navisworks") {
- }
-
- public string ViewName { get; set; } = "Navisworks";
-
- public string TargetFileName { get; set; }
- public string TargetDirectoryName { get; set; }
-
- public double FacetingFactor { get; set; } = 5.0;
-
- public NavisworksParameters Parameters { get; set; } = NavisworksParameters.All;
- public NavisworksCoordinates Coordinates { get; set; } = NavisworksCoordinates.Shared;
-
- public bool ExportUrls { get; set; } = false;
- public bool ExportLinks { get; set; } = true;
- public bool ExportParts { get; set; } = false;
- public bool ExportElementIds { get; set; } = true;
- public bool ExportRoomGeometry { get; set; } = false;
- public bool ExportRoomAsAttribute { get; set; } = false;
-
- public bool ConvertLights { get; set; } = false;
- public bool ConvertLinkedCADFormats { get; set; } = false;
- public bool ConvertElementProperties { get; set; } = true;
-
- public bool FindMissingMaterials { get; set; } = false;
- public bool DivideFileIntoLevels { get; set; } = true;
-
-
- protected override void ExecuteCommand(DesignAutomationData designAutomationData) {
- if(!OptionalFunctionalityUtils.IsNavisworksExporterAvailable()) {
- throw new InvalidOperationException("Please install Navisworks export plugin.");
- }
-
- Document document = designAutomationData.RevitDoc;
- View3D exportView = new FilteredElementCollector(document)
- .OfClass(typeof(View3D))
- .OfType()
- .Where(item => !item.IsTemplate)
- .FirstOrDefault(item =>
- item.Name.Equals(ViewName, StringComparison.CurrentCultureIgnoreCase));
-
- if(exportView == null) {
- throw new InvalidOperationException($"The \"{ViewName}\" view is not found.");
- }
-
- Logger.Information("{@CommandName} Found Export View {@ExportView}", _commandName, new {exportView.Id, exportView.Name});
- var options = new Options() {ComputeReferences = true, DetailLevel = ViewDetailLevel.Fine};
- var hasElements = new FilteredElementCollector(document, exportView.Id)
- .WhereElementIsNotElementType()
- .Any(item => item.get_Geometry(options)?.Any() == true);
-
- if(!hasElements) {
- throw new InvalidOperationException($"The \"{ViewName}\" view does not contain elements.");
- }
-
- var targetFileName = TargetFileName ?? document.Title ?? "Noname";
- Logger.Information("{@CommandName} Export view file name {@ExportViewName}", _commandName, targetFileName);
-
- NavisworksExportOptions navisworksExportOptions = GetExportOptions(exportView);
- document.Export(TargetDirectoryName, targetFileName, navisworksExportOptions);
- }
-
- private NavisworksExportOptions GetExportOptions(View exportView) {
- return new NavisworksExportOptions {
- ViewId = exportView.Id,
- ExportScope = NavisworksExportScope.View,
- FacetingFactor = FacetingFactor,
- Parameters = Parameters,
- Coordinates = Coordinates,
- ExportUrls = ExportUrls,
- ExportLinks = ExportLinks,
- ExportParts = ExportParts,
- ExportElementIds = ExportElementIds,
- ExportRoomGeometry = ExportRoomGeometry,
- ExportRoomAsAttribute = ExportRoomAsAttribute,
- ConvertLights = ConvertLights,
- ConvertLinkedCADFormats = ConvertLinkedCADFormats,
- ConvertElementProperties = ConvertElementProperties,
- FindMissingMaterials = FindMissingMaterials,
- DivideFileIntoLevels = DivideFileIntoLevels,
- };
- }
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreDBApplications/ExportViewSheetsPdfCommand.cs b/src/RevitCoreDBApplications/ExportViewSheetsPdfCommand.cs
deleted file mode 100644
index ec03178..0000000
--- a/src/RevitCoreDBApplications/ExportViewSheetsPdfCommand.cs
+++ /dev/null
@@ -1,153 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-
-using Autodesk.Revit.DB;
-
-using DesignAutomationFramework;
-
-namespace RevitCoreDBApplications {
- public class ExportViewSheetsPdfCommand : BaseCommand {
- public ExportViewSheetsPdfCommand()
- : base("Export sheets to PDF") {
- }
-
- protected override void ExecuteCommand(DesignAutomationData designAutomationData) {
- PrintViewSheets(designAutomationData);
- }
-
-#if REVIT_2021_OR_LESS
- private void PrintViewSheets(DesignAutomationData designAutomationData) {
- var application = designAutomationData.RevitApp;
- throw new NotSupportedException($"Export to pdf is not supported in {application.VersionName}.");
- }
-#else
- private void PrintViewSheets(DesignAutomationData designAutomationData) {
- if(string.IsNullOrEmpty(DirectoryPath)) {
- throw new InvalidOperationException($"The {DirectoryPath} is not set.");
- }
-
- Document document = designAutomationData.RevitDoc;
- List elements = new FilteredElementCollector(document)
- .WhereElementIsNotElementType()
- .OfCategory(BuiltInCategory.OST_Sheets)
- .Select(item => new {View = item, Values = GetParamValues(item, ParamName)})
- .Where(item => IsViewSheet(item.Values))
- .Select(item => item.View)
- .ToList();
-
- if(elements.Count == 0) {
- throw new InvalidOperationException("The export view sheets was not found.");
- }
-
- Logger.Information("{@CommandName} Export view sheets {@ExportViewSheets}",
- _commandName, elements.Select(item => new {item.Id, item.Name}).ToArray());
-
- Directory.CreateDirectory(DirectoryPath);
- document.Export(DirectoryPath, elements.Select(item => item.Id).ToArray(), GetExportOptions(document));
- }
-
- public ColorDepthType ColorDepth { get; set; } = ColorDepthType.Color;
- public PDFExportQualityType ExportQuality { get; set; } = PDFExportQualityType.DPI600;
-
- public ZoomType ZoomType { get; set; } = ZoomType.FitToPage;
- public int ZoomPercentage { get; set; } = 100;
-
- public ExportPaperFormat PaperFormat { get; set; } = ExportPaperFormat.Default;
- public RasterQualityType RasterQuality { get; set; } = RasterQualityType.Medium;
-
- public PaperPlacementType PaperPlacement { get; set; } = PaperPlacementType.Center;
- public PageOrientationType PaperOrientation { get; set; } = PageOrientationType.Auto;
-
- public double OriginOffsetY { get; set; } = 0;
- public double OriginOffsetX { get; set; } = 0;
-
- public bool Combine { get; set; } = true;
- public bool AlwaysUseRaster { get; set; } = false;
- public bool ViewLinksInBlue { get; set; } = false;
- public bool ReplaceHalftoneWithThinLines { get; set; } = true;
-
- public bool HideScopeBoxes { get; set; } = true;
- public bool HideReferencePlane { get; set; } = true;
- public bool HideCropBoundaries { get; set; } = true;
- public bool HideUnreferencedViewTags { get; set; } = true;
- public bool StopOnError { get; set; } = true;
- public bool MaskCoincidentLines { get; set; } = false;
-
- public string FileName { get; set; }
- public string DirectoryPath { get; set; }
-
- public string ParamName { get; set; }
- public string ParamValue { get; set; }
-
- private bool IsViewSheet(List values) {
- if(string.IsNullOrEmpty(ParamName)
- || string.IsNullOrEmpty(ParamValue)) {
- return true;
- }
-
- if(values.Count == 0) {
- return false;
- }
-
- return values.Contains(ParamValue, StringComparer.CurrentCultureIgnoreCase);
- }
-
- private List GetParamValues(Element element, string paramName) {
- return element.GetParameters(paramName)
- .Select(item => GetParamValue(item))
- .Where(item => !string.IsNullOrEmpty(item))
- .ToList();
- }
-
- private string GetParamValue(Parameter parameter) {
- string value = parameter.AsValueString();
- if(string.IsNullOrEmpty(value)) {
- switch(parameter.StorageType) {
- case StorageType.None:
- return null;
- case StorageType.Integer:
- return parameter.AsInteger().ToString();
- case StorageType.Double:
- return parameter.AsDouble().ToString(CultureInfo.CurrentCulture);
- case StorageType.String:
- return parameter.AsString();
- case StorageType.ElementId:
- return parameter.AsValueString();
- }
- }
-
- return value;
- }
-
- private PDFExportOptions GetExportOptions(Document document) {
- return new PDFExportOptions() {
- FileName = FileName ?? document.Title,
- ColorDepth = ColorDepth,
- ExportQuality = ExportQuality,
- ZoomType = ZoomType,
- ZoomPercentage = ZoomPercentage,
- OriginOffsetX = OriginOffsetX,
- OriginOffsetY = OriginOffsetY,
- PaperFormat = PaperFormat,
- PaperPlacement = PaperPlacement,
- PaperOrientation = PaperOrientation,
- RasterQuality = RasterQuality,
- Combine = Combine,
- AlwaysUseRaster = AlwaysUseRaster,
- HideScopeBoxes = HideScopeBoxes,
- ViewLinksInBlue = ViewLinksInBlue,
- HideCropBoundaries = HideCropBoundaries,
- HideReferencePlane = HideReferencePlane,
- HideUnreferencedViewTags = HideUnreferencedViewTags,
- MaskCoincidentLines = MaskCoincidentLines,
- ReplaceHalftoneWithThinLines = ReplaceHalftoneWithThinLines,
- StopOnError = StopOnError,
- };
- }
-
-#endif
- }
-}
\ No newline at end of file
diff --git a/src/RevitCoreDBApplications/PurgeUnusedCommand.cs b/src/RevitCoreDBApplications/PurgeUnusedCommand.cs
deleted file mode 100644
index 78b9621..0000000
--- a/src/RevitCoreDBApplications/PurgeUnusedCommand.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-
-using Autodesk.Revit.DB;
-
-using DesignAutomationFramework;
-
-namespace RevitCoreDBApplications {
- public class PurgeUnusedCommand : BaseCommand {
- public PurgeUnusedCommand()
- : base("Purge unused") {
- }
-
- public int TryCount { get; set; } = 5;
- public bool WithThermals { get; set; } = true;
- public bool WithMaterials { get; set; } = true;
- public bool WithStructures { get; set; } = true;
- public bool WithAppearances { get; set; } = true;
- public bool WithSymbols { get; set; } = true;
- public bool WithLinkSymbols { get; set; } = true;
- public bool WithFamilies { get; set; } = true;
- public bool WithNonDeletable { get; set; } = true;
- public bool WithImportCategories { get; set; } = true;
-
- protected override void ExecuteCommand(DesignAutomationData designAutomationData) {
- var document = designAutomationData.RevitDoc;
- for(int i = 1; i <= TryCount; i++) {
- Logger.Information("{@CommandName} Attempt to remove {@try}", _commandName, i);
-
- using(var transaction = new Transaction(document)) {
- transaction.Start($"BIM: Remove unused [{i}].");
-
- foreach(ElementId elementId in GetElementIds(document)) {
- try {
- document.Delete(elementId);
- } catch {
- Logger.Warning("{@CommandName} Failed to remove ElementId {@elementId}",
- _commandName, elementId);
- }
- }
-
- transaction.Commit();
- }
- }
- }
-
- private IEnumerable GetElementIds(Document document) {
- return GetMethods(document)
- .SelectMany(item => (ICollection) item.Invoke(document, Array.Empty