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 -[![JetBrains Rider](https://img.shields.io/badge/JetBrains-Rider-blue.svg)](https://www.jetbrains.com/pycharm) -[![Visual Studio](https://img.shields.io/badge/Visual_Studio-2022-blue.svg)](https://www.jetbrains.com/pycharm) +[![JetBrains Rider](https://img.shields.io/badge/JetBrains-Rider-blue.svg)](https://www.jetbrains.com/rider) [![License MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE.md) -[![Revit 2016-2025](https://img.shields.io/badge/Revit-2016--2025-blue.svg)](https://www.autodesk.com/products/revit/overview) +[![Revit 2018-2027](https://img.shields.io/badge/Revit-2018--2027-blue.svg)](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 (Русский) + +[![JetBrains Rider](https://img.shields.io/badge/JetBrains-Rider-blue.svg)](https://www.jetbrains.com/rider) +[![License MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE.md) +[![Revit 2018-2027](https://img.shields.io/badge/Revit-2018--2027-blue.svg)](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())) - .Distinct(); - } - - private IEnumerable GetMethods(Document document) { - if(WithThermals) { - yield return document.GetType().GetMethod("GetUnusedThermals", - BindingFlags.Instance | BindingFlags.NonPublic); - } - - if(WithStructures) { - yield return document.GetType().GetMethod("GetUnusedStructures", - BindingFlags.Instance | BindingFlags.NonPublic); - } - - if(WithAppearances) { - yield return document.GetType().GetMethod("GetUnusedAppearances", - BindingFlags.Instance | BindingFlags.NonPublic); - } - - if(WithMaterials) { - yield return document.GetType().GetMethod("GetUnusedMaterials", - BindingFlags.Instance | BindingFlags.NonPublic); - } - - if(WithImportCategories) { - yield return document.GetType().GetMethod("GetUnusedImportCategories", - BindingFlags.Instance | BindingFlags.NonPublic); - } - - if(WithNonDeletable) { - yield return document.GetType().GetMethod("GetNonDeletableUnusedElements", - BindingFlags.Instance | BindingFlags.NonPublic); - } - - if(WithLinkSymbols) { - yield return document.GetType().GetMethod("GetUnusedLinkSymbols", - BindingFlags.Instance | BindingFlags.NonPublic); - } - - if(WithSymbols) { - yield return document.GetType().GetMethod("GetUnusedSymbols", - BindingFlags.Instance | BindingFlags.NonPublic); - } - - if(WithFamilies) { - yield return document.GetType().GetMethod("GetUnusedFamilies", - BindingFlags.Instance | BindingFlags.NonPublic); - } - } - } -} \ No newline at end of file diff --git a/src/RevitCoreDBApplications/RevitCoreDBApplications.csproj b/src/RevitCoreDBApplications/RevitCoreDBApplications.csproj deleted file mode 100644 index 0c8b8d3..0000000 --- a/src/RevitCoreDBApplications/RevitCoreDBApplications.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/RevitCoreDBApplications/SyncDocumentCommand.cs b/src/RevitCoreDBApplications/SyncDocumentCommand.cs deleted file mode 100644 index 3c00408..0000000 --- a/src/RevitCoreDBApplications/SyncDocumentCommand.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Autodesk.Revit.DB; - -using DesignAutomationFramework; - -namespace RevitCoreDBApplications { - public class SyncDocumentCommand : BaseCommand { - public SyncDocumentCommand() - : base("Sync central model") { - } - - public bool Compact { get; set; } = true; - public string Comment { get; set; } = "Sync central model."; - - protected override void ExecuteCommand(DesignAutomationData designAutomationData) { - Document document = designAutomationData.RevitDoc; - document.SynchronizeWithCentral(CreateTransactWithCentralOptions(), CreateSynchronizeWithCentralOptions()); - } - - public TransactWithCentralOptions CreateTransactWithCentralOptions() { - var options = new TransactWithCentralOptions(); - options.SetLockCallback(new CentralLockedCallback(true)); - - return options; - } - - public SynchronizeWithCentralOptions CreateSynchronizeWithCentralOptions() { - var options = new SynchronizeWithCentralOptions { - SaveLocalAfter = true, SaveLocalBefore = true, Comment = Comment, Compact = Compact - }; - - options.SetRelinquishOptions(CreateRelinquishOptions()); - return options; - } - - public RelinquishOptions CreateRelinquishOptions() { - return new RelinquishOptions(true) { - UserWorksets = true, - ViewWorksets = true, - FamilyWorksets = true, - StandardWorksets = true, - CheckedOutElements = true, - }; - } - } - - internal class CentralLockedCallback : ICentralLockedCallback { - private readonly bool _waitLock; - - public CentralLockedCallback(bool waitLock) { - _waitLock = waitLock; - } - - public bool ShouldWaitForLockAvailability() { - return _waitLock; - } - } -} \ No newline at end of file diff --git a/src/RevitEngine.DBApplications/Abstractions/IDBApplicationFactory.cs b/src/RevitEngine.DBApplications/Abstractions/IDBApplicationFactory.cs new file mode 100644 index 0000000..9e9986f --- /dev/null +++ b/src/RevitEngine.DBApplications/Abstractions/IDBApplicationFactory.cs @@ -0,0 +1,20 @@ +using Autodesk.Revit.DB; + +using RevitEngine.DBApplications.Manifests; + +namespace RevitEngine.DBApplications.Abstractions; + +/// +/// Defines a factory for creating instances of from Revit .addin manifest files. +/// +public interface IDBApplicationFactory { + /// + /// Creates and configures an instance of specified by the manifest path. + /// + /// The path to the Revit .addin manifest file that defines the DB application. + /// An initialized instance of . + /// + /// Thrown when the application class type cannot be found or does not implement . + /// + IExternalDBApplication Create(string componentPath); +} diff --git a/src/RevitEngine.DBApplications/Abstractions/IDBApplicationManifest.cs b/src/RevitEngine.DBApplications/Abstractions/IDBApplicationManifest.cs new file mode 100644 index 0000000..f2d288d --- /dev/null +++ b/src/RevitEngine.DBApplications/Abstractions/IDBApplicationManifest.cs @@ -0,0 +1,18 @@ +using RevitEngine.DBApplications.Manifests; + +namespace RevitEngine.DBApplications.Abstractions; + +/// +/// Defines a service for parsing Revit .addin manifest files specifically for DB (external database) applications. +/// +public interface IDBApplicationManifest { + /// + /// Parses the specified .addin manifest file and extracts information about the DB application. + /// + /// The absolute or relative path to the .addin manifest file. + /// A object containing the parsed application details. + /// Thrown when the is null or empty. + /// Thrown when the manifest does not contain a valid DBApplication entry or has missing elements. + /// Thrown when the assembly path specified in the manifest does not exist. + DBApplicationInfo Parse(string manifestPath); +} diff --git a/src/RevitEngine.DBApplications/Manifests/DBApplicationInfo.cs b/src/RevitEngine.DBApplications/Manifests/DBApplicationInfo.cs new file mode 100644 index 0000000..ef660d1 --- /dev/null +++ b/src/RevitEngine.DBApplications/Manifests/DBApplicationInfo.cs @@ -0,0 +1,16 @@ +namespace RevitEngine.DBApplications.Manifests; + +/// +/// Contains metadata about a Revit external database application (DBApplication) resolved from an .addin manifest. +/// +public sealed class DBApplicationInfo { + /// + /// Gets or sets the fully qualified name of the class implementing . + /// + public required string FullClassName { get; init; } + + /// + /// Gets or sets the absolute path to the compiled assembly containing the DB application. + /// + public required string FullAssemblyPath { get; init; } +} diff --git a/src/RevitEngine.DBApplications/Manifests/DBApplicationManifest.cs b/src/RevitEngine.DBApplications/Manifests/DBApplicationManifest.cs new file mode 100644 index 0000000..e0a413e --- /dev/null +++ b/src/RevitEngine.DBApplications/Manifests/DBApplicationManifest.cs @@ -0,0 +1,88 @@ +using System.Xml.Linq; + +using Microsoft.Extensions.Logging; + +using RevitEngine.DBApplications.Abstractions; + +namespace RevitEngine.DBApplications.Manifests; + +/// +/// Default implementation of that parses standard Revit .addin XML files. +/// +public sealed partial class DBApplicationManifest : IDBApplicationManifest { + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The logger instance for diagnostic messages. + public DBApplicationManifest(ILogger logger) { + _logger = logger; + } + + /// + public DBApplicationInfo Parse(string manifestPath) { + if(string.IsNullOrWhiteSpace(manifestPath)) { + LogManifestError(_logger, "The manifest path is empty."); + throw new ArgumentException("The manifest path cannot be empty.", nameof(manifestPath)); + } + + LogManifestLoading(_logger, manifestPath); + var addinManifest = XDocument.Load(manifestPath); + var dbApplicationEntry = addinManifest + .Descendants("AddIn") + .FirstOrDefault(static addInElement => + string.Equals( + (string?) addInElement.Attribute("Type"), + "DBApplication", + StringComparison.OrdinalIgnoreCase)); + + if(dbApplicationEntry is null) { + LogManifestError(_logger, manifestPath); + throw new InvalidOperationException( + $"The bundle doesn't contain manifest module \"{manifestPath}\"."); + } + + string? assemblyPath = dbApplicationEntry.Element("Assembly")?.Value.Trim(); + if(string.IsNullOrWhiteSpace(assemblyPath)) { + LogManifestError(_logger, "The .addin manifest doesn't contain an Assembly element."); + throw new InvalidOperationException("The .addin manifest doesn't contain an Assembly element."); + } + + string? fullClassName = dbApplicationEntry.Element("FullClassName")?.Value.Trim(); + if(string.IsNullOrWhiteSpace(fullClassName)) { + LogManifestError(_logger, "The .addin manifest doesn't contain a FullClassName element."); + throw new InvalidOperationException("The .addin manifest doesn't contain a FullClassName element."); + } + + string fullAssemblyPath = Path.GetFullPath( + Path.Combine( + Path.GetDirectoryName(manifestPath)!, + assemblyPath)); + LogManifestEntry(_logger, fullClassName, fullAssemblyPath); + + if(!File.Exists(fullAssemblyPath)) { + LogAssemblyError(_logger, fullAssemblyPath); + throw new FileNotFoundException( + $"The assembly specified by the .addin manifest was not found: \"{fullAssemblyPath}\".", + fullAssemblyPath); + } + + return new DBApplicationInfo() { + FullClassName = fullClassName!, + FullAssemblyPath = fullAssemblyPath + }; + } + + [LoggerMessage(LogLevel.Debug, "Loading .addin manifest from {ManifestPath}.")] + private static partial void LogManifestLoading(ILogger logger, string manifestPath); + + [LoggerMessage(LogLevel.Debug, "Resolved .addin entry {FullClassName} from assembly {AssemblyPath}.")] + private static partial void LogManifestEntry(ILogger logger, string? fullClassName, string assemblyPath); + + [LoggerMessage(LogLevel.Error, "DB application manifest error: {Message}.")] + private static partial void LogManifestError(ILogger logger, string message); + + [LoggerMessage(LogLevel.Error, "DB application assembly was not found at {AssemblyPath}.")] + private static partial void LogAssemblyError(ILogger logger, string assemblyPath); +} diff --git a/src/RevitEngine.DBApplications/RevitEngine.DBApplications.csproj b/src/RevitEngine.DBApplications/RevitEngine.DBApplications.csproj new file mode 100644 index 0000000..4b8b327 --- /dev/null +++ b/src/RevitEngine.DBApplications/RevitEngine.DBApplications.csproj @@ -0,0 +1,15 @@ + + + + x64 + true + D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027 + + + + + + + + + diff --git a/src/RevitEngine.DBApplications/Runtime/DBApplicationFactory.cs b/src/RevitEngine.DBApplications/Runtime/DBApplicationFactory.cs new file mode 100644 index 0000000..bc8ec8b --- /dev/null +++ b/src/RevitEngine.DBApplications/Runtime/DBApplicationFactory.cs @@ -0,0 +1,81 @@ +using System.Reflection; + +using Autodesk.Revit.DB; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using RevitEngine.DBApplications.Abstractions; +using RevitEngine.DBApplications.Manifests; + +namespace RevitEngine.DBApplications.Runtime; + +/// +/// Factory service that loads, instantiates, and configures implementations. +/// +public sealed partial class DBApplicationFactory : IDBApplicationFactory { + private readonly ILogger _logger; + private readonly IDBApplicationManifest _manifest; + private readonly IServiceProvider _serviceProvider; + + /// + /// Initializes a new instance of the class. + /// + /// The logger instance for diagnostics. + /// The manifest parser service. + /// The application service provider used to resolve dependencies for created DB applications. + public DBApplicationFactory( + ILogger logger, + IDBApplicationManifest manifest, + IServiceProvider serviceProvider) { + _logger = logger; + _manifest = manifest; + _serviceProvider = serviceProvider; + } + + /// + public IExternalDBApplication Create(string componentPath) { + var info = _manifest.Parse(componentPath); + + var assembly = Assembly.LoadFrom(info.FullAssemblyPath); + LogAssemblyLoaded(_logger, info.FullAssemblyPath); + + var applicationType = assembly.GetType(info.FullClassName, throwOnError: true, ignoreCase: false) + ?? throw new InvalidOperationException( + $"The type \"{info.FullClassName}\" was not found in \"{info.FullAssemblyPath}\"."); + + if(!typeof(IExternalDBApplication).IsAssignableFrom(applicationType)) { + LogApplicationTypeError(_logger, info.FullClassName); + throw new InvalidOperationException( + $"The type \"{info.FullClassName}\" must implement {nameof(IExternalDBApplication)}."); + } + + var dbApplication = CreateDBApplication(info, applicationType); + LogApplicationCreated(_logger, info.FullClassName); + + return dbApplication; + } + + private IExternalDBApplication CreateDBApplication(DBApplicationInfo info, Type applicationType) { + string appConfig = Path.ChangeExtension(info.FullAssemblyPath, ".json"); + if(File.Exists(appConfig)) { + IConfiguration configuration = new ConfigurationBuilder() + .AddJsonFile(appConfig, optional: false, reloadOnChange: true) + .Build(); + + return (IExternalDBApplication) ActivatorUtilities.CreateInstance(_serviceProvider, applicationType, configuration)!; + } + + return (IExternalDBApplication) ActivatorUtilities.CreateInstance(_serviceProvider, applicationType)!; + } + + [LoggerMessage(LogLevel.Debug, "Loaded DB application assembly {AssemblyPath}.")] + private static partial void LogAssemblyLoaded(ILogger logger, string assemblyPath); + + [LoggerMessage(LogLevel.Information, "Created DB application {FullClassName}.")] + private static partial void LogApplicationCreated(ILogger logger, string? fullClassName); + + [LoggerMessage(LogLevel.Error, "Configured DB application type {FullClassName} does not implement IExternalDBApplication.")] + private static partial void LogApplicationTypeError(ILogger logger, string? fullClassName); +} diff --git a/src/RevitEngine/Abstractions/IBundle.cs b/src/RevitEngine/Abstractions/IBundle.cs new file mode 100644 index 0000000..74ac10f --- /dev/null +++ b/src/RevitEngine/Abstractions/IBundle.cs @@ -0,0 +1,12 @@ +namespace RevitEngine.Abstractions; + +/// +/// Extracts components from a Design Automation bundle. +/// +public interface IBundle { + /// + /// Extracts the component module matching the current Revit version. + /// + /// The path to the matching component module. + string ExtractBundleComponent(); +} diff --git a/src/RevitEngine/Abstractions/IDesignAutomation.cs b/src/RevitEngine/Abstractions/IDesignAutomation.cs new file mode 100644 index 0000000..2f17601 --- /dev/null +++ b/src/RevitEngine/Abstractions/IDesignAutomation.cs @@ -0,0 +1,19 @@ +using Autodesk.Revit.ApplicationServices; + +using RevitEngine.Documents; + +namespace RevitEngine.Abstractions; + +/// +/// Defines operations for executing Design Automation tasks within a Revit application. +/// +public interface IDesignAutomation { + /// + /// Executes a Design Automation command by loading the specified application bundle, + /// opening the Revit document with the provided options, and running the lifecycle operations + /// within the Design Automation environment. + /// + /// The initialized Revit application used for executing the command. + /// The options specifying how to open the Revit document. + void ExecuteApsCommand(Application application, OpenDocumentOptions openDocumentOptions); +} diff --git a/src/RevitEngine/Abstractions/IRevitApplicationHost.cs b/src/RevitEngine/Abstractions/IRevitApplicationHost.cs new file mode 100644 index 0000000..46d9dfa --- /dev/null +++ b/src/RevitEngine/Abstractions/IRevitApplicationHost.cs @@ -0,0 +1,29 @@ +using Autodesk.Revit.ApplicationServices; + +namespace RevitEngine.Abstractions; + +/// +/// Provides lifecycle management for a Revit application instance. +/// +public interface IRevitApplicationHost { + /// + /// Gets the version of Revit targeted by the current application instance. + /// + string Version { get; } + + /// + /// Application path. + /// + string ApplicationPath { get; } + + /// + /// Initialize revit application. + /// + /// Returns revit application api class. + Application Initialize(); + + /// + /// Closes the initialized Revit application. + /// + void Close(); +} diff --git a/src/RevitEngine/Abstractions/IRevitAssemblyResolver.cs b/src/RevitEngine/Abstractions/IRevitAssemblyResolver.cs new file mode 100644 index 0000000..22104a2 --- /dev/null +++ b/src/RevitEngine/Abstractions/IRevitAssemblyResolver.cs @@ -0,0 +1,16 @@ +namespace RevitEngine.Abstractions; + +/// +/// Controls resolution of Autodesk Revit assemblies from an installed product directory. +/// +public interface IRevitAssemblyResolver { + /// + /// Installs assembly resolution for the configured Revit product. + /// + void Install(); + + /// + /// Removes assembly resolution installed by this resolver. + /// + void Uninstall(); +} diff --git a/src/RevitEngine/AssemblyResolution/RevitAssemblyResolver.cs b/src/RevitEngine/AssemblyResolution/RevitAssemblyResolver.cs new file mode 100644 index 0000000..c511446 --- /dev/null +++ b/src/RevitEngine/AssemblyResolution/RevitAssemblyResolver.cs @@ -0,0 +1,174 @@ +using System.Reflection; + +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +using RevitEngine.Abstractions; +using RevitEngine.Configuration; + +namespace RevitEngine.AssemblyResolution; + +/// +/// Resolves Autodesk Revit assemblies from the configured installation directory. +/// +public sealed partial class RevitAssemblyResolver : IRevitAssemblyResolver, IDisposable { + private bool _isInstalled; + private string? _previousDirectory; + private readonly ILogger _logger; + + /// + /// Creates a resolver for the configured Revit installation. + /// + /// Logger used for resolver lifecycle and resolution events. + /// Configured Revit context options. + public RevitAssemblyResolver( + ILogger logger, + IOptions options) { + _logger = logger; + ApplicationPath = options.Value.ApplicationPath; + } + + /// + /// Gets the Revit installation directory used for assembly resolution. + /// + public string ApplicationPath { get; } + + /// + /// Updates environment paths. + /// + public void Install() { + if(_isInstalled) { + LogInstallSkipped(_logger, ApplicationPath); + return; + } + + LogInstallStarted(_logger, ApplicationPath); + ValidateApplicationPath(); + AddToPath(); + + _previousDirectory = Directory.GetCurrentDirectory(); + Directory.SetCurrentDirectory(ApplicationPath); + + AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; + _isInstalled = true; + LogInstallCompleted(_logger, ApplicationPath); + } + + /// + /// Removes the resolver from the current application domain. + /// + public void Uninstall() { + if(!_isInstalled) { + LogUninstallSkipped(_logger, ApplicationPath); + return; + } + + AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve; + RestorePreviousDirectory(); + _isInstalled = false; + LogUninstallCompleted(_logger, ApplicationPath); + } + + private void RestorePreviousDirectory() { + if(_previousDirectory is null) { + return; + } + + if(Directory.Exists(_previousDirectory)) { + Directory.SetCurrentDirectory(_previousDirectory); + } + + _previousDirectory = null; + } + + private Assembly? CurrentDomain_AssemblyResolve(object? sender, ResolveEventArgs args) { + var assemblyName = new AssemblyName(args.Name); + string assemblyPath = Path.Combine(ApplicationPath, assemblyName.Name + ".dll"); + + if(!File.Exists(assemblyPath)) { + LogAssemblyNotFound(_logger, assemblyName.Name, assemblyPath); + return null; + } + + LogAssemblyResolved(_logger, assemblyName.Name, assemblyPath); + return Assembly.LoadFrom(assemblyPath); + } + + private void AddToPath() { + string? currentPath = Environment.GetEnvironmentVariable("PATH"); + + bool? contains = currentPath? + .Split(Path.PathSeparator) + .Contains(ApplicationPath, StringComparer.OrdinalIgnoreCase); + + if(contains == true) { + LogPathAlreadyConfigured(_logger, ApplicationPath); + return; + } + + Environment.SetEnvironmentVariable("PATH", $"{currentPath}{Path.PathSeparator}{ApplicationPath}"); + LogPathUpdated(_logger, ApplicationPath); + } + + private void ValidateApplicationPath() { + if(string.IsNullOrWhiteSpace(ApplicationPath)) { + LogApplicationPathInvalid(_logger, "The application path is empty."); + throw new InvalidOperationException( + "Revit application path is not configured."); + } + + if(!Directory.Exists(ApplicationPath)) { + LogApplicationPathInvalid(_logger, "The application directory does not exist."); + throw new DirectoryNotFoundException(ApplicationPath); + } + + string apiPath = Path.Combine(ApplicationPath, "RevitAPI.dll"); + string netPath = Path.Combine(ApplicationPath, "RevitNET.dll"); + + if(!File.Exists(apiPath) + || !File.Exists(netPath)) { + LogApplicationPathInvalid(_logger, "Required Revit API assemblies are missing."); + throw new InvalidOperationException( + $"The directory '{ApplicationPath}' is not a Revit installation directory."); + } + } + + #region IDisposable + + /// + public void Dispose() { + Uninstall(); + } + + #endregion + + [LoggerMessage(LogLevel.Information, "Starting Revit assembly resolver installation for {ApplicationPath}.")] + private static partial void LogInstallStarted(ILogger logger, string applicationPath); + + [LoggerMessage(LogLevel.Information, "Revit assembly resolver installed for {ApplicationPath}.")] + private static partial void LogInstallCompleted(ILogger logger, string applicationPath); + + [LoggerMessage(LogLevel.Debug, "Revit assembly resolver installation skipped because it is already installed for {ApplicationPath}.")] + private static partial void LogInstallSkipped(ILogger logger, string applicationPath); + + [LoggerMessage(LogLevel.Information, "Revit assembly resolver uninstalled for {ApplicationPath}.")] + private static partial void LogUninstallCompleted(ILogger logger, string applicationPath); + + [LoggerMessage(LogLevel.Debug, "Revit assembly resolver uninstallation skipped because it is not installed for {ApplicationPath}.")] + private static partial void LogUninstallSkipped(ILogger logger, string applicationPath); + + [LoggerMessage(LogLevel.Debug, "PATH already contains the Revit application path {ApplicationPath}.")] + private static partial void LogPathAlreadyConfigured(ILogger logger, string applicationPath); + + [LoggerMessage(LogLevel.Information, "Added Revit application path {ApplicationPath} to PATH.")] + private static partial void LogPathUpdated(ILogger logger, string applicationPath); + + [LoggerMessage(LogLevel.Debug, "Revit application path validation failed: {Reason}")] + private static partial void LogApplicationPathInvalid(ILogger logger, string reason); + + [LoggerMessage(LogLevel.Debug, "Resolved Revit assembly {AssemblyName} from {AssemblyPath}.")] + private static partial void LogAssemblyResolved(ILogger logger, string? assemblyName, string assemblyPath); + + [LoggerMessage(LogLevel.Debug, "Could not resolve Revit assembly {AssemblyName}; file not found at {AssemblyPath}.")] + private static partial void LogAssemblyNotFound(ILogger logger, string? assemblyName, string assemblyPath); +} diff --git a/src/RevitEngine/Bundles/Bundle.cs b/src/RevitEngine/Bundles/Bundle.cs new file mode 100644 index 0000000..e689773 --- /dev/null +++ b/src/RevitEngine/Bundles/Bundle.cs @@ -0,0 +1,54 @@ +using System.IO.Compression; + +using Autodesk.ExchangeStore; + +using Microsoft.Extensions.Options; + +using RevitEngine.Abstractions; +using RevitEngine.Configuration; +using RevitEngine.Runtime; + +namespace RevitEngine.Bundles; + +/// +/// Extracts components from a Design Automation bundle. +/// +public sealed class Bundle : IBundle { + private readonly BundleOptions _options; + + /// + /// Initializes a bundle service. + /// + /// The bundle options. + public Bundle(IOptions options) { + _options = options.Value; + } + + /// + public string ExtractBundleComponent() { + string extractionPath = Path.Combine(Path.GetTempPath(), "RevitCoreConsole", "Bundles"); + ZipFile.ExtractToDirectory(_options.BundlePath, extractionPath); + + string? bundlePath = Directory.GetDirectories(extractionPath) + .FirstOrDefault(static directoryPath => + directoryPath.EndsWith(".bundle", StringComparison.CurrentCultureIgnoreCase)); + + if(string.IsNullOrEmpty(bundlePath)) { + throw new InvalidOperationException("The bundle doesn't contain a .bundle folder."); + } + + string contentPath = Path.Combine(bundlePath, "PackageContents.xml"); + RunTimeInfo runTimeInfo = new("Revit", "Win64", "R" + RevitApplicationHost.RevitVersion); + + var componentEntry = new RevitPackageContentsParser() + .FindComponentsEntry(contentPath, runTimeInfo) + .FirstOrDefault(); + + if(componentEntry is null) { + throw new InvalidOperationException( + $"The bundle doesn't contain component for revit version {RevitApplicationHost.RevitVersion}."); + } + + return componentEntry.ModuleName; + } +} diff --git a/src/RevitEngine/Configuration/BundleOptions.cs b/src/RevitEngine/Configuration/BundleOptions.cs new file mode 100644 index 0000000..57a83df --- /dev/null +++ b/src/RevitEngine/Configuration/BundleOptions.cs @@ -0,0 +1,11 @@ +namespace RevitEngine.Configuration; + +/// +/// Defines the bundle archive used to load a Design Automation component. +/// +public sealed class BundleOptions { + /// + /// Gets or sets the path to the bundle archive. + /// + public required string BundlePath { get; set; } +} diff --git a/src/RevitEngine/Configuration/RevitApiOptions.cs b/src/RevitEngine/Configuration/RevitApiOptions.cs new file mode 100644 index 0000000..35d8dfe --- /dev/null +++ b/src/RevitEngine/Configuration/RevitApiOptions.cs @@ -0,0 +1,46 @@ +namespace RevitEngine.Configuration; + +/// +/// Defines the Revit API settings applied during document and family operations. +/// +public sealed class RevitApiOptions { + /// + /// Gets a value indicating whether existing files may be overwritten. + /// + public bool OverwriteExistingFiles { get; set; } = true; + + /// + /// Gets a value indicating whether existing symbols may be replaced. + /// + public bool ReplaceExistingSymbols { get; set; } = true; + + /// + /// Gets a value indicating whether linked files are ignored while saving. + /// + public bool IgnoreLinkedFilesOnSave { get; set; } = true; + + /// + /// Gets a value indicating whether multi-undo operations are forced. + /// + public bool ForceMultiUndoOperation { get; set; } = true; + + /// + /// Gets a value indicating whether shared families are updated. + /// + public bool UpdateSharedFamilies { get; set; } = true; + + /// + /// Gets a value indicating whether family parameters are updated. + /// + public bool UpdateFamilyParameters { get; set; } = true; + + /// + /// Gets a value indicating whether missing updaters are ignored. + /// + public bool IgnoreMissingUpdaters { get; set; } = true; + + /// + /// Gets a value indicating whether foreign files are accepted. + /// + public bool AcceptForeignFiles { get; set; } = true; +} diff --git a/src/RevitEngine/Configuration/RevitApplicationOptions.cs b/src/RevitEngine/Configuration/RevitApplicationOptions.cs new file mode 100644 index 0000000..f30a65f --- /dev/null +++ b/src/RevitEngine/Configuration/RevitApplicationOptions.cs @@ -0,0 +1,41 @@ +namespace RevitEngine.Configuration; + +/// +/// Defines the configuration required to initialize a Revit application instance. +/// +public sealed class RevitApplicationOptions { + /// + /// Gets the identifier of the client application registered with Revit. + /// + public required Guid ApplicationGuid { get; set; } + + /// + /// Gets the name of the client application. + /// + public required string ApplicationName { get; set; } + + /// + /// Gets the installation directory of the Revit application. + /// + public required string ApplicationPath { get; set; } + + /// + /// Gets the Autodesk license key used to initialize Revit. + /// + public required string LicenseKey { get; set; } + + /// + /// Gets the identifier of the application vendor. + /// + public required string VendorId { get; set; } + + /// + /// Gets the description of the application vendor. + /// + public required string VendorDescription { get; set; } + + /// + /// Gets the settings applied during Revit startup. + /// + public required RevitStartupOptions Startup { get; set; } +} diff --git a/src/RevitEngine/Configuration/RevitStartupOptions.cs b/src/RevitEngine/Configuration/RevitStartupOptions.cs new file mode 100644 index 0000000..03f5108 --- /dev/null +++ b/src/RevitEngine/Configuration/RevitStartupOptions.cs @@ -0,0 +1,59 @@ +namespace RevitEngine.Configuration; + +/// +/// Defines the settings applied while Revit starts. +/// +public sealed class RevitStartupOptions { + /// + /// Gets the journal file name. + /// + public string? JournalName { get; set; } + + /// + /// Gets the directory used for journal files. + /// + public string JournalPath { get; set; } = GetDefaultJournalPath(); + + /// + /// Gets the directory containing Revit settings files. + /// + public string SettingsFileLocation { get; set; } = GetDefaultSettingsFileLocation(); + + /// + /// Gets a value indicating whether IFC support is enabled. + /// + public bool EnableIFC { get; set; } + + /// + /// Gets a value indicating whether is applied after initialization. + /// + public bool ApplyApiSettings { get; set; } + + /// + /// Gets the Revit language name, such as English_USA. + /// + public string LanguageType { get; set; } = nameof(Autodesk.Revit.ApplicationServices.LanguageType.English_USA); + + /// + /// Gets the options controlling Revit API behavior. + /// + public RevitApiOptions Api { get; set; } = new(); + + /// + /// Returns the default directory used for Revit journal files. + /// + /// The default journal directory. + public static string GetDefaultJournalPath() { + return Environment.ExpandEnvironmentVariables( + $@"%localappdata%\Autodesk\Revit\Autodesk Revit {Runtime.RevitApplicationHost.RevitVersion}\Journals"); + } + + /// + /// Returns the default directory containing Revit settings files. + /// + /// The default settings directory. + public static string GetDefaultSettingsFileLocation() { + return Environment.ExpandEnvironmentVariables( + $@"%appdata%\Autodesk\Revit\Autodesk Revit {Runtime.RevitApplicationHost.RevitVersion}"); + } +} diff --git a/src/RevitEngine/Documents/OpenDocumentOptions.cs b/src/RevitEngine/Documents/OpenDocumentOptions.cs new file mode 100644 index 0000000..7fdcb6d --- /dev/null +++ b/src/RevitEngine/Documents/OpenDocumentOptions.cs @@ -0,0 +1,24 @@ +using Autodesk.Revit.DB; + +namespace RevitEngine.Documents; + +/// +/// Defines the options used to open a Revit document. +/// +public sealed class OpenDocumentOptions { + /// + /// Gets or sets a value indicating whether Revit audits the document while opening it. + /// + public bool Audit { get; set; } + + /// + /// Gets the user-visible path of the Revit document to open. + /// + public string? ModelPath { get; set; } + + /// + /// Gets or sets the workset configuration used when the document is opened. + /// The value must match a member of . + /// + public string? WorksetConfiguration { get; set; } = nameof(WorksetConfigurationOption.OpenAllWorksets); +} diff --git a/src/RevitEngine/Extensions/ApplicationExtensions.cs b/src/RevitEngine/Extensions/ApplicationExtensions.cs new file mode 100644 index 0000000..48ce7dc --- /dev/null +++ b/src/RevitEngine/Extensions/ApplicationExtensions.cs @@ -0,0 +1,99 @@ +using System.Reflection; + +using Autodesk.Revit.ApplicationServices; +using Autodesk.Revit.DB; + +using DesignAutomationFramework; + +using RevitEngine.Documents; + +namespace RevitEngine.Extensions; + +/// +/// Provides document-opening extensions for the Revit application. +/// +public static class ApplicationExtensions { + extension(Application application) { + /// + /// Opens a Revit document using the supplied opening options. + /// + /// Options that identify the document and configure its opening. + /// The opened Revit document. + /// + /// Thrown when the model path is empty or the workset configuration is not a valid + /// value. + /// + /// The caller owns the returned document and must close it when processing is complete. + public Document OpenDocument(OpenDocumentOptions openDocumentOptions) { + if(string.IsNullOrEmpty(openDocumentOptions.ModelPath)) { + throw new ArgumentException( + "OpenDocumentOptions doesn't have a model path.", + nameof(openDocumentOptions)); + } + + var options = new OpenOptions() { + Audit = openDocumentOptions.Audit, +#if REVIT2019_OR_GREATER + OpenForeignOption = OpenForeignOption.Open, +#endif + DetachFromCentralOption = DetachFromCentralOption.DoNotDetach, + }; + + if(!Enum.TryParse( + openDocumentOptions.WorksetConfiguration, + ignoreCase: true, + out WorksetConfigurationOption workset)) { + throw new ArgumentException( + $"Unknown workset configuration '{openDocumentOptions.WorksetConfiguration}'.", + nameof(openDocumentOptions)); + } + + options.SetIgnoreExtensibleStorageSchemaConflict(true); + options.SetOpenWorksetsConfiguration(new WorksetConfiguration(workset)); + + var modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(openDocumentOptions.ModelPath); + return application.OpenDocumentFile(modelPath, options); + } + + /// + /// Creates a controlled application wrapper for the current Revit application. + /// + /// A controlled application associated with the current application. + /// Thrown when the application instance is null. + /// + /// Thrown when Revit cannot initialize the controlled application wrapper. + /// + public ControlledApplication CreateControlledApplication() { + if(application == null) { + throw new ArgumentNullException(nameof(application)); + } + + var controlledApplication = (ControlledApplication?) typeof(ControlledApplication) + .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, [typeof(Application)], null) + ?.Invoke([application]); + + if(controlledApplication is null) { + throw new InvalidOperationException( + $"Failed to initialize \"{typeof(ControlledApplication).FullName}\"."); + } + + return controlledApplication; + } + + /// + /// Marks the Revit application as ready for Design Automation processing. + /// + /// User-visible path of the primary model used by the automation task. + /// Thrown when the application instance is null. + /// The method invokes the Design Automation bridge provided by Revit. + public void SetDesignAutomationReady(string? mainModelPath) { + if(application == null) { + throw new ArgumentNullException(nameof(application)); + } + + typeof(DesignAutomationBridge) + .GetMethod(nameof(SetDesignAutomationReady), BindingFlags.Static | BindingFlags.NonPublic) + ?.Invoke(null, [application, mainModelPath]); + } + } +} diff --git a/src/RevitEngine/Extensions/OpenOptionsExtensions.cs b/src/RevitEngine/Extensions/OpenOptionsExtensions.cs new file mode 100644 index 0000000..5073d33 --- /dev/null +++ b/src/RevitEngine/Extensions/OpenOptionsExtensions.cs @@ -0,0 +1,27 @@ +using System.Reflection; + +using Autodesk.Revit.DB; + +namespace RevitEngine.Extensions; + +/// +/// Provides compatibility extensions for Revit document opening options. +/// +public static class OpenOptionsExtensions { + /// + /// Sets whether extensible-storage schema conflicts are ignored while opening a document. + /// +#if REVIT2022_OR_GREATER + public static void SetIgnoreExtensibleStorageSchemaConflict(this OpenOptions options, bool value) { + options.IgnoreExtensibleStorageSchemaConflict = value; + } +#else + public static void SetIgnoreExtensibleStorageSchemaConflict(this OpenOptions options, bool value) { + options.GetType() + .GetProperty( + "IgnoreExtensibleStorageSchemaConflict", + BindingFlags.Instance | BindingFlags.NonPublic) + ?.SetValue(options, value); + } +#endif +} diff --git a/src/RevitEngine/Extensions/ProductExtensions.cs b/src/RevitEngine/Extensions/ProductExtensions.cs new file mode 100644 index 0000000..5c8b618 --- /dev/null +++ b/src/RevitEngine/Extensions/ProductExtensions.cs @@ -0,0 +1,106 @@ +using System.Reflection; + +using Autodesk.Revit; +using Autodesk.Revit.ApplicationServices; + +using RevitEngine.Configuration; + +namespace RevitEngine.Extensions; + +/// +/// Provides configuration extensions for the Revit product. +/// +public static class ProductExtensions { + extension(Product revitProduct) { + /// + /// Configures the journal file name used by the Revit product. + /// + public void SetJournalFile(string journalName) { + if(string.IsNullOrEmpty(journalName)) { + throw new ArgumentNullException(nameof(journalName)); + } + + var method = typeof(Product) + .GetMethod(nameof(SetJournalFile), BindingFlags.Instance | BindingFlags.NonPublic); + method?.Invoke(revitProduct, [journalName]); + } + + /// + /// Configures the directory used for Revit journal output. + /// + public void SetJournalOutputPath(string journalPath) { + if(string.IsNullOrEmpty(journalPath)) { + throw new ArgumentNullException(nameof(journalPath)); + } + + if(!Directory.Exists(Path.GetDirectoryName(Path.GetFullPath(journalPath)))) { + throw new ArgumentException("JournalPath is not found.", nameof(journalPath)); + } + + var method = typeof(Product) + .GetMethod(nameof(SetJournalOutputPath), BindingFlags.Instance | BindingFlags.NonPublic); + method?.Invoke(revitProduct, [journalPath]); + } + + /// + /// Gets whether advanced API settings are enabled for the product. + /// + public bool GetUseAdvancedApiSettings() { + var property = typeof(Product) + .GetProperty("UseAdvancedAPISettings", BindingFlags.Instance | BindingFlags.NonPublic); + + return (bool) (property?.GetValue(revitProduct) ?? false); + } + + /// + /// Enables or disables advanced API settings for the product. + /// + public void SetUseAdvancedApiSettings(bool useAdvanceSettings) { + if(revitProduct is null) { + throw new ArgumentNullException(nameof(revitProduct)); + } + + var property = typeof(Product) + .GetProperty("UseAdvancedAPISettings", BindingFlags.Instance | BindingFlags.NonPublic); + + property?.SetValue(revitProduct, useAdvanceSettings); + } + + /// + /// Applies startup settings to the Revit product. + /// + public void ApplyStartupSettings(RevitStartupOptions startupOptions) { + revitProduct.EnableIFC(startupOptions.EnableIFC); + revitProduct.SetPreferredLanguage(Enum.Parse(startupOptions.LanguageType)); + revitProduct.SetUseAdvancedApiSettings(startupOptions.ApplyApiSettings); + + if(!string.IsNullOrEmpty(startupOptions.JournalName)) { + revitProduct.SetJournalFile(startupOptions.JournalName!); + } + + if(!string.IsNullOrEmpty(startupOptions.JournalPath)) { + revitProduct.SetJournalOutputPath(startupOptions.JournalPath); + } + + if(!string.IsNullOrEmpty(startupOptions.SettingsFileLocation)) { + revitProduct.SetSettingsFileLocation(startupOptions.SettingsFileLocation); + } + } + + /// + /// Applies API options to the Revit product. + /// + public void ApplyApiSettings(RevitApiOptions apiOptions) { +#if REVIT2019_OR_GREATER + revitProduct.Settings[APIOption.AcceptForeignFiles] = apiOptions.AcceptForeignFiles; +#endif + revitProduct.Settings[APIOption.IgnoreMissingUpdaters] = apiOptions.IgnoreMissingUpdaters; + revitProduct.Settings[APIOption.OverwriteExistingFiles] = apiOptions.OverwriteExistingFiles; + revitProduct.Settings[APIOption.ReplaceExistingSymbols] = apiOptions.ReplaceExistingSymbols; + revitProduct.Settings[APIOption.UpdateSharedFamilies] = apiOptions.UpdateSharedFamilies; + revitProduct.Settings[APIOption.UpdateFamilyParameters] = apiOptions.UpdateFamilyParameters; + revitProduct.Settings[APIOption.ForceMultiUndoOperation] = apiOptions.ForceMultiUndoOperation; + revitProduct.Settings[APIOption.IgnoreLinkedFilesOnSave] = apiOptions.IgnoreLinkedFilesOnSave; + } + } +} diff --git a/src/RevitEngine/RevitEngine.csproj b/src/RevitEngine/RevitEngine.csproj new file mode 100644 index 0000000..10e5f5e --- /dev/null +++ b/src/RevitEngine/RevitEngine.csproj @@ -0,0 +1,23 @@ + + + + x64 + true + D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027 + + + + + + + + + + + + + + + + + diff --git a/src/RevitEngine/Runtime/DesignAutomation.cs b/src/RevitEngine/Runtime/DesignAutomation.cs new file mode 100644 index 0000000..47f0872 --- /dev/null +++ b/src/RevitEngine/Runtime/DesignAutomation.cs @@ -0,0 +1,98 @@ +using System.Reflection; +using System.Xml.Linq; + +using Autodesk.Revit.ApplicationServices; +using Autodesk.Revit.DB; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using RevitEngine.Abstractions; +using RevitEngine.DBApplications.Abstractions; +using RevitEngine.Documents; +using RevitEngine.Extensions; + +namespace RevitEngine.Runtime; + +/// +/// Provides Design Automation operations for a Revit application. +/// +public sealed partial class DesignAutomation : IDesignAutomation { + private readonly IBundle _bundle; + private readonly ILogger _logger; + private readonly IDBApplicationFactory _applicationFactory; + + /// + /// Initializes Design Automation operations. + /// + /// The bundle service. + /// The logger used for lifecycle and manifest diagnostics. + /// The application factory. + public DesignAutomation(IBundle bundle, ILogger logger, IDBApplicationFactory applicationFactory) { + _bundle = bundle ?? throw new ArgumentNullException(nameof(bundle)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _applicationFactory = applicationFactory ?? throw new ArgumentNullException(nameof(applicationFactory)); + } + + /// + /// Executes a Design Automation command by loading the specified application bundle, + /// opening the Revit document with the provided options, and running the lifecycle operations + /// within the Design Automation environment. + /// + /// The initialized Revit application used for executing the command. + /// The options specifying how to open the Revit document. + public void ExecuteApsCommand(Application application, OpenDocumentOptions openDocumentOptions) { + LogExecutionStarted(_logger, openDocumentOptions.ModelPath); + + string componentPath = _bundle.ExtractBundleComponent(); + LogComponentExtracted(_logger, componentPath); + + var retrieveDbApplication = _applicationFactory.Create(componentPath); + LogDbApplicationResolved(_logger, retrieveDbApplication.GetType().FullName ?? retrieveDbApplication.GetType().Name); + + // opens document because + // it needs to apply custom open model settings + _ = application.OpenDocument(openDocumentOptions); + LogDocumentOpened(_logger, openDocumentOptions.ModelPath); + + var controlledApplication = application.CreateControlledApplication(); + try { + var startupResult = retrieveDbApplication.OnStartup(controlledApplication); + LogLifecycleResult(_logger, "Startup", startupResult.ToString()); + CheckResult(startupResult, "Startup"); + + application.SetDesignAutomationReady(openDocumentOptions.ModelPath); + LogDesignAutomationReady(_logger, openDocumentOptions.ModelPath); + } finally { + var shutdownResult = retrieveDbApplication.OnShutdown(controlledApplication); + LogLifecycleResult(_logger, "Shutdown", shutdownResult.ToString()); + CheckResult(shutdownResult, "Shutdown"); + } + } + + private static void CheckResult(ExternalDBApplicationResult result, string operation) { + if(result == ExternalDBApplicationResult.Failed) { + throw new InvalidOperationException($"{operation} result failed."); + } + } + + [LoggerMessage(LogLevel.Information, "Design Automation execution started for model {ModelPath}.")] + private static partial void LogExecutionStarted(ILogger logger, string? modelPath); + + [LoggerMessage(LogLevel.Debug, "Bundle component extracted to {ComponentPath}.")] + private static partial void LogComponentExtracted(ILogger logger, string componentPath); + + [LoggerMessage(LogLevel.Information, "Resolved DB application type {ApplicationType}.")] + private static partial void LogDbApplicationResolved(ILogger logger, string applicationType); + + [LoggerMessage(LogLevel.Debug, "Revit document opened from {ModelPath}.")] + private static partial void LogDocumentOpened(ILogger logger, string? modelPath); + + [LoggerMessage(LogLevel.Information, "DB application lifecycle operation {Operation} returned {Result}.")] + private static partial void LogLifecycleResult(ILogger logger, string operation, string result); + + [LoggerMessage(LogLevel.Information, "Design Automation is ready for model {ModelPath}.")] + private static partial void LogDesignAutomationReady(ILogger logger, string? modelPath); + + +} diff --git a/src/RevitEngine/Runtime/RevitApplicationHost.cs b/src/RevitEngine/Runtime/RevitApplicationHost.cs new file mode 100644 index 0000000..ae44a73 --- /dev/null +++ b/src/RevitEngine/Runtime/RevitApplicationHost.cs @@ -0,0 +1,154 @@ +using System.Reflection; + +using Autodesk.Revit; +using Autodesk.Revit.ApplicationServices; +using Autodesk.Revit.DB; + +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +using RevitEngine.Abstractions; +using RevitEngine.Configuration; +using RevitEngine.Extensions; + +namespace RevitEngine.Runtime; + +/// +/// Initializes and closes a Revit application instance. +/// +public sealed partial class RevitApplicationHost : IRevitApplicationHost, IDisposable { + private readonly ILogger _logger; + private readonly RevitApplicationOptions _options; + + /// + /// Creates revit application. + /// + public RevitApplicationHost(ILogger logger, IOptions options) { + _logger = logger; + _options = options.Value; + } + + /// + /// Gets the version of Revit targeted by the current application instance. + /// + public string Version => RevitVersion; + + /// + /// Gets the Revit version targeted by the current build. + /// +#if REVIT2016 + public const string RevitVersion = "2016"; +#elif REVIT2017 + public const string RevitVersion = "2017"; +#elif REVIT2018 + public const string RevitVersion = "2018"; +#elif REVIT2019 + public const string RevitVersion = "2019"; +#elif REVIT2020 + public const string RevitVersion = "2020"; +#elif REVIT2021 + public const string RevitVersion = "2021"; +#elif REVIT2022 + public const string RevitVersion = "2022"; +#elif REVIT2023 + public const string RevitVersion = "2023"; +#elif REVIT2024 + public const string RevitVersion = "2024"; +#elif REVIT2025 + public const string RevitVersion = "2025"; +#elif REVIT2026 + public const string RevitVersion = "2026"; +#elif REVIT2027 + public const string RevitVersion = "2027"; +#endif + + /// + /// Gets the installation directory of the Revit application. + /// + public string ApplicationPath => _options.ApplicationPath; + + /// + /// Gets the initialized Revit product, or before initialization and after closing. + /// + public Product? RevitProduct { get; private set; } + + /// + /// Initializes Revit and returns its application API object. + /// + /// The initialized Revit application. + public Application Initialize() { + LogInitializationStarted(_logger, RevitVersion, _options.ApplicationPath); + + RevitProduct = Product.GetInstalledProduct(); + RevitProduct.ApplyStartupSettings(_options.Startup); + + var clientId = new ClientApplicationId(_options.ApplicationGuid, _options.ApplicationName, _options.VendorId); + clientId.VendorDescription = _options.VendorDescription; + clientId.SetClientApplicationVer( + Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0.0"); + + try { +#if REVIT2022_OR_GREATER + RevitProduct.Initialize_ForAutodeskInternalUseOnly(clientId, _options.LicenseKey); +#else + RevitProduct.Init(clientId, _options.LicenseKey); +#endif + } catch(global::Autodesk.Revit.Exceptions.ArgumentException ex) when(ex.ParamName.Equals("clientData")) { + LogInitializationFailed(_logger, ex, RevitVersion); + throw new InvalidOperationException($"The \"{_options.LicenseKey}\" license key is not valid.", ex); + } catch(global::Autodesk.Revit.Exceptions.ArgumentException ex) when(ex.ParamName.Equals("id")) { + LogInitializationFailed(_logger, ex, RevitVersion); + throw new InvalidOperationException($"The \"{_options.LicenseKey}\" license key is not valid.", ex); + } + + if(_options.Startup.ApplyApiSettings) { + RevitProduct.ApplyApiSettings(_options.Startup.Api); + } + + LogInitializationCompleted(_logger, RevitVersion); + return RevitProduct.Application; + } + + /// + /// Closes the initialized Revit application. + /// + public void Close() { + if(RevitProduct is null) { + LogCloseSkipped(_logger); + return; + } + + LogClosing(_logger, RevitVersion); + RevitProduct?.Exit(); + RevitProduct?.Dispose(); + RevitProduct = null; + LogClosed(_logger, RevitVersion); + } + + #region IDisposable + + /// + public void Dispose() { + Close(); + } + + #endregion + + [LoggerMessage(LogLevel.Information, "Starting Revit {RevitVersion} initialization from {ApplicationPath}.")] + private static partial void LogInitializationStarted(ILogger logger, string revitVersion, string applicationPath); + + [LoggerMessage(LogLevel.Information, "Revit {RevitVersion} initialized successfully.")] + private static partial void LogInitializationCompleted(ILogger logger, string revitVersion); + + [LoggerMessage(LogLevel.Error, "Revit {RevitVersion} initialization failed because the client data is invalid.")] + private static partial void LogInitializationFailed(ILogger logger, Exception exception, string revitVersion); + + [LoggerMessage(LogLevel.Information, "Closing Revit {RevitVersion}.")] + private static partial void LogClosing(ILogger logger, string revitVersion); + + [LoggerMessage(LogLevel.Information, "Revit {RevitVersion} closed successfully.")] + private static partial void LogClosed(ILogger logger, string revitVersion); + + [LoggerMessage(LogLevel.Debug, "Revit context close skipped because it was not initialized.")] + private static partial void LogCloseSkipped(ILogger logger); +} diff --git a/src/dosymep.Revit.Engine/ApiOptions.cs b/src/dosymep.Revit.Engine/ApiOptions.cs deleted file mode 100644 index bbdcc06..0000000 --- a/src/dosymep.Revit.Engine/ApiOptions.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace dosymep.Revit.Engine -{ - /// - /// Api options. - /// - public class ApiOptions { - /// - /// Overwrite existing files. - /// - public bool IsOverwriteExistingFiles { get; set; } = true; - - /// - /// Replace existing symbols. - /// - public bool IsReplaceExistingSymbols { get; set; } = true; - - /// - /// Ignore linked files on save. - /// - public bool IsIgnoreLinkedFilesOnSave { get; set; } = true; - - /// - /// Force multi undo operation. - /// - public bool IsForceMultiUndoOperation { get; set; } = true; - - /// - /// Update shared families. - /// - public bool IsUpdateSharedFamilies { get; set; } = true; - - /// - /// Update family parameters. - /// - public bool IsUpdateFamilyParameters { get; set; } = true; - - /// - /// Ignore missing updaters. - /// - public bool IsIgnoreMissingUpdaters { get; set; } = true; - - /// - /// Accept foreign files. - /// - public bool IsAcceptForeignFiles { get; set; } = true; - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/CoreCommands/IForgeCommand.cs b/src/dosymep.Revit.Engine/CoreCommands/IForgeCommand.cs deleted file mode 100644 index 01990f2..0000000 --- a/src/dosymep.Revit.Engine/CoreCommands/IForgeCommand.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace dosymep.Revit.Engine.CoreCommands { - public interface IForgeCommand { - string ModelPath { get; } - string BundlePath { get; } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/CoreCommands/IPipelineCommand.cs b/src/dosymep.Revit.Engine/CoreCommands/IPipelineCommand.cs deleted file mode 100644 index 7e07bb6..0000000 --- a/src/dosymep.Revit.Engine/CoreCommands/IPipelineCommand.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace dosymep.Revit.Engine.CoreCommands { - public interface IPipelineCommand { - string PipelineFile { get; } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/CoreCommands/IRevitCommand.cs b/src/dosymep.Revit.Engine/CoreCommands/IRevitCommand.cs deleted file mode 100644 index 144052f..0000000 --- a/src/dosymep.Revit.Engine/CoreCommands/IRevitCommand.cs +++ /dev/null @@ -1,9 +0,0 @@ -using dosymep.Revit.FileInfo.RevitAddins; - -namespace dosymep.Revit.Engine.CoreCommands { - public interface IRevitCommand { - string ModelPath { get; } - string JournalData { get; } - RevitAddinItem RevitAddinItem { get; } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/IRevitContext.cs b/src/dosymep.Revit.Engine/IRevitContext.cs deleted file mode 100644 index f9d382e..0000000 --- a/src/dosymep.Revit.Engine/IRevitContext.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Autodesk.Revit; -using Autodesk.Revit.ApplicationServices; -using Autodesk.Revit.DB; - -using dosymep.Revit.Engine.Pipelines; - -using Serilog; - -namespace dosymep.Revit.Engine { - /// - /// Interface revit application. - /// - public interface IRevitContext { - /// - /// Main app logger. - /// - ILogger Logger { get; } - - /// - /// Revit application. - /// - Application Application { get; } - - /// - /// Opens document in revit context. - /// - /// Open model options. - Document OpenDocument(OpenModelOptions openModelOptions); - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/Pipelines/OpenModelOptions.cs b/src/dosymep.Revit.Engine/Pipelines/OpenModelOptions.cs deleted file mode 100644 index 707a253..0000000 --- a/src/dosymep.Revit.Engine/Pipelines/OpenModelOptions.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Autodesk.Revit.DB; - -using YamlDotNet.Serialization; - -namespace dosymep.Revit.Engine.Pipelines { - /// - /// Open model options. - /// - public class OpenModelOptions { - /// - /// Option name. - /// - [YamlMember(Alias = "name", ApplyNamingConventions = false)] - public string Name { get; set; } - - /// - /// Model path. - /// - [YamlMember(Alias = "path", ApplyNamingConventions = false)] - public string ModelPath { get; set; } - - /// - /// Open with audit. - /// - [YamlMember(Alias = "audit", ApplyNamingConventions = false)] - public bool Audit { get; set; } - - /// - /// Open workset option. - /// - [YamlMember(Alias = "workset", ApplyNamingConventions = false)] - public string WorksetOption { get; set; } - - /// - /// Workset configuration option. - /// - [YamlIgnore] - public WorksetConfigurationOption WorksetConfigurationOption - => RevitPipeline.GetPipelineValue(WorksetOption, WorksetConfigurationOption.OpenAllWorksets); - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/Pipelines/PipelineStepOptions.cs b/src/dosymep.Revit.Engine/Pipelines/PipelineStepOptions.cs deleted file mode 100644 index 569e5b7..0000000 --- a/src/dosymep.Revit.Engine/Pipelines/PipelineStepOptions.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Collections.Generic; - -using YamlDotNet.Serialization; - -namespace dosymep.Revit.Engine.Pipelines { - /// - /// Pipeline step options. - /// - public class PipelineStepOptions { - /// - /// Step name. - /// - [YamlMember(Alias = "name", ApplyNamingConventions = false)] - public string Name { get; set; } - - /// - /// Uses script name. - /// - [YamlMember(Alias = "uses", ApplyNamingConventions = false)] - public string UsesName { get; set; } - - /// - /// Dictionary script start options. - /// - [YamlMember(Alias = "with", ApplyNamingConventions = false)] - public Dictionary WithOptions { get; set; } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/Pipelines/RevitPipeline.cs b/src/dosymep.Revit.Engine/Pipelines/RevitPipeline.cs deleted file mode 100644 index 4dbe07c..0000000 --- a/src/dosymep.Revit.Engine/Pipelines/RevitPipeline.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; - -using YamlDotNet.Serialization; -using YamlDotNet.Serialization.NamingConventions; - -namespace dosymep.Revit.Engine.Pipelines { - /// - /// Revit pipeline. - /// - public class RevitPipeline { - /// - /// Yaml file extensions - /// - public static readonly IReadOnlyCollection Extensions = new[] {".yaml", ".yml"}; - - /// - /// Open model options. - /// - [YamlMember(Alias = "model", ApplyNamingConventions = false)] - public OpenModelOptions OpenModelOptions { get; set; } - - /// - /// Pipeline step options. - /// - [YamlMember(Alias = "steps", ApplyNamingConventions = false)] - public List StepOptions { get; set; } - - /// - /// Creates revit pipeline. - /// - /// Yaml file path. - /// Returns created revit pipeline. - public static RevitPipeline CreateRevitPipeline(string yamlPath) { - if(string.IsNullOrEmpty(yamlPath)) { - throw new ArgumentException("Value cannot be null or empty.", nameof(yamlPath)); - } - - if(!Extensions.Any(item => yamlPath.EndsWith(item, StringComparison.CurrentCultureIgnoreCase))) { - throw new ArgumentException($"The \"{yamlPath}\" is not a yaml file.", nameof(yamlPath)); - } - - if(!File.Exists(yamlPath)) { - throw new ArgumentException($"The \"{yamlPath}\" is not found.", nameof(yamlPath)); - } - - return CreateRevitPipelineYaml(File.ReadAllText(yamlPath)); - } - - /// - /// Creates revit pipeline. - /// - /// Yaml contents. - /// Returns created revit pipeline. - public static RevitPipeline CreateRevitPipelineYaml(string yamlContent) { - if(string.IsNullOrEmpty(yamlContent)) { - throw new ArgumentException("Value cannot be null or empty.", nameof(yamlContent)); - } - - var deserializer = new DeserializerBuilder().Build(); - return deserializer.Deserialize(yamlContent); - } - - /// - /// Returns value. - /// - /// - /// - /// - /// - public static T GetPipelineValue(string value, T defaultValue = default) - where T : struct { - return (T) GetPipelineValue(typeof(T), value, defaultValue); - } - - /// - /// Returns value. - /// - /// - /// - /// - public static string GetPipelineValue(string value, string defaultValue = default) { - if(string.IsNullOrEmpty(value)) { - return defaultValue; - } - - return value - .Replace("_", string.Empty) - .Replace("-", string.Empty); - } - - /// - /// Returns value. - /// - /// - /// - /// - /// - /// - public static object GetPipelineValue(Type type, string value, object defaultValue = default) { - if(string.IsNullOrEmpty(value)) { - return defaultValue; - } - - if(type.IsEnum) { - value = value - .Replace("_", string.Empty) - .Replace("-", string.Empty); - try { - return Enum.Parse(type, value, true); - } catch { - return defaultValue; - } - } - - return Convert.ChangeType(value, type); - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitAssemblyResolver.cs b/src/dosymep.Revit.Engine/RevitAssemblyResolver.cs deleted file mode 100644 index f2d392e..0000000 --- a/src/dosymep.Revit.Engine/RevitAssemblyResolver.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.IO; -using System.Reflection; - -namespace dosymep.Revit.Engine { - /// - /// Revit assembly resolver. - /// - internal class RevitAssemblyResolver : IDisposable { - /// - /// Constructs revit assembly resolver. - /// - public RevitAssemblyResolver() { - AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; - } - - /// - /// Revit installation folder. - /// - public string RevitEnginePath { get; set; } - - /// - /// Updates environments paths. - /// - public void UpdateEnvironmentPaths() - { - string value = string.Concat(Environment.GetEnvironmentVariable("PATH"), - Path.PathSeparator, RevitEnginePath); - Environment.SetEnvironmentVariable("PATH", value); - } - - private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) - { - var assemblyName = new AssemblyName(args.Name); - string assemblyPath = Path.Combine(RevitEnginePath, assemblyName.Name + ".dll"); - if (!File.Exists(assemblyPath)) - { - assemblyPath = Path.Combine(RevitEnginePath, "SDA\\bin", assemblyName.Name + ".dll"); - } - - return File.Exists(assemblyPath) ? Assembly.LoadFrom(assemblyPath) : null; - } - - #region IDisposable - - public void Dispose() - { - AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitContext.cs b/src/dosymep.Revit.Engine/RevitContext.cs deleted file mode 100644 index e433c27..0000000 --- a/src/dosymep.Revit.Engine/RevitContext.cs +++ /dev/null @@ -1,159 +0,0 @@ -using System; -using System.IO; -using System.Linq; - -using Autodesk.Revit; -using Autodesk.Revit.DB; -using Autodesk.Revit.ApplicationServices; -using Autodesk.Revit.UI; - -using dosymep.Revit.Engine.Pipelines; - -using Serilog; - -namespace dosymep.Revit.Engine { - /// - /// Revit application. - /// - public class RevitContext : IRevitContext, IDisposable { - private readonly RevitAssemblyResolver _assemblyResolver; - - /// - /// Creates revit application. - /// - public RevitContext() { - _assemblyResolver = new RevitAssemblyResolver(); - } - - /// - /// Current revit Version. - /// -#if REVIT2016 - public static readonly string RevitVersion = "2016"; -#elif REVIT2017 - public static readonly string RevitVersion = "2017"; -#elif REVIT2018 - public static readonly string RevitVersion = "2018"; -#elif REVIT2019 - public static readonly string RevitVersion = "2019"; -#elif REVIT2020 - public static readonly string RevitVersion = "2020"; -#elif REVIT2021 - public static readonly string RevitVersion = "2021"; -#elif REVIT2022 - public static readonly string RevitVersion = "2022"; -#elif REVIT2023 - public static readonly string RevitVersion = "2023"; -#elif REVIT2024 - public static readonly string RevitVersion = "2024"; -#elif REVIT2025 - public static readonly string RevitVersion = "2025"; -#endif - - /// - /// Revit product. - /// - public Product RevitProduct { get; private set; } - - /// - /// Revit application information. - /// - public RevitContextOptions RevitContextOptions { get; set; } - - /// - public ILogger Logger { get; set; } - - /// - public Application Application => RevitProduct.Application; - - /// - /// Revit engine path. - /// - public string RevitEnginePath { - get => _assemblyResolver.RevitEnginePath; - set => _assemblyResolver.RevitEnginePath = value; - } - - /// - /// Returns default revit engine path. - /// - /// Returns default revit engine path. - public static string GetDefaultRevitEnginePath() { - return Environment.ExpandEnvironmentVariables($@"%programfiles%\Autodesk\Revit {RevitVersion}"); - } - - /// - /// Open revit application. - /// - public void Open() { - if(string.IsNullOrEmpty(RevitEnginePath)) { - throw new InvalidOperationException($"{nameof(RevitEnginePath)} is not set."); - } - - if(!Directory.Exists(RevitEnginePath)) { - throw new InvalidOperationException($"{nameof(RevitEnginePath)} is not found."); - } - - if(!IsRevitPath()) { - throw new InvalidOperationException($"{nameof(RevitEnginePath)} is not revit path."); - } - - _assemblyResolver.UpdateEnvironmentPaths(); - InitRevit(); - } - - /// - public Document OpenDocument(OpenModelOptions openModelOptions) { - return Application.OpenDocument(openModelOptions); - } - - /// - /// Close revit application. - /// - public void Close() { - RevitProduct?.Exit(); - RevitProduct?.Dispose(); - _assemblyResolver.Dispose(); - } - - private void InitRevit() { - RevitProduct = Product.GetInstalledProduct(); - RevitProduct.SetStartUpSettings(RevitContextOptions.StartUpSettings); - - var appId = new ClientApplicationId(RevitContextOptions.Guid, - RevitContextOptions.ApplicationName, RevitContextOptions.VendorName); - - try { -#if REVIT_2021_OR_LESS - RevitProduct.Init(appId, RevitContextOptions.LicenseKey); -#else - RevitProduct.Initialize_ForAutodeskInternalUseOnly(appId, RevitContextOptions.LicenseKey); -#endif - } catch(global::Autodesk.Revit.Exceptions.ArgumentException ex) when(ex.ParamName.Equals("clientData")) { - throw new InvalidOperationException($"The \"{RevitContextOptions.LicenseKey}\" license key is not valid.", ex); - } - - if(RevitContextOptions.StartUpSettings.UseApiOptions) { - RevitProduct.SetApiOptions(RevitContextOptions.StartUpSettings.ApiOptions); - } - } - - private bool IsRevitPath() { - string[] fileNames = Directory.GetFiles(RevitEnginePath, "*.dll") - .Select(item => Path.GetFileName(item)) - .ToArray(); - - return fileNames.Contains("RevitNET.dll") - && fileNames.Contains("RevitAPI.dll"); - } - - #region IDisposable - - /// - public void Dispose() { - Close(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitContextExtensions.cs b/src/dosymep.Revit.Engine/RevitContextExtensions.cs deleted file mode 100644 index 3fa52d2..0000000 --- a/src/dosymep.Revit.Engine/RevitContextExtensions.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using System.Linq; - -using Autodesk.ExchangeStore; -using Autodesk.Revit.DB; - -using dosymep.AutodeskApps; -using dosymep.Revit.Engine.CoreCommands; -using dosymep.Revit.Engine.Pipelines; -using dosymep.Revit.Engine.RevitExternals; -using dosymep.Revit.FileInfo.RevitAddins; - -using Serilog; - -using YamlDotNet.Serialization; -using YamlDotNet.Serialization.NamingConventions; - -namespace dosymep.Revit.Engine { - /// - /// Revit context extensions. - /// - public static class RevitContextExtensions { - public static void ExecutePipelineCommand(this IRevitContext revitContext, IPipelineCommand pipelineCommand) { - ILogger logger = revitContext.Logger; - - RevitPipeline pipeline = RevitPipeline.CreateRevitPipeline(pipelineCommand.PipelineFile); - logger.Debug("Loaded pipeline {@RevitPipelineSteps}", pipeline.StepOptions); - - revitContext.OpenDocument(pipeline.OpenModelOptions); - logger.Debug("Opened Document {@OpenModelOptions}", pipeline.OpenModelOptions); - - var transformer = new RevitExternalTransformer(pipeline.OpenModelOptions.ModelPath, revitContext); - var stepOptions = pipeline.StepOptions - .Select(item => PipelineOptions.CreateOption(item, transformer)); - - foreach(PipelineOptions pipelineOption in stepOptions) { - pipelineOption.Value.ExecuteExternalItem(pipelineOption.Options.WithOptions); - } - } - - public static void ExecuteRevitCommand(this IRevitContext revitContext, IRevitCommand revitCommand) { - IRevitExternalItem revitExternalItem = - revitCommand.RevitAddinItem.Reduce( - new RevitExternalTransformer(revitCommand.ModelPath, revitContext)); - revitExternalItem.ExecuteExternalItem(ReadJournalData(revitCommand.JournalData)); - } - - public static void ExecuteForgeCommand(this IRevitContext revitContext, IForgeCommand forgeCommand) { - ILogger logger = revitContext.Logger; - - var tempName = Path.Combine(Path.GetTempPath(), "RevitCoreConsole", "Bundles"); - ZipFile.ExtractToDirectory(forgeCommand.BundlePath, tempName); - logger.Debug("Extracted bundle to {@TempName}", tempName); - - string bundlePath = Directory.GetDirectories(tempName) - .FirstOrDefault(item => - item.EndsWith(".bundle", StringComparison.CurrentCultureIgnoreCase)); - - if(string.IsNullOrEmpty(bundlePath)) { - throw new InvalidOperationException("The bundle doesn't contain .bundle folder."); - } - - var runTimeInfo = new RunTimeInfo("Revit", "Win64", "R" + RevitContext.RevitVersion); - var contentPath = Path.Combine(bundlePath, "PackageContents.xml"); - var component = new RevitPackageContentsParser() - .FindComponentsEntry(contentPath, runTimeInfo) - .FirstOrDefault(); - - if(component is null) { - throw new InvalidOperationException( - $"The bundle doesn't contain component for revit version {RevitContext.RevitVersion}."); - } - - logger.Debug("Loaded component {@Component}", component); - var dbapplication = RevitAddinManifest.GetAddinManifest(component.ModuleName) - .AddinDBApplications.FirstOrDefault(); - - if(dbapplication is null) { - throw new InvalidOperationException( - $"The bundle doesn't contain component module \"{component.ModuleName}\"."); - } - - logger.Debug("Loaded DBApplication {@DBApplication}", dbapplication); - IRevitExternalItem revitExternalItem = - dbapplication.Reduce( - new RevitExternalTransformer(forgeCommand.ModelPath, revitContext)); - revitExternalItem.ExecuteExternalItem(new Dictionary()); - } - - public static IDictionary ReadJournalData(string journalData) { - if(string.IsNullOrEmpty(journalData)) { - return new Dictionary(); - } - - IDeserializer deserializer = new DeserializerBuilder() - .WithNamingConvention(CamelCaseNamingConvention.Instance) - .Build(); - return deserializer.Deserialize>(journalData); - } - - private class PipelineOptions { - public static PipelineOptions CreateOption(PipelineStepOptions options, - RevitExternalTransformer transformer) { - return new PipelineOptions() { - Options = options, Value = GetRevitExternalItem(options.UsesName, transformer) - }; - } - - public IRevitExternalItem Value { get; set; } - public PipelineStepOptions Options { get; set; } - - private static IRevitExternalItem GetRevitExternalItem(string usesName, - RevitExternalTransformer transformer) { - var revitAddinItem = - RevitAddinManifest.GetAddinManifest(Path.Combine("plugins", usesName + ".addin")) - .AddinItems.FirstOrDefault(); - return revitAddinItem?.Reduce(transformer); - } - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitContextOptions.cs b/src/dosymep.Revit.Engine/RevitContextOptions.cs deleted file mode 100644 index 3ec4b48..0000000 --- a/src/dosymep.Revit.Engine/RevitContextOptions.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.IO; - -namespace dosymep.Revit.Engine { - /// - /// Revit application information. - /// - public class RevitContextOptions { - /// - /// Application Guid. - /// - public Guid Guid { get; set; } - - /// - /// Autodesk licence key. - /// - public string LicenseKey { get; set; } - - /// - /// Vendor name. - /// - public string VendorName { get; set; } - - /// - /// Application name. - /// - public string ApplicationName { get; set; } - - /// - /// Api settings. - /// - public StartUpSettings StartUpSettings { get; set; } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalApplication.cs b/src/dosymep.Revit.Engine/RevitExternals/RevitExternalApplication.cs deleted file mode 100644 index 710dce3..0000000 --- a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalApplication.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Collections.Generic; - -using Autodesk.Revit.ApplicationServices; -using Autodesk.Revit.DB; -using Autodesk.Revit.UI; - -namespace dosymep.Revit.Engine.RevitExternals { - /// - /// External application. - /// - internal class RevitExternalApplication : RevitExternalItem { - /// - /// Creates external application. - /// - /// Revit application instance. - public RevitExternalApplication(IRevitContext revitContext) - : base(revitContext) { - } - - protected override void ExecuteExternalItemImpl(IDictionary journalData) { - UIControlledApplication controlledApplication = _revitContext.Application.CreateUIControlledApplication(); - var application = RevitAddinItem.CreateAddinItemObject(); - ApplyLogger(application, _revitContext.Logger); - ApplyJournalData(application, journalData); - CheckResult(application.OnStartup(controlledApplication)); - } - - private void CheckResult(Result startupResult) { - if(startupResult == Result.Cancelled) { - throw new OperationCanceledException(); - } else if(startupResult == Result.Failed) { - throw new Exception("Startup result failed."); - } - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalCommand.cs b/src/dosymep.Revit.Engine/RevitExternals/RevitExternalCommand.cs deleted file mode 100644 index 703e066..0000000 --- a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalCommand.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -using Autodesk.Revit.ApplicationServices; -using Autodesk.Revit.DB; -using Autodesk.Revit.UI; - -namespace dosymep.Revit.Engine.RevitExternals { - /// - /// External application command. - /// - internal class RevitExternalCommand : RevitExternalItem { - /// - /// Creates external command application. - /// - /// Revit application instance. - public RevitExternalCommand(IRevitContext revitContext) - : base(revitContext) { - } - - /// - protected override void ExecuteExternalItemImpl(IDictionary journalData) { - var application = RevitAddinItem.CreateAddinItemObject(); - ApplyLogger(application, _revitContext.Logger); - ApplyJournalData(application, journalData); - - string message = null; - ElementSet elementSet = new ElementSet(); - var externalCommandData = _revitContext.Application.CreateExternalCommandData(journalData); - CheckResult(application.Execute(externalCommandData, ref message, elementSet), message, elementSet); - } - - private void CheckResult(Result startupResult, string message, ElementSet elementSet) { - if(startupResult == Result.Failed) { - throw new Exception(FormatMessage("Canceled", message, elementSet)); - } else if(startupResult == Result.Cancelled) { - throw new OperationCanceledException(FormatMessage("Failed", message, elementSet)); - } - } - - private string FormatMessage(string operation, string message, ElementSet elementSet) { - return message ?? $"{operation} execute revit command." - + Environment.NewLine - + "ElementIds: " + string.Join("; ", elementSet.OfType().Select(item => item.IntegerValue)); - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalDBApplication.cs b/src/dosymep.Revit.Engine/RevitExternals/RevitExternalDBApplication.cs deleted file mode 100644 index 26732de..0000000 --- a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalDBApplication.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -using Autodesk.Revit.ApplicationServices; -using Autodesk.Revit.DB; - -namespace dosymep.Revit.Engine.RevitExternals { - /// - /// External DB application. - /// - // ReSharper disable once InconsistentNaming - internal class RevitExternalDBApplication : RevitExternalItem { - /// - /// Creates external DB application. - /// - /// Revit application instance. - public RevitExternalDBApplication(IRevitContext revitContext) - : base(revitContext) { - } - - /// - protected override void ExecuteExternalItemImpl(IDictionary journalData) { - ControlledApplication controlledApplication = _revitContext.Application.CreateControlledApplication(); - var application = RevitAddinItem.CreateAddinItemObject(); - try { - ApplyLogger(application, _revitContext.Logger); - ApplyJournalData(application, journalData); - CheckResult(application.OnStartup(controlledApplication), "Startup"); - _revitContext.Application.SetDesignAutomationReady(MainModelPath); - } finally { - CheckResult(application.OnShutdown(controlledApplication), "Shutdown"); - } - } - - private void CheckResult(ExternalDBApplicationResult startupResult, string operation) { - if(startupResult == ExternalDBApplicationResult.Failed) { - throw new Exception($"{operation} result failed. "); - } - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalExtensions.cs b/src/dosymep.Revit.Engine/RevitExternals/RevitExternalExtensions.cs deleted file mode 100644 index b6d843f..0000000 --- a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalExtensions.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -using Autodesk.Revit.ApplicationServices; -using Autodesk.Revit.UI; - -using DesignAutomationFramework; - -namespace dosymep.Revit.Engine.RevitExternals { - /// - /// External app extensions. - /// - public static class RevitExternalExtensions { - /// - /// Creates controlled application. - /// - /// Revit application object. - /// Returns new instance controlled application. - /// When no type constructor was found. - public static ControlledApplication CreateControlledApplication(this Application application) { - if(application == null) { - throw new ArgumentNullException(nameof(application)); - } - - return (ControlledApplication) typeof(ControlledApplication) - .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] {typeof(Application)}, null) - ?.Invoke(new object[] {application}) ?? throw new InvalidOperationException($"Failed to initialize \"{typeof(ControlledApplication).FullName}\"."); - } - - /// - /// Creates controlled application. - /// - /// Revit application object. - /// Returns new instance controlled application. - /// When no type constructor was found. - public static UIControlledApplication CreateUIControlledApplication(this Application application) { - if(application == null) { - throw new ArgumentNullException(nameof(application)); - } - - return (UIControlledApplication) typeof(UIControlledApplication) - .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] {typeof(UIApplication)}, null) - ?.Invoke(new object[] {new UIApplication(application)}) ?? throw new InvalidOperationException($"Failed to initialize \"{typeof(ControlledApplication).FullName}\"."); - } - - /// - /// Creates external command data. - /// - /// Revit application object. - /// Journal data. - /// Returns new instance external command data. - /// When no type constructor was found. - public static ExternalCommandData CreateExternalCommandData(this Application application, IDictionary journalData = default) { - if(application == null) { - throw new ArgumentNullException(nameof(application)); - } - - var externalCommandData = (ExternalCommandData) typeof(ExternalCommandData) - .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null) - ?.Invoke(new object[0]); - - if(externalCommandData == null) { - throw new InvalidOperationException($"Failed to initialize \"{typeof(ExternalCommandData).FullName}\"."); - } - - var uiApplication = new UIApplication(application); - externalCommandData.Application = uiApplication; - externalCommandData.JournalData = journalData; - externalCommandData.View = uiApplication.ActiveUIDocument?.ActiveView; - - return externalCommandData; - } - - /// - /// Set design automation ready. - /// - /// Revit application object. - /// Main model path. - public static void SetDesignAutomationReady(this Application application, string mainModelPath) { - if(application == null) { - throw new ArgumentNullException(nameof(application)); - } - - typeof(DesignAutomationBridge) - .GetMethod(nameof(SetDesignAutomationReady), BindingFlags.Static | BindingFlags.NonPublic) - ?.Invoke(null, new object[] {application, mainModelPath}); - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalItem.cs b/src/dosymep.Revit.Engine/RevitExternals/RevitExternalItem.cs deleted file mode 100644 index 67ec884..0000000 --- a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalItem.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; - -using Autodesk.Revit.ApplicationServices; -using Autodesk.Revit.DB; -using Autodesk.Revit.UI; - -using dosymep.Revit.Engine.Pipelines; -using dosymep.Revit.FileInfo.RevitAddins; - -using Serilog; - -namespace dosymep.Revit.Engine.RevitExternals { - /// - /// External application interface. - /// - public interface IRevitExternalItem { - /// - /// Main model path. - /// - string MainModelPath { get; set; } - - /// - /// Executes application. - /// - /// Journal data. - void ExecuteExternalItem(IDictionary journalData); - } - - /// - /// External application. - /// - internal abstract class RevitExternalItem : IRevitExternalItem { - /// - /// Revit application instance. - /// - protected readonly IRevitContext _revitContext; - - /// - /// Creates external application. - /// - /// Revit application instance. - /// When application is null. - protected RevitExternalItem(IRevitContext revitContext) { - _revitContext = revitContext ?? throw new ArgumentNullException(nameof(revitContext)); - } - - /// - public string MainModelPath { get; set; } - - /// - /// External app information. - /// - public RevitAddinItem RevitAddinItem { get; set; } - - /// - public void ExecuteExternalItem(IDictionary journalData) { - if(RevitAddinItem == null) { - throw new InvalidOperationException($"{nameof(RevitAddinItem)} is not set."); - } - - if(string.IsNullOrEmpty(RevitAddinItem.AssemblyPath)) { - throw new InvalidOperationException($"{nameof(RevitAddinItem.AssemblyPath)} is not set."); - } - - if(string.IsNullOrEmpty(RevitAddinItem.FullClassName)) { - throw new InvalidOperationException($"{nameof(RevitAddinItem.FullClassName)} is not set."); - } - - if(!File.Exists(RevitAddinItem.FullAssemblyPath)) { - throw new InvalidOperationException($"{nameof(RevitAddinItem.AssemblyPath)} not found."); - } - - if(!string.IsNullOrEmpty(MainModelPath) && File.Exists(MainModelPath)) { - // if file not exists consider - // model path is BIM360 or Revit Server - var mainModel = new System.IO.FileInfo(MainModelPath); - if(!string.IsNullOrEmpty(mainModel.DirectoryName)) { - Directory.SetCurrentDirectory(mainModel.DirectoryName); - } - } - - try { - OpenAndActivateDocument(); - ExecuteExternalItemImpl(journalData); - } catch(TargetInvocationException ex) when(ex.InnerException != null) { - throw ex.InnerException; - } - } - - /// - /// Executes application. - /// - /// Journal data. - protected abstract void ExecuteExternalItemImpl(IDictionary journalData); - - protected void OpenAndActivateDocument() { - OpenAndActivateDocument(WorksetConfigurationOption.OpenAllWorksets); - } - - protected void OpenAndActivateDocument(WorksetConfigurationOption worksetConfigurationOption) { - if(!string.IsNullOrEmpty(MainModelPath)) { - _revitContext.OpenDocument(new OpenModelOptions() { - ModelPath = MainModelPath, Audit = false, WorksetOption = worksetConfigurationOption.ToString() - }); - } - } - - protected void ApplyLogger(object externalItem, ILogger logger) { - Type externalType = externalItem.GetType(); - externalType.GetProperty("Logger")?.SetValue(externalItem, logger); - } - - protected void ApplyJournalData(object externalItem, IDictionary journalData) { - Type externalType = externalItem.GetType(); - externalType.GetProperty("JournalData")?.SetValue(externalItem, journalData); - - foreach(var kvp in journalData) { - var propertyName = RevitPipeline.GetPipelineValue(kvp.Key); - var propertyInfo = externalType.GetProperty(propertyName, - BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); - - if(propertyInfo == null) { - continue; - } - - propertyInfo.SetValue(externalItem, - RevitPipeline.GetPipelineValue(propertyInfo.PropertyType, kvp.Value)); - } - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalTransformer.cs b/src/dosymep.Revit.Engine/RevitExternals/RevitExternalTransformer.cs deleted file mode 100644 index ad546ab..0000000 --- a/src/dosymep.Revit.Engine/RevitExternals/RevitExternalTransformer.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Collections; -using System.Collections.Generic; - -using dosymep.AutodeskApps; -using dosymep.Revit.FileInfo.RevitAddins; - -namespace dosymep.Revit.Engine.RevitExternals { - /// - /// Transformer - /// - public class RevitExternalTransformer : - ITransformer, - ITransformer, - ITransformer, - ITransformer, - ITransformer { - private readonly string _mainModelPath; - private readonly IRevitContext _revitContext; - - /// - /// Creates external app transformer. - /// - public RevitExternalTransformer(string mainModelPath, IRevitContext revitContext) { - _mainModelPath = mainModelPath; - _revitContext = revitContext; - } - - /// - public IRevitExternalItem Transform(RevitAddinItem visitable) { - return null; - } - - /// - public IRevitExternalItem Transform(RevitAddinCommand visitable) { - return new RevitExternalCommand(_revitContext) {MainModelPath = _mainModelPath, RevitAddinItem = visitable}; - } - - /// - public IRevitExternalItem Transform(RevitAddinApplication visitable) { - return new RevitExternalApplication(_revitContext) { - MainModelPath = _mainModelPath, RevitAddinItem = visitable - }; - } - - /// - public IRevitExternalItem Transform(RevitAddinDBApplication visitable) { - return new RevitExternalDBApplication(_revitContext) { - MainModelPath = _mainModelPath, RevitAddinItem = visitable - }; - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitJournalContext.cs b/src/dosymep.Revit.Engine/RevitJournalContext.cs deleted file mode 100644 index 7225d87..0000000 --- a/src/dosymep.Revit.Engine/RevitJournalContext.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; - -using Autodesk.Revit.ApplicationServices; -using Autodesk.Revit.DB; -using Autodesk.Revit.UI; - -using dosymep.Revit.Engine.Pipelines; - -using Serilog; - -namespace dosymep.Revit.Engine { - public class RevitJournalContext : IRevitContext { - private readonly ExternalCommandData _externalCommandData; - -#if REVIT_2020 - /// - /// Current revit Version. - /// - public static readonly string RevitVersion = "2020"; -#elif REVIT_2021 - /// - /// Current revit Version. - /// - public static readonly string RevitVersion = "2021"; -#elif REVIT_2022 - /// - /// Current revit Version. - /// - public static readonly string RevitVersion = "2022"; -#elif REVIT_2023 - /// - /// Current revit Version. - /// - public static readonly string RevitVersion = "2023"; -#endif - - public RevitJournalContext(ExternalCommandData externalCommandData) { - _externalCommandData = externalCommandData; - } - - /// - public ILogger Logger { get; } - - /// - public Application Application - => _externalCommandData.Application.Application; - - /// - public Document OpenDocument(OpenModelOptions openModelOptions) { - return Application.OpenDocument(openModelOptions); - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/RevitProductExtensions.cs b/src/dosymep.Revit.Engine/RevitProductExtensions.cs deleted file mode 100644 index 73e34b9..0000000 --- a/src/dosymep.Revit.Engine/RevitProductExtensions.cs +++ /dev/null @@ -1,141 +0,0 @@ -using System; -using System.IO; -using System.Reflection; - -using Autodesk.Revit; -using Autodesk.Revit.DB; -using Autodesk.Revit.ApplicationServices; - -using dosymep.AutodeskApps.FileInfo; -using dosymep.Revit.Engine.Pipelines; - -namespace dosymep.Revit.Engine { - internal static class RevitProductExtensions { - public static void SetJournalFile(this Product revitProduct, string journalName) { - if(revitProduct == null) { - throw new ArgumentNullException(nameof(revitProduct)); - } - - if(string.IsNullOrEmpty(journalName)) { - return; - } - - MethodInfo method = typeof(Product) - .GetMethod(nameof(SetJournalFile), BindingFlags.Instance | BindingFlags.NonPublic); - method?.Invoke(revitProduct, new object[] {journalName}); - } - - public static void SetJournalOutputPath(this Product revitProduct, string journalPath) { - if(revitProduct == null) { - throw new ArgumentNullException(nameof(revitProduct)); - } - - if(string.IsNullOrEmpty(journalPath)) { - return; - } - - if(!Directory.Exists(Path.GetDirectoryName(Path.GetFullPath(journalPath)))) { - throw new ArgumentException($"JournalPath is not found.", nameof(journalPath)); - } - - MethodInfo method = typeof(Product) - .GetMethod(nameof(SetJournalOutputPath), BindingFlags.Instance | BindingFlags.NonPublic); - method?.Invoke(revitProduct, new object[] {journalPath}); - } - - public static bool GetUseAdvancedApiSettings(this Product revitProduct) { - if(revitProduct == null) { - throw new ArgumentNullException(nameof(revitProduct)); - } - - PropertyInfo property = typeof(Product) - .GetProperty("UseAdvancedAPISettings", BindingFlags.Instance | BindingFlags.NonPublic); - return (bool) (property?.GetValue(revitProduct) ?? false); - } - - public static void SetUseAdvancedApiSettings(this Product revitProduct, bool useAdvanceSettings) { - if(revitProduct == null) { - throw new ArgumentNullException(nameof(revitProduct)); - } - - PropertyInfo property = typeof(Product) - .GetProperty("UseAdvancedAPISettings", BindingFlags.Instance | BindingFlags.NonPublic); - - property?.SetValue(revitProduct, useAdvanceSettings); - } - - public static void SetStartUpSettings(this Product revitProduct, StartUpSettings startUpSettings) { - revitProduct.EnableIFC(startUpSettings.EnableIfc); - revitProduct.SetPreferredLanguage(startUpSettings.LanguageType); - revitProduct.SetUseAdvancedApiSettings(startUpSettings.UseApiOptions); - - if(!string.IsNullOrEmpty(startUpSettings.JournalName)) { - revitProduct.SetJournalFile(startUpSettings.JournalName); - } - - if(!string.IsNullOrEmpty(startUpSettings.JournalPath)) { - revitProduct.SetJournalOutputPath(startUpSettings.JournalPath); - } - - if(!string.IsNullOrEmpty(startUpSettings.SettingsFileLocation)) { - revitProduct.SetSettingsFileLocation(startUpSettings.SettingsFileLocation); - } - } - - public static void SetApiOptions(this Product revitProduct, ApiOptions apiOptions) { - revitProduct.Settings[APIOption.AcceptForeignFiles] = apiOptions.IsAcceptForeignFiles; - revitProduct.Settings[APIOption.IgnoreMissingUpdaters] = apiOptions.IsIgnoreMissingUpdaters; - revitProduct.Settings[APIOption.OverwriteExistingFiles] = apiOptions.IsOverwriteExistingFiles; - revitProduct.Settings[APIOption.ReplaceExistingSymbols] = apiOptions.IsReplaceExistingSymbols; - revitProduct.Settings[APIOption.UpdateSharedFamilies] = apiOptions.IsUpdateSharedFamilies; - revitProduct.Settings[APIOption.UpdateFamilyParameters] = apiOptions.IsUpdateFamilyParameters; - revitProduct.Settings[APIOption.ForceMultiUndoOperation] = apiOptions.IsForceMultiUndoOperation; - revitProduct.Settings[APIOption.IgnoreLinkedFilesOnSave] = apiOptions.IsIgnoreLinkedFilesOnSave; - } - - public static LanguageType ToLanguageType(this LanguageCode languageCode) { - if(Enum.TryParse(languageCode.FullCode, out LanguageType languageType)) { - return languageType; - } - - return LanguageType.Unknown; - } - - public static Document OpenDocument(this Application application, OpenModelOptions openModelOptions) { - if(openModelOptions == null) { - throw new ArgumentNullException(nameof(openModelOptions)); - } - - if(string.IsNullOrEmpty(openModelOptions.ModelPath)) { - throw new ArgumentException("OpenModelOptions doesn't have a model path.", - nameof(openModelOptions)); - } - - var options = new OpenOptions() { - Audit = openModelOptions.Audit, - OpenForeignOption = OpenForeignOption.Open, - DetachFromCentralOption = DetachFromCentralOption.DoNotDetach, - }; - - options.SetIgnoreExtensibleStorageSchemaConflict(true); - options.SetOpenWorksetsConfiguration( - new WorksetConfiguration(openModelOptions.WorksetConfigurationOption)); - return application.OpenDocumentFile( - ModelPathUtils.ConvertUserVisiblePathToModelPath(openModelOptions.ModelPath), options); - } - -#if REVIT_2021_OR_LESS - - public static void SetIgnoreExtensibleStorageSchemaConflict(this OpenOptions options, bool value) { - options.GetType().GetProperty("IgnoreExtensibleStorageSchemaConflict", - BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(options, value); - } - -#else - - public static void SetIgnoreExtensibleStorageSchemaConflict(this OpenOptions options, bool value) { - options.IgnoreExtensibleStorageSchemaConflict = true; - } -#endif - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/StartUpSettings.cs b/src/dosymep.Revit.Engine/StartUpSettings.cs deleted file mode 100644 index 8858b2c..0000000 --- a/src/dosymep.Revit.Engine/StartUpSettings.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; - -using Autodesk.Revit.ApplicationServices; - -using dosymep.AutodeskApps.FileInfo; - -namespace dosymep.Revit.Engine -{ - /// - /// Revit startup settings. - /// - public class StartUpSettings { - /// - /// Journal name. - /// - public string JournalName { get; set; } - - /// - /// Journal path. - /// - public string JournalPath { get; set; } - - /// - /// Settings file location. - /// - public string SettingsFileLocation { get; set; } = GetDefaultSettingsFileLocation(); - - /// - /// Enable IFC. - /// - public bool EnableIfc { get; set; } = false; - - /// - /// Use api options. - /// - public bool UseApiOptions { get; set; } = false; - - /// - /// Language type. - /// - public LanguageCode LanguageCode { get; set; } = LanguageCode.ENU; - - /// - /// Language type. - /// - internal LanguageType LanguageType => LanguageCode.ToLanguageType(); - - /// - /// Api options. - /// - public ApiOptions ApiOptions { get; set; } - - /// - /// Returns default journal path. - /// - /// Returns default journal path. - public static string GetDefaultJournalPath() { - return Environment.ExpandEnvironmentVariables($@"%localappdata%\Autodesk\Revit\Autodesk Revit {RevitContext.RevitVersion}\Journals"); - } - - /// - /// Returns default settings file location. - /// - /// Returns default settings file location. - public static string GetDefaultSettingsFileLocation() { - return Environment.ExpandEnvironmentVariables($@"%appdata%\Autodesk\Revit\Autodesk Revit {RevitContext.RevitVersion}"); - } - } -} \ No newline at end of file diff --git a/src/dosymep.Revit.Engine/dosymep.Revit.Engine.csproj b/src/dosymep.Revit.Engine/dosymep.Revit.Engine.csproj deleted file mode 100644 index f48b495..0000000 --- a/src/dosymep.Revit.Engine/dosymep.Revit.Engine.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - x64 - Library - D2016;D2017;D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release; - - - - - - diff --git a/tests/RevitEngine.UnitTests/RevitCoreConsole/CommandLine/CommandLineOptionParsersTests.cs b/tests/RevitEngine.UnitTests/RevitCoreConsole/CommandLine/CommandLineOptionParsersTests.cs new file mode 100644 index 0000000..dc57e91 --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitCoreConsole/CommandLine/CommandLineOptionParsersTests.cs @@ -0,0 +1,235 @@ +using System.CommandLine; + +using RevitCoreConsole.CommandLine; + +using ResourceStrings = RevitCoreConsole.Resources.Resources; + +namespace RevitEngine.UnitTests.RevitCoreConsole.CommandLine; + +public class CommandLineOptionParsersTests { + private const string RvtModelFileName = "sample-model.rvt"; + private const string RfaModelFileName = "sample-family.rfa"; + private const string ZipBundleFileName = "sample-bundle.zip"; + + #region ParseModelPath + + [Test] + public async Task ParseModelPath_MissingValue_AddsRequiredError() { + var result = ParseModelPathOption(["/i", ""]); + + await Assert.That(result.Errors.Select(item => item.Message)) + .Contains(ResourceStrings.ModelPathRequiredError); + } + + [Test] + [Arguments("RSN://server/model")] + [Arguments("BIM 360://account/model")] + [Arguments("rsn://server/model")] + public async Task ParseModelPath_RemotePath_IsAcceptedWithoutFileChecks(string remotePath) { + var result = ParseModelPathOption(["/i", remotePath]); + + await Assert.That(result.Errors).IsEmpty(); + await Assert.That(GetModelPathValue(result)).IsEqualTo(remotePath); + } + + [Test] + public async Task ParseModelPath_WrongExtension_AddsExtensionError() { + string path = CreateTempFile("sample-model.txt"); + try { + var result = ParseModelPathOption(["/i", path]); + + await Assert.That(result.Errors.Select(item => item.Message)) + .Contains(ResourceStrings.ModelPathExtensionError); + } finally { + File.Delete(path); + } + } + + [Test] + public async Task ParseModelPath_MissingFile_AddsNotFoundError() { + string missingPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".rvt"); + + var result = ParseModelPathOption(["/i", missingPath]); + + await Assert.That(result.Errors.Select(item => item.Message)) + .Contains(ResourceStrings.ModelPathNotFoundError); + } + + [Test] + [Arguments(".rvt")] + [Arguments(".rfa")] + [Arguments(".RVT")] + public async Task ParseModelPath_ExistingSupportedFile_ParsesSuccessfully(string extension) { + string path = CreateTempFile("sample-model" + extension); + try { + var result = ParseModelPathOption(["/i", path]); + + await Assert.That(result.Errors).IsEmpty(); + await Assert.That(GetModelPathValue(result)).IsEqualTo(path); + } finally { + File.Delete(path); + } + } + + #endregion + + #region ParseBundlePath + + [Test] + public async Task ParseBundlePath_MissingValue_AddsRequiredError() { + var result = ParseBundlePathOption(["/al", ""]); + + await Assert.That(result.Errors.Select(item => item.Message)) + .Contains(ResourceStrings.BundlePathRequiredError); + } + + [Test] + public async Task ParseBundlePath_MissingPath_AddsNotFoundError() { + string missingPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".zip"); + + var result = ParseBundlePathOption(["/al", missingPath]); + + await Assert.That(result.Errors.Select(item => item.Message)) + .Contains(ResourceStrings.BundlePathNotFoundError); + } + + [Test] + public async Task ParseBundlePath_ExistingDirectory_ParsesWithoutExtensionCheck() { + string directoryPath = CreateTempDirectory(); + try { + var result = ParseBundlePathOption(["/al", directoryPath]); + + await Assert.That(result.Errors).IsEmpty(); + } finally { + Directory.Delete(directoryPath, recursive: true); + } + } + + [Test] + public async Task ParseBundlePath_ExistingFileWithWrongExtension_AddsExtensionError() { + string filePath = CreateTempFile("sample-bundle.rar"); + try { + var result = ParseBundlePathOption(["/al", filePath]); + + await Assert.That(result.Errors.Select(item => item.Message)) + .Contains(ResourceStrings.BundlePathExtensionError); + } finally { + File.Delete(filePath); + } + } + + [Test] + public async Task ParseBundlePath_ExistingZipFile_ParsesSuccessfully() { + string filePath = CreateTempFile(ZipBundleFileName); + try { + var result = ParseBundlePathOption(["/al", filePath]); + + await Assert.That(result.Errors).IsEmpty(); + } finally { + File.Delete(filePath); + } + } + + #endregion + + #region ParseLanguageCode + + [Test] + [Arguments("ENU")] + [Arguments("RUS")] + [Arguments("enu")] + public async Task ParseLanguageCode_KnownCode_ParsesSuccessfully(string code) { + var result = ParseLanguageCodeOption(["/l", code]); + + await Assert.That(result.Errors).IsEmpty(); + } + + [Test] + public async Task ParseLanguageCode_UnknownCode_AddsError() { + var result = ParseLanguageCodeOption(["/l", "not-a-real-language"]); + + await Assert.That(result.Errors.Select(item => item.Message)) + .Contains(ResourceStrings.LanguageCodeError); + } + + #endregion + + #region ParseWorksetConfiguration + + [Test] + [Arguments("OpenAllWorksets")] + [Arguments("CloseAllWorksets")] + [Arguments("openlastviewed")] + public async Task ParseWorksetConfiguration_KnownValue_ParsesSuccessfully(string value) { + var result = ParseWorksetOption(["/w", value]); + + await Assert.That(result.Errors).IsEmpty(); + } + + [Test] + public async Task ParseWorksetConfiguration_UnknownValue_AddsError() { + var result = ParseWorksetOption(["/w", "not-a-real-workset"]); + + await Assert.That(result.Errors.Select(item => item.Message)) + .Contains(ResourceStrings.WorksetsError); + } + + #endregion + + #region helpers + + private static ParseResult ParseModelPathOption(string[] args) { + Option modelPathOption = new("/input", "/i") { + Required = true, + CustomParser = CommandLineOptionParsers.ParseModelPath, + }; + + return new RootCommand { modelPathOption }.Parse(args); + } + + private static string? GetModelPathValue(ParseResult result) { + var option = result.CommandResult.Command.Options + .OfType>() + .First(item => item.Name == "/input"); + return result.GetValue(option); + } + + private static ParseResult ParseBundlePathOption(string[] args) { + Option bundlePathOption = new("/app-bundle", "/al") { + Required = true, + CustomParser = CommandLineOptionParsers.ParseBundlePath, + }; + + return new RootCommand { bundlePathOption }.Parse(args); + } + + private static ParseResult ParseLanguageCodeOption(string[] args) { + Option languageCodeOption = new("/lang", "/l") { + CustomParser = CommandLineOptionParsers.ParseLanguageCode, + }; + + return new RootCommand { languageCodeOption }.Parse(args); + } + + private static ParseResult ParseWorksetOption(string[] args) { + Option worksetsOption = new("/worksets", "/w") { + CustomParser = CommandLineOptionParsers.ParseWorksetConfiguration, + }; + + return new RootCommand { worksetsOption }.Parse(args); + } + + private static string CreateTempFile(string fileName) { + string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + "_" + fileName); + File.WriteAllBytes(path, []); + return path; + } + + private static string CreateTempDirectory() { + string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + return path; + } + + #endregion +} diff --git a/tests/RevitEngine.UnitTests/RevitCoreConsole/CommandLine/LanguageCodeTests.cs b/tests/RevitEngine.UnitTests/RevitCoreConsole/CommandLine/LanguageCodeTests.cs new file mode 100644 index 0000000..3be87d3 --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitCoreConsole/CommandLine/LanguageCodeTests.cs @@ -0,0 +1,119 @@ +using System.Globalization; + +using RevitCoreConsole.CommandLine; + +namespace RevitEngine.UnitTests.RevitCoreConsole.CommandLine; + +public class LanguageCodeTests { + [Test] + [Arguments("RUS", "RUS")] + [Arguments("rus", "RUS")] + [Arguments("Russian", "RUS")] + [Arguments("RUSSIAN", "RUS")] + [Arguments("ENU", "ENU")] + [Arguments("enu", "ENU")] + [Arguments("English_USA", "ENU")] + public async Task GetLanguageCode_ByCodeOrFullCode_ReturnsExpectedCode(string input, string expectedCode) { + var result = LanguageCode.GetLanguageCode(input); + + await Assert.That(result.Code).IsEqualTo(expectedCode); + } + + [Test] + [Arguments("RU")] + [Arguments("ru")] + public async Task GetLanguageCode_RuAlias_ReturnsRussian(string input) { + var result = LanguageCode.GetLanguageCode(input); + + await Assert.That(result.Code).IsEqualTo("RUS"); + } + + [Test] + [Arguments(null)] + [Arguments("")] + public async Task GetLanguageCode_NullOrEmpty_ReturnsUnknown(string? input) { + var result = LanguageCode.GetLanguageCode(input!); + + await Assert.That(result).IsEqualTo(LanguageCode.Unknown); + } + + [Test] + public async Task GetLanguageCode_UnknownValue_ReturnsUnknown() { + var result = LanguageCode.GetLanguageCode("not-a-real-code"); + + await Assert.That(result).IsEqualTo(LanguageCode.Unknown); + } + + [Test] + public async Task GetLanguageCode_ByCultureInfo_ReturnsMatchingCode() { + var result = LanguageCode.GetLanguageCode(CultureInfo.GetCultureInfo("ru-RU")); + + await Assert.That(result.Code).IsEqualTo("RUS"); + } + + [Test] + public async Task GetLanguageCode_ByCultureInfo_NullCulture_Throws() { + await Assert.That(() => LanguageCode.GetLanguageCode((CultureInfo)null!)) + .Throws(); + } + + [Test] + public async Task GetLanguageCode_ByCultureInfo_UnsupportedCulture_Throws() { + var unsupported = CultureInfo.GetCultureInfo("sv-SE"); + + await Assert.That(() => LanguageCode.GetLanguageCode(unsupported)) + .Throws(); + } + + [Test] + public async Task GetLanguageCodes_ReturnsFifteenSupportedCodesPlusUnknown() { + var codes = LanguageCode.GetLanguageCodes().ToList(); + + // 15 supported Revit language codes + the Unknown sentinel value, + // since GetLanguageCodes() reflects over all public static fields. + await Assert.That(codes.Count).IsEqualTo(16); + await Assert.That(codes.Select(item => item.Code).Distinct().Count()).IsEqualTo(16); + } + + [Test] + public async Task GetLanguageCodes_ContainsUnknown() { + var codes = LanguageCode.GetLanguageCodes(); + + await Assert.That(codes).Contains(LanguageCode.Unknown); + } + + [Test] + public async Task Equals_SameCodeAndFullCode_AreEqual() { + var first = LanguageCode.GetLanguageCode("RUS"); + var second = LanguageCode.GetLanguageCode("Russian"); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first == second).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + + [Test] + public async Task Equals_DifferentCodes_AreNotEqual() { + var first = LanguageCode.GetLanguageCode("RUS"); + var second = LanguageCode.GetLanguageCode("ENU"); + + await Assert.That(first.Equals(second)).IsFalse(); + await Assert.That(first != second).IsTrue(); + } + + [Test] + public async Task Equals_Null_ReturnsFalse() { + var code = LanguageCode.GetLanguageCode("RUS"); + + await Assert.That(code.Equals(null)).IsFalse(); + await Assert.That(code == null).IsFalse(); + await Assert.That(code != null).IsTrue(); + } + + [Test] + public async Task ToString_ReturnsDisplayName() { + var code = LanguageCode.GetLanguageCode("RUS"); + + await Assert.That(code.ToString()).IsEqualTo(code.DisplayName); + } +} diff --git a/tests/RevitEngine.UnitTests/RevitCoreConsole/CommandLine/WorksetConfigurationTests.cs b/tests/RevitEngine.UnitTests/RevitCoreConsole/CommandLine/WorksetConfigurationTests.cs new file mode 100644 index 0000000..2d20ef8 --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitCoreConsole/CommandLine/WorksetConfigurationTests.cs @@ -0,0 +1,76 @@ +using RevitCoreConsole.CommandLine; + +namespace RevitEngine.UnitTests.RevitCoreConsole.CommandLine; + +public class WorksetConfigurationTests { + [Test] + [Arguments(null)] + [Arguments("")] + [Arguments(" ")] + public async Task Parse_NullOrWhitespace_ReturnsOpenAllWorksets(string? input) { + var result = WorksetConfiguration.Parse(input); + + await Assert.That(result).IsEqualTo(WorksetConfiguration.OpenAllWorksets); + } + + [Test] + [Arguments("OpenAllWorksets", "OpenAllWorksets")] + [Arguments("openallworksets", "OpenAllWorksets")] + [Arguments("CloseAllWorksets", "CloseAllWorksets")] + [Arguments("closeallworksets", "CloseAllWorksets")] + [Arguments("OpenLastViewed", "OpenLastViewed")] + [Arguments("openlastviewed", "OpenLastViewed")] + public async Task Parse_KnownValue_ReturnsMatchingConfiguration(string input, string expectedName) { + var result = WorksetConfiguration.Parse(input); + + await Assert.That(result.Name).IsEqualTo(expectedName); + } + + [Test] + public async Task Parse_UnknownValue_ReturnsUnknown() { + var result = WorksetConfiguration.Parse("not-a-real-workset-configuration"); + + await Assert.That(result).IsEqualTo(WorksetConfiguration.Unknown); + } + + [Test] + public async Task GetConfigurations_ReturnsThreeSupportedConfigurations() { + var configurations = WorksetConfiguration.GetConfigurations().ToList(); + + await Assert.That(configurations.Count).IsEqualTo(3); + await Assert.That(configurations).Contains(WorksetConfiguration.OpenAllWorksets); + await Assert.That(configurations).Contains(WorksetConfiguration.CloseAllWorksets); + await Assert.That(configurations).Contains(WorksetConfiguration.OpenLastViewed); + } + + [Test] + public async Task GetConfigurations_DoesNotContainUnknown() { + var configurations = WorksetConfiguration.GetConfigurations(); + + await Assert.That(configurations).DoesNotContain(WorksetConfiguration.Unknown); + } + + [Test] + public async Task Equals_SameName_AreEqual() { + var first = WorksetConfiguration.Parse("OpenAllWorksets"); + var second = WorksetConfiguration.Parse("openallworksets"); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + + [Test] + public async Task Equals_DifferentName_AreNotEqual() { + var first = WorksetConfiguration.Parse("OpenAllWorksets"); + var second = WorksetConfiguration.Parse("CloseAllWorksets"); + + await Assert.That(first.Equals(second)).IsFalse(); + } + + [Test] + public async Task Equals_Null_ReturnsFalse() { + var configuration = WorksetConfiguration.OpenAllWorksets; + + await Assert.That(configuration.Equals(null)).IsFalse(); + } +} diff --git a/tests/RevitEngine.UnitTests/RevitEngine.UnitTests.csproj b/tests/RevitEngine.UnitTests/RevitEngine.UnitTests.csproj new file mode 100644 index 0000000..fa9a3cc --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitEngine.UnitTests.csproj @@ -0,0 +1,20 @@ + + + + Exe + false + D2018;D2019;D2020;D2021;D2022;D2023;D2024;D2025;Debug;Release;D2026;D2026.5;D2027 + x64 + + + + + + + + + + + + + diff --git a/tests/RevitEngine.UnitTests/RevitEngine/AssemblyResolution/RevitAssemblyResolverTests.cs b/tests/RevitEngine.UnitTests/RevitEngine/AssemblyResolution/RevitAssemblyResolverTests.cs new file mode 100644 index 0000000..e83406d --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitEngine/AssemblyResolution/RevitAssemblyResolverTests.cs @@ -0,0 +1,140 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; + +using RevitEngine.AssemblyResolution; +using RevitEngine.Configuration; + +namespace RevitEngine.UnitTests.RevitEngine.AssemblyResolution; + +// These tests mutate the process-wide PATH environment variable, so they must not run +// in parallel with each other (or with anything else that reads/writes PATH). +[NotInParallel] +public class RevitAssemblyResolverTests { + [Test] + public async Task Install_EmptyApplicationPath_ThrowsInvalidOperationException() { + var resolver = CreateResolver(applicationPath: ""); + + await Assert.That(() => resolver.Install()).Throws(); + } + + [Test] + public async Task Install_MissingApplicationDirectory_ThrowsDirectoryNotFoundException() { + string missingDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + var resolver = CreateResolver(missingDirectory); + + await Assert.That(() => resolver.Install()).Throws(); + } + + [Test] + public async Task Install_DirectoryWithoutRevitAssemblies_ThrowsInvalidOperationException() { + string directory = CreateTempDirectory(); + try { + var resolver = CreateResolver(directory); + + await Assert.That(() => resolver.Install()).Throws(); + } finally { + Directory.Delete(directory, recursive: true); + } + } + + [Test] + public async Task Install_ValidRevitDirectory_AddsApplicationPathToPath() { + string directory = CreateFakeRevitInstallation(); + using var cleanup = new ResolverTestCleanup(directory); + + var resolver = CreateResolver(directory); + + resolver.Install(); + + string? updatedPath = Environment.GetEnvironmentVariable("PATH"); + await Assert.That(updatedPath).IsNotNull(); + await Assert.That(updatedPath!.Split(Path.PathSeparator)).Contains(directory); + + resolver.Uninstall(); + } + + [Test] + public async Task Install_CalledTwice_DoesNotDuplicatePathEntry() { + string directory = CreateFakeRevitInstallation(); + using var cleanup = new ResolverTestCleanup(directory); + + var resolver = CreateResolver(directory); + + resolver.Install(); + resolver.Install(); + + string[] pathEntries = Environment.GetEnvironmentVariable("PATH")!.Split(Path.PathSeparator); + await Assert.That(pathEntries.Count(entry => + entry.Equals(directory, StringComparison.OrdinalIgnoreCase))) + .IsEqualTo(1); + + resolver.Uninstall(); + } + + [Test] + public async Task Uninstall_WithoutInstall_DoesNotThrow() { + var resolver = CreateResolver(applicationPath: "C:\\does-not-matter"); + + await Assert.That(() => resolver.Uninstall()).ThrowsNothing(); + } + + [Test] + public async Task Dispose_CallsUninstall_DoesNotThrow() { + string directory = CreateFakeRevitInstallation(); + using var cleanup = new ResolverTestCleanup(directory); + + var resolver = CreateResolver(directory); + resolver.Install(); + + await Assert.That(() => resolver.Dispose()).ThrowsNothing(); + } + + private sealed class ResolverTestCleanup : IDisposable { + private readonly string _directory; + private readonly string _originalDirectory; + private readonly string? _originalPath; + + public ResolverTestCleanup(string directory) { + _directory = directory; + _originalDirectory = Directory.GetCurrentDirectory(); + _originalPath = Environment.GetEnvironmentVariable("PATH"); + } + + public void Dispose() { + Directory.SetCurrentDirectory(_originalDirectory); + Environment.SetEnvironmentVariable("PATH", _originalPath); + if(Directory.Exists(_directory)) { + Directory.Delete(_directory, recursive: true); + } + } + } + + private static RevitAssemblyResolver CreateResolver(string applicationPath) { + var options = new RevitApplicationOptions { + ApplicationGuid = Guid.NewGuid(), + ApplicationName = "Test", + ApplicationPath = applicationPath, + LicenseKey = "test-license", + VendorId = "test-vendor", + VendorDescription = "Test Vendor", + Startup = new RevitStartupOptions(), + }; + + return new RevitAssemblyResolver( + NullLogger.Instance, + Microsoft.Extensions.Options.Options.Create(options)); + } + + private static string CreateTempDirectory() { + string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(path); + return path; + } + + private static string CreateFakeRevitInstallation() { + string directory = CreateTempDirectory(); + File.WriteAllBytes(Path.Combine(directory, "RevitAPI.dll"), []); + File.WriteAllBytes(Path.Combine(directory, "RevitNET.dll"), []); + return directory; + } +} diff --git a/tests/RevitEngine.UnitTests/RevitEngine/Configuration/BundleOptionsTests.cs b/tests/RevitEngine.UnitTests/RevitEngine/Configuration/BundleOptionsTests.cs new file mode 100644 index 0000000..5240c78 --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitEngine/Configuration/BundleOptionsTests.cs @@ -0,0 +1,12 @@ +using RevitEngine.Configuration; + +namespace RevitEngine.UnitTests.RevitEngine.Configuration; + +public class BundleOptionsTests { + [Test] + public async Task BundlePath_RoundTripsThroughInitializer() { + var options = new BundleOptions { BundlePath = "C:\\bundles\\my-bundle.zip" }; + + await Assert.That(options.BundlePath).IsEqualTo("C:\\bundles\\my-bundle.zip"); + } +} diff --git a/tests/RevitEngine.UnitTests/RevitEngine/Configuration/RevitApiOptionsTests.cs b/tests/RevitEngine.UnitTests/RevitEngine/Configuration/RevitApiOptionsTests.cs new file mode 100644 index 0000000..c2d160f --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitEngine/Configuration/RevitApiOptionsTests.cs @@ -0,0 +1,42 @@ +using RevitEngine.Configuration; + +namespace RevitEngine.UnitTests.RevitEngine.Configuration; + +public class RevitApiOptionsTests { + [Test] + public async Task Defaults_AreAllTrue() { + var options = new RevitApiOptions(); + + await Assert.That(options.OverwriteExistingFiles).IsTrue(); + await Assert.That(options.ReplaceExistingSymbols).IsTrue(); + await Assert.That(options.IgnoreLinkedFilesOnSave).IsTrue(); + await Assert.That(options.ForceMultiUndoOperation).IsTrue(); + await Assert.That(options.UpdateSharedFamilies).IsTrue(); + await Assert.That(options.UpdateFamilyParameters).IsTrue(); + await Assert.That(options.IgnoreMissingUpdaters).IsTrue(); + await Assert.That(options.AcceptForeignFiles).IsTrue(); + } + + [Test] + public async Task Init_CanOverrideEachOption() { + var options = new RevitApiOptions { + OverwriteExistingFiles = false, + ReplaceExistingSymbols = false, + IgnoreLinkedFilesOnSave = false, + ForceMultiUndoOperation = false, + UpdateSharedFamilies = false, + UpdateFamilyParameters = false, + IgnoreMissingUpdaters = false, + AcceptForeignFiles = false, + }; + + await Assert.That(options.OverwriteExistingFiles).IsFalse(); + await Assert.That(options.ReplaceExistingSymbols).IsFalse(); + await Assert.That(options.IgnoreLinkedFilesOnSave).IsFalse(); + await Assert.That(options.ForceMultiUndoOperation).IsFalse(); + await Assert.That(options.UpdateSharedFamilies).IsFalse(); + await Assert.That(options.UpdateFamilyParameters).IsFalse(); + await Assert.That(options.IgnoreMissingUpdaters).IsFalse(); + await Assert.That(options.AcceptForeignFiles).IsFalse(); + } +} diff --git a/tests/RevitEngine.UnitTests/RevitEngine/Configuration/RevitApplicationOptionsTests.cs b/tests/RevitEngine.UnitTests/RevitEngine/Configuration/RevitApplicationOptionsTests.cs new file mode 100644 index 0000000..a433bda --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitEngine/Configuration/RevitApplicationOptionsTests.cs @@ -0,0 +1,29 @@ +using RevitEngine.Configuration; + +namespace RevitEngine.UnitTests.RevitEngine.Configuration; + +public class RevitApplicationOptionsTests { + [Test] + public async Task Properties_RoundTripThroughInitializer() { + var applicationGuid = Guid.NewGuid(); + var startup = new RevitStartupOptions(); + + var options = new RevitApplicationOptions { + ApplicationGuid = applicationGuid, + ApplicationName = "MyApp", + ApplicationPath = "C:\\Program Files\\Autodesk\\Revit 2025", + LicenseKey = "license-key", + VendorId = "vendor-id", + VendorDescription = "Vendor Description", + Startup = startup, + }; + + await Assert.That(options.ApplicationGuid).IsEqualTo(applicationGuid); + await Assert.That(options.ApplicationName).IsEqualTo("MyApp"); + await Assert.That(options.ApplicationPath).IsEqualTo("C:\\Program Files\\Autodesk\\Revit 2025"); + await Assert.That(options.LicenseKey).IsEqualTo("license-key"); + await Assert.That(options.VendorId).IsEqualTo("vendor-id"); + await Assert.That(options.VendorDescription).IsEqualTo("Vendor Description"); + await Assert.That(options.Startup).IsSameReferenceAs(startup); + } +} diff --git a/tests/RevitEngine.UnitTests/RevitEngine/Configuration/RevitStartupOptionsTests.cs b/tests/RevitEngine.UnitTests/RevitEngine/Configuration/RevitStartupOptionsTests.cs new file mode 100644 index 0000000..2e32b66 --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitEngine/Configuration/RevitStartupOptionsTests.cs @@ -0,0 +1,36 @@ +using RevitEngine.Configuration; +using RevitEngine.Runtime; + +namespace RevitEngine.UnitTests.RevitEngine.Configuration; + +public class RevitStartupOptionsTests { + [Test] + public async Task GetDefaultJournalPath_ExpandsEnvironmentVariables_AndContainsRevitVersion() { + string path = RevitStartupOptions.GetDefaultJournalPath(); + + await Assert.That(path).DoesNotContain("%"); + await Assert.That(path).Contains(RevitApplicationHost.RevitVersion); + await Assert.That(path).Contains("Journals"); + } + + [Test] + public async Task GetDefaultSettingsFileLocation_ExpandsEnvironmentVariables_AndContainsRevitVersion() { + string path = RevitStartupOptions.GetDefaultSettingsFileLocation(); + + await Assert.That(path).DoesNotContain("%"); + await Assert.That(path).Contains(RevitApplicationHost.RevitVersion); + } + + [Test] + public async Task Defaults_MatchDocumentedContract() { + var options = new RevitStartupOptions(); + + await Assert.That(options.JournalName).IsNull(); + await Assert.That(options.EnableIFC).IsFalse(); + await Assert.That(options.ApplyApiSettings).IsFalse(); + await Assert.That(options.LanguageType).IsEqualTo("English_USA"); + await Assert.That(options.Api).IsNotNull(); + await Assert.That(options.JournalPath).IsEqualTo(RevitStartupOptions.GetDefaultJournalPath()); + await Assert.That(options.SettingsFileLocation).IsEqualTo(RevitStartupOptions.GetDefaultSettingsFileLocation()); + } +} diff --git a/tests/RevitEngine.UnitTests/RevitEngine/Documents/OpenDocumentOptionsTests.cs b/tests/RevitEngine.UnitTests/RevitEngine/Documents/OpenDocumentOptionsTests.cs new file mode 100644 index 0000000..e13d62f --- /dev/null +++ b/tests/RevitEngine.UnitTests/RevitEngine/Documents/OpenDocumentOptionsTests.cs @@ -0,0 +1,27 @@ +using RevitEngine.Documents; + +namespace RevitEngine.UnitTests.RevitEngine.Documents; + +public class OpenDocumentOptionsTests { + [Test] + public async Task Defaults_MatchDocumentedContract() { + var options = new OpenDocumentOptions(); + + await Assert.That(options.Audit).IsFalse(); + await Assert.That(options.ModelPath).IsNull(); + await Assert.That(options.WorksetConfiguration).IsEqualTo("OpenAllWorksets"); + } + + [Test] + public async Task Properties_CanBeSet() { + var options = new OpenDocumentOptions { + Audit = true, + ModelPath = "C:\\model.rvt", + WorksetConfiguration = "CloseAllWorksets", + }; + + await Assert.That(options.Audit).IsTrue(); + await Assert.That(options.ModelPath).IsEqualTo("C:\\model.rvt"); + await Assert.That(options.WorksetConfiguration).IsEqualTo("CloseAllWorksets"); + } +}