diff --git a/.editorconfig b/.editorconfig index 8beb94ddb..00fa03f39 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,7 +1,3 @@ -# Rules in this file were initially inferred by Visual Studio IntelliCode from the UA-.NETStandard -# codebase based on best match to current usage at 12/15/2019 -# You can modify the rules from these initially generated values to suit your own policies -# You can learn more about editorconfig here: https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference ############################### # Core EditorConfig Options # @@ -12,19 +8,20 @@ root = true # All files [*] indent_style = space +tab_width = 4 # Code files [*.{cs,csx,vb,vbx}] -indent_size = 4 -charset = utf-8 -trim_trailing_whitespace = true -end_of_line = crlf -insert_final_newline = true -max_line_length = 120 +indent_size = 4 +charset = utf-8 +trim_trailing_whitespace = true +end_of_line = crlf +insert_final_newline = true +max_line_length = 120 # Xml project files [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] -indent_size = 2 +indent_size = 4 # Xml config files [*.{xml,props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] @@ -46,16 +43,16 @@ indent_size = 2 [*.cs] # Null-checking preferences -csharp_style_throw_expression = true : suggestion -csharp_style_conditional_delegate_call = true : suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion # Modifier preferences # require braces to be on a new line for control_blocks, types, and methods (also known as "Allman" style) -csharp_new_line_before_open_brace = control_blocks, types, methods, properties, accessors, object_collection -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async : suggestion +csharp_new_line_before_open_brace = all +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion csharp_new_line_before_catch = true -csharp_new_line_before_else = true : suggestion -csharp_new_line_before_finally = true : suggestion +csharp_new_line_before_else = true:suggestion +csharp_new_line_before_finally = true:suggestion csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_before_members_in_object_initializers = true csharp_new_line_between_query_expression_clauses = true @@ -86,8 +83,9 @@ csharp_space_between_square_brackets = dotnet_sort_system_directives_first = true dotnet_separate_import_directive_groups = false -csharp_style_prefer_method_group_conversion = true : silent -csharp_style_prefer_top_level_statements = true : silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_top_level_statements = true:silent +csharp_using_directive_placement = outside_namespace:suggestion #Formatting - spacing options @@ -100,85 +98,127 @@ csharp_space_between_method_call_name_and_opening_parenthesis = csharp_space_between_method_call_parameter_list_parentheses = false csharp_space_between_method_declaration_empty_parameter_list_parentheses = false csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_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 #Formatting - wrapping options csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true +csharp_preserve_single_line_statements = false +dotnet_style_allow_trailing_commas = false:suggestion #Pattern - matching preferences -csharp_style_pattern_local_over_anonymous_function = true : suggestion -csharp_style_pattern_matching_over_is_with_cast_check = true : suggestion -csharp_style_pattern_matching_over_as_with_null_check = true : suggestion +csharp_style_pattern_local_over_anonymous_function = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion #Style - expression bodied member options -csharp_style_expression_bodied_operators = false : silent -csharp_style_expression_bodied_indexers = true : silent -csharp_style_expression_bodied_accessors = true : suggestion -csharp_style_expression_bodied_constructors = false : suggestion -csharp_style_expression_bodied_methods = false : suggestion -csharp_style_expression_bodied_properties = true : silent -csharp_style_expression_bodied_lambdas = true : silent -csharp_style_expression_bodied_local_functions = false : silent - +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:suggestion +csharp_style_expression_bodied_constructors = false:suggestion +csharp_style_expression_bodied_methods = false:suggestion +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = when_on_single_line:suggestion #Style - expression level options -csharp_prefer_braces = true : silent -csharp_style_deconstructed_variable_declaration = true : suggestion -csharp_prefer_simple_default_expression = true : suggestion -csharp_style_inlined_variable_declaration = false : suggestion -csharp_prefer_simple_using_statement = false : suggestion +csharp_prefer_braces = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_inlined_variable_declaration = false:suggestion +csharp_prefer_simple_using_statement = false:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_prefer_static_local_function = true:suggestion +csharp_prefer_static_anonymous_function = true:suggestion #Style - implicit and explicit types -csharp_style_var_for_built_in_types = false : suggestion -csharp_style_var_when_type_is_apparent = true : suggestion -csharp_style_var_elsewhere = false : suggestion - -#Style - language keyword and framework type options - +csharp_style_var_for_built_in_types = false:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = false:suggestion + +# Style - misc +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_prefer_implicitly_typed_lambda_expression = true:suggestion +csharp_style_prefer_unbound_generic_type_in_nameof = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_prefer_readonly_struct = true:suggestion +csharp_style_prefer_readonly_struct_member = true:suggestion + +# Style - pattern matching +csharp_style_prefer_switch_expression = false:suggestion +csharp_style_prefer_pattern_matching = true:silent +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion + +# Never +dotnet_style_namespace_match_folder = false:none + +# Enable eventually +dotnet_code_quality_unused_parameters = all:silent + +# Style - language keyword and framework type options #prefer the language keyword for local variables, method parameters, and class members, #instead of the type name, for types that have a keyword to represent them -dotnet_style_predefined_type_for_locals_parameters_members = true : suggestion -dotnet_style_predefined_type_for_member_access = true : suggestion - -#Style - qualification options -dotnet_style_qualification_for_event = false : suggestion -dotnet_style_qualification_for_field = false : suggestion -dotnet_style_qualification_for_method = false : suggestion -dotnet_style_qualification_for_property = false : suggestion - -#Style - Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity : silent -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity : silent -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity : silent -dotnet_style_parentheses_in_other_operators = never_if_unnecessary : silent - -#Style - Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members : silent -dotnet_style_readonly_field = true : suggestion - -#Style - Expression-level preferences -dotnet_style_object_initializer = true : suggestion -dotnet_style_collection_initializer = true : suggestion -dotnet_style_explicit_tuple_names = true : suggestion -dotnet_style_null_propagation = true : suggestion -dotnet_style_coalesce_expression = true : suggestion -dotnet_style_prefer_is_null_check_over_reference_equality_method = true : silent -dotnet_style_prefer_inferred_tuple_names = true : suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true : suggestion -dotnet_style_prefer_auto_properties = true : silent -dotnet_style_prefer_conditional_expression_over_assignment = true : suggestion -dotnet_style_prefer_conditional_expression_over_return = true : suggestion +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +dotnet_style_allow_multiple_blank_lines_experimental = false:suggestion +dotnet_style_allow_statement_immediately_after_block_experimental = true:suggestion + +# Style - qualification options +dotnet_style_qualification_for_event = false:suggestion +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_property = false:suggestion + +# Style - Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:suggestion +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:suggestion +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:suggestion +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_operator_placement_when_wrapping = beginning_of_line + +# Style - Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion +dotnet_style_readonly_field = true:suggestion + +# Style - Expression-level preferences +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = false:silent +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion + +csharp_style_unused_value_expression_statement_preference = unused_local_variable:suggestion # 'using' directive preferences -csharp_using_directive_placement = outside_namespace : suggestion -csharp_style_namespace_declarations = block_scoped : suggestion +csharp_using_directive_placement = outside_namespace:suggestion +csharp_style_namespace_declarations = block_scoped:suggestion # Naming rules # Async methods should have "Async" suffix -dotnet_naming_rule.async_methods_end_in_async.severity = suggestion +dotnet_naming_rule.async_methods_end_in_async.severity = warning dotnet_naming_rule.async_methods_end_in_async.symbols = any_async_methods -dotnet_naming_rule.async_methods_end_in_async.style = end_in_async +dotnet_naming_rule.async_methods_end_in_async.style = end_in_async dotnet_naming_symbols.any_async_methods.applicable_kinds = method, interface dotnet_naming_symbols.any_async_methods.applicable_accessibilities = * @@ -188,9 +228,9 @@ dotnet_naming_style.end_in_async.required_suffix = dotnet_naming_style.end_in_async.capitalization = pascal_case # Private Constants are PascalCase and start with k -dotnet_naming_rule.constants_private_should_start_with_k.severity = suggestion +dotnet_naming_rule.constants_private_should_start_with_k.severity = suggestion dotnet_naming_rule.constants_private_should_start_with_k.symbols = constants_with_k -dotnet_naming_rule.constants_private_should_start_with_k.style = constants_with_k_style +dotnet_naming_rule.constants_private_should_start_with_k.style = constants_with_k_style dotnet_naming_symbols.constants_with_k.applicable_kinds = field, local dotnet_naming_symbols.constants_with_k.applicable_accessibilities = private, protected, private_protected, protected_friend @@ -200,9 +240,9 @@ dotnet_naming_style.constants_with_k_style.capitalization = dotnet_naming_style.constants_with_k_style.required_prefix = k # Constants are PascalCase -dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants -dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style +dotnet_naming_rule.constants_should_be_pascal_case.style = non_private_static_field_style dotnet_naming_symbols.constants.applicable_kinds = field, local dotnet_naming_symbols.constants.applicable_accessibilities = public, internal, protected_internal @@ -213,7 +253,7 @@ dotnet_naming_style.constant_style.capitalization = # Non-private readonly fields are PascalCase dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.severity = suggestion dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.symbols = non_private_readonly_fields -dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.style = non_private_readonly_field_style +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.style = non_private_static_field_style dotnet_naming_symbols.non_private_readonly_fields.applicable_kinds = field dotnet_naming_symbols.non_private_readonly_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected @@ -222,9 +262,9 @@ dotnet_naming_symbols.non_private_readonly_fields.required_modifiers = dotnet_naming_style.non_private_readonly_field_style.capitalization = pascal_case # Non-private static fields are PascalCase -dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields -dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected @@ -233,9 +273,9 @@ dotnet_naming_symbols.non_private_static_fields.required_modifiers = dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case # Private static fields are camelCase and start with s_ -dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields -dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style +dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style dotnet_naming_symbols.static_fields.applicable_kinds = field dotnet_naming_symbols.static_fields.applicable_accessibilities = private, protected, private_protected, protected_friend @@ -245,9 +285,9 @@ dotnet_naming_style.static_field_style.capitalization = dotnet_naming_style.static_field_style.required_prefix = s_ # Private instance fields are camelCase and start with m_ -dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields -dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style +dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style dotnet_naming_symbols.instance_fields.applicable_kinds = field dotnet_naming_symbols.instance_fields.applicable_accessibilities = private, protected, private_protected, protected_friend @@ -256,9 +296,9 @@ dotnet_naming_style.instance_field_style.capitalization = dotnet_naming_style.instance_field_style.required_prefix = m_ # Private event fields are PascalCase and start with m_ -dotnet_naming_rule.instance_events_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.instance_events_should_be_pascal_case.severity = suggestion dotnet_naming_rule.instance_events_should_be_pascal_case.symbols = instance_events -dotnet_naming_rule.instance_events_should_be_pascal_case.style = instance_events_style +dotnet_naming_rule.instance_events_should_be_pascal_case.style = instance_events_style dotnet_naming_symbols.instance_events.applicable_kinds = event dotnet_naming_symbols.instance_events.applicable_accessibilities = private, protected, private_protected, protected_friend @@ -267,30 +307,29 @@ dotnet_naming_style.instance_events_style.capitalization = dotnet_naming_style.instance_events_style.required_prefix = m_ # Locals and parameters are camelCase -dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion +dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion 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_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 # Local functions are PascalCase -dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions -dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style +dotnet_naming_rule.local_functions_should_be_pascal_case.style = non_private_static_field_style dotnet_naming_symbols.local_functions.applicable_kinds = local_function dotnet_naming_style.local_function_style.capitalization = pascal_case # By default, name items with PascalCase -dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion 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_rule.members_should_be_pascal_case.style = non_private_static_field_style dotnet_naming_symbols.all_members.applicable_kinds = * - dotnet_naming_style.pascal_case_style.capitalization = pascal_case # Diagnostic settings (windows only) @@ -312,15 +351,241 @@ dotnet_diagnostic.CA1822.severity = dotnet_code_quality.CA1822.api_surface = private, internal # CA3075: Insecure DTD processing in XML -dotnet_diagnostic.CA3075.severity = error -dotnet_diagnostic.CA3077.severity = error +dotnet_diagnostic.CA3075.severity = warning +dotnet_diagnostic.CA3077.severity = warning # CA2007: Do not directly await a Task -dotnet_diagnostic.CA2007.severity = warning +dotnet_diagnostic.CA2007.severity = silent + +# CA2016: Forward the CancellationToken parameter to methods that take one +dotnet_diagnostic.CA2016.severity = warning # IDE0049: Simplify Names -dotnet_diagnostic.IDE0049.severity = silent +dotnet_diagnostic.IDE0049.severity = suggestion # CA1507: Use nameof in place of string dotnet_diagnostic.CA1507.severity = warning +# CA1711: Identifiers should not have incorrect suffix +dotnet_diagnostic.CA1711.severity = none + +# IDE1005: Simplify delegate invocation +dotnet_diagnostic.IDE1005.severity = warning + +# IDE0046: Convert to conditional expression +dotnet_diagnostic.IDE0046.severity = silent + +# IDE0130: Namespace does not match folder structure +dotnet_diagnostic.IDE0130.severity = none + +# CA1305: Specify IFormatProvider +dotnet_diagnostic.CA1305.severity = silent + +# CA1819: Properties should not return arrays +dotnet_diagnostic.CA1819.severity = silent + +# CA1721: The property name is confusing given the existence of another method with the same name. +dotnet_diagnostic.CA1721.severity = silent + +# CA2014: Do not use stackalloc in loops +dotnet_diagnostic.CA2014.severity = error + +# IDE0058: Expression value is never used +dotnet_diagnostic.IDE0058.severity = silent + +# IDE0290: Use primary constructor +csharp_style_prefer_primary_constructors = false:silent +# IDE0045: Convert to conditional expression +dotnet_diagnostic.IDE0045.severity = none +# IDE0065: Using directives must be placed inside a namespace declaration +dotnet_diagnostic.IDE0065.severity = none +csharp_prefer_system_threading_lock = true:suggestion + +# IDE0072: Add missing cases +dotnet_diagnostic.IDE0072.severity = none +dotnet_diagnostic.IDE0010.severity = none + +# CA1510: Use throw helpers - enable when we have a polyfill +dotnet_diagnostic.CA1510.severity = none +dotnet_diagnostic.CA1511.severity = none +dotnet_diagnostic.CA1512.severity = none +dotnet_diagnostic.CA1513.severity = none + +# Roslynator settings +dotnet_analyzer_diagnostic.category-roslynator.severity = suggestion +roslynator_refactorings.enabled = true +roslynator_compiler_diagnostic_fixes.enabled = true +roslynator_tab_length = 4 +roslynator_max_line_length = 160 + +roslynator_blank_line_between_using_directives = never +roslynator_blank_line_between_single_line_accessors = false +roslynator_block_braces_style = multi_line +roslynator_binary_operator_new_line = after +roslynator_null_conditional_operator_new_line = after +roslynator_trailing_comma_style = omit +roslynator_blank_line_between_switch_sections = omit +roslynator_object_creation_parentheses_style = omit +roslynator_conditional_operator_condition_parentheses_style = omit +roslynator_empty_string_style = field +roslynator_configure_await = true +roslynator_infinite_loop_style = while +roslynator_doc_comment_summary_style = multi_line +#roslynator_enum_flag_value_style = decimal_number +#roslynator_null_check_style = pattern_matching + +dotnet_diagnostic.RCS0003.severity = suggestion +dotnet_diagnostic.RCS0006.severity = suggestion +dotnet_diagnostic.RCS0009.severity = suggestion +dotnet_diagnostic.RCS0010.severity = suggestion +dotnet_diagnostic.RCS0011.severity = suggestion +dotnet_diagnostic.RCS0015.severity = suggestion +dotnet_diagnostic.RCS0021.severity = suggestion +dotnet_diagnostic.RCS0023.severity = suggestion +dotnet_diagnostic.RCS0025.severity = suggestion +dotnet_diagnostic.RCS0027.severity = suggestion +dotnet_diagnostic.RCS0029.severity = suggestion +dotnet_diagnostic.RCS0031.severity = suggestion +dotnet_diagnostic.RCS0033.severity = suggestion +dotnet_diagnostic.RCS0034.severity = suggestion +dotnet_diagnostic.RCS0041.severity = suggestion +dotnet_diagnostic.RCS0042.severity = suggestion +dotnet_diagnostic.RCS0046.severity = suggestion +dotnet_diagnostic.RCS0049.severity = suggestion +dotnet_diagnostic.RCS0050.severity = suggestion +dotnet_diagnostic.RCS0051.severity = suggestion +#dotnet_diagnostic.RCS0054.severity = suggestion # Call chain formatting +dotnet_diagnostic.RCS0055.severity = suggestion +dotnet_diagnostic.RCS0056.severity = suggestion +dotnet_diagnostic.RCS0059.severity = suggestion +dotnet_diagnostic.RCS0061.severity = suggestion +dotnet_diagnostic.RCS0063.severity = suggestion +dotnet_diagnostic.RCS1002.severity = none +dotnet_diagnostic.RCS1004.severity = none +dotnet_diagnostic.RCS1005.severity = suggestion +dotnet_diagnostic.RCS1006.severity = suggestion +dotnet_diagnostic.RCS1007.severity = suggestion +dotnet_diagnostic.RCS1013.severity = suggestion +dotnet_diagnostic.RCS1015.severity = suggestion +dotnet_diagnostic.RCS1019.severity = none +dotnet_diagnostic.RCS1020.severity = suggestion +dotnet_diagnostic.RCS1031.severity = suggestion +dotnet_diagnostic.RCS1032.severity = suggestion +dotnet_diagnostic.RCS1033.severity = suggestion +dotnet_diagnostic.RCS1034.severity = suggestion +dotnet_diagnostic.RCS1037.severity = suggestion +dotnet_diagnostic.RCS1039.severity = suggestion +dotnet_diagnostic.RCS1042.severity = suggestion +dotnet_diagnostic.RCS1043.severity = suggestion +dotnet_diagnostic.RCS1044.severity = suggestion +dotnet_diagnostic.RCS1046.severity = suggestion +dotnet_diagnostic.RCS1047.severity = suggestion +dotnet_diagnostic.RCS1049.severity = suggestion +dotnet_diagnostic.RCS1050.severity = suggestion +dotnet_diagnostic.RCS1051.severity = suggestion +dotnet_diagnostic.RCS1052.severity = suggestion +dotnet_diagnostic.RCS1055.severity = suggestion +dotnet_diagnostic.RCS1058.severity = suggestion +dotnet_diagnostic.RCS1061.severity = suggestion +dotnet_diagnostic.RCS1068.severity = suggestion +dotnet_diagnostic.RCS1069.severity = suggestion +dotnet_diagnostic.RCS1070.severity = suggestion +dotnet_diagnostic.RCS1071.severity = suggestion +dotnet_diagnostic.RCS1074.severity = suggestion +dotnet_diagnostic.RCS1077.severity = suggestion +dotnet_diagnostic.RCS1078.severity = suggestion +dotnet_diagnostic.RCS1080.severity = suggestion +dotnet_diagnostic.RCS1081.severity = suggestion +dotnet_diagnostic.RCS1084.severity = suggestion +dotnet_diagnostic.RCS1085.severity = suggestion +dotnet_diagnostic.RCS1089.severity = suggestion +dotnet_diagnostic.RCS1090.severity = silent +dotnet_diagnostic.RCS1091.severity = suggestion +dotnet_diagnostic.RCS1094.severity = suggestion +dotnet_diagnostic.RCS1097.severity = suggestion +dotnet_diagnostic.RCS1098.severity = suggestion +dotnet_diagnostic.RCS1099.severity = suggestion +dotnet_diagnostic.RCS1112.severity = suggestion +dotnet_diagnostic.RCS1124.severity = suggestion +dotnet_diagnostic.RCS1126.severity = suggestion +dotnet_diagnostic.RCS1129.severity = suggestion +dotnet_diagnostic.RCS1132.severity = suggestion +dotnet_diagnostic.RCS1133.severity = suggestion +dotnet_diagnostic.RCS1134.severity = suggestion +dotnet_diagnostic.RCS1136.severity = suggestion +dotnet_diagnostic.RCS1139.severity = suggestion +dotnet_diagnostic.RCS1140.severity = suggestion +dotnet_diagnostic.RCS1141.severity = silent +dotnet_diagnostic.RCS1142.severity = suggestion +dotnet_diagnostic.RCS1143.severity = suggestion +dotnet_diagnostic.RCS1145.severity = suggestion +dotnet_diagnostic.RCS1146.severity = none +dotnet_diagnostic.RCS1151.severity = suggestion +dotnet_diagnostic.RCS1154.severity = suggestion +dotnet_diagnostic.RCS1156.severity = suggestion +dotnet_diagnostic.RCS1160.severity = suggestion +dotnet_diagnostic.RCS1161.severity = none +dotnet_diagnostic.RCS1166.severity = suggestion +dotnet_diagnostic.RCS1169.severity = suggestion +dotnet_diagnostic.RCS1170.severity = suggestion +dotnet_diagnostic.RCS1174.severity = suggestion +dotnet_diagnostic.RCS1181.severity = suggestion +dotnet_diagnostic.RCS1182.severity = suggestion +dotnet_diagnostic.RCS1187.severity = suggestion +dotnet_diagnostic.RCS1188.severity = suggestion +dotnet_diagnostic.RCS1190.severity = suggestion +#dotnet_diagnostic.RCS1198.severity = suggestion # Avoid boxing +dotnet_diagnostic.RCS1201.severity = suggestion +dotnet_diagnostic.RCS1202.severity = suggestion +dotnet_diagnostic.RCS1207.severity = suggestion +dotnet_diagnostic.RCS1211.severity = suggestion +dotnet_diagnostic.RCS1214.severity = suggestion +dotnet_diagnostic.RCS1225.severity = suggestion +dotnet_diagnostic.RCS1227.severity = suggestion +dotnet_diagnostic.RCS1228.severity = none +dotnet_diagnostic.RCS1229.severity = suggestion +dotnet_diagnostic.RCS1237.severity = none +dotnet_diagnostic.RCS1238.severity = none +dotnet_diagnostic.RCS1240.severity = suggestion +dotnet_diagnostic.RCS1241.severity = none +dotnet_diagnostic.RCS1244.severity = suggestion +dotnet_diagnostic.RCS1246.severity = suggestion +dotnet_diagnostic.RCS1249.severity = suggestion +dotnet_diagnostic.RCS1252.severity = suggestion +dotnet_diagnostic.RCS1257.severity = suggestion +dotnet_diagnostic.RCS1258.severity = suggestion +dotnet_diagnostic.RCS1259.severity = suggestion +dotnet_diagnostic.RCS1260.severity = suggestion +dotnet_diagnostic.RCS1262.severity = suggestion +dotnet_diagnostic.RCS1266.severity = suggestion + +# RCS1208: Reduce 'if' nesting +dotnet_diagnostic.RCS1208.severity = suggestion +# RCS1261: Resource can be disposed asynchronously +dotnet_diagnostic.RCS1261.severity = suggestion +# RCS1168: Parameter name differs from base name +dotnet_diagnostic.RCS1168.severity = suggestion + +# RCS1163: Unused parameter +dotnet_diagnostic.RCS1163.severity = none +dotnet_diagnostic.IDE0060.severity = none + +# exclude generated code + +# CA1859: Use concrete types when possible for improved performance +dotnet_diagnostic.CA1859.severity = silent + +# CA1861: Avoid constant arrays as arguments +dotnet_diagnostic.CA1861.severity = silent + +[**/Generated/*.cs] +generated_code = true +dotnet_diagnostic.severity = none +dotnet_analyzer.severity = none +#dotnet_analyzer_diagnostic.category-roslynator.severity = none + +[**/*.{Classes,DataTypes,Constants,StatusCodes,Attributes}.cs] +generated_code = true +dotnet_diagnostic.severity = none +dotnet_analyzer.severity = none +#dotnet_analyzer_diagnostic.category-roslynator.severity = none diff --git a/Samples/Client.Net4/Program.cs b/Samples/Client.Net4/Program.cs index bdbaed8d7..4d1a68a74 100644 --- a/Samples/Client.Net4/Program.cs +++ b/Samples/Client.Net4/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -47,23 +47,23 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationName = "UA Sample Client"; - application.ApplicationType = ApplicationType.ClientAndServer; + application.ApplicationName = "UA Sample Client"; + application.ApplicationType = ApplicationType.ClientAndServer; application.ConfigSectionName = "Opc.Ua.SampleClient"; try { - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().GetAwaiter().GetResult(); // check the application certificate. - bool certOK = application.CheckApplicationInstanceCertificates(false).Result; + bool certOK = application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Result; if (!certOK) { throw new Exception("Application instance certificate invalid!"); } // start the server. - application.Start(new SampleServer()).Wait(); + application.StartAsync(new SampleServer()).Wait(); // run the application interactively. Application.Run(new SampleClientForm(application, null, application.ApplicationConfiguration)); diff --git a/Samples/Client.Net4/SampleClientForm.cs b/Samples/Client.Net4/SampleClientForm.cs index 7dd257aed..c52ff8439 100644 --- a/Samples/Client.Net4/SampleClientForm.cs +++ b/Samples/Client.Net4/SampleClientForm.cs @@ -43,8 +43,8 @@ public SampleClientForm() } public SampleClientForm( - ApplicationInstance application, - ClientForm masterForm, + ApplicationInstance application, + ClientForm masterForm, ApplicationConfiguration configuration) : base(configuration.CreateMessageContext(), application, masterForm, configuration) @@ -71,7 +71,7 @@ void CertificateValidator_CertificateValidation(CertificateValidator validator, } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Client.Net4/UA Sample Client.csproj b/Samples/Client.Net4/UA Sample Client.csproj index e3dac23e0..be95dafa7 100644 --- a/Samples/Client.Net4/UA Sample Client.csproj +++ b/Samples/Client.Net4/UA Sample Client.csproj @@ -37,6 +37,7 @@ false AnyCPU false + AllRules.ruleset pdbonly @@ -48,6 +49,7 @@ false AnyCPU false + AllRules.ruleset @@ -135,10 +137,10 @@ - 9.0.6 + 9.0.8 - 1.5.376.244 + 1.5.377.11-preview 4.3.4 diff --git a/Samples/ClientControls.Net4/Browse/AttributeListCtrl.cs b/Samples/ClientControls.Net4/Browse/AttributeListCtrl.cs index 00c26a478..d85043302 100644 --- a/Samples/ClientControls.Net4/Browse/AttributeListCtrl.cs +++ b/Samples/ClientControls.Net4/Browse/AttributeListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,7 +29,10 @@ using System; using System.Collections.Generic; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; @@ -46,32 +49,32 @@ public partial class AttributeListCtrl : Opc.Ua.Client.Controls.BaseListCtrl public AttributeListCtrl() { InitializeComponent(); - SetColumns(m_ColumnNames); + SetColumns(m_ColumnNames); } #region Private Fields - private Session m_session; - - // The columns to display in the control. - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "Value", HorizontalAlignment.Left, null } - }; - - private class ItemInfo + private ISession m_session; + + // The columns to display in the control. + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "Value", HorizontalAlignment.Left, null } + }; + + private sealed class ItemInfo { public NodeId NodeId; public uint AttributeId; public string Name; public DataValue Value; } - #endregion - + #endregion + /// /// Initializes the control with a set of items. /// - public void Initialize(Session session, ExpandedNodeId nodeId) + public async Task InitializeAsync(ISession session, ExpandedNodeId nodeId, CancellationToken ct = default) { ItemsLV.Items.Clear(); m_session = session; @@ -81,19 +84,15 @@ public void Initialize(Session session, ExpandedNodeId nodeId) return; } - ILocalNode node = m_session.NodeCache.Find(nodeId) as ILocalNode; + ILocalNode node = await m_session.NodeCache.FindAsync(nodeId, ct) as ILocalNode; if (node == null) { return; } - uint[] attributesIds = Attributes.GetIdentifiers(); - - for (int ii = 0; ii < attributesIds.Length; ii++) + foreach (uint attributesId in Attributes.Identifiers) { - uint attributesId = attributesIds[ii]; - if (!node.SupportsAttribute(attributesId)) { continue; @@ -105,7 +104,7 @@ public void Initialize(Session session, ExpandedNodeId nodeId) info.AttributeId = attributesId; info.Name = Attributes.GetBrowseName(attributesId); info.Value = new DataValue(StatusCodes.BadWaitingForInitialData); - + ServiceResult result = node.Read(null, attributesId, info.Value); if (ServiceResult.IsBad(result)) @@ -122,7 +121,7 @@ public void Initialize(Session session, ExpandedNodeId nodeId) { IReference reference = references[ii]; - ILocalNode property = m_session.NodeCache.Find(reference.TargetId) as ILocalNode; + ILocalNode property = await m_session.NodeCache.FindAsync(reference.TargetId, ct) as ILocalNode; if (property == null) { @@ -135,7 +134,7 @@ public void Initialize(Session session, ExpandedNodeId nodeId) info.AttributeId = Attributes.Value; info.Name = Utils.Format("{0}", property.DisplayName); info.Value = new DataValue(StatusCodes.BadWaitingForInitialData); - + ServiceResult result = property.Read(null, Attributes.Value, info.Value); if (ServiceResult.IsBad(result)) @@ -146,13 +145,13 @@ public void Initialize(Session session, ExpandedNodeId nodeId) AddItem(info); } - UpdateValues(); + await UpdateValuesAsync(ct); } /// /// Updates the values from the server. /// - private void UpdateValues() + private async Task UpdateValuesAsync(CancellationToken ct = default) { ReadValueIdCollection valuesToRead = new ReadValueIdCollection(); @@ -160,8 +159,8 @@ private void UpdateValues() { ItemInfo info = item.Tag as ItemInfo; - if (info == null) - { + if (info == null) + { continue; } @@ -174,16 +173,15 @@ private void UpdateValues() valuesToRead.Add(valueToRead); } - DataValueCollection results; - DiagnosticInfoCollection diagnosticInfos; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, valuesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, valuesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead); @@ -193,16 +191,16 @@ private void UpdateValues() ListViewItem item = (ListViewItem)valuesToRead[ii].Handle; ItemInfo info = (ItemInfo)item.Tag; info.Value = results[ii]; - UpdateItem(item, info); + await UpdateItemAsync(item, info, ct); } AdjustColumns(); } - + /// /// Formats the value of an attribute. /// - private string FormatAttributeValue(uint attributeId, object value) + private async Task FormatAttributeValueAsync(uint attributeId, object value, CancellationToken ct = default) { switch (attributeId) { @@ -215,14 +213,14 @@ private string FormatAttributeValue(uint attributeId, object value) return "(null)"; } - + case Attributes.DataType: { NodeId datatypeId = value as NodeId; if (datatypeId != null) { - INode datatype = m_session.NodeCache.Find(datatypeId); + INode datatype = await m_session.NodeCache.FindAsync(datatypeId, ct); if (datatype != null) { @@ -233,10 +231,10 @@ private string FormatAttributeValue(uint attributeId, object value) return String.Format("{0}", datatypeId); } } - + return String.Format("{0}", value); } - + case Attributes.ValueRank: { int? valueRank = value as int?; @@ -245,21 +243,21 @@ private string FormatAttributeValue(uint attributeId, object value) { switch (valueRank.Value) { - case ValueRanks.Scalar: return "Scalar"; - case ValueRanks.OneDimension: return "OneDimension"; + case ValueRanks.Scalar: return "Scalar"; + case ValueRanks.OneDimension: return "OneDimension"; case ValueRanks.OneOrMoreDimensions: return "OneOrMoreDimensions"; - case ValueRanks.Any: return "Any"; + case ValueRanks.Any: return "Any"; default: { return String.Format("{0}", valueRank.Value); } - } + } } return String.Format("{0}", value); } - + case Attributes.MinimumSamplingInterval: { double? minimumSamplingInterval = value as double?; @@ -276,7 +274,7 @@ private string FormatAttributeValue(uint attributeId, object value) return "Continuous"; } - return String.Format("{0}", minimumSamplingInterval.Value); + return String.Format("{0}", minimumSamplingInterval.Value); } return String.Format("{0}", value); @@ -293,37 +291,37 @@ private string FormatAttributeValue(uint attributeId, object value) { bits.Append("Readable"); } - + if ((accessLevel & AccessLevels.CurrentWrite) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("Writeable"); } - + if ((accessLevel & AccessLevels.HistoryRead) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("History Read"); } - + if ((accessLevel & AccessLevels.HistoryWrite) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("History Update"); } - + if (bits.Length == 0) { bits.Append("No Access"); @@ -331,7 +329,7 @@ private string FormatAttributeValue(uint attributeId, object value) return String.Format("{0}", bits); } - + case Attributes.EventNotifier: { byte notifier = Convert.ToByte(value); @@ -342,27 +340,27 @@ private string FormatAttributeValue(uint attributeId, object value) { bits.Append("Subscribe"); } - + if ((notifier & EventNotifiers.HistoryRead) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("History"); } - + if ((notifier & EventNotifiers.HistoryWrite) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("History Update"); } - + if (bits.Length == 0) { bits.Append("No Access"); @@ -380,38 +378,46 @@ private string FormatAttributeValue(uint attributeId, object value) #region Overridden Methods /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - ItemInfo info = item as ItemInfo; + try + { + ItemInfo info = item as ItemInfo; - if (info == null) - { - base.UpdateItem(listItem, item); - return; - } - - listItem.SubItems[0].Text = Utils.Format("{0}", info.Name); + if (info == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } - if (StatusCode.IsBad(info.Value.StatusCode)) - { - listItem.SubItems[1].Text = Utils.Format("{0}", info.Value.StatusCode); - } - else - { - listItem.SubItems[1].Text = FormatAttributeValue(info.AttributeId, info.Value.Value); - } + listItem.SubItems[0].Text = Utils.Format("{0}", info.Name); - if (info.AttributeId != Attributes.Value) - { - listItem.ImageKey = GuiUtils.Icons.Attribute; + if (StatusCode.IsBad(info.Value.StatusCode)) + { + listItem.SubItems[1].Text = Utils.Format("{0}", info.Value.StatusCode); + } + else + { + listItem.SubItems[1].Text = await FormatAttributeValueAsync(info.AttributeId, info.Value.Value, ct); + } + + if (info.AttributeId != Attributes.Value) + { + listItem.ImageKey = GuiUtils.Icons.Attribute; + } + else + { + listItem.ImageKey = GuiUtils.Icons.Property; + } + + listItem.Tag = info; } - else + catch (Exception exception) { - listItem.ImageKey = GuiUtils.Icons.Property; + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } - - listItem.Tag = info; } #endregion } } + diff --git a/Samples/ClientControls.Net4/Browse/BrowseListCtrl.cs b/Samples/ClientControls.Net4/Browse/BrowseListCtrl.cs index 5949e63f6..a15833218 100644 --- a/Samples/ClientControls.Net4/Browse/BrowseListCtrl.cs +++ b/Samples/ClientControls.Net4/Browse/BrowseListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,7 +32,10 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; namespace Opc.Ua.Client.Controls @@ -48,24 +51,24 @@ public partial class BrowseListCtrl : Opc.Ua.Client.Controls.BaseListCtrl public BrowseListCtrl() { InitializeComponent(); - SetColumns(m_ColumnNames); + SetColumns(m_ColumnNames); } #region Private Fields - private Session m_session; - - // The columns to display in the control. - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Type", HorizontalAlignment.Left, null }, - new object[] { "Target", HorizontalAlignment.Left, null } - }; - #endregion - + private ISession m_session; + + // The columns to display in the control. + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Type", HorizontalAlignment.Left, null }, + new object[] { "Target", HorizontalAlignment.Left, null } + }; + #endregion + /// /// Initializes the control with a set of items. /// - public void Initialize(Session session, ExpandedNodeId nodeId) + public async Task InitializeAsync(ISession session, ExpandedNodeId nodeId, CancellationToken ct = default) { ItemsLV.Items.Clear(); m_session = session; @@ -75,7 +78,7 @@ public void Initialize(Session session, ExpandedNodeId nodeId) return; } - ILocalNode node = m_session.NodeCache.Find(nodeId) as ILocalNode; + ILocalNode node = await m_session.NodeCache.FindAsync(nodeId, ct) as ILocalNode; if (node == null) { @@ -90,7 +93,7 @@ public void Initialize(Session session, ExpandedNodeId nodeId) { AddItem(references[ii]); } - + references = node.References.Find(ReferenceTypes.NonHierarchicalReferences, true, true, m_session.TypeTree); for (int ii = 0; ii < references.Count; ii++) @@ -103,47 +106,54 @@ public void Initialize(Session session, ExpandedNodeId nodeId) #region Overridden Methods /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - IReference reference = item as IReference; + try + { + IReference reference = item as IReference; + + if (reference == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } - if (reference == null) - { - base.UpdateItem(listItem, item); - return; - } - - IReferenceType referenceType = m_session.NodeCache.Find(reference.ReferenceTypeId) as IReferenceType; + IReferenceType referenceType = await m_session.NodeCache.FindAsync(reference.ReferenceTypeId, ct) as IReferenceType; - if (referenceType != null) - { - if (reference.IsInverse) + if (referenceType != null) { - listItem.SubItems[0].Text = Utils.Format("{0}", referenceType.InverseName); + if (reference.IsInverse) + { + listItem.SubItems[0].Text = Utils.Format("{0}", referenceType.InverseName); + } + else + { + listItem.SubItems[0].Text = Utils.Format("{0}", referenceType.DisplayName); + } } else { - listItem.SubItems[0].Text = Utils.Format("{0}", referenceType.DisplayName); + listItem.SubItems[0].Text = Utils.Format("{0}", reference.ReferenceTypeId); } - } - else - { - listItem.SubItems[0].Text = Utils.Format("{0}", reference.ReferenceTypeId); - } - - INode target = m_session.NodeCache.Find(reference.TargetId) as INode; - if (target != null) - { - listItem.SubItems[1].Text = Utils.Format("{0}", target.DisplayName); + INode target = await m_session.NodeCache.FindAsync(reference.TargetId, ct) as INode; + + if (target != null) + { + listItem.SubItems[1].Text = Utils.Format("{0}", target.DisplayName); + } + else + { + listItem.SubItems[1].Text = Utils.Format("{0}", reference.TargetId); + } + + listItem.ImageKey = await GuiUtils.GetTargetIconAsync(m_session, NodeClass.ReferenceType, null, ct); + listItem.Tag = reference; } - else + catch (Exception exception) { - listItem.SubItems[1].Text = Utils.Format("{0}", reference.TargetId); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } - - listItem.ImageKey = GuiUtils.GetTargetIcon(m_session, NodeClass.ReferenceType, null); - listItem.Tag = reference; } #endregion } diff --git a/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.Designer.cs b/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.Designer.cs index 430eeee82..d701913fb 100644 --- a/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.Designer.cs @@ -95,7 +95,7 @@ private void InitializeComponent() this.RootBTN.TabIndex = 2; this.RootBTN.Text = "Root"; this.RootBTN.UseVisualStyleBackColor = true; - this.RootBTN.Click += new System.EventHandler(this.RootBTN_Click); + this.RootBTN.Click += new System.EventHandler(this.RootBTN_ClickAsync); // // BrowseDirectionCTRL // diff --git a/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.cs b/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.cs index 363c1879a..5f8a92354 100644 --- a/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.cs +++ b/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,7 @@ using System.Windows.Forms; using System.Threading; using System.Reflection; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -59,7 +60,7 @@ public BrowseTreeCtrl() private NodeId m_rootId; private NodeId m_viewId; - private Session m_session; + private ISession m_session; private NodeId m_referenceTypeId; private BrowseDirection m_browseDirection; private BrowseListCtrl m_referencesCTRL; @@ -71,7 +72,7 @@ public BrowseTreeCtrl() /// public BrowseListCtrl ReferencesCTRL { - get { return m_referencesCTRL; } + get { return m_referencesCTRL; } set { m_referencesCTRL = value; } } @@ -80,7 +81,7 @@ public BrowseListCtrl ReferencesCTRL /// public AttributeListCtrl AttributesCTRL { - get { return m_attributesCTRL; } + get { return m_attributesCTRL; } set { m_attributesCTRL = value; } } @@ -89,8 +90,8 @@ public AttributeListCtrl AttributesCTRL /// public event EventHandler NodesSelected { - add { m_nodesSelected += value; } - remove { m_nodesSelected -= value; } + add { m_nodesSelected += value; } + remove { m_nodesSelected -= value; } } #region NodesSelectedEventArgs Class @@ -118,16 +119,17 @@ public IList Nodes private IList m_nodes; } #endregion - + /// /// Displays the a root in the control. /// - public void Initialize( - Session session, - NodeId rootId, + public async Task InitializeAsync( + ISession session, + NodeId rootId, NodeId viewId, - NodeId referenceTypeId, - BrowseDirection browseDirection) + NodeId referenceTypeId, + BrowseDirection browseDirection, + CancellationToken ct = default) { m_session = session; m_rootId = rootId; @@ -152,16 +154,16 @@ public void Initialize( m_referenceTypeId = ReferenceTypeIds.HierarchicalReferences; } - ReferenceTypeCTRL.Initialize(m_session, ReferenceTypeIds.HierarchicalReferences); + await ReferenceTypeCTRL.InitializeAsync(m_session, ReferenceTypeIds.HierarchicalReferences, ct); ReferenceTypeCTRL.SelectedTypeId = m_referenceTypeId; - ILocalNode root = m_session.NodeCache.Find(m_rootId) as ILocalNode; + ILocalNode root = await m_session.NodeCache.FindAsync(m_rootId, ct) as ILocalNode; if (root == null) { return; } - + ReferenceDescription reference = new ReferenceDescription(); reference.ReferenceTypeId = referenceTypeId; @@ -174,17 +176,17 @@ public void Initialize( TreeNode rootNode = new TreeNode(reference.ToString()); - rootNode.ImageKey = rootNode.SelectedImageKey = GuiUtils.GetTargetIcon(session, reference); + rootNode.ImageKey = rootNode.SelectedImageKey = await GuiUtils.GetTargetIconAsync(session, reference, ct); rootNode.Tag = reference; rootNode.Nodes.Add(new TreeNode()); - + NodesTV.Nodes.Add(rootNode); } /// /// Browses the children of the node and updates the tree. /// - private bool BrowseChildren(TreeNode parent) + private async Task BrowseChildrenAsync(TreeNode parent, CancellationToken ct = default) { ReferenceDescription reference = parent.Tag as ReferenceDescription; @@ -208,7 +210,7 @@ private bool BrowseChildren(TreeNode parent) nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)(int)BrowseResultMask.All; - + BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); @@ -221,53 +223,54 @@ private bool BrowseChildren(TreeNode parent) view.Timestamp = DateTime.MinValue; view.ViewVersion = 0; } - - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.Browse( + BrowseResponse response = await m_session.BrowseAsync( null, view, 0, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; if (results.Count != 1 || StatusCode.IsBad(results[0].StatusCode)) { return false; } - UpdateNode(parent, results[0].References); + await UpdateNodeAsync(parent, results[0].References, ct); while (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) { ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); - m_session.BrowseNext( + BrowseNextResponse response2 = await m_session.BrowseNextAsync( null, parent == null, continuationPoints, - out results, - out diagnosticInfos); + ct); + + results = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; if (results.Count != 1 || StatusCode.IsBad(results[0].StatusCode)) { return false; } - - UpdateNode(parent, results[0].References); + + await UpdateNodeAsync(parent, results[0].References, ct); } return true; } /// - /// Adds the browse results to the node (if not null). + /// Adds the browse results to the node (if not null). /// - private void UpdateNode(TreeNode parent, ReferenceDescriptionCollection references) - { + private async Task UpdateNodeAsync(TreeNode parent, ReferenceDescriptionCollection references, CancellationToken ct = default) + { try { for (int ii = 0; ii < references.Count; ii++) @@ -276,48 +279,55 @@ private void UpdateNode(TreeNode parent, ReferenceDescriptionCollection referenc TreeNode childNode = new TreeNode(reference.ToString()); - childNode.ImageKey = childNode.SelectedImageKey = GuiUtils.GetTargetIcon(m_session, reference); + childNode.ImageKey = childNode.SelectedImageKey = await GuiUtils.GetTargetIconAsync(m_session, reference, ct); childNode.Tag = reference; - + childNode.Nodes.Add(new TreeNode()); - + parent.Nodes.Add(childNode); } - } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - + #region Overridden Members - /// - protected override void SelectNode() + /// + protected override async void SelectNode() { - base.SelectNode(); - - ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; - - if (reference == null) + try { - return; - } + base.SelectNode(); - // update attributes control. - if (AttributesCTRL != null) - { - AttributesCTRL.Initialize(m_session, reference.NodeId); - } + ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; + + if (reference == null) + { + return; + } - // update references control. - if (ReferencesCTRL != null) + // update attributes control. + if (AttributesCTRL != null) + { + await AttributesCTRL.InitializeAsync(m_session, reference.NodeId); + } + + // update references control. + if (ReferencesCTRL != null) + { + await ReferencesCTRL.InitializeAsync(m_session, reference.NodeId); + } + } + catch (Exception exception) { - ReferencesCTRL.Initialize(m_session, reference.NodeId); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - /// - protected override bool BeforeExpand(TreeNode clickedNode) + /// + protected override async Task BeforeExpandAsync(TreeNode clickedNode, CancellationToken ct = default) { try { @@ -325,20 +335,20 @@ protected override bool BeforeExpand(TreeNode clickedNode) if (clickedNode.Nodes.Count == 1 && clickedNode.Nodes[0].Text == String.Empty) { // browse. - return !BrowseChildren(clickedNode); + return !await BrowseChildrenAsync(clickedNode, ct); } // do not cancel expand. return false; - } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); return false; } } - /// + /// protected override void EnableMenuItems(TreeNode clickedNode) { if (NodesTV.SelectedNode == null) @@ -356,7 +366,7 @@ protected override void EnableMenuItems(TreeNode clickedNode) #endregion #region Event Handlers - private void RootBTN_Click(object sender, EventArgs e) + private async void RootBTN_ClickAsync(object sender, EventArgs e) { try { @@ -372,11 +382,11 @@ private void RootBTN_Click(object sender, EventArgs e) return; } - Initialize(m_session, (NodeId)reference.NodeId, m_viewId, m_referenceTypeId, m_browseDirection); - } + await InitializeAsync(m_session, (NodeId)reference.NodeId, m_viewId, m_referenceTypeId, m_browseDirection); + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -394,10 +404,10 @@ private void BrowseDirectionCTRL_SelectedIndexChanged(object sender, EventArgs e NodesTV.SelectedNode.Expand(); return; } - } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -420,11 +430,11 @@ private void SelectMI_Click(object sender, EventArgs e) collection.Add(reference); m_nodesSelected(this, new NodesSelectedEventArgs(collection)); } - } - } + } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -452,14 +462,14 @@ private void SelectChildrenMI_Click(object sender, EventArgs e) } if (collection.Count > 0) - { + { m_nodesSelected(this, new NodesSelectedEventArgs(collection)); } - } - } + } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -477,10 +487,10 @@ private void ReferenceTypeCTRL_ReferenceSelectionChanged(object sender, Referenc NodesTV.SelectedNode.Expand(); return; } - } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Browse/NodeListCtrl.cs b/Samples/ClientControls.Net4/Browse/NodeListCtrl.cs index 8ba9fbcfc..8513782b0 100644 --- a/Samples/ClientControls.Net4/Browse/NodeListCtrl.cs +++ b/Samples/ClientControls.Net4/Browse/NodeListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,9 +32,12 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; +using static System.Net.Mime.MediaTypeNames; namespace Opc.Ua.Client.Controls { @@ -49,28 +52,28 @@ public partial class NodeListCtrl : Opc.Ua.Client.Controls.BaseListCtrl public NodeListCtrl() { InitializeComponent(); - SetColumns(m_ColumnNames); + SetColumns(m_ColumnNames); } #region Private Fields - private Session m_session; + private ISession m_session; private BrowseListCtrl m_referencesCTRL; private AttributeListCtrl m_attributesCTRL; - - // The columns to display in the control. - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "ID", HorizontalAlignment.Left, null } - }; - #endregion + + // The columns to display in the control. + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "ID", HorizontalAlignment.Left, null } + }; + #endregion /// /// The control that displays the non-hierarchial references for the selected node. /// public BrowseListCtrl ReferencesCTRL { - get { return m_referencesCTRL; } + get { return m_referencesCTRL; } set { m_referencesCTRL = value; } } @@ -79,14 +82,14 @@ public BrowseListCtrl ReferencesCTRL /// public AttributeListCtrl AttributesCTRL { - get { return m_attributesCTRL; } + get { return m_attributesCTRL; } set { m_attributesCTRL = value; } } - + /// /// Initializes the control with a set of items. /// - public void Initialize(Session session, IList nodeIds) + public async Task InitializeAsync(ISession session, IList nodeIds, CancellationToken ct = default) { ItemsLV.Items.Clear(); m_session = session; @@ -99,7 +102,7 @@ public void Initialize(Session session, IList nodeIds) for (int ii = 0; ii < nodeIds.Count; ii++) { - ILocalNode node = m_session.NodeCache.Find(nodeIds[ii]) as ILocalNode; + ILocalNode node = await m_session.NodeCache.FindAsync(nodeIds[ii], ct) as ILocalNode; if (node == null) { @@ -111,13 +114,13 @@ public void Initialize(Session session, IList nodeIds) AdjustColumns(); } - + /// /// Adds a node to the control. /// - public void Add(NodeId nodeId) + public async Task AddAsync(NodeId nodeId, CancellationToken ct = default) { - ILocalNode node = m_session.NodeCache.Find(nodeId) as ILocalNode; + ILocalNode node = await m_session.NodeCache.FindAsync(nodeId, ct) as ILocalNode; if (node != null) { @@ -132,8 +135,8 @@ public void Add(NodeId nodeId) public IList GetNodeList() { List items = new List(ItemsLV.Items.Count); - - for (int ii = 0; ii < ItemsLV.Items.Count; ii++) + + for (int ii = 0; ii < ItemsLV.Items.Count; ii++) { items.Add(ItemsLV.Items[ii].Tag as ILocalNode); } @@ -143,59 +146,66 @@ public IList GetNodeList() #region Overridden Methods /// - protected override void SelectItems() + protected override async void SelectItems() { - base.SelectItems(); + try + { + base.SelectItems(); - ILocalNode node = GetSelectedTag(0) as ILocalNode; + ILocalNode node = GetSelectedTag(0) as ILocalNode; - if (node == null) - { - return; - } + if (node == null) + { + return; + } - // update attributes control. - if (AttributesCTRL != null) - { - AttributesCTRL.Initialize(m_session, node.NodeId); - } + // update attributes control. + if (AttributesCTRL != null) + { + await AttributesCTRL.InitializeAsync(m_session, node.NodeId); + } - // update references control. - if (ReferencesCTRL != null) + // update references control. + if (ReferencesCTRL != null) + { + await ReferencesCTRL.InitializeAsync(m_session, node.NodeId); + } + } + catch (Exception exception) { - ReferencesCTRL.Initialize(m_session, node.NodeId); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } /// protected override void EnableMenuItems(ListViewItem clickedItem) - { + { DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; - } + } /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { ILocalNode node = item as ILocalNode; - if (node == null) - { - base.UpdateItem(listItem, item); - return; - } - - listItem.SubItems[0].Text = Utils.Format("{0}", node.DisplayName); - listItem.SubItems[1].Text = Utils.Format("{0}", node.NodeId); - - listItem.ImageKey = GuiUtils.GetTargetIcon(m_session, node.NodeClass, node.TypeDefinitionId); - listItem.Tag = item; + if (node == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } + + listItem.SubItems[0].Text = Utils.Format("{0}", node.DisplayName); + listItem.SubItems[1].Text = Utils.Format("{0}", node.NodeId); + + listItem.ImageKey = await GuiUtils.GetTargetIconAsync(m_session, node.NodeClass, node.TypeDefinitionId, ct); + listItem.Tag = item; } /// /// Handles a drop event. /// - protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) - { + protected override async Task OnDragDropAsync(object sender, DragEventArgs e, CancellationToken ct = default) + { try { ReferenceDescription reference = e.Data.GetData(typeof(ReferenceDescription)) as ReferenceDescription; @@ -205,7 +215,7 @@ protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) return; } - ILocalNode node = m_session.NodeCache.Find(reference.NodeId) as ILocalNode; + ILocalNode node = await m_session.NodeCache.FindAsync(reference.NodeId, ct) as ILocalNode; if (node == null) { @@ -214,11 +224,11 @@ protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) AddItem(node); - AdjustColumns(); + AdjustColumns(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -228,22 +238,22 @@ private void DeleteMI_Click(object sender, EventArgs e) try { List items = new List(ItemsLV.SelectedItems.Count); - - for (int ii = 0; ii < ItemsLV.SelectedItems.Count; ii++) + + for (int ii = 0; ii < ItemsLV.SelectedItems.Count; ii++) { items.Add(ItemsLV.SelectedItems[ii]); } - for (int ii = 0; ii < items.Count; ii++) + for (int ii = 0; ii < items.Count; ii++) { items[ii].Remove(); } AdjustColumns(); - } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/ClientControls.Net4/Browse/SelectNodesDlg.Designer.cs b/Samples/ClientControls.Net4/Browse/SelectNodesDlg.Designer.cs index d50b60065..65e0e2f78 100644 --- a/Samples/ClientControls.Net4/Browse/SelectNodesDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Browse/SelectNodesDlg.Designer.cs @@ -162,7 +162,7 @@ private void InitializeComponent() this.BrowseCTRL.ReferencesCTRL = this.ReferencesCTRL; this.BrowseCTRL.Size = new System.Drawing.Size(377, 255); this.BrowseCTRL.TabIndex = 29; - this.BrowseCTRL.NodesSelected += new System.EventHandler(this.BrowseCTRL_NodesSelected); + this.BrowseCTRL.NodesSelected += new System.EventHandler(this.BrowseCTRL_NodesSelectedAsync); // // AttributesCTRL // diff --git a/Samples/ClientControls.Net4/Browse/SelectNodesDlg.cs b/Samples/ClientControls.Net4/Browse/SelectNodesDlg.cs index 098e68ea6..8f47c10e4 100644 --- a/Samples/ClientControls.Net4/Browse/SelectNodesDlg.cs +++ b/Samples/ClientControls.Net4/Browse/SelectNodesDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,11 +32,12 @@ using System.ComponentModel; using System.Data; using System.Drawing; -using System.Text; -using System.Windows.Forms; using System.Reflection; using System.Security.Cryptography.X509Certificates; - +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; using Opc.Ua.Client; namespace Opc.Ua.Client.Controls @@ -59,17 +60,17 @@ public SelectNodesDlg() #region Private Fields #endregion - + #region Public Interface /// /// Displays the dialog. /// - public IList ShowDialog(Session session, NodeId rootId, IList nodeIds) + public async Task> ShowDialogAsync(ISession session, NodeId rootId, IList nodeIds, CancellationToken ct = default) { - BrowseCTRL.Initialize(session, rootId, null, null, BrowseDirection.Forward); - ReferencesCTRL.Initialize(session, rootId); - AttributesCTRL.Initialize(session, rootId); - NodesCTRL.Initialize(session, nodeIds); + await BrowseCTRL.InitializeAsync(session, rootId, null, null, BrowseDirection.Forward, ct); + await ReferencesCTRL.InitializeAsync(session, rootId, ct); + await AttributesCTRL.InitializeAsync(session, rootId, ct); + await NodesCTRL.InitializeAsync(session, nodeIds, ct); if (ShowDialog() != DialogResult.OK) { @@ -92,7 +93,7 @@ private void OkBTN_Click(object sender, EventArgs e) } } - private void BrowseCTRL_NodesSelected(object sender, BrowseTreeCtrl.NodesSelectedEventArgs e) + private async void BrowseCTRL_NodesSelectedAsync(object sender, BrowseTreeCtrl.NodesSelectedEventArgs e) { try { @@ -100,7 +101,7 @@ private void BrowseCTRL_NodesSelected(object sender, BrowseTreeCtrl.NodesSelecte { if (!reference.NodeId.IsAbsolute) { - NodesCTRL.Add((NodeId)reference.NodeId); + await NodesCTRL.AddAsync((NodeId)reference.NodeId); } } } diff --git a/Samples/ClientControls.Net4/ClientUtils.cs b/Samples/ClientControls.Net4/ClientUtils.cs index f91375d81..0f18ea39f 100644 --- a/Samples/ClientControls.Net4/ClientUtils.cs +++ b/Samples/ClientControls.Net4/ClientUtils.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -31,6 +31,8 @@ using System.Collections.Generic; using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -194,7 +196,7 @@ public static string GetValueRankDisplayText(int valueRank) /// The id of the attribute. /// The value of the attribute. /// The attribute formatted as a string. - public static string GetAttributeDisplayText(Session session, uint attributeId, Variant value) + public static async Task GetAttributeDisplayTextAsync(ISession session, uint attributeId, Variant value, CancellationToken ct = default) { if (value == Variant.Null) { @@ -205,79 +207,79 @@ public static string GetAttributeDisplayText(Session session, uint attributeId, { case Attributes.AccessLevel: case Attributes.UserAccessLevel: - { - byte? field = value.Value as byte?; - - if (field != null) - { - return GetAccessLevelDisplayText(field.Value); - } + { + byte? field = value.Value as byte?; - break; + if (field != null) + { + return GetAccessLevelDisplayText(field.Value); } - case Attributes.EventNotifier: - { - byte? field = value.Value as byte?; + break; + } - if (field != null) - { - return GetEventNotifierDisplayText(field.Value); - } + case Attributes.EventNotifier: + { + byte? field = value.Value as byte?; - break; + if (field != null) + { + return GetEventNotifierDisplayText(field.Value); } + break; + } + case Attributes.DataType: - { - return session.NodeCache.GetDisplayText(value.Value as NodeId); - } + { + return await session.NodeCache.GetDisplayTextAsync(value.Value as NodeId, ct); + } case Attributes.ValueRank: - { - int? field = value.Value as int?; - - if (field != null) - { - return GetValueRankDisplayText(field.Value); - } + { + int? field = value.Value as int?; - break; + if (field != null) + { + return GetValueRankDisplayText(field.Value); } - case Attributes.NodeClass: - { - int? field = value.Value as int?; + break; + } - if (field != null) - { - return ((NodeClass)field.Value).ToString(); - } + case Attributes.NodeClass: + { + int? field = value.Value as int?; - break; + if (field != null) + { + return ((NodeClass)field.Value).ToString(); } - case Attributes.NodeId: - { - NodeId field = value.Value as NodeId; + break; + } - if (!NodeId.IsNull(field)) - { - return field.ToString(); - } + case Attributes.NodeId: + { + NodeId field = value.Value as NodeId; - return "Null"; + if (!NodeId.IsNull(field)) + { + return field.ToString(); } + return "Null"; + } + case Attributes.DataTypeDefinition: + { + ExtensionObject field = value.Value as ExtensionObject; + if (field != null) { - ExtensionObject field = value.Value as ExtensionObject; - if (field != null) - { - return field.ToString(); - } - break; + return field.ToString(); } + break; + } } // check for byte strings. @@ -298,18 +300,19 @@ public static string GetAttributeDisplayText(Session session, uint attributeId, /// The session. /// The set of browse operations to perform. /// if set to true a exception will be thrown on an error. + /// A cancellation token to use to cancel the operation. /// /// The references found. Null if an error occurred. /// - public static ReferenceDescriptionCollection Browse(Session session, BrowseDescriptionCollection nodesToBrowse, bool throwOnError) + public static Task BrowseAsync(ISession session, BrowseDescriptionCollection nodesToBrowse, bool throwOnError, CancellationToken ct = default) { - return Browse(session, null, nodesToBrowse, throwOnError); + return BrowseAsync(session, null, nodesToBrowse, throwOnError, ct); } /// /// Browses the address space and returns the references found. /// - public static ReferenceDescriptionCollection Browse(Session session, ViewDescription view, BrowseDescriptionCollection nodesToBrowse, bool throwOnError) + public static async Task BrowseAsync(ISession session, ViewDescription view, BrowseDescriptionCollection nodesToBrowse, bool throwOnError, CancellationToken ct = default) { try { @@ -318,16 +321,15 @@ public static ReferenceDescriptionCollection Browse(Session session, ViewDescrip while (nodesToBrowse.Count > 0) { // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - session.Browse( + BrowseResponse response = await session.BrowseAsync( null, view, 0, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); @@ -340,7 +342,7 @@ public static ReferenceDescriptionCollection Browse(Session session, ViewDescrip // check for error. if (StatusCode.IsBad(results[ii].StatusCode)) { - // this error indicates that the server does not have enough simultaneously active + // this error indicates that the server does not have enough simultaneously active // continuation points. This request will need to be resent after the other operations // have been completed and their continuation points released. if (results[ii].StatusCode == StatusCodes.BadNoContinuationPoints) @@ -371,12 +373,14 @@ public static ReferenceDescriptionCollection Browse(Session session, ViewDescrip while (continuationPoints.Count > 0) { // continue browse operation. - session.BrowseNext( + BrowseNextResponse response2 = await session.BrowseNextAsync( null, false, continuationPoints, - out results, - out diagnosticInfos); + ct); + + results = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); @@ -434,25 +438,26 @@ public static ReferenceDescriptionCollection Browse(Session session, ViewDescrip /// The session. /// The NodeId for the starting node. /// if set to true a exception will be thrown on an error. + /// The cancellation token to cancel the operation /// /// The references found. Null if an error occurred. /// - public static ReferenceDescriptionCollection Browse(Session session, BrowseDescription nodeToBrowse, bool throwOnError) + public static Task BrowseAsync(ISession session, BrowseDescription nodeToBrowse, bool throwOnError, CancellationToken ct = default) { - return Browse(session, null, nodeToBrowse, throwOnError); + return BrowseAsync(session, null, nodeToBrowse, throwOnError, ct); } /// /// Browses the address space and returns the references found. /// - public static ReferenceDescriptionCollection Browse(Session session, ViewDescription view, BrowseDescription nodeToBrowse, bool throwOnError) + public static Task BrowseAsync(ISession session, ViewDescription view, BrowseDescription nodeToBrowse, bool throwOnError, CancellationToken ct = default) { // construct browse request. BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection { - nodeToBrowse - }; + nodeToBrowse + }; - return Browse(session, view, nodesToBrowse, throwOnError); + return BrowseAsync(session, view, nodesToBrowse, throwOnError, ct); } /// @@ -461,10 +466,11 @@ public static ReferenceDescriptionCollection Browse(Session session, ViewDescrip /// The session. /// The NodeId for a type node in the address space. /// if set to true a exception will be thrown on an error. + /// A cancellation token to use to cancel the operation. /// /// The references found. Null if an error occurred. /// - public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, NodeId typeId, bool throwOnError) + public static async Task BrowseSuperTypesAsync(ISession session, NodeId typeId, bool throwOnError, CancellationToken ct = default) { ReferenceDescriptionCollection supertypes = new ReferenceDescriptionCollection(); @@ -477,10 +483,10 @@ public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, N nodeToBrowse.BrowseDirection = BrowseDirection.Inverse; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype; nodeToBrowse.IncludeSubtypes = false; // more efficient to use IncludeSubtypes=False when possible. - nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. + nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; - ReferenceDescriptionCollection references = Browse(session, nodeToBrowse, throwOnError); + ReferenceDescriptionCollection references = await BrowseAsync(session, nodeToBrowse, throwOnError, ct); while (references != null && references.Count > 0) { @@ -495,7 +501,7 @@ public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, N // get the references for the next level up. nodeToBrowse.NodeId = (NodeId)references[0].NodeId; - references = Browse(session, nodeToBrowse, throwOnError); + references = await BrowseAsync(session, nodeToBrowse, throwOnError, ct); } // return complete list. @@ -518,12 +524,14 @@ public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, N /// An open session with the server to use. /// The starting node for the relative paths. /// The namespace URIs referenced by the relative paths. + /// A cancellation token to use to cancel the operation. /// The relative paths. /// A collection of local nodes. - public static List TranslateBrowsePaths( - Session session, + public static async Task> TranslateBrowsePathsAsync( + ISession session, NodeId startNodeId, NamespaceTable namespacesUris, + CancellationToken ct, params string[] relativePaths) { // build the list of browse paths to follow by parsing the relative paths. @@ -535,7 +543,7 @@ public static List TranslateBrowsePaths( { BrowsePath browsePath = new BrowsePath(); - // The relative paths used indexes in the namespacesUris table. These must be + // The relative paths used indexes in the namespacesUris table. These must be // converted to indexes used by the server. An error occurs if the relative path // refers to a namespaceUri that the server does not recognize. @@ -555,14 +563,14 @@ public static List TranslateBrowsePaths( } // make the call to the server. - BrowsePathResultCollection results; - DiagnosticInfoCollection diagnosticInfos; - - ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds( + TranslateBrowsePathsToNodeIdsResponse response = await session.TranslateBrowsePathsToNodeIdsAsync( null, browsePaths, - out results, - out diagnosticInfos); + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + BrowsePathResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; // ensure that the server returned valid results. Session.ValidateResponse(results, browsePaths); @@ -597,7 +605,7 @@ public static List TranslateBrowsePaths( continue; } - // The targetId is an ExpandedNodeId because it could be node in another server. + // The targetId is an ExpandedNodeId because it could be node in another server. // The ToNodeId function is used to convert a local NodeId stored in a ExpandedNodeId to a NodeId. nodes.Add(ExpandedNodeId.ToNodeId(target.TargetId, session.NamespaceUris)); } @@ -642,15 +650,17 @@ public static NodeId FindEventType(MonitoredItem monitoredItem, EventFieldList n /// The notification. /// The known event types. /// Mapping between event types and known event types. + /// Cancellation token to use to cancel operation /// /// The event object. Null if the notification is not a valid event type. /// - public static BaseEventState ConstructEvent( - Session session, + public static async Task ConstructEventAsync( + ISession session, MonitoredItem monitoredItem, EventFieldList notification, Dictionary knownEventTypes, - Dictionary eventTypeMappings) + Dictionary eventTypeMappings, + CancellationToken ct = default) { // find the event type. NodeId eventTypeId = FindEventType(monitoredItem, notification); @@ -683,7 +693,7 @@ public static BaseEventState ConstructEvent( if (knownType == null) { // browse for the supertypes of the event type. - ReferenceDescriptionCollection supertypes = ClientUtils.BrowseSuperTypes(session, eventTypeId, false); + ReferenceDescriptionCollection supertypes = await ClientUtils.BrowseSuperTypesAsync(session, eventTypeId, false, ct); // can't do anything with unknown types. if (supertypes == null) @@ -736,15 +746,15 @@ public static BaseEventState ConstructEvent( /// /// Collects the instance declarations for a type. /// - public static List CollectInstanceDeclarationsForType(Session session, NodeId typeId) + public static Task> CollectInstanceDeclarationsForTypeAsync(ISession session, NodeId typeId, CancellationToken ct = default) { - return CollectInstanceDeclarationsForType(session, typeId, true); + return CollectInstanceDeclarationsForTypeAsync(session, typeId, true, ct); } /// /// Collects the instance declarations for a type. /// - public static List CollectInstanceDeclarationsForType(Session session, NodeId typeId, bool includeSupertypes) + public static async Task> CollectInstanceDeclarationsForTypeAsync(ISession session, NodeId typeId, bool includeSupertypes, CancellationToken ct = default) { // process the types starting from the top of the tree. List instances = new List(); @@ -753,19 +763,19 @@ public static List CollectInstanceDeclarationsForType(Sessi // get the supertypes. if (includeSupertypes) { - ReferenceDescriptionCollection supertypes = ClientUtils.BrowseSuperTypes(session, typeId, false); + ReferenceDescriptionCollection supertypes = await ClientUtils.BrowseSuperTypesAsync(session, typeId, false, ct); if (supertypes != null) { for (int ii = supertypes.Count - 1; ii >= 0; ii--) { - CollectInstanceDeclarations(session, (NodeId)supertypes[ii].NodeId, null, instances, map); + await CollectInstanceDeclarationsAsync(session, (NodeId)supertypes[ii].NodeId, null, instances, map, ct); } } } // collect the fields for the selected type. - CollectInstanceDeclarations(session, typeId, null, instances, map); + await CollectInstanceDeclarationsAsync(session, typeId, null, instances, map, ct); // return the complete list. return instances; @@ -774,12 +784,13 @@ public static List CollectInstanceDeclarationsForType(Sessi /// /// Collects the fields for the instance node. /// - private static void CollectInstanceDeclarations( - Session session, + private static async Task CollectInstanceDeclarationsAsync( + ISession session, NodeId typeId, InstanceDeclaration parent, List instances, - IDictionary map) + IDictionary map, + CancellationToken ct = default) { // find the children. BrowseDescription nodeToBrowse = new BrowseDescription(); @@ -800,7 +811,7 @@ private static void CollectInstanceDeclarations( nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; // ignore any browsing errors. - ReferenceDescriptionCollection references = ClientUtils.Browse(session, nodeToBrowse, false); + ReferenceDescriptionCollection references = await ClientUtils.BrowseAsync(session, nodeToBrowse, false, ct); if (references == null) { @@ -874,7 +885,7 @@ private static void CollectInstanceDeclarations( } // find the modelling rules. - List modellingRules = FindTargetOfReference(session, nodeIds, Opc.Ua.ReferenceTypeIds.HasModellingRule, false); + List modellingRules = await FindTargetOfReferenceAsync(session, nodeIds, Opc.Ua.ReferenceTypeIds.HasModellingRule, false, ct); if (modellingRules != null) { @@ -891,7 +902,7 @@ private static void CollectInstanceDeclarations( } // update the descriptions. - UpdateInstanceDescriptions(session, children, false); + await UpdateInstanceDescriptionsAsync(session, children, false, ct); // recusively collect instance declarations for the tree below. for (int ii = 0; ii < children.Count; ii++) @@ -899,7 +910,7 @@ private static void CollectInstanceDeclarations( if (!NodeId.IsNull(children[ii].ModellingRule)) { instances.Add(children[ii]); - CollectInstanceDeclarations(session, typeId, children[ii], instances, map); + await CollectInstanceDeclarationsAsync(session, typeId, children[ii], instances, map, ct); } } } @@ -907,7 +918,7 @@ private static void CollectInstanceDeclarations( /// /// Finds the targets for the specified reference. /// - private static List FindTargetOfReference(Session session, List nodeIds, NodeId referenceTypeId, bool throwOnError) + private static async Task> FindTargetOfReferenceAsync(ISession session, List nodeIds, NodeId referenceTypeId, bool throwOnError, CancellationToken ct = default) { try { @@ -927,16 +938,15 @@ private static List FindTargetOfReference(Session session, List } // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - session.Browse( + BrowseResponse response = await session.BrowseAsync( null, null, 1, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); @@ -975,12 +985,14 @@ private static List FindTargetOfReference(Session session, List // release continuation points. if (continuationPoints.Count > 0) { - session.BrowseNext( + BrowseNextResponse response2 = await session.BrowseNextAsync( null, true, continuationPoints, - out results, - out diagnosticInfos); + ct); + + results = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); @@ -1003,7 +1015,7 @@ private static List FindTargetOfReference(Session session, List /// /// Finds the targets for the specified reference. /// - private static void UpdateInstanceDescriptions(Session session, List instances, bool throwOnError) + private static async Task UpdateInstanceDescriptionsAsync(ISession session, List instances, bool throwOnError, CancellationToken ct = default) { try { @@ -1028,16 +1040,15 @@ private static void UpdateInstanceDescriptions(Session session, List= 0) { @@ -1081,10 +1092,10 @@ private static void UpdateInstanceDescriptions(Session session, ListThe type id. /// The fields. /// The node id for the declaration of the field. - private static void CollectFieldsForType(Session session, NodeId typeId, SimpleAttributeOperandCollection fields, List fieldNodeIds) + private static async Task CollectFieldsForTypeAsync(Session session, NodeId typeId, SimpleAttributeOperandCollection fields, List fieldNodeIds, CancellationToken ct = default) { // get the supertypes. - ReferenceDescriptionCollection supertypes = ClientUtils.BrowseSuperTypes(session, typeId, false); + ReferenceDescriptionCollection supertypes = await ClientUtils.BrowseSuperTypesAsync(session, typeId, false, ct); if (supertypes == null) { @@ -1097,11 +1108,11 @@ private static void CollectFieldsForType(Session session, NodeId typeId, SimpleA for (int ii = supertypes.Count - 1; ii >= 0; ii--) { - CollectFields(session, (NodeId)supertypes[ii].NodeId, parentPath, fields, fieldNodeIds, foundNodes); + await CollectFieldsAsync(session, (NodeId)supertypes[ii].NodeId, parentPath, fields, fieldNodeIds, foundNodes, ct); } // collect the fields for the selected type. - CollectFields(session, typeId, parentPath, fields, fieldNodeIds, foundNodes); + await CollectFieldsAsync(session, typeId, parentPath, fields, fieldNodeIds, foundNodes, ct); } /// @@ -1111,11 +1122,12 @@ private static void CollectFieldsForType(Session session, NodeId typeId, SimpleA /// The instance id. /// The fields. /// The node id for the declaration of the field. - private static void CollectFieldsForInstance(Session session, NodeId instanceId, SimpleAttributeOperandCollection fields, List fieldNodeIds) + /// Canceellation token to cancel the operation + private static Task CollectFieldsForInstanceAsync(Session session, NodeId instanceId, SimpleAttributeOperandCollection fields, List fieldNodeIds, CancellationToken ct = default) { Dictionary foundNodes = new Dictionary(); QualifiedNameCollection parentPath = new QualifiedNameCollection(); - CollectFields(session, instanceId, parentPath, fields, fieldNodeIds, foundNodes); + return CollectFieldsAsync(session, instanceId, parentPath, fields, fieldNodeIds, foundNodes, ct); } /// @@ -1127,13 +1139,15 @@ private static void CollectFieldsForInstance(Session session, NodeId instanceId, /// The event fields. /// The node id for the declaration of the field. /// The table of found nodes. - private static void CollectFields( + /// Canceellation token to cancel the operation + private static async Task CollectFieldsAsync( Session session, NodeId nodeId, QualifiedNameCollection parentPath, SimpleAttributeOperandCollection fields, List fieldNodeIds, - Dictionary foundNodes) + Dictionary foundNodes, + CancellationToken ct = default) { // find all of the children of the field. BrowseDescription nodeToBrowse = new BrowseDescription(); @@ -1145,7 +1159,7 @@ private static void CollectFields( nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; - ReferenceDescriptionCollection children = ClientUtils.Browse(session, nodeToBrowse, false); + ReferenceDescriptionCollection children = await ClientUtils.BrowseAsync(session, nodeToBrowse, false, ct); if (children == null) { @@ -1188,7 +1202,7 @@ private static void CollectFields( if (!foundNodes.ContainsKey(targetId)) { foundNodes.Add(targetId, browsePath); - CollectFields(session, (NodeId)child.NodeId, browsePath, fields, fieldNodeIds, foundNodes); + await CollectFieldsAsync(session, (NodeId)child.NodeId, browsePath, fields, fieldNodeIds, foundNodes, ct); } } } diff --git a/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.Designer.cs b/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.Designer.cs index 6d515aeeb..93e33c421 100644 --- a/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.Designer.cs @@ -79,7 +79,7 @@ private void InitializeComponent() this.Attributes_ViewMI.Name = "Attributes_ViewMI"; this.Attributes_ViewMI.Size = new System.Drawing.Size(99, 22); this.Attributes_ViewMI.Text = "View"; - this.Attributes_ViewMI.Click += new System.EventHandler(this.AttributesLV_DoubleClick); + this.Attributes_ViewMI.Click += new System.EventHandler(this.AttributesLV_DoubleClickAsync); // // AttributesLV // @@ -96,7 +96,7 @@ private void InitializeComponent() this.AttributesLV.TabIndex = 2; this.AttributesLV.UseCompatibleStateImageBehavior = false; this.AttributesLV.View = System.Windows.Forms.View.Details; - this.AttributesLV.DoubleClick += new System.EventHandler(this.AttributesLV_DoubleClick); + this.AttributesLV.DoubleClick += new System.EventHandler(this.AttributesLV_DoubleClickAsync); // // NameCH // diff --git a/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.cs index 646623091..20fbbc369 100644 --- a/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -56,7 +58,7 @@ public AttributesListViewCtrl() #endregion #region Private Fields - private Session m_session; + private ISession m_session; #endregion #region Public Interface @@ -69,7 +71,7 @@ public AttributesListViewCtrl() /// Changes the session used by the control. /// /// The session. - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { m_session = session; } @@ -88,7 +90,7 @@ public ContextMenuStrip AttributesMenuStrip /// public ReadValueId GetSelectedAttribute(int index) { - if (index >=0 && index < AttributesLV.SelectedItems.Count) + if (index >= 0 && index < AttributesLV.SelectedItems.Count) { AttributeInfo info = AttributesLV.SelectedItems[index].Tag as AttributeInfo; @@ -104,7 +106,7 @@ public ReadValueId GetSelectedAttribute(int index) /// /// Reads the attributes for the node. /// - public void ReadAttributes(NodeId nodeId, bool showProperties) + public async Task ReadAttributesAsync(NodeId nodeId, bool showProperties, CancellationToken ct = default) { AttributesLV.Items.Clear(); @@ -116,7 +118,7 @@ public void ReadAttributes(NodeId nodeId, bool showProperties) // build list of attributes to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); - foreach (uint attributeId in Attributes.GetIdentifiers()) + foreach (uint attributeId in Attributes.Identifiers) { ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = nodeId; @@ -125,16 +127,15 @@ public void ReadAttributes(NodeId nodeId, bool showProperties) } // read the attributes. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -168,7 +169,7 @@ public void ReadAttributes(NodeId nodeId, bool showProperties) } else { - item.SubItems.Add(ClientUtils.GetAttributeDisplayText(m_session, attributeId, results[ii].WrappedValue)); + item.SubItems.Add(await ClientUtils.GetAttributeDisplayTextAsync(m_session, attributeId, results[ii].WrappedValue, ct)); } item.Tag = new AttributeInfo() { NodeToRead = nodesToRead[ii], Value = results[ii] }; @@ -180,7 +181,7 @@ public void ReadAttributes(NodeId nodeId, bool showProperties) if (showProperties) { - ReadProperties(nodeId); + await ReadPropertiesAsync(nodeId, ct); } // set the column widths. @@ -193,9 +194,9 @@ public void ReadAttributes(NodeId nodeId, bool showProperties) #region AttributeInfo Class /// - /// The saved information for an attribute/property displayed in the control. + /// The saved information for an attribute/property displayed in the control. /// - private class AttributeInfo + private sealed class AttributeInfo { public ReadValueId NodeToRead; public DataValue Value; @@ -206,7 +207,7 @@ private class AttributeInfo /// /// Reads the properties for the node. /// - private void ReadProperties(NodeId nodeId) + private async Task ReadPropertiesAsync(NodeId nodeId, CancellationToken ct = default) { // build list of references to browse. BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); @@ -223,7 +224,7 @@ private void ReadProperties(NodeId nodeId) nodesToBrowse.Add(nodeToBrowse); // find properties. - ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, View, nodesToBrowse, false); + ReferenceDescriptionCollection references = await ClientUtils.BrowseAsync(m_session, View, nodesToBrowse, false, ct); // build list of properties to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); @@ -251,16 +252,15 @@ private void ReadProperties(NodeId nodeId) } // read the properties. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -292,7 +292,7 @@ private void ReadProperties(NodeId nodeId) } item.Tag = new AttributeInfo() { NodeToRead = nodesToRead[ii], Value = results[ii] }; - item.ImageIndex = ClientUtils.GetImageIndex(m_session, NodeClass.Variable, Opc.Ua.VariableTypeIds.PropertyType, false); + item.ImageIndex = await ClientUtils.GetImageIndexAsync(m_session, NodeClass.Variable, Opc.Ua.VariableTypeIds.PropertyType, false, ct); // display in list. AttributesLV.Items.Add(item); @@ -301,7 +301,7 @@ private void ReadProperties(NodeId nodeId) #endregion #region Event Handlers - private void AttributesLV_DoubleClick(object sender, EventArgs e) + private async void AttributesLV_DoubleClickAsync(object sender, EventArgs e) { try { @@ -317,11 +317,11 @@ private void AttributesLV_DoubleClick(object sender, EventArgs e) return; } - new EditComplexValueDlg().ShowDialog( + await new EditComplexValueDlg().ShowDialogAsync( m_session, info.NodeToRead.NodeId, info.NodeToRead.AttributeId, - null, + null, info.Value.Value, true, "View Attribute Value"); diff --git a/Samples/ClientControls.Net4/Common/Client/BrowseNodeCtrl.cs b/Samples/ClientControls.Net4/Common/Client/BrowseNodeCtrl.cs index 9ebdc0287..ef1efbc87 100644 --- a/Samples/ClientControls.Net4/Common/Client/BrowseNodeCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/BrowseNodeCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -59,26 +61,28 @@ public BrowseNodeCtrl() #region Public Interface /// - /// Initializes the control with a root and a set of hierarchial reference types to follow. + /// Initializes the control with a root and a set of hierarchial reference types to follow. /// /// The session. /// The root of the hierarchy to browse. + /// The cancellation token. /// The reference types to follow. - public void Initialize( - Session session, + public async Task InitializeAsync( + ISession session, NodeId rootId, + CancellationToken ct, params NodeId[] referenceTypeIds) { - BrowseCTRL.Initialize(session, rootId, referenceTypeIds); + await BrowseCTRL.InitializeAsync(session, rootId, ct, referenceTypeIds); } /// /// Changes the session used by the control. /// /// The session. - public void ChangeSession(Session session) + public async Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { - BrowseCTRL.ChangeSession(session); + await BrowseCTRL.ChangeSessionAsync(session, ct); } /// @@ -102,9 +106,9 @@ public int SplitterDistance /// /// Gets or sets a flag that indicates whether the attributes should be displayed. /// - public bool AttributesListCollapsed + public bool AttributesListCollapsed { - get { return MainPN.Panel2Collapsed; } + get { return MainPN.Panel2Collapsed; } set { MainPN.Panel2Collapsed = value; } } @@ -175,10 +179,10 @@ public void RefreshSelection() /// /// Raised after a node is selected in the control. /// - public event EventHandler AfterSelect + public event EventHandler AfterSelect { add { BrowseCTRL.AfterSelect += value; } - remove { BrowseCTRL.AfterSelect -= value; } + remove { BrowseCTRL.AfterSelect -= value; } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.Designer.cs b/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.Designer.cs index 9879d0e3c..a9a6f2ce5 100644 --- a/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.Designer.cs @@ -86,8 +86,8 @@ private void InitializeComponent() this.BrowseTV.Name = "BrowseTV"; this.BrowseTV.Size = new System.Drawing.Size(1003, 569); this.BrowseTV.TabIndex = 2; - this.BrowseTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.BrowseTV_BeforeExpand); - this.BrowseTV.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.BrowseTV_AfterSelect); + this.BrowseTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.BrowseTV_BeforeExpandAsync); + this.BrowseTV.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.BrowseTV_AfterSelectAsync); // // BrowseTreeViewCtrl // diff --git a/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.cs index 341f2aa1e..5b65d1b35 100644 --- a/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -59,7 +61,7 @@ public BrowseTreeViewCtrl() #endregion #region Private Fields - private Session m_session; + private ISession m_session; private NodeId m_rootId; private NodeId[] m_referenceTypeIds; private NodeId m_selectedNodeId; @@ -75,14 +77,16 @@ public BrowseTreeViewCtrl() public AttributesListViewCtrl AttributesControl { get; set; } /// - /// Initializes the control with a root and a set of hierarchial reference types to follow. + /// Initializes the control with a root and a set of hierarchial reference types to follow. /// /// The session. /// The root of the hierarchy to browse. + /// The cancellation token. /// The reference types to follow. - public void Initialize( - Session session, + public async Task InitializeAsync( + ISession session, NodeId rootId, + CancellationToken ct, params NodeId[] referenceTypeIds) { // set default root. @@ -101,7 +105,7 @@ public void Initialize( m_referenceTypeIds = referenceTypeIds; // save session. - ChangeSession(session, true); + await ChangeSessionAsync(session, true); } /// @@ -116,21 +120,21 @@ public bool SelectNode(NodeId nodeId) /// Changes the session used by the control. /// /// The session. - public void ChangeSession(Session session) + public async Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { if (Object.ReferenceEquals(session, m_session)) { return; } - ChangeSession(session, false); + await ChangeSessionAsync(session, false, ct); } /// /// The view to use. /// - public ViewDescription View - { + public ViewDescription View + { get { return m_view; @@ -263,7 +267,7 @@ private bool SelectNode(TreeNodeCollection nodes, NodeId nodeId) /// /// Changes the session used by the control. /// - private void ChangeSession(Session session, bool refresh) + private async Task ChangeSessionAsync(ISession session, bool refresh, CancellationToken ct = default) { m_session = session; @@ -276,13 +280,13 @@ private void ChangeSession(Session session, bool refresh) if (m_session != null) { - INode node = m_session.NodeCache.Find(m_rootId); + INode node = await m_session.NodeCache.FindAsync(m_rootId, ct); if (node != null) { TreeNode root = new TreeNode(node.ToString()); - root.ImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, false); - root.SelectedImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, true); + root.ImageIndex = await ClientUtils.GetImageIndexAsync(m_session, node.NodeClass, node.TypeDefinitionId, false, ct); + root.SelectedImageIndex = await ClientUtils.GetImageIndexAsync(m_session, node.NodeClass, node.TypeDefinitionId, true, ct); ReferenceDescription reference = new ReferenceDescription(); reference.NodeId = node.NodeId; @@ -324,7 +328,7 @@ private void BrowseTV_DoubleClick(object sender, EventArgs e) /// /// Handles the AfterSelect event of the BrowseTV control. /// - private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) + private async void BrowseTV_AfterSelectAsync(object sender, TreeViewEventArgs e) { try { @@ -349,7 +353,7 @@ private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) if (AttributesControl != null) { - AttributesControl.ReadAttributes(m_selectedNodeId, true); + await AttributesControl.ReadAttributesAsync(m_selectedNodeId, true); } // raise event. @@ -364,7 +368,7 @@ private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) /// /// Handles the BeforeExpand event of the BrowseTV control. /// - private void BrowseTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) + private async void BrowseTV_BeforeExpandAsync(object sender, TreeViewCancelEventArgs e) { try { @@ -396,7 +400,7 @@ private void BrowseTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) // add the childen to the control. SortedDictionary dictionary = new SortedDictionary(); - ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, View, nodesToBrowse, false); + ReferenceDescriptionCollection references = await ClientUtils.BrowseAsync(m_session, View, nodesToBrowse, false); for (int ii = 0; references != null && ii < references.Count; ii++) { @@ -424,11 +428,11 @@ private void BrowseTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) { if (!m_typeImageMapping.ContainsKey((NodeId)reference.TypeDefinition)) { - List nodeIds = ClientUtils.TranslateBrowsePaths(m_session, (NodeId)reference.TypeDefinition, m_session.NamespaceUris, Opc.Ua.BrowseNames.Icon); + List nodeIds = await ClientUtils.TranslateBrowsePathsAsync(m_session, (NodeId)reference.TypeDefinition, m_session.NamespaceUris, default, Opc.Ua.BrowseNames.Icon); if (nodeIds.Count > 0 && nodeIds[0] != null) { - DataValue value = m_session.ReadValue(nodeIds[0]); + DataValue value = await m_session.ReadValueAsync(nodeIds[0]); byte[] bytes = value.Value as byte[]; if (bytes != null) @@ -451,8 +455,8 @@ private void BrowseTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) if (!m_typeImageMapping.TryGetValue((NodeId)reference.TypeDefinition, out index)) { - child.ImageIndex = ClientUtils.GetImageIndex(m_session, reference.NodeClass, reference.TypeDefinition, false); - child.SelectedImageIndex = ClientUtils.GetImageIndex(m_session, reference.NodeClass, reference.TypeDefinition, true); + child.ImageIndex = await ClientUtils.GetImageIndexAsync(m_session, reference.NodeClass, reference.TypeDefinition, false); + child.SelectedImageIndex = await ClientUtils.GetImageIndexAsync(m_session, reference.NodeClass, reference.TypeDefinition, true); } else { diff --git a/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.Designer.cs index 963e87097..78333a3be 100644 --- a/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.Designer.cs @@ -96,7 +96,7 @@ private void InitializeComponent() this.CallBTN.TabIndex = 1; this.CallBTN.Text = "Call"; this.CallBTN.UseVisualStyleBackColor = true; - this.CallBTN.Click += new System.EventHandler(this.CallBTN_Click); + this.CallBTN.Click += new System.EventHandler(this.CallBTN_ClickAsync); // // BackBTN // @@ -107,7 +107,7 @@ private void InitializeComponent() this.BackBTN.Text = "Back"; this.BackBTN.UseVisualStyleBackColor = true; this.BackBTN.Visible = false; - this.BackBTN.Click += new System.EventHandler(this.BackBTN_Click); + this.BackBTN.Click += new System.EventHandler(this.BackBTN_ClickAsync); // // CallRequestCTRL // diff --git a/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.cs b/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.cs index c6565f3ef..b054e12da 100644 --- a/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,8 @@ using System.ComponentModel; using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -53,34 +55,35 @@ public CallRequestDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; #endregion - + #region Public Interface /// /// Changes the session used for the call request. /// - public void ChangeSession(Session session) + public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { m_session = session; CallRequestCTRL.ChangeSession(session); + return Task.CompletedTask; } /// /// Sets the method called by the control. /// - public void SetMethod(NodeId objectId, NodeId methodId) + public async Task SetMethodAsync(NodeId objectId, NodeId methodId, CancellationToken ct = default) { StringBuilder buffer = new StringBuilder(); buffer.Append("Calling Method "); - buffer.Append(m_session.NodeCache.GetDisplayText(methodId)); + buffer.Append(await m_session.NodeCache.GetDisplayTextAsync(methodId, ct)); buffer.Append(" on Object "); - buffer.Append(m_session.NodeCache.GetDisplayText(objectId)); + buffer.Append(await m_session.NodeCache.GetDisplayTextAsync(objectId, ct)); this.Text = buffer.ToString(); - CallRequestCTRL.SetMethod(objectId, methodId); + await CallRequestCTRL.SetMethodAsync(objectId, methodId, ct); } #endregion @@ -88,11 +91,11 @@ public void SetMethod(NodeId objectId, NodeId methodId) #endregion #region Event Handlers - private void CallBTN_Click(object sender, EventArgs e) + private async void CallBTN_ClickAsync(object sender, EventArgs e) { try { - CallRequestCTRL.Call(); + await CallRequestCTRL.CallAsync(); CallBTN.Visible = false; BackBTN.Visible = true; } @@ -102,11 +105,11 @@ private void CallBTN_Click(object sender, EventArgs e) } } - private void BackBTN_Click(object sender, EventArgs e) + private async void BackBTN_ClickAsync(object sender, EventArgs e) { try { - CallRequestCTRL.Back(); + await CallRequestCTRL.BackAsync(); CallBTN.Visible = true; BackBTN.Visible = false; } diff --git a/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.Designer.cs b/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.Designer.cs index 0d84979eb..8195754e5 100644 --- a/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.Designer.cs @@ -84,7 +84,7 @@ private void InitializeComponent() this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(103, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // ImageList // @@ -125,7 +125,7 @@ private void InitializeComponent() this.ResultsDV.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.ResultsDV.Size = new System.Drawing.Size(779, 365); this.ResultsDV.TabIndex = 5; - this.ResultsDV.DoubleClick += new System.EventHandler(this.EditMI_Click); + this.ResultsDV.DoubleClick += new System.EventHandler(this.EditMI_ClickAsync); // // Icon // diff --git a/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.cs index 913ed3494..03cc78ff2 100644 --- a/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -53,7 +55,7 @@ public CallRequestListViewCtrl() InitializeComponent(); ResultsDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; - + m_dataset = new DataSet(); m_dataset.Tables.Add("Arguments"); @@ -70,7 +72,7 @@ public CallRequestListViewCtrl() #region Private Fields private DataSet m_dataset; - private Session m_session; + private ISession m_session; private NodeId m_objectId; private NodeId m_methodId; private Argument[] m_inputArguments; @@ -81,7 +83,7 @@ public CallRequestListViewCtrl() /// /// Changes the session used for the call request. /// - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { m_session = session; } @@ -89,29 +91,29 @@ public void ChangeSession(Session session) /// /// Sets the method for the call request. /// - public void SetMethod(NodeId objectId, NodeId methodId) + public async Task SetMethodAsync(NodeId objectId, NodeId methodId, CancellationToken ct = default) { if (objectId == null) { - new ArgumentNullException("objectId"); + throw new ArgumentNullException(nameof(objectId)); } if (methodId == null) { - new ArgumentNullException("methodId"); + throw new ArgumentNullException(nameof(methodId)); } m_objectId = objectId; m_methodId = methodId; - ReadArguments(methodId); - DisplayInputArguments(); + await ReadArgumentsAsync(methodId, ct); + await DisplayInputArgumentsAsync(ct); } /// /// Calls the method. /// - public void Call() + public async Task CallAsync(CancellationToken ct = default) { // build list of methods to call. CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection(); @@ -132,18 +134,19 @@ public void Call() methodsToCall.Add(methodToCall); // call the method. - CallMethodResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - ResponseHeader responseHeader = m_session.Call( + CallResponse response = await m_session.CallAsync( null, methodsToCall, - out results, - out diagnosticInfos); + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + CallMethodResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, methodsToCall); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, methodsToCall); - + for (int ii = 0; ii < results.Count; ii++) { // display any input argument errors. @@ -180,13 +183,13 @@ public void Call() if (results[ii].OutputArguments.Count > jj) { - UpdateRow(row, m_outputArguments[jj], results[ii].OutputArguments[jj], true); + await UpdateRowAsync(row, m_outputArguments[jj], results[ii].OutputArguments[jj], true, ct); } else { - UpdateRow(row, m_outputArguments[jj], Variant.Null, true); + await UpdateRowAsync(row, m_outputArguments[jj], Variant.Null, true, ct); } - + m_dataset.Tables[0].Rows.Add(row); } } @@ -196,9 +199,9 @@ public void Call() /// /// Returns the grid to the enter input arguments state. /// - public void Back() + public async Task BackAsync(CancellationToken ct = default) { - DisplayInputArguments(); + await DisplayInputArgumentsAsync(ct); // clear any selection. foreach (DataGridViewRow row in ResultsDV.Rows) @@ -212,20 +215,20 @@ public void Back() /// /// Displays the input arguments. /// - private void DisplayInputArguments() + private async Task DisplayInputArgumentsAsync(CancellationToken ct = default) { ResultCH.Visible = false; NoArgumentsLB.Visible = m_inputArguments == null || m_inputArguments.Length == 0; NoArgumentsLB.Text = "No input arguments to display."; m_dataset.Tables[0].Rows.Clear(); - + if (m_inputArguments != null) { foreach (Argument argument in m_inputArguments) { DataRow row = m_dataset.Tables[0].NewRow(); - UpdateRow(row, argument, new Variant(argument.Value), false); + await UpdateRowAsync(row, argument, new Variant(argument.Value), false, ct); m_dataset.Tables[0].Rows.Add(row); } } @@ -234,9 +237,9 @@ private void DisplayInputArguments() /// /// Updates the row with an argument and its value. /// - private void UpdateRow(DataRow row, Argument argument, Variant value, bool isOutputArgument) + private async Task UpdateRowAsync(DataRow row, Argument argument, Variant value, bool isOutputArgument, CancellationToken ct = default) { - string dataType = m_session.NodeCache.GetDisplayText(argument.DataType); + string dataType = await m_session.NodeCache.GetDisplayTextAsync(argument.DataType, ct); if (argument.ValueRank >= 0) { @@ -254,7 +257,7 @@ private void UpdateRow(DataRow row, Argument argument, Variant value, bool isOut /// /// Reads the arguments for the method. /// - private void ReadArguments(NodeId nodeId) + private async Task ReadArgumentsAsync(NodeId nodeId, CancellationToken ct = default) { m_inputArguments = null; m_outputArguments = null; @@ -274,7 +277,7 @@ private void ReadArguments(NodeId nodeId) nodesToBrowse.Add(nodeToBrowse); // find properties. - ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, null, nodesToBrowse, false); + ReferenceDescriptionCollection references = await ClientUtils.BrowseAsync(m_session, null, nodesToBrowse, false, ct); // build list of properties to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); @@ -309,16 +312,15 @@ private void ReadArguments(NodeId nodeId) } // read the arguments. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -354,7 +356,7 @@ private void ReadArguments(NodeId nodeId) #endregion #region Event Handlers - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -374,7 +376,7 @@ private void EditMI_Click(object sender, EventArgs e) if (result != null) { argument.Value = result; - UpdateRow(source.Row, argument, new Variant(result), false); + await UpdateRowAsync(source.Row, argument, new Variant(result), false); } break; diff --git a/Samples/ClientControls.Net4/Common/Client/ConnectServerCtrl.cs b/Samples/ClientControls.Net4/Common/Client/ConnectServerCtrl.cs index 5dfe0e88b..d3557b3bc 100644 --- a/Samples/ClientControls.Net4/Common/Client/ConnectServerCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/ConnectServerCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Drawing; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua.Client.ComplexTypes; @@ -55,7 +56,7 @@ public ConnectServerCtrl() #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private SessionReconnectHandler m_reconnectHandler; private CertificateValidationEventHandler m_CertificateValidation; private EventHandler m_ReconnectComplete; @@ -202,9 +203,9 @@ public ApplicationConfiguration Configuration } /// - /// The currently active session. + /// The currently active session. /// - public Session Session => m_session; + public ISession Session => m_session; /// /// The number of seconds between reconnect attempts (0 means reconnect is disabled). @@ -290,34 +291,26 @@ public void SetAvailableUrls(IList urls) /// Creates a new session. /// /// The new session object. - private async Task Connect( + private async Task ConnectInternalAsync( ITransportWaitingConnection connection, EndpointDescription endpointDescription, bool useSecurity, - uint sessionTimeout = 0) + uint sessionTimeout = 0, + CancellationToken ct = default) { // disconnect from existing session. - InternalDisconnect(); + await InternalDisconnectAsync(ct); // select the best endpoint. if (endpointDescription == null) { - endpointDescription = CoreClientUtils.SelectEndpoint(m_configuration, connection, useSecurity, DiscoverTimeout); + endpointDescription = await CoreClientUtils.SelectEndpointAsync(m_configuration, connection, useSecurity, DiscoverTimeout, ct); } EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); - m_session = await Session.Create( - m_configuration, - connection, - endpoint, - false, - !DisableDomainCheck, - (String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName, - sessionTimeout, - UserIdentity, - PreferredLocales); + m_session = await DefaultSessionFactory.Instance.CreateAsync(m_configuration, connection, endpoint, false, !DisableDomainCheck, (String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName, sessionTimeout, UserIdentity, PreferredLocales, ct); // set up keep alive callback. m_session.KeepAlive += Session_KeepAlive; @@ -332,7 +325,7 @@ private async Task Connect( { UpdateStatus(false, DateTime.Now, "Connected, loading complex type system."); var typeSystemLoader = new ComplexTypeSystem(m_session); - await typeSystemLoader.Load(); + await typeSystemLoader.LoadAsync(ct: ct); } catch (Exception e) { @@ -348,44 +341,21 @@ private async Task Connect( /// Creates a new session. /// /// The new session object. - public Task Connect() - { - // determine the URL that was selected. - string serverUrl = UrlCB.Text; - if (UrlCB.SelectedIndex >= 0) - { - serverUrl = (string)UrlCB.SelectedItem; - } - bool useSecurity = UseSecurityCK.Checked; - return Connect(serverUrl, useSecurity); - } - - /// - /// Creates a new session. - /// - /// The new session object. - private async Task Connect( + private async Task ConnectInternalAsync( string serverUrl, bool useSecurity, - uint sessionTimeout = 0) + uint sessionTimeout = 0, + CancellationToken ct = default) { // disconnect from existing session. - InternalDisconnect(); + await InternalDisconnectAsync(ct); // select the best endpoint. - var endpointDescription = CoreClientUtils.SelectEndpoint(m_configuration, serverUrl, useSecurity, DiscoverTimeout); + var endpointDescription = await CoreClientUtils.SelectEndpointAsync(m_configuration, serverUrl, useSecurity, DiscoverTimeout, ct); var endpointConfiguration = EndpointConfiguration.Create(m_configuration); var endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); - m_session = await Session.Create( - m_configuration, - endpoint, - false, - !DisableDomainCheck, - (String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName, - sessionTimeout == 0 ? DefaultSessionTimeout : sessionTimeout, - UserIdentity, - PreferredLocales); + m_session = await DefaultSessionFactory.Instance.CreateAsync(m_configuration, endpoint, false, !DisableDomainCheck, (String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName, sessionTimeout == 0 ? DefaultSessionTimeout : sessionTimeout, UserIdentity, PreferredLocales, ct); // set up keep alive callback. m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); @@ -400,7 +370,7 @@ private async Task Connect( { UpdateStatus(false, DateTime.Now, "Connected, loading complex type system."); var typeSystemLoader = new ComplexTypeSystem(m_session); - await typeSystemLoader.Load(); + await typeSystemLoader.LoadAsync(ct: ct); } catch (Exception e) { @@ -418,11 +388,11 @@ private async Task Connect( /// The URL of a server endpoint. /// Whether to use security. /// The new session object. - public Task ConnectAsync( + public Task ConnectAsync( string serverUrl = null, bool useSecurity = false, - uint sessionTimeout = 0 - ) + uint sessionTimeout = 0, + CancellationToken ct = default) { if (serverUrl == null) { @@ -443,7 +413,7 @@ public Task ConnectAsync( UpdateStatus(false, DateTime.Now, "Connecting [{0}]", serverUrl); - return Connect(serverUrl, useSecurity, sessionTimeout); + return ConnectInternalAsync(serverUrl, useSecurity, sessionTimeout, ct); } /// @@ -451,12 +421,12 @@ public Task ConnectAsync( /// /// /// - public async Task ConnectAsync( + public async Task ConnectAsync( ITransportWaitingConnection connection, bool useSecurity, int discoverTimeout = -1, - uint sessionTimeout = 0 - ) + uint sessionTimeout = 0, + CancellationToken ct = default) { if (connection.EndpointUrl == null) { @@ -472,27 +442,27 @@ public async Task ConnectAsync( { // Discovery uses the reverse connection and closes it // return and wait for next reverse hello - endpointDescription = CoreClientUtils.SelectEndpoint(m_configuration, connection, useSecurity, discoverTimeout); + endpointDescription = await CoreClientUtils.SelectEndpointAsync(m_configuration, connection, useSecurity, discoverTimeout, ct); m_endpoints[connection.EndpointUrl] = endpointDescription; return null; } - return await Connect(connection, endpointDescription, UseSecurityCK.Checked, sessionTimeout); + return await ConnectInternalAsync(connection, endpointDescription, UseSecurityCK.Checked, sessionTimeout, ct); } /// /// Disconnects from the server. /// - public Task DisconnectAsync() + public Task DisconnectAsync(CancellationToken ct = default) { UpdateStatus(false, DateTime.UtcNow, "Disconnected"); - return Task.Run(() => InternalDisconnect()); + return Task.Run(() => InternalDisconnectAsync(), ct); } /// /// Disconnects from the server. /// - private void InternalDisconnect() + private async Task InternalDisconnectAsync(CancellationToken ct = default) { // stop any reconnect operation. if (m_reconnectHandler != null) @@ -505,7 +475,7 @@ private void InternalDisconnect() if (m_session != null) { m_session.KeepAlive -= Session_KeepAlive; - m_session.Close(10000); + await m_session.CloseAsync(10000, ct); m_session = null; } @@ -521,7 +491,7 @@ public void Disconnect() UpdateStatus(false, DateTime.UtcNow, "Disconnected"); // stop any reconnect operation. - InternalDisconnect(); + InternalDisconnectAsync().GetAwaiter().GetResult(); } /// @@ -559,7 +529,7 @@ private void DoConnectComplete(object state) /// /// Finds the endpoint that best matches the current settings. /// - private EndpointDescription SelectEndpoint() + private async Task SelectEndpointAsync(CancellationToken ct = default) { try { @@ -574,7 +544,7 @@ private EndpointDescription SelectEndpoint() } // return the selected endpoint. - return CoreClientUtils.SelectEndpoint(m_configuration, discoveryUrl, UseSecurityCK.Checked, DiscoverTimeout); + return await CoreClientUtils.SelectEndpointAsync(m_configuration, discoveryUrl, UseSecurityCK.Checked, DiscoverTimeout, ct); } finally { @@ -683,19 +653,19 @@ private void Server_ConnectMI_Click(object sender, EventArgs e) UpdateStatus(false, DateTime.Now, "Connecting [{0}]", serverUrl); - Task.Run(() => { + Task.Run((Func)(async () => { try { - Connect(serverUrl, useSecurity).GetAwaiter().GetResult(); + await this.ConnectAsync(serverUrl, useSecurity); } catch (ServiceResultException sre) { if (sre.StatusCode == StatusCodes.BadCertificateHostNameInvalid) { - if (GuiUtils.HandleDomainCheckError(this.FindForm().Text, sre.Result)) + if (GuiUtils.HandleDomainCheckError(FindForm().Text, sre.Result)) { DisableDomainCheck = true; - }; + } } else { @@ -707,7 +677,7 @@ private void Server_ConnectMI_Click(object sender, EventArgs e) { ClientUtils.HandleException(this.Text, exception); } - }); + })); } /// diff --git a/Samples/ClientControls.Net4/Common/Client/EditAnnotationDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditAnnotationDlg.cs index 838e290eb..f97593057 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditAnnotationDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditAnnotationDlg.cs @@ -56,14 +56,14 @@ public EditAnnotationDlg() #endregion #region Private Fields - private Session m_session; + private ISession m_session; #endregion #region Public Interface /// /// Prompts the user to edit an annotation. /// - public Annotation ShowDialog(Session session, Annotation annotation, string caption) + public Annotation ShowDialog(ISession session, Annotation annotation, string caption) { if (caption != null) { diff --git a/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.Designer.cs index 220fd12ed..17916465b 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.Designer.cs @@ -118,7 +118,7 @@ private void InitializeComponent() this.UpdateBTN.TabIndex = 0; this.UpdateBTN.Text = "Update"; this.UpdateBTN.UseVisualStyleBackColor = true; - this.UpdateBTN.Click += new System.EventHandler(this.UpdateBTN_Click); + this.UpdateBTN.Click += new System.EventHandler(this.UpdateBTN_ClickAsync); // // RefreshBTN // @@ -129,7 +129,7 @@ private void InitializeComponent() this.RefreshBTN.TabIndex = 3; this.RefreshBTN.Text = "Refresh"; this.RefreshBTN.UseVisualStyleBackColor = true; - this.RefreshBTN.Click += new System.EventHandler(this.RefreshBTN_Click); + this.RefreshBTN.Click += new System.EventHandler(this.RefreshBTN_ClickAsync); // // MainPN // diff --git a/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.cs b/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.cs index e68b4d882..3198d13d8 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using System.Xml.Serialization; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -56,7 +58,7 @@ public EditComplexValue2Dlg() #endregion #region Private Fields - private Session m_session; + private ISession m_session; private NodeId m_variableId; private Variant m_value; private bool m_textChanged; @@ -67,7 +69,7 @@ public EditComplexValue2Dlg() /// /// Prompts the user to edit a value. /// - public Variant ShowDialog(Session session, NodeId variableId, Variant value, string caption) + public async Task ShowDialogAsync(ISession session, NodeId variableId, Variant value, string caption, CancellationToken ct = default) { if (caption != null) { @@ -77,7 +79,7 @@ public Variant ShowDialog(Session session, NodeId variableId, Variant value, str m_session = session; m_variableId = variableId; - SetValue(value); + await SetValueAsync(value, ct); if (ShowDialog() != DialogResult.OK) { @@ -91,7 +93,7 @@ public Variant ShowDialog(Session session, NodeId variableId, Variant value, str /// /// Sets the value shown in the control. /// - private void SetValue(Variant value) + private async Task SetValueAsync(Variant value, CancellationToken ct = default) { ValueTB.ForeColor = Color.Empty; ValueTB.Font = new Font(ValueTB.Font, FontStyle.Regular); @@ -115,7 +117,7 @@ private void SetValue(Variant value) } m_value = new Variant(value.Value, sourceType); - + // display value as text. StringBuilder buffer = new StringBuilder(); XmlWriter writer = XmlWriter.Create(buffer, new XmlWriterSettings() { Indent = true, OmitXmlDeclaration = true }); @@ -159,7 +161,7 @@ private void SetValue(Variant value) } // check if the encoding is known. - IObject encodingNode = m_session.NodeCache.Find(encodingId) as IObject; + IObject encodingNode = await m_session.NodeCache.FindAsync(encodingId, ct) as IObject; if (encodingNode == null) { @@ -174,7 +176,7 @@ private void SetValue(Variant value) } else { - EncodingCB.Text = m_session.NodeCache.GetDisplayText(encodingNode); + EncodingCB.Text = await m_session.NodeCache.GetDisplayTextAsync(encodingNode, ct); } m_encodingName = encodingNode.BrowseName; @@ -182,7 +184,7 @@ private void SetValue(Variant value) // find the data type for the encoding. IDataType dataTypeNode = null; - foreach (INode node in m_session.NodeCache.Find(encodingNode.NodeId, Opc.Ua.ReferenceTypeIds.HasEncoding, true, false)) + foreach (INode node in await m_session.NodeCache.FindAsync(encodingNode.NodeId, Opc.Ua.ReferenceTypeIds.HasEncoding, true, false, ct)) { dataTypeNode = node as IDataType; @@ -199,19 +201,19 @@ private void SetValue(Variant value) } // update data type display. - DataTypeTB.Text = m_session.NodeCache.GetDisplayText(dataTypeNode); + DataTypeTB.Text = await m_session.NodeCache.GetDisplayTextAsync(dataTypeNode, ct); DataTypeTB.Tag = dataTypeNode; // update encoding drop down. EncodingCB.DropDownItems.Clear(); - foreach (INode node in m_session.NodeCache.Find(dataTypeNode.NodeId, Opc.Ua.ReferenceTypeIds.HasEncoding, false, false)) + foreach (INode node in await m_session.NodeCache.FindAsync(dataTypeNode.NodeId, Opc.Ua.ReferenceTypeIds.HasEncoding, false, false, ct)) { IObject encodingNode2 = node as IObject; if (encodingNode2 != null) { - ToolStripMenuItem item = new ToolStripMenuItem(m_session.NodeCache.GetDisplayText(encodingNode2)); + ToolStripMenuItem item = new ToolStripMenuItem(await m_session.NodeCache.GetDisplayTextAsync(encodingNode2, ct)); item.Tag = encodingNode2; item.Click += new EventHandler(EncodingCB_Item_Click); EncodingCB.DropDownItems.Add(item); @@ -231,12 +233,15 @@ private Variant GetValue() return m_value; } - XmlDocument document = new XmlDocument(); - document.InnerXml = ValueTB.Text; - + var document = new XmlDocument { XmlResolver = null }; + using (var reader = XmlReader.Create(ValueTB.Text, new XmlReaderSettings() { XmlResolver = null })) + { + document.Load(reader); + } + // find the first element. XmlElement element = null; - + for (XmlNode node = document.DocumentElement.FirstChild; node != null; node = node.NextSibling) { element = node as XmlElement; @@ -290,7 +295,7 @@ private void EncodingCB_Item_Click(object sender, EventArgs e) } } - private void RefreshBTN_Click(object sender, EventArgs e) + private async void RefreshBTN_ClickAsync(object sender, EventArgs e) { try { @@ -304,16 +309,15 @@ private void RefreshBTN_Click(object sender, EventArgs e) nodesToRead.Add(nodeToRead); // read the attributes. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out results, - out diagnosticInfos); + default); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -327,7 +331,7 @@ private void RefreshBTN_Click(object sender, EventArgs e) return; } - SetValue(results[0].WrappedValue); + await SetValueAsync(results[0].WrappedValue); } catch (Exception exception) { @@ -335,7 +339,7 @@ private void RefreshBTN_Click(object sender, EventArgs e) } } - private void UpdateBTN_Click(object sender, EventArgs e) + private async void UpdateBTN_ClickAsync(object sender, EventArgs e) { try { @@ -349,14 +353,14 @@ private void UpdateBTN_Click(object sender, EventArgs e) nodesToWrite.Add(nodeToWrite); // read the attributes. - StatusCodeCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_session.Write( + WriteResponse response = await m_session.WriteAsync( null, nodesToWrite, - out results, - out diagnosticInfos); + default); + + ResponseHeader responseHeader = response.ResponseHeader; + StatusCodeCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); diff --git a/Samples/ClientControls.Net4/Common/Client/EditComplexValueCtrl.cs b/Samples/ClientControls.Net4/Common/Client/EditComplexValueCtrl.cs index 06b72364c..c11634cd7 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditComplexValueCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditComplexValueCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using System.Windows.Forms; using System.Xml; using System.Reflection; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls.Common { @@ -70,14 +72,14 @@ public EditComplexValueCtrl() #region Private Fields private DataSet m_dataset; - private Session m_session; + private ISession m_session; private AccessInfo m_value; private bool m_readOnly; private int m_maxDisplayTextLength; private event EventHandler m_ValueChanged; #endregion - private class AccessInfo + private sealed class AccessInfo { public AccessInfo Parent { get; set; } public PropertyInfo PropertyInfo { get; set; } @@ -210,7 +212,7 @@ public event EventHandler ValueChanged /// /// Changes the session used for editing the value. /// - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { m_session = session; } @@ -223,8 +225,8 @@ public void Back() if (!CanGoBack) { return; - } - + } + NavigationMENU_Click(NavigationMENU.Items[NavigationMENU.Items.Count - 2], null); } @@ -379,7 +381,7 @@ public void SetType(BuiltInType builtInType) { return; } - + AccessInfo info = NavigationMENU.Items[NavigationMENU.Items.Count - 1].Tag as AccessInfo; TypeInfo currentType = info.TypeInfo; @@ -410,9 +412,9 @@ public void SetType(BuiltInType builtInType) } } } - + TypeInfo targetType = new TypeInfo(builtInType, currentType.ValueRank); - object newValue = Convert(currentValue, currentType, targetType, true); + object newValue = Convert(currentValue, currentType, targetType, true); NavigationMENU.Items.RemoveAt(NavigationMENU.Items.Count - 1); @@ -451,12 +453,13 @@ private object Convert(object oldValue, TypeInfo oldType, TypeInfo newType, bool /// /// Displays the value in the control. /// - public void ShowValue( + public async Task ShowValueAsync( NodeId nodeId, uint attributeId, - string name, - object value, - bool readOnly) + string name, + object value, + bool readOnly, + CancellationToken ct = default) { m_readOnly = readOnly; NavigationMENU.Items.Clear(); @@ -480,7 +483,7 @@ public void ShowValue( // determine the expected data type for value attributes. else if (!NodeId.IsNull(nodeId)) { - IVariableBase variable = m_session.NodeCache.Find(nodeId) as IVariableBase; + IVariableBase variable = await m_session.NodeCache.FindAsync(nodeId, ct) as IVariableBase; if (variable != null) { @@ -602,7 +605,7 @@ public void ShowValue( { name = expectedType.ToString(); } - + AccessInfo info = new AccessInfo(); info.Value = Utils.Clone(value); info.TypeInfo = expectedType; @@ -933,7 +936,7 @@ private void ShowIndexedValue(AccessInfo info) DataRow row = m_dataset.Tables[0].NewRow(); StringBuilder buffer = new StringBuilder(); - buffer.Append("["); + buffer.Append('['); if (info.Indexes != null) { @@ -941,14 +944,14 @@ private void ShowIndexedValue(AccessInfo info) { if (ii > 0) { - buffer.Append(","); + buffer.Append(','); } buffer.Append(info.Indexes[ii]); } } - buffer.Append("]"); + buffer.Append(']'); info.Name = buffer.ToString(); row[0] = info; @@ -1341,7 +1344,7 @@ private bool IsSimpleValue(AccessInfo info) { return false; } - + switch (typeInfo.BuiltInType) { case BuiltInType.String: @@ -1382,7 +1385,7 @@ private void NavigationMENU_Click(object sender, EventArgs e) if (item != null) { // remove all menu items appearing after the selected item. - for (int ii = NavigationMENU.Items.Count-1; ii >= 0; ii--) + for (int ii = NavigationMENU.Items.Count - 1; ii >= 0; ii--) { ToolStripItem target = NavigationMENU.Items[ii]; NavigationMENU.Items.Remove(target); @@ -1417,7 +1420,7 @@ private void ValuesDV_DoubleClick(object sender, EventArgs e) AccessInfo info = (AccessInfo)source.Row[0]; ShowValue(info); } - + break; } } @@ -1513,7 +1516,7 @@ private void UpdateParent(AccessInfo info) int count = 0; int block = 1; - for (int ii = info.Indexes.Length-1; ii >= 0 ; ii--) + for (int ii = info.Indexes.Length - 1; ii >= 0; ii--) { count += info.Indexes[ii] * block; block *= matrix.Dimensions[ii]; diff --git a/Samples/ClientControls.Net4/Common/Client/EditComplexValueDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditComplexValueDlg.cs index 53221aa8e..ea64e4d61 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditComplexValueDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditComplexValueDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,8 @@ using System.Text; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -58,7 +60,7 @@ public EditComplexValueDlg() SetTypeCB.SelectedItem = BuiltInType.String; } #endregion - + #region Private Fields #endregion @@ -66,14 +68,15 @@ public EditComplexValueDlg() /// /// Prompts the user to view or edit the value. /// - public object ShowDialog( - Session session, + public async Task ShowDialogAsync( + ISession session, NodeId nodeId, uint attributeId, - string name, - object value, + string name, + object value, bool readOnly, - string caption) + string caption, + CancellationToken ct = default) { if (!String.IsNullOrEmpty(caption)) { @@ -83,7 +86,7 @@ public object ShowDialog( OkBTN.Visible = !readOnly; ValueCTRL.ChangeSession(session); - ValueCTRL.ShowValue(nodeId, attributeId, name, value, readOnly); + await ValueCTRL.ShowValueAsync(nodeId, attributeId, name, value, readOnly, ct); if (base.ShowDialog() != DialogResult.OK) { @@ -92,12 +95,12 @@ public object ShowDialog( return ValueCTRL.GetValue(); } - + /// /// Prompts the user to edit the value. /// public object ShowDialog( - Session session, + ISession session, string name, NodeId dataType, int valueRank, @@ -152,7 +155,7 @@ public object ShowDialog( /// /// Changes the session used. /// - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { ValueCTRL.ChangeSession(session); } @@ -160,13 +163,14 @@ public void ChangeSession(Session session) /// /// Updates the value shown in the control. /// - public void UpdateValue( + public Task UpdateValueAsync( NodeId nodeId, uint attributeId, string name, - object value) + object value, + CancellationToken ct = default) { - ValueCTRL.ShowValue(nodeId, attributeId, name, value, true); + return ValueCTRL.ShowValueAsync(nodeId, attributeId, name, value, true, ct); } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.Designer.cs index 2467af4db..db763e39a 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.Designer.cs @@ -97,9 +97,10 @@ private void InitializeComponent() // this.CancelBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.CancelBTN.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.CancelBTN.Location = new System.Drawing.Point(293, 4); + this.CancelBTN.Location = new System.Drawing.Point(440, 6); + this.CancelBTN.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.CancelBTN.Name = "CancelBTN"; - this.CancelBTN.Size = new System.Drawing.Size(75, 23); + this.CancelBTN.Size = new System.Drawing.Size(112, 35); this.CancelBTN.TabIndex = 0; this.CancelBTN.Text = "Cancel"; this.CancelBTN.UseVisualStyleBackColor = true; @@ -107,9 +108,10 @@ private void InitializeComponent() // OkBTN // this.OkBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.OkBTN.Location = new System.Drawing.Point(3, 4); + this.OkBTN.Location = new System.Drawing.Point(4, 6); + this.OkBTN.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.OkBTN.Name = "OkBTN"; - this.OkBTN.Size = new System.Drawing.Size(75, 23); + this.OkBTN.Size = new System.Drawing.Size(112, 35); this.OkBTN.TabIndex = 1; this.OkBTN.Text = "OK"; this.OkBTN.UseVisualStyleBackColor = true; @@ -120,9 +122,10 @@ private void InitializeComponent() this.BottomPN.Controls.Add(this.OkBTN); this.BottomPN.Controls.Add(this.CancelBTN); this.BottomPN.Dock = System.Windows.Forms.DockStyle.Bottom; - this.BottomPN.Location = new System.Drawing.Point(0, 285); + this.BottomPN.Location = new System.Drawing.Point(0, 439); + this.BottomPN.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.BottomPN.Name = "BottomPN"; - this.BottomPN.Size = new System.Drawing.Size(371, 30); + this.BottomPN.Size = new System.Drawing.Size(556, 46); this.BottomPN.TabIndex = 0; // // MainPN @@ -132,8 +135,9 @@ private void InitializeComponent() this.MainPN.Controls.Add(this.ControlsPN); this.MainPN.Dock = System.Windows.Forms.DockStyle.Fill; this.MainPN.Location = new System.Drawing.Point(0, 0); + this.MainPN.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.MainPN.Name = "MainPN"; - this.MainPN.Size = new System.Drawing.Size(371, 285); + this.MainPN.Size = new System.Drawing.Size(556, 439); this.MainPN.TabIndex = 1; // // ControlsPN @@ -169,6 +173,7 @@ private void InitializeComponent() this.ControlsPN.Controls.Add(this.DiscardOldestCK, 1, 7); this.ControlsPN.Dock = System.Windows.Forms.DockStyle.Fill; this.ControlsPN.Location = new System.Drawing.Point(0, 0); + this.ControlsPN.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ControlsPN.Name = "ControlsPN"; this.ControlsPN.RowCount = 12; this.ControlsPN.RowStyles.Add(new System.Windows.Forms.RowStyle()); @@ -183,8 +188,8 @@ private void InitializeComponent() this.ControlsPN.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.ControlsPN.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.ControlsPN.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.ControlsPN.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); - this.ControlsPN.Size = new System.Drawing.Size(371, 285); + this.ControlsPN.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 31F)); + this.ControlsPN.Size = new System.Drawing.Size(556, 439); this.ControlsPN.TabIndex = 0; // // TriggerTypeCB @@ -193,18 +198,20 @@ private void InitializeComponent() | System.Windows.Forms.AnchorStyles.Left))); this.TriggerTypeCB.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.TriggerTypeCB.FormattingEnabled = true; - this.TriggerTypeCB.Location = new System.Drawing.Point(97, 261); + this.TriggerTypeCB.Location = new System.Drawing.Point(143, 369); + this.TriggerTypeCB.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.TriggerTypeCB.Name = "TriggerTypeCB"; - this.TriggerTypeCB.Size = new System.Drawing.Size(138, 21); + this.TriggerTypeCB.Size = new System.Drawing.Size(205, 28); this.TriggerTypeCB.TabIndex = 22; // // TriggerTypeLB // this.TriggerTypeLB.AutoSize = true; this.TriggerTypeLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.TriggerTypeLB.Location = new System.Drawing.Point(3, 258); + this.TriggerTypeLB.Location = new System.Drawing.Point(4, 364); + this.TriggerTypeLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.TriggerTypeLB.Name = "TriggerTypeLB"; - this.TriggerTypeLB.Size = new System.Drawing.Size(88, 27); + this.TriggerTypeLB.Size = new System.Drawing.Size(131, 38); this.TriggerTypeLB.TabIndex = 21; this.TriggerTypeLB.Text = "Trigger Type"; this.TriggerTypeLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -213,23 +220,25 @@ private void InitializeComponent() // this.DeadbandValueLB.AutoSize = true; this.DeadbandValueLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.DeadbandValueLB.Location = new System.Drawing.Point(3, 232); + this.DeadbandValueLB.Location = new System.Drawing.Point(4, 328); + this.DeadbandValueLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.DeadbandValueLB.Name = "DeadbandValueLB"; - this.DeadbandValueLB.Size = new System.Drawing.Size(88, 26); + this.DeadbandValueLB.Size = new System.Drawing.Size(131, 36); this.DeadbandValueLB.TabIndex = 19; this.DeadbandValueLB.Text = "Deadband Value"; this.DeadbandValueLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // DeadbandValueUP // - this.DeadbandValueUP.Location = new System.Drawing.Point(97, 235); + this.DeadbandValueUP.Location = new System.Drawing.Point(143, 333); + this.DeadbandValueUP.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.DeadbandValueUP.Maximum = new decimal(new int[] { 0, 1, 0, 0}); this.DeadbandValueUP.Name = "DeadbandValueUP"; - this.DeadbandValueUP.Size = new System.Drawing.Size(138, 20); + this.DeadbandValueUP.Size = new System.Drawing.Size(207, 26); this.DeadbandValueUP.TabIndex = 20; // // DeadbandTypeCB @@ -238,9 +247,10 @@ private void InitializeComponent() | System.Windows.Forms.AnchorStyles.Left))); this.DeadbandTypeCB.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.DeadbandTypeCB.FormattingEnabled = true; - this.DeadbandTypeCB.Location = new System.Drawing.Point(97, 208); + this.DeadbandTypeCB.Location = new System.Drawing.Point(143, 295); + this.DeadbandTypeCB.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.DeadbandTypeCB.Name = "DeadbandTypeCB"; - this.DeadbandTypeCB.Size = new System.Drawing.Size(138, 21); + this.DeadbandTypeCB.Size = new System.Drawing.Size(205, 28); this.DeadbandTypeCB.TabIndex = 18; // // MonitoringModeCB @@ -249,18 +259,20 @@ private void InitializeComponent() | System.Windows.Forms.AnchorStyles.Left))); this.MonitoringModeCB.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.MonitoringModeCB.FormattingEnabled = true; - this.MonitoringModeCB.Location = new System.Drawing.Point(97, 109); + this.MonitoringModeCB.Location = new System.Drawing.Point(143, 154); + this.MonitoringModeCB.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.MonitoringModeCB.Name = "MonitoringModeCB"; - this.MonitoringModeCB.Size = new System.Drawing.Size(138, 21); + this.MonitoringModeCB.Size = new System.Drawing.Size(205, 28); this.MonitoringModeCB.TabIndex = 10; // // MonitoringModeLB // this.MonitoringModeLB.AutoSize = true; this.MonitoringModeLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.MonitoringModeLB.Location = new System.Drawing.Point(3, 106); + this.MonitoringModeLB.Location = new System.Drawing.Point(4, 149); + this.MonitoringModeLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.MonitoringModeLB.Name = "MonitoringModeLB"; - this.MonitoringModeLB.Size = new System.Drawing.Size(88, 27); + this.MonitoringModeLB.Size = new System.Drawing.Size(131, 38); this.MonitoringModeLB.TabIndex = 9; this.MonitoringModeLB.Text = "Monitoring Mode"; this.MonitoringModeLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -269,9 +281,10 @@ private void InitializeComponent() // this.DeadbandTypeLB.AutoSize = true; this.DeadbandTypeLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.DeadbandTypeLB.Location = new System.Drawing.Point(3, 205); + this.DeadbandTypeLB.Location = new System.Drawing.Point(4, 290); + this.DeadbandTypeLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.DeadbandTypeLB.Name = "DeadbandTypeLB"; - this.DeadbandTypeLB.Size = new System.Drawing.Size(88, 27); + this.DeadbandTypeLB.Size = new System.Drawing.Size(131, 38); this.DeadbandTypeLB.TabIndex = 17; this.DeadbandTypeLB.Text = "Deadband Type"; this.DeadbandTypeLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -280,9 +293,10 @@ private void InitializeComponent() // this.DiscardOldestLB.AutoSize = true; this.DiscardOldestLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.DiscardOldestLB.Location = new System.Drawing.Point(3, 185); + this.DiscardOldestLB.Location = new System.Drawing.Point(4, 259); + this.DiscardOldestLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.DiscardOldestLB.Name = "DiscardOldestLB"; - this.DiscardOldestLB.Size = new System.Drawing.Size(88, 20); + this.DiscardOldestLB.Size = new System.Drawing.Size(131, 31); this.DiscardOldestLB.TabIndex = 15; this.DiscardOldestLB.Text = "Discard Oldest"; this.DiscardOldestLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -291,9 +305,10 @@ private void InitializeComponent() // this.QueueSizeLB.AutoSize = true; this.QueueSizeLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.QueueSizeLB.Location = new System.Drawing.Point(3, 159); + this.QueueSizeLB.Location = new System.Drawing.Point(4, 223); + this.QueueSizeLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.QueueSizeLB.Name = "QueueSizeLB"; - this.QueueSizeLB.Size = new System.Drawing.Size(88, 26); + this.QueueSizeLB.Size = new System.Drawing.Size(131, 36); this.QueueSizeLB.TabIndex = 13; this.QueueSizeLB.Text = "Queue Size"; this.QueueSizeLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -302,9 +317,10 @@ private void InitializeComponent() // this.SamplingIntervalLB.AutoSize = true; this.SamplingIntervalLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.SamplingIntervalLB.Location = new System.Drawing.Point(3, 133); + this.SamplingIntervalLB.Location = new System.Drawing.Point(4, 187); + this.SamplingIntervalLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.SamplingIntervalLB.Name = "SamplingIntervalLB"; - this.SamplingIntervalLB.Size = new System.Drawing.Size(88, 26); + this.SamplingIntervalLB.Size = new System.Drawing.Size(131, 36); this.SamplingIntervalLB.TabIndex = 11; this.SamplingIntervalLB.Text = "Sampling Interval"; this.SamplingIntervalLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -314,9 +330,10 @@ private void InitializeComponent() this.NodeLB.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.NodeLB.AutoSize = true; - this.NodeLB.Location = new System.Drawing.Point(3, 0); + this.NodeLB.Location = new System.Drawing.Point(4, 0); + this.NodeLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.NodeLB.Name = "NodeLB"; - this.NodeLB.Size = new System.Drawing.Size(33, 26); + this.NodeLB.Size = new System.Drawing.Size(47, 37); this.NodeLB.TabIndex = 0; this.NodeLB.Text = "Node"; this.NodeLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -324,9 +341,10 @@ private void InitializeComponent() // IndexRangeTB // this.IndexRangeTB.Dock = System.Windows.Forms.DockStyle.Fill; - this.IndexRangeTB.Location = new System.Drawing.Point(97, 56); + this.IndexRangeTB.Location = new System.Drawing.Point(143, 80); + this.IndexRangeTB.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.IndexRangeTB.Name = "IndexRangeTB"; - this.IndexRangeTB.Size = new System.Drawing.Size(247, 20); + this.IndexRangeTB.Size = new System.Drawing.Size(373, 26); this.IndexRangeTB.TabIndex = 6; // // AttributeCB @@ -335,18 +353,20 @@ private void InitializeComponent() | System.Windows.Forms.AnchorStyles.Left))); this.AttributeCB.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.AttributeCB.FormattingEnabled = true; - this.AttributeCB.Location = new System.Drawing.Point(97, 29); + this.AttributeCB.Location = new System.Drawing.Point(143, 42); + this.AttributeCB.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.AttributeCB.Name = "AttributeCB"; - this.AttributeCB.Size = new System.Drawing.Size(138, 21); + this.AttributeCB.Size = new System.Drawing.Size(205, 28); this.AttributeCB.TabIndex = 4; // // AttributeLB // this.AttributeLB.AutoSize = true; this.AttributeLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.AttributeLB.Location = new System.Drawing.Point(3, 26); + this.AttributeLB.Location = new System.Drawing.Point(4, 37); + this.AttributeLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.AttributeLB.Name = "AttributeLB"; - this.AttributeLB.Size = new System.Drawing.Size(88, 27); + this.AttributeLB.Size = new System.Drawing.Size(131, 38); this.AttributeLB.TabIndex = 3; this.AttributeLB.Text = "Attribute"; this.AttributeLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -355,9 +375,10 @@ private void InitializeComponent() // this.IndexRangeLB.AutoSize = true; this.IndexRangeLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.IndexRangeLB.Location = new System.Drawing.Point(3, 53); + this.IndexRangeLB.Location = new System.Drawing.Point(4, 75); + this.IndexRangeLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.IndexRangeLB.Name = "IndexRangeLB"; - this.IndexRangeLB.Size = new System.Drawing.Size(88, 26); + this.IndexRangeLB.Size = new System.Drawing.Size(131, 36); this.IndexRangeLB.TabIndex = 5; this.IndexRangeLB.Text = "Index Range"; this.IndexRangeLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -366,9 +387,10 @@ private void InitializeComponent() // this.DataEncodingLB.AutoSize = true; this.DataEncodingLB.Dock = System.Windows.Forms.DockStyle.Fill; - this.DataEncodingLB.Location = new System.Drawing.Point(3, 79); + this.DataEncodingLB.Location = new System.Drawing.Point(4, 111); + this.DataEncodingLB.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.DataEncodingLB.Name = "DataEncodingLB"; - this.DataEncodingLB.Size = new System.Drawing.Size(88, 27); + this.DataEncodingLB.Size = new System.Drawing.Size(131, 38); this.DataEncodingLB.TabIndex = 7; this.DataEncodingLB.Text = "Data Encoding"; this.DataEncodingLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -379,45 +401,48 @@ private void InitializeComponent() | System.Windows.Forms.AnchorStyles.Left))); this.DataEncodingCB.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.DataEncodingCB.FormattingEnabled = true; - this.DataEncodingCB.Location = new System.Drawing.Point(97, 82); + this.DataEncodingCB.Location = new System.Drawing.Point(143, 116); + this.DataEncodingCB.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.DataEncodingCB.Name = "DataEncodingCB"; - this.DataEncodingCB.Size = new System.Drawing.Size(138, 21); + this.DataEncodingCB.Size = new System.Drawing.Size(205, 28); this.DataEncodingCB.TabIndex = 8; // // NodeTB // this.NodeTB.Dock = System.Windows.Forms.DockStyle.Fill; - this.NodeTB.Location = new System.Drawing.Point(97, 3); + this.NodeTB.Location = new System.Drawing.Point(143, 5); + this.NodeTB.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.NodeTB.Name = "NodeTB"; this.NodeTB.ReadOnly = true; - this.NodeTB.Size = new System.Drawing.Size(247, 20); + this.NodeTB.Size = new System.Drawing.Size(373, 26); this.NodeTB.TabIndex = 1; // // NodeBTN // - this.NodeBTN.Location = new System.Drawing.Point(347, 0); + this.NodeBTN.Location = new System.Drawing.Point(520, 0); this.NodeBTN.Margin = new System.Windows.Forms.Padding(0); this.NodeBTN.Name = "NodeBTN"; this.NodeBTN.NodeControl = this.NodeTB; this.NodeBTN.ReferenceTypeIds = null; this.NodeBTN.RootId = null; - this.NodeBTN.SelectedNode = null; + this.NodeBTN.ClearSelectedNode(); this.NodeBTN.SelectedReference = null; this.NodeBTN.Session = null; - this.NodeBTN.Size = new System.Drawing.Size(24, 24); + this.NodeBTN.Size = new System.Drawing.Size(36, 37); this.NodeBTN.TabIndex = 2; this.NodeBTN.View = null; // // QueueSizeUP // - this.QueueSizeUP.Location = new System.Drawing.Point(97, 162); + this.QueueSizeUP.Location = new System.Drawing.Point(143, 228); + this.QueueSizeUP.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.QueueSizeUP.Maximum = new decimal(new int[] { 0, 1, 0, 0}); this.QueueSizeUP.Name = "QueueSizeUP"; - this.QueueSizeUP.Size = new System.Drawing.Size(138, 20); + this.QueueSizeUP.Size = new System.Drawing.Size(207, 26); this.QueueSizeUP.TabIndex = 14; // // SamplingIntervalUP @@ -427,7 +452,8 @@ private void InitializeComponent() 0, 0, 0}); - this.SamplingIntervalUP.Location = new System.Drawing.Point(97, 136); + this.SamplingIntervalUP.Location = new System.Drawing.Point(143, 192); + this.SamplingIntervalUP.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.SamplingIntervalUP.Maximum = new decimal(new int[] { 0, 1, @@ -439,7 +465,7 @@ private void InitializeComponent() 0, -2147483648}); this.SamplingIntervalUP.Name = "SamplingIntervalUP"; - this.SamplingIntervalUP.Size = new System.Drawing.Size(138, 20); + this.SamplingIntervalUP.Size = new System.Drawing.Size(207, 26); this.SamplingIntervalUP.TabIndex = 12; this.SamplingIntervalUP.ThousandsSeparator = true; // @@ -448,23 +474,25 @@ private void InitializeComponent() this.DiscardOldestCK.AutoSize = true; this.DiscardOldestCK.Checked = true; this.DiscardOldestCK.CheckState = System.Windows.Forms.CheckState.Checked; - this.DiscardOldestCK.Location = new System.Drawing.Point(97, 188); + this.DiscardOldestCK.Location = new System.Drawing.Point(143, 264); + this.DiscardOldestCK.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.DiscardOldestCK.Name = "DiscardOldestCK"; - this.DiscardOldestCK.Size = new System.Drawing.Size(15, 14); + this.DiscardOldestCK.Size = new System.Drawing.Size(22, 21); this.DiscardOldestCK.TabIndex = 16; this.DiscardOldestCK.UseVisualStyleBackColor = true; // // EditMonitoredItemDlg // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.CancelButton = this.CancelBTN; - this.ClientSize = new System.Drawing.Size(371, 315); + this.ClientSize = new System.Drawing.Size(556, 485); this.Controls.Add(this.MainPN); this.Controls.Add(this.BottomPN); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "EditMonitoredItemDlg"; diff --git a/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.cs index 168a45cad..d102982c9 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,8 @@ using System.Text; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -51,7 +53,7 @@ public EditMonitoredItemDlg() this.Icon = ClientUtils.GetAppIcon(); // add the attributes in numerical order. - foreach (uint attributeId in Attributes.GetIdentifiers()) + foreach (uint attributeId in Attributes.Identifiers) { AttributeCB.Items.Add(Attributes.GetBrowseName(attributeId)); } @@ -62,7 +64,7 @@ public EditMonitoredItemDlg() MonitoringModeCB.Items.Add(MonitoringMode.Sampling); MonitoringModeCB.Items.Add(MonitoringMode.Disabled); MonitoringModeCB.SelectedIndex = 0; - + DeadbandTypeCB.Items.Add(DeadbandType.None); DeadbandTypeCB.Items.Add(DeadbandType.Absolute); DeadbandTypeCB.Items.Add(DeadbandType.Percent); @@ -79,7 +81,7 @@ public EditMonitoredItemDlg() /// /// Stores information about a data encoding. /// - private class EncodingInfo + private sealed class EncodingInfo { public QualifiedName EncodingName; @@ -94,7 +96,7 @@ public override string ToString() } } #endregion - + #region Private Fields #endregion @@ -102,12 +104,12 @@ public override string ToString() /// /// Prompts the user to edit the monitored item. /// - public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool isEvent) + public async Task ShowDialogAsync(ISession session, MonitoredItem monitoredItem, bool isEvent, CancellationToken ct = default) { if (!monitoredItem.Created) { NodeBTN.Session = session; - NodeBTN.SelectedNode = monitoredItem.StartNodeId; + await NodeBTN.SetSelectedNodeIdAsync(monitoredItem.StartNodeId, ct); } // hide fields not used for events. @@ -134,7 +136,7 @@ public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool isEven DeadbandValueUP.Visible = !isEvent; TriggerTypeLB.Visible = !isEvent; TriggerTypeCB.Visible = !isEvent; - + // fill in values. SamplingIntervalUP.Value = monitoredItem.SamplingInterval; DiscardOldestCK.Checked = monitoredItem.DiscardOldest; @@ -158,16 +160,16 @@ public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool isEven if (!monitoredItem.Created) { // fetch the available encodings for the first node in the list from the server. - IVariableBase variable = session.NodeCache.Find(monitoredItem.StartNodeId) as IVariableBase; + IVariableBase variable = await session.NodeCache.FindAsync(monitoredItem.StartNodeId, ct) as IVariableBase; DataEncodingCB.Items.Add(new EncodingInfo()); DataEncodingCB.SelectedIndex = 0; if (variable != null) { - if (session.NodeCache.IsTypeOf(variable.DataType, Opc.Ua.DataTypeIds.Structure)) + if (await session.NodeCache.IsTypeOfAsync(variable.DataType, Opc.Ua.DataTypeIds.Structure, ct)) { - foreach (INode encoding in session.NodeCache.Find(variable.DataType, Opc.Ua.ReferenceTypeIds.HasEncoding, false, true)) + foreach (INode encoding in await session.NodeCache.FindAsync(variable.DataType, Opc.Ua.ReferenceTypeIds.HasEncoding, false, true, ct)) { DataEncodingCB.Items.Add(new EncodingInfo() { EncodingName = encoding.BrowseName }); @@ -194,7 +196,7 @@ public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool isEven if (!monitoredItem.Created) { monitoredItem.StartNodeId = NodeBTN.SelectedNode; - monitoredItem.DisplayName = session.NodeCache.GetDisplayText(monitoredItem.StartNodeId); + monitoredItem.DisplayName = await session.NodeCache.GetDisplayTextAsync(monitoredItem.StartNodeId, ct); monitoredItem.RelativePath = null; monitoredItem.AttributeId = (uint)(AttributeCB.SelectedIndex + 1); monitoredItem.MonitoringMode = (MonitoringMode)MonitoringModeCB.SelectedItem; @@ -236,7 +238,7 @@ public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool isEven monitoredItem.QueueSize = 0; monitoredItem.Filter = new EventFilter(); } - + return true; } @@ -279,7 +281,7 @@ public MonitoringMode ShowDialog(MonitoringMode monitoringMode) return (MonitoringMode)MonitoringModeCB.SelectedItem; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.Designer.cs index 74d568d36..b13a6e3d8 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.Designer.cs @@ -240,7 +240,7 @@ private void InitializeComponent() this.NodeBTN.NodeControl = this.NodeTB; this.NodeBTN.ReferenceTypeIds = null; this.NodeBTN.RootId = null; - this.NodeBTN.SelectedNode = null; + this.NodeBTN.ClearSelectedNode(); this.NodeBTN.SelectedReference = null; this.NodeBTN.Session = null; this.NodeBTN.Size = new System.Drawing.Size(24, 24); diff --git a/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.cs index eeed3d7ff..277850b6a 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,8 @@ using System.Text; using Opc.Ua; using Opc.Ua.Client; +using System.Threading; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -51,7 +53,7 @@ public EditReadValueIdDlg() this.Icon = ClientUtils.GetAppIcon(); // add the attributes in numerical order. - foreach (uint attributeId in Attributes.GetIdentifiers()) + foreach (uint attributeId in Attributes.Identifiers) { AttributeCB.Items.Add(Attributes.GetBrowseName(attributeId)); } @@ -62,7 +64,7 @@ public EditReadValueIdDlg() /// /// Stores information about a data encoding. /// - private class EncodingInfo + private sealed class EncodingInfo { public QualifiedName EncodingName; @@ -77,7 +79,7 @@ public override string ToString() } } #endregion - + #region Private Fields #endregion @@ -85,7 +87,7 @@ public override string ToString() /// /// Prompts the user to edit the read request parameters for the set of nodes provided. /// - public ReadValueId[] ShowDialog(Session session, params ReadValueId[] nodesToRead) + public async Task ShowDialogAsync(ISession session, CancellationToken ct, params ReadValueId[] nodesToRead) { NodeBTN.Session = session; NodeBTN.SelectedReference = null; @@ -119,7 +121,7 @@ public ReadValueId[] ShowDialog(Session session, params ReadValueId[] nodesToRea } else { - NodeBTN.SelectedNode = nodesToRead[ii].NodeId; + await NodeBTN.SetSelectedNodeIdAsync(nodesToRead[ii].NodeId, ct); } } @@ -159,16 +161,16 @@ public ReadValueId[] ShowDialog(Session session, params ReadValueId[] nodesToRea IndexRangeTB.Text = nodesToRead[0].IndexRange; // fetch the available encodings for the first node in the list from the server. - IVariableBase variable = session.NodeCache.Find(nodesToRead[0].NodeId) as IVariableBase; + IVariableBase variable = await session.NodeCache.FindAsync(nodesToRead[0].NodeId, ct) as IVariableBase; if (variable != null) { - if (session.NodeCache.IsTypeOf(variable.DataType, Opc.Ua.DataTypeIds.Structure)) + if (await session.NodeCache.IsTypeOfAsync(variable.DataType, Opc.Ua.DataTypeIds.Structure, ct)) { DataEncodingCB.Items.Add(new EncodingInfo()); DataEncodingCB.SelectedIndex = 0; - foreach (INode encoding in session.NodeCache.Find(variable.DataType, Opc.Ua.ReferenceTypeIds.HasEncoding, false, true)) + foreach (INode encoding in await session.NodeCache.FindAsync(variable.DataType, Opc.Ua.ReferenceTypeIds.HasEncoding, false, true, ct)) { DataEncodingCB.Items.Add(new EncodingInfo() { EncodingName = encoding.BrowseName }); @@ -225,7 +227,7 @@ public ReadValueId[] ShowDialog(Session session, params ReadValueId[] nodesToRea results[ii] = new ReadValueId(); } - // only copy results that were actually being edited. + // only copy results that were actually being edited. if (editNode) { results[ii].NodeId = NodeBTN.SelectedNode; @@ -266,7 +268,7 @@ public ReadValueId[] ShowDialog(Session session, params ReadValueId[] nodesToRea return results; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Samples/ClientControls.Net4/Common/Client/EditSubscriptionDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditSubscriptionDlg.cs index 9f751b54a..92beccf00 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditSubscriptionDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditSubscriptionDlg.cs @@ -51,7 +51,7 @@ public EditSubscriptionDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields #endregion @@ -78,12 +78,12 @@ public bool ShowDialog(Subscription subscription) subscription.LifetimeCount = (uint)LifetimeCountUP.Value; subscription.MaxNotificationsPerPublish = (uint)MaxNotificationsPerPublishUP.Value; subscription.Priority = (byte)PriorityTB.Value; - subscription.PublishingEnabled = PublishingEnabledCK.Checked; + subscription.PublishingEnabled = PublishingEnabledCK.Checked; return true; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Samples/ClientControls.Net4/Common/Client/EditValueCtrl.cs b/Samples/ClientControls.Net4/Common/Client/EditValueCtrl.cs index 0c7374762..40d6deb51 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditValueCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditValueCtrl.cs @@ -53,21 +53,21 @@ public EditValue2Ctrl() InitializeComponent(); } #endregion - + #region Private Fields private event EventHandler m_ValueChanged; private Variant m_value; #endregion - + #region Public Interface /// /// The value in the control. /// - public Variant Value + public Variant Value { - get + get { - return m_value; + return m_value; } set @@ -80,7 +80,7 @@ public Variant Value m_value = value; } } - + /// /// Gets or sets the control that shows the current value. /// @@ -109,7 +109,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) null, m_value.Value, "Edit Value"); - + if (value == null) { return; diff --git a/Samples/ClientControls.Net4/Common/Client/EditWriteValueDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditWriteValueDlg.cs index 4aba9ecbe..318cea56e 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditWriteValueDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditWriteValueDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,8 @@ using System.Text; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -51,13 +53,13 @@ public EditWriteValueDlg() this.Icon = ClientUtils.GetAppIcon(); // add the attributes in numerical order. - foreach (uint attributeId in Attributes.GetIdentifiers()) + foreach (uint attributeId in Attributes.Identifiers) { AttributeCB.Items.Add(Attributes.GetBrowseName(attributeId)); } } #endregion - + #region Private Fields #endregion @@ -65,13 +67,13 @@ public EditWriteValueDlg() /// /// Prompts the user to edit the write request parameters for the set of nodes provided. /// - public WriteValue ShowDialog(Session session, WriteValue nodeToWrite) + public async Task ShowDialogAsync(ISession session, WriteValue nodeToWrite, CancellationToken ct = default) { NodeBTN.Session = session; NodeBTN.SelectedReference = null; // fill in the control. - NodeBTN.SelectedNode = nodeToWrite.NodeId; + await NodeBTN.SetSelectedNodeIdAsync(nodeToWrite.NodeId, ct); AttributeCB.SelectedIndex = (int)nodeToWrite.AttributeId - 1; IndexRangeTB.Text = nodeToWrite.IndexRange; ValueBTN.Value = nodeToWrite.Value.WrappedValue; @@ -121,7 +123,7 @@ public WriteValue ShowDialog(Session session, WriteValue nodeToWrite) { result.Value.ServerTimestamp = (DateTime)TypeInfo.Cast(ServerTimestampTB.Text, BuiltInType.DateTime); } - + if (NumericRange.Empty != result.ParsedIndexRange) { result.IndexRange = result.ParsedIndexRange.ToString(); @@ -134,7 +136,7 @@ public WriteValue ShowDialog(Session session, WriteValue nodeToWrite) return result; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Samples/ClientControls.Net4/Common/Client/EventFilterListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/EventFilterListViewCtrl.cs index 1687374ba..456d4fa53 100644 --- a/Samples/ClientControls.Net4/Common/Client/EventFilterListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/EventFilterListViewCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,9 +30,11 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Drawing; using System.Data; +using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -53,7 +55,7 @@ public EventFilterListViewCtrl() InitializeComponent(); FilterDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; - + m_dataset = new DataSet(); m_dataset.Tables.Add("Events"); @@ -76,7 +78,7 @@ public EventFilterListViewCtrl() #region Private Fields private DataSet m_dataset; - private Session m_session; + private ISession m_session; private int m_counter; #endregion @@ -84,7 +86,7 @@ public EventFilterListViewCtrl() /// /// Changes the session used for the read request. /// - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { m_session = session; } @@ -92,7 +94,7 @@ public void ChangeSession(Session session) /// /// Sets the filter to edit. /// - public void SetFilter(FilterDeclaration filter) + public async Task SetFilterAsync(FilterDeclaration filter, CancellationToken ct = default) { m_dataset.Tables[0].Rows.Clear(); @@ -101,7 +103,7 @@ public void SetFilter(FilterDeclaration filter) foreach (FilterDeclarationField field in filter.Fields) { DataRow row = m_dataset.Tables[0].NewRow(); - UpdateRow(row, field); + await UpdateRowAsync(row, field, ct); m_dataset.Tables[0].Rows.Add(row); } } @@ -112,10 +114,10 @@ public void SetFilter(FilterDeclaration filter) /// /// Updates the row. /// - public void UpdateRow(DataRow row, FilterDeclarationField field) + public async Task UpdateRowAsync(DataRow row, FilterDeclarationField field, CancellationToken ct = default) { row[0] = field; - row[1] = ImageList.Images[ClientUtils.GetImageIndex(m_session, field.InstanceDeclaration.NodeClass, field.InstanceDeclaration.RootTypeId, false)]; + row[1] = ImageList.Images[await ClientUtils.GetImageIndexAsync(m_session, field.InstanceDeclaration.NodeClass, field.InstanceDeclaration.RootTypeId, false, ct)]; row[2] = field.InstanceDeclaration.BrowsePathDisplayText; row[3] = field.Selected; row[4] = field.DisplayInList; @@ -171,11 +173,11 @@ private void FilterDV_CellDoubleClick(object sender, DataGridViewCellEventArgs e InstanceDeclaration declaration = field.InstanceDeclaration; object result = new EditComplexValueDlg().ShowDialog( - m_session, + m_session, declaration.DisplayName, - declaration.DataType, - declaration.ValueRank, - field.FilterValue.Value, + declaration.DataType, + declaration.ValueRank, + field.FilterValue.Value, "Edit Filter Value"); if (result != null) @@ -270,7 +272,7 @@ private void MoveUpMI_Click(object sender, EventArgs e) if (rows[ii].Index > 0) { - DataRowView target = FilterDV.Rows[rows[ii].Index-1].DataBoundItem as DataRowView; + DataRowView target = FilterDV.Rows[rows[ii].Index - 1].DataBoundItem as DataRowView; int index = (int)target.Row[8]; target.Row[8] = source.Row[8]; source.Row[8] = index; @@ -300,7 +302,7 @@ private void FilterDV_ColumnHeaderMouseClick(object sender, DataGridViewCellMous foreach (DataRowView row in m_dataset.Tables[0].DefaultView) { - FilterDeclarationField field = (FilterDeclarationField)row.Row[0]; + FilterDeclarationField field = (FilterDeclarationField)row.Row[0]; row.Row[3] = field.Selected = state; } } diff --git a/Samples/ClientControls.Net4/Common/Client/EventListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/EventListViewCtrl.cs index bcce5aaa8..3faa7f533 100644 --- a/Samples/ClientControls.Net4/Common/Client/EventListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/EventListViewCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -58,7 +60,7 @@ public EventListViewCtrl() #region Private Fields private DataSet m_dataset; - private Session m_session; + private ISession m_session; private FilterDeclaration m_filter; #endregion @@ -66,7 +68,7 @@ public EventListViewCtrl() /// /// Changes the session used for the read request. /// - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { m_session = session; } @@ -91,7 +93,7 @@ public void SetFilter(FilterDeclaration filter) } } } - + EventsDV.DataSource = m_dataset.Tables[0]; } @@ -141,24 +143,24 @@ public void DisplayEvent(VariantCollection fields) /// /// Fetches the recent history. /// - private void ReadHistory(ReadEventDetails details, NodeId areaId) + private async Task ReadHistoryAsync(ReadEventDetails details, NodeId areaId, CancellationToken ct = default) { HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = areaId; nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Neither, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -169,7 +171,7 @@ private void ReadHistory(ReadEventDetails details, NodeId areaId) } HistoryEvent events = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryEvent; - + foreach (HistoryEventFieldList e in events.Events) { DisplayEvent(e.EventFields); @@ -180,21 +182,23 @@ private void ReadHistory(ReadEventDetails details, NodeId areaId) { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; - m_session.HistoryRead( + response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Neither, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; } } /// /// Deletes the recent history. /// - private void DeleteHistory(NodeId areaId, List events, FilterDeclaration filter) + private async Task DeleteHistoryAsync(NodeId areaId, List events, FilterDeclaration filter, CancellationToken ct = default) { // find the event id. int index = 0; @@ -235,14 +239,14 @@ private void DeleteHistory(NodeId areaId, List events, Filter ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection(); nodesToUpdate.Add(new ExtensionObject(details)); - HistoryUpdateResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.HistoryUpdate( + HistoryUpdateResponse response = await m_session.HistoryUpdateAsync( null, nodesToUpdate, - out results, - out diagnosticInfos); + ct); + + HistoryUpdateResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToUpdate); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToUpdate); @@ -269,7 +273,7 @@ private void DeleteHistory(NodeId areaId, List events, Filter if (count > 0) { throw ServiceResultException.Create( - StatusCodes.BadEventIdUnknown, + StatusCodes.BadEventIdUnknown, "Error deleting events. Only {0} of {1} deletes succeeded.", events.Count - count, events.Count); @@ -288,7 +292,7 @@ private void EventsDV_ColumnAdded(object sender, DataGridViewColumnEventArgs e) if (EventsDV.Columns.Count > 1) { - EventsDV.Columns[EventsDV.Columns.Count-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + EventsDV.Columns[EventsDV.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } } diff --git a/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.Designer.cs index 0405bfeef..81f61719d 100644 --- a/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.Designer.cs @@ -128,7 +128,7 @@ private void InitializeComponent() this.SearchBTN.TabIndex = 2; this.SearchBTN.Text = "Search"; this.SearchBTN.UseVisualStyleBackColor = true; - this.SearchBTN.Click += new System.EventHandler(this.SearchBTN_Click); + this.SearchBTN.Click += new System.EventHandler(this.SearchBTN_ClickAsync); // // OkBTN // @@ -380,7 +380,7 @@ private void InitializeComponent() this.SystemElementBTN.NodeControl = this.SystemElementTB; this.SystemElementBTN.ReferenceTypeIds = null; this.SystemElementBTN.RootId = null; - this.SystemElementBTN.SelectedNode = null; + this.SystemElementBTN.ClearSelectedNode(); this.SystemElementBTN.SelectedReference = null; this.SystemElementBTN.Session = null; this.SystemElementBTN.Size = new System.Drawing.Size(24, 24); @@ -407,7 +407,7 @@ private void InitializeComponent() this.BrowseCTRL.SplitterDistance = 387; this.BrowseCTRL.TabIndex = 9; this.BrowseCTRL.View = null; - this.BrowseCTRL.AfterSelect += new System.EventHandler(this.BrowseCTRL_AfterSelect); + this.BrowseCTRL.AfterSelect += new System.EventHandler(this.BrowseCTRL_AfterSelectAsync); // // ServerCTRL // @@ -430,8 +430,8 @@ private void InitializeComponent() this.ServerCTRL.TabIndex = 10; this.ServerCTRL.UserIdentity = null; this.ServerCTRL.UseSecurity = true; - this.ServerCTRL.ReconnectComplete += new System.EventHandler(this.ServerCTRL_ReconnectComplete); - this.ServerCTRL.ConnectComplete += new System.EventHandler(this.ServerCTRL_ConnectComplete); + this.ServerCTRL.ReconnectComplete += new System.EventHandler(this.ServerCTRL_ReconnectCompleteAsync); + this.ServerCTRL.ConnectComplete += new System.EventHandler(this.ServerCTRL_ConnectCompleteAsync); // // GdsDiscoverServersDlg // diff --git a/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.cs b/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.cs index 2a205e20c..a72bc62f6 100644 --- a/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,7 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -56,7 +57,7 @@ public GdsDiscoverServersDlg() this.Icon = ClientUtils.GetAppIcon(); ServersLV.SmallImageList = new ClientUtils().ImageList; - List items = new List(); + List items = new List(); foreach (object value in Enum.GetValues(typeof(Match))) { @@ -115,7 +116,7 @@ private enum Match /// /// Shows the dialog. /// - public async Task ShowDialog(ApplicationConfiguration configuration, bool showSearchPanel) + public async Task ShowDialogAsync(ApplicationConfiguration configuration, bool showSearchPanel, CancellationToken ct = default) { List urls = new List(); @@ -135,7 +136,7 @@ public async Task ShowDialog(ApplicationConfiguration co try { - await ServerCTRL.Connect(); + await ServerCTRL.ConnectAsync(ct: ct); } catch (Exception exception) { @@ -161,7 +162,7 @@ public async Task ShowDialog(ApplicationConfiguration co /// /// Adds the results to the control. /// - private void UpdateResults(ApplicationDescription[] descriptions) + private async Task UpdateResultsAsync(ApplicationDescription[] descriptions, CancellationToken ct = default) { ServersLV.Items.Clear(); @@ -181,7 +182,7 @@ private void UpdateResults(ApplicationDescription[] descriptions) ListViewItem item = new ListViewItem(); item.Text = Utils.Format("{0}", description.ApplicationName); - item.ImageIndex = ClientUtils.GetImageIndex(ServerCTRL.Session, NodeClass.Object, null, false); + item.ImageIndex = await ClientUtils.GetImageIndexAsync(ServerCTRL.Session, NodeClass.Object, null, false, ct); item.SubItems.Add(new ListViewItem.ListViewSubItem()); item.SubItems.Add(new ListViewItem.ListViewSubItem()); item.SubItems.Add(new ListViewItem.ListViewSubItem()); @@ -194,7 +195,7 @@ private void UpdateResults(ApplicationDescription[] descriptions) { continue; } - + // collect the domains and protocols. List domains = new List(); List protocols = new List(); @@ -264,7 +265,7 @@ private string ProcessFilter(ComboBox selection, TextBox filter) { return String.Empty; } - + string text = filter.Text; Match match = (Match)selection.SelectedItem; @@ -290,16 +291,16 @@ private string ProcessFilter(ComboBox selection, TextBox filter) /// /// Searches the server for servers. /// - private void Search() + private async Task SearchAsync(CancellationToken ct = default) { - Session session = ServerCTRL.Session; + ISession session = ServerCTRL.Session; if (session == null) { return; } - NodeId elementId = null; + NodeId elementId = null; ReferenceDescription reference = SystemElementBTN.SelectedReference; if (reference != null && !reference.NodeId.IsAbsolute) @@ -309,9 +310,10 @@ private void Search() ushort namespaceIndex = (ushort)session.NamespaceUris.GetIndex(Namespaces.OpcUaGds); - IList outputArguments = session.Call( + IList outputArguments = await session.CallAsync( new NodeId(GdsId_Directory, namespaceIndex), new NodeId(GdsId_RootDirectoryEntryType_QueryServers, namespaceIndex), + ct, elementId, ProcessFilter(ApplicationNameCB, ApplicationNameTB), ProcessFilter(MachineNameCB, MachineNameTB), @@ -322,19 +324,19 @@ private void Search() { ExtensionObject[] extensions = outputArguments[0] as ExtensionObject[]; ApplicationDescription[] descriptions = (ApplicationDescription[])ExtensionObject.ToArray(extensions, typeof(ApplicationDescription)); - UpdateResults(descriptions); + await UpdateResultsAsync(descriptions, ct); } } /// /// Reads the application description from the GDS. /// - private ApplicationDescription Read(NodeId nodeId) + private async Task ReadAsync(NodeId nodeId, CancellationToken ct = default) { NamespaceTable wellKnownNamespaceUris = new NamespaceTable(); wellKnownNamespaceUris.Append(Namespaces.OpcUaGds); - string[] browsePaths = new string[] + string[] browsePaths = new string[] { "1:ApplicationName", "1:ApplicationType", @@ -344,10 +346,11 @@ private ApplicationDescription Read(NodeId nodeId) "1:DiscoveryUrls" }; - List propertyIds = ClientUtils.TranslateBrowsePaths( + List propertyIds = await ClientUtils.TranslateBrowsePathsAsync( ServerCTRL.Session, nodeId, wellKnownNamespaceUris, + ct, browsePaths); ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); @@ -360,16 +363,16 @@ private ApplicationDescription Read(NodeId nodeId) nodesToRead.Add(nodeToRead); } - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - ServerCTRL.Session.Read( + ReadResponse response = await ServerCTRL.Session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -394,11 +397,11 @@ private ApplicationDescription Read(NodeId nodeId) #endregion #region Event Handlers - private void SearchBTN_Click(object sender, EventArgs e) + private async void SearchBTN_ClickAsync(object sender, EventArgs e) { try { - Search(); + await SearchAsync(); } catch (Exception exception) { @@ -418,11 +421,11 @@ private void CloseBTN_Click(object sender, EventArgs e) } } - private void ServerCTRL_ConnectComplete(object sender, EventArgs e) + private async void ServerCTRL_ConnectCompleteAsync(object sender, EventArgs e) { try { - Session session = ServerCTRL.Session; + ISession session = ServerCTRL.Session; if (session != null) { @@ -430,14 +433,14 @@ private void ServerCTRL_ConnectComplete(object sender, EventArgs e) NodeId rootId = new NodeId(GdsId_Directory_Applications, namespaceIndex); NodeId[] referenceTypeIds = new NodeId[] { Opc.Ua.ReferenceTypeIds.Organizes, Opc.Ua.ReferenceTypeIds.HasChild }; - BrowseCTRL.Initialize(session, rootId, referenceTypeIds); + await BrowseCTRL.InitializeAsync(session, rootId, default, referenceTypeIds); SystemElementBTN.Session = session; SystemElementBTN.RootId = rootId; SystemElementBTN.ReferenceTypeIds = referenceTypeIds; } else { - BrowseCTRL.ChangeSession(session); + await BrowseCTRL.ChangeSessionAsync(session); SystemElementBTN.Session = session; } } @@ -447,12 +450,12 @@ private void ServerCTRL_ConnectComplete(object sender, EventArgs e) } } - private void ServerCTRL_ReconnectComplete(object sender, EventArgs e) + private async void ServerCTRL_ReconnectCompleteAsync(object sender, EventArgs e) { try { - Session session = ServerCTRL.Session; - BrowseCTRL.ChangeSession(session); + ISession session = ServerCTRL.Session; + await BrowseCTRL.ChangeSessionAsync(session); SystemElementBTN.Session = session; } catch (Exception exception) @@ -500,10 +503,10 @@ private void ServersLV_SelectedIndexChanged(object sender, EventArgs e) } } - private void BrowseCTRL_AfterSelect(object sender, EventArgs e) + private async void BrowseCTRL_AfterSelectAsync(object sender, EventArgs e) { try - { + { if (ServerCTRL.Session == null) { return; @@ -518,7 +521,7 @@ private void BrowseCTRL_AfterSelect(object sender, EventArgs e) { if (reference.TypeDefinition == typeId) { - m_application = Read((NodeId)reference.NodeId); + m_application = await ReadAsync((NodeId)reference.NodeId); OkBTN.Enabled = m_application.ApplicationType == ApplicationType.Server || m_application.ApplicationType == ApplicationType.ClientAndServer; return; } diff --git a/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.Designer.cs index bb3679f68..3500ee8be 100644 --- a/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.Designer.cs @@ -67,7 +67,7 @@ private void InitializeComponent() this.HistoryDataCTRL.Location = new System.Drawing.Point(0, 0); this.HistoryDataCTRL.MaxReturnValues = ((uint)(0u)); this.HistoryDataCTRL.Name = "HistoryDataCTRL"; - this.HistoryDataCTRL.NodeId = null; + this.HistoryDataCTRL.ClearNodeId(); this.HistoryDataCTRL.ProcessingInterval = 10000D; this.HistoryDataCTRL.ReadType = Opc.Ua.Client.Controls.HistoryDataListView.HistoryReadType.Raw; this.HistoryDataCTRL.ReturnBounds = false; diff --git a/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.cs b/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.cs index 51ae9a39d..5777f9981 100644 --- a/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -54,7 +56,7 @@ public HistoryDataDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields #endregion @@ -62,17 +64,17 @@ public HistoryDataDlg() /// /// Changes the session used. /// - public void ChangeSession(Session session) + public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { - HistoryDataCTRL.ChangeSession(session); + return HistoryDataCTRL.ChangeSessionAsync(session, ct); } /// /// Sets the variable shown in the dialog. /// - public void SetVariable(NodeId variableId) + public Task SetVariableAsync(NodeId variableId, CancellationToken ct = default) { - HistoryDataCTRL.ChangeNode(variableId); + return HistoryDataCTRL.ChangeNodeAsync(variableId, ct); } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.Designer.cs b/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.Designer.cs index 5bc1bbbba..6d31170ba 100644 --- a/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.Designer.cs @@ -166,7 +166,7 @@ private void InitializeComponent() this.InsertAnnotationMI.Name = "InsertAnnotationMI"; this.InsertAnnotationMI.Size = new System.Drawing.Size(347, 38); this.InsertAnnotationMI.Text = "Insert Annotation..."; - this.InsertAnnotationMI.Click += new System.EventHandler(this.InsertAnnotationMI_Click); + this.InsertAnnotationMI.Click += new System.EventHandler(this.InsertAnnotationMI_ClickAsync); // // ShowServerTimestampMI // @@ -527,7 +527,7 @@ private void InitializeComponent() this.NodeIdBTN.TabIndex = 4; this.NodeIdBTN.Text = "..."; this.NodeIdBTN.UseVisualStyleBackColor = true; - this.NodeIdBTN.Click += new System.EventHandler(this.NodeIdBTN_Click); + this.NodeIdBTN.Click += new System.EventHandler(this.NodeIdBTN_ClickAsync); // // NodeIdTB // @@ -848,7 +848,7 @@ private void InitializeComponent() this.StopBTN.TabIndex = 2; this.StopBTN.Text = "Stop"; this.StopBTN.UseVisualStyleBackColor = true; - this.StopBTN.Click += new System.EventHandler(this.StopBTN_Click); + this.StopBTN.Click += new System.EventHandler(this.StopBTN_ClickAsync); // // NextBTN // @@ -859,7 +859,7 @@ private void InitializeComponent() this.NextBTN.TabIndex = 1; this.NextBTN.Text = "Next"; this.NextBTN.UseVisualStyleBackColor = true; - this.NextBTN.Click += new System.EventHandler(this.NextBTN_Click); + this.NextBTN.Click += new System.EventHandler(this.NextBTN_ClickAsync); // // TimeShiftBTN // @@ -882,7 +882,7 @@ private void InitializeComponent() this.GoBTN.TabIndex = 37; this.GoBTN.Text = "Go"; this.GoBTN.UseVisualStyleBackColor = true; - this.GoBTN.Click += new System.EventHandler(this.GoBTN_Click); + this.GoBTN.Click += new System.EventHandler(this.GoBTN_ClickAsync); // // DetectLimitsBTN // @@ -893,7 +893,7 @@ private void InitializeComponent() this.DetectLimitsBTN.TabIndex = 41; this.DetectLimitsBTN.Text = "Auto Detect"; this.DetectLimitsBTN.UseVisualStyleBackColor = true; - this.DetectLimitsBTN.Click += new System.EventHandler(this.DetectLimitsBTN_Click); + this.DetectLimitsBTN.Click += new System.EventHandler(this.DetectLimitsBTN_ClickAsync); // // RightPN // diff --git a/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.cs b/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.cs index 63e920ebb..0364872ed 100644 --- a/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.cs +++ b/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,9 +30,11 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Drawing; using System.Data; +using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -67,7 +69,7 @@ public HistoryDataListView() ReadTypeCB.Items.Add(HistoryReadType.DeleteModified); ReadTypeCB.Items.Add(HistoryReadType.DeleteAtTime); ReadTypeCB.SelectedIndex = 0; - + m_dataset = new DataSet(); m_dataset.Tables.Add("Results"); @@ -159,9 +161,9 @@ public enum HistoryReadType #region AvailableAggregate Class /// - /// An aggregate supported by server. + /// An aggregate supported by server. /// - private class AvailableAggregate + private sealed class AvailableAggregate { public NodeId NodeId { get; set; } public string DisplayName { get; set; } @@ -177,7 +179,7 @@ public override string ToString() /// /// A session available in the conntrol. /// - private class AvailableSession + private sealed class AvailableSession { public Session Session { get; set; } @@ -192,7 +194,7 @@ public override string ToString() /// /// Stores the metadata about a property with history to read or update. /// - private class PropertyWithHistory + private sealed class PropertyWithHistory { public PropertyWithHistory() { @@ -219,7 +221,7 @@ public override string ToString() #endregion #region Private Fields - private Session m_session; + private ISession m_session; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private NodeId m_nodeId; @@ -236,34 +238,34 @@ public override string ToString() #region Public Members /// /// The node id to use. - /// + /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] - public NodeId NodeId + public NodeId NodeId => m_nodeId; + + public void ClearNodeId() { - get - { - return m_nodeId; + m_nodeId = null; + NodeIdTB.Text = String.Empty; + } + + public async Task SetNodeIdAsync(NodeId value, CancellationToken ct = default) + { + m_nodeId = value; + + if (m_session != null) + { + NodeIdTB.Text = await m_session.NodeCache.GetDisplayTextAsync(m_nodeId, ct); } - - set + else { - m_nodeId = value; - - if (m_session != null) + if (NodeId.IsNull(m_nodeId)) { - NodeIdTB.Text = m_session.NodeCache.GetDisplayText(m_nodeId); + NodeIdTB.Text = String.Empty; } else { - if (NodeId.IsNull(m_nodeId)) - { - NodeIdTB.Text = String.Empty; - } - else - { - NodeIdTB.Text = m_nodeId.ToString(); - } + NodeIdTB.Text = m_nodeId.ToString(); } } } @@ -446,7 +448,7 @@ public double ProcessingInterval /// /// Changes the session. /// - public void ChangeSession(Session session) + public async Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { if (Object.ReferenceEquals(session, m_session)) { @@ -455,7 +457,7 @@ public void ChangeSession(Session session) if (m_session != null) { - DeleteSubscription(); + await DeleteSubscriptionAsync(ct); m_session = null; } @@ -472,19 +474,19 @@ public void ChangeSession(Session session) { AggregateCB.Items.Clear(); - ILocalNode node = m_session.NodeCache.Find(ObjectIds.Server_ServerCapabilities_AggregateFunctions) as ILocalNode; + ILocalNode node = await m_session.NodeCache.FindAsync(ObjectIds.Server_ServerCapabilities_AggregateFunctions, ct) as ILocalNode; if (node != null) { foreach (IReference reference in node.References.Find(ReferenceTypeIds.HierarchicalReferences, false, true, m_session.TypeTree)) { - ILocalNode aggregate = m_session.NodeCache.Find(reference.TargetId) as ILocalNode; + ILocalNode aggregate = await m_session.NodeCache.FindAsync(reference.TargetId, ct) as ILocalNode; if (aggregate != null && aggregate.TypeDefinitionId == ObjectTypeIds.AggregateFunctionType) { AvailableAggregate item = new AvailableAggregate(); item.NodeId = aggregate.NodeId; - item.DisplayName = m_session.NodeCache.GetDisplayText(aggregate); + item.DisplayName = await m_session.NodeCache.GetDisplayTextAsync(aggregate, ct); AggregateCB.Items.Add(item); } } @@ -507,11 +509,11 @@ public void ChangeSession(Session session) SubscriptionStateChanged(); } } - + /// /// Updates the control after the session has reconnected. /// - public void SessionReconnected(Session session) + public void SessionReconnected(ISession session) { m_session = session; @@ -538,18 +540,18 @@ public void SessionReconnected(Session session) /// /// Changes the node monitored by the control. /// - public void ChangeNode(NodeId nodeId) + public async Task ChangeNodeAsync(NodeId nodeId, CancellationToken ct = default) { m_nodeId = nodeId; m_configuration = null; m_properties = null; PropertyCB.Items.Clear(); m_dataset.Clear(); - NodeIdTB.Text = m_session.NodeCache.GetDisplayText(m_nodeId); + NodeIdTB.Text = await m_session.NodeCache.GetDisplayTextAsync(m_nodeId, ct); if (!NodeId.IsNull(nodeId)) { - m_properties = FindPropertiesWithHistory(); + m_properties = await FindPropertiesWithHistoryAsync(ct); if (m_properties == null || m_properties.Count <= 1) { @@ -564,7 +566,7 @@ public void ChangeNode(NodeId nodeId) PropertyCB.Visible = true; } - m_configuration = ReadConfiguration(); + m_configuration = await ReadConfigurationAsync(ct); if (StatusCode.IsBad(m_configuration.Stepped.StatusCode)) { @@ -577,14 +579,14 @@ public void ChangeNode(NodeId nodeId) if (!m_timesChanged) { - DateTime startTime = ReadFirstDate(); + DateTime startTime = await ReadFirstDateAsync(ct); if (startTime != DateTime.MinValue) { StartTimeDP.Value = startTime; } - DateTime endTime = ReadLastDate(); + DateTime endTime = await ReadLastDateAsync(ct); if (endTime != DateTime.MinValue) { @@ -593,7 +595,7 @@ public void ChangeNode(NodeId nodeId) } } } - + if (m_subscription != null) { MonitoredItem monitoredItem = new MonitoredItem(m_monitoredItem); @@ -605,7 +607,7 @@ public void ChangeNode(NodeId nodeId) monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); SubscriptionStateChanged(); } } @@ -634,7 +636,7 @@ public void SetSortOrder(bool mostRecentFirst) /// public void Reset() { - NodeId = null; + ClearNodeId(); ReadType = HistoryReadType.Raw; StartTime = DateTime.MinValue; EndTime = DateTime.MinValue; @@ -651,13 +653,13 @@ public void Reset() /// /// Shows the configuration. /// - public void ShowConfiguration() + public async Task ShowConfigurationAsync(CancellationToken ct = default) { if (m_session != null) { if (m_configuration != null) { - new ViewNodeStateDlg().ShowDialog(m_session, m_configuration, null); + await new ViewNodeStateDlg().ShowDialogAsync(m_session, m_configuration, null, ct); } } } @@ -703,14 +705,14 @@ public void GetBrowsePathFromNodeState( browsePaths.Add(browsePath); } - GetBrowsePathFromNodeState(context, rootId, child, browsePath.RelativePath, browsePaths); + GetBrowsePathFromNodeState(context, rootId, child, browsePath.RelativePath, browsePaths); } } /// /// Reads the historical configuration for the node. /// - private List FindPropertiesWithHistory() + private async Task> FindPropertiesWithHistoryAsync(CancellationToken ct = default) { BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = m_nodeId; @@ -720,7 +722,7 @@ private List FindPropertiesWithHistory() nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)(BrowseResultMask.DisplayName | BrowseResultMask.BrowseName); - ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, nodeToBrowse, false); + ReferenceDescriptionCollection references = await ClientUtils.BrowseAsync(m_session, nodeToBrowse, false, ct); ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); @@ -743,16 +745,15 @@ private List FindPropertiesWithHistory() if (nodesToRead.Count > 0) { - DataValueCollection values = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out values, - out diagnosticInfos); + ct); + + DataValueCollection values = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(values, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -774,9 +775,9 @@ private List FindPropertiesWithHistory() /// /// Reads the historical configuration for the node. /// - private HistoricalDataConfigurationState ReadConfiguration() + private async Task ReadConfigurationAsync(CancellationToken ct = default) { - // load the defaults for the historical configuration object. + // load the defaults for the historical configuration object. HistoricalDataConfigurationState configuration = new HistoricalDataConfigurationState(null); configuration.Definition = new PropertyState(configuration); @@ -793,7 +794,7 @@ private HistoricalDataConfigurationState ReadConfiguration() Opc.Ua.BrowseNames.HAConfiguration, null, false); - + // get the browse paths to query. RelativePathElement element = new RelativePathElement(); element.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasHistoricalConfiguration; @@ -814,14 +815,15 @@ private HistoricalDataConfigurationState ReadConfiguration() pathsToTranslate); // translate browse paths. - BrowsePathResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.TranslateBrowsePathsToNodeIds( + TranslateBrowsePathsToNodeIdsResponse response = await m_session.TranslateBrowsePathsToNodeIdsAsync( null, pathsToTranslate, - out results, - out diagnosticInfos); + ct); + + BrowsePathResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; + ClientBase.ValidateResponse(results, pathsToTranslate); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, pathsToTranslate); @@ -851,19 +853,19 @@ private HistoricalDataConfigurationState ReadConfiguration() valuesToRead.Add(valueToRead); } } - + // read the values. if (valuesToRead.Count > 0) { - DataValueCollection values = null; - - m_session.Read( + ReadResponse response2 = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, valuesToRead, - out values, - out diagnosticInfos); + ct); + + DataValueCollection values = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; ClientBase.ValidateResponse(values, valuesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead); @@ -882,7 +884,7 @@ private HistoricalDataConfigurationState ReadConfiguration() /// /// Reads the first date in the archive (truncates milliseconds and converts to local). /// - private DateTime ReadFirstDate() + private async Task ReadFirstDateAsync(CancellationToken ct = default) { // use the historical data configuration if available. if (m_configuration != null) @@ -912,17 +914,16 @@ private DateTime ReadFirstDate() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -945,19 +946,21 @@ private DateTime ReadFirstDate() { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; - m_session.HistoryRead( + response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); } - + startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, startTime.Hour, startTime.Minute, startTime.Second, 0, DateTimeKind.Utc); startTime = startTime.ToLocalTime(); @@ -967,7 +970,7 @@ private DateTime ReadFirstDate() /// /// Reads the last date in the archive (truncates milliseconds and converts to local). /// - private DateTime ReadLastDate() + private async Task ReadLastDateAsync(CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = DateTime.MinValue; @@ -982,17 +985,16 @@ private DateTime ReadLastDate() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -1015,14 +1017,16 @@ private DateTime ReadLastDate() { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; - m_session.HistoryRead( + response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -1038,7 +1042,7 @@ private DateTime ReadLastDate() /// /// Creates the subscription. /// - private void CreateSubscription() + private async Task CreateSubscriptionAsync(CancellationToken ct = default) { if (m_session == null) { @@ -1056,7 +1060,7 @@ private void CreateSubscription() m_subscription.TimestampsToReturn = TimestampsToReturn.Both; m_session.AddSubscription(m_subscription); - m_subscription.Create(); + await m_subscription.CreateAsync(ct); m_monitoredItem = new MonitoredItem(); m_monitoredItem.StartNodeId = m_nodeId; @@ -1091,19 +1095,19 @@ private void CreateSubscription() m_monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); m_subscription.AddItem(m_monitoredItem); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); SubscriptionStateChanged(); } /// /// Deletes the subscription. /// - private void DeleteSubscription() + private async Task DeleteSubscriptionAsync(CancellationToken ct = default) { if (m_subscription != null) { - m_subscription.Delete(true); - m_session.RemoveSubscription(m_subscription); + await m_subscription.DeleteAsync(true, ct); + _ = await m_session.RemoveSubscriptionAsync(m_subscription, ct); m_subscription = null; m_monitoredItem = null; } @@ -1146,7 +1150,7 @@ private void SubscriptionStateChanged() /// Adds a value to the grid. /// private void AddValue(DataValue value, ModificationInfo modificationInfo) - { + { DataRow row = m_dataset.Tables[0].NewRow(); m_nextId += 10000; @@ -1179,7 +1183,7 @@ private void UpdateRow(DataRow row, DataValue value, ModificationInfo modificati } /// - /// Updates the display with a new value for a monitored variable. + /// Updates the display with a new value for a monitored variable. /// private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { @@ -1220,7 +1224,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt /// /// Fetches the next batch of history. /// - private void ReadNext() + private async Task ReadNextAsync(CancellationToken ct = default) { if (m_nodeToContinue == null) { @@ -1230,17 +1234,16 @@ private void ReadNext() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(m_nodeToContinue); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(m_details), TimestampsToReturn.Both, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -1254,7 +1257,7 @@ private void ReadNext() DisplayResults(values); // save any continuation point. - SaveContinuationPoint(m_details, m_nodeToContinue, results[0].ContinuationPoint); + await SaveContinuationPointAsync(m_details, m_nodeToContinue, results[0].ContinuationPoint, ct); } /// @@ -1273,33 +1276,32 @@ private NodeId GetSelectedNode() /// /// Fetches the recent history. /// - private void ReadRaw(bool isReadModified) + private async Task ReadRawAsync(bool isReadModified, CancellationToken ct = default) { m_dataset.Clear(); ReadRawModifiedDetails details = new ReadRawModifiedDetails(); - details.StartTime =(StartTimeCK.Checked)?StartTimeDP.Value.ToUniversalTime():DateTime.MinValue; - details.EndTime = (EndTimeCK.Checked)?EndTimeDP.Value.ToUniversalTime():DateTime.MinValue; - details.NumValuesPerNode = (MaxReturnValuesCK.Checked)?(uint)MaxReturnValuesNP.Value:0; + details.StartTime = (StartTimeCK.Checked) ? StartTimeDP.Value.ToUniversalTime() : DateTime.MinValue; + details.EndTime = (EndTimeCK.Checked) ? EndTimeDP.Value.ToUniversalTime() : DateTime.MinValue; + details.NumValuesPerNode = (MaxReturnValuesCK.Checked) ? (uint)MaxReturnValuesNP.Value : 0; details.IsReadModified = isReadModified; - details.ReturnBounds = (isReadModified)?false:ReturnBoundsCK.Checked; + details.ReturnBounds = (isReadModified) ? false : ReturnBoundsCK.Checked; HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = GetSelectedNode(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Both, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -1313,13 +1315,13 @@ private void ReadRaw(bool isReadModified) DisplayResults(values); // save any continuation point. - SaveContinuationPoint(details, nodeToRead, results[0].ContinuationPoint); + await SaveContinuationPointAsync(details, nodeToRead, results[0].ContinuationPoint, ct); } /// /// Fetches the recent history. /// - private void ReadAtTime() + private async Task ReadAtTimeAsync(CancellationToken ct = default) { m_dataset.Clear(); @@ -1331,7 +1333,7 @@ private void ReadAtTime() for (int ii = 0; ii < MaxReturnValuesNP.Value; ii++) { - details.ReqTimes.Add(startTime.AddMilliseconds((double)(ii*TimeStepNP.Value))); + details.ReqTimes.Add(startTime.AddMilliseconds((double)(ii * TimeStepNP.Value))); } HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); @@ -1339,17 +1341,16 @@ private void ReadAtTime() nodeToRead.NodeId = GetSelectedNode(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Both, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -1363,13 +1364,13 @@ private void ReadAtTime() DisplayResults(values); // save any continuation point. - SaveContinuationPoint(details, nodeToRead, results[0].ContinuationPoint); + await SaveContinuationPointAsync(details, nodeToRead, results[0].ContinuationPoint, ct); } /// /// Fetches the recent history. /// - private void ReadProcessed() + private async Task ReadProcessedAsync(CancellationToken ct = default) { m_dataset.Clear(); @@ -1392,17 +1393,16 @@ private void ReadProcessed() nodeToRead.NodeId = m_nodeId; nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Both, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -1416,31 +1416,30 @@ private void ReadProcessed() DisplayResults(values); // save any continuation point. - SaveContinuationPoint(details, nodeToRead, results[0].ContinuationPoint); + await SaveContinuationPointAsync(details, nodeToRead, results[0].ContinuationPoint, ct); } /// /// Saves a continuation point for later use. /// - private void SaveContinuationPoint(HistoryReadDetails details, HistoryReadValueId nodeToRead, byte[] continuationPoint) + private async Task SaveContinuationPointAsync(HistoryReadDetails details, HistoryReadValueId nodeToRead, byte[] continuationPoint, CancellationToken ct = default) { // clear existing continuation point. if (m_nodeToContinue != null) { HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(m_nodeToContinue); - - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(m_details), TimestampsToReturn.Neither, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -1477,7 +1476,7 @@ private void SaveContinuationPoint(HistoryReadDetails details, HistoryReadValueI /// /// Updates the history. /// - private void InsertReplace(PerformUpdateType updateType) + private async Task InsertReplaceAsync(PerformUpdateType updateType, CancellationToken ct = default) { DataValueCollection values = new DataValueCollection(); @@ -1486,7 +1485,7 @@ private void InsertReplace(PerformUpdateType updateType) DataValue value = (DataValue)row.Row[9]; values.Add(value); } - + bool isStructured = false; PropertyWithHistory property = PropertyCB.SelectedItem as PropertyWithHistory; @@ -1496,7 +1495,7 @@ private void InsertReplace(PerformUpdateType updateType) isStructured = true; } - HistoryUpdateResultCollection results = InsertReplace(GetSelectedNode(), updateType, isStructured, values); + HistoryUpdateResultCollection results = await InsertReplaceAsync(GetSelectedNode(), updateType, isStructured, values, ct); ResultsDV.Columns[ResultsDV.Columns.Count - 1].Visible = true; @@ -1511,7 +1510,7 @@ private void InsertReplace(PerformUpdateType updateType) /// /// Updates the history. /// - private HistoryUpdateResultCollection InsertReplace(NodeId nodeId, PerformUpdateType updateType, bool isStructure, IList values) + private async Task InsertReplaceAsync(NodeId nodeId, PerformUpdateType updateType, bool isStructure, IList values, CancellationToken ct = default) { HistoryUpdateDetails details = null; @@ -1535,14 +1534,13 @@ private HistoryUpdateResultCollection InsertReplace(NodeId nodeId, PerformUpdate ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection(); nodesToUpdate.Add(new ExtensionObject(details)); - HistoryUpdateResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryUpdate( + HistoryUpdateResponse response = await m_session.HistoryUpdateAsync( null, nodesToUpdate, - out results, - out diagnosticInfos); + ct); + + HistoryUpdateResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToUpdate); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToUpdate); @@ -1558,7 +1556,7 @@ private HistoryUpdateResultCollection InsertReplace(NodeId nodeId, PerformUpdate /// /// Deletes the block of data. /// - private void DeleteRaw(bool isModified) + private async Task DeleteRawAsync(bool isModified, CancellationToken ct = default) { DeleteRawModifiedDetails details = new DeleteRawModifiedDetails(); details.NodeId = m_nodeId; @@ -1569,14 +1567,13 @@ private void DeleteRaw(bool isModified) ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection(); nodesToUpdate.Add(new ExtensionObject(details)); - HistoryUpdateResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; + HistoryUpdateResponse response = await m_session.HistoryUpdateAsync( + null, + nodesToUpdate, + ct); - m_session.HistoryUpdate( - null, - nodesToUpdate, - out results, - out diagnosticInfos); + HistoryUpdateResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToUpdate); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToUpdate); @@ -1593,7 +1590,7 @@ private void DeleteRaw(bool isModified) /// /// Deletes the history. /// - private void DeleteAtTime() + private async Task DeleteAtTimeAsync(CancellationToken ct = default) { DeleteAtTimeDetails details = new DeleteAtTimeDetails(); details.NodeId = m_nodeId; @@ -1607,14 +1604,13 @@ private void DeleteAtTime() ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection(); nodesToUpdate.Add(new ExtensionObject(details)); - HistoryUpdateResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; + HistoryUpdateResponse response = await m_session.HistoryUpdateAsync( + null, + nodesToUpdate, + ct); - m_session.HistoryUpdate( - null, - nodesToUpdate, - out results, - out diagnosticInfos); + HistoryUpdateResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToUpdate); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToUpdate); @@ -1624,7 +1620,7 @@ private void DeleteAtTime() throw new ServiceResultException(results[0].StatusCode); } - ResultsDV.Columns[ResultsDV.Columns.Count-1].Visible = true; + ResultsDV.Columns[ResultsDV.Columns.Count - 1].Visible = true; for (int ii = 0; ii < m_dataset.Tables[0].DefaultView.Count; ii++) { @@ -1672,7 +1668,7 @@ private void DisplayResults(HistoryData values) m_dataset.AcceptChanges(); } - private void NodeIdBTN_Click(object sender, EventArgs e) + private async void NodeIdBTN_ClickAsync(object sender, EventArgs e) { try { @@ -1681,11 +1677,12 @@ private void NodeIdBTN_Click(object sender, EventArgs e) return; } - ReferenceDescription reference = new SelectNodeDlg().ShowDialog( + ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync( m_session, Opc.Ua.ObjectIds.ObjectsFolder, null, "Select Variable", + default, Opc.Ua.ReferenceTypeIds.Organizes, Opc.Ua.ReferenceTypeIds.Aggregates); @@ -1696,7 +1693,7 @@ private void NodeIdBTN_Click(object sender, EventArgs e) if (reference.NodeId != m_nodeId) { - ChangeNode((NodeId)reference.NodeId); + await ChangeNodeAsync((NodeId)reference.NodeId); } } catch (Exception exception) @@ -1705,7 +1702,7 @@ private void NodeIdBTN_Click(object sender, EventArgs e) } } - private void SubscribeCK_CheckedChanged(object sender, EventArgs e) + private async void SubscribeCK_CheckedChangedAsync(object sender, EventArgs e) { try { @@ -1713,11 +1710,11 @@ private void SubscribeCK_CheckedChanged(object sender, EventArgs e) { if (m_isSubscribed) { - CreateSubscription(); + await CreateSubscriptionAsync(); } else { - DeleteSubscription(); + await DeleteSubscriptionAsync(); } } } @@ -1727,7 +1724,7 @@ private void SubscribeCK_CheckedChanged(object sender, EventArgs e) } } - private void GoBTN_Click(object sender, EventArgs e) + private async void GoBTN_ClickAsync(object sender, EventArgs e) { try { @@ -1737,73 +1734,73 @@ private void GoBTN_Click(object sender, EventArgs e) { case HistoryReadType.Subscribe: { - CreateSubscription(); + await CreateSubscriptionAsync(); break; } case HistoryReadType.Raw: { - ReadRaw(false); + await ReadRawAsync(false); break; } case HistoryReadType.Modified: { - ReadRaw(true); + await ReadRawAsync(true); break; } case HistoryReadType.Processed: { - ReadProcessed(); + await ReadProcessedAsync(); break; } case HistoryReadType.AtTime: { - ReadAtTime(); + await ReadAtTimeAsync(); break; } case HistoryReadType.Insert: { - InsertReplace(PerformUpdateType.Insert); + await InsertReplaceAsync(PerformUpdateType.Insert); break; } case HistoryReadType.Replace: { - InsertReplace(PerformUpdateType.Replace); + await InsertReplaceAsync(PerformUpdateType.Replace); break; } case HistoryReadType.InsertReplace: { - InsertReplace(PerformUpdateType.Update); + await InsertReplaceAsync(PerformUpdateType.Update); break; } case HistoryReadType.Remove: { - InsertReplace(PerformUpdateType.Remove); + await InsertReplaceAsync(PerformUpdateType.Remove); break; } case HistoryReadType.DeleteRaw: { - DeleteRaw(false); + await DeleteRawAsync(false); break; } case HistoryReadType.DeleteModified: { - DeleteRaw(true); + await DeleteRawAsync(true); break; } case HistoryReadType.DeleteAtTime: { - DeleteAtTime(); + await DeleteAtTimeAsync(); break; } } @@ -1815,11 +1812,11 @@ private void GoBTN_Click(object sender, EventArgs e) } } - private void NextBTN_Click(object sender, EventArgs e) + private async void NextBTN_ClickAsync(object sender, EventArgs e) { try { - ReadNext(); + await ReadNextAsync(); } catch (Exception exception) { @@ -1827,11 +1824,11 @@ private void NextBTN_Click(object sender, EventArgs e) } } - private void StopBTN_Click(object sender, EventArgs e) + private async void StopBTN_ClickAsync(object sender, EventArgs e) { try { - DeleteSubscription(); + await DeleteSubscriptionAsync(); } catch (Exception exception) { @@ -2168,18 +2165,18 @@ private void StartTimeDP_ValueChanged(object sender, EventArgs e) } } - private void DetectLimitsBTN_Click(object sender, EventArgs e) + private async void DetectLimitsBTN_ClickAsync(object sender, EventArgs e) { try { - DateTime startTime = ReadFirstDate(); + DateTime startTime = await ReadFirstDateAsync(); if (startTime != DateTime.MinValue) { StartTimeDP.Value = startTime; } - DateTime endTime = ReadLastDate(); + DateTime endTime = await ReadLastDateAsync(); if (endTime != DateTime.MinValue) { @@ -2250,7 +2247,7 @@ private void TimeShiftBTN_Click(object sender, EventArgs e) } } - private void InsertAnnotationMI_Click(object sender, EventArgs e) + private async void InsertAnnotationMI_ClickAsync(object sender, EventArgs e) { try { @@ -2291,7 +2288,7 @@ private void InsertAnnotationMI_Click(object sender, EventArgs e) } - HistoryUpdateResultCollection results = InsertReplace(propertyId, PerformUpdateType.Insert, true, valuesToUpdate); + HistoryUpdateResultCollection results = await InsertReplaceAsync(propertyId, PerformUpdateType.Insert, true, valuesToUpdate); ResultsDV.Columns[ResultsDV.Columns.Count - 1].Visible = true; @@ -2319,7 +2316,7 @@ private void EditValueMI_Click(object sender, EventArgs e) { return; } - + foreach (DataGridViewRow row in ResultsDV.SelectedRows) { DataRowView source = row.DataBoundItem as DataRowView; diff --git a/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.Designer.cs b/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.Designer.cs index cd10e09a8..1c0e42994 100644 --- a/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.Designer.cs @@ -277,7 +277,7 @@ private void InitializeComponent() this.NodeIdBTN.TabIndex = 4; this.NodeIdBTN.Text = "..."; this.NodeIdBTN.UseVisualStyleBackColor = true; - this.NodeIdBTN.Click += new System.EventHandler(this.NodeIdBTN_Click); + this.NodeIdBTN.Click += new System.EventHandler(this.NodeIdBTN_ClickAsync); // // NodeIdTB // diff --git a/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.cs b/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.cs index 13e4b09ee..bb9327065 100644 --- a/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -91,36 +93,18 @@ public enum HistoryOperation #region Public Members /// /// The node id to use. - /// + /// [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public NodeId NodeId { - get - { - return m_nodeId; - } - - set - { - m_nodeId = value; + get => m_nodeId; + } - if (m_session != null) - { - NodeIdTB.Text = m_session.NodeCache.GetDisplayText(m_nodeId); - } - else - { - if (NodeId.IsNull(m_nodeId)) - { - NodeIdTB.Text = String.Empty; - } - else - { - NodeIdTB.Text = m_nodeId.ToString(); - } - } - } + public void ClearNodeId() + { + m_nodeId = null; + NodeIdTB.Text = String.Empty; } /// @@ -212,7 +196,7 @@ public void ChangeSession(Session session) m_session = session; LeftPN.Enabled = m_session != null; } - + /// /// Updates the control after the session has reconnected. /// @@ -224,10 +208,25 @@ public void SessionReconnected(Session session) /// /// Changes the node monitored by the control. /// - public void ChangeNode(NodeId nodeId) + public async Task ChangeNodeAsync(NodeId value, CancellationToken ct = default) { - m_nodeId = nodeId; - NodeIdTB.Text = m_session.NodeCache.GetDisplayText(m_nodeId); + m_nodeId = value; + + if (m_session != null) + { + NodeIdTB.Text = await m_session.NodeCache.GetDisplayTextAsync(m_nodeId, ct); + } + else + { + if (NodeId.IsNull(m_nodeId)) + { + NodeIdTB.Text = String.Empty; + } + else + { + NodeIdTB.Text = m_nodeId.ToString(); + } + } } /// @@ -235,7 +234,7 @@ public void ChangeNode(NodeId nodeId) /// public void Reset() { - NodeId = null; + ClearNodeId(); Operation = HistoryOperation.Read; StartTime = DateTime.MinValue; EndTime = DateTime.MinValue; @@ -284,11 +283,11 @@ public void GetBrowsePathFromNodeState( browsePaths.Add(browsePath); } - GetBrowsePathFromNodeState(context, rootId, child, browsePath.RelativePath, browsePaths); + GetBrowsePathFromNodeState(context, rootId, child, browsePath.RelativePath, browsePaths); } } - private void NodeIdBTN_Click(object sender, EventArgs e) + private async void NodeIdBTN_ClickAsync(object sender, EventArgs e) { try { @@ -297,11 +296,12 @@ private void NodeIdBTN_Click(object sender, EventArgs e) return; } - ReferenceDescription reference = new SelectNodeDlg().ShowDialog( + ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync( m_session, Opc.Ua.ObjectIds.Server, null, "Select Notifier", + default, Opc.Ua.ReferenceTypeIds.HasNotifier); if (reference == null) @@ -311,7 +311,7 @@ private void NodeIdBTN_Click(object sender, EventArgs e) if (reference.NodeId != m_nodeId) { - ChangeNode((NodeId)reference.NodeId); + await ChangeNodeAsync((NodeId)reference.NodeId); } } catch (Exception exception) diff --git a/Samples/ClientControls.Net4/Common/Client/ISessionForm.cs b/Samples/ClientControls.Net4/Common/Client/ISessionForm.cs index 76e87dbba..401f61e4b 100644 --- a/Samples/ClientControls.Net4/Common/Client/ISessionForm.cs +++ b/Samples/ClientControls.Net4/Common/Client/ISessionForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -31,6 +31,8 @@ using System.Collections.Generic; using System.Linq; using System.Text; +using System.Threading; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -43,6 +45,6 @@ public interface ISessionForm /// Changes the session being used by the form. /// /// The new session to use. A null value means the session has been disconnected. - void ChangeSession(Session session); + Task ChangeSessionAsync(ISession session, CancellationToken ct = default); } } diff --git a/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.Designer.cs index 617a1929a..f7cdc3fae 100644 --- a/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.Designer.cs @@ -96,7 +96,7 @@ private void InitializeComponent() this.ReadBTN.TabIndex = 1; this.ReadBTN.Text = "Read"; this.ReadBTN.UseVisualStyleBackColor = true; - this.ReadBTN.Click += new System.EventHandler(this.ReadBTN_Click); + this.ReadBTN.Click += new System.EventHandler(this.ReadBTN_ClickAsync); // // BackBTN // diff --git a/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.cs b/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.cs index fdbcdccc0..a87b5d10d 100644 --- a/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,8 @@ using System.ComponentModel; using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -53,25 +55,26 @@ public ReadRequestDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields #endregion - + #region Public Interface /// /// Changes the session used for the read request. /// - public void ChangeSession(Session session) + public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { ReadRequestCTRL.ChangeSession(session); + return Task.CompletedTask; } /// /// Adds the nodes to the read request. /// - public void AddNodes(params ReadValueId[] nodesToRead) + public async Task AddNodesAsync(CancellationToken ct, params ReadValueId[] nodesToRead) { - ReadRequestCTRL.AddNodes(nodesToRead); + await ReadRequestCTRL.AddNodesAsync(ct, nodesToRead); } #endregion @@ -79,11 +82,11 @@ public void AddNodes(params ReadValueId[] nodesToRead) #endregion #region Event Handlers - private void ReadBTN_Click(object sender, EventArgs e) + private async void ReadBTN_ClickAsync(object sender, EventArgs e) { try { - ReadRequestCTRL.Read(); + await ReadRequestCTRL.ReadAsync(); BackBTN.Visible = true; } catch (Exception exception) diff --git a/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.Designer.cs b/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.Designer.cs index 7a176db11..35d9fe2e8 100644 --- a/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.Designer.cs @@ -95,7 +95,7 @@ private void InitializeComponent() this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(152, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // ResultsDV // @@ -124,7 +124,7 @@ private void InitializeComponent() this.ResultsDV.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.ResultsDV.Size = new System.Drawing.Size(754, 346); this.ResultsDV.TabIndex = 0; - this.ResultsDV.DoubleClick += new System.EventHandler(this.EditMI_Click); + this.ResultsDV.DoubleClick += new System.EventHandler(this.EditMI_ClickAsync); // // Icon // @@ -244,7 +244,7 @@ private void InitializeComponent() this.NewMI.Name = "NewMI"; this.NewMI.Size = new System.Drawing.Size(152, 22); this.NewMI.Text = "New..."; - this.NewMI.Click += new System.EventHandler(this.NewMI_Click); + this.NewMI.Click += new System.EventHandler(this.NewMI_ClickAsync); // // ReadRequestListView // diff --git a/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.cs index d73613f5d..415debd92 100644 --- a/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -53,7 +55,7 @@ public ReadRequestListViewCtrl() InitializeComponent(); ResultsDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; - + m_dataset = new DataSet(); m_dataset.Tables.Add("Requests"); @@ -76,7 +78,7 @@ public ReadRequestListViewCtrl() #region Private Fields private DataSet m_dataset; - private Session m_session; + private ISession m_session; private bool m_showResults; #endregion @@ -84,7 +86,7 @@ public ReadRequestListViewCtrl() /// /// Changes the session used for the read request. /// - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { m_session = session; } @@ -92,7 +94,7 @@ public void ChangeSession(Session session) /// /// Adds a node to the read request. /// - public void AddNodes(params ReadValueId[] nodesToRead) + public async Task AddNodesAsync(CancellationToken ct, params ReadValueId[] nodesToRead) { if (nodesToRead != null) { @@ -104,7 +106,7 @@ public void AddNodes(params ReadValueId[] nodesToRead) } DataRow row = m_dataset.Tables[0].NewRow(); - UpdateRow(row, nodesToRead[ii]); + await UpdateRowAsync(row, nodesToRead[ii], ct); m_dataset.Tables[0].Rows.Add(row); } } @@ -113,7 +115,7 @@ public void AddNodes(params ReadValueId[] nodesToRead) /// /// Reads the values displayed in the control and moves to the display results state. /// - public void Read() + public async Task ReadAsync(CancellationToken ct = default) { if (m_session == null) { @@ -130,18 +132,17 @@ public void Read() row.Selected = false; nodesToRead.Add(value); } - - // read the values. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.Read( + // read the values. + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Both, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -202,11 +203,11 @@ public void UpdateRow(DataRow row, DataValue value) /// /// Updates the row with the node to read. /// - public void UpdateRow(DataRow row, ReadValueId nodeToRead) + public async Task UpdateRowAsync(DataRow row, ReadValueId nodeToRead, CancellationToken ct = default) { row[0] = nodeToRead; row[1] = ImageList.Images[ClientUtils.GetImageIndex(nodeToRead.AttributeId, null)]; - row[2] = (m_session != null) ? m_session.NodeCache.GetDisplayText(nodeToRead.NodeId) : Utils.ToString(nodeToRead.NodeId); + row[2] = (m_session != null) ? await m_session.NodeCache.GetDisplayTextAsync(nodeToRead.NodeId, ct) : Utils.ToString(nodeToRead.NodeId); row[3] = Attributes.GetBrowseName(nodeToRead.AttributeId); row[4] = nodeToRead.IndexRange; row[5] = (nodeToRead.DataEncoding != null) ? nodeToRead.DataEncoding : QualifiedName.Null; @@ -222,7 +223,7 @@ private void PopupMenu_Opening(object sender, CancelEventArgs e) DeleteMI.Visible = !m_showResults; } - private void NewMI_Click(object sender, EventArgs e) + private async void NewMI_ClickAsync(object sender, EventArgs e) { try { @@ -245,7 +246,7 @@ private void NewMI_Click(object sender, EventArgs e) } // edit the parameters. - ReadValueId[] results = new EditReadValueIdDlg().ShowDialog(m_session, nodeToRead); + ReadValueId[] results = await new EditReadValueIdDlg().ShowDialogAsync(m_session, default, nodeToRead); if (results != null) { @@ -253,7 +254,7 @@ private void NewMI_Click(object sender, EventArgs e) for (int ii = 0; ii < results.Length; ii++) { DataRow row = m_dataset.Tables[0].NewRow(); - UpdateRow(row, results[ii]); + await UpdateRowAsync(row, results[ii]); m_dataset.Tables[0].Rows.Add(row); } } @@ -265,7 +266,7 @@ private void NewMI_Click(object sender, EventArgs e) } } - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -277,11 +278,11 @@ private void EditMI_Click(object sender, EventArgs e) ReadValueId nodeToRead = (ReadValueId)source.Row[0]; DataValue value = (DataValue)source.Row[6]; - new EditComplexValueDlg().ShowDialog( + await new EditComplexValueDlg().ShowDialogAsync( m_session, null, 0, - null, + null, value, true, "View Read Result"); @@ -300,14 +301,14 @@ private void EditMI_Click(object sender, EventArgs e) nodesToRead.Add(value); } - ReadValueId[] results = new EditReadValueIdDlg().ShowDialog(m_session, nodesToRead.ToArray()); + ReadValueId[] results = await new EditReadValueIdDlg().ShowDialogAsync(m_session, default, nodesToRead.ToArray()); if (results != null) { for (int ii = 0; ii < results.Length; ii++) { DataRowView source = ResultsDV.SelectedRows[ii].DataBoundItem as DataRowView; - UpdateRow(source.Row, results[ii]); + await UpdateRowAsync(source.Row, results[ii]); } } } diff --git a/Samples/ClientControls.Net4/Common/Client/SelectLocaleDlg.cs b/Samples/ClientControls.Net4/Common/Client/SelectLocaleDlg.cs index 1fcdd282f..4059a0394 100644 --- a/Samples/ClientControls.Net4/Common/Client/SelectLocaleDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SelectLocaleDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,8 @@ using System.Text; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -51,25 +53,25 @@ public SelectLocaleDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; #endregion - + #region Public Interface /// /// Displays the available areas in a tree view. /// /// The session. /// - public string ShowDialog(Session session) + public async Task ShowDialogAsync(ISession session, CancellationToken ct = default) { m_session = session; LocaleCB.Items.Clear(); // get the locales from the server. - DataValue value = m_session.ReadValue(VariableIds.Server_ServerCapabilities_LocaleIdArray); + DataValue value = await m_session.ReadValueAsync(VariableIds.Server_ServerCapabilities_LocaleIdArray, ct); if (value != null) { @@ -99,7 +101,7 @@ public string ShowDialog(Session session) return LocaleCB.SelectedItem as string; } #endregion - + #region Private Methods #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.Designer.cs b/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.Designer.cs index 571fbdaca..ea68626be 100644 --- a/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.Designer.cs @@ -69,7 +69,7 @@ private void InitializeComponent() this.BrowseBTN.TabIndex = 0; this.BrowseBTN.Text = "..."; this.BrowseBTN.UseVisualStyleBackColor = true; - this.BrowseBTN.Click += new System.EventHandler(this.BrowseBTN_Click); + this.BrowseBTN.Click += new System.EventHandler(this.BrowseBTN_ClickAsync); // // SelectFileCtrl // diff --git a/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.cs b/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.cs index 564cb16da..5678e1b41 100644 --- a/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,12 +30,15 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Drawing; using System.Data; +using System.Drawing; +using System.IO; using System.Linq; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.IO; +using Newtonsoft.Json.Linq; namespace Opc.Ua.Client.Controls { @@ -53,7 +56,7 @@ public SelectNodeCtrl() InitializeComponent(); } #endregion - + #region Private Fields private event EventHandler m_NodeSelected; private ReferenceDescription m_selectedNode; @@ -63,7 +66,7 @@ public SelectNodeCtrl() /// /// Gets or sets the current session. /// - public Session Session { get; set; } + public ISession Session { get; set; } /// /// Gets or sets starting node. @@ -79,50 +82,58 @@ public SelectNodeCtrl() /// Gets or sets the reference types to follow. /// public NodeId[] ReferenceTypeIds { get; set; } - + /// /// Gets or sets the currently selected node. /// public NodeId SelectedNode { - get + get => m_selectedNode != null ? (NodeId)m_selectedNode.NodeId : null; + set { - if (m_selectedNode != null) + if (value == null) { - return (NodeId)m_selectedNode.NodeId; + ClearSelectedNode(); + } + else + { + SetSelectedNodeIdAsync(value).Wait(); } - - return null; } + } - set + public void ClearSelectedNode() + { + m_selectedNode = new ReferenceDescription(); + } + + public async Task SetSelectedNodeIdAsync(NodeId value, CancellationToken ct = default) + { + if (NodeControl != null) { - if (NodeControl != null) - { - NodeControl.Text = null; + NodeControl.Text = null; - if (value != null && Session != null) - { - NodeControl.Text = Session.NodeCache.GetDisplayText(value); - } + if (value != null && Session != null) + { + NodeControl.Text = await Session.NodeCache.GetDisplayTextAsync(value, ct); } + } - ReferenceDescription reference = new ReferenceDescription(); - reference.NodeId = value; - - if (Session != null) - { - INode node = Session.NodeCache.Find(value); + ReferenceDescription reference = new ReferenceDescription(); + reference.NodeId = value; - if (node != null) - { - reference.BrowseName = node.BrowseName; - reference.DisplayName = node.DisplayName; - } - } + if (Session != null) + { + INode node = await Session.NodeCache.FindAsync(value, ct); - m_selectedNode = reference; + if (node != null) + { + reference.BrowseName = node.BrowseName; + reference.DisplayName = node.DisplayName; + } } + + m_selectedNode = reference; } /// @@ -173,13 +184,14 @@ public event EventHandler NodeSelected #endregion #region Event Handlers - private void BrowseBTN_Click(object sender, EventArgs e) + private async void BrowseBTN_ClickAsync(object sender, EventArgs e) { - ReferenceDescription reference = new SelectNodeDlg().ShowDialog( + ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync( Session, RootId, View, null, + default, ReferenceTypeIds); if (reference != null) diff --git a/Samples/ClientControls.Net4/Common/Client/SelectNodeDlg.cs b/Samples/ClientControls.Net4/Common/Client/SelectNodeDlg.cs index 112f8c0e9..9e42ade21 100644 --- a/Samples/ClientControls.Net4/Common/Client/SelectNodeDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SelectNodeDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,8 @@ using System.Text; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -51,7 +53,7 @@ public SelectNodeDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields #endregion @@ -59,10 +61,11 @@ public SelectNodeDlg() /// /// Prompts the user to select a node. /// - public NodeId ShowDialog( - Session session, + public async Task ShowDialogAsync( + ISession session, NodeId rootId, string caption, + CancellationToken ct, params NodeId[] referenceTypeIds) { // set the caption. @@ -84,7 +87,7 @@ public NodeId ShowDialog( } // initialize the control. - BrowseCTRL.Initialize(session, rootId, referenceTypeIds); + await BrowseCTRL.InitializeAsync(session, rootId, ct, referenceTypeIds); // display the dialog. if (ShowDialog() != DialogResult.OK) @@ -106,11 +109,12 @@ public NodeId ShowDialog( /// /// Prompts the user to select a node. /// - public ReferenceDescription ShowDialog( - Session session, + public async Task ShowDialogAsync( + ISession session, NodeId rootId, - ViewDescription view, + ViewDescription view, string caption, + CancellationToken ct, params NodeId[] referenceTypeIds) { // set the caption. @@ -118,7 +122,7 @@ public ReferenceDescription ShowDialog( { this.Text = caption; } - + // set default root. if (NodeId.IsNull(rootId)) { @@ -132,7 +136,7 @@ public ReferenceDescription ShowDialog( } // initialize the control. - BrowseCTRL.Initialize(session, rootId, referenceTypeIds); + await BrowseCTRL.InitializeAsync(session, rootId, ct, referenceTypeIds); BrowseCTRL.View = view; // display the dialog. @@ -144,7 +148,7 @@ public ReferenceDescription ShowDialog( return BrowseCTRL.SelectedNode; } #endregion - + #region Private Methods #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/SetFilterOperatorDlg.cs b/Samples/ClientControls.Net4/Common/Client/SetFilterOperatorDlg.cs index 9ae1dd1ad..2fe5b0c4b 100644 --- a/Samples/ClientControls.Net4/Common/Client/SetFilterOperatorDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SetFilterOperatorDlg.cs @@ -63,7 +63,7 @@ public SetFilterOperatorDlg() FilterOperatorCB.Items.Add(FilterOperator.BitwiseOr); } #endregion - + #region Private Fields #endregion @@ -74,7 +74,7 @@ public SetFilterOperatorDlg() public bool ShowDialog(ref FilterOperator filterOperator) { FilterOperatorCB.SelectedItem = filterOperator; - + // display the dialog. if (base.ShowDialog() != DialogResult.OK) { @@ -85,7 +85,7 @@ public bool ShowDialog(ref FilterOperator filterOperator) return true; } #endregion - + #region Private Methods #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.Designer.cs index d36f5591d..5c78dff97 100644 --- a/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.Designer.cs @@ -203,7 +203,7 @@ private void InitializeComponent() this.StructureTypeBTN.NodeControl = this.StructureTypeTB; this.StructureTypeBTN.ReferenceTypeIds = null; this.StructureTypeBTN.RootId = null; - this.StructureTypeBTN.SelectedNode = null; + this.StructureTypeBTN.ClearSelectedNode(); this.StructureTypeBTN.SelectedReference = null; this.StructureTypeBTN.Session = null; this.StructureTypeBTN.Size = new System.Drawing.Size(24, 24); diff --git a/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.cs b/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.cs index bb31723e1..705999bb7 100644 --- a/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.cs @@ -57,7 +57,7 @@ public SetTypeDlg() StructureTypeBTN.ReferenceTypeIds = new NodeId[] { Opc.Ua.ReferenceTypeIds.HasSubtype }; } #endregion - + #region Private Fields private SetTypeResult m_result; private TypeInfo m_typeInfo; @@ -106,7 +106,7 @@ public SetTypeResult ShowDialog(TypeInfo typeInfo, int[] dimensions) ArrayDimensionsTB.Visible = dimensions != null; ErrorHandlingCB.SelectedIndex = 0; - + StringBuilder builder = new StringBuilder(); // display the current dimensions. @@ -134,7 +134,7 @@ public SetTypeResult ShowDialog(TypeInfo typeInfo, int[] dimensions) return m_result; } #endregion - + #region Private Methods #endregion @@ -177,7 +177,7 @@ private void OkBTN_Click(object sender, EventArgs e) dimensions.Add(dimension); } - + // save the result. int valueRank = (dimensions.Count < 1) ? ValueRanks.Scalar : dimensions.Count; diff --git a/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.Designer.cs index 181f649bf..50b56c376 100644 --- a/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.Designer.cs @@ -96,7 +96,7 @@ private void InitializeComponent() this.NextBTN.TabIndex = 1; this.NextBTN.Text = "Next"; this.NextBTN.UseVisualStyleBackColor = true; - this.NextBTN.Click += new System.EventHandler(this.NextBTN_Click); + this.NextBTN.Click += new System.EventHandler(this.NextBTN_ClickAsync); // // BackBTN // @@ -107,7 +107,7 @@ private void InitializeComponent() this.BackBTN.Text = "Back"; this.BackBTN.UseVisualStyleBackColor = true; this.BackBTN.Visible = false; - this.BackBTN.Click += new System.EventHandler(this.BackBTN_Click); + this.BackBTN.Click += new System.EventHandler(this.BackBTN_ClickAsync); // // SubscribeRequestCTRL // diff --git a/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.cs b/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.cs index 9d920a9ba..65110e6ff 100644 --- a/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,8 @@ using System.ComponentModel; using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -53,19 +55,20 @@ public SubscribeDataDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; #endregion - + #region Public Interface /// /// Changes the session used for the subscription. /// - public void ChangeSession(Session session) + public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { SubscribeRequestCTRL.ChangeSession(session); m_session = session; + return Task.CompletedTask; } /// @@ -92,9 +95,9 @@ public void SetSubscription(Subscription subscription) /// /// Adds the items to monitor. /// - public void AddItems(params ReadValueId[] nodesToRead) + public async Task AddItemsAsync(CancellationToken ct, params ReadValueId[] nodesToRead) { - SubscribeRequestCTRL.AddItems(nodesToRead); + await SubscribeRequestCTRL.AddItemsAsync(ct, nodesToRead); NextBTN.Visible = SubscribeRequestCTRL.CanCallNext; BackBTN.Visible = SubscribeRequestCTRL.CanCallBack; } @@ -104,11 +107,11 @@ public void AddItems(params ReadValueId[] nodesToRead) #endregion #region Event Handlers - private void NextBTN_Click(object sender, EventArgs e) + private async void NextBTN_ClickAsync(object sender, EventArgs e) { try { - SubscribeRequestCTRL.Next(); + await SubscribeRequestCTRL.NextAsync(); NextBTN.Visible = SubscribeRequestCTRL.CanCallNext; BackBTN.Visible = SubscribeRequestCTRL.CanCallBack; } @@ -118,11 +121,11 @@ private void NextBTN_Click(object sender, EventArgs e) } } - private void BackBTN_Click(object sender, EventArgs e) + private async void BackBTN_ClickAsync(object sender, EventArgs e) { try { - SubscribeRequestCTRL.Back(); + await SubscribeRequestCTRL.BackAsync(); NextBTN.Visible = SubscribeRequestCTRL.CanCallNext; BackBTN.Visible = SubscribeRequestCTRL.CanCallBack; } diff --git a/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.Designer.cs b/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.Designer.cs index 6afed8920..84f3fbd59 100644 --- a/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.Designer.cs @@ -114,14 +114,14 @@ private void InitializeComponent() this.NewMI.Name = "NewMI"; this.NewMI.Size = new System.Drawing.Size(196, 22); this.NewMI.Text = "New..."; - this.NewMI.Click += new System.EventHandler(this.NewMI_Click); + this.NewMI.Click += new System.EventHandler(this.NewMI_ClickAsync); // // EditMI // this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(196, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // DeleteMI // @@ -135,14 +135,14 @@ private void InitializeComponent() this.ViewValueMI.Name = "ViewValueMI"; this.ViewValueMI.Size = new System.Drawing.Size(196, 22); this.ViewValueMI.Text = "View Value...."; - this.ViewValueMI.Click += new System.EventHandler(this.ViewValueMI_Click); + this.ViewValueMI.Click += new System.EventHandler(this.ViewValueMI_ClickAsync); // // SetMonitoringModeMI // this.SetMonitoringModeMI.Name = "SetMonitoringModeMI"; this.SetMonitoringModeMI.Size = new System.Drawing.Size(196, 22); this.SetMonitoringModeMI.Text = "Set Monitoring Mode..."; - this.SetMonitoringModeMI.Click += new System.EventHandler(this.SetMonitoringModeMI_Click); + this.SetMonitoringModeMI.Click += new System.EventHandler(this.SetMonitoringModeMI_ClickAsync); // // ResultsDV // @@ -362,7 +362,7 @@ private void InitializeComponent() this.Subscription_EditMI.Name = "Subscription_EditMI"; this.Subscription_EditMI.Size = new System.Drawing.Size(152, 22); this.Subscription_EditMI.Text = "Edit..."; - this.Subscription_EditMI.Click += new System.EventHandler(this.Subscription_EditMI_Click); + this.Subscription_EditMI.Click += new System.EventHandler(this.Subscription_EditMI_ClickAsync); // // SequenceNumberLB // diff --git a/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.cs index 79eda8096..b6f436e49 100644 --- a/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,9 +30,11 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Drawing; using System.Data; +using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -82,7 +84,7 @@ public SubscribeDataListViewCtrl() #region Private Fields private DataSet m_dataset; - private Session m_session; + private ISession m_session; private Subscription m_subscription; private DisplayState m_state; private EditComplexValueDlg m_EditComplexValueDlg; @@ -105,7 +107,7 @@ private enum DisplayState /// /// Changes the session used. /// - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { if (!Object.ReferenceEquals(session, m_session)) { @@ -127,7 +129,7 @@ public void ChangeSession(Session session) { m_subscription = subscription; m_subscription.PublishStatusChanged += m_PublishStatusChanged; - m_subscription.FastDataChangeCallback = OnDataChange; + m_subscription.FastDataChangeCallback = OnDataChangeAsync; break; } } @@ -187,7 +189,7 @@ public void SetSubscription(Subscription subscription) m_subscription = subscription; m_subscription.DisableMonitoredItemCache = true; m_subscription.PublishStatusChanged += m_PublishStatusChanged; - m_subscription.FastDataChangeCallback = OnDataChange; + m_subscription.FastDataChangeCallback = OnDataChangeAsync; m_dataset.Tables[0].Rows.Clear(); if (m_subscription != null) @@ -200,7 +202,7 @@ public void SetSubscription(Subscription subscription) /// /// Adds the monitored items to the subscription. /// - public void AddItems(params ReadValueId[] itemsToMonitor) + public async Task AddItemsAsync(CancellationToken ct, params ReadValueId[] itemsToMonitor) { if (m_subscription == null) { @@ -228,7 +230,7 @@ public void AddItems(params ReadValueId[] itemsToMonitor) monitoredItem.Handle = row; m_subscription.AddItem(monitoredItem); - UpdateRow(row, monitoredItem); + await UpdateRowAsync(row, monitoredItem); m_dataset.Tables[0].Rows.Add(row); } } @@ -259,7 +261,7 @@ public bool CanCallBack /// /// Moves the grid to the next state. /// - public void Next() + public async Task NextAsync(CancellationToken ct = default) { if (m_state == DisplayState.ViewUpdates) { @@ -279,7 +281,7 @@ public void Next() // apply any changes. if (m_state == DisplayState.ApplyChanges) { - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); foreach (DataRow row in m_dataset.Tables[0].Rows) { @@ -293,7 +295,7 @@ public void Next() /// /// Moves the grid back to the edit items state. /// - public void Back() + public async Task BackAsync(CancellationToken ct = default) { if (m_state == DisplayState.EditItems) { @@ -310,7 +312,7 @@ public void Back() // revert to specified parameters. DataRowView source = row.DataBoundItem as DataRowView; MonitoredItem monitoredItem = (MonitoredItem)source.Row[0]; - UpdateRow(source.Row, monitoredItem); + await UpdateRowAsync(source.Row, monitoredItem, ct); } } #endregion @@ -375,11 +377,11 @@ private void SetDisplayState(DisplayState state) /// /// Updates the row with the monitored item. /// - private void UpdateRow(DataRow row, MonitoredItem monitoredItem) + private async Task UpdateRowAsync(DataRow row, MonitoredItem monitoredItem, CancellationToken ct = default) { row[0] = monitoredItem; row[1] = ImageList.Images[ClientUtils.GetImageIndex(monitoredItem.AttributeId, null)]; - row[2] = m_session.NodeCache.GetDisplayText(monitoredItem.StartNodeId) + "/" + Attributes.GetBrowseName(monitoredItem.AttributeId); + row[2] = await m_session.NodeCache.GetDisplayTextAsync(monitoredItem.StartNodeId, ct) + "/" + Attributes.GetBrowseName(monitoredItem.AttributeId); row[3] = monitoredItem.IndexRange; row[4] = monitoredItem.Encoding; row[5] = monitoredItem.MonitoringMode; @@ -442,9 +444,9 @@ private string GetDisplayString(Subscription subscription) buffer.Append(subscription.CurrentPublishingInterval); buffer.Append("ms/"); buffer.Append(subscription.CurrentKeepAliveCount); - buffer.Append("/"); + buffer.Append('/'); buffer.Append(subscription.CurrentLifetimeCount); - buffer.Append("}"); + buffer.Append('}'); return buffer.ToString(); } @@ -486,7 +488,7 @@ private void OnPublishStatusChanged(object sender, PublishStateChangedEventArgs } } - private void OnDataChange(Subscription subscription, DataChangeNotification notification, IList stringTable) + private async void OnDataChangeAsync(Subscription subscription, DataChangeNotification notification, IList stringTable) { if (!Object.ReferenceEquals(subscription, m_subscription)) { @@ -495,7 +497,7 @@ private void OnDataChange(Subscription subscription, DataChangeNotification noti if (this.InvokeRequired) { - this.BeginInvoke(new FastDataChangeNotificationEventHandler(OnDataChange), subscription, notification, stringTable); + this.BeginInvoke(new FastDataChangeNotificationEventHandler(OnDataChangeAsync), subscription, notification, stringTable); return; } @@ -521,7 +523,7 @@ private void OnDataChange(Subscription subscription, DataChangeNotification noti if (m_EditComplexValueDlg != null && Object.ReferenceEquals(m_EditComplexValueDlg.Tag, monitoredItem)) { - m_EditComplexValueDlg.UpdateValue(monitoredItem.ResolvedNodeId, monitoredItem.AttributeId, null, itemNotification.Value.Value); + await m_EditComplexValueDlg.UpdateValueAsync(monitoredItem.ResolvedNodeId, monitoredItem.AttributeId, null, itemNotification.Value.Value); } } } @@ -540,7 +542,7 @@ private void PopupMenu_Opening(object sender, CancelEventArgs e) SetMonitoringModeMI.Visible = m_state != DisplayState.ApplyChanges; } - private void NewMI_Click(object sender, EventArgs e) + private async void NewMI_ClickAsync(object sender, EventArgs e) { try { @@ -562,12 +564,12 @@ private void NewMI_Click(object sender, EventArgs e) monitoredItem = new MonitoredItem(monitoredItem); } - if (new EditMonitoredItemDlg().ShowDialog(m_session, monitoredItem, false)) + if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, false)) { m_subscription.AddItem(monitoredItem); DataRow row = m_dataset.Tables[0].NewRow(); monitoredItem.Handle = row; - UpdateRow(row, monitoredItem); + await UpdateRowAsync(row, monitoredItem); m_dataset.Tables[0].Rows.Add(row); } } @@ -577,7 +579,7 @@ private void NewMI_Click(object sender, EventArgs e) } } - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -595,10 +597,10 @@ private void EditMI_Click(object sender, EventArgs e) return; } - if (new EditMonitoredItemDlg().ShowDialog(m_session, monitoredItem, false)) + if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, false)) { DataRow row = (DataRow)monitoredItem.Handle; - UpdateRow(row, monitoredItem); + await UpdateRowAsync(row, monitoredItem); } } catch (Exception exception) @@ -627,7 +629,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } } - private void ViewValueMI_Click(object sender, EventArgs e) + private async void ViewValueMI_ClickAsync(object sender, EventArgs e) { try { @@ -650,7 +652,7 @@ private void ViewValueMI_Click(object sender, EventArgs e) m_EditComplexValueDlg = new EditComplexValueDlg(); m_EditComplexValueDlg.Tag = monitoredItem; - m_EditComplexValueDlg.ShowDialog( + await m_EditComplexValueDlg.ShowDialogAsync( m_session, monitoredItem.ResolvedNodeId, monitoredItem.AttributeId, @@ -673,11 +675,11 @@ private void ResultsDV_DoubleClick(object sender, EventArgs e) { if (m_state == DisplayState.EditItems) { - EditMI_Click(sender, e); + EditMI_ClickAsync(sender, e); } else { - ViewValueMI_Click(sender, e); + ViewValueMI_ClickAsync(sender, e); } } catch (Exception exception) @@ -686,7 +688,7 @@ private void ResultsDV_DoubleClick(object sender, EventArgs e) } } - private void SetMonitoringModeMI_Click(object sender, EventArgs e) + private async void SetMonitoringModeMI_ClickAsync(object sender, EventArgs e) { try { @@ -726,7 +728,7 @@ private void SetMonitoringModeMI_Click(object sender, EventArgs e) if (itemsToModify.Count != 0) { - m_subscription.SetMonitoringMode(newMonitoringMode, itemsToModify); + await m_subscription.SetMonitoringModeAsync(newMonitoringMode, itemsToModify); } } } @@ -736,17 +738,17 @@ private void SetMonitoringModeMI_Click(object sender, EventArgs e) } } - private void Subscription_EditMI_Click(object sender, EventArgs e) + private async void Subscription_EditMI_ClickAsync(object sender, EventArgs e) { try { if (new EditSubscriptionDlg().ShowDialog(m_subscription)) { - m_subscription.Modify(); + await m_subscription.ModifyAsync(); if (m_subscription.PublishingEnabled != m_subscription.CurrentPublishingEnabled) { - m_subscription.SetPublishingMode(m_subscription.PublishingEnabled); + await m_subscription.SetPublishingModeAsync(m_subscription.PublishingEnabled); } SubscriptionStateTB.Text = GetDisplayString(m_subscription); diff --git a/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.Designer.cs index 7cf6ecd6d..4cf535c0b 100644 --- a/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.Designer.cs @@ -145,7 +145,7 @@ private void InitializeComponent() this.NextBTN.TabIndex = 6; this.NextBTN.Text = "Next"; this.NextBTN.UseVisualStyleBackColor = true; - this.NextBTN.Click += new System.EventHandler(this.NextBTN_Click); + this.NextBTN.Click += new System.EventHandler(this.NextBTN_ClickAsync); // // BackBTN // @@ -155,7 +155,7 @@ private void InitializeComponent() this.BackBTN.TabIndex = 7; this.BackBTN.Text = "Back"; this.BackBTN.UseVisualStyleBackColor = true; - this.BackBTN.Click += new System.EventHandler(this.BackBTN_Click); + this.BackBTN.Click += new System.EventHandler(this.BackBTN_ClickAsync); // // ImageList // @@ -195,7 +195,7 @@ private void InitializeComponent() this.SubscriptionStateTB.Name = "SubscriptionStateTB"; this.SubscriptionStateTB.Size = new System.Drawing.Size(67, 20); this.SubscriptionStateTB.Text = ""; - this.SubscriptionStateTB.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.SubscriptionStateTB_DropDownItemClicked); + this.SubscriptionStateTB.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.SubscriptionStateTB_DropDownItemClickedAsync); // // Subscription_EditMI // @@ -323,14 +323,14 @@ private void InitializeComponent() this.NewMI.Name = "NewMI"; this.NewMI.Size = new System.Drawing.Size(196, 22); this.NewMI.Text = "New..."; - this.NewMI.Click += new System.EventHandler(this.NewMI_Click); + this.NewMI.Click += new System.EventHandler(this.NewMI_ClickAsync); // // EditMI // this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(196, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // DeleteMI // @@ -344,7 +344,7 @@ private void InitializeComponent() this.SetMonitoringModeMI.Name = "SetMonitoringModeMI"; this.SetMonitoringModeMI.Size = new System.Drawing.Size(196, 22); this.SetMonitoringModeMI.Text = "Set Monitoring Mode..."; - this.SetMonitoringModeMI.Click += new System.EventHandler(this.SetMonitoringModeMI_Click); + this.SetMonitoringModeMI.Click += new System.EventHandler(this.SetMonitoringModeMI_ClickAsync); // // EventTypePN // @@ -372,7 +372,7 @@ private void InitializeComponent() this.BrowseCTRL.Size = new System.Drawing.Size(261, 311); this.BrowseCTRL.TabIndex = 15; this.BrowseCTRL.View = null; - this.BrowseCTRL.AfterSelect += new System.EventHandler(this.BrowseCTRL_AfterSelect); + this.BrowseCTRL.AfterSelect += new System.EventHandler(this.BrowseCTRL_AfterSelectAsync); // // EventTypeCTRL // diff --git a/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.cs b/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.cs index cba47b470..174b7b092 100644 --- a/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,10 +29,12 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; -using System.Text; using System.Data; using System.Drawing; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -79,7 +81,7 @@ public SubscribeEventsDlg() private DataSet m_dataset; private FilterDeclaration m_filter; private DisplayState m_state; - private Session m_session; + private ISession m_session; private Subscription m_subscription; private PublishStateChangedEventHandler m_PublishStatusChanged; #endregion @@ -97,13 +99,13 @@ private enum DisplayState /// /// Changes the session used. /// - public void ChangeSession(Session session) + public async Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { if (!Object.ReferenceEquals(session, m_session)) { m_session = session; - BrowseCTRL.ChangeSession(m_session); + await BrowseCTRL.ChangeSessionAsync(m_session, ct); EventTypeCTRL.ChangeSession(m_session); EventFilterCTRL.ChangeSession(m_session); EventsCTRL.ChangeSession(m_session); @@ -172,7 +174,7 @@ public void SetSubscription(Subscription subscription) /// /// Adds items to the subscription. /// - public void AddItems(params NodeId[] itemsToMonitor) + public async Task AddItemsAsync(CancellationToken ct, params NodeId[] itemsToMonitor) { if (itemsToMonitor != null) { @@ -196,7 +198,7 @@ public void AddItems(params NodeId[] itemsToMonitor) monitoredItem.Handle = row; m_subscription.AddItem(monitoredItem); - UpdateRow(row, monitoredItem); + await UpdateRowAsync(row, monitoredItem); m_dataset.Tables[0].Rows.Add(row); } } @@ -205,7 +207,7 @@ public void AddItems(params NodeId[] itemsToMonitor) /// /// Moves the sequence forward. /// - public void Next() + public async Task NextAsync(CancellationToken ct = default) { if (m_state == DisplayState.ViewUpdates) { @@ -214,28 +216,28 @@ public void Next() if (m_state == DisplayState.SelectEventType) { - UpdateFilter(); + await UpdateFilterAsync(ct); } SetDisplayState(++m_state); if (m_state == DisplayState.SelectEventType) { - BrowseCTRL.Initialize(m_session, Opc.Ua.ObjectTypeIds.BaseEventType, Opc.Ua.ReferenceTypeIds.HasSubtype); + await BrowseCTRL.InitializeAsync(m_session, Opc.Ua.ObjectTypeIds.BaseEventType, ct, Opc.Ua.ReferenceTypeIds.HasSubtype); BrowseCTRL.SelectNode((m_filter == null || m_filter.EventTypeId == null) ? Opc.Ua.ObjectTypeIds.BaseEventType : m_filter.EventTypeId); - EventTypeCTRL.ShowType(Opc.Ua.ObjectTypeIds.BaseEventType); + await EventTypeCTRL.ShowTypeAsync(Opc.Ua.ObjectTypeIds.BaseEventType, ct); return; } if (m_state == DisplayState.SelectEventFields) { - EventFilterCTRL.SetFilter(m_filter); + await EventFilterCTRL.SetFilterAsync(m_filter, ct); return; } if (m_state == DisplayState.ApplyChanges) { - UpdateItems(); + await UpdateItemsAsync(ct); return; } @@ -249,7 +251,7 @@ public void Next() /// /// Moves the sequence backward. /// - public void Back() + public async Task BackAsync(CancellationToken ct = default) { if (m_state == DisplayState.EditItems) { @@ -260,7 +262,7 @@ public void Back() if (m_state == DisplayState.SelectEventFields) { - EventFilterCTRL.SetFilter(m_filter); + await EventFilterCTRL.SetFilterAsync(m_filter, ct); return; } } @@ -351,11 +353,11 @@ private void SetDisplayState(DisplayState state) /// /// Updates the row with the monitored item. /// - private void UpdateRow(DataRow row, MonitoredItem monitoredItem) + private async Task UpdateRowAsync(DataRow row, MonitoredItem monitoredItem, CancellationToken ct = default) { row[0] = monitoredItem; row[1] = ImageList.Images[ClientUtils.GetImageIndex(monitoredItem.AttributeId, null)]; - row[2] = m_session.NodeCache.GetDisplayText(monitoredItem.StartNodeId) + "/" + Attributes.GetBrowseName(monitoredItem.AttributeId); + row[2] = await m_session.NodeCache.GetDisplayTextAsync(monitoredItem.StartNodeId, ct) + "/" + Attributes.GetBrowseName(monitoredItem.AttributeId); row[3] = monitoredItem.MonitoringMode; row[4] = monitoredItem.SamplingInterval; row[5] = monitoredItem.DiscardOldest; @@ -400,7 +402,7 @@ private string GetDisplayString(Subscription subscription) /// /// Updates the items with the current filter. /// - private void UpdateItems() + private async Task UpdateItemsAsync(CancellationToken ct = default) { List fields = new List(); @@ -440,7 +442,7 @@ private void UpdateItems() } // apply changes. - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); // show results. for (int ii = 0; ii < m_dataset.Tables[0].Rows.Count; ii++) @@ -454,11 +456,11 @@ private void UpdateItems() /// /// Updates the filter from the controls. /// - private void UpdateFilter() + private async Task UpdateFilterAsync(CancellationToken ct = default) { // get selected declarations. List declarations = new List(); - NodeId eventTypeId = CollectInstanceDeclarations(declarations); + NodeId eventTypeId = await CollectInstanceDeclarationsAsync(declarations, ct); if (m_filter == null) { @@ -522,7 +524,7 @@ private void AddDefaultFilter(List fields, string browse /// /// Collects the instance declarations for the selected types. /// - private NodeId CollectInstanceDeclarations(List declarations) + private async Task CollectInstanceDeclarationsAsync(List declarations, CancellationToken ct = default) { List typeIds = new List(); @@ -532,7 +534,7 @@ private NodeId CollectInstanceDeclarations(List declaration // merge declarations from the selected types. foreach (NodeId typeId in typeIds) { - List declarations2 = ClientUtils.CollectInstanceDeclarationsForType(m_session, typeId); + List declarations2 = await ClientUtils.CollectInstanceDeclarationsForTypeAsync(m_session, typeId, ct); for (int ii = 0; ii < declarations2.Count; ii++) { @@ -705,11 +707,11 @@ private void OnEvent(Subscription subscription, EventNotificationList notificati } } - private void BackBTN_Click(object sender, EventArgs e) + private async void BackBTN_ClickAsync(object sender, EventArgs e) { try { - Back(); + await BackAsync(); } catch (Exception exception) { @@ -717,11 +719,11 @@ private void BackBTN_Click(object sender, EventArgs e) } } - private void NextBTN_Click(object sender, EventArgs e) + private async void NextBTN_ClickAsync(object sender, EventArgs e) { try { - Next(); + await NextAsync(); } catch (Exception exception) { @@ -741,7 +743,7 @@ private void OkBTN_Click(object sender, EventArgs e) } } - private void SubscriptionStateTB_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) + private async void SubscriptionStateTB_DropDownItemClickedAsync(object sender, ToolStripItemClickedEventArgs e) { try { @@ -755,11 +757,11 @@ private void SubscriptionStateTB_DropDownItemClicked(object sender, ToolStripIte return; } - m_subscription.Modify(); + await m_subscription.ModifyAsync(); if (m_subscription.PublishingEnabled != m_subscription.CurrentPublishingEnabled) { - m_subscription.SetPublishingMode(m_subscription.PublishingEnabled); + await m_subscription.SetPublishingModeAsync(m_subscription.PublishingEnabled); } SubscriptionStateTB.Text = GetDisplayString(m_subscription); @@ -770,7 +772,7 @@ private void SubscriptionStateTB_DropDownItemClicked(object sender, ToolStripIte } } - private void BrowseCTRL_AfterSelect(object sender, EventArgs e) + private async void BrowseCTRL_AfterSelectAsync(object sender, EventArgs e) { try { @@ -778,11 +780,11 @@ private void BrowseCTRL_AfterSelect(object sender, EventArgs e) if (reference == null || NodeId.IsNull(reference.NodeId) || reference.NodeId.IsAbsolute) { - EventTypeCTRL.ShowType(null); + await EventTypeCTRL.ShowTypeAsync(null); return; } - EventTypeCTRL.ShowType((NodeId)reference.NodeId); + await EventTypeCTRL.ShowTypeAsync((NodeId)reference.NodeId); } catch (Exception exception) { @@ -821,7 +823,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } } - private void NewMI_Click(object sender, EventArgs e) + private async void NewMI_ClickAsync(object sender, EventArgs e) { try { @@ -848,12 +850,12 @@ private void NewMI_Click(object sender, EventArgs e) monitoredItem = new MonitoredItem(monitoredItem); } - if (new EditMonitoredItemDlg().ShowDialog(m_session, monitoredItem, true)) + if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, true)) { m_subscription.AddItem(monitoredItem); DataRow row = m_dataset.Tables[0].NewRow(); monitoredItem.Handle = row; - UpdateRow(row, monitoredItem); + await UpdateRowAsync(row, monitoredItem); m_dataset.Tables[0].Rows.Add(row); } } @@ -863,7 +865,7 @@ private void NewMI_Click(object sender, EventArgs e) } } - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -886,10 +888,10 @@ private void EditMI_Click(object sender, EventArgs e) return; } - if (new EditMonitoredItemDlg().ShowDialog(m_session, monitoredItem, true)) + if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, true)) { DataRow row = (DataRow)monitoredItem.Handle; - UpdateRow(row, monitoredItem); + await UpdateRowAsync(row, monitoredItem); } } catch (Exception exception) @@ -929,7 +931,7 @@ private void ItemsDV_DoubleClick(object sender, EventArgs e) { if (m_state == DisplayState.EditItems) { - EditMI_Click(sender, e); + EditMI_ClickAsync(sender, e); } } catch (Exception exception) @@ -938,7 +940,7 @@ private void ItemsDV_DoubleClick(object sender, EventArgs e) } } - private void SetMonitoringModeMI_Click(object sender, EventArgs e) + private async void SetMonitoringModeMI_ClickAsync(object sender, EventArgs e) { try { @@ -983,7 +985,7 @@ private void SetMonitoringModeMI_Click(object sender, EventArgs e) if (itemsToModify.Count != 0) { - m_subscription.SetMonitoringMode(newMonitoringMode, itemsToModify); + await m_subscription.SetMonitoringModeAsync(newMonitoringMode, itemsToModify); } } } diff --git a/Samples/ClientControls.Net4/Common/Client/TypeFieldsListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/TypeFieldsListViewCtrl.cs index e8f3ca1cc..ac1773175 100644 --- a/Samples/ClientControls.Net4/Common/Client/TypeFieldsListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/TypeFieldsListViewCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,9 +30,11 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Drawing; using System.Data; +using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -53,7 +55,7 @@ public TypeFieldsListViewCtrl() InitializeComponent(); ResultsDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; - + m_dataset = new DataSet(); m_dataset.Tables.Add("Requests"); @@ -70,7 +72,7 @@ public TypeFieldsListViewCtrl() #region Private Fields private DataSet m_dataset; - private Session m_session; + private ISession m_session; private List m_declarations; #endregion @@ -78,7 +80,7 @@ public TypeFieldsListViewCtrl() /// /// Changes the session used by the control. /// - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { m_session = session; } @@ -86,7 +88,7 @@ public void ChangeSession(Session session) /// /// Displays the components of the type in the control. /// - public void ShowType(NodeId typeId) + public async Task ShowTypeAsync(NodeId typeId, CancellationToken ct = default) { if (NodeId.IsNull(typeId)) { @@ -94,7 +96,7 @@ public void ShowType(NodeId typeId) return; } - m_declarations = ClientUtils.CollectInstanceDeclarationsForType(m_session, typeId, false); + m_declarations = await ClientUtils.CollectInstanceDeclarationsForTypeAsync(m_session, typeId, false, ct); // update existing rows. for (int ii = 0; ii < m_declarations.Count && ii < m_dataset.Tables[0].Rows.Count; ii++) @@ -164,7 +166,7 @@ public void UpdateRow(DataRow row, InstanceDeclaration declaration) /// /// Reads the values displayed in the control and moves to the display results state. /// - public void Read() + public async Task ReadAsync(CancellationToken ct = default) { if (m_session == null) { @@ -185,18 +187,17 @@ public void Read() nodeToRead.AttributeId = (value.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId; nodesToRead.Add(nodeToRead); } - - // read the values. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.Read( + // read the values. + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Both, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); diff --git a/Samples/ClientControls.Net4/Common/Client/ViewEventDetailsDlg.cs b/Samples/ClientControls.Net4/Common/Client/ViewEventDetailsDlg.cs index 675c239f4..838be4ded 100644 --- a/Samples/ClientControls.Net4/Common/Client/ViewEventDetailsDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/ViewEventDetailsDlg.cs @@ -51,10 +51,10 @@ public ViewEventDetailsDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields #endregion - + #region Public Interface /// /// Shows all fields for the current condition. @@ -71,7 +71,7 @@ public bool ShowDialog(FilterDeclaration filter, VariantCollection fields) string text = null; // check for missing fields. - if (fields.Count <= ii+1 || fields[ii+1].Value == null) + if (fields.Count <= ii + 1 || fields[ii + 1].Value == null) { text = String.Empty; } @@ -79,7 +79,7 @@ public bool ShowDialog(FilterDeclaration filter, VariantCollection fields) // use default string format. else { - text = fields[ii+1].ToString(); + text = fields[ii + 1].ToString(); } item.SubItems.Add(text); diff --git a/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.Designer.cs b/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.Designer.cs index 05ca24b58..a178d7f52 100644 --- a/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.Designer.cs @@ -98,7 +98,7 @@ private void InitializeComponent() this.WriteBTN.TabIndex = 3; this.WriteBTN.Text = "Write"; this.WriteBTN.UseVisualStyleBackColor = true; - this.WriteBTN.Click += new System.EventHandler(this.WriteBTN_Click); + this.WriteBTN.Click += new System.EventHandler(this.WriteBTN_ClickAsync); // // ReadBTN // @@ -108,7 +108,7 @@ private void InitializeComponent() this.ReadBTN.TabIndex = 1; this.ReadBTN.Text = "Read"; this.ReadBTN.UseVisualStyleBackColor = true; - this.ReadBTN.Click += new System.EventHandler(this.ReadBTN_Click); + this.ReadBTN.Click += new System.EventHandler(this.ReadBTN_ClickAsync); // // BackBTN // diff --git a/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.cs b/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.cs index 777c079ed..523235d0a 100644 --- a/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,8 @@ using System.ComponentModel; using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -53,25 +55,26 @@ public WriteRequestDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields #endregion - + #region Public Interface /// /// Changes the session used for the read request. /// - public void ChangeSession(Session session) + public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { WriteRequestCTRL.ChangeSession(session); + return Task.CompletedTask; } /// /// Adds a node to the read request. /// - public void AddNodes(params WriteValue[] nodesToWrite) + public Task AddNodesAsync(CancellationToken ct, params WriteValue[] nodesToWrite) { - WriteRequestCTRL.AddNodes(nodesToWrite); + return WriteRequestCTRL.AddNodesAsync(ct, nodesToWrite); } #endregion @@ -79,11 +82,11 @@ public void AddNodes(params WriteValue[] nodesToWrite) #endregion #region Event Handlers - private void ReadBTN_Click(object sender, EventArgs e) + private async void ReadBTN_ClickAsync(object sender, EventArgs e) { try { - WriteRequestCTRL.Read(); + await WriteRequestCTRL.ReadAsync(); } catch (Exception exception) { @@ -91,11 +94,11 @@ private void ReadBTN_Click(object sender, EventArgs e) } } - private void WriteBTN_Click(object sender, EventArgs e) + private async void WriteBTN_ClickAsync(object sender, EventArgs e) { try { - WriteRequestCTRL.Write(); + await WriteRequestCTRL.WriteAsync(); ReadBTN.Visible = false; BackBTN.Visible = true; } diff --git a/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.Designer.cs b/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.Designer.cs index c2c6c3dff..9e370cc82 100644 --- a/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.Designer.cs @@ -97,7 +97,7 @@ private void InitializeComponent() this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(152, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // ResultsDV // @@ -126,7 +126,7 @@ private void InitializeComponent() this.ResultsDV.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.ResultsDV.Size = new System.Drawing.Size(754, 346); this.ResultsDV.TabIndex = 0; - this.ResultsDV.DoubleClick += new System.EventHandler(this.EditValueMI_Click); + this.ResultsDV.DoubleClick += new System.EventHandler(this.EditValueMI_ClickAsync); // // Icon // @@ -238,7 +238,7 @@ private void InitializeComponent() this.NewMI.Name = "NewMI"; this.NewMI.Size = new System.Drawing.Size(152, 22); this.NewMI.Text = "New..."; - this.NewMI.Click += new System.EventHandler(this.NewMI_Click); + this.NewMI.Click += new System.EventHandler(this.NewMI_ClickAsync); // // DeleteMI // @@ -252,7 +252,7 @@ private void InitializeComponent() this.EditValueMI.Name = "EditValueMI"; this.EditValueMI.Size = new System.Drawing.Size(152, 22); this.EditValueMI.Text = "Edit Value..."; - this.EditValueMI.Click += new System.EventHandler(this.EditValueMI_Click); + this.EditValueMI.Click += new System.EventHandler(this.EditValueMI_ClickAsync); // // WriteRequestListViewCtrl // diff --git a/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.cs index 80d1ba944..f9f4d6cd0 100644 --- a/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -53,7 +55,7 @@ public WriteRequestListViewCtrl() InitializeComponent(); ResultsDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; - + m_dataset = new DataSet(); m_dataset.Tables.Add("Requests"); @@ -75,14 +77,14 @@ public WriteRequestListViewCtrl() #region Private Fields private DataSet m_dataset; - private Session m_session; + private ISession m_session; #endregion #region Public Members /// /// Changes the session used for the write request. /// - public void ChangeSession(Session session) + public void ChangeSession(ISession session) { m_session = session; } @@ -90,32 +92,32 @@ public void ChangeSession(Session session) /// /// Adds the nodes to the write request. /// - public void AddNodes(params WriteValue[] nodesToWrite) + public async Task AddNodesAsync(CancellationToken ct, params WriteValue[] nodesToWrite) { if (nodesToWrite != null && nodesToWrite.Length > 0) { foreach (WriteValue nodeToWrite in nodesToWrite) { DataRow row = m_dataset.Tables[0].NewRow(); - UpdateRow(row, nodeToWrite); + await UpdateRowAsync(row, nodeToWrite, ct); nodeToWrite.Handle = row; m_dataset.Tables[0].Rows.Add(row); } - Read(nodesToWrite); + await ReadAsync(ct, nodesToWrite); } } /// /// Updates the values with the current values read from the server. /// - public void Read(params WriteValue[] nodesToWrite) + public async Task ReadAsync(CancellationToken ct = default, params WriteValue[] nodesToWrite) { if (m_session == null) { throw new ServiceResultException(StatusCodes.BadNotConnected); } - + // build list of values to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); @@ -151,16 +153,15 @@ public void Read(params WriteValue[] nodesToWrite) } // read the values. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -182,7 +183,7 @@ public void Read(params WriteValue[] nodesToWrite) /// /// Reads the values displayed in the control and moves to the display results state. /// - public void Write() + public async Task WriteAsync(CancellationToken ct = default) { if (m_session == null) { @@ -199,16 +200,15 @@ public void Write() row.Selected = false; nodesToWrite.Add(value); } - - // read the values. - StatusCodeCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.Write( + // read the values. + WriteResponse response = await m_session.WriteAsync( null, nodesToWrite, - out results, - out diagnosticInfos); + ct); + + StatusCodeCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); @@ -270,11 +270,11 @@ public void UpdateRow(DataRow row, DataValue value) /// /// Updates the row with the node to write. /// - public void UpdateRow(DataRow row, WriteValue nodeToWrite) + public async Task UpdateRowAsync(DataRow row, WriteValue nodeToWrite, CancellationToken ct = default) { row[0] = nodeToWrite; row[1] = ImageList.Images[ClientUtils.GetImageIndex(nodeToWrite.AttributeId, null)]; - row[2] = (m_session != null) ? m_session.NodeCache.GetDisplayText(nodeToWrite.NodeId) : Utils.ToString(nodeToWrite.NodeId); + row[2] = (m_session != null) ? await m_session.NodeCache.GetDisplayTextAsync(nodeToWrite.NodeId, ct) : Utils.ToString(nodeToWrite.NodeId); row[3] = Attributes.GetBrowseName(nodeToWrite.AttributeId); row[4] = nodeToWrite.IndexRange; @@ -289,7 +289,7 @@ private void PopupMenu_Opening(object sender, CancelEventArgs e) { EditMI.Enabled = ResultsDV.SelectedRows.Count == 1; EditValueMI.Enabled = ResultsDV.SelectedRows.Count > 0; - DeleteMI.Enabled = ResultsDV.SelectedRows.Count > 0; + DeleteMI.Enabled = ResultsDV.SelectedRows.Count > 0; } catch (Exception exception) { @@ -297,7 +297,7 @@ private void PopupMenu_Opening(object sender, CancelEventArgs e) } } - private void NewMI_Click(object sender, EventArgs e) + private async void NewMI_ClickAsync(object sender, EventArgs e) { try { @@ -318,12 +318,12 @@ private void NewMI_Click(object sender, EventArgs e) } // prompt use to edit new value. - WriteValue result = new EditWriteValueDlg().ShowDialog(m_session, nodeToWrite); + WriteValue result = await new EditWriteValueDlg().ShowDialogAsync(m_session, nodeToWrite); if (result != null) { DataRow row = m_dataset.Tables[0].NewRow(); - UpdateRow(row, result); + await UpdateRowAsync(row, result); m_dataset.Tables[0].Rows.Add(row); } } @@ -333,7 +333,7 @@ private void NewMI_Click(object sender, EventArgs e) } } - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -343,11 +343,11 @@ private void EditMI_Click(object sender, EventArgs e) DataRowView source = row.DataBoundItem as DataRowView; WriteValue value = (WriteValue)source.Row[0]; - WriteValue result = new EditWriteValueDlg().ShowDialog(m_session, value); + WriteValue result = await new EditWriteValueDlg().ShowDialogAsync(m_session, value); if (result != null) { - UpdateRow(source.Row, result); + await UpdateRowAsync(source.Row, result); } break; @@ -359,7 +359,7 @@ private void EditMI_Click(object sender, EventArgs e) } } - private void EditValueMI_Click(object sender, EventArgs e) + private async void EditValueMI_ClickAsync(object sender, EventArgs e) { try { @@ -376,7 +376,7 @@ private void EditValueMI_Click(object sender, EventArgs e) if (nodeToWrite != null) { // prompt use to edit value. - object value = new EditComplexValueDlg().ShowDialog( + object value = new EditComplexValueDlg().ShowDialogAsync( m_session, nodeToWrite.NodeId, nodeToWrite.AttributeId, @@ -393,10 +393,10 @@ private void EditValueMI_Click(object sender, EventArgs e) DataRowView source = row.DataBoundItem as DataRowView; nodeToWrite = (WriteValue)source.Row[0]; nodeToWrite.Value.Value = value; - UpdateRow(source.Row, nodeToWrite); + await UpdateRowAsync(source.Row, nodeToWrite); } } - } + } } catch (Exception exception) { diff --git a/Samples/ClientControls.Net4/Common/ClientUtils.cs b/Samples/ClientControls.Net4/Common/ClientUtils.cs index 93af6fd55..e9c62752c 100644 --- a/Samples/ClientControls.Net4/Common/ClientUtils.cs +++ b/Samples/ClientControls.Net4/Common/ClientUtils.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -27,6 +27,8 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; namespace Opc.Ua.Client.Controls @@ -78,7 +80,7 @@ public static int GetImageIndex(bool isOutputArgument, object value) /// /// Returns an image index for the specified attribute. /// - #pragma warning disable 0162 +#pragma warning disable 0162 public static int GetImageIndex(uint attributeId, object value) { // Workaround to avoid exception when accessing ImageList @@ -149,11 +151,11 @@ public static int GetImageIndex(uint attributeId, object value) /// /// Returns an image index for the specified attribute. /// - public static int GetImageIndex(Session session, NodeClass nodeClass, ExpandedNodeId typeDefinitionId, bool selected) + public static async Task GetImageIndexAsync(ISession session, NodeClass nodeClass, ExpandedNodeId typeDefinitionId, bool selected, CancellationToken ct = default) { if (nodeClass == NodeClass.Variable) { - if (session.NodeCache.IsTypeOf(typeDefinitionId, Opc.Ua.VariableTypeIds.PropertyType)) + if (await session.NodeCache.IsTypeOfAsync(typeDefinitionId, Opc.Ua.VariableTypeIds.PropertyType, ct)) { return ClientUtils.Property; } @@ -163,7 +165,7 @@ public static int GetImageIndex(Session session, NodeClass nodeClass, ExpandedNo if (nodeClass == NodeClass.Object) { - if (session.NodeCache.IsTypeOf(typeDefinitionId, Opc.Ua.ObjectTypeIds.FolderType)) + if (await session.NodeCache.IsTypeOfAsync(typeDefinitionId, Opc.Ua.ObjectTypeIds.FolderType, ct)) { if (selected) { diff --git a/Samples/ClientControls.Net4/Common/DiscoverServerDlg.Designer.cs b/Samples/ClientControls.Net4/Common/DiscoverServerDlg.Designer.cs index 1ffe90f73..3b86d436e 100644 --- a/Samples/ClientControls.Net4/Common/DiscoverServerDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Common/DiscoverServerDlg.Designer.cs @@ -129,7 +129,7 @@ private void InitializeComponent() this.FindBTN.TabIndex = 4; this.FindBTN.Text = "Find"; this.FindBTN.UseVisualStyleBackColor = true; - this.FindBTN.Click += new System.EventHandler(this.FindBTN_Click); + this.FindBTN.Click += new System.EventHandler(this.FindBTN_ClickAsync); // // DiscoverServerDlg // diff --git a/Samples/ClientControls.Net4/Common/DiscoverServerDlg.cs b/Samples/ClientControls.Net4/Common/DiscoverServerDlg.cs index 308d51b52..1cd666ae1 100644 --- a/Samples/ClientControls.Net4/Common/DiscoverServerDlg.cs +++ b/Samples/ClientControls.Net4/Common/DiscoverServerDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,8 @@ using System.ComponentModel; using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -53,11 +55,11 @@ public DiscoverServerDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields private ApplicationConfiguration m_configuration; #endregion - + #region Public Interface /// /// Shows the dialog. @@ -103,7 +105,7 @@ public string ShowDialog(ApplicationConfiguration configuration, string hostName /// Gets the endpoints for the host. /// /// Name of the host. - private string[] GetEndpoints(string hostName) + private async Task GetEndpointsAsync(string hostName, CancellationToken ct = default) { List urls = new List(); @@ -118,7 +120,7 @@ private string[] GetEndpoints(string hostName) // Connect to the local discovery server and find the available servers. using (DiscoveryClient client = DiscoveryClient.Create(new Uri(Utils.Format("opc.tcp://{0}:4840", hostName)), configuration)) { - ApplicationDescriptionCollection servers = client.FindServers(null); + ApplicationDescriptionCollection servers = await client.FindServersAsync(null, ct); // populate the drop down list with the discovery URLs for the available servers. for (int ii = 0; ii < servers.Count; ii++) @@ -134,7 +136,7 @@ private string[] GetEndpoints(string hostName) string discoveryUrl = servers[ii].DiscoveryUrls[jj]; // Many servers will use the '/discovery' suffix for the discovery endpoint. - // The URL without this prefix should be the base URL for the server. + // The URL without this prefix should be the base URL for the server. if (discoveryUrl.EndsWith("/discovery")) { discoveryUrl = discoveryUrl.Substring(0, discoveryUrl.Length - "/discovery".Length); @@ -161,7 +163,7 @@ private string[] GetEndpoints(string hostName) } } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { @@ -190,7 +192,7 @@ private void ServersLB_SelectedIndexChanged(object sender, EventArgs e) } } - private void FindBTN_Click(object sender, EventArgs e) + private async void FindBTN_ClickAsync(object sender, EventArgs e) { try { @@ -206,10 +208,7 @@ private void FindBTN_Click(object sender, EventArgs e) ServersLB.Items.Clear(); - foreach (string url in GetEndpoints(ValueTB.Text)) - { - ServersLB.Items.Add(url); - } + ServersLB.Items.AddRange(await GetEndpointsAsync(ValueTB.Text)); if (ServersLB.Items.Count == 0) { diff --git a/Samples/ClientControls.Net4/Common/DiscoveredServerListCtrl.cs b/Samples/ClientControls.Net4/Common/DiscoveredServerListCtrl.cs index 6bb99e0c0..9164f4b87 100644 --- a/Samples/ClientControls.Net4/Common/DiscoveredServerListCtrl.cs +++ b/Samples/ClientControls.Net4/Common/DiscoveredServerListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -37,6 +37,7 @@ using System.Threading; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -57,17 +58,17 @@ public DiscoveredServerListCtrl() ItemsLV.MultiSelect = false; } #endregion - + #region Private Fields - // The columns to display in the control. - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "Type", HorizontalAlignment.Left, null }, - new object[] { "Host", HorizontalAlignment.Left, null }, - new object[] { "URI", HorizontalAlignment.Left, null } - }; - + // The columns to display in the control. + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "Type", HorizontalAlignment.Left, null }, + new object[] { "Host", HorizontalAlignment.Left, null }, + new object[] { "URI", HorizontalAlignment.Left, null } + }; + private ApplicationConfiguration m_configuration; private int m_discoveryTimeout; private int m_discoverCount; @@ -125,7 +126,7 @@ public void Initialize(string hostname, ApplicationConfiguration configuration) { hostname = System.Net.Dns.GetHostName(); } - + this.Instructions = Utils.Format("Discovering servers on host '{0}'.", hostname); AdjustColumns(); @@ -141,7 +142,7 @@ public void Initialize(string hostname, ApplicationConfiguration configuration) { discoveryUrls = new StringCollection(Utils.DiscoveryUrls); } - + // update the urls with the hostname. StringCollection urlsToUse = new StringCollection(); @@ -151,7 +152,7 @@ public void Initialize(string hostname, ApplicationConfiguration configuration) } Interlocked.Increment(ref m_discoverCount); - ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverServers), urlsToUse); + Task.Run(() => OnDiscoverServersAsync(urlsToUse)); } /// @@ -164,7 +165,7 @@ private void OnUpdateServers(object state) this.BeginInvoke(new WaitCallback(OnUpdateServers), state); return; } - + ItemsLV.Items.Clear(); ApplicationDescriptionCollection servers = state as ApplicationDescriptionCollection; @@ -193,15 +194,12 @@ private void OnUpdateServers(object state) /// /// Attempts fetch the list of servers from the discovery server. /// - private void OnDiscoverServers(object state) + private async Task OnDiscoverServersAsync(IList discoveryUrls, CancellationToken ct = default) { try { int discoverCount = m_discoverCount; - // do nothing if a valid list is not provided. - IList discoveryUrls = state as IList; - if (discoveryUrls == null) { return; @@ -214,7 +212,7 @@ private void OnDiscoverServers(object state) if (url != null) { - if (DiscoverServers(url)) + if (await DiscoverServersAsync(url, ct)) { return; } @@ -239,7 +237,7 @@ private void OnDiscoverServers(object state) /// /// Fetches the servers from the discovery server. /// - private bool DiscoverServers(Uri discoveryUrl) + private async Task DiscoverServersAsync(Uri discoveryUrl, CancellationToken ct = default) { // use a short timeout. EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration); @@ -253,7 +251,7 @@ private bool DiscoverServers(Uri discoveryUrl) discoveryUrl, EndpointConfiguration.Create(m_configuration)); - ApplicationDescriptionCollection servers = client.FindServers(null); + ApplicationDescriptionCollection servers = await client.FindServersAsync(null, ct); m_discoveryUrl = discoveryUrl.ToString(); OnUpdateServers(servers); return true; @@ -267,7 +265,7 @@ private bool DiscoverServers(Uri discoveryUrl) { if (client != null) { - client.Close(); + await client.CloseAsync(ct); } } } @@ -277,13 +275,13 @@ private bool DiscoverServers(Uri discoveryUrl) /// /// Updates an item in the control. /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { ApplicationDescription server = listItem.Tag as ApplicationDescription; if (server == null) { - base.UpdateItem(listItem, server); + await base.UpdateItemAsync(listItem, server, ct); return; } @@ -291,10 +289,10 @@ protected override void UpdateItem(ListViewItem listItem, object item) // extract host from application uri. Uri uri = Utils.ParseUri(server.ApplicationUri); - + if (uri != null) { - hostname = uri.DnsSafeHost; + hostname = uri.DnsSafeHost; } // get the host name from the discovery urls. @@ -312,10 +310,10 @@ protected override void UpdateItem(ListViewItem listItem, object item) } } - listItem.SubItems[0].Text = String.Format("{0}", server.ApplicationName); - listItem.SubItems[1].Text = String.Format("{0}", server.ApplicationType); - listItem.SubItems[2].Text = String.Format("{0}", hostname); - listItem.SubItems[3].Text = String.Format("{0}", server.ApplicationUri); + listItem.SubItems[0].Text = String.Format("{0}", server.ApplicationName); + listItem.SubItems[1].Text = String.Format("{0}", server.ApplicationType); + listItem.SubItems[2].Text = String.Format("{0}", hostname); + listItem.SubItems[3].Text = String.Format("{0}", server.ApplicationUri); listItem.ImageKey = GuiUtils.Icons.Service; } diff --git a/Samples/ClientControls.Net4/Common/DiscoveredServerListDlg.cs b/Samples/ClientControls.Net4/Common/DiscoveredServerListDlg.cs index b653410a1..583d06b95 100644 --- a/Samples/ClientControls.Net4/Common/DiscoveredServerListDlg.cs +++ b/Samples/ClientControls.Net4/Common/DiscoveredServerListDlg.cs @@ -53,13 +53,13 @@ public DiscoveredServerListDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields private string m_hostname; private ApplicationDescription m_server; private ApplicationConfiguration m_configuration; #endregion - + #region Public Interface /// /// Displays the dialog. @@ -85,11 +85,11 @@ public ApplicationDescription ShowDialog(string hostname, ApplicationConfigurati { return null; } - + return m_server; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListCtrl.cs b/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListCtrl.cs index b4ae4c372..867b0120f 100644 --- a/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListCtrl.cs +++ b/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -37,6 +37,7 @@ using System.Threading; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -59,7 +60,7 @@ public DiscoveredServerOnNetworkListCtrl() #endregion #region Private Fields - // The columns to display in the control. + // The columns to display in the control. private readonly object[][] m_ColumnNames = new object[][] { new object[] { "RecordId", HorizontalAlignment.Left, null }, @@ -141,7 +142,7 @@ public void Initialize(string hostname, NumericUpDown startingRecordId, NumericU } Interlocked.Increment(ref m_discoverCount); - ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverServersOnNetwork), urlsToUse); + Task.Run(() => OnDiscoverServersOnNetworkAsync(urlsToUse)); } /// @@ -178,15 +179,13 @@ private void OnUpdateServers(object state) /// /// Attempts fetch the list of network servers from the discovery server. /// - private void OnDiscoverServersOnNetwork(object state) + private async Task OnDiscoverServersOnNetworkAsync(IList discoveryUrls, CancellationToken ct = default) { try { int discoverCount = m_discoverCount; // do nothing if a valid list is not provided. - IList discoveryUrls = state as IList; - if (discoveryUrls == null) { return; @@ -199,7 +198,7 @@ private void OnDiscoverServersOnNetwork(object state) if (url != null) { - if (DiscoverServersOnNetwork(url)) + if (await DiscoverServersOnNetworkAsync(url, ct)) { return; } @@ -224,7 +223,7 @@ private void OnDiscoverServersOnNetwork(object state) /// /// Fetches the network servers from the discovery server. /// - private bool DiscoverServersOnNetwork(Uri discoveryUrl) + private async Task DiscoverServersOnNetworkAsync(Uri discoveryUrl, CancellationToken ct = default) { // use a short timeout. EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration); @@ -258,7 +257,8 @@ private bool DiscoverServersOnNetwork(Uri discoveryUrl) return false; } - ServerOnNetworkCollection servers = client.FindServersOnNetwork(startingRecordId, maxRecordsToReturn, serverCapabilityFilter, out lastCounterResetTime); + ServerOnNetworkCollection servers; + (servers, lastCounterResetTime) = await client.FindServersOnNetworkAsync(startingRecordId, maxRecordsToReturn, serverCapabilityFilter, ct); m_discoveryUrl = discoveryUrl.ToString(); OnUpdateServers(servers); return true; @@ -272,7 +272,7 @@ private bool DiscoverServersOnNetwork(Uri discoveryUrl) { if (client != null) { - client.Close(); + await client.CloseAsync(ct); } } } @@ -282,13 +282,13 @@ private bool DiscoverServersOnNetwork(Uri discoveryUrl) /// /// Updates an item in the control. /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { ServerOnNetwork server = listItem.Tag as ServerOnNetwork; if (server == null) { - base.UpdateItem(listItem, server); + await base.UpdateItemAsync(listItem, server, ct); return; } diff --git a/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListDlg.cs b/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListDlg.cs index ede7c5b4a..96e8cab5b 100644 --- a/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListDlg.cs +++ b/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListDlg.cs @@ -53,13 +53,13 @@ public DiscoveredServerOnNetworkListDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields private string m_hostname; private ServerOnNetwork m_server; private ApplicationConfiguration m_configuration; #endregion - + #region Public Interface /// /// Displays the dialog. @@ -85,11 +85,11 @@ public ServerOnNetwork ShowDialog(string hostname, ApplicationConfiguration conf { return null; } - + return m_server; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { @@ -110,7 +110,7 @@ private void HostNameCTRL_HostSelected(object sender, SelectHostCtrlEventArgs e) if (m_hostname != e.Hostname) { m_hostname = e.Hostname; - ServersCTRL.Initialize(m_hostname,this.StartingRecordUP, this.MaxRecordsUP, this.CapabilityFilterTB, m_configuration); + ServersCTRL.Initialize(m_hostname, this.StartingRecordUP, this.MaxRecordsUP, this.CapabilityFilterTB, m_configuration); m_server = null; OkBTN.Enabled = false; } diff --git a/Samples/ClientControls.Net4/Common/EditDataValueCtrl.cs b/Samples/ClientControls.Net4/Common/EditDataValueCtrl.cs index 9711e6b07..f58cf3e93 100644 --- a/Samples/ClientControls.Net4/Common/EditDataValueCtrl.cs +++ b/Samples/ClientControls.Net4/Common/EditDataValueCtrl.cs @@ -186,7 +186,7 @@ public BuiltInType DataType DataTypeCB.SelectedItem = value; } } - + /// /// The value rank of the value displayed in the control. /// diff --git a/Samples/ClientControls.Net4/Common/EditDataValueDlg.cs b/Samples/ClientControls.Net4/Common/EditDataValueDlg.cs index 59e5cdcb2..1972d387b 100644 --- a/Samples/ClientControls.Net4/Common/EditDataValueDlg.cs +++ b/Samples/ClientControls.Net4/Common/EditDataValueDlg.cs @@ -51,7 +51,7 @@ public EditDataValueDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields private DataValue m_value; #endregion @@ -104,7 +104,7 @@ public DataValue ShowDialog(DataValue value, TypeInfo expectedType, string capti return m_value; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Samples/ClientControls.Net4/Common/EditValueCtrl.cs b/Samples/ClientControls.Net4/Common/EditValueCtrl.cs index df4a5cee2..3585c1b75 100644 --- a/Samples/ClientControls.Net4/Common/EditValueCtrl.cs +++ b/Samples/ClientControls.Net4/Common/EditValueCtrl.cs @@ -62,7 +62,7 @@ public EditValueCtrl() /// /// The value being edited in the control. /// - public Variant Value + public Variant Value { get { diff --git a/Samples/ClientControls.Net4/Common/EventListView.Designer.cs b/Samples/ClientControls.Net4/Common/EventListView.Designer.cs index eabd0afb7..cc541b223 100644 --- a/Samples/ClientControls.Net4/Common/EventListView.Designer.cs +++ b/Samples/ClientControls.Net4/Common/EventListView.Designer.cs @@ -97,7 +97,7 @@ private void InitializeComponent() this.DeleteHistoryMI.Name = "DeleteHistoryMI"; this.DeleteHistoryMI.Size = new System.Drawing.Size(196, 22); this.DeleteHistoryMI.Text = "Delete from Historian..."; - this.DeleteHistoryMI.Click += new System.EventHandler(this.DeleteHistoryMI_Click); + this.DeleteHistoryMI.Click += new System.EventHandler(this.DeleteHistoryMI_ClickAsync); // // EventListView // diff --git a/Samples/ClientControls.Net4/Common/EventListView.cs b/Samples/ClientControls.Net4/Common/EventListView.cs index 1eda7fd0b..fb7247d41 100644 --- a/Samples/ClientControls.Net4/Common/EventListView.cs +++ b/Samples/ClientControls.Net4/Common/EventListView.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; +using System.Threading; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -66,26 +68,23 @@ public EventListView() /// /// Whether the control subscribes for new events. /// - public bool IsSubscribed + public bool IsSubscribed => m_isSubscribed; + + public async Task SetSubscribedAsync(bool subscribed, CancellationToken ct = default) { - get { return m_isSubscribed; } - - set + if (m_isSubscribed != subscribed) { - if (m_isSubscribed != value) - { - m_isSubscribed = value; + m_isSubscribed = subscribed; - if (m_session != null) + if (m_session != null) + { + if (m_isSubscribed) { - if (m_isSubscribed) - { - CreateSubscription(); - } - else - { - DeleteSubscription(); - } + await CreateSubscriptionAsync(ct); + } + else + { + await DeleteSubscriptionAsync(ct); } } } @@ -128,7 +127,7 @@ public FilterDeclaration Filter /// /// Changes the session. /// - public void ChangeSession(Session session, bool fetchRecent) + public async Task ChangeSessionAsync(Session session, bool fetchRecent, CancellationToken ct = default) { if (Object.ReferenceEquals(session, m_session)) { @@ -137,7 +136,7 @@ public void ChangeSession(Session session, bool fetchRecent) if (m_session != null) { - DeleteSubscription(); + await DeleteSubscriptionAsync(ct); m_session = null; } @@ -146,22 +145,22 @@ public void ChangeSession(Session session, bool fetchRecent) if (m_session != null && m_isSubscribed) { - CreateSubscription(); + await CreateSubscriptionAsync(ct); if (fetchRecent) { - ReadRecentHistory(); + await ReadRecentHistoryAsync(ct); } } } - + /// /// Updates the control after the session has reconnected. /// public void SessionReconnected(Session session) { m_session = session; - + if (m_isSubscribed) { foreach (Subscription subscription in m_session.Subscriptions) @@ -185,14 +184,14 @@ public void SessionReconnected(Session session) /// /// Changes the area monitored by the control. /// - public void ChangeArea(NodeId areaId, bool fetchRecent) + public async Task ChangeAreaAsync(NodeId areaId, bool fetchRecent, CancellationToken ct = default) { m_areaId = areaId; EventsLV.Items.Clear(); if (fetchRecent) { - ReadRecentHistory(); + await ReadRecentHistoryAsync(ct); } if (m_subscription != null) @@ -204,16 +203,16 @@ public void ChangeArea(NodeId areaId, bool fetchRecent) m_subscription.RemoveItem(m_monitoredItem); m_monitoredItem = monitoredItem; - monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); + monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); } } /// /// Changes the filter used to select the events. /// - public void ChangeFilter(FilterDeclaration filter, bool fetchRecent) + public async Task ChangeFilterAsync(FilterDeclaration filter, bool fetchRecent, CancellationToken ct = default) { m_filter = filter; EventsLV.Items.Clear(); @@ -254,14 +253,14 @@ public void ChangeFilter(FilterDeclaration filter, bool fetchRecent) // fetch recent history. if (fetchRecent) { - ReadRecentHistory(); + await ReadRecentHistoryAsync(ct); } // update subscription. if (m_subscription != null && m_filter != null) { m_monitoredItem.Filter = m_filter.GetFilter(); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); } } @@ -282,11 +281,11 @@ public void ClearEventHistory() /// /// Adds the event history to the control. /// - public void AddEventHistory(HistoryEvent events) + public async Task AddEventHistoryAsync(HistoryEvent events, CancellationToken ct = default) { for (int ii = 0; ii < events.Events.Count; ii++) { - ListViewItem item = CreateListItem(m_filter, events.Events[ii].EventFields); + ListViewItem item = await CreateListItemAsync(m_filter, events.Events[ii].EventFields, ct); EventsLV.Items.Add(item); } @@ -300,11 +299,11 @@ public void AddEventHistory(HistoryEvent events) /// /// Refreshes the conditions displayed. /// - public void ConditionRefresh() + public async Task ConditionRefreshAsync(CancellationToken ct = default) { if (m_subscription != null) { - m_subscription.ConditionRefresh(); + await m_subscription.ConditionRefreshAsync(ct); } } @@ -326,7 +325,7 @@ public VariantCollection GetSelectedEvent(int index) /// /// Creates the subscription. /// - private void CreateSubscription() + private async Task CreateSubscriptionAsync(CancellationToken ct = default) { m_subscription = new Subscription(); m_subscription.Handle = this; @@ -339,7 +338,7 @@ private void CreateSubscription() m_subscription.TimestampsToReturn = TimestampsToReturn.Both; m_session.AddSubscription(m_subscription); - m_subscription.Create(); + await m_subscription.CreateAsync(ct); m_monitoredItem = new MonitoredItem(); m_monitoredItem.StartNodeId = m_areaId; @@ -348,23 +347,23 @@ private void CreateSubscription() m_monitoredItem.QueueSize = 1000; m_monitoredItem.DiscardOldest = true; - ChangeFilter(m_filter, false); + await ChangeFilterAsync(m_filter, false, ct); - m_monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); + m_monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); m_subscription.AddItem(m_monitoredItem); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); } /// /// Deletes the subscription. /// - private void DeleteSubscription() + private async Task DeleteSubscriptionAsync(CancellationToken ct = default) { if (m_subscription != null) { - m_subscription.Delete(true); - m_session.RemoveSubscription(m_subscription); + await m_subscription.DeleteAsync(true, ct); + await m_session.RemoveSubscriptionAsync(m_subscription, ct); m_subscription = null; m_monitoredItem = null; } @@ -373,7 +372,7 @@ private void DeleteSubscription() /// /// Creates list item for an event. /// - private ListViewItem CreateListItem(FilterDeclaration filter, VariantCollection fieldValues) + private async Task CreateListItemAsync(FilterDeclaration filter, VariantCollection fieldValues, CancellationToken ct = default) { ListViewItem item = null; @@ -425,7 +424,7 @@ private ListViewItem CreateListItem(FilterDeclaration filter, VariantCollection // display the name of a node instead of the node id. else if (value.TypeInfo.BuiltInType == BuiltInType.NodeId) { - INode node = m_session.NodeCache.Find((NodeId)value.Value); + INode node = await m_session.NodeCache.FindAsync((NodeId)value.Value, ct); if (node != null) { @@ -477,13 +476,13 @@ private ListViewItem CreateListItem(FilterDeclaration filter, VariantCollection } /// - /// Updates the display with a new value for a monitored variable. + /// Updates the display with a new value for a monitored variable. /// - private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) + private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (this.InvokeRequired) { - this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_Notification), monitoredItem, e); + this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync), monitoredItem, e); return; } @@ -504,7 +503,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt } // check if the filter has changed. - if (notification.EventFields.Count != m_filter.Fields.Count+1) + if (notification.EventFields.Count != m_filter.Fields.Count + 1) { return; } @@ -525,7 +524,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt } // create an item and add to top of list. - ListViewItem item = CreateListItem(m_filter, notification.EventFields); + ListViewItem item = await CreateListItemAsync(m_filter, notification.EventFields); if (item.ListView == null) { @@ -543,17 +542,17 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt ClientUtils.HandleException(this.Text, exception); } } - + /// /// Fetches the recent history. /// - private void ReadRecentHistory() + private async Task ReadRecentHistoryAsync(CancellationToken ct = default) { // check if session is active. if (m_session != null) { // check if area supports history. - IObject area = m_session.NodeCache.Find(m_areaId) as IObject; + IObject area = await m_session.NodeCache.FindAsync(m_areaId, ct) as IObject; if (area != null && ((area.EventNotifier & EventNotifiers.HistoryRead) != 0)) { @@ -565,7 +564,7 @@ private void ReadRecentHistory() details.Filter = m_filter.GetFilter(); // read the history. - ReadHistory(details, m_areaId); + await ReadHistoryAsync(details, m_areaId, ct); } } } @@ -573,24 +572,23 @@ private void ReadRecentHistory() /// /// Fetches the recent history. /// - private void ReadHistory(ReadEventDetails details, NodeId areaId) + private async Task ReadHistoryAsync(ReadEventDetails details, NodeId areaId, CancellationToken ct = default) { HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = areaId; nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Neither, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -601,28 +599,30 @@ private void ReadHistory(ReadEventDetails details, NodeId areaId) } HistoryEvent events = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryEvent; - AddEventHistory(events); + await AddEventHistoryAsync(events, ct); // release continuation points. if (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; - m_session.HistoryRead( + response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Neither, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; } } /// /// Deletes the recent history. /// - private void DeleteHistory(NodeId areaId, List events, FilterDeclaration filter) + private async Task DeleteHistoryAsync(NodeId areaId, List events, FilterDeclaration filter, CancellationToken ct = default) { // find the event id. int index = 0; @@ -663,14 +663,13 @@ private void DeleteHistory(NodeId areaId, List events, Filter ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection(); nodesToUpdate.Add(new ExtensionObject(details)); - HistoryUpdateResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryUpdate( + HistoryUpdateResponse response = await m_session.HistoryUpdateAsync( null, nodesToUpdate, - out results, - out diagnosticInfos); + ct); + + HistoryUpdateResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToUpdate); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToUpdate); @@ -697,7 +696,7 @@ private void DeleteHistory(NodeId areaId, List events, Filter if (count > 0) { throw ServiceResultException.Create( - StatusCodes.BadEventIdUnknown, + StatusCodes.BadEventIdUnknown, "Error deleting events. Only {0} of {1} deletes succeeded.", events.Count - count, events.Count); @@ -727,7 +726,7 @@ private void ViewDetailsMI_Click(object sender, EventArgs e) } } - private void DeleteHistoryMI_Click(object sender, EventArgs e) + private async void DeleteHistoryMI_ClickAsync(object sender, EventArgs e) { try { @@ -750,7 +749,7 @@ private void DeleteHistoryMI_Click(object sender, EventArgs e) if (events.Count > 0) { - DeleteHistory(m_areaId, events, m_filter); + await DeleteHistoryAsync(m_areaId, events, m_filter); foreach (ListViewItem item in EventsLV.SelectedItems) { diff --git a/Samples/ClientControls.Net4/Common/FilterDeclaration.cs b/Samples/ClientControls.Net4/Common/FilterDeclaration.cs index 43df5eb35..b5554251d 100644 --- a/Samples/ClientControls.Net4/Common/FilterDeclaration.cs +++ b/Samples/ClientControls.Net4/Common/FilterDeclaration.cs @@ -295,7 +295,7 @@ public EventFilter GetFilter() filter.WhereClause = GetWhereClause(); return filter; } - + /// /// Adds a simple field to the declaration. /// @@ -394,7 +394,7 @@ public SimpleAttributeOperandCollection GetSelectClause() return selectClause; } - + /// /// Returns the where clause defined by the filter declaration. /// @@ -444,12 +444,12 @@ public T GetValue(QualifiedName browseName, VariantCollection fields, T defau { if (this.Fields[ii].InstanceDeclaration.BrowseName == browseName) { - if (ii >= fields.Count+1) + if (ii >= fields.Count + 1) { return defaultValue; } - object value = fields[ii+1].Value; + object value = fields[ii + 1].Value; if (typeof(T).IsInstanceOfType(value)) { diff --git a/Samples/ClientControls.Net4/Common/HostListCtrl.cs b/Samples/ClientControls.Net4/Common/HostListCtrl.cs index ce8e9440e..0734908b3 100644 --- a/Samples/ClientControls.Net4/Common/HostListCtrl.cs +++ b/Samples/ClientControls.Net4/Common/HostListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,7 @@ using System.Net; using Opc.Ua.Configuration; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -53,17 +54,17 @@ public partial class HostListCtrl : Opc.Ua.Client.Controls.BaseListCtrl public HostListCtrl() { InitializeComponent(); - SetColumns(m_ColumnNames); + SetColumns(m_ColumnNames); } #endregion - + #region Private Fields - // The columns to display in the control. - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "Addresses", HorizontalAlignment.Left, null } - }; + // The columns to display in the control. + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "Addresses", HorizontalAlignment.Left, null } + }; #endregion #region Public Interface @@ -78,7 +79,7 @@ public void Initialize(string domain) AdjustColumns(); } #endregion - + #region Private Methods /// /// Finds the addresses for the specified host. @@ -119,7 +120,7 @@ private void OnFetchAddresses(object state) } catch (Exception e) { - Utils.LogError(e, "Could not get ip addresses for host: {0}", hostname); + Utils.LogError(e, "Could not get ip addresses for host: {0}", hostname); ThreadPool.QueueUserWorkItem(new WaitCallback(OnUpdateAddress), new object[] { listItem, e.Message }); } } @@ -134,7 +135,7 @@ private void OnUpdateAddress(object state) this.BeginInvoke(new WaitCallback(OnUpdateAddress), state); return; } - + ListViewItem listItem = ((object[])state)[0] as ListViewItem; if (listItem == null) @@ -149,7 +150,7 @@ private void OnUpdateAddress(object state) return; } - listItem.SubItems[1].Text = addresses; + listItem.SubItems[1].Text = addresses; AdjustColumns(); } @@ -159,18 +160,18 @@ private void OnUpdateAddress(object state) /// /// Updates an item in the control. /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { string hostname = listItem.Tag as string; if (hostname == null) { - base.UpdateItem(listItem, hostname); + await base.UpdateItemAsync(listItem, hostname, ct); return; } - listItem.SubItems[0].Text = String.Format("{0}", hostname); - listItem.SubItems[1].Text = ""; + listItem.SubItems[0].Text = String.Format("{0}", hostname); + listItem.SubItems[1].Text = ""; listItem.ImageKey = GuiUtils.Icons.Computer; diff --git a/Samples/ClientControls.Net4/Common/HostListDlg.cs b/Samples/ClientControls.Net4/Common/HostListDlg.cs index 76582ad4b..db5fc60f3 100644 --- a/Samples/ClientControls.Net4/Common/HostListDlg.cs +++ b/Samples/ClientControls.Net4/Common/HostListDlg.cs @@ -55,12 +55,12 @@ public HostListDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields private string m_domain; private string m_hostname; #endregion - + #region Public Interface /// /// Displays the dialog. @@ -82,11 +82,11 @@ public string ShowDialog(string domain) { return null; } - + return m_hostname; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Samples/ClientControls.Net4/Common/ReferenceListCtrl.cs b/Samples/ClientControls.Net4/Common/ReferenceListCtrl.cs index fe6198c97..e84a7f8a3 100644 --- a/Samples/ClientControls.Net4/Common/ReferenceListCtrl.cs +++ b/Samples/ClientControls.Net4/Common/ReferenceListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -35,6 +35,8 @@ using System.Linq; using System.Text; using System.Windows.Forms; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -69,12 +71,12 @@ public ReferenceListCtrl() ReferencesDV.DataSource = m_dataset.Tables[0].DefaultView; } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; private DataSet m_dataset; #endregion - + #region Public Interface /// /// The node id shown in the control. @@ -108,7 +110,7 @@ public ContextMenuStrip ReferencesMenuStrip /// /// Changes the session. /// - public void ChangeSession(Session session) + public async Task ChangeSessionAsync(ISession session, CancellationToken ct = default) { // do nothing if no change or no node id. if (Object.ReferenceEquals(m_session, session)) @@ -119,13 +121,13 @@ public void ChangeSession(Session session) m_session = session; // update the display. - Browse(); + await BrowseAsync(ct); } /// /// Changes the node id. /// - public void ChangeNodeId(NodeId nodeId) + public async Task ChangeNodeIdAsync(NodeId nodeId, CancellationToken ct = default) { // do nothing if no change or no session. if (NodeId == nodeId) @@ -137,7 +139,7 @@ public void ChangeNodeId(NodeId nodeId) NodeId = nodeId; // update the display. - Browse(); + await BrowseAsync(ct); } #endregion @@ -185,7 +187,7 @@ private BrowseDescriptionCollection CreateNodesToBrowse() /// /// Browses for the requested references. /// - private void Browse() + private async Task BrowseAsync(CancellationToken ct = default) { m_dataset.Tables[0].Rows.Clear(); @@ -194,7 +196,7 @@ private void Browse() return; } - ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, View, CreateNodesToBrowse(), false); + ReferenceDescriptionCollection references = await ClientUtils.BrowseAsync(m_session, View, CreateNodesToBrowse(), false, ct); for (int ii = 0; references != null && ii < references.Count; ii++) { @@ -203,12 +205,12 @@ private void Browse() DataRow row = m_dataset.Tables[0].NewRow(); row[0] = reference; - row[1] = m_session.NodeCache.GetDisplayText(reference.NodeId); - row[2] = m_session.NodeCache.GetDisplayText(reference.ReferenceTypeId); + row[1] = await m_session.NodeCache.GetDisplayTextAsync(reference.NodeId, ct); + row[2] = await m_session.NodeCache.GetDisplayTextAsync(reference.ReferenceTypeId, ct); row[3] = reference.IsForward.ToString(); row[4] = reference.NodeClass.ToString(); - row[5] = m_session.NodeCache.GetDisplayText(reference.TypeDefinition); - row[6] = ImageList.Images[ClientUtils.GetImageIndex(m_session, reference.NodeClass, reference.TypeDefinition, false)]; + row[5] = await m_session.NodeCache.GetDisplayTextAsync(reference.TypeDefinition, ct); + row[6] = ImageList.Images[await ClientUtils.GetImageIndexAsync(m_session, reference.NodeClass, reference.TypeDefinition, false, ct)]; m_dataset.Tables[0].Rows.Add(row); } diff --git a/Samples/ClientControls.Net4/Common/SelectHostCtrl.cs b/Samples/ClientControls.Net4/Common/SelectHostCtrl.cs index eac7a9002..1afc0493d 100644 --- a/Samples/ClientControls.Net4/Common/SelectHostCtrl.cs +++ b/Samples/ClientControls.Net4/Common/SelectHostCtrl.cs @@ -61,7 +61,7 @@ public SelectHostCtrl() private event EventHandler m_HostSelected; private event EventHandler m_HostConnected; #endregion - + #region Public Interface /// /// Whether the control is used to select domains instead of hosts. @@ -69,7 +69,7 @@ public SelectHostCtrl() [System.ComponentModel.DefaultValue(false)] public bool SelectDomains { - get { return m_selectDomains; } + get { return m_selectDomains; } set { m_selectDomains = value; } } @@ -79,7 +79,7 @@ public bool SelectDomains [System.ComponentModel.DefaultValue("Connect")] public string CommandText { - get { return ConnectBTN.Text; } + get { return ConnectBTN.Text; } set { ConnectBTN.Text = value; } } @@ -89,7 +89,7 @@ public string CommandText public void Initialize(string defaultHost, IList hostnames) { HostsCB.Items.Clear(); - + // add option to browse for hosts. HostsCB.Items.Add(""); @@ -101,12 +101,12 @@ public void Initialize(string defaultHost, IList hostnames) HostsCB.Items.Add(hostname); } } - + // set a suitable default hostname. if (String.IsNullOrEmpty(defaultHost)) { defaultHost = System.Net.Dns.GetHostName(); - + if (hostnames != null && hostnames.Count > 0) { defaultHost = hostnames[0]; @@ -142,12 +142,12 @@ public event EventHandler HostConnected remove { m_HostConnected -= value; } } #endregion - + #region Event Handlers private void HostsCB_SelectedIndexChanged(object sender, EventArgs e) { try - { + { if (HostsCB.SelectedIndex != 0) { if (m_HostSelected != null) @@ -169,7 +169,7 @@ private void HostsCB_SelectedIndexChanged(object sender, EventArgs e) HostsCB.SelectedIndex = m_selectedIndex; return; } - + // set the current selection. m_selectedIndex = HostsCB.FindString(hostname); @@ -178,19 +178,20 @@ private void HostsCB_SelectedIndexChanged(object sender, EventArgs e) m_selectedIndex = HostsCB.Items.Add(hostname); } } - + HostsCB.SelectedIndex = m_selectedIndex; } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void ConnectBTN_Click(object sender, EventArgs e) { try - { int index = HostsCB.SelectedIndex; + { + int index = HostsCB.SelectedIndex; if (index == 0) { @@ -205,7 +206,7 @@ private void ConnectBTN_Click(object sender, EventArgs e) { m_HostConnected(this, new SelectHostCtrlEventArgs(HostsCB.Text)); } - + // add host to list. m_selectedIndex = HostsCB.FindString(HostsCB.Text); @@ -216,13 +217,13 @@ private void ConnectBTN_Click(object sender, EventArgs e) return; } - + m_HostConnected(this, new SelectHostCtrlEventArgs((string)HostsCB.SelectedItem)); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/ViewNodeStateDlg.cs b/Samples/ClientControls.Net4/Common/ViewNodeStateDlg.cs index 253b2c425..c16af3267 100644 --- a/Samples/ClientControls.Net4/Common/ViewNodeStateDlg.cs +++ b/Samples/ClientControls.Net4/Common/ViewNodeStateDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -34,6 +34,8 @@ using System.Data; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -65,9 +67,9 @@ public ViewNodeStateDlg() ResultsDV.DataSource = m_dataset.Tables[0]; } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; private DataSet m_dataset; #endregion @@ -75,7 +77,7 @@ public ViewNodeStateDlg() /// /// Prompts the user to edit a value. /// - public bool ShowDialog(Session session, NodeState node, string caption) + public async Task ShowDialogAsync(ISession session, NodeState node, string caption, CancellationToken ct = default) { m_session = session; @@ -84,7 +86,7 @@ public bool ShowDialog(Session session, NodeState node, string caption) this.Text = caption; } - PopulateDataView(m_session.SystemContext, node, String.Empty); + await PopulateDataViewAsync(m_session.SystemContext, node, String.Empty, ct); m_dataset.AcceptChanges(); if (ShowDialog() != DialogResult.OK) @@ -98,10 +100,11 @@ public bool ShowDialog(Session session, NodeState node, string caption) /// /// Recursively populates the data view. /// - private void PopulateDataView( + private async Task PopulateDataViewAsync( ISystemContext context, NodeState parent, - string parentPath) + string parentPath, + CancellationToken ct = default) { List children = new List(); parent.GetChildren(context, children); @@ -115,7 +118,7 @@ private void PopulateDataView( if (!String.IsNullOrEmpty(parentPath)) { childPath.Append(parentPath); - childPath.Append("/"); + childPath.Append('/'); } childPath.Append(child.GetDisplayText()); @@ -126,11 +129,11 @@ private void PopulateDataView( if (StatusCode.IsGood(variable.StatusCode)) { - string dataType = m_session.NodeCache.GetDisplayText(variable.DataType); + string dataType = await m_session.NodeCache.GetDisplayTextAsync(variable.DataType, ct); if (variable.ValueRank >= 0) { - dataType += "[]"; + dataType += "[]"; } DataRow row = m_dataset.Tables[0].NewRow(); @@ -142,11 +145,11 @@ private void PopulateDataView( } } - PopulateDataView(context, child, childPath.ToString()); + await PopulateDataViewAsync(context, child, childPath.ToString(), ct); } } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Samples/ClientControls.Net4/Configuration/CertificateDlg.cs b/Samples/ClientControls.Net4/Configuration/CertificateDlg.cs index 9e4f3d7ba..86f967399 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,7 @@ using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -56,7 +57,7 @@ public CertificateDlg() /// /// Displays the dialog. /// - public async Task ShowDialog(CertificateIdentifier certificateIdentifier) + public async Task ShowDialogAsync(CertificateIdentifier certificateIdentifier, CancellationToken ct = default) { CertificateStoreCTRL.StoreType = null; CertificateStoreCTRL.StorePath = null; @@ -65,12 +66,12 @@ public async Task ShowDialog(CertificateIdentifier certificateIdentifier) if (certificateIdentifier != null) { - X509Certificate2 certificate = await certificateIdentifier.Find(); + X509Certificate2 certificate = await certificateIdentifier.FindAsync(ct: ct); CertificateStoreCTRL.StoreType = certificateIdentifier.StoreType; CertificateStoreCTRL.StorePath = certificateIdentifier.StorePath; - if (certificate != null && certificateIdentifier.Find(true) != null) + if (certificate != null && await certificateIdentifier.FindAsync(true, ct: ct) != null) { PrivateKeyCB.SelectedIndex = 1; } @@ -104,7 +105,7 @@ public bool ShowDialog(X509Certificate2 certificate) { return false; } - + return true; } diff --git a/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.Designer.cs b/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.Designer.cs index bcc42ae66..f430804ec 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.Designer.cs @@ -93,14 +93,14 @@ private void InitializeComponent() this.ViewMI.Name = "ViewMI"; this.ViewMI.Size = new System.Drawing.Size(118, 22); this.ViewMI.Text = "View..."; - this.ViewMI.Click += new System.EventHandler(this.ViewMI_Click); + this.ViewMI.Click += new System.EventHandler(this.ViewMI_ClickAsync); // // DeleteMI // this.DeleteMI.Name = "DeleteMI"; this.DeleteMI.Size = new System.Drawing.Size(118, 22); this.DeleteMI.Text = "Delete"; - this.DeleteMI.Click += new System.EventHandler(this.DeleteMI_Click); + this.DeleteMI.Click += new System.EventHandler(this.DeleteMI_ClickAsync); // // toolStripSeparator1 // diff --git a/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.cs b/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.cs index 364464771..5f696c956 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,7 @@ using System.Runtime.Serialization; using System.Threading.Tasks; using Opc.Ua.Security.Certificates; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -57,18 +58,18 @@ public CertificateListCtrl() SetColumns(m_ColumnNames); } #endregion - + #region Private Fields - // The columns to display in the control. - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "Type", HorizontalAlignment.Left, null }, - new object[] { "Private Key", HorizontalAlignment.Center, null }, - new object[] { "Domains", HorizontalAlignment.Left, null }, - new object[] { "Uri ", HorizontalAlignment.Left, null }, - new object[] { "Valid Until", HorizontalAlignment.Left, null } - }; + // The columns to display in the control. + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "Type", HorizontalAlignment.Left, null }, + new object[] { "Private Key", HorizontalAlignment.Center, null }, + new object[] { "Domains", HorizontalAlignment.Left, null }, + new object[] { "Uri ", HorizontalAlignment.Left, null }, + new object[] { "Valid Until", HorizontalAlignment.Left, null } + }; private CertificateStoreIdentifier m_storeId; private CertificateIdentifierCollection m_certificates; @@ -111,7 +112,7 @@ internal void Clear() { ItemsLV.Items.Clear(); Instructions = String.Empty; - AdjustColumns(); + AdjustColumns(); } /// @@ -136,7 +137,7 @@ internal void SetFilter(CertificateListFilter filter) ListViewItem item = m_items[ii]; X509Certificate2 certificate = item.Tag as X509Certificate2; - + if (certificate == null) { continue; @@ -190,7 +191,7 @@ internal void Initialize(CertificateIdentifierCollection certificates) // save the unfiltered list. m_items = new List(ItemsLV.Items.Count); - + foreach (ListViewItem item in ItemsLV.Items) { m_items.Add(item); @@ -202,7 +203,7 @@ internal void Initialize(CertificateIdentifierCollection certificates) /// /// Displays the applications in the control. /// - internal async Task Initialize(CertificateStoreIdentifier id, IList thumbprints) + internal async Task InitializeAsync(CertificateStoreIdentifier id, IList thumbprints, CancellationToken ct = default) { ItemsLV.Items.Clear(); @@ -213,7 +214,7 @@ internal async Task Initialize(CertificateStoreIdentifier id, IList thum { Instructions = "No certificates are in the store."; AdjustColumns(); - return ; + return; } try @@ -228,7 +229,7 @@ internal async Task Initialize(CertificateStoreIdentifier id, IList thum foreach (string thumbprint in thumbprints) { - X509Certificate2Collection certificates = await store.FindByThumbprint(thumbprint); + X509Certificate2Collection certificates = await store.FindByThumbprintAsync(thumbprint, ct); if (certificates.Count > 0) { @@ -242,7 +243,7 @@ internal async Task Initialize(CertificateStoreIdentifier id, IList thum { Instructions = "No certificates are in the store."; - X509Certificate2Collection certificates = await store.Enumerate(); + X509Certificate2Collection certificates = await store.EnumerateAsync(ct); foreach (X509Certificate2 certificate in certificates) { AddItem(certificate); @@ -275,23 +276,23 @@ internal async Task Initialize(CertificateStoreIdentifier id, IList thum protected override void PickItems() { base.PickItems(); - ViewMI_Click(this, null); + ViewMI_ClickAsync(this, null); } /// /// Updates an item in the view. /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { X509Certificate2 certificate = item as X509Certificate2; if (certificate == null) { - base.UpdateItem(listItem, item); + await base.UpdateItemAsync(listItem, item, ct); return; } - listItem.SubItems[0].Text = null; + listItem.SubItems[0].Text = null; listItem.SubItems[1].Text = null; listItem.SubItems[2].Text = null; listItem.SubItems[3].Text = null; @@ -359,7 +360,7 @@ protected override void UpdateItem(ListViewItem listItem, object item) { if (buffer.Length > 0) { - buffer.Append(";"); + buffer.Append(';'); } buffer.Append(domains[ii]); @@ -392,15 +393,15 @@ protected override void EnableMenuItems(ListViewItem clickedItem) } IDataObject clipboardData = Clipboard.GetDataObject(); - - if (clipboardData.GetDataPresent(DataFormats.Text)) + + if (clipboardData.GetDataPresent(DataFormats.Text)) { PasteMI.Enabled = true; } } #endregion - private async void ViewMI_Click(object sender, EventArgs e) + private async void ViewMI_ClickAsync(object sender, EventArgs e) { try { @@ -417,7 +418,7 @@ private async void ViewMI_Click(object sender, EventArgs e) id.StorePath = m_storeId.StorePath; } - await new ViewCertificateDlg().ShowDialog(id); + await new ViewCertificateDlg().ShowDialogAsync(id); } } catch (Exception exception) @@ -426,7 +427,7 @@ private async void ViewMI_Click(object sender, EventArgs e) } } - private async void DeleteMI_Click(object sender, EventArgs e) + private async void DeleteMI_ClickAsync(object sender, EventArgs e) { try { @@ -457,14 +458,14 @@ private async void DeleteMI_Click(object sender, EventArgs e) X509Certificate2 certificate = ItemsLV.SelectedItems[ii].Tag as X509Certificate2; // check for private key. - X509Certificate2Collection certificate2 = await store.FindByThumbprint(certificate.Thumbprint); + X509Certificate2Collection certificate2 = await store.FindByThumbprintAsync(certificate.Thumbprint); if (!yesToAll && (certificate2.Count > 0) && certificate2[0].HasPrivateKey) { StringBuilder buffer = new StringBuilder(); buffer.Append("Certificate '"); buffer.Append(certificate2[0].Subject); - buffer.Append("'"); + buffer.Append('\''); buffer.Append("Deleting it may cause applications to stop working."); buffer.Append("\r\n"); buffer.Append("\r\n"); @@ -482,7 +483,7 @@ private async void DeleteMI_Click(object sender, EventArgs e) if (certificate != null) { - await store.Delete(certificate.Thumbprint); + await store.DeleteAsync(certificate.Thumbprint); itemsToDelete.Add(ItemsLV.SelectedItems[ii]); } } @@ -497,14 +498,14 @@ private async void DeleteMI_Click(object sender, EventArgs e) catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); - await Initialize(m_storeId, m_thumbprints); + await InitializeAsync(m_storeId, m_thumbprints); } } private void CopyMI_Click(object sender, EventArgs e) { try - { + { X509Certificate2 certificate = SelectedTag as X509Certificate2; if (certificate == null) @@ -531,35 +532,35 @@ private void CopyMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void PasteMI_Click(object sender, EventArgs e) { try - { + { string xml = (string)ClipboardHack.GetData(DataFormats.Text); if (String.IsNullOrEmpty(xml)) { return; } - + // deserialize the data. CertificateIdentifier id = null; - using (XmlTextReader reader = new XmlTextReader(new StringReader(xml))) + using (XmlReader reader = XmlReader.Create(xml, new XmlReaderSettings() { XmlResolver = null })) { - DataContractSerializer serializer = new DataContractSerializer(typeof(CertificateIdentifier)); + DataContractSerializer serializer = new DataContractSerializer(typeof(CertificateIdentifier)); id = (CertificateIdentifier)serializer.ReadObject(reader, false); } - + if (id.Certificate != null) { using (ICertificateStore store = m_storeId.OpenStore()) { - store.Add(id.Certificate); + store.AddAsync(id.Certificate); } AddItem(id.Certificate); @@ -567,7 +568,7 @@ private void PasteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/ClientControls.Net4/Configuration/CertificateListDlg.Designer.cs b/Samples/ClientControls.Net4/Configuration/CertificateListDlg.Designer.cs index bd5a34264..d4db886a8 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateListDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateListDlg.Designer.cs @@ -162,7 +162,7 @@ private void InitializeComponent() this.CertificateStoreCTRL.Size = new System.Drawing.Size(899, 51); this.CertificateStoreCTRL.StorePath = "X:\\OPC\\Source\\UA311\\Source\\Utilities\\CertificateGenerator"; this.CertificateStoreCTRL.TabIndex = 0; - this.CertificateStoreCTRL.StoreChanged += new System.EventHandler(this.CertificateStoreCTRL_StoreChanged); + this.CertificateStoreCTRL.StoreChanged += new System.EventHandler(this.CertificateStoreCTRL_StoreChangedAsync); // // FiltersGB // diff --git a/Samples/ClientControls.Net4/Configuration/CertificateListDlg.cs b/Samples/ClientControls.Net4/Configuration/CertificateListDlg.cs index f6d3ae7a7..9001ace14 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateListDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateListDlg.cs @@ -82,7 +82,7 @@ public CertificateIdentifier ShowDialog(CertificateStoreIdentifier store, bool a id.Certificate = CertificatesCTRL.SelectedCertificate; return id; } - + private void OkBTN_Click(object sender, EventArgs e) { try @@ -152,14 +152,14 @@ private void CertificatesCTRL_ItemsSelected(object sender, ListItemActionEventAr } } - private void CertificateStoreCTRL_StoreChanged(object sender, EventArgs e) + private async void CertificateStoreCTRL_StoreChangedAsync(object sender, EventArgs e) { try { CertificateStoreIdentifier store = new CertificateStoreIdentifier(); store.StoreType = CertificateStoreCTRL.StoreType; store.StorePath = CertificateStoreCTRL.StorePath; - CertificatesCTRL.Initialize(store, null).Wait(); + await CertificatesCTRL.InitializeAsync(store, null); FilterBTN_Click(sender, e); } diff --git a/Samples/ClientControls.Net4/Configuration/CertificatePropertiesListCtrl.cs b/Samples/ClientControls.Net4/Configuration/CertificatePropertiesListCtrl.cs index 0d2c682db..8fb130d84 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificatePropertiesListCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificatePropertiesListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -31,10 +31,12 @@ using System.Collections.Generic; using System.ComponentModel; using System.Drawing; -using System.Text; -using System.Windows.Forms; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; using Opc.Ua.Configuration; using Opc.Ua.Security.Certificates; @@ -56,18 +58,18 @@ public CertificatePropertiesListCtrl() SetColumns(m_ColumnNames); } #endregion - + #region Private Fields - // The columns to display in the control. - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Field", HorizontalAlignment.Left, null }, - new object[] { "Value", HorizontalAlignment.Left, null }, - }; + // The columns to display in the control. + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Field", HorizontalAlignment.Left, null }, + new object[] { "Value", HorizontalAlignment.Left, null }, + }; #endregion - + #region FieldInfo Class - private class FieldInfo + private sealed class FieldInfo { public string Name; public string Value; @@ -80,7 +82,7 @@ public FieldInfo(string name, object value) } #endregion - #region Public Interface + #region Public Interface /// /// Removes all items in the list. /// @@ -88,7 +90,7 @@ internal void Clear() { ItemsLV.Items.Clear(); Instructions = String.Empty; - AdjustColumns(); + AdjustColumns(); } /// @@ -105,8 +107,8 @@ internal void Initialize(X509Certificate2 certificate) return; } - AddItem(new FieldInfo("Version", certificate.Version)); - AddItem(new FieldInfo("Subject", certificate.Subject)); + AddItem(new FieldInfo("Version", certificate.Version)); + AddItem(new FieldInfo("Subject", certificate.Subject)); AddItem(new FieldInfo("FriendlyName", certificate.FriendlyName)); AddItem(new FieldInfo("Thumbprint", certificate.Thumbprint)); AddItem(new FieldInfo("Issuer", certificate.Issuer)); @@ -119,8 +121,8 @@ internal void Initialize(X509Certificate2 certificate) foreach (X509Extension extension in certificate.Extensions) { - X509BasicConstraintsExtension basicContraints = extension as X509BasicConstraintsExtension; - + X509BasicConstraintsExtension basicContraints = extension as X509BasicConstraintsExtension; + if (basicContraints != null) { StringBuilder buffer = new StringBuilder(); @@ -167,7 +169,7 @@ internal void Initialize(X509Certificate2 certificate) } X509EnhancedKeyUsageExtension enhancedKeyUsage = extension as X509EnhancedKeyUsageExtension; - + if (enhancedKeyUsage != null) { StringBuilder buffer = new StringBuilder(); @@ -194,7 +196,7 @@ internal void Initialize(X509Certificate2 certificate) } X509SubjectKeyIdentifierExtension subjectKeyId = extension as X509SubjectKeyIdentifierExtension; - + if (subjectKeyId != null) { AddItem(new FieldInfo("SubjectKeyIdentifier", subjectKeyId.SubjectKeyIdentifier)); @@ -223,9 +225,9 @@ internal void Initialize(X509Certificate2 certificate) } string value = Utils.ToHexString(extension.RawData); - + AddItem(new FieldInfo(name, value)); - } + } AdjustColumns(); } @@ -245,11 +247,11 @@ internal void Initialize(Opc.Ua.Security.SecuredApplication application) } AddItem(new FieldInfo("ApplicationName", application.ApplicationName)); - AddItem(new FieldInfo("ApplicationUri", application.ApplicationUri)); - AddItem(new FieldInfo("ProductName", application.ProductName)); - AddItem(new FieldInfo("ApplicationType", application.ApplicationType)); - AddItem(new FieldInfo("ConfigurationFile", application.ConfigurationFile)); - AddItem(new FieldInfo("ExecutableFile", application.ExecutableFile)); + AddItem(new FieldInfo("ApplicationUri", application.ApplicationUri)); + AddItem(new FieldInfo("ProductName", application.ProductName)); + AddItem(new FieldInfo("ApplicationType", application.ApplicationType)); + AddItem(new FieldInfo("ConfigurationFile", application.ConfigurationFile)); + AddItem(new FieldInfo("ExecutableFile", application.ExecutableFile)); AdjustColumns(); } @@ -259,19 +261,19 @@ internal void Initialize(Opc.Ua.Security.SecuredApplication application) /// /// Updates an item in the control. /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { FieldInfo info = item as FieldInfo; if (info == null) { - base.UpdateItem(listItem, item); + await base.UpdateItemAsync(listItem, item, ct); return; } - listItem.SubItems[0].Text = String.Format("{0}", info.Name); - listItem.SubItems[1].Text = String.Format("{0}", info.Value); - + listItem.SubItems[0].Text = String.Format("{0}", info.Name); + listItem.SubItems[1].Text = String.Format("{0}", info.Value); + listItem.Tag = item; } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/CertificateStoreCtrl.cs b/Samples/ClientControls.Net4/Configuration/CertificateStoreCtrl.cs index 4808d9dac..278de52e5 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateStoreCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateStoreCtrl.cs @@ -60,7 +60,7 @@ public CertificateStoreCtrl() StoreTypeCB.SelectedIndex = 0; } #endregion - + #region Private Fields private event EventHandler m_StoreChanged; #endregion @@ -117,9 +117,9 @@ public bool ReadOnly [DefaultValue(Utils.DefaultStoreType)] public string StoreType { - get - { - return StoreTypeCB.SelectedItem as string; + get + { + return StoreTypeCB.SelectedItem as string; } set diff --git a/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeCtrl.cs b/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeCtrl.cs index 2439affe5..08ba9d9f6 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,13 +29,15 @@ using System; using System.Drawing; -using System.Text; -using System.Windows.Forms; using System.IO; -using System.Xml; -using System.Runtime.Serialization; using System.Reflection; +using System.Runtime.Serialization; using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Xml; namespace Opc.Ua.Client.Controls { @@ -63,10 +65,10 @@ private enum ContainerInfoType TopLevelStore, Service, User, - Store + Store } - private class ContainerInfo + private sealed class ContainerInfo { public ContainerInfoType Type; public string DisplayName; @@ -107,7 +109,7 @@ public CertificateStoreIdentifier GetCertificateStore() } } #endregion - + #region Public Interface /// /// Returns the currently selected store. @@ -152,24 +154,24 @@ public void Initialize() /// /// Updates the controls after a node is selected. /// - protected override void SelectNode() + protected override async void SelectNode() { base.SelectNode(); if (m_certificateListCtrl != null) { - m_certificateListCtrl.Initialize(SelectedStore, null).Wait(); + await m_certificateListCtrl.InitializeAsync(SelectedStore, null); } } /// /// Fetches the children before expanding a node. /// - protected override bool BeforeExpand(TreeNode clickedNode) + protected override Task BeforeExpandAsync(TreeNode clickedNode, CancellationToken ct = default) { if (clickedNode == null) { - return false; + return Task.FromResult(false); } // check for a dummy placeholder node. @@ -186,7 +188,7 @@ protected override bool BeforeExpand(TreeNode clickedNode) } } - return base.BeforeExpand(clickedNode); + return base.BeforeExpandAsync(clickedNode, ct); } /// @@ -313,7 +315,7 @@ protected override void NodesTV_DragDrop(object sender, DragEventArgs e) if (certificate != null) { - store.Add(certificate); + store.AddAsync(certificate); } } } @@ -340,7 +342,7 @@ private void FetchChildren(TreeNode parent) // check for a valid node. ContainerInfo info = parent.Tag as ContainerInfo; - + if (info == null) { return; @@ -352,7 +354,7 @@ private void FetchChildren(TreeNode parent) child.Nodes.Add(new TreeNode()); } } - + /// /// Sets the icon for the tree node. /// @@ -365,7 +367,7 @@ private void SetIcon(TreeNode treeNode, ContainerInfo info) treeNode.ImageKey = GuiUtils.Icons.Desktop; treeNode.SelectedImageKey = GuiUtils.Icons.Desktop; break; - } + } case ContainerInfoType.Service: { @@ -467,7 +469,7 @@ private void PasteMI_Click(object sender, EventArgs e) { CertificateIdentifier id = null; - using (XmlTextReader reader = new XmlTextReader(new StringReader(xml))) + using (XmlReader reader = XmlReader.Create(xml, new XmlReaderSettings() { XmlResolver = null })) { DataContractSerializer serializer = new DataContractSerializer(typeof(CertificateIdentifier)); id = (CertificateIdentifier)serializer.ReadObject(reader, false); @@ -479,7 +481,7 @@ private void PasteMI_Click(object sender, EventArgs e) using (ICertificateStore store = storeId.OpenStore()) { - store.Add(id.Certificate); + store.AddAsync(id.Certificate); } } diff --git a/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeDlg.cs b/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeDlg.cs index 1e7208df6..e5dbeb68a 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeDlg.cs @@ -51,7 +51,7 @@ public CertificateStoreTreeDlg() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } - + /// /// Displays the dialog. /// @@ -63,7 +63,7 @@ public CertificateStoreIdentifier ShowDialog(CertificateStoreIdentifier store) { return null; } - + return ContainersCTRL.SelectedStore; } diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.Designer.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.Designer.cs index 5d4a5ff42..47ac9e2bb 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.Designer.cs @@ -71,8 +71,8 @@ private void InitializeComponent() this.ItemsLV.TabIndex = 0; this.ItemsLV.UseCompatibleStateImageBehavior = false; this.ItemsLV.View = System.Windows.Forms.View.Details; - this.ItemsLV.DragEnter += new System.Windows.Forms.DragEventHandler(this.ItemsLV_DragEnter); - this.ItemsLV.DragDrop += new System.Windows.Forms.DragEventHandler(this.ItemsLV_DragDrop); + this.ItemsLV.DragEnter += new System.Windows.Forms.DragEventHandler(this.ItemsLV_DragEnterAsync); + this.ItemsLV.DragDrop += new System.Windows.Forms.DragEventHandler(this.ItemsLV_DragDropAsync); this.ItemsLV.DoubleClick += new System.EventHandler(this.ItemsLV_DoubleClick); this.ItemsLV.SelectedIndexChanged += new System.EventHandler(this.ItemsLV_SelectedIndexChanged); this.ItemsLV.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ItemsLV_MouseUp); diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.cs index a991d31ec..94ce1b9bc 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,9 @@ using System.Text; using System.Windows.Forms; using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -60,23 +63,23 @@ public BaseListCtrl() /// protected System.Windows.Forms.ListView ItemsLV; - #region Public Interface - /// - /// Whether the control should allow items to be dragged. - /// + #region Public Interface + /// + /// Whether the control should allow items to be dragged. + /// [DefaultValue(false)] - public bool EnableDragging - { - get { return m_enableDragging; } - set { m_enableDragging = value; } - } + public bool EnableDragging + { + get { return m_enableDragging; } + set { m_enableDragging = value; } + } /// /// The instructions to display when no items are in the list. /// public string Instructions { - get { return m_instructions; } + get { return m_instructions; } set { m_instructions = value; } } @@ -86,84 +89,84 @@ public string Instructions [DefaultValue(false)] public bool PrependItems { - get { return m_prependItems; } + get { return m_prependItems; } set { m_prependItems = value; } } - /// - /// Raised whenever items are 'picked' in the control. - /// - public event ListItemActionEventHandler ItemsPicked - { - add { m_ItemsPicked += value; } - remove { m_ItemsPicked -= value; } - } - - /// - /// Raised whenever items are selected in the control. - /// - public event ListItemActionEventHandler ItemsSelected - { - add { m_ItemsSelected += value; } - remove { m_ItemsSelected -= value; } - } - - /// - /// Raised whenever items are added to the control. - /// - public event ListItemActionEventHandler ItemsAdded - { - add { m_ItemsAdded += value; } - remove { m_ItemsAdded -= value; } - } - - /// - /// Raised whenever items are modified in the control. - /// - public event ListItemActionEventHandler ItemsModified - { - add { m_ItemsModified += value; } - remove { m_ItemsModified -= value; } - } - - /// - /// Raised whenever items are removed from the control. - /// - public event ListItemActionEventHandler ItemsRemoved - { - add { m_ItemsRemoved += value; } - remove { m_ItemsRemoved -= value; } - } - - /// - /// Returns the number of items in the control. - /// - public int Count - { - get { return ItemsLV.Items.Count; } - } - - /// - /// Returns the objects associated with the items in the control. - /// - public Array GetItems(System.Type type) - { - ArrayList items = new ArrayList(); - - foreach (ListViewItem listItem in ItemsLV.Items) - { - items.Add(listItem.Tag); - } - - return items.ToArray(type); - } - - /// - /// Returns the objects associated with the selected items in the control. - /// - public Array GetSelectedItems(System.Type type) - { - ArrayList items = new ArrayList(); + /// + /// Raised whenever items are 'picked' in the control. + /// + public event ListItemActionEventHandler ItemsPicked + { + add { m_ItemsPicked += value; } + remove { m_ItemsPicked -= value; } + } + + /// + /// Raised whenever items are selected in the control. + /// + public event ListItemActionEventHandler ItemsSelected + { + add { m_ItemsSelected += value; } + remove { m_ItemsSelected -= value; } + } + + /// + /// Raised whenever items are added to the control. + /// + public event ListItemActionEventHandler ItemsAdded + { + add { m_ItemsAdded += value; } + remove { m_ItemsAdded -= value; } + } + + /// + /// Raised whenever items are modified in the control. + /// + public event ListItemActionEventHandler ItemsModified + { + add { m_ItemsModified += value; } + remove { m_ItemsModified -= value; } + } + + /// + /// Raised whenever items are removed from the control. + /// + public event ListItemActionEventHandler ItemsRemoved + { + add { m_ItemsRemoved += value; } + remove { m_ItemsRemoved -= value; } + } + + /// + /// Returns the number of items in the control. + /// + public int Count + { + get { return ItemsLV.Items.Count; } + } + + /// + /// Returns the objects associated with the items in the control. + /// + public Array GetItems(System.Type type) + { + ArrayList items = new ArrayList(); + + foreach (ListViewItem listItem in ItemsLV.Items) + { + items.Add(listItem.Tag); + } + + return items.ToArray(type); + } + + /// + /// Returns the objects associated with the selected items in the control. + /// + public Array GetSelectedItems(System.Type type) + { + ArrayList items = new ArrayList(); if (ItemsLV.View == View.Details) { @@ -173,26 +176,26 @@ public Array GetSelectedItems(System.Type type) } } - return items.ToArray(type); - } - #endregion + return items.ToArray(type); + } + #endregion - #region Private Members + #region Private Members private bool m_prependItems; - private event ListItemActionEventHandler m_ItemsPicked; - private event ListItemActionEventHandler m_ItemsSelected; - private event ListItemActionEventHandler m_ItemsAdded; - private event ListItemActionEventHandler m_ItemsModified; - private event ListItemActionEventHandler m_ItemsRemoved; - private object[][] m_columns; + private event ListItemActionEventHandler m_ItemsPicked; + private event ListItemActionEventHandler m_ItemsSelected; + private event ListItemActionEventHandler m_ItemsAdded; + private event ListItemActionEventHandler m_ItemsModified; + private event ListItemActionEventHandler m_ItemsRemoved; + private object[][] m_columns; private bool m_updating; private int m_updateCount; private string m_instructions; private Point m_dragPosition; private bool m_enableDragging; - #endregion + #endregion - #region Protected Methods + #region Protected Methods /// /// Returns tag of the selected item. Null if no items or more than one item is selected. /// @@ -209,9 +212,9 @@ protected object SelectedTag } } - /// - /// Deletes the currently selected items. - /// + /// + /// Deletes the currently selected items. + /// protected virtual void DeleteSelection() { List itemsToDelete = new List(); @@ -227,9 +230,9 @@ protected virtual void DeleteSelection() } } - /// - /// Compares two items in the list. - /// + /// + /// Compares two items in the list. + /// protected virtual int CompareItems(object item1, object item2) { IComparable comparable = item1 as IComparable; @@ -262,23 +265,23 @@ protected virtual object GetDataToDrag() return null; } - /// - /// Adds an item to the list. - /// + /// + /// Adds an item to the list. + /// protected virtual ListViewItem AddItem(object item) { return AddItem(item, "SimpleItem", -1); } - /// - /// Adds an item to the list. - /// - protected virtual ListViewItem AddItem(object item, string icon, int index) - { + /// + /// Adds an item to the list. + /// + protected virtual ListViewItem AddItem(object item, string icon, int index) + { // switch to detail view as soon as an item is added. if (ItemsLV.View == View.List) { - ItemsLV.Items.Clear(); + ItemsLV.Items.Clear(); ItemsLV.View = View.Details; } @@ -293,22 +296,22 @@ protected virtual ListViewItem AddItem(object item, string icon, int index) m_updateCount++; } - + if (listItem == null) { listItem = new ListViewItem(); } - listItem.Text = String.Format("{0}", item); - listItem.ImageKey = icon; - listItem.Tag = item; - - // fill columns with blanks. - for (int ii = listItem.SubItems.Count; ii < ItemsLV.Columns.Count-1; ii++) + listItem.Text = String.Format("{0}", item); + listItem.ImageKey = icon; + listItem.Tag = item; + + // fill columns with blanks. + for (int ii = listItem.SubItems.Count; ii < ItemsLV.Columns.Count - 1; ii++) { listItem.SubItems.Add(String.Empty); } - + // calculate new index. int newIndex = index; @@ -317,8 +320,8 @@ protected virtual ListViewItem AddItem(object item, string icon, int index) newIndex = ItemsLV.Items.Count; } - // update columns. - UpdateItem(listItem, item, newIndex); + // update columns. + UpdateItemAsync(listItem, item, newIndex); if (listItem.ListView == null) { @@ -335,9 +338,9 @@ protected virtual ListViewItem AddItem(object item, string icon, int index) NotifyItemAdded(item); - // return new item. - return listItem; - } + // return new item. + return listItem; + } /// /// Starts overwriting the contents of the control. @@ -347,7 +350,7 @@ protected void BeginUpdate() m_updating = true; m_updateCount = 0; } - + /// /// Finishes overwriting the contents of the control. /// @@ -357,60 +360,61 @@ protected void EndUpdate() while (ItemsLV.Items.Count > m_updateCount) { - ItemsLV.Items[ItemsLV.Items.Count-1].Remove(); + ItemsLV.Items[ItemsLV.Items.Count - 1].Remove(); } m_updateCount = 0; AdjustColumns(); } - /// - /// Updates a list item with the current contents of an object. - /// - protected virtual void UpdateItem(ListViewItem listItem, object item) - { - listItem.Tag = item; - } - - /// - /// Updates a list item with the current contents of an object. - /// - protected virtual void UpdateItem(ListViewItem listItem, object item, int index) - { - UpdateItem(listItem, item); - } - - /// - /// Sets the columns shown in the list view. - /// - protected virtual void SetColumns(object[][] columns) - { - ItemsLV.Clear(); - - m_columns = columns; - - foreach (object[] column in columns) - { - ColumnHeader header = new ColumnHeader(); - - header.Text = column[0] as string; - header.TextAlign = (HorizontalAlignment)column[1]; - - ItemsLV.Columns.Add(header); - } - - ColumnHeader blank = new ColumnHeader(); - blank.Text = String.Empty; - ItemsLV.Columns.Add(blank); - - AdjustColumns(); - } - - /// - /// Adjusts the columns shown in the list view. - /// - protected virtual void AdjustColumns() - { + /// + /// Updates a list item with the current contents of an object. + /// + protected virtual Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) + { + listItem.Tag = item; + return Task.CompletedTask; + } + + /// + /// Updates a list item with the current contents of an object. + /// + protected virtual Task UpdateItemAsync(ListViewItem listItem, object item, int index, CancellationToken ct = default) + { + return UpdateItemAsync(listItem, item, ct); + } + + /// + /// Sets the columns shown in the list view. + /// + protected virtual void SetColumns(object[][] columns) + { + ItemsLV.Clear(); + + m_columns = columns; + + foreach (object[] column in columns) + { + ColumnHeader header = new ColumnHeader(); + + header.Text = column[0] as string; + header.TextAlign = (HorizontalAlignment)column[1]; + + ItemsLV.Columns.Add(header); + } + + ColumnHeader blank = new ColumnHeader(); + blank.Text = String.Empty; + ItemsLV.Columns.Add(blank); + + AdjustColumns(); + } + + /// + /// Adjusts the columns shown in the list view. + /// + protected virtual void AdjustColumns() + { if (ItemsLV.View == View.List || ItemsLV.Items.Count == 0) { ItemsLV.View = View.List; @@ -418,8 +422,8 @@ protected virtual void AdjustColumns() if (ItemsLV.Items.Count == 0 && !String.IsNullOrEmpty(m_instructions)) { ListViewItem item = new ListViewItem(m_instructions); - - item.ImageKey = "Info"; + + item.ImageKey = "Info"; item.ForeColor = Color.Gray; ItemsLV.Items.Add(item); @@ -431,171 +435,171 @@ protected virtual void AdjustColumns() ItemsLV.View = View.Details; - for (int ii = 0; ii < m_columns.Length && ii < ItemsLV.Columns.Count; ii++) - { - // check for fixed width columns. - if (m_columns[ii].Length >= 4 && m_columns[ii][3] != null) - { + for (int ii = 0; ii < m_columns.Length && ii < ItemsLV.Columns.Count; ii++) + { + // check for fixed width columns. + if (m_columns[ii].Length >= 4 && m_columns[ii][3] != null) + { int width = (int)m_columns[ii][3]; if (ItemsLV.Columns[ii].Width < width) { - ItemsLV.Columns[ii].Width = width; + ItemsLV.Columns[ii].Width = width; } - continue; - } - - // check mandatory columns. - if (m_columns[ii].Length < 3 || m_columns[ii][2] == null) - { - ItemsLV.Columns[ii].Width = -2; - continue; - } - - // check if all items have the default value for the column. - bool display = false; - - foreach (ListViewItem listItem in ItemsLV.Items) - { - if (!m_columns[ii][2].Equals(listItem.SubItems[ii].Text)) - { - display = true; - break; - } - } - - // only display columns with non-default information. - if (display) - { - ItemsLV.Columns[ii].Width = -2; - } - else - { - ItemsLV.Columns[ii].Width = 0; - } - } - - if (ItemsLV.Columns.Count > 0) - { - ItemsLV.Columns[ItemsLV.Columns.Count-1].Width = 0; - } - } - - /// - /// Enables the state of menu items. - /// - protected virtual void EnableMenuItems(ListViewItem clickedItem) - { - // do nothing. - } - - /// - /// Sends notifications whenever items in the control are 'picked'. - /// - protected virtual void PickItems() - { - if (m_ItemsPicked != null) - { - ICollection data = GetDataToDrag() as ICollection; + continue; + } + + // check mandatory columns. + if (m_columns[ii].Length < 3 || m_columns[ii][2] == null) + { + ItemsLV.Columns[ii].Width = -2; + continue; + } + + // check if all items have the default value for the column. + bool display = false; + + foreach (ListViewItem listItem in ItemsLV.Items) + { + if (!m_columns[ii][2].Equals(listItem.SubItems[ii].Text)) + { + display = true; + break; + } + } + + // only display columns with non-default information. + if (display) + { + ItemsLV.Columns[ii].Width = -2; + } + else + { + ItemsLV.Columns[ii].Width = 0; + } + } + + if (ItemsLV.Columns.Count > 0) + { + ItemsLV.Columns[ItemsLV.Columns.Count - 1].Width = 0; + } + } + + /// + /// Enables the state of menu items. + /// + protected virtual void EnableMenuItems(ListViewItem clickedItem) + { + // do nothing. + } + + /// + /// Sends notifications whenever items in the control are 'picked'. + /// + protected virtual void PickItems() + { + if (m_ItemsPicked != null) + { + ICollection data = GetDataToDrag() as ICollection; if (data != null) { m_ItemsPicked(this, new ListItemActionEventArgs(ListItemAction.Picked, data)); } - } - } - - /// - /// Sends notifications whenever items in the control are 'selected'. - /// - protected virtual void SelectItems() - { - if (m_ItemsSelected != null) - { - object[] selectedObjects = new object[ItemsLV.SelectedItems.Count]; - - for (int ii = 0; ii < selectedObjects.Length; ii++) - { - selectedObjects[ii] = ItemsLV.SelectedItems[ii].Tag; - } - - m_ItemsSelected(this, new ListItemActionEventArgs(ListItemAction.Selected, selectedObjects)); - } - } - - /// - /// Sends notifications that an item has been added to the control. - /// - protected virtual void NotifyItemAdded(object item) - { - NotifyItemsAdded(new object[] { item }); - } - - /// - /// Sends notifications that items have been added to the control. - /// - protected virtual void NotifyItemsAdded(object[] items) - { - if (m_ItemsAdded != null && items != null && items.Length > 0) - { - m_ItemsAdded(this, new ListItemActionEventArgs(ListItemAction.Added, items)); - } - } - - /// - /// Sends notifications that an item has been modified in the control. - /// - protected virtual void NotifyItemModified(object item) - { - NotifyItemsModified(new object[] { item }); - } - - /// - /// Sends notifications that items have been modified in the control. - /// - protected virtual void NotifyItemsModified(object[] items) - { - if (m_ItemsModified != null && items != null && items.Length > 0) - { - m_ItemsModified(this, new ListItemActionEventArgs(ListItemAction.Modified, items)); - } - } - - /// - /// Sends notifications that and item has been removed from the control. - /// - protected virtual void NotifyItemRemoved(object item) - { - NotifyItemsRemoved(new object[] { item }); - } - - /// - /// Sends notifications that items have been removed from the control. - /// - protected virtual void NotifyItemsRemoved(object[] items) - { - if (m_ItemsRemoved != null && items != null && items.Length > 0) - { - m_ItemsRemoved(this, new ListItemActionEventArgs(ListItemAction.Removed, items)); - } - } - - /// - /// Finds the list item with specified tag in the control, - /// - protected ListViewItem FindItem(object tag) - { - foreach (ListViewItem listItem in ItemsLV.Items) - { - if (Object.ReferenceEquals(tag, listItem.Tag)) - { - return listItem; - } - } - - return null; - } + } + } + + /// + /// Sends notifications whenever items in the control are 'selected'. + /// + protected virtual void SelectItems() + { + if (m_ItemsSelected != null) + { + object[] selectedObjects = new object[ItemsLV.SelectedItems.Count]; + + for (int ii = 0; ii < selectedObjects.Length; ii++) + { + selectedObjects[ii] = ItemsLV.SelectedItems[ii].Tag; + } + + m_ItemsSelected(this, new ListItemActionEventArgs(ListItemAction.Selected, selectedObjects)); + } + } + + /// + /// Sends notifications that an item has been added to the control. + /// + protected virtual void NotifyItemAdded(object item) + { + NotifyItemsAdded(new object[] { item }); + } + + /// + /// Sends notifications that items have been added to the control. + /// + protected virtual void NotifyItemsAdded(object[] items) + { + if (m_ItemsAdded != null && items != null && items.Length > 0) + { + m_ItemsAdded(this, new ListItemActionEventArgs(ListItemAction.Added, items)); + } + } + + /// + /// Sends notifications that an item has been modified in the control. + /// + protected virtual void NotifyItemModified(object item) + { + NotifyItemsModified(new object[] { item }); + } + + /// + /// Sends notifications that items have been modified in the control. + /// + protected virtual void NotifyItemsModified(object[] items) + { + if (m_ItemsModified != null && items != null && items.Length > 0) + { + m_ItemsModified(this, new ListItemActionEventArgs(ListItemAction.Modified, items)); + } + } + + /// + /// Sends notifications that and item has been removed from the control. + /// + protected virtual void NotifyItemRemoved(object item) + { + NotifyItemsRemoved(new object[] { item }); + } + + /// + /// Sends notifications that items have been removed from the control. + /// + protected virtual void NotifyItemsRemoved(object[] items) + { + if (m_ItemsRemoved != null && items != null && items.Length > 0) + { + m_ItemsRemoved(this, new ListItemActionEventArgs(ListItemAction.Removed, items)); + } + } + + /// + /// Finds the list item with specified tag in the control, + /// + protected ListViewItem FindItem(object tag) + { + foreach (ListViewItem listItem in ItemsLV.Items) + { + if (Object.ReferenceEquals(tag, listItem.Tag)) + { + return listItem; + } + } + + return null; + } /// /// Returns the tag associated with a selected item. @@ -609,14 +613,14 @@ protected object GetSelectedTag(int index) return null; } - #endregion + #endregion #region BaseListCtrlSorter Class /// /// A class that allows the list to be sorted. /// - private class BaseListCtrlSorter : IComparer - { + private sealed class BaseListCtrlSorter : IComparer + { /// /// Initializes the sorter. /// @@ -635,16 +639,16 @@ public int Compare(object x, object y) return m_control.CompareItems(itemX.Tag, itemY.Tag); } - + private BaseListCtrl m_control; } #endregion - + #region Event Handlers - private void ItemsLV_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) - { - try - { + private void ItemsLV_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) + { + try + { // ignore non-right clicks. if (e.Button == MouseButtons.Left) { @@ -652,11 +656,11 @@ private void ItemsLV_MouseDown(object sender, System.Windows.Forms.MouseEventArg return; } - // disable everything. - if (ItemsLV.ContextMenuStrip != null) - { - foreach (ToolStripItem item in ItemsLV.ContextMenuStrip.Items) - { + // disable everything. + if (ItemsLV.ContextMenuStrip != null) + { + foreach (ToolStripItem item in ItemsLV.ContextMenuStrip.Items) + { ToolStripMenuItem menuItem = item as ToolStripMenuItem; if (menuItem == null) @@ -678,66 +682,66 @@ private void ItemsLV_MouseDown(object sender, System.Windows.Forms.MouseEventArg } } } - } - } - - // selects the item that was right clicked on. - ListViewItem clickedItem = ItemsLV.GetItemAt(e.X, e.Y); - - // ensure clicked item is selected. - if (clickedItem != null) - { - clickedItem.Selected = true; - } - - // enable menu items according to context. + } + } + + // selects the item that was right clicked on. + ListViewItem clickedItem = ItemsLV.GetItemAt(e.X, e.Y); + + // ensure clicked item is selected. + if (clickedItem != null) + { + clickedItem.Selected = true; + } + + // enable menu items according to context. EnableMenuItems(clickedItem); - } - catch (Exception exception) - { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); - } - } + } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } + } private void ItemsLV_MouseUp(object sender, MouseEventArgs e) { - try - { + try + { if (e.Button == MouseButtons.Left) { m_dragPosition = e.Location; return; } - } - catch (Exception exception) - { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); - } - } - - private void ItemsLV_DoubleClick(object sender, System.EventArgs e) - { - try - { - PickItems(); - } - catch (Exception exception) - { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); - } - } - - private void ItemsLV_SelectedIndexChanged(object sender, System.EventArgs e) - { - try - { + } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } + } + + private void ItemsLV_DoubleClick(object sender, System.EventArgs e) + { + try + { + PickItems(); + } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } + } + + private void ItemsLV_SelectedIndexChanged(object sender, System.EventArgs e) + { + try + { SelectItems(); - } - catch (Exception exception) - { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); - } - } + } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } + } private void ItemsLV_MouseMove(object sender, MouseEventArgs e) { @@ -752,12 +756,37 @@ private void ItemsLV_MouseMove(object sender, MouseEventArgs e) } } + private async void ItemsLV_DragEnterAsync(object sender, DragEventArgs e) + { + try + { + await OnDragEnterAsync(sender, e); + } + catch (Exception ex) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), ex); + } + } + + private async void ItemsLV_DragDropAsync(object sender, DragEventArgs e) + { + try + { + await OnDragDropAsync(sender, e); + } + catch (Exception ex) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), ex); + } + } + /// /// Handles the DragEnter event of the ItemsLV control. /// /// The source of the event. /// The instance containing the event data. - protected virtual void ItemsLV_DragEnter(object sender, DragEventArgs e) + /// Cancellation token to cancel with + protected virtual Task OnDragEnterAsync(object sender, DragEventArgs e, CancellationToken ct = default) { if (m_enableDragging) { @@ -767,6 +796,7 @@ protected virtual void ItemsLV_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.None; } + return Task.CompletedTask; } /// @@ -774,18 +804,20 @@ protected virtual void ItemsLV_DragEnter(object sender, DragEventArgs e) /// /// The source of the event. /// The instance containing the event data. - protected virtual void ItemsLV_DragDrop(object sender, DragEventArgs e) + /// Cancellation token to cancel with + protected virtual Task OnDragDropAsync(object sender, DragEventArgs e, CancellationToken ct = default) { // overriden by sub-class. + return Task.CompletedTask; } #endregion } - + #region ListItemAction Enumeration - /// - /// The possible actions that could affect an item. - /// - public enum ListItemAction + /// + /// The possible actions that could affect an item. + /// + public enum ListItemAction { /// @@ -820,7 +852,7 @@ public enum ListItemAction /// The event argurments passed when an item event occurs. /// public class ListItemActionEventArgs : EventArgs - { + { #region Constructors /// /// Initializes a new instance of the class. @@ -828,37 +860,37 @@ public class ListItemActionEventArgs : EventArgs /// The action. /// The items. public ListItemActionEventArgs(ListItemAction action, ICollection items) - { - m_items = items; - m_action = action; - } + { + m_items = items; + m_action = action; + } #endregion - + #region Public Properties /// /// Gets the items. /// /// The items. - public ICollection Items + public ICollection Items { - get { return m_items; } + get { return m_items; } } /// /// Gets the action. /// /// The action. - public ListItemAction Action + public ListItemAction Action { get { return m_action; } } #endregion - + #region Private Fields - private ICollection m_items; - private ListItemAction m_action; + private ICollection m_items; + private ListItemAction m_action; #endregion - } + } /// /// The delegate used to receive item action events. diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.Designer.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.Designer.cs index c37759475..ce4b0dadc 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.Designer.cs @@ -69,7 +69,7 @@ private void InitializeComponent() this.NodesTV.Size = new System.Drawing.Size(489, 397); this.NodesTV.TabIndex = 1; this.NodesTV.GiveFeedback += new System.Windows.Forms.GiveFeedbackEventHandler(this.NodesTV_GiveFeedback); - this.NodesTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.NodesTV_BeforeExpand); + this.NodesTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.NodesTV_BeforeExpandAsync); this.NodesTV.DoubleClick += new System.EventHandler(this.NodesTV_DoubleClick); this.NodesTV.DragDrop += new System.Windows.Forms.DragEventHandler(this.NodesTV_DragDrop); this.NodesTV.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.NodesTV_AfterSelect); diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.cs index fa6b72ec2..6c9cae75a 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,11 +30,13 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Drawing; using System.Data; +using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; namespace Opc.Ua.Client.Controls { @@ -59,85 +61,85 @@ public BaseTreeCtrl() /// protected System.Windows.Forms.TreeView NodesTV; - /// - /// Raised whenever a node is 'picked' in the control. - /// - public event TreeNodeActionEventHandler NodePicked - { - add { m_NodePicked += value; } - remove { m_NodePicked -= value; } - } - - /// - /// Raised whenever a node is selected in the control. - /// - public event TreeNodeActionEventHandler NodeSelected - { - add { m_NodeSelected += value; } - remove { m_NodeSelected -= value; } - } - - /// - /// Whether the control should allow items to be dragged. - /// - public bool EnableDragging - { - get { return m_enableDragging; } - set { m_enableDragging = value; } - } - #endregion - - #region Private Fields - private event TreeNodeActionEventHandler m_NodePicked; - private event TreeNodeActionEventHandler m_NodeSelected; + /// + /// Raised whenever a node is 'picked' in the control. + /// + public event TreeNodeActionEventHandler NodePicked + { + add { m_NodePicked += value; } + remove { m_NodePicked -= value; } + } + + /// + /// Raised whenever a node is selected in the control. + /// + public event TreeNodeActionEventHandler NodeSelected + { + add { m_NodeSelected += value; } + remove { m_NodeSelected -= value; } + } + + /// + /// Whether the control should allow items to be dragged. + /// + public bool EnableDragging + { + get { return m_enableDragging; } + set { m_enableDragging = value; } + } + #endregion + + #region Private Fields + private event TreeNodeActionEventHandler m_NodePicked; + private event TreeNodeActionEventHandler m_NodeSelected; private bool m_enableDragging; - #endregion - - #region Protected Methods - /// - /// Adds an item to the tree. - /// - protected virtual TreeNode AddNode(TreeNode treeNode, object item) - { + #endregion + + #region Protected Methods + /// + /// Adds an item to the tree. + /// + protected virtual TreeNode AddNode(TreeNode treeNode, object item) + { return AddNode(treeNode, item, String.Format("{0}", item), "ClosedFolder"); - } - - /// - /// Adds an item to the tree. - /// - protected virtual TreeNode AddNode(TreeNode parent, object item, string text, string icon) - { - // create node. - TreeNode treeNode = new TreeNode(); - - // update text/icon. - UpdateNode(treeNode, item, text, icon); - - // add to control. - if (parent == null) - { - NodesTV.Nodes.Add(treeNode); - } - else - { - parent.Nodes.Add(treeNode); - } - - // return new tree node. - return treeNode; - } - - /// - /// Updates a tree node with the current contents of an object. - /// - protected virtual void UpdateNode(TreeNode treeNode, object item, string text, string icon) - { - treeNode.Text = text; - treeNode.Tag = item; - treeNode.ImageKey = icon; + } + + /// + /// Adds an item to the tree. + /// + protected virtual TreeNode AddNode(TreeNode parent, object item, string text, string icon) + { + // create node. + TreeNode treeNode = new TreeNode(); + + // update text/icon. + UpdateNode(treeNode, item, text, icon); + + // add to control. + if (parent == null) + { + NodesTV.Nodes.Add(treeNode); + } + else + { + parent.Nodes.Add(treeNode); + } + + // return new tree node. + return treeNode; + } + + /// + /// Updates a tree node with the current contents of an object. + /// + protected virtual void UpdateNode(TreeNode treeNode, object item, string text, string icon) + { + treeNode.Text = text; + treeNode.Tag = item; + treeNode.ImageKey = icon; treeNode.SelectedImageKey = icon; - } - + } + /// /// Returns the data to drag. /// @@ -146,31 +148,31 @@ protected virtual object GetDataToDrag(TreeNode node) return node.Tag; } - /// - /// Enables the state of menu items. - /// - protected virtual void EnableMenuItems(TreeNode clickedNode) - { - // do nothing. - } - - /// - /// Initializes a node before expanding it. - /// - protected virtual bool BeforeExpand(TreeNode clickedNode) - { - return false; - } - - /// - /// Sends notifications whenever a node in the control is 'picked'. - /// - protected virtual void PickNode() - { - if (m_NodePicked != null) - { - if (NodesTV.SelectedNode != null) - { + /// + /// Enables the state of menu items. + /// + protected virtual void EnableMenuItems(TreeNode clickedNode) + { + // do nothing. + } + + /// + /// Initializes a node before expanding it. + /// + protected virtual Task BeforeExpandAsync(TreeNode clickedNode, CancellationToken ct = default) + { + return Task.FromResult(false); + } + + /// + /// Sends notifications whenever a node in the control is 'picked'. + /// + protected virtual void PickNode() + { + if (m_NodePicked != null) + { + if (NodesTV.SelectedNode != null) + { object parent = null; if (NodesTV.SelectedNode.Parent != null) @@ -178,20 +180,20 @@ protected virtual void PickNode() parent = NodesTV.SelectedNode.Tag; } - m_NodePicked(this, new TreeNodeActionEventArgs(TreeNodeAction.Picked, NodesTV.SelectedNode.Tag, parent)); - } - } - } - - /// - /// Sends notifications whenever a node in the control is 'selected'. - /// - protected virtual void SelectNode() - { - if (m_NodeSelected != null) - { - if (NodesTV.SelectedNode != null) - { + m_NodePicked(this, new TreeNodeActionEventArgs(TreeNodeAction.Picked, NodesTV.SelectedNode.Tag, parent)); + } + } + } + + /// + /// Sends notifications whenever a node in the control is 'selected'. + /// + protected virtual void SelectNode() + { + if (m_NodeSelected != null) + { + if (NodesTV.SelectedNode != null) + { object parent = null; if (NodesTV.SelectedNode.Parent != null) @@ -199,10 +201,10 @@ protected virtual void SelectNode() parent = NodesTV.SelectedNode.Tag; } - m_NodeSelected(this, new TreeNodeActionEventArgs(TreeNodeAction.Selected, NodesTV.SelectedNode.Tag, parent)); - } - } - } + m_NodeSelected(this, new TreeNodeActionEventArgs(TreeNodeAction.Selected, NodesTV.SelectedNode.Tag, parent)); + } + } + } /// /// Returns the Tag for the current selection. @@ -219,27 +221,27 @@ protected object SelectedTag return null; } } - #endregion - - #region Event Handlers + #endregion + + #region Event Handlers private void NodesTV_AfterSelect(object sender, TreeViewEventArgs e) { try { - SelectNode(); + SelectNode(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void NodesTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) + private async void NodesTV_BeforeExpandAsync(object sender, TreeViewCancelEventArgs e) { try { - Cursor = Cursors.WaitCursor; - e.Cancel = BeforeExpand(e.Node); + Cursor = Cursors.WaitCursor; + e.Cancel = await BeforeExpandAsync(e.Node); } catch (Exception exception) { @@ -247,31 +249,31 @@ private void NodesTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) } finally { - Cursor = Cursors.Default; + Cursor = Cursors.Default; } } private void NodesTV_DoubleClick(object sender, EventArgs e) - { + { try { - PickNode(); + PickNode(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void NodesTV_MouseDown(object sender, MouseEventArgs e) - { + { try { - // selects the item that was right clicked on. - TreeNode clickedNode = NodesTV.SelectedNode = NodesTV.GetNodeAt(e.X, e.Y); + // selects the item that was right clicked on. + TreeNode clickedNode = NodesTV.SelectedNode = NodesTV.GetNodeAt(e.X, e.Y); - // no item clicked on - do nothing. - if (clickedNode == null) return; + // no item clicked on - do nothing. + if (clickedNode == null) return; // start drag operation. if (e.Button == MouseButtons.Left) @@ -289,11 +291,11 @@ private void NodesTV_MouseDown(object sender, MouseEventArgs e) return; } - // disable everything. - if (NodesTV.ContextMenuStrip != null) - { - foreach (ToolStripItem item in NodesTV.ContextMenuStrip.Items) - { + // disable everything. + if (NodesTV.ContextMenuStrip != null) + { + foreach (ToolStripItem item in NodesTV.ContextMenuStrip.Items) + { ToolStripMenuItem menuItem = item as ToolStripMenuItem; if (menuItem == null) @@ -315,10 +317,10 @@ private void NodesTV_MouseDown(object sender, MouseEventArgs e) } } } - } - } + } + } - // enable menu items according to context. + // enable menu items according to context. if (e.Button == MouseButtons.Right) { EnableMenuItems(clickedNode); @@ -326,7 +328,7 @@ private void NodesTV_MouseDown(object sender, MouseEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -376,15 +378,15 @@ protected virtual void NodesTV_DragOver(object sender, DragEventArgs e) { // overridden by sub-class. } - #endregion + #endregion } - + #region TreeNodeAction Eumeration - /// - /// The possible actions that could affect a node. - /// - public enum TreeNodeAction - { + /// + /// The possible actions that could affect a node. + /// + public enum TreeNodeAction + { /// /// A node was picked in the tree. /// @@ -394,27 +396,27 @@ public enum TreeNodeAction /// A node was selected in the tree. /// Selected - } + } #endregion - + #region TreeNodeActionEventArgs class - /// - /// The event argurments passed when an node event occurs. - /// - public class TreeNodeActionEventArgs : EventArgs - { + /// + /// The event argurments passed when an node event occurs. + /// + public class TreeNodeActionEventArgs : EventArgs + { #region Constructor /// /// Initializes the object. /// public TreeNodeActionEventArgs(TreeNodeAction action, object node, object parent) - { - m_node = node; + { + m_node = node; m_parent = parent; - m_action = action; - } + m_action = action; + } #endregion - + #region Private Fields /// /// The tag associated with the node that was acted on. @@ -423,7 +425,7 @@ public object Node { get { return m_node; } } - + /// /// The tag associated with the parent of the node that was acted on. /// @@ -431,22 +433,22 @@ public object Parent { get { return m_parent; } } - + /// /// The action in question. /// - public TreeNodeAction Action + public TreeNodeAction Action { get { return m_action; } } #endregion #region Private Fields - private object m_node; + private object m_node; private object m_parent; - private TreeNodeAction m_action; + private TreeNodeAction m_action; #endregion - } + } /// /// The delegate used to receive node action events. diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ClipboardHack.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ClipboardHack.cs index bafaae01e..accb66476 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ClipboardHack.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ClipboardHack.cs @@ -58,7 +58,7 @@ public static object GetData(string format) Thread thread = new Thread(new ThreadStart(GetClipboardPrivate)); thread.IsBackground = true; - + thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); @@ -71,7 +71,7 @@ public static object GetData(string format) return m_data; } } - + /// /// Saves the data in the clipboard. /// @@ -85,7 +85,7 @@ public static void SetData(string format, object data) Thread thread = new Thread(new ThreadStart(SetClipboardPrivate)); thread.IsBackground = true; - + thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); @@ -109,11 +109,11 @@ private static void GetClipboardPrivate() m_error = null; if (String.IsNullOrEmpty(m_format) || !Clipboard.ContainsData(m_format)) - { + { m_data = null; return; } - + m_data = Clipboard.GetData(m_format); } catch (Exception e) @@ -121,7 +121,7 @@ private static void GetClipboardPrivate() m_error = e; } } - + /// /// Saves the data in the clipboard if it is the correct format. /// @@ -132,7 +132,7 @@ private static void SetClipboardPrivate() m_error = null; if (String.IsNullOrEmpty(m_format) || m_data == null) - { + { return; } diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ComplexValueEditDlg.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ComplexValueEditDlg.cs index 196baabd4..660e97fc8 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ComplexValueEditDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ComplexValueEditDlg.cs @@ -56,11 +56,11 @@ public ComplexValueEditDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields private object m_value; #endregion - + #region Public Interface /// /// Displays the dialog. @@ -78,7 +78,7 @@ public object ShowDialog(object value, MonitoredItem monitoredItem) m_value = Utils.Clone(value); ValueCTRL.MonitoredItem = monitoredItem; - ValueCTRL.ShowValue(m_value); + ValueCTRL.ShowValueAsync(m_value); if (ShowDialog() != DialogResult.OK) { @@ -88,17 +88,17 @@ public object ShowDialog(object value, MonitoredItem monitoredItem) return m_value; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) - { + { try { DialogResult = DialogResult.OK; } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.Designer.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.Designer.cs index a4cbae4af..d6683ac68 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.Designer.cs @@ -74,7 +74,7 @@ private void InitializeComponent() // this.ItemsLV.ContextMenuStrip = this.PopupMenu; this.ItemsLV.MultiSelect = false; - this.ItemsLV.MouseClick += new System.Windows.Forms.MouseEventHandler(this.ItemsLV_MouseClick); + this.ItemsLV.MouseClick += new System.Windows.Forms.MouseEventHandler(this.ItemsLV_MouseClickAsync); // // PopupMenu // @@ -121,7 +121,7 @@ private void InitializeComponent() this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(135, 22); this.EditMI.Text = "Edit Value..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // DataListCtrl // diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.cs index 848dba32e..f62a52ee9 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -42,6 +42,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -122,15 +124,15 @@ public void Clear() /// /// Displays a value in the control. /// - public void ShowValue(object value) + public Task ShowValueAsync(object value, CancellationToken ct = default) { - ShowValue(value, false); + return ShowValueAsync(value, false, ct); } /// /// Displays a value in the control. /// - public void ShowValue(object value, bool overwrite) + public async Task ShowValueAsync(object value, bool overwrite, CancellationToken ct = default) { if (!overwrite) { @@ -151,7 +153,7 @@ public void ShowValue(object value, bool overwrite) // show the value. int index = 0; - ShowValue(ref index, ref overwrite, value); + await ShowValueAsync(index, overwrite, value, ct); // adjust columns. AdjustColumns(); @@ -179,7 +181,7 @@ protected override void EnableMenuItems(ListViewItem clickedItem) /// /// Stores the state associated with an item. /// - private class ValueState + private sealed class ValueState { public bool Expanded = false; public bool Expandable = false; @@ -217,8 +219,8 @@ private bool IsEditableType(object value) /// /// Shows the components of a value in the control. - /// - private void ShowChildren(ListViewItem listItem) + /// + private async Task ShowChildrenAsync(ListViewItem listItem, CancellationToken ct = default) { ValueState state = listItem.Tag as ValueState; @@ -236,14 +238,14 @@ private void ShowChildren(ListViewItem listItem) int index = listItem.Index + 1; bool overwrite = false; - ShowValue(ref index, ref overwrite, state.Component); + await ShowValueAsync(index, overwrite, state.Component, ct); AdjustColumns(); } /// /// Hides the components of a value in the control. - /// + /// private void HideChildren(ListViewItem listItem) { ValueState state = listItem.Tag as ValueState; @@ -430,7 +432,7 @@ private bool IsExpandableType(object value) /// /// Formats a value for display in the control. /// - private string GetValueText(object value) + private async Task GetValueTextAsync(object value, CancellationToken ct = default) { // check for null. if (value == null) @@ -449,7 +451,7 @@ private string GetValueText(object value) { if (ii != 0 && ii % 16 == 0) { - buffer.Append(" "); + buffer.Append(' '); } buffer.AppendFormat("{0:X2} ", bytes[ii]); @@ -536,7 +538,7 @@ private string GetValueText(object value) if (extension != null) { - return GetValueText(extension.Body); + return await GetValueTextAsync(extension.Body, ct); } // check for event value. @@ -546,7 +548,7 @@ private string GetValueText(object value) { if (m_monitoredItem != null) { - return String.Format("{0}", m_monitoredItem.GetEventType(eventFields)); + return String.Format("{0}", await m_monitoredItem.GetEventTypeAsync(eventFields, ct)); } return eventFields.GetType().Name; @@ -561,7 +563,7 @@ private string GetValueText(object value) if (!StatusCode.IsGood(dataValue.StatusCode)) { - formattedValue.Append("["); + formattedValue.Append('['); formattedValue.AppendFormat("Q:{0}", dataValue.StatusCode); } @@ -576,7 +578,7 @@ private string GetValueText(object value) } else { - formattedValue.Append("["); + formattedValue.Append('['); } formattedValue.Append("T:future"); @@ -598,14 +600,15 @@ private string GetValueText(object value) /// /// Updates the list with the specified value. /// - private void UpdateList( - ref int index, - ref bool overwrite, + private async Task<(int, bool)> UpdateListAsync( + int index, + bool overwrite, object value, object componentValue, object componentId, string name, - string type) + string type, + CancellationToken ct = default) { // get the list item to update. ListViewItem listitem = GetListItem(index, ref overwrite, name, type); @@ -616,7 +619,7 @@ private void UpdateList( else { // update list item. - listitem.SubItems[1].Text = GetValueText(componentValue); + listitem.SubItems[1].Text = await GetValueTextAsync(componentValue, ct); } // move to next item. @@ -630,7 +633,7 @@ private void UpdateList( if (state.Expanded && state.Expandable) { m_depth++; - ShowValue(ref index, ref overwrite, componentValue); + (index, overwrite) = await ShowValueAsync(index, overwrite, componentValue, ct); m_depth--; } } @@ -646,20 +649,22 @@ private void UpdateList( { listitem.ImageKey = CollapseIcon; } + return (index, overwrite); } /// /// Updates the list with the specified value. /// - private void UpdateList( - ref int index, - ref bool overwrite, + private async Task<(int, bool)> UpdateListAsync( + int index, + bool overwrite, object value, object componentValue, object componentId, string name, string type, - bool enabled) + bool enabled, + CancellationToken ct = default) { // get the list item to update. ListViewItem listitem = GetListItem(index, ref overwrite, name, type); @@ -670,7 +675,7 @@ private void UpdateList( } // update list item. - listitem.SubItems[1].Text = GetValueText(componentValue); + listitem.SubItems[1].Text = await GetValueTextAsync(componentValue, ct); // move to next item. index++; @@ -683,7 +688,7 @@ private void UpdateList( if (state.Expanded && state.Expandable) { m_depth++; - ShowValue(ref index, ref overwrite, componentValue); + (index, overwrite) = await ShowValueAsync(index, overwrite, componentValue, ct); m_depth--; } } @@ -699,18 +704,20 @@ private void UpdateList( { listitem.ImageKey = CollapseIcon; } + return (index, overwrite); } + /// /// Shows property of an encodeable object in the control. /// - private void ShowValue(ref int index, ref bool overwrite, IEncodeable value, PropertyInfo property) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, IEncodeable value, PropertyInfo property, CancellationToken ct = default) { // get the name of the property. string name = Utils.GetDataMemberName(property); if (name == null) { - return; + return Task.FromResult((index, overwrite)); } // get the property value. @@ -733,20 +740,13 @@ private void ShowValue(ref int index, ref bool overwrite, IEncodeable value, Pro } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - propertyValue, - property, - name, - property.PropertyType.Name); + return UpdateListAsync(index, overwrite, value, propertyValue, property, name, property.PropertyType.Name, ct); } /// /// Shows the element of an array in the control. /// - private void ShowValue(ref int index, ref bool overwrite, Array value, int element) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, Array value, int element, CancellationToken ct = default) { // get the name of the element. string name = Utils.Format("[{0}]", element); @@ -804,20 +804,13 @@ private void ShowValue(ref int index, ref bool overwrite, Array value, int eleme } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - elementValue, - element, - name, - type); + return UpdateListAsync(index, overwrite, value, elementValue, element, name, type, ct); } /// /// Shows the element of an array in the control. /// - private void ShowValue(ref int index, ref bool overwrite, Array value, int element, bool enabled) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, Array value, int element, bool enabled, CancellationToken ct = default) { // get the name of the element. string name = Utils.Format("[{0}]", element); @@ -834,15 +827,7 @@ private void ShowValue(ref int index, ref bool overwrite, Array value, int eleme } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - elementValue, - element, - name, - type, - enabled); + return UpdateListAsync(index, overwrite, value, elementValue, element, name, type, enabled, ct); } /// @@ -868,7 +853,7 @@ private bool PromptOnLongList(int length) /// /// Shows the element of a list in the control. /// - private void ShowValue(ref int index, ref bool overwrite, IList value, int element) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, IList value, int element, CancellationToken ct = default) { // get the name of the element. string name = Utils.Format("[{0}]", element); @@ -885,27 +870,20 @@ private void ShowValue(ref int index, ref bool overwrite, IList value, int eleme } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - elementValue, - element, - name, - type); + return UpdateListAsync(index, overwrite, value, elementValue, element, name, type, ct); } /// /// Shows an XML element in the control. /// - private void ShowValue(ref int index, ref bool overwrite, XmlElement value, int childIndex) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, XmlElement value, int childIndex, CancellationToken ct = default) { // ignore children that are not elements. XmlElement child = value.ChildNodes[childIndex] as XmlElement; if (child == null) { - return; + return Task.FromResult((index, overwrite)); } // get the name of the element. @@ -915,27 +893,20 @@ private void ShowValue(ref int index, ref bool overwrite, XmlElement value, int string type = value.GetType().Name; // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - child, - childIndex, - name, - type); + return UpdateListAsync(index, overwrite, value, child, childIndex, name, type, ct); } /// /// Shows an event in the control. /// - private void ShowValue(ref int index, ref bool overwrite, EventFieldList value, int fieldIndex) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, EventFieldList value, int fieldIndex, CancellationToken ct = default) { // ignore children that are not elements. object field = value.EventFields[fieldIndex].Value; if (field == null) { - return; + return Task.FromResult((index, overwrite)); } // get the name of the element. @@ -950,20 +921,13 @@ private void ShowValue(ref int index, ref bool overwrite, EventFieldList value, string type = value.GetType().Name; // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - field, - fieldIndex, - name, - type); + return UpdateListAsync(index, overwrite, value, field, fieldIndex, name, type, ct); } /// - /// Shows a byte array in the control. + /// Shows a byte array in the control. /// - private void ShowValue(ref int index, ref bool overwrite, byte[] value, int blockStart) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, byte[] value, int blockStart, CancellationToken ct = default) { // get the name of the element. string name = Utils.Format("[{0:X4}]", blockStart); @@ -983,20 +947,13 @@ private void ShowValue(ref int index, ref bool overwrite, byte[] value, int bloc string type = value.GetType().Name; // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - blockValue, - blockStart, - name, - type); + return UpdateListAsync(index, overwrite, value, blockValue, blockStart, name, type, ct); } /// - /// Shows a data value in the control. + /// Shows a data value in the control. /// - private void ShowValue(ref int index, ref bool overwrite, DataValue value, int component) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, DataValue value, int component, CancellationToken ct = default) { string name = null; object componentValue = null; @@ -1051,7 +1008,7 @@ private void ShowValue(ref int index, ref bool overwrite, DataValue value, int c // don't display empty components. if (name == null) { - return; + return Task.FromResult((index, overwrite)); } // get the type name. @@ -1063,20 +1020,13 @@ private void ShowValue(ref int index, ref bool overwrite, DataValue value, int c } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - componentValue, - component, - name, - type); + return UpdateListAsync(index, overwrite, value, componentValue, component, name, type, ct); } /// - /// Shows a node id in the control. + /// Shows a node id in the control. /// - private void ShowValue(ref int index, ref bool overwrite, NodeId value, int component) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, NodeId value, int component, CancellationToken ct = default) { string name = null; object componentValue = null; @@ -1108,7 +1058,7 @@ private void ShowValue(ref int index, ref bool overwrite, NodeId value, int comp // don't display empty components. if (name == null) { - return; + return Task.FromResult((index, overwrite)); } // get the type name. @@ -1120,20 +1070,13 @@ private void ShowValue(ref int index, ref bool overwrite, NodeId value, int comp } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - componentValue, - component, - name, - type); + return UpdateListAsync(index, overwrite, value, componentValue, component, name, type, ct); } /// - /// Shows am expanded node id in the control. + /// Shows am expanded node id in the control. /// - private void ShowValue(ref int index, ref bool overwrite, ExpandedNodeId value, int component) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, ExpandedNodeId value, int component, CancellationToken ct = default) { string name = null; object componentValue = null; @@ -1172,7 +1115,7 @@ private void ShowValue(ref int index, ref bool overwrite, ExpandedNodeId value, // don't display empty components. if (name == null) { - return; + return Task.FromResult((index, overwrite)); } // get the type name. @@ -1184,20 +1127,13 @@ private void ShowValue(ref int index, ref bool overwrite, ExpandedNodeId value, } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - componentValue, - component, - name, - type); + return UpdateListAsync(index, overwrite, value, componentValue, component, name, type, ct); } /// - /// Shows qualified name in the control. + /// Shows qualified name in the control. /// - private void ShowValue(ref int index, ref bool overwrite, QualifiedName value, int component) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, QualifiedName value, int component, CancellationToken ct = default) { string name = null; object componentValue = null; @@ -1222,7 +1158,7 @@ private void ShowValue(ref int index, ref bool overwrite, QualifiedName value, i // don't display empty components. if (name == null) { - return; + return Task.FromResult((index, overwrite)); ; } // get the type name. @@ -1234,20 +1170,13 @@ private void ShowValue(ref int index, ref bool overwrite, QualifiedName value, i } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - componentValue, - component, - name, - type); + return UpdateListAsync(index, overwrite, value, componentValue, component, name, type, ct); } /// - /// Shows localized text in the control. + /// Shows localized text in the control. /// - private void ShowValue(ref int index, ref bool overwrite, LocalizedText value, int component) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, LocalizedText value, int component, CancellationToken ct = default) { string name = null; object componentValue = null; @@ -1272,7 +1201,7 @@ private void ShowValue(ref int index, ref bool overwrite, LocalizedText value, i // don't display empty components. if (name == null) { - return; + return Task.FromResult((index, overwrite)); ; } // get the type name. @@ -1284,20 +1213,13 @@ private void ShowValue(ref int index, ref bool overwrite, LocalizedText value, i } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - componentValue, - component, - name, - type); + return UpdateListAsync(index, overwrite, value, componentValue, component, name, type, ct); } /// - /// Shows a string in the control. + /// Shows a string in the control. /// - private void ShowValue(ref int index, ref bool overwrite, string value) + private Task<(int, bool)> ShowValueAsync(int index, bool overwrite, string value, CancellationToken ct = default) { string name = "Value"; object componentValue = value; @@ -1305,7 +1227,7 @@ private void ShowValue(ref int index, ref bool overwrite, string value) // don't display empty components. if (name == null) { - return; + return Task.FromResult((index, overwrite)); } // get the type name. @@ -1317,24 +1239,17 @@ private void ShowValue(ref int index, ref bool overwrite, string value) } // update the list view. - UpdateList( - ref index, - ref overwrite, - value, - componentValue, - 0, - name, - type); + return UpdateListAsync(index, overwrite, value, componentValue, 0, name, type, ct); } /// /// Shows a value in control. /// - private void ShowValue(ref int index, ref bool overwrite, object value) + private async Task<(int, bool)> ShowValueAsync(int index, bool overwrite, object value, CancellationToken ct = default) { if (value == null) { - return; + return (index, overwrite); } // show monitored items. @@ -1343,8 +1258,7 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (monitoredItem != null) { m_monitoredItem = monitoredItem; - ShowValue(ref index, ref overwrite, monitoredItem.LastValue); - return; + return await ShowValueAsync(index, overwrite, monitoredItem.LastValue, ct); } // show data changes @@ -1352,8 +1266,7 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (datachange != null) { - ShowValue(ref index, ref overwrite, datachange.Value); - return; + return await ShowValueAsync(index, overwrite, datachange.Value, ct); } // show write value with IndexRange @@ -1376,10 +1289,10 @@ private void ShowValue(ref int index, ref bool overwrite, object value) bool enabled = ((indexRange.Begin <= ii && indexRange.End >= ii) || (indexRange.End < 0 && indexRange.Begin == ii)); - ShowValue(ref index, ref overwrite, arrayvalue, ii, enabled); + (index, overwrite) = await ShowValueAsync(index, overwrite, arrayvalue, ii, enabled, ct); } - return; + return (index, overwrite); } } } @@ -1391,10 +1304,10 @@ private void ShowValue(ref int index, ref bool overwrite, object value) { for (int ii = 0; ii < eventFields.EventFields.Count; ii++) { - ShowValue(ref index, ref overwrite, eventFields, ii); + (index, overwrite) = await ShowValueAsync(index, overwrite, eventFields, ii, ct); } - return; + return (index, overwrite); } // show extension bodies. @@ -1402,8 +1315,7 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (extension != null) { - ShowValue(ref index, ref overwrite, extension.Body); - return; + return await ShowValueAsync(index, overwrite, extension.Body, ct); } // show encodeables. @@ -1415,10 +1327,10 @@ private void ShowValue(ref int index, ref bool overwrite, object value) foreach (PropertyInfo property in properties) { - ShowValue(ref index, ref overwrite, encodeable, property); + (index, overwrite) = await ShowValueAsync(index, overwrite, encodeable, property, ct); } - return; + return (index, overwrite); } // show bytes. @@ -1426,17 +1338,14 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (bytes != null) { - if (!PromptOnLongList(bytes.Length / 16)) + if (PromptOnLongList(bytes.Length / 16)) { - return; - } - - for (int ii = 0; ii < bytes.Length; ii += 16) - { - ShowValue(ref index, ref overwrite, bytes, ii); + for (int ii = 0; ii < bytes.Length; ii += 16) + { + (index, overwrite) = await ShowValueAsync(index, overwrite, bytes, ii, ct); + } } - - return; + return (index, overwrite); } // show arrays @@ -1454,17 +1363,14 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (array != null) { - if (!PromptOnLongList(array.GetLength(0))) + if (PromptOnLongList(array.GetLength(0))) { - return; - } - - for (int ii = 0; ii < array.GetLength(0); ii++) - { - ShowValue(ref index, ref overwrite, array, ii); + for (int ii = 0; ii < array.GetLength(0); ii++) + { + (index, overwrite) = await ShowValueAsync(index, overwrite, array, ii, ct); + } } - - return; + return (index, overwrite); } // show lists @@ -1472,17 +1378,14 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (list != null) { - if (!PromptOnLongList(list.Count)) + if (PromptOnLongList(list.Count)) { - return; - } - - for (int ii = 0; ii < list.Count; ii++) - { - ShowValue(ref index, ref overwrite, list, ii); + for (int ii = 0; ii < list.Count; ii++) + { + (index, overwrite) = await ShowValueAsync(index, overwrite, list, ii, ct); + } } - - return; + return (index, overwrite); } // show xml elements @@ -1490,17 +1393,14 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (xml != null) { - if (!PromptOnLongList(xml.ChildNodes.Count)) + if (PromptOnLongList(xml.ChildNodes.Count)) { - return; - } - - for (int ii = 0; ii < xml.ChildNodes.Count; ii++) - { - ShowValue(ref index, ref overwrite, xml, ii); + for (int ii = 0; ii < xml.ChildNodes.Count; ii++) + { + (index, overwrite) = await ShowValueAsync(index, overwrite, xml, ii, ct); + } } - - return; + return (index, overwrite); } // show data value. @@ -1508,11 +1408,10 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (datavalue != null) { - ShowValue(ref index, ref overwrite, datavalue, 0); - ShowValue(ref index, ref overwrite, datavalue, 1); - ShowValue(ref index, ref overwrite, datavalue, 2); - ShowValue(ref index, ref overwrite, datavalue, 3); - return; + (index, overwrite) = await ShowValueAsync(index, overwrite, datavalue, 0, ct); + (index, overwrite) = await ShowValueAsync(index, overwrite, datavalue, 1, ct); + (index, overwrite) = await ShowValueAsync(index, overwrite, datavalue, 2, ct); + return await ShowValueAsync(index, overwrite, datavalue, 3, ct); } // show node id value. @@ -1520,10 +1419,9 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (nodeId != null) { - ShowValue(ref index, ref overwrite, nodeId, 0); - ShowValue(ref index, ref overwrite, nodeId, 1); - ShowValue(ref index, ref overwrite, nodeId, 2); - return; + (index, overwrite) = await ShowValueAsync(index, overwrite, nodeId, 0, ct); + (index, overwrite) = await ShowValueAsync(index, overwrite, nodeId, 1, ct); + return await ShowValueAsync(index, overwrite, nodeId, 2, ct); } // show expanded node id value. @@ -1531,11 +1429,10 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (expandedNodeId != null) { - ShowValue(ref index, ref overwrite, expandedNodeId, 0); - ShowValue(ref index, ref overwrite, expandedNodeId, 1); - ShowValue(ref index, ref overwrite, expandedNodeId, 2); - ShowValue(ref index, ref overwrite, expandedNodeId, 3); - return; + (index, overwrite) = await ShowValueAsync(index, overwrite, expandedNodeId, 0, ct); + (index, overwrite) = await ShowValueAsync(index, overwrite, expandedNodeId, 1, ct); + (index, overwrite) = await ShowValueAsync(index, overwrite, expandedNodeId, 2, ct); + return await ShowValueAsync(index, overwrite, expandedNodeId, 3, ct); } // show qualified name value. @@ -1543,9 +1440,8 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (qualifiedName != null) { - ShowValue(ref index, ref overwrite, qualifiedName, 0); - ShowValue(ref index, ref overwrite, qualifiedName, 1); - return; + (index, overwrite) = await ShowValueAsync(index, overwrite, qualifiedName, 0, ct); + return await ShowValueAsync(index, overwrite, qualifiedName, 1, ct); } // show qualified name value. @@ -1553,9 +1449,8 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (localizedText != null) { - ShowValue(ref index, ref overwrite, localizedText, 0); - ShowValue(ref index, ref overwrite, localizedText, 1); - return; + (index, overwrite) = await ShowValueAsync(index, overwrite, localizedText, 0, ct); + return await ShowValueAsync(index, overwrite, localizedText, 1, ct); } // show variant. @@ -1563,15 +1458,14 @@ private void ShowValue(ref int index, ref bool overwrite, object value) if (variant != null) { - ShowValue(ref index, ref overwrite, variant.Value.Value); - return; + return await ShowValueAsync(index, overwrite, variant.Value.Value, ct); } // show unknown types as strings. - ShowValue(ref index, ref overwrite, String.Format("{0}", value)); + return await ShowValueAsync(index, overwrite, String.Format("{0}", value), ct); } - private void ItemsLV_MouseClick(object sender, MouseEventArgs e) + private async void ItemsLV_MouseClickAsync(object sender, MouseEventArgs e) { try { @@ -1600,7 +1494,7 @@ private void ItemsLV_MouseClick(object sender, MouseEventArgs e) } else { - ShowChildren(listItem); + await ShowChildrenAsync(listItem); } } catch (Exception exception) @@ -1641,7 +1535,7 @@ private void RefreshMI_Click(object sender, EventArgs e) { /* Clear(); - ShowValue(m_monitoredItem); + ShowValueAsync(m_monitoredItem); */ } catch (Exception exception) @@ -1662,7 +1556,7 @@ private void ClearMI_Click(object sender, EventArgs e) } } - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -1743,7 +1637,7 @@ private void EditMI_Click(object sender, EventArgs e) } bool overwrite = true; - ShowValue(ref index, ref overwrite, state.Value); + await ShowValueAsync(index, overwrite, state.Value); } catch (Exception exception) { diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/DateTimeValueEditDlg.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/DateTimeValueEditDlg.cs index 9b2eb5951..b01a40821 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/DateTimeValueEditDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/DateTimeValueEditDlg.cs @@ -53,7 +53,7 @@ public DateTimeValueEditDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Public Interface /// /// Displays the dialog. @@ -77,7 +77,7 @@ public bool ShowDialog(ref DateTime value) { return false; } - + value = ValueCTRL.Value; if (value == ValueCTRL.MinDate) diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/GuiUtils.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/GuiUtils.cs index b05baab3a..6619ebf2b 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/GuiUtils.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/GuiUtils.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,8 +33,10 @@ using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; +using System.Xml; namespace Opc.Ua.Client.Controls { @@ -272,7 +274,7 @@ public static bool HandleDomainCheckError(string caption, ServiceResult serviceR { if (comma) { - buffer.Append(","); + buffer.Append(','); } buffer.AppendFormat(" {0}", domain); comma = true; @@ -356,7 +358,7 @@ public static object GetDefaultValue(NodeId datatypeId, int valueRank) if (type == typeof(byte[])) { - return new byte[0]; + return Array.Empty(); } if (type == typeof(NodeId)) @@ -386,8 +388,9 @@ public static object GetDefaultValue(NodeId datatypeId, int valueRank) if (type == typeof(System.Xml.XmlElement)) { - System.Xml.XmlDocument document = new System.Xml.XmlDocument(); - document.InnerXml = ""; + System.Xml.XmlDocument document = new System.Xml.XmlDocument { XmlResolver = null }; + using XmlReader reader = XmlReader.Create("", new XmlReaderSettings() { XmlResolver = null }); + document.Load(reader); return document.DocumentElement; } @@ -524,18 +527,18 @@ public static object EditValue(Session session, object value, NodeId datatypeId, /// /// Returns to display icon for the target of a reference. /// - public static string GetTargetIcon(Session session, ReferenceDescription reference) + public static Task GetTargetIconAsync(ISession session, ReferenceDescription reference, CancellationToken ct = default) { - return GetTargetIcon(session, reference.NodeClass, reference.TypeDefinition); + return GetTargetIconAsync(session, reference.NodeClass, reference.TypeDefinition, ct); } /// /// Returns to display icon for the target of a reference. /// - public static string GetTargetIcon(Session session, NodeClass nodeClass, ExpandedNodeId typeDefinitionId) + public static async Task GetTargetIconAsync(ISession session, NodeClass nodeClass, ExpandedNodeId typeDefinitionId, CancellationToken ct = default) { // make sure the type definition is in the cache. - INode typeDefinition = session.NodeCache.Find(typeDefinitionId); + INode typeDefinition = await session.NodeCache.FindAsync(typeDefinitionId, ct); switch (nodeClass) { diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.Designer.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.Designer.cs index 36713968c..f257ad952 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.Designer.cs @@ -81,7 +81,7 @@ private void InitializeComponent() this.BrowseBTN.TabIndex = 5; this.BrowseBTN.Text = "..."; this.BrowseBTN.UseVisualStyleBackColor = true; - this.BrowseBTN.Click += new System.EventHandler(this.BrowseBTN_Click); + this.BrowseBTN.Click += new System.EventHandler(this.BrowseBTN_ClickAsync); // // NodeIdCtrl // diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.cs index 1a86214d6..d0d618dbd 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -46,7 +46,7 @@ namespace Opc.Ua.Client.Controls /// public partial class NodeIdCtrl : UserControl { - #region Constructors + #region Constructors /// /// Initializes a new instance of the class. /// @@ -57,43 +57,43 @@ public NodeIdCtrl() m_rootId = Objects.RootFolder; BrowseBTN.Enabled = false; } - #endregion - - #region Event Handlers + #endregion + + #region Event Handlers private Browser m_browser; private NodeId m_rootId; private ReferenceDescription m_reference; private event EventHandler m_IdentifierChanged; - #endregion - - #region Public Interface + #endregion + + #region Public Interface /// /// Raised if the node id is changed. /// public event EventHandler IdentifierChanged { - add { m_IdentifierChanged += value; } + add { m_IdentifierChanged += value; } remove { m_IdentifierChanged -= value; } } - + /// /// The browser to used browse for a node id. /// [DefaultValue(null)] public Browser Browser { - get - { - return m_browser; + get + { + return m_browser; } - - set - { - m_browser = value; + + set + { + m_browser = value; BrowseBTN.Enabled = m_browser != null; } } - + /// /// The root node id to display when browsing. /// @@ -102,7 +102,7 @@ public NodeId RootId { get { - return m_rootId; + return m_rootId; } set @@ -123,7 +123,7 @@ public NodeId RootId public bool IsEmpty { get - { + { return String.IsNullOrEmpty(NodeIdTB.Text); } } @@ -135,16 +135,16 @@ public bool IsEmpty public NodeId Identifier { get - { - return NodeId.Parse(NodeIdTB.Text); + { + return NodeId.Parse(NodeIdTB.Text); } - + set - { - NodeIdTB.Text = Utils.Format("{0}", value); + { + NodeIdTB.Text = Utils.Format("{0}", value); } } - + /// /// The reference seleected if the browse feature was used. /// @@ -152,12 +152,12 @@ public NodeId Identifier public ReferenceDescription Reference { get - { - return m_reference; + { + return m_reference; } - + set - { + { m_reference = value; if (m_reference != null) @@ -166,14 +166,14 @@ public ReferenceDescription Reference } } } - #endregion - - #region Event Handlers - private void BrowseBTN_Click(object sender, EventArgs e) + #endregion + + #region Event Handlers + private async void BrowseBTN_ClickAsync(object sender, EventArgs e) { try { - ReferenceDescription reference = new SelectNodeDlg().ShowDialog(m_browser.Session as Session, RootId, null, "", null); + ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync(m_browser.Session as Session, RootId, null, "", default, null); if (reference != null && reference.NodeId != null) { @@ -188,7 +188,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -199,6 +199,6 @@ private void NodeIdTB_TextChanged(object sender, EventArgs e) m_IdentifierChanged(this, null); } } - #endregion + #endregion } } diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdValueEditDlg.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdValueEditDlg.cs index c57e3949b..0a6269c6a 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdValueEditDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdValueEditDlg.cs @@ -55,17 +55,17 @@ public NodeIdValueEditDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Public Interface /// /// Displays the dialog. /// public NodeId ShowDialog(Session session, NodeId value) { - if (session == null) throw new ArgumentNullException("session"); + if (session == null) throw new ArgumentNullException(nameof(session)); - ValueCTRL.Browser = new Browser(session); - ValueCTRL.RootId = Objects.RootFolder; + ValueCTRL.Browser = new Browser(session); + ValueCTRL.RootId = Objects.RootFolder; ValueCTRL.Identifier = value; if (ShowDialog() != DialogResult.OK) @@ -81,10 +81,10 @@ public NodeId ShowDialog(Session session, NodeId value) /// public ExpandedNodeId ShowDialog(Session session, ExpandedNodeId value) { - if (session == null) throw new ArgumentNullException("session"); + if (session == null) throw new ArgumentNullException(nameof(session)); - ValueCTRL.Browser = new Browser(session); - ValueCTRL.RootId = Objects.RootFolder; + ValueCTRL.Browser = new Browser(session); + ValueCTRL.RootId = Objects.RootFolder; ValueCTRL.Identifier = ExpandedNodeId.ToNodeId(value, session.NamespaceUris); if (ShowDialog() != DialogResult.OK) diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NumericValueEditDlg.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NumericValueEditDlg.cs index 4e8781dd3..0bc77ec2b 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NumericValueEditDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NumericValueEditDlg.cs @@ -53,7 +53,7 @@ public NumericValueEditDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Public Interface /// /// Displays the dialog. @@ -82,7 +82,7 @@ public object ShowDialog(object value, Type type) return Convert.ChangeType(ValueCTRL.Value, type); } #endregion - + #region Private Methods /// /// Sets the limits according to the data type. diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ReferenceTypeCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ReferenceTypeCtrl.cs index d5013f1ce..1d5e743d7 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ReferenceTypeCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ReferenceTypeCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -35,6 +35,8 @@ using System.Text; using System.Windows.Forms; using System.Reflection; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -55,16 +57,16 @@ public ReferenceTypeCtrl() #endregion #region Private Fields - private Session m_session; + private ISession m_session; private NodeId m_baseTypeId; private event EventHandler m_referenceSelectionChanged; #endregion - + #region Public Interface /// /// Initializes the control with references starting with the specified based type. /// - public void Initialize(Session session, NodeId baseTypeId) + public async Task InitializeAsync(ISession session, NodeId baseTypeId, CancellationToken ct = default) { m_session = session; m_baseTypeId = baseTypeId; @@ -79,10 +81,10 @@ public void Initialize(Session session, NodeId baseTypeId) // recurcively fetch the reference types from the server. if (m_session != null) { - AddReferenceTypes(m_baseTypeId, null); + await AddReferenceTypesAsync(m_baseTypeId, null, ct); } } - + /// /// The currently seleected reference type id. /// @@ -97,7 +99,7 @@ public NodeId SelectedTypeId return null; } - return choice.ReferenceType.NodeId; + return choice.ReferenceType.NodeId; } set @@ -105,7 +107,7 @@ public NodeId SelectedTypeId for (int ii = 0; ii < ReferenceTypesCB.Items.Count; ii++) { ReferenceTypeChoice choice = ReferenceTypesCB.Items[ii] as ReferenceTypeChoice; - + if (choice != null && choice.ReferenceType.NodeId == value) { ReferenceTypesCB.SelectedIndex = ii; @@ -125,8 +127,8 @@ public NodeId SelectedTypeId /// public event EventHandler ReferenceSelectionChanged { - add { m_referenceSelectionChanged += value; } - remove { m_referenceSelectionChanged -= value; } + add { m_referenceSelectionChanged += value; } + remove { m_referenceSelectionChanged -= value; } } #region ReferenceSelectedEventArgs Class @@ -155,12 +157,12 @@ public NodeId ReferenceTypeId } #endregion #endregion - + #region ReferenceTypeChoice Class /// /// A reference type that may be used as a browse filter. /// - private class ReferenceTypeChoice + private sealed class ReferenceTypeChoice { /// /// The text to display in the control. @@ -172,35 +174,35 @@ public override string ToString() return ""; } - StringBuilder text = new StringBuilder(); - + StringBuilder text = new StringBuilder(); + GetPrefix(text); if (text.Length > 0) { text.Append("> "); } - + if (ReferenceType != null) { text.Append(ReferenceType.ToString()); } - + return text.ToString(); } - + /// /// Adds a prefix for subtypes. /// private void GetPrefix(StringBuilder prefix) - { + { if (SuperType != null) { SuperType.GetPrefix(prefix); - prefix.Append("--"); + prefix.Append("--"); } } - + public ReferenceTypeNode ReferenceType; public ReferenceTypeChoice SuperType; } @@ -210,14 +212,14 @@ private void GetPrefix(StringBuilder prefix) /// /// Adds the reference types to drop down box. /// - private void AddReferenceTypes(ExpandedNodeId referenceTypeId, ReferenceTypeChoice supertype) + private async Task AddReferenceTypesAsync(ExpandedNodeId referenceTypeId, ReferenceTypeChoice supertype, CancellationToken ct = default) { if (referenceTypeId == null) throw new ApplicationException("referenceTypeId"); - + try { // find reference. - ReferenceTypeNode node = m_session.NodeCache.Find(referenceTypeId) as ReferenceTypeNode; + ReferenceTypeNode node = await m_session.NodeCache.FindAsync(referenceTypeId, ct) as ReferenceTypeNode; if (node == null) { @@ -228,16 +230,16 @@ private void AddReferenceTypes(ExpandedNodeId referenceTypeId, ReferenceTypeChoi ReferenceTypeChoice choice = new ReferenceTypeChoice(); choice.ReferenceType = node; - choice.SuperType = supertype; + choice.SuperType = supertype; ReferenceTypesCB.Items.Add(choice); - + // recursively add subtypes. - IList subtypes = m_session.NodeCache.FindReferences(node.NodeId, ReferenceTypeIds.HasSubtype, false, true); + IList subtypes = await m_session.NodeCache.FindReferencesAsync(node.NodeId, ReferenceTypeIds.HasSubtype, false, true, ct); foreach (INode subtype in subtypes) { - AddReferenceTypes(subtype.NodeId, choice); + await AddReferenceTypesAsync(subtype.NodeId, choice, ct); } } catch (Exception e) @@ -261,11 +263,11 @@ private void ReferenceTypesCB_SelectedIndexChanged(object sender, EventArgs e) { m_referenceSelectionChanged(this, new ReferenceSelectedEventArgs(referenceTypeId)); } - } - } + } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/SimpleValueEditDlg.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/SimpleValueEditDlg.cs index 07b377bb8..6a2c226c9 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/SimpleValueEditDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/SimpleValueEditDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -41,34 +41,34 @@ namespace Opc.Ua.Client.Controls { - /// - /// - /// + /// + /// Simple value edit dialog + /// public partial class SimpleValueEditDlg : Form { #region Constructors - /// - /// Default constructor - /// + /// + /// Default constructor + /// public SimpleValueEditDlg() { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields private object m_value; private Type m_type; #endregion - + #region Public Interface /// /// Displays the dialog. /// public object ShowDialog(object value, Type type) { - if (type == null) throw new ArgumentNullException("type"); + if (type == null) throw new ArgumentNullException(nameof(type)); m_type = type; @@ -83,47 +83,47 @@ public object ShowDialog(object value, Type type) return m_value; } - + /// /// Returns true if the dialog supports editing the type. /// public static bool IsSimpleType(Type type) { - if (type == typeof(bool)) return true; - if (type == typeof(sbyte)) return true; - if (type == typeof(byte)) return true; - if (type == typeof(short)) return true; - if (type == typeof(ushort)) return true; - if (type == typeof(int)) return true; - if (type == typeof(uint)) return true; - if (type == typeof(long)) return true; - if (type == typeof(ulong)) return true; - if (type == typeof(float)) return true; - if (type == typeof(double)) return true; - if (type == typeof(string)) return true; + if (type == typeof(bool)) return true; + if (type == typeof(sbyte)) return true; + if (type == typeof(byte)) return true; + if (type == typeof(short)) return true; + if (type == typeof(ushort)) return true; + if (type == typeof(int)) return true; + if (type == typeof(uint)) return true; + if (type == typeof(long)) return true; + if (type == typeof(ulong)) return true; + if (type == typeof(float)) return true; + if (type == typeof(double)) return true; + if (type == typeof(string)) return true; if (type == typeof(DateTime)) return true; - if (type == typeof(Guid)) return true; + if (type == typeof(Guid)) return true; return false; } #endregion - + private object Parse(string text) { - if (m_type == typeof(bool)) return Convert.ToBoolean(text); - if (m_type == typeof(sbyte)) return Convert.ToSByte(text); - if (m_type == typeof(byte)) return Convert.ToByte(text); - if (m_type == typeof(short)) return Convert.ToInt16(text); - if (m_type == typeof(ushort)) return Convert.ToUInt16(text); - if (m_type == typeof(int)) return Convert.ToInt32(text); - if (m_type == typeof(uint)) return Convert.ToUInt32(text); - if (m_type == typeof(long)) return Convert.ToInt64(text); - if (m_type == typeof(ulong)) return Convert.ToUInt64(text); - if (m_type == typeof(float)) return Convert.ToSingle(text); - if (m_type == typeof(double)) return Convert.ToDouble(text); - if (m_type == typeof(string)) return text; - if (m_type == typeof(DateTime)) return DateTime.ParseExact(text, "yyyy-MM-dd HH:mm:ss.fff", null); - if (m_type == typeof(Guid)) return new Guid(text); + if (m_type == typeof(bool)) return Convert.ToBoolean(text); + if (m_type == typeof(sbyte)) return Convert.ToSByte(text); + if (m_type == typeof(byte)) return Convert.ToByte(text); + if (m_type == typeof(short)) return Convert.ToInt16(text); + if (m_type == typeof(ushort)) return Convert.ToUInt16(text); + if (m_type == typeof(int)) return Convert.ToInt32(text); + if (m_type == typeof(uint)) return Convert.ToUInt32(text); + if (m_type == typeof(long)) return Convert.ToInt64(text); + if (m_type == typeof(ulong)) return Convert.ToUInt64(text); + if (m_type == typeof(float)) return Convert.ToSingle(text); + if (m_type == typeof(double)) return Convert.ToDouble(text); + if (m_type == typeof(string)) return text; + if (m_type == typeof(DateTime)) return DateTime.ParseExact(text, "yyyy-MM-dd HH:mm:ss.fff", null); + if (m_type == typeof(Guid)) return new Guid(text); if (m_type == typeof(QualifiedName)) return new QualifiedName(text); if (m_type == typeof(LocalizedText)) return new LocalizedText(text); @@ -132,7 +132,7 @@ private object Parse(string text) #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) - { + { try { m_value = Parse(ValueTB.Text); @@ -140,7 +140,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/StringValueEditDlg.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/StringValueEditDlg.cs index 8493705c2..73d8398d7 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/StringValueEditDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/StringValueEditDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -53,7 +53,7 @@ public StringValueEditDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Public Interface /// /// Displays the dialog. @@ -71,7 +71,7 @@ public string ShowDialog(string value) length = 20; } - this.Height += (length-1)*16; + this.Height += (length - 1) * 16; } if (ShowDialog() != DialogResult.OK) diff --git a/Samples/ClientControls.Net4/Configuration/SelectCertificateStoreCtrl.cs b/Samples/ClientControls.Net4/Configuration/SelectCertificateStoreCtrl.cs index 2ab31ee4e..b43a86fe6 100644 --- a/Samples/ClientControls.Net4/Configuration/SelectCertificateStoreCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/SelectCertificateStoreCtrl.cs @@ -53,11 +53,11 @@ public SelectCertificateStoreCtrl() InitializeComponent(); } #endregion - + #region Private Fields private event EventHandler m_CertificateStoreSelected; #endregion - + #region Public Interface /// /// Gets or sets the control that is stores with the current certificate store. diff --git a/Samples/ClientControls.Net4/Configuration/SelectFileCtrl.cs b/Samples/ClientControls.Net4/Configuration/SelectFileCtrl.cs index da17ce636..b7c51c024 100644 --- a/Samples/ClientControls.Net4/Configuration/SelectFileCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/SelectFileCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -53,11 +53,11 @@ public SelectFileCtrl() InitializeComponent(); } #endregion - + #region Private Fields private event EventHandler m_FileSelected; #endregion - + #region Public Interface /// /// Gets or sets the default file extension. diff --git a/Samples/ClientControls.Net4/Configuration/SelectProfileCtrl.cs b/Samples/ClientControls.Net4/Configuration/SelectProfileCtrl.cs index 881abded3..bab7c5a0b 100644 --- a/Samples/ClientControls.Net4/Configuration/SelectProfileCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/SelectProfileCtrl.cs @@ -53,21 +53,21 @@ public SelectProfileCtrl() InitializeComponent(); } #endregion - + #region Private Fields private event EventHandler m_ProfilesChanged; private Opc.Ua.Security.ListOfSecurityProfiles m_profiles; #endregion - + #region Public Interface /// /// The list of available security profiles. /// - public Opc.Ua.Security.ListOfSecurityProfiles Profiles + public Opc.Ua.Security.ListOfSecurityProfiles Profiles { - get - { - return m_profiles; + get + { + return m_profiles; } set @@ -99,7 +99,7 @@ public Opc.Ua.Security.ListOfSecurityProfiles Profiles } } - + /// /// Gets or sets the control that is stores with the current file path. /// diff --git a/Samples/ClientControls.Net4/Configuration/SelectUrlsCtrl.cs b/Samples/ClientControls.Net4/Configuration/SelectUrlsCtrl.cs index fdbdc268b..d386547ea 100644 --- a/Samples/ClientControls.Net4/Configuration/SelectUrlsCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/SelectUrlsCtrl.cs @@ -53,21 +53,21 @@ public SelectUrlsCtrl() InitializeComponent(); } #endregion - + #region Private Fields private event EventHandler m_UrlsChanged; private List m_urls; #endregion - + #region Public Interface /// /// The list of urls. /// - public List Urls + public List Urls { - get + get { - return m_urls; + return m_urls; } set @@ -89,7 +89,7 @@ public List Urls if (value[ii].Port > 0) { - builder.Append(":"); + builder.Append(':'); builder.Append(value[ii].Port); } } @@ -101,7 +101,7 @@ public List Urls m_urls = value; } } - + /// /// Gets or sets the control that is stores with the current file path. /// diff --git a/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.Designer.cs b/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.Designer.cs index 6932e6550..919aae06a 100644 --- a/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.Designer.cs +++ b/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.Designer.cs @@ -107,7 +107,7 @@ private void InitializeComponent() this.ExportBTN.TabIndex = 3; this.ExportBTN.Text = "Export..."; this.ExportBTN.UseVisualStyleBackColor = true; - this.ExportBTN.Click += new System.EventHandler(this.ExportBTN_Click); + this.ExportBTN.Click += new System.EventHandler(this.ExportBTN_ClickAsync); // // DetailsBTN // @@ -118,7 +118,7 @@ private void InitializeComponent() this.DetailsBTN.TabIndex = 2; this.DetailsBTN.Text = "Details..."; this.DetailsBTN.UseVisualStyleBackColor = true; - this.DetailsBTN.Click += new System.EventHandler(this.DetailsBTN_Click); + this.DetailsBTN.Click += new System.EventHandler(this.DetailsBTN_ClickAsync); // // OkBTN // diff --git a/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.cs b/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.cs index 37866d325..a35d21d55 100644 --- a/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -34,6 +34,7 @@ using System.Windows.Forms; using System.Threading.Tasks; using Opc.Ua.Security.Certificates; +using System.Threading; namespace Opc.Ua.Client.Controls { @@ -62,7 +63,7 @@ public ViewCertificateDlg() /// /// Displays the dialog. /// - public async Task ShowDialog(CertificateIdentifier certificate) + public async Task ShowDialogAsync(CertificateIdentifier certificate, CancellationToken ct = default) { m_certificate = certificate; @@ -86,7 +87,7 @@ public async Task ShowDialog(CertificateIdentifier certificate) SubjectNameTB.Text = certificate.SubjectName; ThumbprintTB.Text = certificate.Thumbprint; - X509Certificate2 data = await certificate.Find(); + X509Certificate2 data = await certificate.FindAsync(ct: ct); if (data != null) { @@ -191,11 +192,11 @@ private void OkBTN_Click(object sender, EventArgs e) } } - private async void DetailsBTN_Click(object sender, EventArgs e) + private async void DetailsBTN_ClickAsync(object sender, EventArgs e) { try { - await new CertificateDlg().ShowDialog(m_certificate); + await new CertificateDlg().ShowDialogAsync(m_certificate); } catch (Exception exception) { @@ -203,7 +204,7 @@ private async void DetailsBTN_Click(object sender, EventArgs e) } } - private async void ExportBTN_Click(object sender, EventArgs e) + private async void ExportBTN_ClickAsync(object sender, EventArgs e) { try { @@ -219,7 +220,7 @@ private async void ExportBTN_Click(object sender, EventArgs e) m_currentDirectory = Environment.CurrentDirectory; } - X509Certificate2 certificate = await m_certificate.Find(); + X509Certificate2 certificate = await m_certificate.FindAsync(); if (certificate == null) { @@ -243,10 +244,10 @@ private async void ExportBTN_Click(object sender, EventArgs e) if (!String.IsNullOrEmpty(displayName)) { filePath.Append(displayName); - filePath.Append(" "); + filePath.Append(' '); } - filePath.Append("["); + filePath.Append('['); filePath.Append(certificate.Thumbprint); filePath.Append("].der"); diff --git a/Samples/ClientControls.Net4/Configuration/YesNoDlg.cs b/Samples/ClientControls.Net4/Configuration/YesNoDlg.cs index 5a25c7cf5..f92cc7cb3 100644 --- a/Samples/ClientControls.Net4/Configuration/YesNoDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/YesNoDlg.cs @@ -51,7 +51,7 @@ public YesNoDlg() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } - + /// /// Displays the dialog. /// diff --git a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerDlg.cs b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerDlg.cs index ee6a90ca1..66e0ad64a 100644 --- a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerDlg.cs +++ b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,7 @@ using System.Threading; using System.Security.Cryptography.X509Certificates; using Opc.Ua.Security.Certificates; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -112,7 +113,7 @@ private enum UseDefaultLimits /// Initialize it with the number of status channels and update "StatusChannel" accordingly. /// Provides a general view of all the statuses (joined texts, worst status). /// - private class StatusObject + private sealed class StatusObject { public StatusObject(int maxChannels) { @@ -201,7 +202,7 @@ public void ClearStatus(StatusChannel channel) /// Also prepares a user-friendly text representation of all the endpoint-rellevant characteristics. /// The extracted EndpointDescription properties are used in selecting the right combo-box values when user clicks in the endpoint list box. /// - private class EndpointDescriptionString + private sealed class EndpointDescriptionString { public EndpointDescriptionString(EndpointDescription endpointDescription) { @@ -348,7 +349,7 @@ public int DiscoveryTimeout /// public ConfiguredEndpoint ShowDialog(ApplicationDescription server, ApplicationConfiguration configuration) { - if (server == null) throw new ArgumentNullException("server"); + if (server == null) throw new ArgumentNullException(nameof(server)); m_configuration = configuration; @@ -368,7 +369,7 @@ public ConfiguredEndpoint ShowDialog(ApplicationDescription server, ApplicationC // discover endpoints in the background. m_discoverySucceeded = false; Interlocked.Increment(ref m_discoverCount); - ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverEndpoints), server); + Task.Run(() => OnDiscoverEndpointsAsync(server)); if (ShowDialog() != DialogResult.OK) { @@ -383,7 +384,7 @@ public ConfiguredEndpoint ShowDialog(ApplicationDescription server, ApplicationC /// public ConfiguredEndpoint ShowDialog(ConfiguredEndpoint endpoint, ApplicationConfiguration configuration) { - if (endpoint == null) throw new ArgumentNullException("endpoint"); + if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); m_endpoint = endpoint; m_configuration = configuration; @@ -452,7 +453,7 @@ public ConfiguredEndpoint ShowDialog(ConfiguredEndpoint endpoint, ApplicationCon // discover endpoints in the background. Interlocked.Increment(ref m_discoverCount); - ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverEndpoints), m_endpoint.Description.Server); + Task.Run(() => OnDiscoverEndpointsAsync(m_endpoint.Description.Server)); if (ShowDialog() != DialogResult.OK) { @@ -555,7 +556,7 @@ private EndpointDescription FindBestEndpointDescription(EndpointDescriptionColle // filter by the current security policy. string currentPolicy = (string)SecurityPolicyCB.SelectedItem; - // find all matching descriptions. + // find all matching descriptions. EndpointDescriptionCollection matches = new EndpointDescriptionCollection(); if (endpoints != null) @@ -614,7 +615,7 @@ private EndpointDescription FindBestEndpointDescription(EndpointDescriptionColle return bestMatch; } - private class Protocol + private sealed class Protocol { public Uri Url; public string Profile; @@ -683,7 +684,7 @@ public override string ToString() if (!String.IsNullOrEmpty(Profile)) { - builder.Append(" "); + builder.Append(' '); builder.Append(Profile); } @@ -692,11 +693,11 @@ public override string ToString() if (Url.Port != -1) { - builder.Append(":"); + builder.Append(':'); builder.Append(Url.Port); } - builder.Append("]"); + builder.Append(']'); return builder.ToString(); } @@ -869,14 +870,10 @@ private void InitializeSecurityPolicies(EndpointDescriptionCollection endpoints) // set all available security policies. if (m_showAllOptions) { - var securityPolicies = SecurityPolicies.GetDisplayNames(); - foreach (var policy in securityPolicies) - { - SecurityPolicyCB.Items.Add(policy); - } + SecurityPolicyCB.Items.AddRange(SecurityPolicies.GetDisplayNames()); } - // find all unique security policies. + // find all unique security policies. else { if (endpoints != null) @@ -1015,7 +1012,7 @@ private void InitializeEncodings(EndpointDescriptionCollection endpoints, Endpoi EncodingCB.SelectedIndex = index; } - private class UserTokenItem + private sealed class UserTokenItem { public UserTokenPolicy Policy; @@ -1084,22 +1081,20 @@ private void SelectCorrespondingEndpointFromList(EndpointDescription endpoint) /// /// Attempts fetch the list of servers from the discovery server. /// - private void OnDiscoverEndpoints(object state) + private async Task OnDiscoverEndpointsAsync(ApplicationDescription server, CancellationToken ct = default) { int discoverCount = m_discoverCount; // do nothing if a valid list is not provided. - ApplicationDescription server = state as ApplicationDescription; - if (server == null) { return; - } OnUpdateStatus(new Tuple("Attempting to read latest configuration options from server.", StatusType.Ok)); String discoveryMessage = String.Empty; + bool success; // process each url. foreach (string discoveryUrl in server.DiscoveryUrls) @@ -1108,7 +1103,8 @@ private void OnDiscoverEndpoints(object state) if (url != null) { - if (DiscoverEndpoints(url, out discoveryMessage)) + (success, discoveryMessage) = await DiscoverEndpointsAsync(url, ct); + if (success) { m_discoverySucceeded = true; m_discoveryUrl = url; @@ -1131,7 +1127,7 @@ private void OnDiscoverEndpoints(object state) /// /// Fetches the servers from the discovery server. /// - private bool DiscoverEndpoints(Uri discoveryUrl, out String message) + private async Task<(bool Success, string Message)> DiscoverEndpointsAsync(Uri discoveryUrl, CancellationToken ct = default) { // use a short timeout. EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); @@ -1144,20 +1140,18 @@ private bool DiscoverEndpoints(Uri discoveryUrl, out String message) try { - EndpointDescriptionCollection endpoints = client.GetEndpoints(null); + EndpointDescriptionCollection endpoints = await client.GetEndpointsAsync(null, ct); OnUpdateEndpoints(endpoints); - message = String.Empty; - return true; + return (true, String.Empty); } catch (Exception e) { Utils.Trace("Could not fetch endpoints from url: {0}. Reason={1}", discoveryUrl, e.Message); - message = e.Message; - return false; + return (false, e.Message); } finally { - client.Close(); + await client.CloseAsync(ct); } } @@ -1396,7 +1390,7 @@ private void OkBTN_Click(object sender, EventArgs e) // the discovery endpoint should always be on the same machine as the server. // if there is a mismatch it is likely because the server has multiple addresses // and was not configured to return the current address to the client. - // The code automatically updates the domain in the url. + // The code automatically updates the domain in the url. Uri endpointUrl = Utils.ParseUri(m_currentDescription.EndpointUrl); if (m_discoverySucceeded) @@ -1515,7 +1509,7 @@ private void SecurityModeCB_SelectedIndexChanged(object sender, EventArgs e) if (SecurityModeCB.SelectedItem != null) { if ((((MessageSecurityMode)SecurityModeCB.SelectedItem) == MessageSecurityMode.None) && - (ProtocolCB.SelectedItem != null) && (((Protocol)ProtocolCB.SelectedItem).ToString().IndexOf("https") != 0)) + (ProtocolCB.SelectedItem != null) && (!((Protocol)ProtocolCB.SelectedItem).ToString().StartsWith("https"))) { m_statusObject.SetStatus(StatusChannel.SelectedSecurityMode, "Warning: Selected Endpoint has no security.", StatusType.Warning); } diff --git a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.Designer.cs b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.Designer.cs index 5c350d3a5..70df1d81f 100644 --- a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.Designer.cs +++ b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.Designer.cs @@ -90,7 +90,7 @@ private void InitializeComponent() this.ConfigureMI.Name = "ConfigureMI"; this.ConfigureMI.Size = new System.Drawing.Size(152, 22); this.ConfigureMI.Text = "Configure..."; - this.ConfigureMI.Click += new System.EventHandler(this.ConfigureMI_Click); + this.ConfigureMI.Click += new System.EventHandler(this.ConfigureMI_ClickAsync); // // DeleteMI // diff --git a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.cs b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.cs index 5e8891c67..0c1579cdf 100644 --- a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.cs +++ b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,7 @@ using System.Reflection; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; namespace Opc.Ua.Client.Controls { @@ -56,18 +57,18 @@ public ConfiguredServerListCtrl() SetColumns(m_ColumnNames); } #endregion - + #region Private Fields - // The columns to display in the control. - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "Host", HorizontalAlignment.Left, null }, - new object[] { "Protocol", HorizontalAlignment.Left, null }, - new object[] { "Security Mode", HorizontalAlignment.Left, null }, - new object[] { "User Token", HorizontalAlignment.Left, null } - }; - + // The columns to display in the control. + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "Host", HorizontalAlignment.Left, null }, + new object[] { "Protocol", HorizontalAlignment.Left, null }, + new object[] { "Security Mode", HorizontalAlignment.Left, null }, + new object[] { "User Token", HorizontalAlignment.Left, null } + }; + private ApplicationConfiguration m_configuration; private ConfiguredEndpointCollection m_endpoints; #endregion @@ -105,7 +106,7 @@ protected override void EnableMenuItems(ListViewItem clickedItem) base.EnableMenuItems(clickedItem); NewMI.Enabled = true; - + if (clickedItem != null) { ConfiguredEndpoint endpoint = clickedItem.Tag as ConfiguredEndpoint; @@ -123,13 +124,13 @@ protected override void EnableMenuItems(ListViewItem clickedItem) /// /// Updates an item in the control. /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { ConfiguredEndpoint endpoint = listItem.Tag as ConfiguredEndpoint; if (endpoint == null) { - base.UpdateItem(listItem, endpoint); + await base.UpdateItemAsync(listItem, endpoint, ct); return; } @@ -137,23 +138,23 @@ protected override void UpdateItem(ListViewItem listItem, object item) string protocol = ""; Uri uri = endpoint.EndpointUrl; - + if (uri != null) { - hostname = uri.DnsSafeHost; + hostname = uri.DnsSafeHost; protocol = uri.Scheme; } - listItem.SubItems[0].Text = String.Format("{0}", endpoint.Description.Server.ApplicationName); - listItem.SubItems[1].Text = String.Format("{0}", hostname); - listItem.SubItems[2].Text = String.Format("{0}", protocol); + listItem.SubItems[0].Text = String.Format("{0}", endpoint.Description.Server.ApplicationName); + listItem.SubItems[1].Text = String.Format("{0}", hostname); + listItem.SubItems[2].Text = String.Format("{0}", protocol); - listItem.SubItems[3].Text = String.Format( - "{0}/{1}", + listItem.SubItems[3].Text = String.Format( + "{0}/{1}", SecurityPolicies.GetDisplayName(endpoint.Description.SecurityPolicyUri), endpoint.Description.SecurityMode); - - listItem.SubItems[4].Text = ""; + + listItem.SubItems[4].Text = ""; UserTokenPolicy policy = endpoint.SelectedUserTokenPolicy; @@ -165,17 +166,17 @@ protected override void UpdateItem(ListViewItem listItem, object item) if (endpoint.UserIdentity != null) { - buffer.Append("/"); + buffer.Append('/'); buffer.Append(endpoint.UserIdentity); } - listItem.SubItems[4].Text = buffer.ToString(); + listItem.SubItems[4].Text = buffer.ToString(); } listItem.ImageKey = GuiUtils.Icons.Process; } #endregion - + #region Event Handlers private void NewMI_Click(object sender, EventArgs e) { @@ -204,12 +205,12 @@ private void NewMI_Click(object sender, EventArgs e) } } - private void ConfigureMI_Click(object sender, EventArgs e) + private async void ConfigureMI_ClickAsync(object sender, EventArgs e) { try { ConfiguredEndpoint endpoint = SelectedTag as ConfiguredEndpoint; - + if (endpoint == null) { return; @@ -221,8 +222,8 @@ private void ConfigureMI_Click(object sender, EventArgs e) { return; } - - UpdateItem(ItemsLV.SelectedItems[0], endpoint); + + await UpdateItemAsync(ItemsLV.SelectedItems[0], endpoint); AdjustColumns(); } catch (Exception exception) @@ -236,7 +237,7 @@ private void DeleteMI_Click(object sender, EventArgs e) try { ConfiguredEndpoint endpoint = SelectedTag as ConfiguredEndpoint; - + if (endpoint == null) { return; diff --git a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListDlg.cs b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListDlg.cs index a6da13d3f..7515ea71a 100644 --- a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListDlg.cs +++ b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListDlg.cs @@ -53,12 +53,12 @@ public ConfiguredServerListDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields private ConfiguredEndpoint m_endpoint; private ApplicationConfiguration m_configuration; #endregion - + #region Public Interface /// /// Displays the dialog. @@ -80,20 +80,20 @@ public ConfiguredEndpoint ShowDialog(ApplicationConfiguration configuration, boo return null; } - + ServersCTRL.Initialize(null, configuration); - + OkBTN.Enabled = false; if (ShowDialog() != DialogResult.OK) { return null; } - + return m_endpoint; } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Samples/ClientControls.Net4/Endpoints/EndpointSelectorCtrl.cs b/Samples/ClientControls.Net4/Endpoints/EndpointSelectorCtrl.cs index 8a247b9d6..c27b82fd9 100644 --- a/Samples/ClientControls.Net4/Endpoints/EndpointSelectorCtrl.cs +++ b/Samples/ClientControls.Net4/Endpoints/EndpointSelectorCtrl.cs @@ -63,14 +63,14 @@ public EndpointSelectorCtrl() private event ConnectEndpointEventHandler m_ConnectEndpoint; private event EventHandler m_EndpointsChanged; #endregion - + #region Public Interface /// /// Raised when the user presses the connect button. /// public event ConnectEndpointEventHandler ConnectEndpoint { - add { m_ConnectEndpoint += value; } + add { m_ConnectEndpoint += value; } remove { m_ConnectEndpoint -= value; } } @@ -79,7 +79,7 @@ public event ConnectEndpointEventHandler ConnectEndpoint /// public event EventHandler EndpointsChanged { - add { m_EndpointsChanged += value; } + add { m_EndpointsChanged += value; } remove { m_EndpointsChanged -= value; } } @@ -93,15 +93,15 @@ public ConfiguredEndpoint SelectedEndpoint ConfiguredEndpoint item = EndpointCB.SelectedItem as ConfiguredEndpoint; if (item != null) - { + { return item; } if (String.IsNullOrEmpty(EndpointCB.Text)) - { + { return null; - } - + } + return m_endpoints.Create(EndpointCB.Text); } @@ -143,7 +143,7 @@ public ConfiguredEndpoint SelectedEndpoint /// public void Initialize(ConfiguredEndpointCollection endpoints, ApplicationConfiguration configuration) { - if (endpoints == null) throw new ArgumentNullException("endpoints"); + if (endpoints == null) throw new ArgumentNullException(nameof(endpoints)); m_endpoints = endpoints; m_configuration = configuration; @@ -194,18 +194,18 @@ private void ConnectButton_Click(object sender, EventArgs e) Initialize(m_endpoints, m_configuration); SelectedEndpoint = endpoint; } - } + } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void EndpointCB_SelectedIndexChanged(object sender, EventArgs e) { try - { + { if (EndpointCB.SelectedIndex != 0) { m_selectedIndex = EndpointCB.SelectedIndex; @@ -214,7 +214,7 @@ private void EndpointCB_SelectedIndexChanged(object sender, EventArgs e) // modify configuration. ConfiguredEndpoint endpoint = new ConfiguredServerListDlg().ShowDialog(m_configuration, true); - + if (endpoint == null) { EndpointCB.SelectedIndex = m_selectedIndex; @@ -236,20 +236,20 @@ private void EndpointCB_SelectedIndexChanged(object sender, EventArgs e) for (int ii = 0; ii < m_endpoints.Endpoints.Count; ii++) { if (Object.ReferenceEquals(endpoint, m_endpoints.Endpoints[ii])) - { - EndpointCB.SelectedIndex = ii+1; + { + EndpointCB.SelectedIndex = ii + 1; break; } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion } - + #region ConnectEndpointEventArgs Class /// /// Contains arguments for a ConnectEndpoint event. @@ -261,7 +261,7 @@ public class ConnectEndpointEventArgs : EventArgs /// public ConnectEndpointEventArgs(ConfiguredEndpoint endpoint, bool updateControl) { - m_endpoint = endpoint; + m_endpoint = endpoint; m_updateControl = updateControl; } @@ -278,10 +278,10 @@ public ConfiguredEndpoint Endpoint /// public bool UpdateControl { - get { return m_updateControl; } + get { return m_updateControl; } set { m_updateControl = value; } } - + #region Private Fields private ConfiguredEndpoint m_endpoint; private bool m_updateControl; @@ -291,6 +291,6 @@ public bool UpdateControl /// /// The delegate used to receive connect endpoint notifications. /// - public delegate void ConnectEndpointEventHandler(object sender, ConnectEndpointEventArgs e); + public delegate void ConnectEndpointEventHandler(object sender, ConnectEndpointEventArgs e); #endregion } diff --git a/Samples/ClientControls.Net4/Endpoints/UsernameTokenDlg.cs b/Samples/ClientControls.Net4/Endpoints/UsernameTokenDlg.cs index f630083bf..e7249103b 100644 --- a/Samples/ClientControls.Net4/Endpoints/UsernameTokenDlg.cs +++ b/Samples/ClientControls.Net4/Endpoints/UsernameTokenDlg.cs @@ -60,7 +60,7 @@ public UsernameTokenDlg() #region Private Fields #endregion - + #region Public Interface /// /// Displays the dialog. diff --git a/Samples/ClientControls.Net4/ExceptionDlg.cs b/Samples/ClientControls.Net4/ExceptionDlg.cs index fb0e416da..281c4ef56 100644 --- a/Samples/ClientControls.Net4/ExceptionDlg.cs +++ b/Samples/ClientControls.Net4/ExceptionDlg.cs @@ -91,7 +91,7 @@ private void AddBlock(StringBuilder buffer, string text, int level) } buffer.Append("color:#FFFFFF;font-weight:bold;font-size:10pt;font-family:Verdana'>"); - buffer.Append("

"); + buffer.Append("

"); } else { @@ -183,7 +183,7 @@ public static void Show(string caption, Exception e) Utils.Trace(e, "Unexpected error in '{0}'.", caption); return; } - + new ExceptionDlg().ShowDialog(caption, e); } @@ -198,12 +198,12 @@ public void ShowDialog(string caption, Exception e) } m_exception = e; - - #if _DEBUG + +#if _DEBUG ShowStackTracesCK.Checked = true; - #else +#else ShowStackTracesCK.Checked = false; - #endif +#endif Show(ShowStackTracesCK.Checked); ShowDialog(); diff --git a/Samples/ClientControls.Net4/MessageDlg.cs b/Samples/ClientControls.Net4/MessageDlg.cs index 1b967b7ea..7e8ef5738 100644 --- a/Samples/ClientControls.Net4/MessageDlg.cs +++ b/Samples/ClientControls.Net4/MessageDlg.cs @@ -1,8 +1,8 @@ -/* ======================================================================== +/* ======================================================================== * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -27,9 +27,10 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System.Threading; using System.Threading.Tasks; -using Opc.Ua.Configuration; using System.Windows.Forms; +using Opc.Ua.Configuration; namespace Opc.Ua.Client.Controls { @@ -52,10 +53,10 @@ public override void Message(string text, bool ask) } } - public override async Task ShowAsync() + public override Task ShowAsync() { DialogResult result = MessageBox.Show(message, "OPC UA", buttons); - return await Task.FromResult((result == DialogResult.OK) || (result == DialogResult.Yes)); + return Task.FromResult((result == DialogResult.OK) || (result == DialogResult.Yes)); } } } diff --git a/Samples/ClientControls.Net4/UA Client Controls.csproj b/Samples/ClientControls.Net4/UA Client Controls.csproj index 1e64f12a6..e087ea8ed 100644 --- a/Samples/ClientControls.Net4/UA Client Controls.csproj +++ b/Samples/ClientControls.Net4/UA Client Controls.csproj @@ -48,6 +48,7 @@ false + AllRules.ruleset pdbonly @@ -60,6 +61,7 @@ false + AllRules.ruleset @@ -1015,16 +1017,16 @@ - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview diff --git a/Samples/Controls.Net4/ClientForm.Designer.cs b/Samples/Controls.Net4/ClientForm.Designer.cs index 3fa5207bd..8fead5147 100644 --- a/Samples/Controls.Net4/ClientForm.Designer.cs +++ b/Samples/Controls.Net4/ClientForm.Designer.cs @@ -175,7 +175,7 @@ private void InitializeComponent() this.PerformanceTestMI.Name = "PerformanceTestMI"; this.PerformanceTestMI.Size = new System.Drawing.Size(154, 22); this.PerformanceTestMI.Text = "Stack Test..."; - this.PerformanceTestMI.Click += new System.EventHandler(this.PerformanceTestMI_Click); + this.PerformanceTestMI.Click += new System.EventHandler(this.PerformanceTestMI_ClickAsync); // // toolStripSeparator1 // @@ -333,7 +333,7 @@ private void InitializeComponent() this.EndpointSelectorCTRL.SelectedEndpoint = null; this.EndpointSelectorCTRL.Size = new System.Drawing.Size(553, 27); this.EndpointSelectorCTRL.TabIndex = 2; - this.EndpointSelectorCTRL.ConnectEndpoint += new Opc.Ua.Client.Controls.ConnectEndpointEventHandler(this.EndpointSelectorCTRL_ConnectEndpoint); + this.EndpointSelectorCTRL.ConnectEndpoint += new Opc.Ua.Client.Controls.ConnectEndpointEventHandler(this.EndpointSelectorCTRL_ConnectEndpointAsync); this.EndpointSelectorCTRL.EndpointsChanged += new System.EventHandler(this.EndpointSelectorCTRL_OnChange); // // serverHeaderBranding1 @@ -369,7 +369,7 @@ private void InitializeComponent() this.MainMenuStrip = this.MainMenu; this.Name = "ClientForm"; this.Text = "UA Sample Client"; - this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosingAsync); this.MainMenu.ResumeLayout(false); this.MainMenu.PerformLayout(); this.StatusStrip.ResumeLayout(false); diff --git a/Samples/Controls.Net4/ClientForm.cs b/Samples/Controls.Net4/ClientForm.cs index e13b334e1..4e652cb24 100644 --- a/Samples/Controls.Net4/ClientForm.cs +++ b/Samples/Controls.Net4/ClientForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,10 +33,13 @@ using System.Drawing; using System.IO; using System.Reflection; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua.Client; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; +using static System.Net.Mime.MediaTypeNames; namespace Opc.Ua.Sample.Controls { @@ -89,7 +92,7 @@ public ClientForm( EndpointSelectorCTRL.Initialize(m_endpoints, m_configuration); // initialize control state. - Disconnect(); + DisconnectAsync().GetAwaiter().GetResult(); } ///

@@ -130,7 +133,7 @@ void Window_FormClosing(object sender, FormClosingEventArgs e) /// /// Disconnect from the server if ths form is closing. /// - protected override void OnClosing(CancelEventArgs e) + protected override async void OnClosing(CancelEventArgs e) { if (m_masterForm == null && m_forms.Count > 0) { @@ -147,14 +150,20 @@ protected override void OnClosing(CancelEventArgs e) form.Close(); } } - - Disconnect(); + try + { + await DisconnectAsync(); + } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } } /// /// Disconnects from a server. /// - public void Disconnect() + public async Task DisconnectAsync(CancellationToken ct = default) { if (m_session != null) { @@ -167,7 +176,7 @@ public void Disconnect() m_session.KeepAlive -= StandardClient_KeepAlive; - m_session.Close(); + await m_session.CloseAsync(ct); m_session = null; } @@ -182,11 +191,11 @@ protected virtual void DoTest(Session session) MessageBox.Show("A handy place to put test code."); } - void EndpointSelectorCTRL_ConnectEndpoint(object sender, ConnectEndpointEventArgs e) + private async void EndpointSelectorCTRL_ConnectEndpointAsync(object sender, ConnectEndpointEventArgs e) { try { - Connect(e.Endpoint); + await ConnectAsync(e.Endpoint); } catch (Exception exception) { @@ -201,7 +210,7 @@ private void EndpointSelectorCTRL_OnChange(object sender, EventArgs e) { m_endpoints.Save(); } - catch (Exception) + catch { // GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } @@ -210,14 +219,14 @@ private void EndpointSelectorCTRL_OnChange(object sender, EventArgs e) /// /// Connects to a server. /// - public async void Connect(ConfiguredEndpoint endpoint) + public async Task ConnectAsync(ConfiguredEndpoint endpoint, CancellationToken ct = default) { if (endpoint == null) { return; } - Session session = await SessionsCTRL.Connect(endpoint); + Session session = await SessionsCTRL.ConnectAsync(endpoint, ct); if (session != null) { @@ -230,7 +239,7 @@ public async void Connect(ConfiguredEndpoint endpoint) m_session = session; m_session.KeepAlive += new KeepAliveEventHandler(StandardClient_KeepAlive); - BrowseCTRL.SetView(m_session, BrowseViewType.Objects, null); + await BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, ct); StandardClient_KeepAlive(m_session, null); } } @@ -327,7 +336,7 @@ private void StandardClient_Server_ReconnectComplete(object sender, EventArgs e) } } - BrowseCTRL.SetView(m_session, BrowseViewType.Objects, null); + BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null); SessionsCTRL.Reload(m_session); @@ -339,11 +348,11 @@ private void StandardClient_Server_ReconnectComplete(object sender, EventArgs e) } } - private void MainForm_FormClosing(object sender, FormClosingEventArgs e) + private async void MainForm_FormClosingAsync(object sender, FormClosingEventArgs e) { try { - SessionsCTRL.Close(); + await SessionsCTRL.CloseAsync(); if (m_masterForm == null) { @@ -361,14 +370,14 @@ private void FileExit_Click(object sender, EventArgs e) this.Close(); } - private async void PerformanceTestMI_Click(object sender, EventArgs e) + private async void PerformanceTestMI_ClickAsync(object sender, EventArgs e) { try { - new PerformanceTestDlg().ShowDialog( + _ = new PerformanceTestDlg().ShowDialog( m_configuration, m_endpoints, - await m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true)); + await m_configuration.SecurityConfiguration.ApplicationCertificate.FindAsync(true)); } catch (Exception exception) { @@ -480,7 +489,7 @@ private void contentsToolStripMenuItem_Click(object sender, EventArgs e) { try { - System.Diagnostics.Process.Start(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "WebHelp" + Path.DirectorySeparatorChar + "index.htm"); + System.Diagnostics.Process.Start(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + Path.DirectorySeparatorChar + "WebHelp" + Path.DirectorySeparatorChar + "index.htm"); } catch (Exception ex) { diff --git a/Samples/Controls.Net4/Common/ArgumentListCtrl.Designer.cs b/Samples/Controls.Net4/Common/ArgumentListCtrl.Designer.cs index c458ce66e..07ba7f3ca 100644 --- a/Samples/Controls.Net4/Common/ArgumentListCtrl.Designer.cs +++ b/Samples/Controls.Net4/Common/ArgumentListCtrl.Designer.cs @@ -81,14 +81,14 @@ private void InitializeComponent() this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(152, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // ClearValueMI // this.ClearValueMI.Name = "ClearValueMI"; this.ClearValueMI.Size = new System.Drawing.Size(152, 22); this.ClearValueMI.Text = "Clear Value"; - this.ClearValueMI.Click += new System.EventHandler(this.ClearValueMI_Click); + this.ClearValueMI.Click += new System.EventHandler(this.ClearValueMI_ClickAsync); // // ArgumentListCtrl // diff --git a/Samples/Controls.Net4/Common/ArgumentListCtrl.cs b/Samples/Controls.Net4/Common/ArgumentListCtrl.cs index b084f25a0..4923e5dda 100644 --- a/Samples/Controls.Net4/Common/ArgumentListCtrl.cs +++ b/Samples/Controls.Net4/Common/ArgumentListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -45,8 +46,8 @@ public partial class ArgumentListCtrl : Opc.Ua.Client.Controls.BaseListCtrl { public ArgumentListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -56,13 +57,13 @@ public ArgumentListCtrl() /// The columns to display in the control. /// private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "DataType", HorizontalAlignment.Left, null }, - new object[] { "Value", HorizontalAlignment.Left, null }, - new object[] { "Description", HorizontalAlignment.Left, null }, - }; - #endregion + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "DataType", HorizontalAlignment.Left, null }, + new object[] { "Value", HorizontalAlignment.Left, null }, + new object[] { "Description", HorizontalAlignment.Left, null }, + }; + #endregion #region Public Interface /// @@ -77,17 +78,17 @@ public void Clear() /// /// Sets the nodes in the control. /// - public bool Update(Session session, NodeId methodId, bool inputArgs) + public async Task UpdateAsync(Session session, NodeId methodId, bool inputArgs, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - if (methodId == null) throw new ArgumentNullException("methodId"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + if (methodId == null) throw new ArgumentNullException(nameof(methodId)); + Clear(); - + m_session = session; // find the method. - MethodNode method = session.NodeCache.Find(methodId) as MethodNode; + MethodNode method = await session.NodeCache.FindAsync(methodId, ct) as MethodNode; if (method == null) { @@ -96,7 +97,7 @@ public bool Update(Session session, NodeId methodId, bool inputArgs) // select the property to find. QualifiedName browseName = null; - + if (inputArgs) { browseName = Opc.Ua.BrowseNames.InputArguments; @@ -107,7 +108,7 @@ public bool Update(Session session, NodeId methodId, bool inputArgs) } // fetch the argument list. - VariableNode argumentsNode = session.NodeCache.Find(methodId, ReferenceTypeIds.HasProperty, false, true, browseName) as VariableNode; + VariableNode argumentsNode = await session.NodeCache.FindAsync(methodId, ReferenceTypeIds.HasProperty, false, true, browseName, ct) as VariableNode; if (argumentsNode == null) { @@ -115,7 +116,7 @@ public bool Update(Session session, NodeId methodId, bool inputArgs) } // read the value from the server. - DataValue value = m_session.ReadValue(argumentsNode.NodeId); + DataValue value = await m_session.ReadValueAsync(argumentsNode.NodeId, ct); ExtensionObject[] argumentsList = value.Value as ExtensionObject[]; @@ -130,7 +131,7 @@ public bool Update(Session session, NodeId methodId, bool inputArgs) AdjustColumns(); return ItemsLV.Items.Count > 0; - } + } /// /// Returns the argument values @@ -155,7 +156,7 @@ public VariantCollection GetValues() /// /// Updates the argument values. /// - public void SetValues(VariantCollection values) + public async Task SetValuesAsync(VariantCollection values, CancellationToken ct = default) { int ii = 0; @@ -166,88 +167,95 @@ public void SetValues(VariantCollection values) if (argument != null) { argument.Value = values[ii++].Value; - UpdateItem(item, argument); + await UpdateItemAsync(item, argument, ct); } } AdjustColumns(); } - #endregion - + #endregion + #region Overridden Methods /// protected override void PickItems() { base.PickItems(); - EditMI_Click(this, null); + EditMI_ClickAsync(this, null); } /// protected override void EnableMenuItems(ListViewItem clickedItem) - { - EditMI.Enabled = ItemsLV.SelectedItems.Count == 1; - ClearValueMI.Enabled = EditMI.Enabled; - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item) { - Argument argument = item as Argument; + EditMI.Enabled = ItemsLV.SelectedItems.Count == 1; + ClearValueMI.Enabled = EditMI.Enabled; + } - if (argument == null) - { - base.UpdateItem(listItem, item); - return; - } + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) + { + try + { + Argument argument = item as Argument; - listItem.SubItems[0].Text = String.Format("{0}", argument.Name); + if (argument == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } - INode datatype = m_session.NodeCache.Find(argument.DataType); + listItem.SubItems[0].Text = String.Format("{0}", argument.Name); - if (datatype != null) - { - listItem.SubItems[1].Text = String.Format("{0}", datatype); - } - else - { - listItem.SubItems[1].Text = String.Format("{0}", argument.DataType); - } + INode datatype = await m_session.NodeCache.FindAsync(argument.DataType, ct); - if (argument.ValueRank >= ValueRanks.OneOrMoreDimensions) - { - listItem.SubItems[1].Text += "[]"; - } + if (datatype != null) + { + listItem.SubItems[1].Text = String.Format("{0}", datatype); + } + else + { + listItem.SubItems[1].Text = String.Format("{0}", argument.DataType); + } - if (argument.Value == null) - { - argument.Value = TypeInfo.GetDefaultValue(argument.DataType, argument.ValueRank, m_session.TypeTree); + if (argument.ValueRank >= ValueRanks.OneOrMoreDimensions) + { + listItem.SubItems[1].Text += "[]"; + } if (argument.Value == null) { - Type type = m_session.MessageContext.Factory.GetSystemType(argument.DataType); + argument.Value = TypeInfo.GetDefaultValue(argument.DataType, argument.ValueRank, m_session.TypeTree); - if (type != null) + if (argument.Value == null) { - if (argument.ValueRank == ValueRanks.Scalar) - { - argument.Value = new ExtensionObject(Activator.CreateInstance(type)); - } - else + Type type = m_session.MessageContext.Factory.GetSystemType(argument.DataType); + + if (type != null) { - argument.Value = new ExtensionObject[0]; + if (argument.ValueRank == ValueRanks.Scalar) + { + argument.Value = new ExtensionObject(Activator.CreateInstance(type)); + } + else + { + argument.Value = Array.Empty(); + } } } } - } - listItem.SubItems[2].Text = String.Format("{0}", argument.Value); - listItem.SubItems[3].Text = String.Format("{0}", argument.Description.Text); + listItem.SubItems[2].Text = String.Format("{0}", argument.Value); + listItem.SubItems[3].Text = String.Format("{0}", argument.Description.Text); - listItem.Tag = item; + listItem.Tag = item; + } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } } #endregion - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -265,15 +273,15 @@ private void EditMI_Click(object sender, EventArgs e) arguments[0].Value = value; } - UpdateItem(ItemsLV.SelectedItems[0], arguments[0]); + await UpdateItemAsync(ItemsLV.SelectedItems[0], arguments[0]); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void ClearValueMI_Click(object sender, EventArgs e) + private async void ClearValueMI_ClickAsync(object sender, EventArgs e) { try { @@ -286,11 +294,11 @@ private void ClearValueMI_Click(object sender, EventArgs e) arguments[0].Value = null; - UpdateItem(ItemsLV.SelectedItems[0], arguments[0]); + await UpdateItemAsync(ItemsLV.SelectedItems[0], arguments[0]); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/AttributeListCtrl.Designer.cs b/Samples/Controls.Net4/Common/AttributeListCtrl.Designer.cs index 81e7e06cc..d9ecacea7 100644 --- a/Samples/Controls.Net4/Common/AttributeListCtrl.Designer.cs +++ b/Samples/Controls.Net4/Common/AttributeListCtrl.Designer.cs @@ -83,7 +83,7 @@ private void InitializeComponent() this.ViewMI.Name = "ViewMI"; this.ViewMI.Size = new System.Drawing.Size(152, 22); this.ViewMI.Text = "View..."; - this.ViewMI.Click += new System.EventHandler(this.EditMI_Click); + this.ViewMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // Separator01 // diff --git a/Samples/Controls.Net4/Common/AttributeListCtrl.cs b/Samples/Controls.Net4/Common/AttributeListCtrl.cs index b2cc39400..5315e9dcb 100644 --- a/Samples/Controls.Net4/Common/AttributeListCtrl.cs +++ b/Samples/Controls.Net4/Common/AttributeListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,12 +32,13 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -45,8 +46,8 @@ public partial class AttributeListCtrl : Opc.Ua.Client.Controls.BaseListCtrl { public AttributeListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -58,20 +59,20 @@ public AttributeListCtrl() /// The columns to display in the control. /// private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Field", HorizontalAlignment.Left, null }, - new object[] { "Value", HorizontalAlignment.Left, null }, - new object[] { "Status", HorizontalAlignment.Left, "Good" } - }; - #endregion + { + new object[] { "Field", HorizontalAlignment.Left, null }, + new object[] { "Value", HorizontalAlignment.Left, null }, + new object[] { "Status", HorizontalAlignment.Left, "Good" } + }; + #endregion #region Public Interface /// - /// + /// /// public bool ReadOnly { - get { return m_readOnly; } + get { return m_readOnly; } set { m_readOnly = value; } } @@ -87,81 +88,80 @@ public void Clear() /// /// Sets the nodes in the control. /// - public void Initialize(Session session, ExpandedNodeId nodeId) + public async Task InitializeAsync(Session session, ExpandedNodeId nodeId, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); if (nodeId == null) { - return; + return; } - + m_session = session; - m_nodeId = (NodeId)nodeId; + m_nodeId = (NodeId)nodeId; - INode node = m_session.NodeCache.Find(m_nodeId); + INode node = await m_session.NodeCache.FindAsync(m_nodeId, ct); if (node != null && (node.NodeClass & (NodeClass.Variable | NodeClass.Object)) != 0) { - AddReferences(ReferenceTypeIds.HasTypeDefinition, BrowseDirection.Forward); - AddReferences(ReferenceTypeIds.HasModellingRule, BrowseDirection.Forward); + await AddReferencesAsync(ReferenceTypeIds.HasTypeDefinition, BrowseDirection.Forward, ct); + await AddReferencesAsync(ReferenceTypeIds.HasModellingRule, BrowseDirection.Forward, ct); } - AddAttributes(); - AddProperties(); + await AddAttributesAsync(ct); + await AddPropertiesAsync(ct); AdjustColumns(); } - #endregion - + #endregion + #region NodeField Class /// /// A field associated with a node. /// - private class NodeField - { - public string Name; - public object Value; - public StatusCode StatusCode; + private sealed class NodeField + { + public string Name; + public object Value; + public StatusCode StatusCode; public DiagnosticInfo DiagnosticInfo; - public ReadValueId ValueId; + public ReadValueId ValueId; } - #endregion + #endregion #region Private Methods /// /// Adds the attributes to the control. /// - private void AddAttributes() + private async Task AddAttributesAsync(CancellationToken ct = default) { // build list of attributes to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); - foreach (uint attributeId in Attributes.GetIdentifiers()) + foreach (uint attributeId in Attributes.Identifiers) { ReadValueId valueId = new ReadValueId(); - valueId.NodeId = m_nodeId; - valueId.AttributeId = attributeId; - valueId.IndexRange = null; + valueId.NodeId = m_nodeId; + valueId.AttributeId = attributeId; + valueId.IndexRange = null; valueId.DataEncoding = null; nodesToRead.Add(valueId); } // read attributes. - DataValueCollection values; - DiagnosticInfoCollection diagnosticInfos; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out values, - out diagnosticInfos); + ct); + + DataValueCollection values = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(values, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -177,10 +177,10 @@ private void AddAttributes() NodeField field = new NodeField(); - field.ValueId = nodesToRead[ii]; - field.Name = Attributes.GetBrowseName(nodesToRead[ii].AttributeId); - field.Value = values[ii].Value; - field.StatusCode = values[ii].StatusCode; + field.ValueId = nodesToRead[ii]; + field.Name = Attributes.GetBrowseName(nodesToRead[ii].AttributeId); + field.Value = values[ii].Value; + field.StatusCode = values[ii].StatusCode; if (diagnosticInfos != null && diagnosticInfos.Count > ii) { @@ -190,32 +190,32 @@ private void AddAttributes() AddItem(field, "SimpleItem", -1); } } - + /// /// Adds the properties to the control. /// - private void AddProperties() + private async Task AddPropertiesAsync(CancellationToken ct = default) { // build list of properties to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); Browser browser = new Browser(m_session); - - browser.BrowseDirection = BrowseDirection.Forward; - browser.ReferenceTypeId = ReferenceTypeIds.HasProperty; - browser.IncludeSubtypes = true; - browser.NodeClassMask = (int)NodeClass.Variable; + + browser.BrowseDirection = BrowseDirection.Forward; + browser.ReferenceTypeId = ReferenceTypeIds.HasProperty; + browser.IncludeSubtypes = true; + browser.NodeClassMask = (int)NodeClass.Variable; browser.ContinueUntilDone = true; - ReferenceDescriptionCollection references = browser.Browse(m_nodeId); + ReferenceDescriptionCollection references = await browser.BrowseAsync(m_nodeId, ct); foreach (ReferenceDescription reference in references) { ReadValueId valueId = new ReadValueId(); - valueId.NodeId = (NodeId)reference.NodeId; - valueId.AttributeId = Attributes.Value; - valueId.IndexRange = null; + valueId.NodeId = (NodeId)reference.NodeId; + valueId.AttributeId = Attributes.Value; + valueId.IndexRange = null; valueId.DataEncoding = null; nodesToRead.Add(valueId); @@ -228,28 +228,27 @@ private void AddProperties() } // read values. - DataValueCollection values; - DiagnosticInfoCollection diagnosticInfos; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out values, - out diagnosticInfos); + ct); + + DataValueCollection values = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(values, nodesToRead); - ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); + ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); // update control. for (int ii = 0; ii < nodesToRead.Count; ii++) { NodeField field = new NodeField(); - field.ValueId = nodesToRead[ii]; - field.Name = references[ii].ToString(); - field.Value = values[ii].Value; + field.ValueId = nodesToRead[ii]; + field.Name = references[ii].ToString(); + field.Value = values[ii].Value; field.StatusCode = values[ii].StatusCode; if (diagnosticInfos != null && diagnosticInfos.Count > ii) @@ -264,34 +263,34 @@ private void AddProperties() /// /// Adds the targets of references to the control. /// - private void AddReferences(NodeId referenceTypeId, BrowseDirection browseDirection) + private async Task AddReferencesAsync(NodeId referenceTypeId, BrowseDirection browseDirection, CancellationToken ct = default) { // fetch the attributes for the reference type. - INode referenceType = m_session.NodeCache.Find(referenceTypeId); + INode referenceType = await m_session.NodeCache.FindAsync(referenceTypeId, ct); if (referenceType == null) { return; } - + // browse for the references. Browser browser = new Browser(m_session); - - browser.BrowseDirection = browseDirection; - browser.ReferenceTypeId = referenceTypeId; - browser.IncludeSubtypes = true; - browser.NodeClassMask = 0; + + browser.BrowseDirection = browseDirection; + browser.ReferenceTypeId = referenceTypeId; + browser.IncludeSubtypes = true; + browser.NodeClassMask = 0; browser.ContinueUntilDone = true; - ReferenceDescriptionCollection references = browser.Browse(m_nodeId); + ReferenceDescriptionCollection references = await browser.BrowseAsync(m_nodeId, ct); // add results to list. foreach (ReferenceDescription reference in references) { NodeField field = new NodeField(); - field.Name = referenceType.ToString(); - field.Value = reference.ToString(); + field.Name = referenceType.ToString(); + field.Value = reference.ToString(); field.StatusCode = StatusCodes.Good; AddItem(field, "ReferenceType", -1); @@ -301,7 +300,7 @@ private void AddReferences(NodeId referenceTypeId, BrowseDirection browseDirecti /// /// Formats the value of an attribute. /// - private string FormatAttributeValue(uint attributeId, object value) + private async Task FormatAttributeValueAsync(uint attributeId, object value, CancellationToken ct = default) { switch (attributeId) { @@ -314,14 +313,14 @@ private string FormatAttributeValue(uint attributeId, object value) return "(null)"; } - + case Attributes.DataType: { NodeId datatypeId = value as NodeId; if (datatypeId != null) { - INode datatype = m_session.NodeCache.Find(datatypeId); + INode datatype = await m_session.NodeCache.FindAsync(datatypeId, ct); if (datatype != null) { @@ -332,10 +331,10 @@ private string FormatAttributeValue(uint attributeId, object value) return String.Format("{0}", datatypeId); } } - + return String.Format("{0}", value); } - + case Attributes.ValueRank: { int? valueRank = value as int?; @@ -344,21 +343,21 @@ private string FormatAttributeValue(uint attributeId, object value) { switch (valueRank.Value) { - case ValueRanks.Scalar: return "Scalar"; - case ValueRanks.OneDimension: return "OneDimension"; + case ValueRanks.Scalar: return "Scalar"; + case ValueRanks.OneDimension: return "OneDimension"; case ValueRanks.OneOrMoreDimensions: return "OneOrMoreDimensions"; - case ValueRanks.Any: return "Any"; + case ValueRanks.Any: return "Any"; default: { return String.Format("{0}", valueRank.Value); } - } + } } return String.Format("{0}", value); } - + case Attributes.MinimumSamplingInterval: { double? minimumSamplingInterval = value as double?; @@ -375,7 +374,7 @@ private string FormatAttributeValue(uint attributeId, object value) return "Continuous"; } - return String.Format("{0}", minimumSamplingInterval.Value); + return String.Format("{0}", minimumSamplingInterval.Value); } return String.Format("{0}", value); @@ -392,37 +391,37 @@ private string FormatAttributeValue(uint attributeId, object value) { bits.Append("Readable"); } - + if ((accessLevel & AccessLevels.CurrentWrite) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("Writeable"); } - + if ((accessLevel & AccessLevels.HistoryRead) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("History"); } - + if ((accessLevel & AccessLevels.HistoryWrite) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("History Update"); } - + if (bits.Length == 0) { bits.Append("No Access"); @@ -430,7 +429,7 @@ private string FormatAttributeValue(uint attributeId, object value) return String.Format("{0}", bits); } - + case Attributes.EventNotifier: { byte notifier = Convert.ToByte(value); @@ -441,27 +440,27 @@ private string FormatAttributeValue(uint attributeId, object value) { bits.Append("Subscribe"); } - + if ((notifier & EventNotifiers.HistoryRead) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("History"); } - + if ((notifier & EventNotifiers.HistoryWrite) != 0) { if (bits.Length > 0) { bits.Append(" | "); } - + bits.Append("History Update"); } - + if (bits.Length == 0) { bits.Append("No Access"); @@ -476,8 +475,8 @@ private string FormatAttributeValue(uint attributeId, object value) } } } - #endregion - + #endregion + #region Overridden Methods /// protected override object GetDataToDrag() @@ -501,42 +500,42 @@ protected override object GetDataToDrag() protected override void PickItems() { base.PickItems(); - EditMI_Click(this, null); + EditMI_ClickAsync(this, null); } /// protected override void EnableMenuItems(ListViewItem clickedItem) - { + { RefreshMI.Enabled = true; - + NodeField[] items = GetSelectedItems(typeof(NodeField)) as NodeField[]; if (items != null && items.Length > 0) { ViewMI.Enabled = items.Length == 1; } - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item) + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - NodeField field = item as NodeField; + NodeField field = item as NodeField; - if (field == null) - { - base.UpdateItem(listItem, item); - return; - } + if (field == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } Array array = field.Value as Array; - listItem.SubItems[0].Text = String.Format("{0}", field.Name); + listItem.SubItems[0].Text = String.Format("{0}", field.Name); if (array == null) { if (field.ValueId != null) { - listItem.SubItems[1].Text = FormatAttributeValue(field.ValueId.AttributeId, field.Value); + listItem.SubItems[1].Text = await FormatAttributeValueAsync(field.ValueId.AttributeId, field.Value, ct); } else { @@ -550,18 +549,18 @@ protected override void UpdateItem(ListViewItem listItem, object item) listItem.SubItems[2].Text = String.Format("{0}", field.StatusCode); - listItem.Tag = item; + listItem.Tag = item; } #endregion - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { NodeField[] items = GetSelectedItems(typeof(NodeField)) as NodeField[]; if (items != null && items.Length == 1) - { + { object value = GuiUtils.EditValue(m_session, items[0].Value); if (!m_readOnly) @@ -569,14 +568,14 @@ private void EditMI_Click(object sender, EventArgs e) if (value != null) { items[0].Value = value; - UpdateItem(ItemsLV.SelectedItems[0], items[0]); + await UpdateItemAsync(ItemsLV.SelectedItems[0], items[0]); } } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/BackgroundTaskDlg.cs b/Samples/Controls.Net4/Common/BackgroundTaskDlg.cs index 1fad72d19..cf597bc00 100644 --- a/Samples/Controls.Net4/Common/BackgroundTaskDlg.cs +++ b/Samples/Controls.Net4/Common/BackgroundTaskDlg.cs @@ -48,10 +48,10 @@ public BackgroundTaskDlg() public int Progress { - get { return ProgressCTRL.Value; } - - set - { + get { return ProgressCTRL.Value; } + + set + { ProgressCTRL.Value = value; if (value == ProgressCTRL.Maximum) diff --git a/Samples/Controls.Net4/Common/CallMethodDlg.Designer.cs b/Samples/Controls.Net4/Common/CallMethodDlg.Designer.cs index 01cd49388..621038150 100644 --- a/Samples/Controls.Net4/Common/CallMethodDlg.Designer.cs +++ b/Samples/Controls.Net4/Common/CallMethodDlg.Designer.cs @@ -89,7 +89,7 @@ private void InitializeComponent() this.OkBTN.TabIndex = 0; this.OkBTN.Text = "Call"; this.OkBTN.UseVisualStyleBackColor = true; - this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click); + this.OkBTN.Click += new System.EventHandler(this.OkBTN_ClickAsync); // // CancelBTN // diff --git a/Samples/Controls.Net4/Common/CallMethodDlg.cs b/Samples/Controls.Net4/Common/CallMethodDlg.cs index 0fb89a54e..1028bfda4 100644 --- a/Samples/Controls.Net4/Common/CallMethodDlg.cs +++ b/Samples/Controls.Net4/Common/CallMethodDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -58,16 +59,16 @@ public CallMethodDlg() private NodeId m_objectId; private NodeId m_methodId; #endregion - + #region Public Interface /// /// Displays the dialog. /// - public void Show(Session session, NodeId objectId, NodeId methodId) + public async Task ShowAsync(Session session, NodeId objectId, NodeId methodId, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - if (methodId == null) throw new ArgumentNullException("methodId"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + if (methodId == null) throw new ArgumentNullException(nameof(methodId)); + if (m_session != null) { m_session.SessionClosing -= m_SessionClosing; @@ -75,15 +76,15 @@ public void Show(Session session, NodeId objectId, NodeId methodId) m_session = session; m_session.SessionClosing += m_SessionClosing; - - m_objectId = objectId; + + m_objectId = objectId; m_methodId = methodId; - InputArgumentsCTRL.Update(session, methodId, true); - OutputArgumentsCTRL.Update(session, methodId, false); - - Node target = session.NodeCache.Find(objectId) as Node; - Node method = session.NodeCache.Find(methodId) as Node; + await InputArgumentsCTRL.UpdateAsync(session, methodId, true, ct); + await OutputArgumentsCTRL.UpdateAsync(session, methodId, false, ct); + + Node target = await session.NodeCache.FindAsync(objectId, ct) as Node; + Node method = await session.NodeCache.FindAsync(methodId, ct) as Node; if (target != null && method != null) { @@ -94,7 +95,7 @@ public void Show(Session session, NodeId objectId, NodeId methodId) BringToFront(); } #endregion - + private void Session_Closing(object sender, EventArgs e) { if (Object.ReferenceEquals(sender, m_session)) @@ -105,36 +106,36 @@ private void Session_Closing(object sender, EventArgs e) } } - private void OkBTN_Click(object sender, EventArgs e) + private async void OkBTN_ClickAsync(object sender, EventArgs e) { try { VariantCollection inputArguments = InputArgumentsCTRL.GetValues(); - + CallMethodRequest request = new CallMethodRequest(); - request.ObjectId = m_objectId; - request.MethodId = m_methodId; + request.ObjectId = m_objectId; + request.MethodId = m_methodId; request.InputArguments = inputArguments; CallMethodRequestCollection requests = new CallMethodRequestCollection(); requests.Add(request); - CallMethodResultCollection results; - DiagnosticInfoCollection diagnosticInfos; - - ResponseHeader responseHeader = m_session.Call( + CallResponse response = await m_session.CallAsync( null, requests, - out results, - out diagnosticInfos); + default); + + ResponseHeader responseHeader = response.ResponseHeader; + CallMethodResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(new ServiceResult(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable)); } - OutputArgumentsCTRL.SetValues(results[0].OutputArguments); + await OutputArgumentsCTRL.SetValuesAsync(results[0].OutputArguments); if (results[0].OutputArguments.Count == 0) { diff --git a/Samples/Controls.Net4/Common/DataEncodingDlg.Designer.cs b/Samples/Controls.Net4/Common/DataEncodingDlg.Designer.cs deleted file mode 100644 index c828c7f6b..000000000 --- a/Samples/Controls.Net4/Common/DataEncodingDlg.Designer.cs +++ /dev/null @@ -1,299 +0,0 @@ -/* ======================================================================== - * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. - * - * OPC Foundation MIT License 1.00 - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * The complete license agreement can be found here: - * http://opcfoundation.org/License/MIT/1.00/ - * ======================================================================*/ - -namespace Opc.Ua.Sample.Controls -{ - partial class DataEncodingDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.ButtonsPN = new System.Windows.Forms.Panel(); - this.OkBTN = new System.Windows.Forms.Button(); - this.CancelBTN = new System.Windows.Forms.Button(); - this.MainPN = new System.Windows.Forms.Panel(); - this.TypeNameTB = new System.Windows.Forms.TextBox(); - this.ShowEntireDictionaryLN = new System.Windows.Forms.Label(); - this.ShowEntireDictionaryCHK = new System.Windows.Forms.CheckBox(); - this.TypeSystemNameTB = new System.Windows.Forms.TextBox(); - this.DictionaryNameTB = new System.Windows.Forms.TextBox(); - this.DescriptionPN = new System.Windows.Forms.Panel(); - this.DescriptionTB = new System.Windows.Forms.RichTextBox(); - this.TypeSystemNameLB = new System.Windows.Forms.Label(); - this.EncodingCB = new System.Windows.Forms.ComboBox(); - this.DictionaryNameLB = new System.Windows.Forms.Label(); - this.TypeNameLB = new System.Windows.Forms.Label(); - this.EncodingLB = new System.Windows.Forms.Label(); - this.ButtonsPN.SuspendLayout(); - this.MainPN.SuspendLayout(); - this.DescriptionPN.SuspendLayout(); - this.SuspendLayout(); - // - // ButtonsPN - // - this.ButtonsPN.Controls.Add(this.OkBTN); - this.ButtonsPN.Controls.Add(this.CancelBTN); - this.ButtonsPN.Dock = System.Windows.Forms.DockStyle.Bottom; - this.ButtonsPN.Location = new System.Drawing.Point(0, 335); - this.ButtonsPN.Name = "ButtonsPN"; - this.ButtonsPN.Size = new System.Drawing.Size(492, 31); - this.ButtonsPN.TabIndex = 0; - // - // OkBTN - // - this.OkBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.OkBTN.Location = new System.Drawing.Point(4, 4); - this.OkBTN.Name = "OkBTN"; - this.OkBTN.Size = new System.Drawing.Size(75, 23); - this.OkBTN.TabIndex = 1; - this.OkBTN.Text = "OK"; - this.OkBTN.UseVisualStyleBackColor = true; - this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click); - // - // CancelBTN - // - this.CancelBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.CancelBTN.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.CancelBTN.Location = new System.Drawing.Point(413, 4); - this.CancelBTN.Name = "CancelBTN"; - this.CancelBTN.Size = new System.Drawing.Size(75, 23); - this.CancelBTN.TabIndex = 0; - this.CancelBTN.Text = "Cancel"; - this.CancelBTN.UseVisualStyleBackColor = true; - // - // MainPN - // - this.MainPN.Controls.Add(this.TypeNameTB); - this.MainPN.Controls.Add(this.ShowEntireDictionaryLN); - this.MainPN.Controls.Add(this.ShowEntireDictionaryCHK); - this.MainPN.Controls.Add(this.TypeSystemNameTB); - this.MainPN.Controls.Add(this.DictionaryNameTB); - this.MainPN.Controls.Add(this.DescriptionPN); - this.MainPN.Controls.Add(this.TypeSystemNameLB); - this.MainPN.Controls.Add(this.EncodingCB); - this.MainPN.Controls.Add(this.DictionaryNameLB); - this.MainPN.Controls.Add(this.TypeNameLB); - this.MainPN.Controls.Add(this.EncodingLB); - this.MainPN.Dock = System.Windows.Forms.DockStyle.Fill; - this.MainPN.Location = new System.Drawing.Point(0, 0); - this.MainPN.Name = "MainPN"; - this.MainPN.Size = new System.Drawing.Size(492, 335); - this.MainPN.TabIndex = 1; - // - // TypeNameTB - // - this.TypeNameTB.Location = new System.Drawing.Point(105, 76); - this.TypeNameTB.Name = "TypeNameTB"; - this.TypeNameTB.Size = new System.Drawing.Size(202, 20); - this.TypeNameTB.TabIndex = 23; - // - // ShowEntireDictionaryLN - // - this.ShowEntireDictionaryLN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.ShowEntireDictionaryLN.AutoSize = true; - this.ShowEntireDictionaryLN.Location = new System.Drawing.Point(353, 80); - this.ShowEntireDictionaryLN.Name = "ShowEntireDictionaryLN"; - this.ShowEntireDictionaryLN.Size = new System.Drawing.Size(114, 13); - this.ShowEntireDictionaryLN.TabIndex = 18; - this.ShowEntireDictionaryLN.Text = "Show Entire Dictionary"; - this.ShowEntireDictionaryLN.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // ShowEntireDictionaryCHK - // - this.ShowEntireDictionaryCHK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.ShowEntireDictionaryCHK.AutoSize = true; - this.ShowEntireDictionaryCHK.Location = new System.Drawing.Point(472, 81); - this.ShowEntireDictionaryCHK.Name = "ShowEntireDictionaryCHK"; - this.ShowEntireDictionaryCHK.Size = new System.Drawing.Size(15, 14); - this.ShowEntireDictionaryCHK.TabIndex = 19; - this.ShowEntireDictionaryCHK.UseVisualStyleBackColor = true; - this.ShowEntireDictionaryCHK.CheckStateChanged += new System.EventHandler(this.EncodingCB_SelectedIndexChanged); - // - // TypeSystemNameTB - // - this.TypeSystemNameTB.Location = new System.Drawing.Point(105, 28); - this.TypeSystemNameTB.Name = "TypeSystemNameTB"; - this.TypeSystemNameTB.Size = new System.Drawing.Size(202, 20); - this.TypeSystemNameTB.TabIndex = 22; - // - // DictionaryNameTB - // - this.DictionaryNameTB.Location = new System.Drawing.Point(105, 52); - this.DictionaryNameTB.Name = "DictionaryNameTB"; - this.DictionaryNameTB.Size = new System.Drawing.Size(202, 20); - this.DictionaryNameTB.TabIndex = 21; - // - // DescriptionPN - // - this.DescriptionPN.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.DescriptionPN.Controls.Add(this.DescriptionTB); - this.DescriptionPN.Location = new System.Drawing.Point(0, 100); - this.DescriptionPN.Name = "DescriptionPN"; - this.DescriptionPN.Size = new System.Drawing.Size(493, 235); - this.DescriptionPN.TabIndex = 20; - // - // DescriptionTB - // - this.DescriptionTB.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.DescriptionTB.Location = new System.Drawing.Point(3, 2); - this.DescriptionTB.Name = "DescriptionTB"; - this.DescriptionTB.Size = new System.Drawing.Size(486, 233); - this.DescriptionTB.TabIndex = 17; - this.DescriptionTB.Text = ""; - this.DescriptionTB.WordWrap = false; - // - // TypeSystemNameLB - // - this.TypeSystemNameLB.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.TypeSystemNameLB.AutoSize = true; - this.TypeSystemNameLB.Location = new System.Drawing.Point(4, 32); - this.TypeSystemNameLB.Name = "TypeSystemNameLB"; - this.TypeSystemNameLB.Size = new System.Drawing.Size(99, 13); - this.TypeSystemNameLB.TabIndex = 15; - this.TypeSystemNameLB.Text = "Type System Name"; - this.TypeSystemNameLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // EncodingCB - // - this.EncodingCB.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.EncodingCB.FormattingEnabled = true; - this.EncodingCB.Location = new System.Drawing.Point(105, 4); - this.EncodingCB.Name = "EncodingCB"; - this.EncodingCB.Size = new System.Drawing.Size(202, 21); - this.EncodingCB.TabIndex = 11; - this.EncodingCB.SelectedIndexChanged += new System.EventHandler(this.EncodingCB_SelectedIndexChanged); - // - // DictionaryNameLB - // - this.DictionaryNameLB.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.DictionaryNameLB.AutoSize = true; - this.DictionaryNameLB.Location = new System.Drawing.Point(4, 56); - this.DictionaryNameLB.Name = "DictionaryNameLB"; - this.DictionaryNameLB.Size = new System.Drawing.Size(85, 13); - this.DictionaryNameLB.TabIndex = 14; - this.DictionaryNameLB.Text = "Dictionary Name"; - this.DictionaryNameLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // TypeNameLB - // - this.TypeNameLB.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.TypeNameLB.AutoSize = true; - this.TypeNameLB.Location = new System.Drawing.Point(4, 80); - this.TypeNameLB.Name = "TypeNameLB"; - this.TypeNameLB.Size = new System.Drawing.Size(62, 13); - this.TypeNameLB.TabIndex = 12; - this.TypeNameLB.Text = "Type Name"; - this.TypeNameLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // EncodingLB - // - this.EncodingLB.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.EncodingLB.AutoSize = true; - this.EncodingLB.Location = new System.Drawing.Point(4, 8); - this.EncodingLB.Name = "EncodingLB"; - this.EncodingLB.Size = new System.Drawing.Size(52, 13); - this.EncodingLB.TabIndex = 10; - this.EncodingLB.Text = "Encoding"; - this.EncodingLB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // DataEncodingDlg - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(492, 366); - this.Controls.Add(this.MainPN); - this.Controls.Add(this.ButtonsPN); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; - this.MaximizeBox = false; - this.Name = "DataEncodingDlg"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Data Encoding"; - this.ButtonsPN.ResumeLayout(false); - this.MainPN.ResumeLayout(false); - this.MainPN.PerformLayout(); - this.DescriptionPN.ResumeLayout(false); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Panel ButtonsPN; - private System.Windows.Forms.Button OkBTN; - private System.Windows.Forms.Button CancelBTN; - private System.Windows.Forms.Panel MainPN; - private System.Windows.Forms.Label EncodingLB; - private System.Windows.Forms.Label DictionaryNameLB; - private System.Windows.Forms.Label TypeNameLB; - private System.Windows.Forms.ComboBox EncodingCB; - private System.Windows.Forms.Label TypeSystemNameLB; - private System.Windows.Forms.Label ShowEntireDictionaryLN; - private System.Windows.Forms.Panel DescriptionPN; - private System.Windows.Forms.CheckBox ShowEntireDictionaryCHK; - private System.Windows.Forms.TextBox TypeNameTB; - private System.Windows.Forms.TextBox TypeSystemNameTB; - private System.Windows.Forms.TextBox DictionaryNameTB; - private System.Windows.Forms.RichTextBox DescriptionTB; - } -} diff --git a/Samples/Controls.Net4/Common/DataEncodingDlg.cs b/Samples/Controls.Net4/Common/DataEncodingDlg.cs deleted file mode 100644 index 8a8dd1179..000000000 --- a/Samples/Controls.Net4/Common/DataEncodingDlg.cs +++ /dev/null @@ -1,295 +0,0 @@ -/* ======================================================================== - * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. - * - * OPC Foundation MIT License 1.00 - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * The complete license agreement can be found here: - * http://opcfoundation.org/License/MIT/1.00/ - * ======================================================================*/ - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Reflection; - -using Opc.Ua.Client; -using Opc.Ua.Client.Controls; - -namespace Opc.Ua.Sample.Controls -{ - public partial class DataEncodingDlg : Form - { - #region Constructors - public DataEncodingDlg() - { - InitializeComponent(); - this.Icon = ClientUtils.GetAppIcon(); - } - #endregion - - #region Private Fields - private Session m_session; - private ReferenceDescriptionCollection m_encodings; - #endregion - - #region Private Methods - /// - /// Formats the description. - /// - private void FormatDescription() - { - string text = DescriptionTB.Text; - - int state = 0; - int start = 0; - int offset = 0; - - for (int ii = 0; ii < 4096 && ii < text.Length; ii++) - { - if (text[ii] == '\r') - { - offset--; - } - - if (state == 0) - { - if (text[ii] == '<') - { - start = ii; - state = 1; - continue; - } - } - - if (state == 1) - { - if (Char.IsLetter(text[ii])) - { - DescriptionTB.SelectionStart = start + offset; - DescriptionTB.SelectionLength = ii - start; - DescriptionTB.SelectionColor = Color.Blue; - - string selection = DescriptionTB.SelectedText; - - start = ii; - state = 2; - continue; - } - } - - if (state == 2) - { - if (Char.IsWhiteSpace(text[ii]) || text[ii] == '>' || text[ii] == '/') - { - DescriptionTB.SelectionStart = start + offset; - DescriptionTB.SelectionLength = ii - start; - DescriptionTB.SelectionColor = Color.Maroon; - - string selection = DescriptionTB.SelectedText; - - start = ii; - - if (text[ii] == '>' || text[ii] == '/') - { - state = 0; - } - else - { - state = 3; - } - - continue; - } - } - - if (state == 3) - { - if (text[ii] == '>') - { - DescriptionTB.SelectionStart = start + offset; - DescriptionTB.SelectionLength = ii - start + 1; - DescriptionTB.SelectionColor = Color.Blue; - - string selection = DescriptionTB.SelectedText; - - start = ii+1; - state = 0; - continue; - } - - if (Char.IsLetter(text[ii])) - { - start = ii; - state = 4; - continue; - } - } - - if (state == 4) - { - if (text[ii] == '=') - { - DescriptionTB.SelectionStart = start + offset; - DescriptionTB.SelectionLength = ii - start; - DescriptionTB.SelectionColor = Color.Red; - - string selection = DescriptionTB.SelectedText; - - start = ii; - state = 5; - continue; - } - } - - if (state == 5) - { - if (text[ii] == '"' || text[ii] == '\'') - { - state = 6; - continue; - } - } - - if (state == 6) - { - if (text[ii] == '"' || text[ii] == '\'') - { - DescriptionTB.SelectionStart = start + offset; - DescriptionTB.SelectionLength = ii - start + 1; - DescriptionTB.SelectionColor = Color.Blue; - - string selection = DescriptionTB.SelectedText; - - start = ii+1; - state = 3; - continue; - } - } - } - } - #endregion - - #region Event Handlers - /// - /// Prompts the user to specify the browse options. - /// - public bool ShowDialog(Session session, NodeId variableId) - { - if (session == null) throw new ArgumentNullException("session"); - if (variableId == null) throw new ArgumentNullException("variableId"); - - m_session = session; - m_encodings = session.ReadAvailableEncodings(variableId); - - foreach (ReferenceDescription encoding in m_encodings) - { - EncodingCB.Items.Add(encoding.ToString()); - } - - if (EncodingCB.Items.Count > 0) - { - EncodingCB.SelectedIndex = 0; - } - - if (ShowDialog() != DialogResult.OK) - { - return false; - } - - return true; - } - - private void OkBTN_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.OK; - } - - private async void EncodingCB_SelectedIndexChanged(object sender, EventArgs e) - { - try - { - DescriptionTB.Text = null; - TypeNameTB.Text = null; - DictionaryNameTB.Text = null; - TypeSystemNameTB.Text = null; - - if (EncodingCB.SelectedIndex < 0 || EncodingCB.SelectedIndex > m_encodings.Count) - { - return; - } - - // get the current encoding. - ReferenceDescription encoding = m_encodings[EncodingCB.SelectedIndex]; - - // find the desctiption. - ReferenceDescription description = m_session.FindDataDescription((NodeId)encoding.NodeId); - - if (description == null) - { - return; - } - - TypeNameTB.Text = description.ToString(); - - // find the dictionary. - DataDictionary dictionary = await m_session.FindDataDictionary((NodeId)description.NodeId); - - if (dictionary == null) - { - return; - } - - NodeId descriptionId = null; - - if (!ShowEntireDictionaryCHK.Checked) - { - descriptionId = (NodeId)description.NodeId; - } - - DictionaryNameTB.Text = dictionary.Name; - TypeSystemNameTB.Text = dictionary.TypeSystemName; - DescriptionTB.Text = dictionary.GetSchema(descriptionId); - - Cursor = Cursors.WaitCursor; - - try - { - FormatDescription(); - } - finally - { - Cursor = Cursors.Default; - } - } - catch (Exception exception) - { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); - } - } - #endregion - } -} diff --git a/Samples/Controls.Net4/Common/DataEncodingDlg.resx b/Samples/Controls.Net4/Common/DataEncodingDlg.resx deleted file mode 100644 index d58980a38..000000000 --- a/Samples/Controls.Net4/Common/DataEncodingDlg.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/Samples/Controls.Net4/Common/DataValueListCtrl.cs b/Samples/Controls.Net4/Common/DataValueListCtrl.cs index 6413e6a9c..8873a4fb3 100644 --- a/Samples/Controls.Net4/Common/DataValueListCtrl.cs +++ b/Samples/Controls.Net4/Common/DataValueListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -46,8 +47,8 @@ public partial class DataValueListCtrl : Opc.Ua.Client.Controls.BaseListCtrl #region Constructors public DataValueListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #endregion @@ -59,15 +60,15 @@ public DataValueListCtrl() /// The columns to display in the control. /// private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Node", HorizontalAlignment.Left, null }, - new object[] { "Attribute", HorizontalAlignment.Left, "Value", }, - new object[] { "Value", HorizontalAlignment.Left, "", 200 }, - new object[] { "Status", HorizontalAlignment.Left, "" }, - new object[] { "Source Time", HorizontalAlignment.Left, "" }, - new object[] { "Server Time", HorizontalAlignment.Left, "" }, - }; - #endregion + { + new object[] { "Node", HorizontalAlignment.Left, null }, + new object[] { "Attribute", HorizontalAlignment.Left, "Value", }, + new object[] { "Value", HorizontalAlignment.Left, "", 200 }, + new object[] { "Status", HorizontalAlignment.Left, "" }, + new object[] { "Source Time", HorizontalAlignment.Left, "" }, + new object[] { "Server Time", HorizontalAlignment.Left, "" }, + }; + #endregion #region Public Interface /// @@ -75,8 +76,8 @@ public DataValueListCtrl() /// public DataListCtrl DataListCtrl { - get { return m_DataListCtrl; } - set { m_DataListCtrl = value; } + get { return m_DataListCtrl; } + set { m_DataListCtrl = value; } } /// @@ -91,17 +92,18 @@ public void Clear() /// /// Sets the nodes in the control. /// - public void Initialize( - Session session, - ReadValueIdCollection valueIds, - DataValueCollection values, - List results) + public async Task InitializeAsync( + Session session, + ReadValueIdCollection valueIds, + DataValueCollection values, + List results, + CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); - - m_session = session; + + m_session = session; if (valueIds != null) { @@ -109,7 +111,7 @@ public void Initialize( { ValueItem item = new ValueItem(); - item.Node = m_session.NodeCache.Find(valueIds[ii].NodeId) as Node; + item.Node = await m_session.NodeCache.FindAsync(valueIds[ii].NodeId, ct) as Node; item.AttributeId = valueIds[ii].AttributeId; if (values != null && ii < values.Count) @@ -132,26 +134,27 @@ public void Initialize( /// /// Sets the nodes in the control. /// - public void Initialize( - Session session, - WriteValueCollection values, - List results) + public async Task InitializeAsync( + Session session, + WriteValueCollection values, + List results, + CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); - + m_session = session; - + if (values != null) { for (int ii = 0; ii < values.Count; ii++) { ValueItem item = new ValueItem(); - item.Node = m_session.NodeCache.Find(values[ii].NodeId) as Node; + item.Node = await m_session.NodeCache.FindAsync(values[ii].NodeId, ct) as Node; item.AttributeId = values[ii].AttributeId; - item.Value = values[ii].Value; + item.Value = values[ii].Value; if (results != null && ii < results.Count) { @@ -164,35 +167,35 @@ public void Initialize( AdjustColumns(); } - #endregion - + #endregion + #region NodeField Class /// /// A field associated with a node. /// - private class ValueItem - { + private sealed class ValueItem + { public Node Node; public uint AttributeId; public DataValue Value; public ServiceResult Result; } - #endregion + #endregion #region Private Methods - #endregion - + #endregion + #region Overridden Methods - /// - protected override void UpdateItem(ListViewItem listItem, object item) + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - ValueItem dataValue = item as ValueItem; + ValueItem dataValue = item as ValueItem; - if (dataValue == null) - { - base.UpdateItem(listItem, item); - return; - } + if (dataValue == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } listItem.SubItems[0].Text = String.Format("{0}", dataValue.Node); listItem.SubItems[1].Text = Attributes.GetBrowseName(dataValue.AttributeId); @@ -218,12 +221,12 @@ protected override void UpdateItem(ListViewItem listItem, object item) if (dataValue.Result != null) { - listItem.SubItems[3].Text =String.Format("{0}", dataValue.Result); + listItem.SubItems[3].Text = String.Format("{0}", dataValue.Result); } - listItem.Tag = item; + listItem.Tag = item; } - + /// protected override void SelectItems() { @@ -235,11 +238,11 @@ protected override void SelectItems() if (values != null && values.Length > 0) { - m_DataListCtrl.ShowValue(values[0].Value); + m_DataListCtrl.ShowValueAsync(values[0].Value); } else { - m_DataListCtrl.ShowValue(null); + m_DataListCtrl.ShowValueAsync(null); } } } diff --git a/Samples/Controls.Net4/Common/FindNodeDlg.Designer.cs b/Samples/Controls.Net4/Common/FindNodeDlg.Designer.cs index 090a459a5..b79239465 100644 --- a/Samples/Controls.Net4/Common/FindNodeDlg.Designer.cs +++ b/Samples/Controls.Net4/Common/FindNodeDlg.Designer.cs @@ -104,7 +104,7 @@ private void InitializeComponent() this.FindBTN.TabIndex = 2; this.FindBTN.Text = "Find"; this.FindBTN.UseVisualStyleBackColor = true; - this.FindBTN.Click += new System.EventHandler(this.OkBTN_Click); + this.FindBTN.Click += new System.EventHandler(this.OkBTN_ClickAsync); // // OkBTN // @@ -116,7 +116,7 @@ private void InitializeComponent() this.OkBTN.TabIndex = 0; this.OkBTN.Text = "OK"; this.OkBTN.UseVisualStyleBackColor = true; - this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click); + this.OkBTN.Click += new System.EventHandler(this.OkBTN_ClickAsync); // // CancelBTN // diff --git a/Samples/Controls.Net4/Common/FindNodeDlg.cs b/Samples/Controls.Net4/Common/FindNodeDlg.cs index ef2b50cd9..74e49577d 100644 --- a/Samples/Controls.Net4/Common/FindNodeDlg.cs +++ b/Samples/Controls.Net4/Common/FindNodeDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -58,7 +58,7 @@ public NodeIdCollection ShowDialog(Session session, NodeId startNodeId) { m_session = session; - StartNode.Text = String.Format("{0}", startNodeId); + StartNode.Text = String.Format("{0}", startNodeId); RelativePath.Text = null; if (ShowDialog() != DialogResult.OK) @@ -69,36 +69,35 @@ public NodeIdCollection ShowDialog(Session session, NodeId startNodeId) return null; } - private void OkBTN_Click(object sender, EventArgs e) + private async void OkBTN_ClickAsync(object sender, EventArgs e) { try - { + { BrowsePathCollection browsePaths = new BrowsePathCollection(); - + BrowsePath browsePath = new BrowsePath(); browsePath.StartingNode = NodeId.Parse(StartNode.Text); browsePath.RelativePath = Opc.Ua.RelativePath.Parse(RelativePath.Text, m_session.TypeTree); - - browsePaths.Add(browsePath); - BrowsePathResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; + browsePaths.Add(browsePath); - m_session.TranslateBrowsePathsToNodeIds( + TranslateBrowsePathsToNodeIdsResponse response = await m_session.TranslateBrowsePathsToNodeIdsAsync( null, browsePaths, - out results, - out diagnosticInfos); + default); + + BrowsePathResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; if (results != null && results.Count == 1) { // NodesCTRL.SetNodeList(results[0].MatchingNodeIds); - } + } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/NodeListCtrl.Designer.cs b/Samples/Controls.Net4/Common/NodeListCtrl.Designer.cs index 4d41311cd..7c28f201f 100644 --- a/Samples/Controls.Net4/Common/NodeListCtrl.Designer.cs +++ b/Samples/Controls.Net4/Common/NodeListCtrl.Designer.cs @@ -81,7 +81,7 @@ private void InitializeComponent() this.ViewMI.Name = "ViewMI"; this.ViewMI.Size = new System.Drawing.Size(166, 22); this.ViewMI.Text = "View..."; - this.ViewMI.Click += new System.EventHandler(this.ViewMI_Click); + this.ViewMI.Click += new System.EventHandler(this.ViewMI_ClickAsync); // // DeleteMI // diff --git a/Samples/Controls.Net4/Common/NodeListCtrl.cs b/Samples/Controls.Net4/Common/NodeListCtrl.cs index b2e91f3c5..55f51f7b4 100644 --- a/Samples/Controls.Net4/Common/NodeListCtrl.cs +++ b/Samples/Controls.Net4/Common/NodeListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -45,8 +47,8 @@ public partial class NodeListCtrl : Opc.Ua.Client.Controls.BaseListCtrl { public NodeListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -58,12 +60,12 @@ public NodeListCtrl() /// The columns to display in the control. /// private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "NodeId", HorizontalAlignment.Left, null }, - new object[] { "Class", HorizontalAlignment.Left, null } - }; - #endregion + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "NodeId", HorizontalAlignment.Left, null }, + new object[] { "Class", HorizontalAlignment.Left, null } + }; + #endregion #region Public Interface /// @@ -78,24 +80,24 @@ public void Clear() /// /// Sets the nodes in the control. /// - public void Initialize(Session session, NodeIdCollection nodeIds, NodeClass nodeClassMask) + public async Task InitializeAsync(Session session, NodeIdCollection nodeIds, NodeClass nodeClassMask, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); - - m_session = session; - m_nodeIds = nodeIds; - m_nodeClassMask = (nodeClassMask == 0)?(NodeClass)Byte.MaxValue:nodeClassMask; + + m_session = session; + m_nodeIds = nodeIds; + m_nodeClassMask = (nodeClassMask == 0) ? (NodeClass)Byte.MaxValue : nodeClassMask; if (nodeIds == null) { - return; + return; } foreach (NodeId nodeId in nodeIds) { - INode node = m_session.NodeCache.Find(nodeId); + INode node = await m_session.NodeCache.FindAsync(nodeId, ct); if (node != null && (m_nodeClassMask & node.NodeClass) != 0) { @@ -105,15 +107,15 @@ public void Initialize(Session session, NodeIdCollection nodeIds, NodeClass node AdjustColumns(); } - + /// /// Adds a node to the list. /// - public void AddNodeId(ReferenceDescription reference) + public async Task AddNodeIdAsync(ReferenceDescription reference, CancellationToken ct = default) { if (reference != null) { - AddNodeId(reference.NodeId); + await AddNodeIdAsync(reference.NodeId, ct); AdjustColumns(); } } @@ -121,9 +123,9 @@ public void AddNodeId(ReferenceDescription reference) /// /// Adds a node to the list. /// - public void AddNodeId(ExpandedNodeId nodeId) + public async Task AddNodeIdAsync(ExpandedNodeId nodeId, CancellationToken ct = default) { - Node node = m_session.NodeCache.Find(nodeId) as Node; + Node node = await m_session.NodeCache.FindAsync(nodeId, ct) as Node; if (node == null) { @@ -140,12 +142,12 @@ public void AddNodeId(ExpandedNodeId nodeId) { if (target.NodeId == node.NodeId) { - UpdateItem(listItem, node); + await UpdateItemAsync(listItem, node, ct); return; } } } - + AddItem(node, "Property", -1); return; } @@ -156,15 +158,15 @@ public void AddNodeId(ExpandedNodeId nodeId) if (supertypeId != null) { - AddNodeId(supertypeId); + await AddNodeIdAsync(supertypeId, ct); } } - + IList properties = node.ReferenceTable.Find(ReferenceTypeIds.HasProperty, false, true, m_session.TypeTree); for (int ii = 0; ii < properties.Count; ii++) { - AddNodeId(properties[ii].TargetId); + await AddNodeIdAsync(properties[ii].TargetId, ct); } } @@ -187,40 +189,40 @@ public NodeIdCollection GetNodeIds() return nodeIds; } - #endregion - + #endregion + #region Private Methods - #endregion - + #endregion + #region Overridden Methods /// - protected override void EnableMenuItems(ListViewItem clickedItem) - { - ViewMI.Enabled = ItemsLV.SelectedItems.Count == 1; + protected override void EnableMenuItems(ListViewItem clickedItem) + { + ViewMI.Enabled = ItemsLV.SelectedItems.Count == 1; DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item) + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - Node node = item as Node; + Node node = item as Node; - if (node == null) - { - base.UpdateItem(listItem, item); - return; - } + if (node == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } listItem.SubItems[0].Text = String.Format("{0}", node); - listItem.SubItems[1].Text = String.Format("{0}", node.NodeId); - listItem.SubItems[2].Text = String.Format("{0}", (NodeClass)node.NodeClass); + listItem.SubItems[1].Text = String.Format("{0}", node.NodeId); + listItem.SubItems[2].Text = String.Format("{0}", (NodeClass)node.NodeClass); - listItem.Tag = item; + listItem.Tag = item; } #endregion - + #region Event Handlers - private void ViewMI_Click(object sender, EventArgs e) + private async void ViewMI_ClickAsync(object sender, EventArgs e) { try { @@ -228,24 +230,24 @@ private void ViewMI_Click(object sender, EventArgs e) if (nodes == null || nodes.Length == 1) { - new NodeAttributesDlg().ShowDialog(m_session, nodes[0].NodeId); + await new NodeAttributesDlg().ShowDialogAsync(m_session, nodes[0].NodeId); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) - { + protected override async Task OnDragDropAsync(object sender, DragEventArgs e, CancellationToken ct = default) + { try { ReferenceDescription reference = e.Data.GetData(typeof(ReferenceDescription)) as ReferenceDescription; if (reference != null) { - AddNodeId(reference); + await AddNodeIdAsync(reference, ct); } ReferenceDescriptionCollection references = e.Data.GetData(typeof(ReferenceDescriptionCollection)) as ReferenceDescriptionCollection; @@ -254,7 +256,7 @@ protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) { foreach (ReferenceDescription current in references) { - AddNodeId(current); + await AddNodeIdAsync(current, ct); } } @@ -270,7 +272,7 @@ protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -292,7 +294,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Common/PerformanceResultsListCtrl.cs b/Samples/Controls.Net4/Common/PerformanceResultsListCtrl.cs index e012ea178..b6b2cef38 100644 --- a/Samples/Controls.Net4/Common/PerformanceResultsListCtrl.cs +++ b/Samples/Controls.Net4/Common/PerformanceResultsListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client.Controls; namespace Opc.Ua.Sample.Controls @@ -44,8 +45,8 @@ public partial class PerformanceResultsListCtrl : Opc.Ua.Client.Controls.BaseLis { public PerformanceResultsListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -53,19 +54,19 @@ public PerformanceResultsListCtrl() /// The columns to display in the control. /// private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Server", HorizontalAlignment.Left, null }, - new object[] { "1", HorizontalAlignment.Left, "-1" }, - new object[] { "10", HorizontalAlignment.Left, "-1" }, - new object[] { "50", HorizontalAlignment.Left, "-1" }, - new object[] { "100", HorizontalAlignment.Left, "-1" }, - new object[] { "250", HorizontalAlignment.Left, "-1" }, - new object[] { "500", HorizontalAlignment.Left, "-1" }, - new object[] { "1000", HorizontalAlignment.Left, "-1" }, + { + new object[] { "Server", HorizontalAlignment.Left, null }, + new object[] { "1", HorizontalAlignment.Left, "-1" }, + new object[] { "10", HorizontalAlignment.Left, "-1" }, + new object[] { "50", HorizontalAlignment.Left, "-1" }, + new object[] { "100", HorizontalAlignment.Left, "-1" }, + new object[] { "250", HorizontalAlignment.Left, "-1" }, + new object[] { "500", HorizontalAlignment.Left, "-1" }, + new object[] { "1000", HorizontalAlignment.Left, "-1" }, //new object[] { "2500", HorizontalAlignment.Left, "-1" }, - //new object[] { "5000", HorizontalAlignment.Left, "-1" }, + //new object[] { "5000", HorizontalAlignment.Left, "-1" }, }; - #endregion + #endregion #region Public Interface /// @@ -73,7 +74,7 @@ public PerformanceResultsListCtrl() /// public void Add(PerformanceTestResult result) { - if (result == null) throw new ArgumentNullException("result"); + if (result == null) throw new ArgumentNullException(nameof(result)); AddItem(result); AdjustColumns(); @@ -95,8 +96,8 @@ public PerformanceTestResult[] GetResults() { return (PerformanceTestResult[])GetItems(typeof(PerformanceTestResult)); } - #endregion - + #endregion + #region Overridden Methods /// protected override void PickItems() @@ -106,22 +107,22 @@ protected override void PickItems() /// protected override void EnableMenuItems(ListViewItem clickedItem) - { - DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; + { + DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; ClearAllMI.Enabled = ItemsLV.Items.Count > 0; - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item) + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - PerformanceTestResult result = item as PerformanceTestResult; - - if (result == null) - { - base.UpdateItem(listItem, item); - return; - } - + PerformanceTestResult result = item as PerformanceTestResult; + + if (result == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } + listItem.SubItems[0].Text = String.Format("{0}", result.Endpoint); listItem.SubItems[1].Text = String.Format("{0:0.##}", result.Results[1]); listItem.SubItems[2].Text = String.Format("{0:0.##}", result.Results[10]); @@ -132,8 +133,8 @@ protected override void UpdateItem(ListViewItem listItem, object item) //listItem.SubItems[7].Text = String.Format("{0:0.##}", result.Results[1000]); //listItem.SubItems[7].Text = String.Format("{0:0.##}", result.Results[2500]); //listItem.SubItems[8].Text = String.Format("{0:0.##}", result.Results[5000]); - - listItem.Tag = item; + + listItem.Tag = item; listItem.ImageKey = "DataType"; } #endregion @@ -158,7 +159,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -170,7 +171,7 @@ private void ClearAllMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/PerformanceTestDlg.cs b/Samples/Controls.Net4/Common/PerformanceTestDlg.cs index 49156757c..64cfda812 100644 --- a/Samples/Controls.Net4/Common/PerformanceTestDlg.cs +++ b/Samples/Controls.Net4/Common/PerformanceTestDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -43,6 +43,7 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; namespace Opc.Ua.Sample.Controls { @@ -64,24 +65,24 @@ public PerformanceTestDlg() private ServiceMessageContext m_messageContext; private X509Certificate2 m_clientCertificate; private string m_filePath; - + /// /// Displays the dialog. /// public EndpointDescription ShowDialog( - ApplicationConfiguration configuration, + ApplicationConfiguration configuration, ConfiguredEndpointCollection endpoints, - X509Certificate2 clientCertificate) + X509Certificate2 clientCertificate) { - m_configuration = configuration; - m_endpoints = endpoints; - m_messageContext = configuration.CreateMessageContext(); + m_configuration = configuration; + m_endpoints = endpoints; + m_messageContext = configuration.CreateMessageContext(); m_clientCertificate = clientCertificate; - m_running = false; - m_filePath = @".\perftest.csv"; - + m_running = false; + m_filePath = @".\perftest.csv"; + EndpointSelectorCTRL.Initialize(m_endpoints, configuration); - + lock (m_lock) { OkBTN.Enabled = m_running = false; @@ -105,7 +106,7 @@ private void LoadResults(string filePath) DataContractSerializer serializer = new DataContractSerializer(typeof(PerformanceTestResult[])); PerformanceTestResult[] results = (PerformanceTestResult[])serializer.ReadObject(istrm); istrm.Close(); - + ResultsCTRL.Clear(); foreach (PerformanceTestResult result in results) @@ -127,7 +128,7 @@ private void SaveResults(string filePath) { return; } - + Stream ostrm = File.Open(filePath, FileMode.Create); StreamWriter writer = new StreamWriter(ostrm); @@ -137,8 +138,8 @@ private void SaveResults(string filePath) writer.Write(",Algorithms"); writer.Write(",Encoding"); - foreach (KeyValuePair result in results[0].Results) - { + foreach (KeyValuePair result in results[0].Results) + { writer.Write(",{0} Values", result.Key); } @@ -154,17 +155,17 @@ private void SaveResults(string filePath) writer.Write(",{0}", uri.Scheme); writer.Write(",{0}", endpoint.SecurityMode); writer.Write(",{0}", SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri)); - writer.Write(",{0}", (results[ii].Endpoint.Configuration.UseBinaryEncoding)?"Binary":"XML"); + writer.Write(",{0}", (results[ii].Endpoint.Configuration.UseBinaryEncoding) ? "Binary" : "XML"); - foreach (KeyValuePair result in results[ii].Results) - { + foreach (KeyValuePair result in results[ii].Results) + { writer.Write(",{0}", result.Value); } writer.Write("\r\n"); } - writer.Close(); + writer.Close(); m_filePath = filePath; } @@ -180,13 +181,13 @@ public void TestComplete(object state) } try - { + { ProgressCTRL.Value = ProgressCTRL.Maximum; ResultsCTRL.Add((PerformanceTestResult)state); - } + } catch (Exception e) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); } } @@ -204,15 +205,15 @@ private void TestProgress(object state) try { ProgressCTRL.Value = (int)state; - } + } catch (Exception e) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); } } /// - /// Called when the the test fails with an exception. + /// Called when the test fails with an exception. /// private void TestException(object state) { @@ -225,26 +226,26 @@ private void TestException(object state) try { OkBTN.Enabled = m_running = false; - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), (Exception)state); - } + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), (Exception)state); + } catch (Exception e) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); } } - + /// /// Runs all tests in a background thread. /// - private void DoAllTests(object state) + private async Task DoAllTestsAsync(CancellationToken ct = default) { for (int ii = 0; ii < m_endpoints.Count; ii++) { try { - DoTest(m_endpoints[ii]); + await DoTestAsync(m_endpoints[ii], ct); } - catch + catch { // ignore. } @@ -256,24 +257,7 @@ private void DoAllTests(object state) /// /// Runs the test in a background thread. /// - private void DoTest(object state) - { - try - { - DoTest((ConfiguredEndpoint)state); - } - catch (Exception e) - { - TestException(e); - } - - m_running = false; - } - - /// - /// Runs the test in a background thread. - /// - private void DoTest(ConfiguredEndpoint endpoint) + private async Task DoTestAsync(ConfiguredEndpoint endpoint, CancellationToken ct = default) { PerformanceTestResult result = new PerformanceTestResult(endpoint, 100); @@ -289,7 +273,7 @@ private void DoTest(ConfiguredEndpoint endpoint) // update the endpoint. if (endpoint.UpdateBeforeConnect) { - endpoint.UpdateFromServer(); + await endpoint.UpdateFromServerAsync(ct); } SessionClient client = null; @@ -339,16 +323,15 @@ private void DoTest(ConfiguredEndpoint endpoint) } // ensure valid connection. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - client.Read( + ReadResponse response = await client.ReadAsync( requestHeader, 0, TimestampsToReturn.Both, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; if (results.Count != count) { @@ -360,13 +343,15 @@ private void DoTest(ConfiguredEndpoint endpoint) for (int jj = 0; jj < result.Iterations; jj++) { - client.Read( + response = await client.ReadAsync( requestHeader, 0, TimestampsToReturn.Both, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; if (results.Count != count) { @@ -404,11 +389,11 @@ private void EndpointSelectorCTRL_ConnectEndpoint(object sender, ConnectEndpoint // start processing. OkBTN.Enabled = m_running = true; - ThreadPool.QueueUserWorkItem(new WaitCallback(DoTest), endpoint); + Task.Run(() => DoTestAsync(endpoint)); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); e.UpdateControl = false; } } @@ -424,70 +409,70 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void SaveBTN_Click(object sender, EventArgs e) { - try - { + try + { FileInfo fileInfo = new FileInfo(m_filePath); - SaveFileDialog dialog = new SaveFileDialog(); + SaveFileDialog dialog = new SaveFileDialog(); - dialog.CheckFileExists = false; - dialog.CheckPathExists = true; - dialog.DefaultExt = ".csv"; - dialog.Filter = "Result Files (*.csv)|*.csv|All Files (*.*)|*.*"; - dialog.ValidateNames = true; - dialog.Title = "Save Performance Test Result File"; - dialog.FileName = m_filePath; + dialog.CheckFileExists = false; + dialog.CheckPathExists = true; + dialog.DefaultExt = ".csv"; + dialog.Filter = "Result Files (*.csv)|*.csv|All Files (*.*)|*.*"; + dialog.ValidateNames = true; + dialog.Title = "Save Performance Test Result File"; + dialog.FileName = m_filePath; dialog.InitialDirectory = fileInfo.DirectoryName; dialog.RestoreDirectory = true; - if (dialog.ShowDialog() != DialogResult.OK) - { - return; - } + if (dialog.ShowDialog() != DialogResult.OK) + { + return; + } SaveResults(dialog.FileName); - } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void LoadBTN_Click(object sender, EventArgs e) - { - try - { + { + try + { FileInfo fileInfo = new FileInfo(m_filePath); - OpenFileDialog dialog = new OpenFileDialog(); + OpenFileDialog dialog = new OpenFileDialog(); - dialog.CheckFileExists = true; - dialog.CheckPathExists = true; - dialog.DefaultExt = ".csv"; - dialog.Filter = "Result Files (*.csv)|*.csv|All Files (*.*)|*.*"; - dialog.Multiselect = false; - dialog.ValidateNames = true; - dialog.Title = "Open Performance Test Result File"; - dialog.FileName = m_filePath; + dialog.CheckFileExists = true; + dialog.CheckPathExists = true; + dialog.DefaultExt = ".csv"; + dialog.Filter = "Result Files (*.csv)|*.csv|All Files (*.*)|*.*"; + dialog.Multiselect = false; + dialog.ValidateNames = true; + dialog.Title = "Open Performance Test Result File"; + dialog.FileName = m_filePath; dialog.InitialDirectory = fileInfo.DirectoryName; dialog.RestoreDirectory = true; - if (dialog.ShowDialog() != DialogResult.OK) - { - return; - } + if (dialog.ShowDialog() != DialogResult.OK) + { + return; + } LoadResults(dialog.FileName); - } + } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -502,7 +487,7 @@ private void TestAllBTN_Click(object sender, EventArgs e) ResultsCTRL.Clear(); OkBTN.Enabled = m_running = true; - ThreadPool.QueueUserWorkItem(new WaitCallback(DoAllTests), null); + Task.Run(() => DoAllTestsAsync()); } catch (Exception exception) { @@ -525,19 +510,19 @@ public PerformanceTestResult(ConfiguredEndpoint endpoint, int iterations) { Initialize(); - m_endpoint = endpoint; + m_endpoint = endpoint; m_iterations = iterations; } - /// - /// Sets private members to default values. - /// - private void Initialize() - { - m_endpoint = null; + /// + /// Sets private members to default values. + /// + private void Initialize() + { + m_endpoint = null; m_iterations = 0; - m_results = new Dictionary(); - } + m_results = new Dictionary(); + } /// /// Initializes the object during deserialization. @@ -577,14 +562,14 @@ public int Iterations private List TestCaseResults { get - { + { List results = new List(); - foreach (KeyValuePair entry in m_results) + foreach (KeyValuePair entry in m_results) { PerformanceTestResultItem item = new PerformanceTestResultItem(); - item.Count = entry.Key; + item.Count = entry.Key; item.Average = entry.Value; results.Add(item); @@ -592,8 +577,8 @@ private List TestCaseResults return results; } - set - { + set + { m_results.Clear(); if (value != null) @@ -607,18 +592,18 @@ private List TestCaseResults } /// - /// The average roundtrip time in milliseconds indexed by the payload size in bytes. + /// The average roundtrip time in milliseconds indexed by the payload size in bytes. /// - public IDictionary Results + public IDictionary Results { get { return m_results; } } #endregion - + #region Private Fields private ConfiguredEndpoint m_endpoint; private int m_iterations; - private Dictionary m_results; + private Dictionary m_results; #endregion } @@ -637,14 +622,14 @@ public PerformanceTestResultItem() Initialize(); } - /// - /// Sets private members to default values. - /// - private void Initialize() - { - m_count = 0; + /// + /// Sets private members to default values. + /// + private void Initialize() + { + m_count = 0; m_average = 0; - } + } /// /// Initializes the object during deserialization. @@ -663,7 +648,7 @@ private void Initialize(StreamingContext context) [DataMember(Order = 1)] public int Count { - get { return m_count; } + get { return m_count; } set { m_count = value; } } @@ -673,11 +658,11 @@ public int Count [DataMember(Order = 2)] public double Average { - get { return m_average; } + get { return m_average; } set { m_average = value; } } #endregion - + #region Private Fields private int m_count; private double m_average; diff --git a/Samples/Controls.Net4/Common/PropertyListCtrl.cs b/Samples/Controls.Net4/Common/PropertyListCtrl.cs index 8ad8dc835..dde321b9a 100644 --- a/Samples/Controls.Net4/Common/PropertyListCtrl.cs +++ b/Samples/Controls.Net4/Common/PropertyListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -45,8 +46,8 @@ public partial class PropertyListCtrl : Opc.Ua.Client.Controls.BaseListCtrl { public PropertyListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -57,13 +58,13 @@ public PropertyListCtrl() /// The columns to display in the control. /// private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Property", HorizontalAlignment.Left, null }, - new object[] { "Value", HorizontalAlignment.Left, "" }, - new object[] { "DataType", HorizontalAlignment.Left, null }, - new object[] { "Description", HorizontalAlignment.Left, null } - }; - #endregion + { + new object[] { "Property", HorizontalAlignment.Left, null }, + new object[] { "Value", HorizontalAlignment.Left, "" }, + new object[] { "DataType", HorizontalAlignment.Left, null }, + new object[] { "Description", HorizontalAlignment.Left, null } + }; + #endregion #region Public Interface /// @@ -71,10 +72,10 @@ public PropertyListCtrl() /// public bool ShowValues { - get { return m_showValues; } + get { return m_showValues; } set { m_showValues = value; } } - + /// /// Clears the contents of the control, /// @@ -87,44 +88,44 @@ public void Clear() /// /// Sets the nodes in the control. /// - public void Update(Session session, ReferenceDescription reference) + public async Task UpdateAsync(Session session, ReferenceDescription reference, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); if (reference == null) { - return; + return; } - + m_session = session; - AddProperties(reference.NodeId); + await AddPropertiesAsync(reference.NodeId, ct); AdjustColumns(); } - #endregion - + #endregion + #region NodeField Class /// /// A field associated with a node. /// - private class PropertyItem - { + private sealed class PropertyItem + { public ReferenceDescription Reference; - public VariableNode Property; + public VariableNode Property; } - #endregion + #endregion #region Private Methods /// /// Adds the properties to the control. /// - private void AddProperties(ExpandedNodeId nodeId) + private async Task AddPropertiesAsync(ExpandedNodeId nodeId, CancellationToken ct = default) { // get node. - Node node = m_session.NodeCache.Find(nodeId) as Node; + Node node = await m_session.NodeCache.FindAsync(nodeId, ct) as Node; if (node == null) { @@ -136,21 +137,21 @@ private void AddProperties(ExpandedNodeId nodeId) if (supertypeId != null) { - AddProperties(supertypeId); + await AddPropertiesAsync(supertypeId, ct); } // build list of properties to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); Browser browser = new Browser(m_session); - - browser.BrowseDirection = BrowseDirection.Forward; - browser.ReferenceTypeId = ReferenceTypeIds.HasProperty; - browser.IncludeSubtypes = true; - browser.NodeClassMask = (int)NodeClass.Variable; + + browser.BrowseDirection = BrowseDirection.Forward; + browser.ReferenceTypeId = ReferenceTypeIds.HasProperty; + browser.IncludeSubtypes = true; + browser.NodeClassMask = (int)NodeClass.Variable; browser.ContinueUntilDone = true; - ReferenceDescriptionCollection references = browser.Browse(node.NodeId); + ReferenceDescriptionCollection references = await browser.BrowseAsync(node.NodeId, ct); // add propertoes to view. foreach (ReferenceDescription reference in references) @@ -158,13 +159,13 @@ private void AddProperties(ExpandedNodeId nodeId) PropertyItem field = new PropertyItem(); field.Reference = reference; - field.Property = m_session.NodeCache.Find(reference.NodeId) as VariableNode; + field.Property = await m_session.NodeCache.FindAsync(reference.NodeId, ct) as VariableNode; AddItem(field, "Property", -1); } } - #endregion - + #endregion + #region Overridden Methods /// protected override object GetDataToDrag() @@ -186,25 +187,25 @@ protected override object GetDataToDrag() /// protected override void EnableMenuItems(ListViewItem clickedItem) - { + { PropertyItem[] items = GetSelectedItems(typeof(PropertyItem)) as PropertyItem[]; if (items != null && items.Length > 0) { SelectMI.Enabled = true; } - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item) + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - PropertyItem property = item as PropertyItem; + PropertyItem property = item as PropertyItem; - if (property == null) - { - base.UpdateItem(listItem, item); - return; - } + if (property == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } listItem.SubItems[0].Text = String.Format("{0}", property.Reference); listItem.SubItems[1].Text = ""; @@ -224,7 +225,7 @@ protected override void UpdateItem(ListViewItem listItem, object item) } } - INode node = m_session.NodeCache.Find(property.Property.DataType); + INode node = await m_session.NodeCache.FindAsync(property.Property.DataType, ct); if (node != null) { @@ -239,10 +240,10 @@ protected override void UpdateItem(ListViewItem listItem, object item) { listItem.SubItems[2].Text += "[]"; } - + listItem.SubItems[3].Text = String.Format("{0}", property.Property.Description); - listItem.Tag = item; + listItem.Tag = item; } #endregion @@ -254,7 +255,7 @@ private void SelectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/SelectNodesDlg.Designer.cs b/Samples/Controls.Net4/Common/SelectNodesDlg.Designer.cs index 10e804dac..3df22f483 100644 --- a/Samples/Controls.Net4/Common/SelectNodesDlg.Designer.cs +++ b/Samples/Controls.Net4/Common/SelectNodesDlg.Designer.cs @@ -136,7 +136,7 @@ private void InitializeComponent() this.BrowseCTRL.SessionTreeCtrl = null; this.BrowseCTRL.Size = new System.Drawing.Size(375, 285); this.BrowseCTRL.TabIndex = 1; - this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_NodesSelected); + this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_NodesSelectedAsync); // // AttributesCTRL // diff --git a/Samples/Controls.Net4/Common/SelectNodesDlg.cs b/Samples/Controls.Net4/Common/SelectNodesDlg.cs index e538e95a5..ed4369e2a 100644 --- a/Samples/Controls.Net4/Common/SelectNodesDlg.cs +++ b/Samples/Controls.Net4/Common/SelectNodesDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading; +using System.Threading.Tasks; namespace Opc.Ua.Sample.Controls { @@ -54,45 +56,46 @@ public SelectNodesDlg() #region Private Fields private Session m_session; #endregion - + #region Public Interface /// /// Displays the dialog. /// - public NodeIdCollection ShowDialog( - Session session, - BrowseViewType browseView, + public async Task ShowDialogAsync( + Session session, + BrowseViewType browseView, NodeIdCollection nodesIds, - NodeClass nodeClassMask) + NodeClass nodeClassMask, + CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); + if (session == null) throw new ArgumentNullException(nameof(session)); m_session = session; - BrowseCTRL.SetView(session, browseView, null); - NodeListCTRL.Initialize(session, nodesIds, nodeClassMask); - + await BrowseCTRL.SetViewAsync(session, browseView, null, ct); + await NodeListCTRL.InitializeAsync(session, nodesIds, nodeClassMask, ct); + if (ShowDialog() != DialogResult.OK) { return null; } - + return NodeListCTRL.GetNodeIds(); } #endregion - + #region Private Methods #endregion - + #region Event Handler - private void BrowseCTRL_NodesSelected(object sender, NodesSelectedEventArgs e) + private async void BrowseCTRL_NodesSelectedAsync(object sender, NodesSelectedEventArgs e) { try { foreach (ReferenceDescription reference in e.References) { - NodeListCTRL.AddNodeId(reference); - } + await NodeListCTRL.AddNodeIdAsync(reference); + } } catch (Exception exception) { diff --git a/Samples/Controls.Net4/SelectLocaleDlg.cs b/Samples/Controls.Net4/SelectLocaleDlg.cs index a647bc8ff..75a2296df 100644 --- a/Samples/Controls.Net4/SelectLocaleDlg.cs +++ b/Samples/Controls.Net4/SelectLocaleDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,8 @@ using System.Text; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -50,25 +52,25 @@ public SelectLocaleDlg() InitializeComponent(); } #endregion - + #region Private Fields private Session m_session; #endregion - + #region Public Interface /// /// Displays the available areas in a tree view. /// /// The session. /// - public string ShowDialog(Session session) + public async Task ShowDialogAsync(Session session, CancellationToken ct = default) { m_session = session; LocaleCB.Items.Clear(); // get the locales from the server. - DataValue value = m_session.ReadValue(VariableIds.Server_ServerCapabilities_LocaleIdArray); + DataValue value = await m_session.ReadValueAsync(VariableIds.Server_ServerCapabilities_LocaleIdArray, ct); if (value != null) { @@ -98,7 +100,7 @@ public string ShowDialog(Session session) return LocaleCB.SelectedItem as string; } #endregion - + #region Private Methods #endregion diff --git a/Samples/Controls.Net4/ServerForm.cs b/Samples/Controls.Net4/ServerForm.cs index b6bc593f8..1e32aac94 100644 --- a/Samples/Controls.Net4/ServerForm.cs +++ b/Samples/Controls.Net4/ServerForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -48,7 +48,7 @@ public ServerForm(StandardServer server, ApplicationConfiguration configuration) { InitializeComponent(); this.Icon = this.TrayIcon.Icon = ClientUtils.GetAppIcon(); - + GuiUtils.DisplayUaTcpImplementation(this, configuration); m_server = server; @@ -59,46 +59,46 @@ public ServerForm(StandardServer server, ApplicationConfiguration configuration) } } #endregion - + #region Private Fields private bool m_exit; private StandardServer m_server; #endregion - + #region Private Methods /// /// Shows the diagnostics window and starts the update timer. /// private void ShowStatus() - { + { this.WindowState = FormWindowState.Normal; this.BringToFront(); Timer.Enabled = true; } - + /// /// Hides the diagnostics window and starts the update timer. /// private void HideStatus() - { + { this.WindowState = FormWindowState.Minimized; Timer.Enabled = false; } - - /// - /// Displays an unhandled exception. - /// - public static void HandleException(string caption, MethodBase method, Exception e) - { + + /// + /// Displays an unhandled exception. + /// + public static void HandleException(string caption, MethodBase method, Exception e) + { if (String.IsNullOrEmpty(caption)) { caption = method.Name; } - MessageBox.Show(e.Message, caption); - } + MessageBox.Show(e.Message, caption); + } #endregion - + #region Event Handlers /// /// Handles a certificate validation error. @@ -111,7 +111,7 @@ void CertificateValidator_CertificateValidation(CertificateValidator validator, } catch (Exception exception) { - Opc.Ua.Client.Controls.GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + Opc.Ua.Client.Controls.GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -125,11 +125,11 @@ private void TrayIcon_DoubleClick(object sender, EventArgs e) { try { - ShowStatus(); + ShowStatus(); } catch (Exception exception) { - HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -141,11 +141,11 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; HideStatus(); - } + } } catch (Exception exception) { - HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -153,11 +153,11 @@ private void ShowMI_Click(object sender, EventArgs e) { try { - ShowStatus(); + ShowStatus(); } catch (Exception exception) { - HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -165,15 +165,17 @@ private void Timer_Tick(object sender, EventArgs e) { try { +#pragma warning disable CS0618 // Type or member is obsolete ServerStatusDataType status = m_server.GetStatus(); +#pragma warning restore CS0618 // Type or member is obsolete - StartTimeTB.Text = Utils.Format("{0:HH:mm:ss.ff}", status.StartTime.ToLocalTime()); + StartTimeTB.Text = Utils.Format("{0:HH:mm:ss.ff}", status.StartTime.ToLocalTime()); CurrentTimeTB.Text = Utils.Format("{0:HH:mm:ss.ff}", status.CurrentTime.ToLocalTime()); ServerStateTB.Text = Utils.Format("{0}", status.State); } catch (Exception exception) { - HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Sessions/AddressSpaceDlg.cs b/Samples/Controls.Net4/Sessions/AddressSpaceDlg.cs index 20c3cf450..38c963360 100644 --- a/Samples/Controls.Net4/Sessions/AddressSpaceDlg.cs +++ b/Samples/Controls.Net4/Sessions/AddressSpaceDlg.cs @@ -33,6 +33,7 @@ using System.Data; using System.Drawing; using System.Text; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua.Client; @@ -50,9 +51,9 @@ public AddressSpaceDlg() m_SessionClosing = new EventHandler(Session_Closing); } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; private EventHandler m_SessionClosing; #endregion @@ -61,23 +62,23 @@ public AddressSpaceDlg() /// Displays the address space with the specified view /// public void Show(Session session, BrowseViewType viewType, NodeId viewId) - { - if (session == null) throw new ArgumentNullException("session"); - + { + if (session == null) throw new ArgumentNullException(nameof(session)); + if (m_session != null) { m_session.SessionClosing -= m_SessionClosing; } - m_session = session; + m_session = session; m_session.SessionClosing += m_SessionClosing; - - BrowseCTRL.SetView(session, viewType, viewId); + + BrowseCTRL.SetViewAsync(session, viewType, viewId); Show(); BringToFront(); } #endregion - + private void Session_Closing(object sender, EventArgs e) { if (Object.ReferenceEquals(sender, m_session)) diff --git a/Samples/Controls.Net4/Sessions/BrowseDlg.Designer.cs b/Samples/Controls.Net4/Sessions/BrowseDlg.Designer.cs index 3412c0335..f84049abe 100644 --- a/Samples/Controls.Net4/Sessions/BrowseDlg.Designer.cs +++ b/Samples/Controls.Net4/Sessions/BrowseDlg.Designer.cs @@ -87,7 +87,7 @@ private void InitializeComponent() this.BrowseCTRL.Size = new System.Drawing.Size(696, 372); this.BrowseCTRL.TabIndex = 0; this.BrowseCTRL.PositionChanged += new System.EventHandler(this.BrowseCTRL_PositionChanged); - this.BrowseCTRL.PositionAdded += new System.EventHandler(this.BrowseCTRL_PositionAdded); + this.BrowseCTRL.PositionAdded += new System.EventHandler(this.BrowseCTRL_PositionAddedAsync); // // TopPN // @@ -111,7 +111,7 @@ private void InitializeComponent() this.NodeCTRL.Name = "NodeCTRL"; this.NodeCTRL.Size = new System.Drawing.Size(642, 21); this.NodeCTRL.TabIndex = 2; - this.NodeCTRL.SelectedIndexChanged += new System.EventHandler(this.NodeCTRL_SelectedIndexChanged); + this.NodeCTRL.SelectedIndexChanged += new System.EventHandler(this.NodeCTRL_SelectedIndexChangedAsync); // // ForwardBTN // @@ -122,7 +122,7 @@ private void InitializeComponent() this.ForwardBTN.TabIndex = 1; this.ForwardBTN.Text = ">"; this.ForwardBTN.UseVisualStyleBackColor = true; - this.ForwardBTN.Click += new System.EventHandler(this.ForwardBTN_Click); + this.ForwardBTN.Click += new System.EventHandler(this.ForwardBTN_ClickAsync); // // BackBTN // @@ -132,7 +132,7 @@ private void InitializeComponent() this.BackBTN.TabIndex = 0; this.BackBTN.Text = "<"; this.BackBTN.UseVisualStyleBackColor = true; - this.BackBTN.Click += new System.EventHandler(this.BackBTN_Click); + this.BackBTN.Click += new System.EventHandler(this.BackBTN_ClickAsync); // // BrowseDlg // diff --git a/Samples/Controls.Net4/Sessions/BrowseDlg.cs b/Samples/Controls.Net4/Sessions/BrowseDlg.cs index 4464c8f25..8ef105354 100644 --- a/Samples/Controls.Net4/Sessions/BrowseDlg.cs +++ b/Samples/Controls.Net4/Sessions/BrowseDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -51,7 +53,7 @@ public BrowseDlg() m_SessionClosing = new EventHandler(Session_Closing); } #endregion - + #region Private Fields private Session m_session; private EventHandler m_SessionClosing; @@ -61,27 +63,27 @@ public BrowseDlg() /// /// Displays the address space with the specified view /// - public void Show(Session session, NodeId startId) - { - if (session == null) throw new ArgumentNullException("session"); - + public async Task ShowAsync(Session session, NodeId startId, CancellationToken ct = default) + { + if (session == null) throw new ArgumentNullException(nameof(session)); + if (m_session != null) { m_session.SessionClosing -= m_SessionClosing; } - m_session = session; + m_session = session; m_session.SessionClosing += m_SessionClosing; - - Browser browser = new Browser(session); + + Browser browser = new Browser(session); browser.BrowseDirection = BrowseDirection.Both; browser.ContinueUntilDone = true; browser.ReferenceTypeId = ReferenceTypeIds.References; - BrowseCTRL.Initialize(browser, startId); - - UpdateNavigationBar(); + await BrowseCTRL.InitializeAsync(browser, startId, ct); + + await UpdateNavigationBarAsync(ct); Show(); BringToFront(); @@ -91,15 +93,15 @@ public void Show(Session session, NodeId startId) /// /// Updates the navigation bar with the current positions in the browse control. /// - private void UpdateNavigationBar() + private async Task UpdateNavigationBarAsync(CancellationToken ct = default) { int index = 0; foreach (NodeId nodeId in BrowseCTRL.Positions) { - Node node = m_session.NodeCache.Find(nodeId) as Node; + Node node = await m_session.NodeCache.FindAsync(nodeId, ct) as Node; - string displayText = m_session.NodeCache.GetDisplayText(node); + string displayText = await m_session.NodeCache.GetDisplayTextAsync(node, ct); if (index < NodeCTRL.Items.Count) { @@ -114,16 +116,16 @@ private void UpdateNavigationBar() } index++; - } - + } + while (index < NodeCTRL.Items.Count) { - NodeCTRL.Items.RemoveAt(NodeCTRL.Items.Count-1); + NodeCTRL.Items.RemoveAt(NodeCTRL.Items.Count - 1); } - + NodeCTRL.SelectedIndex = BrowseCTRL.Position; } - + private void Session_Closing(object sender, EventArgs e) { if (Object.ReferenceEquals(sender, m_session)) @@ -143,44 +145,44 @@ private void AddressSpaceDlg_FormClosing(object sender, FormClosingEventArgs e) } } - private void BackBTN_Click(object sender, EventArgs e) + private async void BackBTN_ClickAsync(object sender, EventArgs e) { try - { - BrowseCTRL.Back(); + { + await BrowseCTRL.BackAsync(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void ForwardBTN_Click(object sender, EventArgs e) + private async void ForwardBTN_ClickAsync(object sender, EventArgs e) { try - { - BrowseCTRL.Forward(); + { + await BrowseCTRL.ForwardAsync(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void NodeCTRL_SelectedIndexChanged(object sender, EventArgs e) - { + private async void NodeCTRL_SelectedIndexChangedAsync(object sender, EventArgs e) + { try - { - BrowseCTRL.SetPosition(NodeCTRL.SelectedIndex); + { + await BrowseCTRL.SetPositionAsync(NodeCTRL.SelectedIndex); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void BrowseCTRL_PositionChanged(object sender, EventArgs e) - { + { try { if (BrowseCTRL.Position < NodeCTRL.Items.Count) @@ -190,23 +192,23 @@ private void BrowseCTRL_PositionChanged(object sender, EventArgs e) else { NodeCTRL.SelectedIndex = -1; - } + } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void BrowseCTRL_PositionAdded(object sender, EventArgs e) + private async void BrowseCTRL_PositionAddedAsync(object sender, EventArgs e) { try { - UpdateNavigationBar(); + await UpdateNavigationBarAsync(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Sessions/BrowseListCtrl.cs b/Samples/Controls.Net4/Sessions/BrowseListCtrl.cs index c1b879625..d8a600b6b 100644 --- a/Samples/Controls.Net4/Sessions/BrowseListCtrl.cs +++ b/Samples/Controls.Net4/Sessions/BrowseListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -49,18 +51,18 @@ public partial class BrowseListCtrl : Opc.Ua.Client.Controls.BaseListCtrl /// public BrowseListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); ItemsLV.Sorting = SortOrder.Ascending; m_stack = new List(); m_position = -1; } - #endregion + #endregion #region Private Fields - private Session m_session; + private ISession m_session; private Browser m_browser; private NodeId m_startId; private List m_stack; @@ -72,13 +74,13 @@ public BrowseListCtrl() /// The columns to display in the control. ///
private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "ReferenceType", HorizontalAlignment.Left, null }, - new object[] { "Node", HorizontalAlignment.Left, null }, - new object[] { "Type", HorizontalAlignment.Left, null }, - new object[] { "Value", HorizontalAlignment.Left, null } - }; - #endregion + { + new object[] { "ReferenceType", HorizontalAlignment.Left, null }, + new object[] { "Node", HorizontalAlignment.Left, null }, + new object[] { "Type", HorizontalAlignment.Left, null }, + new object[] { "Value", HorizontalAlignment.Left, null } + }; + #endregion #region Public Interface /// @@ -105,8 +107,8 @@ public event EventHandler PositionAdded [DefaultValue(-1)] public int Position { - get { return m_position+1; } - set { SetPosition(value-1); } + get { return m_position + 1; } + set { SetPositionAsync(value - 1).GetAwaiter().GetResult(); } } /// @@ -115,7 +117,7 @@ public int Position public ICollection Positions { get - { + { List positions = new List(); positions.Add(m_startId); @@ -141,49 +143,49 @@ public void Clear() /// /// Initializes the control with the session/subscription indicated. /// - public void Initialize(Browser browser, NodeId startId) + public async Task InitializeAsync(Browser browser, NodeId startId, CancellationToken ct = default) { m_browser = null; m_session = null; - + Clear(); // nothing to do if no browser provided. if (browser == null) { return; - } - - m_browser = browser; - m_session = browser.Session as Session; - m_startId = startId; + } + + m_browser = browser; + m_session = browser.Session as Session; + m_startId = startId; m_position = -1; - + m_stack.Clear(); - Browse(startId); + await BrowseAsync(startId, ct); } /// /// Moves to the previous position. /// - public void Back() + public async Task BackAsync(CancellationToken ct = default) { - SetPosition(m_position); + await SetPositionAsync(m_position, ct); } /// /// Moves to the next position. /// - public void Forward() + public async Task ForwardAsync(CancellationToken ct = default) { - SetPosition(m_position+2); + await SetPositionAsync(m_position + 2, ct); } /// /// Sets the current position. /// - public void SetPosition(int position) + public async Task SetPositionAsync(int position, CancellationToken ct = default) { position--; @@ -194,23 +196,23 @@ public void SetPosition(int position) if (position >= m_stack.Count) { - position = m_stack.Count-1; + position = m_stack.Count - 1; } if (m_position == position) { return; } - + m_position = position; - + if (m_position == -1) { - Browse(m_startId); - } + await BrowseAsync(m_startId, ct); + } else { - Browse(m_stack[m_position].Target.NodeId); + await BrowseAsync(m_stack[m_position].Target.NodeId, ct); } if (m_PositionChanged != null) @@ -222,44 +224,44 @@ public void SetPosition(int position) /// /// Displays the target of a browse operation in the control. /// - private void Browse(NodeId startId) + private async Task BrowseAsync(NodeId startId, CancellationToken ct = default) { if (m_browser == null || NodeId.IsNull(startId)) - { + { Clear(); return; } - + List variables = new List(); - + // browse the references from the node and build list of variables. BeginUpdate(); - foreach (ReferenceDescription reference in m_browser.Browse(startId)) + foreach (ReferenceDescription reference in await m_browser.BrowseAsync(startId, ct)) { - Node target = m_session.NodeCache.Find(reference.NodeId) as Node; + Node target = await m_session.NodeCache.FindAsync(reference.NodeId, ct) as Node; if (target == null) { continue; } - ReferenceTypeNode referenceType = m_session.NodeCache.Find(reference.ReferenceTypeId) as ReferenceTypeNode; + ReferenceTypeNode referenceType = await m_session.NodeCache.FindAsync(reference.ReferenceTypeId, ct) as ReferenceTypeNode; Node typeDefinition = null; if ((target.NodeClass & (NodeClass.Variable | NodeClass.Object)) != 0) { - typeDefinition = m_session.NodeCache.Find(reference.TypeDefinition) as Node; + typeDefinition = await m_session.NodeCache.FindAsync(reference.TypeDefinition, ct) as Node; } else { - typeDefinition = m_session.NodeCache.Find(m_session.NodeCache.TypeTree.FindSuperType(target.NodeId)) as Node; + typeDefinition = await m_session.NodeCache.FindAsync(await m_session.NodeCache.TypeTree.FindSuperTypeAsync(target.NodeId, ct), ct) as Node; } ItemData item = new ItemData(referenceType, !reference.IsForward, target, typeDefinition); - AddItem(item, GuiUtils.GetTargetIcon(m_browser.Session as Session, reference), -1); - + AddItem(item, await GuiUtils.GetTargetIconAsync(m_browser.Session as Session, reference, ct), -1); + if ((target.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) != 0) { variables.Add(item); @@ -272,42 +274,41 @@ private void Browse(NodeId startId) if (variables.Count > 0) { ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); - + foreach (ItemData item in variables) { ReadValueId valueId = new ReadValueId(); - valueId.NodeId = item.Target.NodeId; - valueId.AttributeId = Attributes.Value; - valueId.IndexRange = null; + valueId.NodeId = item.Target.NodeId; + valueId.AttributeId = Attributes.Value; + valueId.IndexRange = null; valueId.DataEncoding = null; nodesToRead.Add(valueId); } - - DataValueCollection values; - DiagnosticInfoCollection diagnosticInfos; - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out values, - out diagnosticInfos); + ct); + + DataValueCollection values = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(values, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); - + for (int ii = 0; ii < variables.Count; ii++) { variables[ii].Value = values[ii]; - + foreach (ListViewItem item in ItemsLV.Items) { if (Object.ReferenceEquals(item.Tag, variables[ii])) { - UpdateItem(item, variables[ii]); + await UpdateItemAsync(item, variables[ii], ct); break; } } @@ -317,12 +318,12 @@ private void Browse(NodeId startId) AdjustColumns(); } #endregion - + #region ItemData Class /// /// Stores the data associated with a list view item. /// - private class ItemData : IComparable + private sealed class ItemData : IComparable { public ReferenceTypeNode ReferenceType; public bool IsInverse; @@ -330,12 +331,12 @@ private class ItemData : IComparable public Node TypeDefinition; public DataValue Value; public string SortKey; - + public ItemData(ReferenceTypeNode referenceType, bool isInverse, Node target, Node typeDefinition) { - ReferenceType = referenceType; - IsInverse = isInverse; - Target = target; + ReferenceType = referenceType; + IsInverse = isInverse; + Target = target; TypeDefinition = typeDefinition; } @@ -366,92 +367,99 @@ public int CompareTo(object obj) #region Overridden Methods /// protected override void EnableMenuItems(ListViewItem clickedItem) - { + { // TBD - } + } /// /// Handles a double click. /// - protected override void PickItems() + protected override async void PickItems() { - if (ItemsLV.SelectedItems.Count <= 0) + try { - return; - } + if (ItemsLV.SelectedItems.Count <= 0) + { + return; + } - ItemData itemData = ItemsLV.SelectedItems[0].Tag as ItemData; - - if (itemData == null) - { - return; - } + ItemData itemData = ItemsLV.SelectedItems[0].Tag as ItemData; - base.PickItems(); - - if (m_position >= 0 && m_position < m_stack.Count-1) - { - m_stack.RemoveRange(m_position, m_stack.Count-m_position); - } - else if (m_position == -1) - { - m_stack.Clear(); - } - - m_position++; - m_stack.Add(itemData); + if (itemData == null) + { + return; + } + + base.PickItems(); + + if (m_position >= 0 && m_position < m_stack.Count - 1) + { + m_stack.RemoveRange(m_position, m_stack.Count - m_position); + } + else if (m_position == -1) + { + m_stack.Clear(); + } + + m_position++; + m_stack.Add(itemData); - if (m_PositionAdded != null) + if (m_PositionAdded != null) + { + m_PositionAdded(this, null); + } + + await BrowseAsync(itemData.Target.NodeId); + } + catch (Exception exception) { - m_PositionAdded(this, null); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } - - Browse(itemData.Target.NodeId); } - /// - protected override void UpdateItem(ListViewItem listItem, object item) + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { ItemData itemData = item as ItemData; - if (itemData == null) - { - base.UpdateItem(listItem, item); - return; - } + if (itemData == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } if (itemData.ReferenceType != null) { if (itemData.IsInverse) { - listItem.SubItems[0].Text = String.Format("{0}", itemData.ReferenceType.InverseName); + listItem.SubItems[0].Text = String.Format("{0}", itemData.ReferenceType.InverseName); } else { - listItem.SubItems[0].Text = String.Format("{0}", itemData.ReferenceType.DisplayName); + listItem.SubItems[0].Text = String.Format("{0}", itemData.ReferenceType.DisplayName); } } else { listItem.SubItems[0].Text = "(unknown)"; } - - listItem.SubItems[1].Text = String.Format("{0}", itemData.Target); - listItem.SubItems[2].Text = String.Format("{0}", itemData.TypeDefinition); + + listItem.SubItems[1].Text = String.Format("{0}", itemData.Target); + listItem.SubItems[2].Text = String.Format("{0}", itemData.TypeDefinition); if (itemData.Value != null) { - listItem.SubItems[3].Text = String.Format("{0}", itemData.Value); + listItem.SubItems[3].Text = String.Format("{0}", itemData.Value); } else { - listItem.SubItems[3].Text = String.Empty; + listItem.SubItems[3].Text = String.Empty; } - + itemData.SortKey = String.Format("{0}{1}", listItem.SubItems[0].Text, listItem.SubItems[1].Text); - listItem.Tag = item; + listItem.Tag = item; } - #endregion + #endregion } } diff --git a/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.Designer.cs b/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.Designer.cs index f43a25348..5d380aca1 100644 --- a/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.Designer.cs +++ b/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.Designer.cs @@ -223,7 +223,7 @@ private void InitializeComponent() this.BrowseBTN.TabIndex = 17; this.BrowseBTN.Text = "..."; this.BrowseBTN.UseVisualStyleBackColor = true; - this.BrowseBTN.Click += new System.EventHandler(this.BrowseBTN_Click); + this.BrowseBTN.Click += new System.EventHandler(this.BrowseBTN_ClickAsync); // // ViewIdTB // diff --git a/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.cs b/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.cs index 0c09b46cd..e8ce9b04c 100644 --- a/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.cs +++ b/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -57,44 +59,44 @@ public BrowseOptionsDlg() BrowseDirectionCB.SelectedIndex = 0; } #endregion - + #region Private Fields private Browser m_browser; #endregion - + #region Public Interface /// /// Prompts the user to specify the browse options. /// - public bool ShowDialog(Browser browser) + public async Task ShowDialogAsync(Browser browser, CancellationToken ct = default) { - if (browser == null) throw new ArgumentNullException("browser"); + if (browser == null) throw new ArgumentNullException(nameof(browser)); m_browser = browser; - ReferenceTypeCTRL.Initialize(m_browser.Session as Session, null); + await ReferenceTypeCTRL.InitializeAsync(m_browser.Session as Session, null, ct); - ViewIdTB.Text = null; + ViewIdTB.Text = null; ViewTimestampDP.Value = ViewTimestampDP.MinDate; - ViewVersionNC.Value = 0; + ViewVersionNC.Value = 0; if (browser.View != null) { - ViewIdTB.Text = String.Format("{0}", browser.View.ViewId); - ViewVersionNC.Value = browser.View.ViewVersion; + ViewIdTB.Text = String.Format("{0}", browser.View.ViewId); + ViewVersionNC.Value = browser.View.ViewVersion; ViewVersionCK.Checked = browser.View.ViewVersion != 0; if (browser.View.Timestamp > ViewTimestampDP.MinDate) - { - ViewTimestampDP.Value = browser.View.Timestamp ; + { + ViewTimestampDP.Value = browser.View.Timestamp; ViewTimestampCK.Checked = true; } } - MaxReferencesReturnedNC.Value = browser.MaxReferencesReturned; - BrowseDirectionCB.SelectedItem = browser.BrowseDirection; + MaxReferencesReturnedNC.Value = browser.MaxReferencesReturned; + BrowseDirectionCB.SelectedItem = browser.BrowseDirection; ReferenceTypeCTRL.SelectedTypeId = browser.ReferenceTypeId; - IncludeSubtypesCK.Checked = browser.IncludeSubtypes; - NodeClassMaskCK.Checked = browser.NodeClassMask != 0; + IncludeSubtypesCK.Checked = browser.IncludeSubtypes; + NodeClassMaskCK.Checked = browser.NodeClassMask != 0; NodeClassList.Items.Clear(); @@ -117,7 +119,7 @@ public bool ShowDialog(Browser browser) return true; } #endregion - + #region Event Handlers private void ViewIdTB_TextChanged(object sender, EventArgs e) { @@ -125,8 +127,8 @@ private void ViewIdTB_TextChanged(object sender, EventArgs e) } private void NodeClassMask_CheckedChanged(object sender, EventArgs e) - { - NodeClassList.Enabled = NodeClassMaskCK.Checked; + { + NodeClassList.Enabled = NodeClassMaskCK.Checked; } private void ViewVersionCK_CheckedChanged(object sender, EventArgs e) @@ -139,24 +141,24 @@ private void ViewTimestampCK_CheckedChanged(object sender, EventArgs e) ViewTimestampDP.Enabled = ViewTimestampCK.Checked; } - private void BrowseBTN_Click(object sender, EventArgs e) + private async void BrowseBTN_ClickAsync(object sender, EventArgs e) { try { Browser browser = new Browser(m_browser.Session); browser.BrowseDirection = BrowseDirection.Forward; - browser.NodeClassMask = (int)NodeClass.View | (int)NodeClass.Object; + browser.NodeClassMask = (int)NodeClass.View | (int)NodeClass.Object; browser.ReferenceTypeId = ReferenceTypeIds.Organizes; browser.IncludeSubtypes = true; - ReferenceDescription reference = new SelectNodeDlg().ShowDialog(browser, Objects.ViewsFolder); + ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync(browser, Objects.ViewsFolder); if (reference != null) { if (reference.NodeClass != NodeClass.View) { - MessageBox.Show("Please select a valid view node id.", this.Text); + MessageBox.Show("Please select a valid view node id.", this.Text); return; } @@ -165,7 +167,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -179,9 +181,9 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception) { - MessageBox.Show("Please enter a valid node id for the view id.", this.Text); + MessageBox.Show("Please enter a valid node id for the view id.", this.Text); } - + try { ViewDescription view = null; @@ -190,28 +192,28 @@ private void OkBTN_Click(object sender, EventArgs e) { view = new ViewDescription(); - view.ViewId = viewId; - view.Timestamp = DateTime.MinValue; + view.ViewId = viewId; + view.Timestamp = DateTime.MinValue; view.ViewVersion = 0; if (ViewTimestampCK.Checked && ViewTimestampDP.Value > ViewTimestampDP.MinDate) { view.Timestamp = ViewTimestampDP.Value; } - + if (ViewVersionCK.Checked) { view.ViewVersion = (uint)ViewVersionNC.Value; } } - m_browser.View = view; + m_browser.View = view; m_browser.MaxReferencesReturned = (uint)MaxReferencesReturnedNC.Value; - m_browser.BrowseDirection = (BrowseDirection)BrowseDirectionCB.SelectedItem; - m_browser.NodeClassMask = (int)NodeClass.View | (int)NodeClass.Object; - m_browser.ReferenceTypeId = ReferenceTypeCTRL.SelectedTypeId; - m_browser.IncludeSubtypes = IncludeSubtypesCK.Checked; - m_browser.NodeClassMask = 0; + m_browser.BrowseDirection = (BrowseDirection)BrowseDirectionCB.SelectedItem; + m_browser.NodeClassMask = (int)NodeClass.View | (int)NodeClass.Object; + m_browser.ReferenceTypeId = ReferenceTypeCTRL.SelectedTypeId; + m_browser.IncludeSubtypes = IncludeSubtypesCK.Checked; + m_browser.NodeClassMask = 0; int nodeClassMask = 0; @@ -221,12 +223,12 @@ private void OkBTN_Click(object sender, EventArgs e) } m_browser.NodeClassMask = nodeClassMask; - + DialogResult = DialogResult.OK; } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.Designer.cs b/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.Designer.cs index d73d929a0..182efa590 100644 --- a/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.Designer.cs +++ b/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.Designer.cs @@ -68,7 +68,6 @@ private void InitializeComponent() this.HistoryReadMI = new System.Windows.Forms.ToolStripMenuItem(); this.WriteMI = new System.Windows.Forms.ToolStripMenuItem(); this.HistoryUpdateMI = new System.Windows.Forms.ToolStripMenuItem(); - this.EncodingsMI = new System.Windows.Forms.ToolStripMenuItem(); this.SubscribeMI = new System.Windows.Forms.ToolStripMenuItem(); this.SubscribeNewMI = new System.Windows.Forms.ToolStripMenuItem(); this.CallMI = new System.Windows.Forms.ToolStripMenuItem(); @@ -85,9 +84,11 @@ private void InitializeComponent() // this.NodesTV.ContextMenuStrip = this.PopupMenu; this.NodesTV.LineColor = System.Drawing.Color.Black; + this.NodesTV.Size = new System.Drawing.Size(896, 733); // // PopupMenu // + this.PopupMenu.ImageScalingSize = new System.Drawing.Size(28, 28); this.PopupMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.BrowseOptionsMI, this.ShowReferencesMI, @@ -98,7 +99,6 @@ private void InitializeComponent() this.HistoryReadMI, this.WriteMI, this.HistoryUpdateMI, - this.EncodingsMI, this.SubscribeMI, this.CallMI, this.Separator02, @@ -106,14 +106,14 @@ private void InitializeComponent() this.SelectSeparatorMI, this.BrowseRefreshMI}); this.PopupMenu.Name = "PopupMenu"; - this.PopupMenu.Size = new System.Drawing.Size(162, 330); + this.PopupMenu.Size = new System.Drawing.Size(271, 492); // // BrowseOptionsMI // this.BrowseOptionsMI.Name = "BrowseOptionsMI"; - this.BrowseOptionsMI.Size = new System.Drawing.Size(161, 22); + this.BrowseOptionsMI.Size = new System.Drawing.Size(270, 36); this.BrowseOptionsMI.Text = "Browse Options..."; - this.BrowseOptionsMI.Click += new System.EventHandler(this.BrowseOptionsMI_Click); + this.BrowseOptionsMI.Click += new System.EventHandler(this.BrowseOptionsMI_ClickAsync); // // ShowReferencesMI // @@ -121,89 +121,82 @@ private void InitializeComponent() this.ShowReferencesMI.CheckOnClick = true; this.ShowReferencesMI.CheckState = System.Windows.Forms.CheckState.Checked; this.ShowReferencesMI.Name = "ShowReferencesMI"; - this.ShowReferencesMI.Size = new System.Drawing.Size(161, 22); + this.ShowReferencesMI.Size = new System.Drawing.Size(270, 36); this.ShowReferencesMI.Text = "Show References"; - this.ShowReferencesMI.CheckedChanged += new System.EventHandler(this.ShowReferencesMI_CheckedChanged); + this.ShowReferencesMI.CheckedChanged += new System.EventHandler(this.ShowReferencesMI_CheckedChangedAsync); // // Separator01 // this.Separator01.Name = "Separator01"; - this.Separator01.Size = new System.Drawing.Size(158, 6); + this.Separator01.Size = new System.Drawing.Size(267, 6); // // BrowseMI // this.BrowseMI.Name = "BrowseMI"; - this.BrowseMI.Size = new System.Drawing.Size(161, 22); + this.BrowseMI.Size = new System.Drawing.Size(270, 36); this.BrowseMI.Text = "Browse..."; - this.BrowseMI.Click += new System.EventHandler(this.BrowseMI_Click); + this.BrowseMI.Click += new System.EventHandler(this.BrowseMI_ClickAsync); // // ViewAttributesMI // this.ViewAttributesMI.Name = "ViewAttributesMI"; - this.ViewAttributesMI.Size = new System.Drawing.Size(161, 22); + this.ViewAttributesMI.Size = new System.Drawing.Size(270, 36); this.ViewAttributesMI.Text = "View Attributes..."; - this.ViewAttributesMI.Click += new System.EventHandler(this.ViewAttributesMI_Click); + this.ViewAttributesMI.Click += new System.EventHandler(this.ViewAttributesMI_ClickAsync); // // ReadMI // this.ReadMI.Name = "ReadMI"; - this.ReadMI.Size = new System.Drawing.Size(161, 22); + this.ReadMI.Size = new System.Drawing.Size(270, 36); this.ReadMI.Text = "Read.."; - this.ReadMI.Click += new System.EventHandler(this.ReadMI_Click); + this.ReadMI.Click += new System.EventHandler(this.ReadMI_ClickAsync); // // HistoryReadMI // this.HistoryReadMI.Name = "HistoryReadMI"; - this.HistoryReadMI.Size = new System.Drawing.Size(161, 22); + this.HistoryReadMI.Size = new System.Drawing.Size(270, 36); this.HistoryReadMI.Text = "History Read..."; - this.HistoryReadMI.Click += new System.EventHandler(this.HistoryReadMI_Click); + this.HistoryReadMI.Click += new System.EventHandler(this.HistoryReadMI_ClickAsync); // // WriteMI // this.WriteMI.Name = "WriteMI"; - this.WriteMI.Size = new System.Drawing.Size(161, 22); + this.WriteMI.Size = new System.Drawing.Size(270, 36); this.WriteMI.Text = "Write..."; - this.WriteMI.Click += new System.EventHandler(this.WriteMI_Click); + this.WriteMI.Click += new System.EventHandler(this.WriteMI_ClickAsync); // // HistoryUpdateMI // this.HistoryUpdateMI.Name = "HistoryUpdateMI"; - this.HistoryUpdateMI.Size = new System.Drawing.Size(161, 22); + this.HistoryUpdateMI.Size = new System.Drawing.Size(270, 36); this.HistoryUpdateMI.Text = "History Update..."; // - // EncodingsMI - // - this.EncodingsMI.Name = "EncodingsMI"; - this.EncodingsMI.Size = new System.Drawing.Size(161, 22); - this.EncodingsMI.Text = "View Encodings..."; - this.EncodingsMI.Click += new System.EventHandler(this.EncodingsMI_Click); - // // SubscribeMI // this.SubscribeMI.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.SubscribeNewMI}); this.SubscribeMI.Name = "SubscribeMI"; - this.SubscribeMI.Size = new System.Drawing.Size(161, 22); + this.SubscribeMI.Size = new System.Drawing.Size(270, 36); this.SubscribeMI.Text = "Subscribe"; // // SubscribeNewMI // this.SubscribeNewMI.Name = "SubscribeNewMI"; - this.SubscribeNewMI.Size = new System.Drawing.Size(152, 22); + this.SubscribeNewMI.Size = new System.Drawing.Size(315, 40); this.SubscribeNewMI.Text = "New..."; - this.SubscribeNewMI.Click += new System.EventHandler(this.SubscribeNewMI_Click); + this.SubscribeNewMI.Click += new System.EventHandler(this.SubscribeNewMI_ClickAsync); // // CallMI // this.CallMI.Name = "CallMI"; - this.CallMI.Size = new System.Drawing.Size(161, 22); + this.CallMI.Size = new System.Drawing.Size(270, 36); this.CallMI.Text = "Call..."; - this.CallMI.Click += new System.EventHandler(this.CallMI_Click); + this.CallMI.Click += new System.EventHandler(this.CallMI_ClickAsync); // // Separator02 // this.Separator02.Name = "Separator02"; - this.Separator02.Size = new System.Drawing.Size(158, 6); + this.Separator02.Size = new System.Drawing.Size(267, 6); // // SelectMI // @@ -211,38 +204,39 @@ private void InitializeComponent() this.SelectItemMI, this.SelectChildrenMI}); this.SelectMI.Name = "SelectMI"; - this.SelectMI.Size = new System.Drawing.Size(161, 22); + this.SelectMI.Size = new System.Drawing.Size(270, 36); this.SelectMI.Text = "Select"; // // SelectItemMI // this.SelectItemMI.Name = "SelectItemMI"; - this.SelectItemMI.Size = new System.Drawing.Size(145, 22); + this.SelectItemMI.Size = new System.Drawing.Size(269, 40); this.SelectItemMI.Text = "Select Item"; this.SelectItemMI.Click += new System.EventHandler(this.SelectItemMI_Click); // // SelectChildrenMI // this.SelectChildrenMI.Name = "SelectChildrenMI"; - this.SelectChildrenMI.Size = new System.Drawing.Size(145, 22); + this.SelectChildrenMI.Size = new System.Drawing.Size(269, 40); this.SelectChildrenMI.Text = "Select Children"; this.SelectChildrenMI.Click += new System.EventHandler(this.SelectChildrenMI_Click); // // SelectSeparatorMI // this.SelectSeparatorMI.Name = "SelectSeparatorMI"; - this.SelectSeparatorMI.Size = new System.Drawing.Size(158, 6); + this.SelectSeparatorMI.Size = new System.Drawing.Size(267, 6); // // BrowseRefreshMI // this.BrowseRefreshMI.Name = "BrowseRefreshMI"; - this.BrowseRefreshMI.Size = new System.Drawing.Size(161, 22); + this.BrowseRefreshMI.Size = new System.Drawing.Size(270, 36); this.BrowseRefreshMI.Text = "Refresh"; - this.BrowseRefreshMI.Click += new System.EventHandler(this.BrowseRefreshMI_Click); + this.BrowseRefreshMI.Click += new System.EventHandler(this.BrowseRefreshMI_ClickAsync); // // BrowseTreeCtrl // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 24F); + this.Margin = new System.Windows.Forms.Padding(11, 11, 11, 11); this.Name = "BrowseTreeCtrl"; this.Controls.SetChildIndex(this.NodesTV, 0); this.PopupMenu.ResumeLayout(false); @@ -268,7 +262,6 @@ private void InitializeComponent() private System.Windows.Forms.ToolStripMenuItem WriteMI; private System.Windows.Forms.ToolStripMenuItem ReadMI; private System.Windows.Forms.ToolStripMenuItem SubscribeNewMI; - private System.Windows.Forms.ToolStripMenuItem EncodingsMI; private System.Windows.Forms.ToolStripMenuItem HistoryReadMI; private System.Windows.Forms.ToolStripMenuItem HistoryUpdateMI; private System.Windows.Forms.ToolStripMenuItem BrowseMI; diff --git a/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.cs b/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.cs index b6a0ddabd..a67db1246 100644 --- a/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.cs +++ b/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -48,7 +50,7 @@ public BrowseTreeCtrl() { InitializeComponent(); m_references = new ReferenceDescriptionCollection(); - m_BrowserMoreReferences = new BrowserEventHandler(Browser_MoreReferences); + m_BrowserMoreReferences = new BrowserEventHandler(Browser_MoreReferencesAsync); } #endregion @@ -66,14 +68,14 @@ public BrowseTreeCtrl() private BrowserEventHandler m_BrowserMoreReferences; private SessionTreeCtrl m_SessionTreeCtrl; #endregion - + #region Public Interface /// /// The control used to display the address space for a session. /// public SessionTreeCtrl SessionTreeCtrl { - get { return m_SessionTreeCtrl; } + get { return m_SessionTreeCtrl; } set { m_SessionTreeCtrl = value; } } @@ -83,32 +85,32 @@ public SessionTreeCtrl SessionTreeCtrl [DefaultValue(false)] public bool AllowPick { - get { return m_allowPick; } + get { return m_allowPick; } set { m_allowPick = value; } } - + /// /// Whether references should be displayed in the control. /// [DefaultValue(false)] public bool ShowReferences { - get { return m_showReferences; } + get { return m_showReferences; } set { m_showReferences = value; } } - + /// /// Whether references should be displayed in the control. /// public ReferenceDescriptionCollection SelectedReferences { - get - { + get + { return m_references; } - set - { + set + { m_references = value; if (m_references == null) @@ -123,16 +125,16 @@ public ReferenceDescriptionCollection SelectedReferences /// public AttributeListCtrl AttributesCtrl { - get { return m_AttributesCtrl; } + get { return m_AttributesCtrl; } set { m_AttributesCtrl = value; } } - + /// /// Raised when nodes are selected in the control. /// public event NodesSelectedEventHandler ItemsSelected { - add { m_ItemsSelected += value; } + add { m_ItemsSelected += value; } remove { m_ItemsSelected -= value; } } @@ -141,7 +143,7 @@ public event NodesSelectedEventHandler ItemsSelected /// public event MethodCalledEventHandler MethodCalled { - add { m_MethodCalled += value; } + add { m_MethodCalled += value; } remove { m_MethodCalled -= value; } } @@ -161,13 +163,13 @@ public void Clear() /// /// Sets the root node for the control. /// - public void SetRoot(Browser browser, NodeId rootId) - { + public async Task SetRootAsync(Browser browser, NodeId rootId, CancellationToken ct = default) + { Clear(); - + ShowReferencesMI.Checked = m_showReferences; - - m_rootId = rootId; + + m_rootId = rootId; m_browser = browser; if (m_browser != null) @@ -188,7 +190,7 @@ public void SetRoot(Browser browser, NodeId rootId) if (m_browser != null) { - INode node = m_browser.Session.NodeCache.Find(m_rootId); + INode node = await m_browser.Session.NodeCache.FindAsync(m_rootId, ct); if (node == null) { @@ -196,53 +198,53 @@ public void SetRoot(Browser browser, NodeId rootId) } ReferenceDescription reference = new ReferenceDescription(); - + reference.ReferenceTypeId = ReferenceTypeIds.References; - reference.IsForward = true; - reference.NodeId = node.NodeId; - reference.NodeClass = (NodeClass)node.NodeClass; - reference.BrowseName = node.BrowseName; - reference.DisplayName = node.DisplayName; - reference.TypeDefinition = null; - + reference.IsForward = true; + reference.NodeId = node.NodeId; + reference.NodeClass = (NodeClass)node.NodeClass; + reference.BrowseName = node.BrowseName; + reference.DisplayName = node.DisplayName; + reference.TypeDefinition = null; + string text = GetTargetText(reference); - string icon = GuiUtils.GetTargetIcon(m_browser.Session as Session, reference); + string icon = await GuiUtils.GetTargetIconAsync(m_browser.Session as Session, reference, ct); TreeNode root = AddNode(null, reference, text, icon); root.Nodes.Add(new TreeNode()); root.Expand(); } } - + /// /// Sets the root node for the control. /// - public void SetRoot(Session session, NodeId rootId) + public Task SetRootAsync(Session session, NodeId rootId, CancellationToken ct = default) { - SetRoot(new Browser(session), rootId); + return SetRootAsync(new Browser(session), rootId, ct); } /// /// Sets the view for the control. /// - public void SetView(Session session, BrowseViewType viewType, NodeId viewId) - { + public Task SetViewAsync(Session session, BrowseViewType viewType, NodeId viewId, CancellationToken ct = default) + { Clear(); // check if session is connected. if (session == null || !session.Connected) { - return; + return Task.CompletedTask; } Browser browser = new Browser(session); - browser.BrowseDirection = BrowseDirection.Forward; - browser.ReferenceTypeId = null; - browser.IncludeSubtypes = true; - browser.NodeClassMask = 0; + browser.BrowseDirection = BrowseDirection.Forward; + browser.ReferenceTypeId = null; + browser.IncludeSubtypes = true; + browser.NodeClassMask = 0; browser.ContinueUntilDone = false; - + NodeId rootId = Objects.RootFolder; ShowReferences = false; @@ -305,8 +307,8 @@ public void SetView(Session session, BrowseViewType viewType, NodeId viewId) break; } } - - SetRoot(browser, rootId); + + return SetRootAsync(browser, rootId, ct); } /// @@ -317,249 +319,249 @@ public NodeId RootId get { return m_rootId; } } #endregion - + #region Overridden Members - /// - protected override bool BeforeExpand(TreeNode clickedNode) + /// + protected override Task BeforeExpandAsync(TreeNode clickedNode, CancellationToken ct = default) { // check if a placeholder child is present. if (clickedNode.Nodes.Count == 1 && clickedNode.Nodes[0].Text == String.Empty) { // clear dummy children. clickedNode.Nodes.Clear(); - + // do nothing if an error is detected. if (m_browser.Session.KeepAliveStopped) { - return false; + return Task.FromResult(false); } // browse. - return Browse(clickedNode); + return BrowseAsync(clickedNode, ct); } // do not cancel expand. - return false; + return Task.FromResult(false); } /// - protected override void EnableMenuItems(TreeNode clickedNode) + protected override async void EnableMenuItems(TreeNode clickedNode) { - BrowseOptionsMI.Enabled = true; - ShowReferencesMI.Enabled = true; - SelectMI.Visible = m_allowPick; - SelectSeparatorMI.Visible = m_allowPick; - - if (clickedNode != null) + try { - // do nothing if an error is detected. - if (m_browser.Session.KeepAliveStopped) - { - return; - } + BrowseOptionsMI.Enabled = true; + ShowReferencesMI.Enabled = true; + SelectMI.Visible = m_allowPick; + SelectSeparatorMI.Visible = m_allowPick; - SelectMI.Enabled = true; - SelectItemMI.Enabled = true; - SelectChildrenMI.Enabled = clickedNode.Nodes.Count > 0; - BrowseRefreshMI.Enabled = true; - - ReferenceDescription reference = clickedNode.Tag as ReferenceDescription; - - if (reference != null) + if (clickedNode != null) { - BrowseMI.Enabled = (reference.NodeId != null && !reference.NodeId.IsAbsolute); - ViewAttributesMI.Enabled = true; - - NodeId nodeId = ExpandedNodeId.ToNodeId(reference.NodeId, m_browser.Session.NamespaceUris); + // do nothing if an error is detected. + if (m_browser.Session.KeepAliveStopped) + { + return; + } - INode node = m_browser.Session.ReadNode(nodeId); - - byte accessLevel = 0; - byte eventNotifier = 0; - bool executable = false; + SelectMI.Enabled = true; + SelectItemMI.Enabled = true; + SelectChildrenMI.Enabled = clickedNode.Nodes.Count > 0; + BrowseRefreshMI.Enabled = true; - VariableNode variableNode = node as VariableNode; + ReferenceDescription reference = clickedNode.Tag as ReferenceDescription; - if (variableNode != null) + if (reference != null) { - accessLevel = variableNode.UserAccessLevel; - } - - ObjectNode objectNode = node as ObjectNode; + BrowseMI.Enabled = (reference.NodeId != null && !reference.NodeId.IsAbsolute); + ViewAttributesMI.Enabled = true; - if (objectNode != null) - { - eventNotifier = objectNode.EventNotifier; - } - - ViewNode viewNode = node as ViewNode; + NodeId nodeId = ExpandedNodeId.ToNodeId(reference.NodeId, m_browser.Session.NamespaceUris); - if (viewNode != null) - { - eventNotifier = viewNode.EventNotifier; - } - - MethodNode methodNode = node as MethodNode; + INode node = await m_browser.Session.ReadNodeAsync(nodeId); - if (methodNode != null) - { - executable = methodNode.UserExecutable; - } - - ReadMI.Visible = false; - HistoryReadMI.Visible = false; - WriteMI.Visible = false; - HistoryUpdateMI.Visible = false; - EncodingsMI.Visible = false; - SubscribeMI.Visible = false; - CallMI.Visible = false; - - if (accessLevel != 0) - { - ReadMI.Visible = true; - HistoryReadMI.Visible = true; - WriteMI.Visible = true; - HistoryUpdateMI.Visible = true; - EncodingsMI.Visible = true; - SubscribeMI.Visible = m_SessionTreeCtrl != null; - - if ((accessLevel & (byte)AccessLevels.CurrentRead) != 0) + byte accessLevel = 0; + byte eventNotifier = 0; + bool executable = false; + + VariableNode variableNode = node as VariableNode; + + if (variableNode != null) { - ReadMI.Enabled = true; - EncodingsMI.Enabled = true; - SubscribeMI.Enabled = true; - SubscribeNewMI.Enabled = true; + accessLevel = variableNode.UserAccessLevel; } - if ((accessLevel & (byte)AccessLevels.CurrentWrite) != 0) + ObjectNode objectNode = node as ObjectNode; + + if (objectNode != null) { - WriteMI.Enabled = true; - EncodingsMI.Enabled = true; + eventNotifier = objectNode.EventNotifier; } - if ((accessLevel & (byte)AccessLevels.HistoryRead) != 0) + ViewNode viewNode = node as ViewNode; + + if (viewNode != null) { - HistoryReadMI.Enabled = true; + eventNotifier = viewNode.EventNotifier; } - if ((accessLevel & (byte)AccessLevels.HistoryWrite) != 0) + MethodNode methodNode = node as MethodNode; + + if (methodNode != null) { - HistoryUpdateMI.Enabled = true; + executable = methodNode.UserExecutable; } - } - - if (eventNotifier != 0) - { - HistoryReadMI.Visible = true; - HistoryUpdateMI.Visible = true; - SubscribeMI.Visible = true; - - if ((eventNotifier & (byte)EventNotifiers.HistoryRead) != 0) + + ReadMI.Visible = false; + HistoryReadMI.Visible = false; + WriteMI.Visible = false; + HistoryUpdateMI.Visible = false; + SubscribeMI.Visible = false; + CallMI.Visible = false; + + if (accessLevel != 0) { - HistoryReadMI.Enabled = true; + ReadMI.Visible = true; + HistoryReadMI.Visible = true; + WriteMI.Visible = true; + HistoryUpdateMI.Visible = true; + SubscribeMI.Visible = m_SessionTreeCtrl != null; + + if ((accessLevel & (byte)AccessLevels.CurrentRead) != 0) + { + ReadMI.Enabled = true; + SubscribeMI.Enabled = true; + SubscribeNewMI.Enabled = true; + } + + if ((accessLevel & (byte)AccessLevels.CurrentWrite) != 0) + { + WriteMI.Enabled = true; + } + + if ((accessLevel & (byte)AccessLevels.HistoryRead) != 0) + { + HistoryReadMI.Enabled = true; + } + + if ((accessLevel & (byte)AccessLevels.HistoryWrite) != 0) + { + HistoryUpdateMI.Enabled = true; + } } - if ((eventNotifier & (byte)EventNotifiers.HistoryWrite) != 0) + if (eventNotifier != 0) { - HistoryUpdateMI.Enabled = true; - } + HistoryReadMI.Visible = true; + HistoryUpdateMI.Visible = true; + SubscribeMI.Visible = true; - SubscribeMI.Enabled = (eventNotifier & (byte)EventNotifiers.SubscribeToEvents) != 0; - SubscribeNewMI.Enabled = SubscribeMI.Enabled; - } - - if (methodNode != null) - { - CallMI.Visible = true; - CallMI.Enabled = executable; - } - - if (variableNode != null && EncodingsMI.Enabled) - { - ReferenceDescriptionCollection encodings = m_browser.Session.ReadAvailableEncodings(variableNode.NodeId); + if ((eventNotifier & (byte)EventNotifiers.HistoryRead) != 0) + { + HistoryReadMI.Enabled = true; + } - if (encodings.Count == 0) - { - EncodingsMI.Visible = false; + if ((eventNotifier & (byte)EventNotifiers.HistoryWrite) != 0) + { + HistoryUpdateMI.Enabled = true; + } + + SubscribeMI.Enabled = (eventNotifier & (byte)EventNotifiers.SubscribeToEvents) != 0; + SubscribeNewMI.Enabled = SubscribeMI.Enabled; } - } - if (SubscribeMI.Enabled) - { - while (SubscribeMI.DropDown.Items.Count > 1) + if (methodNode != null) { - SubscribeMI.DropDown.Items.RemoveAt(SubscribeMI.DropDown.Items.Count - 1); + CallMI.Visible = true; + CallMI.Enabled = executable; } - foreach (Subscription subscription in m_browser.Session.Subscriptions) + if (SubscribeMI.Enabled) { - if (subscription.Created) + while (SubscribeMI.DropDown.Items.Count > 1) + { + SubscribeMI.DropDown.Items.RemoveAt(SubscribeMI.DropDown.Items.Count - 1); + } + + foreach (Subscription subscription in m_browser.Session.Subscriptions) { - ToolStripItem item = SubscribeMI.DropDown.Items.Add(subscription.DisplayName); - item.Click += new EventHandler(Subscription_Click); - item.Tag = subscription; + if (subscription.Created) + { + ToolStripItem item = SubscribeMI.DropDown.Items.Add(subscription.DisplayName); + item.Click += new EventHandler(Subscription_ClickAsync); + item.Tag = subscription; + } } } } } } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } } /// - protected override void SelectNode() + protected override async void SelectNode() { - base.SelectNode(); - - // check if node is selected. - if (NodesTV.SelectedNode == null) + try { - return; - } - - m_parent = GetParentOfSelected(); + base.SelectNode(); - ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; + // check if node is selected. + if (NodesTV.SelectedNode == null) + { + return; + } - // update the attributes control. - if (m_AttributesCtrl != null) - { - if (reference != null) + m_parent = GetParentOfSelected(); + + ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; + + // update the attributes control. + if (m_AttributesCtrl != null) { - m_AttributesCtrl.Initialize(m_browser.Session as Session, reference.NodeId); + if (reference != null) + { + await m_AttributesCtrl.InitializeAsync(m_browser.Session as Session, reference.NodeId); + } + else + { + m_AttributesCtrl.Clear(); + } } - else + + // check for single reference. + if (reference != null) { - m_AttributesCtrl.Clear(); + m_references = new ReferenceDescription[] { reference }; + return; } - } - - // check for single reference. - if (reference != null) - { - m_references = new ReferenceDescription[] { reference }; - return; - } - - // check if reference type folder is selected. - NodeId referenceTypeId = NodesTV.SelectedNode.Tag as NodeId; - if (referenceTypeId != null) - { - m_references = new ReferenceDescriptionCollection(); + // check if reference type folder is selected. + NodeId referenceTypeId = NodesTV.SelectedNode.Tag as NodeId; - foreach (TreeNode child in NodesTV.SelectedNode.Nodes) - { - reference = child.Tag as ReferenceDescription; + if (referenceTypeId != null) + { + m_references = new ReferenceDescriptionCollection(); - if (reference != null) + foreach (TreeNode child in NodesTV.SelectedNode.Nodes) { - m_references.Add(reference); + reference = child.Tag as ReferenceDescription; + + if (reference != null) + { + m_references.Add(reference); + } } } - } + } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } } #endregion - + #region Private Members /// /// Returns the parent node of the selected reference. @@ -587,16 +589,16 @@ private ReferenceDescription GetParentOfSelected() /// /// Adds a item to a subscription. /// - private void Subscribe(Subscription subscription, ReferenceDescription reference) - { + private async Task SubscribeAsync(Subscription subscription, ReferenceDescription reference, CancellationToken ct = default) + { MonitoredItem monitoredItem = new MonitoredItem(subscription.DefaultItem); - monitoredItem.DisplayName = subscription.Session.NodeCache.GetDisplayText(reference); - monitoredItem.StartNodeId = (NodeId)reference.NodeId; - monitoredItem.NodeClass = (NodeClass)reference.NodeClass; - monitoredItem.AttributeId = Attributes.Value; + monitoredItem.DisplayName = await subscription.Session.NodeCache.GetDisplayTextAsync(reference, ct); + monitoredItem.StartNodeId = (NodeId)reference.NodeId; + monitoredItem.NodeClass = (NodeClass)reference.NodeClass; + monitoredItem.AttributeId = Attributes.Value; monitoredItem.SamplingInterval = 0; - monitoredItem.QueueSize = 1; + monitoredItem.QueueSize = 1; // add condition fields to any event filter. EventFilter filter = monitoredItem.Filter as EventFilter; @@ -604,18 +606,18 @@ private void Subscribe(Subscription subscription, ReferenceDescription reference if (filter != null) { monitoredItem.AttributeId = Attributes.EventNotifier; - monitoredItem.QueueSize = 0; + monitoredItem.QueueSize = 0; } - + subscription.AddItem(monitoredItem); - subscription.ApplyChanges(); + await subscription.ApplyChangesAsync(ct); } /// /// Browses the server address space and adds the targets to the tree. /// - private bool Browse(TreeNode node) - { + private async Task BrowseAsync(TreeNode node, CancellationToken ct = default) + { // save node being browsed. m_nodeToBrowse = node; @@ -626,21 +628,21 @@ private bool Browse(TreeNode node) { return false; } - + // fetch references. ReferenceDescriptionCollection references = null; if (reference != null) { - references = m_browser.Browse((NodeId)reference.NodeId); + references = await m_browser.BrowseAsync((NodeId)reference.NodeId, ct); } else { - references = m_browser.Browse(m_rootId); + references = await m_browser.BrowseAsync(m_rootId, ct); } - + // add nodes to tree. - AddReferences(m_nodeToBrowse, references); + await AddReferencesAsync(m_nodeToBrowse, references, ct); return false; } @@ -648,7 +650,7 @@ private bool Browse(TreeNode node) /// /// Adds a target to the tree control. /// - private void AddReferences(TreeNode parent, ReferenceDescriptionCollection references) + private async Task AddReferencesAsync(TreeNode parent, ReferenceDescriptionCollection references, CancellationToken ct = default) { foreach (ReferenceDescription reference in references) { @@ -658,7 +660,7 @@ private void AddReferences(TreeNode parent, ReferenceDescriptionCollection refer continue; } - ReferenceTypeNode typeNode = m_browser.Session.NodeCache.Find(reference.ReferenceTypeId) as ReferenceTypeNode; + ReferenceTypeNode typeNode = await m_browser.Session.NodeCache.FindAsync(reference.ReferenceTypeId, ct) as ReferenceTypeNode; if (typeNode == null) { Utils.Trace("Reference {0} has invalid reference type id.", reference.DisplayName); @@ -689,7 +691,7 @@ private void AddReferences(TreeNode parent, ReferenceDescriptionCollection refer Utils.Trace("Node class is an unknown or unspecified value, for reference {0}", reference.DisplayName); continue; } - + if (m_browser.NodeClassMask != 0 && m_browser.NodeClassMask != 255) { if (reference.TypeDefinition == null || reference.TypeDefinition.IsNull) @@ -725,13 +727,13 @@ private void AddReferences(TreeNode parent, ReferenceDescriptionCollection refer } string text = GetTargetText(reference); - string icon = GuiUtils.GetTargetIcon(m_browser.Session as Session, reference); + string icon = await GuiUtils.GetTargetIconAsync(m_browser.Session as Session, reference, ct); TreeNode container = parent; if (m_showReferences) { - container = FindReferenceTypeContainer(parent, reference); + container = await FindReferenceTypeContainerAsync(parent, reference, ct); } if (container != null) @@ -741,11 +743,11 @@ private void AddReferences(TreeNode parent, ReferenceDescriptionCollection refer } } } - + /// /// Adds a container for the reference type to the tree control. /// - private TreeNode FindReferenceTypeContainer(TreeNode parent, ReferenceDescription reference) + private async Task FindReferenceTypeContainerAsync(TreeNode parent, ReferenceDescription reference, CancellationToken ct = default) { if (parent == null) { @@ -758,7 +760,7 @@ private TreeNode FindReferenceTypeContainer(TreeNode parent, ReferenceDescriptio return null; } - ReferenceTypeNode typeNode = m_browser.Session.NodeCache.Find(reference.ReferenceTypeId) as ReferenceTypeNode; + ReferenceTypeNode typeNode = await m_browser.Session.NodeCache.FindAsync(reference.ReferenceTypeId, ct) as ReferenceTypeNode; foreach (TreeNode child in parent.Nodes) { @@ -805,7 +807,7 @@ private TreeNode FindReferenceTypeContainer(TreeNode parent, ReferenceDescriptio return null; } - + /// /// Returns to display text for the target of a reference. /// @@ -824,52 +826,52 @@ public string GetTargetText(ReferenceDescription reference) } } - return null; + return null; } #endregion - - private void BrowseOptionsMI_Click(object sender, EventArgs e) + + private async void BrowseOptionsMI_ClickAsync(object sender, EventArgs e) { try { - if (new BrowseOptionsDlg().ShowDialog(m_browser)) - { + if (await new BrowseOptionsDlg().ShowDialogAsync(m_browser)) + { if (NodesTV.SelectedNode != null) { NodesTV.SelectedNode.Nodes.Clear(); - Browse(NodesTV.SelectedNode); + await BrowseAsync(NodesTV.SelectedNode); } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void BrowseRefreshMI_Click(object sender, EventArgs e) + private async void BrowseRefreshMI_ClickAsync(object sender, EventArgs e) { try { if (NodesTV.SelectedNode != null) { NodesTV.SelectedNode.Nodes.Clear(); - Browse(NodesTV.SelectedNode); + await BrowseAsync(NodesTV.SelectedNode); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void Browser_MoreReferences(Browser sender, BrowserEventArgs e) + private async void Browser_MoreReferencesAsync(Browser sender, BrowserEventArgs e) { try { - AddReferences(m_nodeToBrowse, e.References); + await AddReferencesAsync(m_nodeToBrowse, e.References); e.References.Clear(); - + if (MessageBox.Show("More references exist. Continue?", "Browse", MessageBoxButtons.YesNo) == DialogResult.No) { e.Cancel = true; @@ -877,7 +879,7 @@ private void Browser_MoreReferences(Browser sender, BrowserEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -897,10 +899,10 @@ private void SelectItemMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - + private void SelectChildrenMI_Click(object sender, EventArgs e) { try @@ -920,7 +922,7 @@ private void SelectChildrenMI_Click(object sender, EventArgs e) if (reference != null) { m_references.Add(reference); - } + } } if (m_references.Count > 0) @@ -930,17 +932,24 @@ private void SelectChildrenMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void ShowReferencesMI_CheckedChanged(object sender, EventArgs e) + private async void ShowReferencesMI_CheckedChangedAsync(object sender, EventArgs e) { m_showReferences = ShowReferencesMI.Checked; - SetRoot(m_browser, m_rootId); + try + { + await SetRootAsync(m_browser, m_rootId); + } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } } - private void ViewAttributesMI_Click(object sender, EventArgs e) + private async void ViewAttributesMI_ClickAsync(object sender, EventArgs e) { try { @@ -948,23 +957,23 @@ private void ViewAttributesMI_Click(object sender, EventArgs e) { return; } - + ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; - + if (reference == null) { return; } - - new NodeAttributesDlg().ShowDialog(m_browser.Session as Session, reference.NodeId); + + await new NodeAttributesDlg().ShowDialogAsync(m_browser.Session as Session, reference.NodeId); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void CallMI_Click(object sender, EventArgs e) + private async void CallMI_ClickAsync(object sender, EventArgs e) { try { @@ -974,18 +983,18 @@ private void CallMI_Click(object sender, EventArgs e) } Session session = m_browser.Session as Session; - + ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; - + if (reference == null || reference.NodeClass != NodeClass.Method) { return; } NodeId methodId = (NodeId)reference.NodeId; - + reference = NodesTV.SelectedNode.Parent.Tag as ReferenceDescription; - + if (reference == null) { reference = NodesTV.SelectedNode.Parent.Parent.Tag as ReferenceDescription; @@ -995,7 +1004,7 @@ private void CallMI_Click(object sender, EventArgs e) return; } } - + NodeId objectId = (NodeId)reference.NodeId; if (m_MethodCalled != null) @@ -1009,15 +1018,15 @@ private void CallMI_Click(object sender, EventArgs e) } } - new CallMethodDlg().Show(m_browser.Session as Session, objectId, methodId); + await new CallMethodDlg().ShowAsync(m_browser.Session as Session, objectId, methodId); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void ReadMI_Click(object sender, EventArgs e) + private async void ReadMI_ClickAsync(object sender, EventArgs e) { try { @@ -1025,9 +1034,9 @@ private void ReadMI_Click(object sender, EventArgs e) { return; } - + ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; - + if (reference == null || (reference.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0) { return; @@ -1040,23 +1049,23 @@ private void ReadMI_Click(object sender, EventArgs e) ReadValueId valueId = new ReadValueId(); - valueId.NodeId = (NodeId)reference.NodeId; - valueId.AttributeId = Attributes.Value; - valueId.IndexRange = null; + valueId.NodeId = (NodeId)reference.NodeId; + valueId.AttributeId = Attributes.Value; + valueId.IndexRange = null; valueId.DataEncoding = null; valueIds.Add(valueId); // show form. - new ReadDlg().Show(session, valueIds); + await new ReadDlg().ShowAsync(session, valueIds); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void WriteMI_Click(object sender, EventArgs e) + private async void WriteMI_ClickAsync(object sender, EventArgs e) { try { @@ -1064,9 +1073,9 @@ private void WriteMI_Click(object sender, EventArgs e) { return; } - + ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; - + if (reference == null || (reference.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0) { return; @@ -1079,23 +1088,23 @@ private void WriteMI_Click(object sender, EventArgs e) WriteValue value = new WriteValue(); - value.NodeId = (NodeId)reference.NodeId; + value.NodeId = (NodeId)reference.NodeId; value.AttributeId = Attributes.Value; - value.IndexRange = null; - value.Value = null; + value.IndexRange = null; + value.Value = null; values.Add(value); // show form. - new WriteDlg().Show(session, values); + await new WriteDlg().ShowAsync(session, values); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void SubscribeNewMI_Click(object sender, EventArgs e) + private async void SubscribeNewMI_ClickAsync(object sender, EventArgs e) { try { @@ -1112,22 +1121,22 @@ private void SubscribeNewMI_Click(object sender, EventArgs e) } if (m_SessionTreeCtrl != null) - { - Subscription subscription = m_SessionTreeCtrl.CreateSubscription(m_browser.Session as Session); + { + Subscription subscription = await m_SessionTreeCtrl.CreateSubscriptionAsync(m_browser.Session as Session); if (subscription != null) { - Subscribe(subscription, reference); + await SubscribeAsync(subscription, reference); } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - void Subscription_Click(object sender, EventArgs e) + private async void Subscription_ClickAsync(object sender, EventArgs e) { try { @@ -1142,45 +1151,21 @@ void Subscription_Click(object sender, EventArgs e) { return; } - + Subscription subscription = ((ToolStripItem)sender).Tag as Subscription; if (subscription != null) { - Subscribe(subscription, reference); - } - } - catch (Exception exception) - { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); - } - } - - private void EncodingsMI_Click(object sender, EventArgs e) - { - try - { - if (NodesTV.SelectedNode == null) - { - return; - } - - ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; - - if (reference == null || (reference.NodeClass & NodeClass.Variable) == 0) - { - return; + await SubscribeAsync(subscription, reference); } - - new DataEncodingDlg().ShowDialog(m_browser.Session as Session, (NodeId)reference.NodeId); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void HistoryReadMI_Click(object sender, EventArgs e) + private async void HistoryReadMI_ClickAsync(object sender, EventArgs e) { try { @@ -1196,7 +1181,7 @@ private void HistoryReadMI_Click(object sender, EventArgs e) return; } - new ReadHistoryDlg().ShowDialog(m_browser.Session as Session, (NodeId)reference.NodeId); + await new ReadHistoryDlg().ShowDialogAsync(m_browser.Session as Session, (NodeId)reference.NodeId); } catch (Exception exception) { @@ -1204,7 +1189,7 @@ private void HistoryReadMI_Click(object sender, EventArgs e) } } - private void BrowseMI_Click(object sender, EventArgs e) + private async void BrowseMI_ClickAsync(object sender, EventArgs e) { try { @@ -1220,15 +1205,15 @@ private void BrowseMI_Click(object sender, EventArgs e) return; } - new BrowseDlg().Show(m_browser.Session as Session, (NodeId)reference.NodeId); + await new BrowseDlg().ShowAsync(m_browser.Session as Session, (NodeId)reference.NodeId); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } - + #region NodesSelectedEventArgs Class /// /// The event arguments provided nodes are picked in the dialog. @@ -1241,7 +1226,7 @@ public class NodesSelectedEventArgs : EventArgs /// internal NodesSelectedEventArgs(ExpandedNodeId sourceId, ReferenceDescriptionCollection references) { - m_sourceId = sourceId; + m_sourceId = sourceId; m_references = references; } #endregion @@ -1263,7 +1248,7 @@ public IEnumerable References get { return m_references; } } #endregion - + #region Private Fields private ExpandedNodeId m_sourceId; private ReferenceDescriptionCollection m_references; @@ -1274,11 +1259,11 @@ public IEnumerable References /// The delegate used to receive notifications when nodes are picked in the dialog. /// public delegate void NodesSelectedEventHandler(object sender, NodesSelectedEventArgs e); - #endregion - + #endregion + #region BrowseViewType Enumeration /// - /// The type views that can be used when browsing the address space. + /// The type views that can be used when browsing the address space. /// public enum BrowseViewType { @@ -1322,9 +1307,9 @@ public enum BrowseViewType /// ServerDefinedView } - #endregion + #endregion + - #region MethodCalledEventArgs Class /// /// The event arguments provided nodes are picked in the dialog. @@ -1337,7 +1322,7 @@ public class MethodCalledEventArgs : EventArgs /// internal MethodCalledEventArgs(Session session, NodeId objectId, NodeId methodId) { - m_session = session; + m_session = session; m_objectId = objectId; m_methodId = methodId; } @@ -1345,7 +1330,7 @@ internal MethodCalledEventArgs(Session session, NodeId objectId, NodeId methodId #region Public Properties /// - /// The session + /// The session /// public Session Session { @@ -1373,11 +1358,11 @@ public NodeId MethodId ///
public bool Handled { - get { return m_handled; } + get { return m_handled; } set { m_handled = value; } } #endregion - + #region Private Fields private Session m_session; private NodeId m_objectId; @@ -1390,5 +1375,5 @@ public bool Handled /// The delegate used to receive notifications when nodes are picked in the dialog. ///
public delegate void MethodCalledEventHandler(object sender, MethodCalledEventArgs e); - #endregion + #endregion } diff --git a/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.resx b/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.resx index edd3be8a4..664168a02 100644 --- a/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.resx +++ b/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.resx @@ -112,12 +112,12 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + 17, 17 \ No newline at end of file diff --git a/Samples/Controls.Net4/Sessions/BrowseTypesDlg.Designer.cs b/Samples/Controls.Net4/Sessions/BrowseTypesDlg.Designer.cs index 433d0db9b..e95189d0f 100644 --- a/Samples/Controls.Net4/Sessions/BrowseTypesDlg.Designer.cs +++ b/Samples/Controls.Net4/Sessions/BrowseTypesDlg.Designer.cs @@ -128,7 +128,7 @@ private void InitializeComponent() this.TypeNavigatorCTRL.Name = "TypeNavigatorCTRL"; this.TypeNavigatorCTRL.Size = new System.Drawing.Size(788, 24); this.TypeNavigatorCTRL.TabIndex = 1; - this.TypeNavigatorCTRL.TypeSelected += new Opc.Ua.Sample.TypeNavigatorEventHandler(this.TypeNavigatorCTRL_TypeSelected); + this.TypeNavigatorCTRL.TypeSelected += new Opc.Ua.Sample.TypeNavigatorEventHandler(this.TypeNavigatorCTRL_TypeSelectedAsync); // // BrowseTypesDlg // diff --git a/Samples/Controls.Net4/Sessions/BrowseTypesDlg.cs b/Samples/Controls.Net4/Sessions/BrowseTypesDlg.cs index dc12aec1d..1fe09bc3d 100644 --- a/Samples/Controls.Net4/Sessions/BrowseTypesDlg.cs +++ b/Samples/Controls.Net4/Sessions/BrowseTypesDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -55,32 +57,33 @@ public BrowseTypesDlg() private Session m_session; private ILocalNode m_selectedType; #endregion - + #region Public Interface /// /// Displays the dialog. /// - public void Show( + public async Task ShowAsync( Session session, - NodeId typeId) + NodeId typeId, + CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); + if (session == null) throw new ArgumentNullException(nameof(session)); - m_session = session; - - TypeNavigatorCTRL.Initialize(m_session, typeId); - TypeHierarchyCTRL.Initialize(m_session, typeId); + m_session = session; + + await TypeNavigatorCTRL.InitializeAsync(m_session, typeId, ct); + await TypeHierarchyCTRL.InitializeAsync(m_session, typeId, ct); Show(); BringToFront(); } #endregion - + #region Private Methods #endregion - + #region Event Handler - private void TypeNavigatorCTRL_TypeSelected(object sender, TypeNavigatorEventArgs e) + private async void TypeNavigatorCTRL_TypeSelectedAsync(object sender, TypeNavigatorEventArgs e) { try { @@ -88,11 +91,11 @@ private void TypeNavigatorCTRL_TypeSelected(object sender, TypeNavigatorEventArg if (m_selectedType != null) { - TypeHierarchyCTRL.Initialize(m_session, m_selectedType.NodeId); + await TypeHierarchyCTRL.InitializeAsync(m_session, m_selectedType.NodeId); } else { - TypeHierarchyCTRL.Initialize(m_session, null); + await TypeHierarchyCTRL.InitializeAsync(m_session, null); } } catch (Exception exception) diff --git a/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.Designer.cs b/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.Designer.cs index b09959186..8bd7c2f21 100644 --- a/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.Designer.cs +++ b/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.Designer.cs @@ -146,7 +146,7 @@ private void InitializeComponent() this.OkBTN.TabIndex = 1; this.OkBTN.Text = "OK"; this.OkBTN.UseVisualStyleBackColor = true; - this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click); + this.OkBTN.Click += new System.EventHandler(this.OkBTN_ClickAsync); // // CancelBTN // diff --git a/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.cs b/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.cs index 4084cfa5a..d59982f39 100644 --- a/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.cs +++ b/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.cs @@ -63,19 +63,19 @@ public CreateSecureChannelDlg() private ApplicationConfiguration m_configuration; private EndpointDescriptionCollection m_endpoints; private ServiceMessageContext m_messageContext; - + /// /// Displays the dialog. /// public ITransportChannel ShowDialog( - ApplicationConfiguration configuration, + ApplicationConfiguration configuration, EndpointDescriptionCollection endpoints) { - if (endpoints == null) throw new ArgumentNullException("endpoints"); - if (configuration == null) throw new ArgumentNullException("configuration"); + if (endpoints == null) throw new ArgumentNullException(nameof(endpoints)); + if (configuration == null) throw new ArgumentNullException(nameof(configuration)); - m_endpoints = endpoints; - m_configuration = configuration; + m_endpoints = endpoints; + m_configuration = configuration; m_messageContext = configuration.CreateMessageContext(); EndpointCB.Items.Clear(); @@ -89,23 +89,23 @@ public ITransportChannel ShowDialog( { EndpointCB.SelectedIndex = 0; } - - OperationTimeoutNC.Value = configuration.TransportQuotas.OperationTimeout; - MaxMessageSizeNC.Value = configuration.TransportQuotas.MaxMessageSize; - MaxArrayLengthNC.Value = configuration.TransportQuotas.MaxArrayLength; - MaxStringLengthNC.Value = configuration.TransportQuotas.MaxStringLength; + + OperationTimeoutNC.Value = configuration.TransportQuotas.OperationTimeout; + MaxMessageSizeNC.Value = configuration.TransportQuotas.MaxMessageSize; + MaxArrayLengthNC.Value = configuration.TransportQuotas.MaxArrayLength; + MaxStringLengthNC.Value = configuration.TransportQuotas.MaxStringLength; MaxByteStringLengthNC.Value = configuration.TransportQuotas.MaxByteStringLength; if (ShowDialog() != DialogResult.OK) { return null; } - + // return the channel. return m_channel; } - private async void OkBTN_Click(object sender, EventArgs e) + private async void OkBTN_ClickAsync(object sender, EventArgs e) { try { @@ -122,7 +122,7 @@ private async void OkBTN_Click(object sender, EventArgs e) m_configuration, m_endpoints[EndpointCB.SelectedIndex], configuration, - await m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true), + await m_configuration.SecurityConfiguration.ApplicationCertificate.FindAsync(true), m_messageContext); // create the channel. @@ -189,7 +189,7 @@ private void EndpointCB_SelectedIndexChanged(object sender, EventArgs e) } private void DetailsBTN_Click(object sender, EventArgs e) - { + { try { int index = EndpointCB.SelectedIndex; diff --git a/Samples/Controls.Net4/Sessions/EndpointViewDlg.cs b/Samples/Controls.Net4/Sessions/EndpointViewDlg.cs index 3749f46e4..7a750e99e 100644 --- a/Samples/Controls.Net4/Sessions/EndpointViewDlg.cs +++ b/Samples/Controls.Net4/Sessions/EndpointViewDlg.cs @@ -54,17 +54,17 @@ public EndpointViewDlg() { InitializeComponent(); } - + /// /// Displays the dialog. /// public bool ShowDialog(EndpointDescription endpoint) { - if (endpoint == null) throw new ArgumentNullException("endpoint"); - - EndpointTB.Text = endpoint.EndpointUrl; + if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); + + EndpointTB.Text = endpoint.EndpointUrl; ServerNameTB.Text = endpoint.Server.ApplicationName.Text; - ServerUriTB.Text = endpoint.Server.ApplicationUri; + ServerUriTB.Text = endpoint.Server.ApplicationUri; try { @@ -75,11 +75,11 @@ public bool ShowDialog(EndpointDescription endpoint) { ServerCertificateTB.Text = ""; } - - - SecurityModeTB.Text = String.Format("{0}", endpoint.SecurityMode);; + + + SecurityModeTB.Text = String.Format("{0}", endpoint.SecurityMode); ; SecurityPolicyUriTB.Text = String.Format("{0}", endpoint.SecurityPolicyUri); - + UserIdentityTypeTB.Text = ""; foreach (UserTokenPolicy policy in endpoint.UserIdentityTokens) @@ -91,7 +91,7 @@ public bool ShowDialog(EndpointDescription endpoint) { return false; } - + return true; } } diff --git a/Samples/Controls.Net4/Sessions/NodeAttributesDlg.Designer.cs b/Samples/Controls.Net4/Sessions/NodeAttributesDlg.Designer.cs index 97df8dd30..998bd2c8f 100644 --- a/Samples/Controls.Net4/Sessions/NodeAttributesDlg.Designer.cs +++ b/Samples/Controls.Net4/Sessions/NodeAttributesDlg.Designer.cs @@ -85,7 +85,7 @@ private void InitializeComponent() this.OkBTN.TabIndex = 0; this.OkBTN.Text = "Refresh"; this.OkBTN.UseVisualStyleBackColor = true; - this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click); + this.OkBTN.Click += new System.EventHandler(this.OkBTN_ClickAsync); // // CancelBTN // diff --git a/Samples/Controls.Net4/Sessions/NodeAttributesDlg.cs b/Samples/Controls.Net4/Sessions/NodeAttributesDlg.cs index 8de810284..c4d13212f 100644 --- a/Samples/Controls.Net4/Sessions/NodeAttributesDlg.cs +++ b/Samples/Controls.Net4/Sessions/NodeAttributesDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -39,6 +39,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -56,20 +58,20 @@ public NodeAttributesDlg() private Session m_session; private ExpandedNodeId m_nodeId; #endregion - + #region Public Interface /// /// Displays the dialog. /// - public void ShowDialog(Session session, ExpandedNodeId nodeId) + public async Task ShowDialogAsync(Session session, ExpandedNodeId nodeId, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - if (nodeId == null) throw new ArgumentNullException("nodeId"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + if (nodeId == null) throw new ArgumentNullException(nameof(nodeId)); + m_session = session; - m_nodeId = nodeId; + m_nodeId = nodeId; - AttributesCTRL.Initialize(session, nodeId); + await AttributesCTRL.InitializeAsync(session, nodeId, ct); if (ShowDialog() != DialogResult.OK) { @@ -78,11 +80,11 @@ public void ShowDialog(Session session, ExpandedNodeId nodeId) } #endregion - private void OkBTN_Click(object sender, EventArgs e) + private async void OkBTN_ClickAsync(object sender, EventArgs e) { try { - AttributesCTRL.Initialize(m_session, m_nodeId); + await AttributesCTRL.InitializeAsync(m_session, m_nodeId); } catch (Exception exception) { diff --git a/Samples/Controls.Net4/Sessions/ReadHistoryDlg.Designer.cs b/Samples/Controls.Net4/Sessions/ReadHistoryDlg.Designer.cs index 87fda8871..ed55eb6da 100644 --- a/Samples/Controls.Net4/Sessions/ReadHistoryDlg.Designer.cs +++ b/Samples/Controls.Net4/Sessions/ReadHistoryDlg.Designer.cs @@ -173,7 +173,7 @@ private void InitializeComponent() this.StopBTN.TabIndex = 19; this.StopBTN.Text = "Stop"; this.StopBTN.UseVisualStyleBackColor = true; - this.StopBTN.Click += new System.EventHandler(this.StopBTN_Click); + this.StopBTN.Click += new System.EventHandler(this.StopBTN_ClickAsync); // // NextBTN // @@ -357,7 +357,7 @@ private void InitializeComponent() this.ReadTypeCB.Name = "ReadTypeCB"; this.ReadTypeCB.Size = new System.Drawing.Size(138, 21); this.ReadTypeCB.TabIndex = 1; - this.ReadTypeCB.SelectedIndexChanged += new System.EventHandler(this.ReadTypeCB_SelectedIndexChanged); + this.ReadTypeCB.SelectedIndexChanged += new System.EventHandler(this.ReadTypeCB_SelectedIndexChangedAsync); // // ReadTypeLB // diff --git a/Samples/Controls.Net4/Sessions/ReadHistoryDlg.cs b/Samples/Controls.Net4/Sessions/ReadHistoryDlg.cs index a48f59349..64a1169af 100644 --- a/Samples/Controls.Net4/Sessions/ReadHistoryDlg.cs +++ b/Samples/Controls.Net4/Sessions/ReadHistoryDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -43,6 +43,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -67,7 +69,7 @@ public ReadHistoryDlg() AggregateCB.Items.Add(BrowseNames.AggregateFunction_Count); AggregateCB.Items.Add(BrowseNames.AggregateFunction_Maximum); AggregateCB.Items.Add(BrowseNames.AggregateFunction_Minimum); - AggregateCB.Items.Add(BrowseNames.AggregateFunction_Total); + AggregateCB.Items.Add(BrowseNames.AggregateFunction_Total); } private enum ReadType @@ -82,17 +84,17 @@ private enum ReadType private NodeId m_nodeId; private HistoryReadResult m_result; private int m_index; - + /// /// Displays the dialog. /// - public bool ShowDialog(Session session, NodeId nodeId) + public async Task ShowDialogAsync(Session session, NodeId nodeId, CancellationToken ct = default) { m_session = session; m_nodeId = nodeId; // update the title. - string displayText = session.NodeCache.GetDisplayText(nodeId); + string displayText = await session.NodeCache.GetDisplayTextAsync(nodeId, ct); if (!String.IsNullOrEmpty(displayText)) { @@ -104,7 +106,7 @@ public bool ShowDialog(Session session, NodeId nodeId) try { - startTime = ReadFirstDate().ToLocalTime(); + startTime = (await ReadFirstDateAsync(ct)).ToLocalTime(); } catch (Exception) { @@ -115,7 +117,7 @@ public bool ShowDialog(Session session, NodeId nodeId) { startTime = StartTimeDP.MinDate; } - + ReadTypeCB.SelectedItem = ReadType.Raw; StartTimeDP.Value = startTime; StartTimeCK.Checked = true; @@ -134,7 +136,7 @@ public bool ShowDialog(Session session, NodeId nodeId) { return false; } - + return true; } @@ -182,8 +184,8 @@ private void ShowResults() ResultsLV.Columns[ii].Width = -2; } } - - private void ReleaseContinuationPoints() + + private async Task ReleaseContinuationPointsAsync(CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); @@ -198,17 +200,16 @@ private void ReleaseContinuationPoints() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -218,7 +219,7 @@ private void ReleaseContinuationPoints() ShowResults(); } - private DateTime ReadFirstDate() + private async Task ReadFirstDateAsync(CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = new DateTime(1970, 1, 1); @@ -233,17 +234,16 @@ private DateTime ReadFirstDate() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -266,14 +266,16 @@ private DateTime ReadFirstDate() { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; - m_session.HistoryRead( + response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -282,7 +284,7 @@ private DateTime ReadFirstDate() return startTime; } - private void ReadRaw(bool isReadModified) + private async Task ReadRawAsync(bool isReadModified, CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = DateTime.MinValue; @@ -317,36 +319,36 @@ private void ReadRaw(bool isReadModified) HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); - + if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(results[0].StatusCode); } m_result = results[0]; - + ShowResults(); } - private void ReadAtTime() + private Task ReadAtTimeAsync(CancellationToken ct = default) { + return Task.CompletedTask; } - private void ReadProcessed() + private async Task ReadProcessedAsync(CancellationToken ct = default) { ReadProcessedDetails details = new ReadProcessedDetails(); details.StartTime = StartTimeDP.Value.ToUniversalTime(); @@ -379,17 +381,16 @@ private void ReadProcessed() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -404,34 +405,31 @@ private void ReadProcessed() ShowResults(); } - private void Read() + private Task ReadAsync(CancellationToken ct = default) { switch ((ReadType)ReadTypeCB.SelectedItem) { case ReadType.Raw: { - ReadRaw(false); - break; + return ReadRawAsync(false, ct); } case ReadType.Modified: { - ReadRaw(true); - break; + return ReadRawAsync(true, ct); } case ReadType.AtTime: { - ReadAtTime(); - break; + return ReadAtTimeAsync(ct); } case ReadType.Processed: { - ReadProcessed(); - break; + return ReadProcessedAsync(ct); } } + return Task.CompletedTask; } private void GoBTN_Click(object sender, EventArgs e) @@ -442,7 +440,7 @@ private void GoBTN_Click(object sender, EventArgs e) ResultsLV.Items.Clear(); m_result = null; - Read(); + ReadAsync(); } catch (Exception exception) { @@ -454,7 +452,7 @@ private void NextBTN_Click(object sender, EventArgs e) { try { - Read(); + ReadAsync(); } catch (Exception exception) { @@ -462,11 +460,11 @@ private void NextBTN_Click(object sender, EventArgs e) } } - private void StopBTN_Click(object sender, EventArgs e) + private async void StopBTN_ClickAsync(object sender, EventArgs e) { try { - ReleaseContinuationPoints(); + await ReleaseContinuationPointsAsync(); } catch (Exception exception) { @@ -474,13 +472,13 @@ private void StopBTN_Click(object sender, EventArgs e) } } - private void ReadTypeCB_SelectedIndexChanged(object sender, EventArgs e) + private async void ReadTypeCB_SelectedIndexChangedAsync(object sender, EventArgs e) { try { - ReleaseContinuationPoints(); + await ReleaseContinuationPointsAsync(); } - catch (Exception) + catch { // ignore is ok. } diff --git a/Samples/Controls.Net4/Sessions/SecuritySettingsDlg.cs b/Samples/Controls.Net4/Sessions/SecuritySettingsDlg.cs index 508387747..8d4bd6651 100644 --- a/Samples/Controls.Net4/Sessions/SecuritySettingsDlg.cs +++ b/Samples/Controls.Net4/Sessions/SecuritySettingsDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -61,10 +61,7 @@ public SecuritySettingsDlg() SecurityModeCB.Items.Add(value); } - foreach (string value in SecurityPolicies.GetDisplayNames()) - { - SecurityPolicyUriCB.Items.Add(value); - } + SecurityPolicyUriCB.Items.AddRange(SecurityPolicies.GetDisplayNames()); } /// @@ -74,7 +71,7 @@ public bool ShowDialog(ref MessageSecurityMode securityMode, ref string security { // set security mode. SecurityModeCB.SelectedItem = securityMode; - + // set security policy uri SecurityPolicyUriCB.SelectedIndex = -1; @@ -91,11 +88,11 @@ public bool ShowDialog(ref MessageSecurityMode securityMode, ref string security { return false; } - - securityMode = (MessageSecurityMode)SecurityModeCB.SelectedItem; + + securityMode = (MessageSecurityMode)SecurityModeCB.SelectedItem; securityPolicyUri = SecurityPolicies.GetUri((string)SecurityPolicyUriCB.SelectedItem); - useNativeStack = UseNativeStackCK.Checked; - + useNativeStack = UseNativeStackCK.Checked; + return true; } diff --git a/Samples/Controls.Net4/Sessions/SelectNodeDlg.cs b/Samples/Controls.Net4/Sessions/SelectNodeDlg.cs index 0546838b3..356490049 100644 --- a/Samples/Controls.Net4/Sessions/SelectNodeDlg.cs +++ b/Samples/Controls.Net4/Sessions/SelectNodeDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -39,6 +39,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -65,27 +67,27 @@ public SelectNodeDlg() #region Private Fields private ReferenceDescription m_reference; #endregion - + #region Public Interface /// /// Displays the dialog. /// - public ReferenceDescription ShowDialog(Browser browser, NodeId rootId) + public async Task ShowDialogAsync(Browser browser, NodeId rootId, CancellationToken ct = default) { - if (browser == null) throw new ArgumentNullException("browser"); + if (browser == null) throw new ArgumentNullException(nameof(browser)); - BrowseCTRL.SetRoot(browser, rootId); + await BrowseCTRL.SetRootAsync(browser, rootId, ct); NamespaceUriCB.Items.Clear(); NamespaceUriCB.Items.AddRange(browser.Session.NamespaceUris.ToArray()); - + OkBTN.Enabled = false; if (ShowDialog() != DialogResult.OK) { return null; } - + return m_reference; } #endregion @@ -134,7 +136,7 @@ private void BrowseCTRL_NodeSelected(object sender, TreeNodeActionEventArgs e) OkBTN.Enabled = false; ReferenceDescription reference = e.Node as ReferenceDescription; - + if (reference == null) { return; @@ -146,9 +148,9 @@ private void BrowseCTRL_NodeSelected(object sender, TreeNodeActionEventArgs e) } // set the display name. - DisplayNameTB.Text = reference.ToString(); + DisplayNameTB.Text = reference.ToString(); NodeClassCB.SelectedItem = (NodeClass)reference.NodeClass; - + // set identifier type. IdentifierTypeCB.SelectedItem = reference.NodeId.IdType; @@ -170,7 +172,7 @@ private void BrowseCTRL_NodeSelected(object sender, TreeNodeActionEventArgs e) NamespaceUriCB.Text = null; } } - + // set identifier. switch (reference.NodeId.IdType) { diff --git a/Samples/Controls.Net4/Sessions/SessionOpenDlg.cs b/Samples/Controls.Net4/Sessions/SessionOpenDlg.cs index 6d73780af..d4d88b23d 100644 --- a/Samples/Controls.Net4/Sessions/SessionOpenDlg.cs +++ b/Samples/Controls.Net4/Sessions/SessionOpenDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -35,6 +35,7 @@ using System.Reflection; using System.Text; using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; namespace Opc.Ua.Sample.Controls @@ -56,18 +57,18 @@ public SessionOpenDlg() private IList m_preferredLocales; private bool m_checkDomain = true; #endregion - + #region Public Interface /// /// Displays the dialog. /// public bool ShowDialog(Session session, IList preferredLocales) { - if (session == null) throw new ArgumentNullException("session"); + if (session == null) throw new ArgumentNullException(nameof(session)); m_session = session; m_preferredLocales = preferredLocales; - + UserIdentityTypeCB.Items.Clear(); foreach (UserTokenPolicy policy in session.Endpoint.UserIdentityTokens) @@ -88,7 +89,7 @@ public bool ShowDialog(Session session, IList preferredLocales) { SessionNameTB.Text = Utils.Format("MySession {0}", Utils.IncrementIdentifier(ref m_Counter)); } - + if (session.Identity != null) { UserIdentityTypeCB.SelectedItem = session.Identity.TokenType; @@ -98,19 +99,19 @@ public bool ShowDialog(Session session, IList preferredLocales) { return false; } - + return true; } #endregion private void UserIdentityTypeCB_SelectedIndexChanged(object sender, EventArgs e) - { + { try { UserTokenType tokenType = (UserTokenType)UserIdentityTypeCB.SelectedItem; UserNameCB.Items.Clear(); - + UserNameCB.Enabled = true; PasswordTB.Enabled = true; @@ -132,7 +133,7 @@ private void UserIdentityTypeCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -151,7 +152,7 @@ private void OkBTN_Click(object sender, EventArgs e) { username = UserNameCB.Text; } - + if (!String.IsNullOrEmpty(username) || !String.IsNullOrEmpty(PasswordTB.Text)) { identity = new UserIdentity(username, PasswordTB.Text); @@ -160,8 +161,8 @@ private void OkBTN_Click(object sender, EventArgs e) Cursor = Cursors.WaitCursor; - ThreadPool.QueueUserWorkItem(Open, new object[] { m_session, SessionNameTB.Text, identity, m_preferredLocales, m_checkDomain }); - + Task.Run(() => OpenAsync(m_session, SessionNameTB.Text, identity, m_preferredLocales, m_checkDomain)); + CancelBTN.Enabled = false; OkBTN.Enabled = false; } @@ -169,7 +170,7 @@ private void OkBTN_Click(object sender, EventArgs e) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } - } + } /// /// Reports the results of the open session operation. @@ -246,21 +247,15 @@ private void OpenComplete(object e) /// /// Asynchronously open the session. /// - private void Open(object state) + private async Task OpenAsync(Session session, string sessionName, IUserIdentity identity, IList preferredLocales, bool? checkDomain, CancellationToken ct = default) { try { - Session session = ((object[])state)[0] as Session; - string sessionName = ((object[])state)[1] as string; - IUserIdentity identity = ((object[])state)[2] as IUserIdentity; - IList preferredLocales = ((object[])state)[3] as IList; - bool? checkDomain = ((object[])state)[4] as bool?; - // open the session. - session.Open(sessionName, (uint)session.SessionTimeout, identity, preferredLocales, checkDomain ?? true); + await session.OpenAsync(sessionName, (uint)session.SessionTimeout, identity, preferredLocales, checkDomain ?? true, ct); var typeSystemLoader = new ComplexTypeSystem(session); - typeSystemLoader.Load().Wait(); + _ = await typeSystemLoader.LoadAsync(ct: ct); OpenComplete(null); } diff --git a/Samples/Controls.Net4/Sessions/SessionTreeCtrl.Designer.cs b/Samples/Controls.Net4/Sessions/SessionTreeCtrl.Designer.cs index 9389e3811..072b215cc 100644 --- a/Samples/Controls.Net4/Sessions/SessionTreeCtrl.Designer.cs +++ b/Samples/Controls.Net4/Sessions/SessionTreeCtrl.Designer.cs @@ -111,7 +111,7 @@ private void InitializeComponent() this.NewSessionMI.Name = "NewSessionMI"; this.NewSessionMI.Size = new System.Drawing.Size(183, 22); this.NewSessionMI.Text = "New Session..."; - this.NewSessionMI.Click += new System.EventHandler(this.NewSessionMI_Click); + this.NewSessionMI.Click += new System.EventHandler(this.NewSessionMI_ClickAsync); // // NewWindowMI // @@ -132,14 +132,14 @@ private void InitializeComponent() this.SessionLoadMI.Name = "SessionLoadMI"; this.SessionLoadMI.Size = new System.Drawing.Size(183, 22); this.SessionLoadMI.Text = "Load Subscriptions..."; - this.SessionLoadMI.Click += new System.EventHandler(this.SessionLoadMI_Click); + this.SessionLoadMI.Click += new System.EventHandler(this.SessionLoadMI_ClickAsync); // // DeleteMI // this.DeleteMI.Name = "DeleteMI"; this.DeleteMI.Size = new System.Drawing.Size(183, 22); this.DeleteMI.Text = "Delete"; - this.DeleteMI.Click += new System.EventHandler(this.DeleteMI_Click); + this.DeleteMI.Click += new System.EventHandler(this.DeleteMI_ClickAsync); // // Separator01 // @@ -180,28 +180,28 @@ private void InitializeComponent() this.BrowseServerViewsMI.Name = "BrowseServerViewsMI"; this.BrowseServerViewsMI.Size = new System.Drawing.Size(178, 22); this.BrowseServerViewsMI.Text = "Server Defined View"; - this.BrowseServerViewsMI.DropDownOpening += new System.EventHandler(this.BrowseServerViewsMI_DropDownOpening); + this.BrowseServerViewsMI.DropDownOpening += new System.EventHandler(this.BrowseServerViewsMI_DropDownOpeningAsync); // // BrowseObjectTypesMI // this.BrowseObjectTypesMI.Name = "BrowseObjectTypesMI"; this.BrowseObjectTypesMI.Size = new System.Drawing.Size(178, 22); this.BrowseObjectTypesMI.Text = "Object Types..."; - this.BrowseObjectTypesMI.Click += new System.EventHandler(this.BrowseObjectTypesMI_Click); + this.BrowseObjectTypesMI.Click += new System.EventHandler(this.BrowseObjectTypesMI_ClickAsync); // // BrowseEventTypesMI // this.BrowseEventTypesMI.Name = "BrowseEventTypesMI"; this.BrowseEventTypesMI.Size = new System.Drawing.Size(178, 22); this.BrowseEventTypesMI.Text = "Event Types..."; - this.BrowseEventTypesMI.Click += new System.EventHandler(this.BrowseEventTypesMI_Click); + this.BrowseEventTypesMI.Click += new System.EventHandler(this.BrowseEventTypesMI_ClickAsync); // // BrowseVariableTypesMI // this.BrowseVariableTypesMI.Name = "BrowseVariableTypesMI"; this.BrowseVariableTypesMI.Size = new System.Drawing.Size(178, 22); this.BrowseVariableTypesMI.Text = "Variable Types..."; - this.BrowseVariableTypesMI.Click += new System.EventHandler(this.BrowseVariableTypesMI_Click); + this.BrowseVariableTypesMI.Click += new System.EventHandler(this.BrowseVariableTypesMI_ClickAsync); // // BrowseDataTypesMI // @@ -232,7 +232,7 @@ private void InitializeComponent() this.SubscriptionCreateMI.Name = "SubscriptionCreateMI"; this.SubscriptionCreateMI.Size = new System.Drawing.Size(168, 22); this.SubscriptionCreateMI.Text = "New..."; - this.SubscriptionCreateMI.Click += new System.EventHandler(this.SubscriptionCreateMI_Click); + this.SubscriptionCreateMI.Click += new System.EventHandler(this.SubscriptionCreateMI_ClickAsync); // // SubscriptionMonitorMI // @@ -247,28 +247,28 @@ private void InitializeComponent() this.SubscriptionEnabledPublishingMI.Name = "SubscriptionEnabledPublishingMI"; this.SubscriptionEnabledPublishingMI.Size = new System.Drawing.Size(168, 22); this.SubscriptionEnabledPublishingMI.Text = "Enable Publishing"; - this.SubscriptionEnabledPublishingMI.Click += new System.EventHandler(this.SubscriptionEnabledPublishingMI_Click); + this.SubscriptionEnabledPublishingMI.Click += new System.EventHandler(this.SubscriptionEnabledPublishingMI_ClickAsync); // // ReadMI // this.ReadMI.Name = "ReadMI"; this.ReadMI.Size = new System.Drawing.Size(183, 22); this.ReadMI.Text = "Read..."; - this.ReadMI.Click += new System.EventHandler(this.ReadMI_Click); + this.ReadMI.Click += new System.EventHandler(this.ReadMI_ClickAsync); // // WriteMI // this.WriteMI.Name = "WriteMI"; this.WriteMI.Size = new System.Drawing.Size(183, 22); this.WriteMI.Text = "Write..."; - this.WriteMI.Click += new System.EventHandler(this.WriteMI_Click); + this.WriteMI.Click += new System.EventHandler(this.WriteMI_ClickAsync); // // SetLocaleMI // this.SetLocaleMI.Name = "SetLocaleMI"; this.SetLocaleMI.Size = new System.Drawing.Size(183, 22); this.SetLocaleMI.Text = "Set Locale..."; - this.SetLocaleMI.Click += new System.EventHandler(this.SetLocaleMI_Click); + this.SetLocaleMI.Click += new System.EventHandler(this.SetLocaleMI_ClickAsync); // // SessionTreeCtrl // diff --git a/Samples/Controls.Net4/Sessions/SessionTreeCtrl.cs b/Samples/Controls.Net4/Sessions/SessionTreeCtrl.cs index 0b9cb6dbe..4aa6a48db 100644 --- a/Samples/Controls.Net4/Sessions/SessionTreeCtrl.cs +++ b/Samples/Controls.Net4/Sessions/SessionTreeCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -37,6 +37,7 @@ using Opc.Ua.Client.Controls; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -98,7 +99,7 @@ public ServiceMessageContext MessageContext /// /// Closes all open sessions within the control. /// - public void Close() + public async Task CloseAsync(CancellationToken ct = default) { // close any dialogs. foreach (SubscriptionDlg dialog in new List(m_dialogs.Values)) @@ -113,17 +114,17 @@ public void Close() if (session != null) { - session.Close(); + await session.CloseAsync(ct); } } - Clear(); + await ClearAsync(ct); } /// /// Clears the contents of the control, /// - public void Clear() + public async Task ClearAsync(CancellationToken ct = default) { // close all active sessions. foreach (TreeNode root in NodesTV.Nodes) @@ -132,7 +133,7 @@ public void Clear() if (session != null) { - session.Close(); + await session.CloseAsync(ct); } } @@ -169,9 +170,9 @@ public ToolStripStatusLabel ServerStatusCtrl /// /// Creates a session with the endpoint. /// - public async Task Connect(ConfiguredEndpoint endpoint) + public async Task ConnectAsync(ConfiguredEndpoint endpoint, CancellationToken ct = default) { - if (endpoint == null) throw new ArgumentNullException("endpoint"); + if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); EndpointDescriptionCollection availableEndpoints = null; @@ -204,7 +205,7 @@ public async Task Connect(ConfiguredEndpoint endpoint) throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate must be specified."); } - clientCertificate = await m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true); + clientCertificate = await m_configuration.SecurityConfiguration.ApplicationCertificate.FindAsync(true, ct: ct); if (clientCertificate == null) { @@ -214,7 +215,7 @@ public async Task Connect(ConfiguredEndpoint endpoint) // load certificate chain clientCertificateChain = new X509Certificate2Collection(clientCertificate); List issuers = new List(); - await m_configuration.CertificateValidator.GetIssuers(clientCertificate, issuers); + await m_configuration.CertificateValidator.GetIssuersAsync(clientCertificate, issuers); for (int i = 0; i < issuers.Count; i++) { clientCertificateChain.Add(issuers[i].Certificate); @@ -231,15 +232,15 @@ public async Task Connect(ConfiguredEndpoint endpoint) m_messageContext); // create the session. - return Connect(endpoint, channel, availableEndpoints); + return await ConnectAsync(endpoint, channel, availableEndpoints, ct); } /// /// Opens a new session. /// - public Session Connect(ConfiguredEndpoint endpoint, ITransportChannel channel, EndpointDescriptionCollection availableEndpoints) + public async Task ConnectAsync(ConfiguredEndpoint endpoint, ITransportChannel channel, EndpointDescriptionCollection availableEndpoints, CancellationToken ct = default) { - if (channel == null) throw new ArgumentNullException("channel"); + if (channel == null) throw new ArgumentNullException(nameof(channel)); try { @@ -256,7 +257,7 @@ public Session Connect(ConfiguredEndpoint endpoint, ITransportChannel channel, E channel = null; // delete the existing session. - Close(); + await CloseAsync(ct); // add session to tree. AddNode(session); @@ -277,9 +278,9 @@ public Session Connect(ConfiguredEndpoint endpoint, ITransportChannel channel, E /// /// Deletes a session. /// - public void Delete(Session session) + public async Task DeleteAsync(Session session, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); + if (session == null) throw new ArgumentNullException(nameof(session)); TreeNode node = FindNode(NodesTV.Nodes, session); @@ -295,7 +296,7 @@ public void Delete(Session session) dialog.Close(); } - session.Close(); + await session.CloseAsync(ct); NodesTV.SelectedNode = null; SelectNode(); } @@ -303,9 +304,9 @@ public void Delete(Session session) /// /// Deletes a subscription. /// - public void Delete(Subscription subscription) + public async Task DeleteAsync(Subscription subscription, CancellationToken ct = default) { - if (subscription == null) throw new ArgumentNullException("subscription"); + if (subscription == null) throw new ArgumentNullException(nameof(subscription)); // close any dialog. SubscriptionDlg dialog = null; @@ -316,7 +317,7 @@ public void Delete(Subscription subscription) } Session session = subscription.Session as Session; - session.RemoveSubscription(subscription); + await session.RemoveSubscriptionAsync(subscription, ct); TreeNode node = FindNode(NodesTV.Nodes, subscription); @@ -332,9 +333,9 @@ public void Delete(Subscription subscription) /// /// Deletes a monitored item. /// - public void Delete(MonitoredItem monitoredItem) + public async Task DeleteAsync(MonitoredItem monitoredItem, CancellationToken ct = default) { - if (monitoredItem == null) throw new ArgumentNullException("monitoredItem"); + if (monitoredItem == null) throw new ArgumentNullException(nameof(monitoredItem)); TreeNode node = FindNode(NodesTV.Nodes, monitoredItem); @@ -346,21 +347,21 @@ public void Delete(MonitoredItem monitoredItem) Subscription subscription = monitoredItem.Subscription; subscription.RemoveItem(monitoredItem); - subscription.ApplyChanges(); + await subscription.ApplyChangesAsync(ct); NodesTV.SelectedNode = FindNode(NodesTV.Nodes, subscription); } /// /// Creates a new subscription. /// - public Subscription CreateSubscription(Session session) + public async Task CreateSubscriptionAsync(Session session, CancellationToken ct = default) { // create form. SubscriptionDlg dialog = new SubscriptionDlg(); dialog.FormClosing += new FormClosingEventHandler(Subscription_FormClosing); // create subscription. - Subscription subscription = dialog.New(session); + Subscription subscription = await dialog.NewAsync(session, ct); if (subscription != null) { @@ -480,7 +481,7 @@ protected override void SelectNode() // update address space control. if (m_AddressSpaceCtrl != null) { - m_AddressSpaceCtrl.SetView(session, BrowseViewType.Objects, null); + m_AddressSpaceCtrl.SetViewAsync(session, BrowseViewType.Objects, null); } // update notification messages control. @@ -613,7 +614,7 @@ private TreeNode FindChild(TreeNodeCollection collection, object tag, object chi /// private void AddNode(Session session) { - if (session == null) throw new ArgumentNullException("session"); + if (session == null) throw new ArgumentNullException(nameof(session)); TreeNode node = AddNode(null, session, session.SessionName, "Server"); UpdateNode(node, session); @@ -672,7 +673,7 @@ private void UpdateNode(TreeNode parent, Subscription subscription) AddNode(parent, monitoredItem, monitoredItem.DisplayName, "Property"); } } - #endregion + #endregion private void BrowseAllMI_Click(object sender, EventArgs e) { @@ -726,7 +727,7 @@ private void BrowseObjectsMI_Click(object sender, EventArgs e) } } - private void BrowseObjectTypesMI_Click(object sender, EventArgs e) + private async void BrowseObjectTypesMI_ClickAsync(object sender, EventArgs e) { try { @@ -743,7 +744,7 @@ private void BrowseObjectTypesMI_Click(object sender, EventArgs e) if (session != null) { - new BrowseTypesDlg().Show(session, ObjectTypeIds.BaseObjectType); + await new BrowseTypesDlg().ShowAsync(session, ObjectTypeIds.BaseObjectType); } } catch (Exception exception) @@ -752,7 +753,7 @@ private void BrowseObjectTypesMI_Click(object sender, EventArgs e) } } - private void BrowseVariableTypesMI_Click(object sender, EventArgs e) + private async void BrowseVariableTypesMI_ClickAsync(object sender, EventArgs e) { try { @@ -769,7 +770,7 @@ private void BrowseVariableTypesMI_Click(object sender, EventArgs e) if (session != null) { - new BrowseTypesDlg().Show(session, VariableTypeIds.BaseDataVariableType); + await new BrowseTypesDlg().ShowAsync(session, VariableTypeIds.BaseDataVariableType); } } catch (Exception exception) @@ -830,7 +831,7 @@ private void BrowseReferenceTypesMI_Click(object sender, EventArgs e) } } - private void BrowseEventTypesMI_Click(object sender, EventArgs e) + private async void BrowseEventTypesMI_ClickAsync(object sender, EventArgs e) { try { @@ -847,7 +848,7 @@ private void BrowseEventTypesMI_Click(object sender, EventArgs e) if (session != null) { - new BrowseTypesDlg().Show(session, ObjectTypeIds.BaseEventType); + await new BrowseTypesDlg().ShowAsync(session, ObjectTypeIds.BaseEventType); } } catch (Exception exception) @@ -856,7 +857,7 @@ private void BrowseEventTypesMI_Click(object sender, EventArgs e) } } - private void BrowseServerViewsMI_DropDownOpening(object sender, EventArgs e) + private async void BrowseServerViewsMI_DropDownOpeningAsync(object sender, EventArgs e) { try { @@ -883,7 +884,7 @@ private void BrowseServerViewsMI_DropDownOpening(object sender, EventArgs e) browser.NodeClassMask = (int)NodeClass.View; browser.ContinueUntilDone = true; - ReferenceDescriptionCollection references = browser.Browse(Objects.ViewsFolder); + ReferenceDescriptionCollection references = await browser.BrowseAsync(Objects.ViewsFolder); foreach (ReferenceDescription reference in references) { @@ -935,7 +936,7 @@ void BrowseServerViewsMI_Click(object sender, EventArgs e) } } - private void SubscriptionCreateMI_Click(object sender, EventArgs e) + private async void SubscriptionCreateMI_ClickAsync(object sender, EventArgs e) { try { @@ -956,7 +957,7 @@ private void SubscriptionCreateMI_Click(object sender, EventArgs e) } // create the subscription. - CreateSubscription(session); + await CreateSubscriptionAsync(session); } catch (Exception exception) { @@ -964,7 +965,7 @@ private void SubscriptionCreateMI_Click(object sender, EventArgs e) } } - void Subscription_FormClosing(object sender, FormClosingEventArgs e) + private void Subscription_FormClosing(object sender, FormClosingEventArgs e) { foreach (KeyValuePair current in m_dialogs) { @@ -976,11 +977,11 @@ void Subscription_FormClosing(object sender, FormClosingEventArgs e) } } - private async void NewSessionMI_Click(object sender, EventArgs e) + private async void NewSessionMI_ClickAsync(object sender, EventArgs e) { try { - await Connect(m_endpoint); + await ConnectAsync(m_endpoint); } catch (Exception exception) { @@ -988,7 +989,7 @@ private async void NewSessionMI_Click(object sender, EventArgs e) } } - private void DeleteMI_Click(object sender, EventArgs e) + private async void DeleteMI_ClickAsync(object sender, EventArgs e) { try { @@ -1005,7 +1006,7 @@ private void DeleteMI_Click(object sender, EventArgs e) if (session != null) { - Delete(session); + await DeleteAsync(session); } // delete subscription @@ -1013,7 +1014,7 @@ private void DeleteMI_Click(object sender, EventArgs e) if (subscription != null) { - Delete(subscription); + await DeleteAsync(subscription); } // delete monitored item @@ -1021,7 +1022,7 @@ private void DeleteMI_Click(object sender, EventArgs e) if (monitoredItem != null) { - Delete(monitoredItem); + await DeleteAsync(monitoredItem); } } catch (Exception exception) @@ -1030,7 +1031,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } } - private void ReadMI_Click(object sender, EventArgs e) + private async void ReadMI_ClickAsync(object sender, EventArgs e) { try { @@ -1079,7 +1080,7 @@ private void ReadMI_Click(object sender, EventArgs e) } // show form. - new ReadDlg().Show(session, valueIds); + await new ReadDlg().ShowAsync(session, valueIds); } catch (Exception exception) { @@ -1087,7 +1088,7 @@ private void ReadMI_Click(object sender, EventArgs e) } } - private void WriteMI_Click(object sender, EventArgs e) + private async void WriteMI_ClickAsync(object sender, EventArgs e) { try { @@ -1148,7 +1149,7 @@ private void WriteMI_Click(object sender, EventArgs e) } // show form. - new WriteDlg().Show(session, values); + await new WriteDlg().ShowAsync(session, values); } catch (Exception exception) { @@ -1156,7 +1157,7 @@ private void WriteMI_Click(object sender, EventArgs e) } } - private void SubscriptionEnabledPublishingMI_Click(object sender, EventArgs e) + private async void SubscriptionEnabledPublishingMI_ClickAsync(object sender, EventArgs e) { try { @@ -1173,7 +1174,7 @@ private void SubscriptionEnabledPublishingMI_Click(object sender, EventArgs e) if (subscription != null) { - subscription.SetPublishingMode(SubscriptionEnabledPublishingMI.Checked); + await subscription.SetPublishingModeAsync(SubscriptionEnabledPublishingMI.Checked); } } catch (Exception exception) @@ -1268,7 +1269,7 @@ private void SessionSaveMI_Click(object sender, EventArgs e) } } - private void SessionLoadMI_Click(object sender, EventArgs e) + private async void SessionLoadMI_ClickAsync(object sender, EventArgs e) { try { @@ -1322,7 +1323,7 @@ private void SessionLoadMI_Click(object sender, EventArgs e) { foreach (Subscription subscription in subscriptions) { - subscription.Create(); + await subscription.CreateAsync(); } } } @@ -1349,7 +1350,7 @@ private void NewWindowMI_Click(object sender, EventArgs e) } } - private void SetLocaleMI_Click(object sender, EventArgs e) + private async void SetLocaleMI_ClickAsync(object sender, EventArgs e) { try { @@ -1361,7 +1362,7 @@ private void SetLocaleMI_Click(object sender, EventArgs e) return; } - string locale = new SelectLocaleDlg().ShowDialog(session); + string locale = await new SelectLocaleDlg().ShowDialogAsync(session); if (locale == null) { @@ -1369,7 +1370,7 @@ private void SetLocaleMI_Click(object sender, EventArgs e) } PreferredLocales = new string[] { locale }; - session.ChangePreferredLocales(new StringCollection(PreferredLocales)); + await session.ChangePreferredLocalesAsync(new StringCollection(PreferredLocales), CancellationToken.None); } catch (Exception exception) { diff --git a/Samples/Controls.Net4/Sessions/TypeHierarchyListCtrl.cs b/Samples/Controls.Net4/Sessions/TypeHierarchyListCtrl.cs index b9c72d4fa..c1badc6bc 100644 --- a/Samples/Controls.Net4/Sessions/TypeHierarchyListCtrl.cs +++ b/Samples/Controls.Net4/Sessions/TypeHierarchyListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample { @@ -47,35 +49,35 @@ public partial class TypeHierarchyListCtrl : Opc.Ua.Client.Controls.BaseListCtrl public TypeHierarchyListCtrl() { InitializeComponent(); - SetColumns(m_ColumnNames); + SetColumns(m_ColumnNames); } - #endregion + #endregion #region Private Fields private Session m_session; - // The columns to display in the control. - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "Type", HorizontalAlignment.Left, null }, - new object[] { "Description", HorizontalAlignment.Left, null } - }; + // The columns to display in the control. + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "Type", HorizontalAlignment.Left, null }, + new object[] { "Description", HorizontalAlignment.Left, null } + }; - private class InstanceDeclaration + private sealed class InstanceDeclaration { public ILocalNode Instance; public string DisplayPath; public string DataType; public string Description; } - #endregion + #endregion #region Public Interface /// /// Initializes the control. /// - public void Initialize(Session session, NodeId typeId) + public async Task InitializeAsync(Session session, NodeId typeId, CancellationToken ct = default) { ItemsLV.Items.Clear(); AdjustColumns(); @@ -85,29 +87,29 @@ public void Initialize(Session session, NodeId typeId) return; } - ILocalNode root = session.NodeCache.Find(typeId) as ILocalNode; + ILocalNode root = await session.NodeCache.FindAsync(typeId, ct) as ILocalNode; if (root == null) { return; } - + m_session = session; - SortedDictionary instances = new SortedDictionary(); - + SortedDictionary instances = new SortedDictionary(); + InstanceDeclaration declaration = new InstanceDeclaration(); declaration.Instance = root; declaration.DisplayPath = Utils.Format("({0})", root.NodeClass); declaration.Description = Utils.Format("{0}", root.Description); declaration.DataType = "NodeId"; - + IVariableBase variable = root as IVariableBase; if (variable != null) { - INode dataType = m_session.NodeCache.Find(variable.DataType); + INode dataType = await m_session.NodeCache.FindAsync(variable.DataType, ct); if (dataType != null) { @@ -118,39 +120,39 @@ public void Initialize(Session session, NodeId typeId) { declaration.DataType += "[]"; } - } + } instances.Add(declaration.DisplayPath, declaration); - CollectInstances(root, String.Empty, instances); + await CollectInstancesAsync(root, String.Empty, instances, ct); foreach (InstanceDeclaration instance in instances.Values) { AddItem(instance); } - + AdjustColumns(); } #endregion - + #region Overridden Methods /// - protected override void UpdateItem(ListViewItem listItem, object item) + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { InstanceDeclaration instance = item as InstanceDeclaration; - if (instance == null) - { - base.UpdateItem(listItem, item); - return; - } - - listItem.SubItems[0].Text = instance.DisplayPath; - listItem.SubItems[1].Text = instance.DataType; - listItem.SubItems[2].Text = instance.Description; - - listItem.ImageKey = GuiUtils.GetTargetIcon(m_session, instance.Instance.NodeClass, instance.Instance.TypeDefinitionId); - listItem.Tag = item; + if (instance == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } + + listItem.SubItems[0].Text = instance.DisplayPath; + listItem.SubItems[1].Text = instance.DataType; + listItem.SubItems[2].Text = instance.Description; + + listItem.ImageKey = await GuiUtils.GetTargetIconAsync(m_session, instance.Instance.NodeClass, instance.Instance.TypeDefinitionId, ct); + listItem.Tag = item; } #endregion @@ -158,8 +160,8 @@ protected override void UpdateItem(ListViewItem listItem, object item) /// /// Collects the instance declarations to display in the control. /// - private void CollectInstances(ILocalNode parent, string basePath, SortedDictionary instances) - { + private async Task CollectInstancesAsync(ILocalNode parent, string basePath, SortedDictionary instances, CancellationToken ct = default) + { if (parent == null) { return; @@ -173,14 +175,14 @@ private void CollectInstances(ILocalNode parent, string basePath, SortedDictiona for (int ii = 0; ii < supertypes.Count; ii++) { - ILocalNode supertype = m_session.NodeCache.Find(supertypes[ii].TargetId) as ILocalNode; + ILocalNode supertype = await m_session.NodeCache.FindAsync(supertypes[ii].TargetId, ct) as ILocalNode; if (supertype == null) { continue; } - CollectInstances(supertype, basePath, instances); + await CollectInstancesAsync(supertype, basePath, instances, ct); } IList children = parent.References.Find( @@ -191,7 +193,7 @@ private void CollectInstances(ILocalNode parent, string basePath, SortedDictiona for (int ii = 0; ii < children.Count; ii++) { - ILocalNode child = m_session.NodeCache.Find(children[ii].TargetId) as ILocalNode; + ILocalNode child = await m_session.NodeCache.FindAsync(children[ii].TargetId, ct) as ILocalNode; if (child == null) { @@ -209,12 +211,12 @@ private void CollectInstances(ILocalNode parent, string basePath, SortedDictiona } string displayPath = Utils.Format("{0}", child); - + if (!String.IsNullOrEmpty(basePath)) { displayPath = Utils.Format("{0}/{1}", basePath, displayPath); } - + InstanceDeclaration declaration = new InstanceDeclaration(); declaration.Instance = child; @@ -226,7 +228,7 @@ private void CollectInstances(ILocalNode parent, string basePath, SortedDictiona if (variable != null) { - INode dataType = m_session.NodeCache.Find(variable.DataType); + INode dataType = await m_session.NodeCache.FindAsync(variable.DataType, ct); if (dataType != null) { @@ -238,16 +240,16 @@ private void CollectInstances(ILocalNode parent, string basePath, SortedDictiona declaration.DataType += "[]"; } } - + IObject objectn = child as IObject; if (objectn != null) - { + { declaration.DataType = "NodeId"; } instances[displayPath] = declaration; - CollectInstances(child, displayPath, instances); + await CollectInstancesAsync(child, displayPath, instances, ct); } } #endregion diff --git a/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.Designer.cs b/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.Designer.cs index be9cfffed..8f18cbb8d 100644 --- a/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.Designer.cs +++ b/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.Designer.cs @@ -87,7 +87,7 @@ private void InitializeComponent() this.RootBTN.Size = new System.Drawing.Size(45, 21); this.RootBTN.Text = "Root"; this.RootBTN.ToolTipText = "Root"; - this.RootBTN.DropDownOpening += new System.EventHandler(this.RootBTN_DropDownOpening); + this.RootBTN.DropDownOpening += new System.EventHandler(this.RootBTN_DropDownOpeningAsync); this.RootBTN.Click += new System.EventHandler(this.RootBTN_Click); // // childToolStripMenuItem diff --git a/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.cs b/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.cs index 32e432c32..9058f0e4f 100644 --- a/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.cs +++ b/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample { @@ -49,12 +51,12 @@ public TypeNavigatorCtrl() InitializeComponent(); } #endregion - + #region Private Fields private Session m_session; private event TypeNavigatorEventHandler m_TypeSelected; #endregion - + #region Public Interface /// /// Raised when a type is selected in the control. @@ -68,7 +70,7 @@ public event TypeNavigatorEventHandler TypeSelected /// /// Initializes the control. /// - public void Initialize(Session session, NodeId typeId) + public async Task InitializeAsync(Session session, NodeId typeId, CancellationToken ct = default) { if (session == null) { @@ -76,7 +78,7 @@ public void Initialize(Session session, NodeId typeId) return; } - ILocalNode root = session.NodeCache.Find(typeId) as ILocalNode; + ILocalNode root = await session.NodeCache.FindAsync(typeId, ct) as ILocalNode; if (root == null) { @@ -103,7 +105,7 @@ private void RootBTN_Click(object sender, EventArgs e) { return; } - + ILocalNode node = button.Tag as ILocalNode; if (node == null) @@ -129,11 +131,11 @@ private void RootBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void RootBTN_DropDownOpening(object sender, EventArgs e) + private async void RootBTN_DropDownOpeningAsync(object sender, EventArgs e) { try { @@ -152,7 +154,7 @@ private void RootBTN_DropDownOpening(object sender, EventArgs e) { return; } - + IList subtypes = node.References.Find( ReferenceTypeIds.HasSubtype, false, @@ -161,7 +163,7 @@ private void RootBTN_DropDownOpening(object sender, EventArgs e) for (int ii = 0; ii < subtypes.Count; ii++) { - ILocalNode subtype = m_session.NodeCache.Find(subtypes[ii].TargetId) as ILocalNode; + ILocalNode subtype = await m_session.NodeCache.FindAsync(subtypes[ii].TargetId) as ILocalNode; if (subtype == null) { @@ -185,11 +187,11 @@ private void RootBTN_DropDownOpening(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - void ChildBTN_Click(object sender, EventArgs e) + private void ChildBTN_Click(object sender, EventArgs e) { try { @@ -199,13 +201,13 @@ void ChildBTN_Click(object sender, EventArgs e) { return; } - + ILocalNode node = menuItem.Tag as ILocalNode; if (node == null) { return; - } + } bool found = false; @@ -222,21 +224,21 @@ void ChildBTN_Click(object sender, EventArgs e) TypePathCTRL.Items.Remove(TypePathCTRL.Items[ii]); } } - + if (!found) { return; } string text = Utils.Format("{0}", node.DisplayName); - + ToolStripDropDownButton button = new ToolStripDropDownButton(text); button.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; button.Name = Utils.Format("Type{0}BTN", TypePathCTRL.Items.Count); button.Size = new System.Drawing.Size(48, 21); button.Text = Utils.Format("{0}", node.DisplayName); - button.DropDownOpening += RootBTN_DropDownOpening; + button.DropDownOpening += RootBTN_DropDownOpeningAsync; button.Click += RootBTN_Click; button.Tag = node; @@ -249,7 +251,7 @@ void ChildBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.Designer.cs b/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.Designer.cs index d9d231b6b..a348c096e 100644 --- a/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.Designer.cs @@ -97,7 +97,7 @@ private void InitializeComponent() this.SelectNodeMI.Name = "SelectEventTypeMI"; this.SelectNodeMI.Size = new System.Drawing.Size(161, 22); this.SelectNodeMI.Text = "Select Node..."; - this.SelectNodeMI.Click += new System.EventHandler(this.SelectNodeMI_Click); + this.SelectNodeMI.Click += new System.EventHandler(this.SelectNodeMI_ClickAsync); // // CreateElementMI // diff --git a/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.cs b/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.cs index 9aff0da3a..9eeb0f63f 100644 --- a/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading; +using System.Threading.Tasks; namespace Opc.Ua.Sample.Controls { @@ -45,8 +47,8 @@ public partial class ContentFilterElementListCtrl : Opc.Ua.Client.Controls.BaseL { public ContentFilterElementListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -58,11 +60,11 @@ public ContentFilterElementListCtrl() /// The columns to display in the control. /// private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Index", HorizontalAlignment.Left, null }, - new object[] { "Expression", HorizontalAlignment.Left, null } - }; - #endregion + { + new object[] { "Index", HorizontalAlignment.Left, null }, + new object[] { "Expression", HorizontalAlignment.Left, null } + }; + #endregion #region Public Interface /// @@ -79,17 +81,17 @@ public void Clear() /// public void Initialize(Session session, ContentFilter filter) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); - + m_session = session; m_browser = new Browser(session); - m_filter = filter; + m_filter = filter; if (m_filter == null) { - return; + return; } foreach (ContentFilterElement element in filter.Elements) @@ -106,7 +108,7 @@ public void Initialize(Session session, ContentFilter filter) public ContentFilter GetFilter() { ContentFilter filter = new ContentFilter(); - + for (int ii = 0; ii < ItemsLV.Items.Count; ii++) { ContentFilterElement element = ItemsLV.Items[ii].Tag as ContentFilterElement; @@ -126,7 +128,7 @@ public ContentFilter GetFilter() public List GetElements() { List elements = new List(); - + for (int ii = 0; ii < ItemsLV.Items.Count; ii++) { ContentFilterElement element = ItemsLV.Items[ii].Tag as ContentFilterElement; @@ -144,41 +146,41 @@ public List GetElements() #region Overridden Methods /// protected override void EnableMenuItems(ListViewItem clickedItem) - { - SetOperatorMI.Enabled = ItemsLV.SelectedItems.Count == 1; - SelectNodeMI.Enabled = true; - EditValueMI.Enabled = ItemsLV.SelectedItems.Count == 1; - DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; - CreateElementMI.Enabled = ItemsLV.SelectedItems.Count > 0; + { + SetOperatorMI.Enabled = ItemsLV.SelectedItems.Count == 1; + SelectNodeMI.Enabled = true; + EditValueMI.Enabled = ItemsLV.SelectedItems.Count == 1; + DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; + CreateElementMI.Enabled = ItemsLV.SelectedItems.Count > 0; CreateElementAndMI.Enabled = ItemsLV.SelectedItems.Count == 2; - CreateElementOrMI.Enabled = ItemsLV.SelectedItems.Count == 2; + CreateElementOrMI.Enabled = ItemsLV.SelectedItems.Count == 2; CreateElementNotMI.Enabled = ItemsLV.SelectedItems.Count == 1; - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item, int index) + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, int index, CancellationToken ct = default) { - ContentFilterElement element = item as ContentFilterElement; - - if (element == null) - { - base.UpdateItem(listItem, item); - return; - } - + ContentFilterElement element = item as ContentFilterElement; + + if (element == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } + listItem.SubItems[0].Text = String.Format("[{0}]", index); - listItem.SubItems[1].Text = String.Format("{0}", element.ToString(m_session.NodeCache)); - + listItem.SubItems[1].Text = String.Format("{0}", element.ToString(m_session.NodeCache.AsNodeTable())); + listItem.Tag = element; } #endregion - + #region Event Handlers /// /// Updates the control with a new filter. /// private void Update(ContentFilter filter) - { + { BeginUpdate(); int index = 0; @@ -187,7 +189,7 @@ private void Update(ContentFilter filter) { AddItem(element, "Property", index++); } - + EndUpdate(); AdjustColumns(); @@ -209,15 +211,15 @@ private void SetOperatorMI_Click(object sender, EventArgs e) if (!new FilterOperatorEditDlg().ShowDialog(ref op)) { return; - } + } element.FilterOperator = op; - UpdateItem(ItemsLV.SelectedItems[0], element); + UpdateItemAsync(ItemsLV.SelectedItems[0], element); AdjustColumns(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -230,25 +232,25 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void SelectNodeMI_Click(object sender, EventArgs e) + private async void SelectNodeMI_ClickAsync(object sender, EventArgs e) { try { - ReferenceDescription reference = new SelectNodeDlg().ShowDialog(m_browser, ObjectTypes.BaseEventType); + ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync(m_browser, ObjectTypes.BaseEventType); if (reference != null) { - Node node = m_session.NodeCache.Find(reference.NodeId) as Node; + Node node = await m_session.NodeCache.FindAsync(reference.NodeId) as Node; if (node == null) { return; } - + ContentFilterElement element = null; // build the relative path. @@ -268,7 +270,7 @@ private void SelectNodeMI_Click(object sender, EventArgs e) // create attribute operand. SimpleAttributeOperand attribute = new SimpleAttributeOperand( - m_session.FilterContext, + m_session.FilterContext, typeId, browsePath); @@ -284,7 +286,7 @@ private void SelectNodeMI_Click(object sender, EventArgs e) { // create attribute operand. SimpleAttributeOperand attribute = new SimpleAttributeOperand( - m_session.FilterContext, + m_session.FilterContext, typeId, browsePath); @@ -317,7 +319,7 @@ private void SelectNodeMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -329,10 +331,10 @@ private void CreateElementAndMI_Click(object sender, EventArgs e) { return; } - + ContentFilterElement element1 = ItemsLV.SelectedItems[0].Tag as ContentFilterElement; ContentFilterElement element2 = ItemsLV.SelectedItems[1].Tag as ContentFilterElement; - + ContentFilter filter = GetFilter(); filter.Push(FilterOperator.And, element1, element2); @@ -340,7 +342,7 @@ private void CreateElementAndMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -352,10 +354,10 @@ private void CreateElementOrMI_Click(object sender, EventArgs e) { return; } - + ContentFilterElement element1 = ItemsLV.SelectedItems[0].Tag as ContentFilterElement; ContentFilterElement element2 = ItemsLV.SelectedItems[1].Tag as ContentFilterElement; - + ContentFilter filter = GetFilter(); filter.Push(FilterOperator.Or, element1, element2); @@ -363,7 +365,7 @@ private void CreateElementOrMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -375,7 +377,7 @@ private void CreateElementNotMI_Click(object sender, EventArgs e) { return; } - + ContentFilterElement element1 = ItemsLV.SelectedItems[0].Tag as ContentFilterElement; ContentFilter filter = GetFilter(); @@ -385,10 +387,10 @@ private void CreateElementNotMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - + private void EditValueMI_Click(object sender, EventArgs e) { try @@ -404,7 +406,7 @@ private void EditValueMI_Click(object sender, EventArgs e) if (operands.Count != 2) { - return; + return; } LiteralOperand literal = operands[1] as LiteralOperand; @@ -437,7 +439,7 @@ private void EditValueMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.Designer.cs b/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.Designer.cs index a434e38ee..b56cdc51e 100644 --- a/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.Designer.cs @@ -103,7 +103,7 @@ private void InitializeComponent() this.ApplyBTN.TabIndex = 4; this.ApplyBTN.Text = "Apply"; this.ApplyBTN.UseVisualStyleBackColor = true; - this.ApplyBTN.Click += new System.EventHandler(this.ApplyBTN_Click); + this.ApplyBTN.Click += new System.EventHandler(this.ApplyBTN_ClickAsync); // // SplitterPN // @@ -133,7 +133,7 @@ private void InitializeComponent() this.BrowseCTRL.SessionTreeCtrl = null; this.BrowseCTRL.Size = new System.Drawing.Size(276, 392); this.BrowseCTRL.TabIndex = 1; - this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelected); + this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelectedAsync); // // MonitoredItemsCTRL // diff --git a/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.cs b/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.cs index 59a5372dd..0d5db1e3b 100644 --- a/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -56,15 +56,15 @@ public CreateMonitoredItemsDlg() private Subscription m_subscription; private SubscriptionStateChangedEventHandler m_SubscriptionStateChanged; #endregion - + #region Public Interface /// /// Displays the dialog. /// public void Show(Subscription subscription, bool useTypeModel) { - if (subscription == null) throw new ArgumentNullException("subscription"); - + if (subscription == null) throw new ArgumentNullException(nameof(subscription)); + Show(); BringToFront(); @@ -73,24 +73,24 @@ public void Show(Subscription subscription, bool useTypeModel) { m_subscription.StateChanged -= m_SubscriptionStateChanged; } - + // start receiving notifications from the new subscription. m_subscription = subscription; - + if (subscription != null) { m_subscription.StateChanged += m_SubscriptionStateChanged; - } + } m_subscription = subscription; - + BrowseCTRL.AllowPick = true; - BrowseCTRL.SetView(subscription.Session as Session, (useTypeModel)?BrowseViewType.ObjectTypes:BrowseViewType.Objects, null); + BrowseCTRL.SetViewAsync(subscription.Session as Session, (useTypeModel) ? BrowseViewType.ObjectTypes : BrowseViewType.Objects, null); MonitoredItemsCTRL.Initialize(subscription); } #endregion - + #region Event Handlers /// /// Handles a change to the state of the subscription. @@ -110,7 +110,7 @@ void Subscription_StateChanged(Subscription subscription, SubscriptionStateChang try { // ignore notifications for other subscriptions. - if (!Object.ReferenceEquals(m_subscription, subscription)) + if (!Object.ReferenceEquals(m_subscription, subscription)) { return; } @@ -120,11 +120,11 @@ void Subscription_StateChanged(Subscription subscription, SubscriptionStateChang } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) + private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEventArgs e) { try { @@ -132,25 +132,25 @@ private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) { if (reference.ReferenceTypeId == ReferenceTypeIds.HasProperty || reference.IsForward) { - MonitoredItemsCTRL.AddItem(reference); + await MonitoredItemsCTRL.AddItemAsync(reference); } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void ApplyBTN_Click(object sender, EventArgs e) + private async void ApplyBTN_ClickAsync(object sender, EventArgs e) { try { - MonitoredItemsCTRL.ApplyChanges(true); + await MonitoredItemsCTRL.ApplyChangesAsync(true); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -162,7 +162,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/DataChangeFilterEditDlg.cs b/Samples/Controls.Net4/Subscriptions/DataChangeFilterEditDlg.cs index 6d929a092..9db70682c 100644 --- a/Samples/Controls.Net4/Subscriptions/DataChangeFilterEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/DataChangeFilterEditDlg.cs @@ -47,14 +47,14 @@ public DataChangeFilterEditDlg() { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); - + Array values = Enum.GetValues(typeof(DataChangeTrigger)); foreach (object value in values) { TriggerCB.Items.Add(value); } - + values = Enum.GetValues(typeof(DeadbandType)); foreach (object value in values) @@ -68,7 +68,7 @@ public DataChangeFilterEditDlg() /// public bool ShowDialog(Session session, MonitoredItem monitoredItem) { - if (monitoredItem == null) throw new ArgumentNullException("monitoredItem"); + if (monitoredItem == null) throw new ArgumentNullException(nameof(monitoredItem)); DataChangeFilter filter = monitoredItem.Filter as DataChangeFilter; @@ -76,22 +76,22 @@ public bool ShowDialog(Session session, MonitoredItem monitoredItem) { filter = new DataChangeFilter(); - filter.Trigger = DataChangeTrigger.StatusValue; + filter.Trigger = DataChangeTrigger.StatusValue; filter.DeadbandValue = 0; - filter.DeadbandType = (uint)(int)DeadbandType.None; + filter.DeadbandType = (uint)(int)DeadbandType.None; } - TriggerCB.SelectedItem = filter.Trigger; + TriggerCB.SelectedItem = filter.Trigger; DeadbandTypeCB.SelectedItem = (DeadbandType)(int)filter.DeadbandType; - DeadbandNC.Value = (decimal)filter.DeadbandValue; - + DeadbandNC.Value = (decimal)filter.DeadbandValue; + if (ShowDialog() != DialogResult.OK) { return false; } - filter.Trigger = (DataChangeTrigger)TriggerCB.SelectedItem; - filter.DeadbandType = Convert.ToUInt32(DeadbandTypeCB.SelectedItem); + filter.Trigger = (DataChangeTrigger)TriggerCB.SelectedItem; + filter.DeadbandType = Convert.ToUInt32(DeadbandTypeCB.SelectedItem); filter.DeadbandValue = (double)DeadbandNC.Value; monitoredItem.Filter = filter; @@ -100,7 +100,7 @@ public bool ShowDialog(Session session, MonitoredItem monitoredItem) } private void OkBTN_Click(object sender, EventArgs e) - { + { DialogResult = DialogResult.OK; } diff --git a/Samples/Controls.Net4/Subscriptions/DataChangeNotificationListCtrl.cs b/Samples/Controls.Net4/Subscriptions/DataChangeNotificationListCtrl.cs index 0fc99e990..677a9966c 100644 --- a/Samples/Controls.Net4/Subscriptions/DataChangeNotificationListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/DataChangeNotificationListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -45,8 +46,8 @@ public partial class DataChangeNotificationListCtrl : Opc.Ua.Client.Controls.Bas { public DataChangeNotificationListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -59,15 +60,15 @@ public DataChangeNotificationListCtrl() /// The columns to display in the control. /// private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Item", HorizontalAlignment.Left, null }, - new object[] { "Variable", HorizontalAlignment.Left, null }, - new object[] { "Value", HorizontalAlignment.Left, String.Empty, 250 }, - new object[] { "Status", HorizontalAlignment.Left, String.Empty }, - new object[] { "Source Time", HorizontalAlignment.Center, String.Empty }, - new object[] { "Server Time", HorizontalAlignment.Center, String.Empty } - }; - #endregion + { + new object[] { "Item", HorizontalAlignment.Left, null }, + new object[] { "Variable", HorizontalAlignment.Left, null }, + new object[] { "Value", HorizontalAlignment.Left, String.Empty, 250 }, + new object[] { "Status", HorizontalAlignment.Left, String.Empty }, + new object[] { "Source Time", HorizontalAlignment.Center, String.Empty }, + new object[] { "Server Time", HorizontalAlignment.Center, String.Empty } + }; + #endregion #region Public Interface /// @@ -76,17 +77,17 @@ public DataChangeNotificationListCtrl() [DefaultValue(20)] public int MaxChangeCount { - get { return m_maxChangeCount; } + get { return m_maxChangeCount; } set { m_maxChangeCount = value; } } - + /// /// Whether to show previous values in the control after an update. /// [DefaultValue(false)] public bool ShowHistory { - get { return m_showHistory; } + get { return m_showHistory; } set { m_showHistory = value; } } @@ -102,14 +103,14 @@ public void Clear() /// /// Sets the nodes in the control. /// - public void Initialize(Subscription subscription, MonitoredItem monitoredItem) + public async void InitializeAsync(Subscription subscription, MonitoredItem monitoredItem, CancellationToken ct = default) { - if (subscription == null) throw new ArgumentNullException("subscription"); - + if (subscription == null) throw new ArgumentNullException(nameof(subscription)); + Clear(); - + // start receiving notifications from the new subscription. - m_subscription = subscription; + m_subscription = subscription; m_monitoredItem = monitoredItem; // get the events. @@ -148,14 +149,14 @@ public void Initialize(Subscription subscription, MonitoredItem monitoredItem) } } - UpdateChanges(changes, 0); + await UpdateChangesAsync(changes, 0, ct); AdjustColumns(); } - + /// /// Processes a new notification. /// - public void NotificationReceived(NotificationEventArgs e) + public async Task NotificationReceivedAsync(NotificationEventArgs e, CancellationToken ct = default) { // get the changes. List changes = new List(); @@ -194,7 +195,7 @@ public void NotificationReceived(NotificationEventArgs e) foreach (ListViewItem listItem in ItemsLV.Items) { MonitoredItemNotification change = listItem.Tag as MonitoredItemNotification; - + if (change == null) { continue; @@ -220,22 +221,22 @@ public void NotificationReceived(NotificationEventArgs e) changes.Reverse(); } - UpdateChanges(changes, offset); + await UpdateChangesAsync(changes, offset, ct); AdjustColumns(); } - + /// /// Processes a new notification. /// - public void NotificationReceived(MonitoredItemNotificationEventArgs e) + public async Task NotificationReceivedAsync(MonitoredItemNotificationEventArgs e, CancellationToken ct = default) { MonitoredItemNotification change = e.NotificationValue as MonitoredItemNotification; - + if (change == null) { return; } - + if (m_monitoredItem != null) { if (m_monitoredItem.ClientHandle != change.ClientHandle) @@ -248,13 +249,13 @@ public void NotificationReceived(MonitoredItemNotificationEventArgs e) List changes = new List(); changes.Add(change); - // fill in earlier changes. + // fill in earlier changes. if (m_showHistory) { foreach (ListViewItem listItem in ItemsLV.Items) { change = listItem.Tag as MonitoredItemNotification; - + if (change == null) { continue; @@ -276,11 +277,11 @@ public void NotificationReceived(MonitoredItemNotificationEventArgs e) } } } - - UpdateChanges(changes, 1); + + await UpdateChangesAsync(changes, 1, ct); AdjustColumns(); } - + /// /// Processes a change to the subscription. /// @@ -303,19 +304,19 @@ public void SubscriptionChanged(SubscriptionStateChangedEventArgs e) } } } - + // remove events for items that have been deleted. foreach (ListViewItem listItem in itemsToRemove) { listItem.Remove(); - } + } } } /// /// Updates the display after the publish status for the subscription changes. /// - public void PublishStatusChanged() + public async Task PublishStatusChangedAsync(CancellationToken ct = default) { foreach (ListViewItem listItem in ItemsLV.Items) { @@ -323,10 +324,10 @@ public void PublishStatusChanged() if (change != null) { - UpdateItem(listItem, change); + await UpdateItemAsync(listItem, change, ct); } } - + AdjustColumns(); } #endregion @@ -334,22 +335,22 @@ public void PublishStatusChanged() #region Overridden Methods /// protected override void EnableMenuItems(ListViewItem clickedItem) - { - ViewMI.Enabled = ItemsLV.SelectedItems.Count == 1; + { + ViewMI.Enabled = ItemsLV.SelectedItems.Count == 1; DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; - } - + } + /// protected override void PickItems() { base.PickItems(); ViewMI_Click(this, null); } - + /// /// Updates the events displayed in the control. /// - private void UpdateChanges(IList changes, int offset) + private async Task UpdateChangesAsync(IList changes, int offset, CancellationToken ct = default) { // save selected indexes. List indexes = new List(ItemsLV.SelectedIndices.Count); @@ -358,7 +359,7 @@ private void UpdateChanges(IList changes, int offset) { indexes.Add(index); } - + // add all new values. if (m_showHistory) { @@ -374,13 +375,13 @@ private void UpdateChanges(IList changes, int offset) // only update changed values. else - { + { foreach (ListViewItem listItem in ItemsLV.Items) { listItem.ForeColor = Color.Gray; } - for (int ii = changes.Count-1; ii >= 0; ii--) + for (int ii = changes.Count - 1; ii >= 0; ii--) { bool found = false; @@ -390,7 +391,7 @@ private void UpdateChanges(IList changes, int offset) if (change != null && change.ClientHandle == changes[ii].ClientHandle) { - UpdateItem(listItem, changes[ii]); + await UpdateItemAsync(listItem, changes[ii], ct); found = true; listItem.ForeColor = Color.Empty; break; @@ -398,7 +399,7 @@ private void UpdateChanges(IList changes, int offset) } if (!found) - { + { AddItem(changes[ii]); } } @@ -409,29 +410,29 @@ private void UpdateChanges(IList changes, int offset) { ItemsLV.Items[index].Selected = false; - if (index+offset < ItemsLV.Items.Count) + if (index + offset < ItemsLV.Items.Count) { - ItemsLV.Items[index+offset].Selected = true; + ItemsLV.Items[index + offset].Selected = true; } } } - /// - protected override void UpdateItem(ListViewItem listItem, object item) + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - MonitoredItemNotification change = item as MonitoredItemNotification; - - if (change == null) - { - base.UpdateItem(listItem, item); - return; - } - + MonitoredItemNotification change = item as MonitoredItemNotification; + + if (change == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } + // fill in the columns. listItem.SubItems[0].Text = String.Format("[{0}]", change.ClientHandle); MonitoredItem monitoredItem = null; - + if (m_subscription != null) { monitoredItem = m_subscription.FindItemByClientHandle(change.ClientHandle); @@ -445,7 +446,7 @@ protected override void UpdateItem(ListViewItem listItem, object item) { listItem.SubItems[1].Text = "(unknown)"; } - + listItem.SubItems[2].Text = String.Format("{0}", change.Value.WrappedValue); // check of publishing has stopped for some reason. @@ -468,7 +469,7 @@ protected override void UpdateItem(ListViewItem listItem, object item) { listItem.SubItems[4].Text = String.Empty; } - + time = change.Value.ServerTimestamp; if (time != null && time != DateTime.MinValue) @@ -479,12 +480,12 @@ protected override void UpdateItem(ListViewItem listItem, object item) { listItem.SubItems[5].Text = String.Empty; } - + listItem.Tag = change; - listItem.ForeColor = (m_subscription.PublishingStopped)?Color.Red:Color.Empty; + listItem.ForeColor = (m_subscription.PublishingStopped) ? Color.Red : Color.Empty; } #endregion - + #region Event Handlers private void ViewMI_Click(object sender, EventArgs e) { @@ -501,7 +502,7 @@ private void ViewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/EventFilterDlg.Designer.cs b/Samples/Controls.Net4/Subscriptions/EventFilterDlg.Designer.cs index 111df91bb..9797902d6 100644 --- a/Samples/Controls.Net4/Subscriptions/EventFilterDlg.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/EventFilterDlg.Designer.cs @@ -172,7 +172,7 @@ private void InitializeComponent() this.BrowseCTRL.SessionTreeCtrl = null; this.BrowseCTRL.Size = new System.Drawing.Size(340, 395); this.BrowseCTRL.TabIndex = 1; - this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelected); + this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelectedAsync); // // FilterOperandsCTRL // diff --git a/Samples/Controls.Net4/Subscriptions/EventFilterDlg.cs b/Samples/Controls.Net4/Subscriptions/EventFilterDlg.cs index 248729a9f..6af6d7e67 100644 --- a/Samples/Controls.Net4/Subscriptions/EventFilterDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/EventFilterDlg.cs @@ -55,25 +55,25 @@ public EventFilterDlg() private Session m_session; private EventFilter m_filter; #endregion - + #region Public Interface /// /// Displays the dialog. /// public EventFilter ShowDialog(Session session, EventFilter filter, bool editWhereClause) { - if (session == null) throw new ArgumentNullException("session"); - if (filter == null) throw new ArgumentNullException("filter"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + if (filter == null) throw new ArgumentNullException(nameof(filter)); + m_session = session; - m_filter = filter; + m_filter = filter; - BrowseCTRL.SetView(m_session, BrowseViewType.EventTypes, null); + BrowseCTRL.SetViewAsync(m_session, BrowseViewType.EventTypes, null); SelectClauseCTRL.Initialize(session, filter.SelectClauses); ContentFilterCTRL.Initialize(session, filter.WhereClause); FilterOperandsCTRL.Initialize(session, null, -1); - MoveBTN_Click((editWhereClause)?NextBTN:BackBTN, null); + MoveBTN_Click((editWhereClause) ? NextBTN : BackBTN, null); if (ShowDialog() != DialogResult.OK) { @@ -83,9 +83,9 @@ public EventFilter ShowDialog(Session session, EventFilter filter, bool editWher return m_filter; } #endregion - + #region Event Handlers - private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) + private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEventArgs e) { try { @@ -93,13 +93,13 @@ private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) { if (reference.ReferenceTypeId == ReferenceTypeIds.HasProperty || reference.IsForward) { - SelectClauseCTRL.AddSelectClause(reference); + await SelectClauseCTRL.AddSelectClauseAsync(reference); } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -126,12 +126,12 @@ private void ContentFilterCTRL_ItemsSelected(object sender, ListItemActionEventA } else { - FilterOperandsCTRL.Initialize(m_session, null, -1); + FilterOperandsCTRL.Initialize(m_session, null, -1); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -140,30 +140,30 @@ private void MoveBTN_Click(object sender, EventArgs e) try { if (sender == NextBTN) - { - BackBTN.Visible = true; - NextBTN.Visible = false; - OkBTN.Visible = true; - ContentFilterCTRL.Visible = true; + { + BackBTN.Visible = true; + NextBTN.Visible = false; + OkBTN.Visible = true; + ContentFilterCTRL.Visible = true; FilterOperandsCTRL.Visible = true; - BrowseCTRL.Visible = false; - SelectClauseCTRL.Visible = false; + BrowseCTRL.Visible = false; + SelectClauseCTRL.Visible = false; } else if (sender == BackBTN) - { - BackBTN.Visible = false; - NextBTN.Visible = true; - OkBTN.Visible = false; - ContentFilterCTRL.Visible = false; + { + BackBTN.Visible = false; + NextBTN.Visible = true; + OkBTN.Visible = false; + ContentFilterCTRL.Visible = false; FilterOperandsCTRL.Visible = false; - BrowseCTRL.Visible = true; - SelectClauseCTRL.Visible = true; + BrowseCTRL.Visible = true; + SelectClauseCTRL.Visible = true; } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -175,7 +175,7 @@ private void OkBTN_Click(object sender, EventArgs e) filter.SelectClauses.AddRange(SelectClauseCTRL.GetSelectClauses()); filter.WhereClause = ContentFilterCTRL.GetFilter(); - + EventFilter.Result result = filter.Validate(new FilterContext(m_session.NamespaceUris, m_session.TypeTree)); if (ServiceResult.IsBad(result.Status)) @@ -189,7 +189,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/Controls.Net4/Subscriptions/EventNotificationListCtrl.cs b/Samples/Controls.Net4/Subscriptions/EventNotificationListCtrl.cs index d05992c1c..cde08bca8 100644 --- a/Samples/Controls.Net4/Subscriptions/EventNotificationListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/EventNotificationListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -45,8 +46,8 @@ public partial class EventNotificationListListCtrl : Opc.Ua.Client.Controls.Base { public EventNotificationListListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -58,15 +59,15 @@ public EventNotificationListListCtrl() /// The columns to display in the control. /// private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Item", HorizontalAlignment.Left, null }, - new object[] { "Type", HorizontalAlignment.Left, null }, - new object[] { "Source", HorizontalAlignment.Left, String.Empty }, - new object[] { "Time", HorizontalAlignment.Center, String.Empty }, - new object[] { "Severity", HorizontalAlignment.Center, String.Empty }, - new object[] { "Message", HorizontalAlignment.Left, String.Empty } - }; - #endregion + { + new object[] { "Item", HorizontalAlignment.Left, null }, + new object[] { "Type", HorizontalAlignment.Left, null }, + new object[] { "Source", HorizontalAlignment.Left, String.Empty }, + new object[] { "Time", HorizontalAlignment.Center, String.Empty }, + new object[] { "Severity", HorizontalAlignment.Center, String.Empty }, + new object[] { "Message", HorizontalAlignment.Left, String.Empty } + }; + #endregion #region Public Interface /// @@ -75,7 +76,7 @@ public EventNotificationListListCtrl() [DefaultValue(20)] public int MaxEventCount { - get { return m_maxEventCount; } + get { return m_maxEventCount; } set { m_maxEventCount = value; } } @@ -93,12 +94,12 @@ public void Clear() /// public void Initialize(Subscription subscription, MonitoredItem monitoredItem) { - if (subscription == null) throw new ArgumentNullException("subscription"); - + if (subscription == null) throw new ArgumentNullException(nameof(subscription)); + Clear(); - + // start receiving notifications from the new subscription. - m_subscription = subscription; + m_subscription = subscription; m_monitoredItem = monitoredItem; // get the events. @@ -122,7 +123,7 @@ public void Initialize(Subscription subscription, MonitoredItem monitoredItem) continue; } } - + events.Add(eventFields); if (events.Count >= MaxEventCount) @@ -140,7 +141,7 @@ public void Initialize(Subscription subscription, MonitoredItem monitoredItem) UpdateEvents(events, 0); AdjustColumns(); } - + /// /// Processes a new notification. /// @@ -164,7 +165,7 @@ public void NotificationReceived(NotificationEventArgs e) { continue; } - } + } events.Add(eventFields); @@ -199,15 +200,15 @@ public void NotificationReceived(NotificationEventArgs e) continue; } } - - events.Add(eventFields); + + events.Add(eventFields); if (events.Count >= MaxEventCount) { break; } } - + UpdateEvents(events, offset); AdjustColumns(); } @@ -218,12 +219,12 @@ public void NotificationReceived(NotificationEventArgs e) public void NotificationReceived(MonitoredItemNotificationEventArgs e) { EventFieldList eventFields = e.NotificationValue as EventFieldList; - + if (eventFields == null) { return; } - + if (m_monitoredItem != null) { if (m_monitoredItem.ClientHandle != eventFields.ClientHandle) @@ -240,7 +241,7 @@ public void NotificationReceived(MonitoredItemNotificationEventArgs e) foreach (ListViewItem listItem in ItemsLV.Items) { eventFields = listItem.Tag as EventFieldList; - + if (m_monitoredItem != null) { if (m_monitoredItem.ClientHandle != eventFields.ClientHandle) @@ -259,11 +260,11 @@ public void NotificationReceived(MonitoredItemNotificationEventArgs e) break; } } - + UpdateEvents(events, 1); AdjustColumns(); } - + /// /// Processes a change to the subscription. /// @@ -286,12 +287,12 @@ public void SubscriptionChanged(SubscriptionStateChangedEventArgs e) } } } - + // remove events for items that have been deleted. foreach (ListViewItem listItem in itemsToRemove) { listItem.Remove(); - } + } } } #endregion @@ -299,18 +300,18 @@ public void SubscriptionChanged(SubscriptionStateChangedEventArgs e) #region Overridden Methods /// protected override void EnableMenuItems(ListViewItem clickedItem) - { - ViewMI.Enabled = ItemsLV.SelectedItems.Count == 1; + { + ViewMI.Enabled = ItemsLV.SelectedItems.Count == 1; DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; - } + } /// protected override void PickItems() { base.PickItems(); ViewMI_Click(this, null); - } - + } + /// /// Updates the events displayed in the control. /// @@ -326,7 +327,7 @@ private void UpdateEvents(IList events, int offset) // update items. BeginUpdate(); - + foreach (EventFieldList eventFields in events) { AddItem(eventFields); @@ -339,23 +340,23 @@ private void UpdateEvents(IList events, int offset) { ItemsLV.Items[index].Selected = false; - if (index+offset < ItemsLV.Items.Count) + if (index + offset < ItemsLV.Items.Count) { - ItemsLV.Items[index+offset].Selected = true; + ItemsLV.Items[index + offset].Selected = true; } } } - /// - protected override void UpdateItem(ListViewItem listItem, object item) + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - EventFieldList eventFields = item as EventFieldList; + EventFieldList eventFields = item as EventFieldList; - if (eventFields == null) - { - base.UpdateItem(listItem, item); - return; - } + if (eventFields == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } MonitoredItem monitoredItem = m_subscription.FindItemByClientHandle(eventFields.ClientHandle); @@ -367,22 +368,22 @@ protected override void UpdateItem(ListViewItem listItem, object item) listItem.SubItems[3].Text = null; listItem.SubItems[4].Text = null; listItem.SubItems[5].Text = null; - + listItem.Tag = eventFields; return; - } - + } + // get the event fields. - NodeId eventType = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.EventType) as NodeId; - string sourceName = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.SourceName) as string; - DateTime? time = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Time) as DateTime?; - ushort? severity = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Severity) as ushort?; + NodeId eventType = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.EventType) as NodeId; + string sourceName = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.SourceName) as string; + DateTime? time = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Time) as DateTime?; + ushort? severity = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Severity) as ushort?; LocalizedText message = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Message) as LocalizedText; - + // fill in the columns. listItem.SubItems[0].Text = String.Format("[{0}]", eventFields.ClientHandle); - INode typeNode = m_subscription.Session.NodeCache.Find(eventType); + INode typeNode = await m_subscription.Session.NodeCache.FindAsync(eventType, ct); if (typeNode == null) { @@ -405,7 +406,7 @@ protected override void UpdateItem(ListViewItem listItem, object item) } listItem.SubItems[4].Text = String.Format("{0}", severity); - + if (message != null) { listItem.SubItems[5].Text = String.Format("{0}", message.Text); @@ -414,11 +415,11 @@ protected override void UpdateItem(ListViewItem listItem, object item) { listItem.SubItems[5].Text = String.Empty; } - + listItem.Tag = eventFields; } #endregion - + #region Event Handlers private void ViewMI_Click(object sender, EventArgs e) { @@ -429,13 +430,13 @@ private void ViewMI_Click(object sender, EventArgs e) if (fieldList == null) { return; - } + } new ComplexValueEditDlg().ShowDialog(fieldList, m_subscription.FindItemByClientHandle(fieldList.ClientHandle)); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/FilterOperandEditDlg.cs b/Samples/Controls.Net4/Subscriptions/FilterOperandEditDlg.cs index 578d5f521..8a5231e65 100644 --- a/Samples/Controls.Net4/Subscriptions/FilterOperandEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/FilterOperandEditDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,7 @@ using System.Data; using System.Drawing; using System.Text; +using System.Linq; using System.Windows.Forms; using System.Reflection; @@ -59,31 +60,31 @@ public FilterOperandEditDlg() DataTypeCB.Items.Add(datatype); } - AttributeIdCB.Items.AddRange(Attributes.GetBrowseNames()); + AttributeIdCB.Items.AddRange(Attributes.BrowseNames.ToArray()); } #endregion #region Private Fields private Session m_session; #endregion - + #region Public Interface /// /// Displays the dialog. /// public FilterOperand ShowDialog( - Session session, - IList elements, - int index, - FilterOperand operand) + Session session, + IList elements, + int index, + FilterOperand operand) { - if (session == null) throw new ArgumentNullException("session"); - if (elements == null) throw new ArgumentNullException("elements"); + if (session == null) throw new ArgumentNullException(nameof(session)); + if (elements == null) throw new ArgumentNullException(nameof(elements)); m_session = session; - + TypeDefinitionIdCTRL.Browser = new Browser(session); - TypeDefinitionIdCTRL.RootId = ObjectTypes.BaseEventType; + TypeDefinitionIdCTRL.RootId = ObjectTypes.BaseEventType; OperandTypeCB.SelectedItem = typeof(LiteralOperand).Name; @@ -91,32 +92,32 @@ public FilterOperand ShowDialog( { OperandTypeCB.SelectedItem = operand.GetType().Name; } - + ElementsCB.Items.Clear(); - for (int ii = index+1; ii < elements.Count; ii++) + for (int ii = index + 1; ii < elements.Count; ii++) { - ElementsCB.Items.Add(elements[ii].ToString(m_session.NodeCache)); + ElementsCB.Items.Add(elements[ii].ToString(m_session.NodeCache.AsNodeTable())); } - + ElementOperand elementOperand = operand as ElementOperand; if (elementOperand != null) { - ElementsCB.SelectedIndex = (int)elementOperand.Index - index -1; + ElementsCB.SelectedIndex = (int)elementOperand.Index - index - 1; } - + AttributeOperand attributeOperand = operand as AttributeOperand; if (attributeOperand != null) { TypeDefinitionIdCTRL.Identifier = attributeOperand.NodeId; - BrowsePathTB.Text = attributeOperand.BrowsePath.Format(session.NodeCache.TypeTree); - AttributeIdCB.SelectedItem = Attributes.GetBrowseName(attributeOperand.AttributeId); - IndexRangeTB.Text = attributeOperand.IndexRange; - AliasTB.Text = attributeOperand.Alias; + BrowsePathTB.Text = attributeOperand.BrowsePath.Format(session.TypeTree); + AttributeIdCB.SelectedItem = Attributes.GetBrowseName(attributeOperand.AttributeId); + IndexRangeTB.Text = attributeOperand.IndexRange; + AliasTB.Text = attributeOperand.Alias; } - + LiteralOperand literalOperand = operand as LiteralOperand; if (literalOperand != null) @@ -147,7 +148,7 @@ public FilterOperand ShowDialog( ValueTB.Text = buffer.ToString(); } - + if (ShowDialog() != DialogResult.OK) { return null; @@ -156,7 +157,7 @@ public FilterOperand ShowDialog( return operand; } #endregion - + #region Event Handlers private void OperandTypeCB_SelectedIndexChanged(object sender, EventArgs e) { @@ -166,32 +167,32 @@ private void OperandTypeCB_SelectedIndexChanged(object sender, EventArgs e) { case "LiteralOperand": { - LiteralPN.Visible = true; + LiteralPN.Visible = true; AttributePN.Visible = false; - ElementPN.Visible = false; + ElementPN.Visible = false; break; } case "AttributeOperand": { - LiteralPN.Visible = false; + LiteralPN.Visible = false; AttributePN.Visible = true; - ElementPN.Visible = false; + ElementPN.Visible = false; break; } case "ElementOperand": { - LiteralPN.Visible = false; + LiteralPN.Visible = false; AttributePN.Visible = false; - ElementPN.Visible = true; + ElementPN.Visible = true; break; } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.Designer.cs b/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.Designer.cs index c09719919..731d12ff4 100644 --- a/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.Designer.cs @@ -84,7 +84,7 @@ private void InitializeComponent() this.NewMI.Name = "NewMI"; this.NewMI.Size = new System.Drawing.Size(152, 22); this.NewMI.Text = "New..."; - this.NewMI.Click += new System.EventHandler(this.NewMI_Click); + this.NewMI.Click += new System.EventHandler(this.NewMI_ClickAsync); // // DeleteMI // diff --git a/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.cs b/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.cs index ffafc0da7..103c58f06 100644 --- a/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -45,8 +46,8 @@ public partial class FilterOperandListCtrl : Opc.Ua.Client.Controls.BaseListCtrl { public FilterOperandListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -58,11 +59,11 @@ public FilterOperandListCtrl() /// The columns to display in the control. ///
private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Index", HorizontalAlignment.Left, null }, - new object[] { "Operand", HorizontalAlignment.Left, null }, - }; - #endregion + { + new object[] { "Index", HorizontalAlignment.Left, null }, + new object[] { "Operand", HorizontalAlignment.Left, null }, + }; + #endregion #region Public Interface /// @@ -79,17 +80,17 @@ public void Clear() /// public void Initialize(Session session, IList elements, int index) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); - - m_session = session; + + m_session = session; m_elements = elements; - m_index = index; + m_index = index; if (elements == null || index < 0 || index >= elements.Count) { - return; + return; } foreach (FilterOperand operand in elements[index].GetOperands()) @@ -106,7 +107,7 @@ public void Initialize(Session session, IList elements, in public List GetOperands() { List operands = new List(); - + for (int ii = 0; ii < ItemsLV.Items.Count; ii++) { FilterOperand operand = ItemsLV.Items[ii].Tag as FilterOperand; @@ -124,32 +125,32 @@ public List GetOperands() #region Overridden Methods /// protected override void EnableMenuItems(ListViewItem clickedItem) - { - NewMI.Enabled = true; - EditMI.Enabled = ItemsLV.SelectedItems.Count == 1; + { + NewMI.Enabled = true; + EditMI.Enabled = ItemsLV.SelectedItems.Count == 1; DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item, int index) + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, int index, CancellationToken ct = default) { - FilterOperand operand = item as FilterOperand; - - if (operand == null) - { - base.UpdateItem(listItem, item); - return; - } - + FilterOperand operand = item as FilterOperand; + + if (operand == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } + listItem.SubItems[0].Text = String.Format("[{0}]", index); - listItem.SubItems[1].Text = operand.ToString(m_session.NodeCache); - + listItem.SubItems[1].Text = operand.ToString(m_session.NodeCache.AsNodeTable()); + listItem.Tag = operand; } #endregion - + #region Event Handlers - private void NewMI_Click(object sender, EventArgs e) + private async void NewMI_ClickAsync(object sender, EventArgs e) { try { @@ -158,14 +159,14 @@ private void NewMI_Click(object sender, EventArgs e) if (operand == null) { return; - } + } // insert after the current selection. int index = ItemsLV.SelectedIndices.Count; if (ItemsLV.SelectedIndices.Count > 0) { - index = ItemsLV.SelectedIndices[0]+1; + index = ItemsLV.SelectedIndices[0] + 1; } AddItem(operand, "SimpleItem", index); @@ -173,9 +174,9 @@ private void NewMI_Click(object sender, EventArgs e) // must update index for all items. for (int ii = 0; ii < ItemsLV.Items.Count; ii++) { - UpdateItem(ItemsLV.Items[ii], ItemsLV.Items[ii].Tag, ii); + await UpdateItemAsync(ItemsLV.Items[ii], ItemsLV.Items[ii].Tag, ii); } - + AdjustColumns(); m_elements[m_index].FilterOperands.Clear(); @@ -183,7 +184,7 @@ private void NewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -194,7 +195,7 @@ private void EditMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -205,7 +206,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/FilterOperatorEditDlg.cs b/Samples/Controls.Net4/Subscriptions/FilterOperatorEditDlg.cs index 22ed971f0..a1f25f8ff 100644 --- a/Samples/Controls.Net4/Subscriptions/FilterOperatorEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/FilterOperatorEditDlg.cs @@ -53,7 +53,7 @@ public FilterOperatorEditDlg() } } #endregion - + #region Public Interface /// /// Displays the dialog. @@ -66,9 +66,9 @@ public bool ShowDialog(ref FilterOperator value) { return false; } - + value = (FilterOperator)OperatorCB.SelectedItem; - + return true; } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/HistoryReadDetails.cs b/Samples/Controls.Net4/Subscriptions/HistoryReadDetails.cs index 17099e632..f6bf55118 100644 --- a/Samples/Controls.Net4/Subscriptions/HistoryReadDetails.cs +++ b/Samples/Controls.Net4/Subscriptions/HistoryReadDetails.cs @@ -44,14 +44,14 @@ public partial class HistoryReadDetails : UserControl public HistoryReadDetails() { InitializeComponent(); - + QueryTypeCB.Items.Clear(); QueryTypeCB.Items.Add("Read Raw or Modified"); } private Session m_session; private ReadRawModifiedDetails m_details; - + #region Private Methods /// /// Initializes the control @@ -76,18 +76,18 @@ public void Initialize( IsModifiedCHK.Checked = details.IsReadModified; } #endregion - + #region Private Methods private DateTime ToControlDateTime(DateTime value) { - if (value < new DateTime(1900,1,1)) + if (value < new DateTime(1900, 1, 1)) { - return new DateTime(1900,1,1); + return new DateTime(1900, 1, 1); } - if (value > new DateTime(2100,1,1)) + if (value > new DateTime(2100, 1, 1)) { - return new DateTime(2100,1,1); + return new DateTime(2100, 1, 1); } return value; @@ -95,12 +95,12 @@ private DateTime ToControlDateTime(DateTime value) private DateTime FromControlDateTime(DateTime value) { - if (value <= new DateTime(1900,1,1)) + if (value <= new DateTime(1900, 1, 1)) { return DateTime.MinValue; } - if (value >= new DateTime(2100,1,1)) + if (value >= new DateTime(2100, 1, 1)) { return DateTime.MaxValue; } diff --git a/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.Designer.cs b/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.Designer.cs index 2cd45f95e..3f1fe828e 100644 --- a/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.Designer.cs @@ -99,7 +99,7 @@ private void InitializeComponent() this.BackBTN.TabIndex = 3; this.BackBTN.Text = "< Back"; this.BackBTN.UseVisualStyleBackColor = true; - this.BackBTN.Click += new System.EventHandler(this.MoveBTN_Click); + this.BackBTN.Click += new System.EventHandler(this.MoveBTN_ClickAsync); // // CancelBTN // @@ -122,7 +122,7 @@ private void InitializeComponent() this.NextBTN.TabIndex = 2; this.NextBTN.Text = "Next >"; this.NextBTN.UseVisualStyleBackColor = true; - this.NextBTN.Click += new System.EventHandler(this.MoveBTN_Click); + this.NextBTN.Click += new System.EventHandler(this.MoveBTN_ClickAsync); // // ReadBTN // @@ -133,7 +133,7 @@ private void InitializeComponent() this.ReadBTN.TabIndex = 4; this.ReadBTN.Text = "Read"; this.ReadBTN.UseVisualStyleBackColor = true; - this.ReadBTN.Click += new System.EventHandler(this.ReadMI_Click); + this.ReadBTN.Click += new System.EventHandler(this.ReadMI_ClickAsync); // // SplitterPN // @@ -173,7 +173,7 @@ private void InitializeComponent() this.BrowseCTRL.SessionTreeCtrl = null; this.BrowseCTRL.Size = new System.Drawing.Size(291, 392); this.BrowseCTRL.TabIndex = 1; - this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelected); + this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelectedAsync); // // ReadResultsCTRL // diff --git a/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.cs b/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.cs index 8a52167b2..92c236e0a 100644 --- a/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading; +using System.Threading.Tasks; namespace Opc.Ua.Sample.Controls { @@ -54,27 +56,27 @@ public HistoryReadDlg() #region Private Fields private Session m_session; #endregion - + #region Public Interface /// /// Displays the dialog. /// public void Show(Session session, ReadValueIdCollection valueIds) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + m_session = session; - BrowseCTRL.SetView(m_session, BrowseViewType.Objects, null); + BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null); ReadValuesCTRL.Initialize(session, valueIds); - MoveBTN_Click(BackBTN, null); + MoveBTN_ClickAsync(BackBTN, null); Show(); BringToFront(); } - private void Read() + private async Task ReadAsync(CancellationToken ct = default) { ReadValueIdCollection nodesToRead = ReadValuesCTRL.GetValueIds(); @@ -83,26 +85,25 @@ private void Read() return; } - DataValueCollection values = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Both, nodesToRead, - out values, - out diagnosticInfos); + ct); + + DataValueCollection values = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(values, nodesToRead); - ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); - - ReadResultsCTRL.ShowValue(values, true); + ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); + + await ReadResultsCTRL.ShowValueAsync(values, true, ct); } #endregion - + #region Event Handlers - private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) + private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEventArgs e) { try { @@ -110,57 +111,57 @@ private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) { if (reference.ReferenceTypeId == ReferenceTypeIds.HasProperty || reference.IsForward) { - ReadValuesCTRL.AddValueId(reference); + await ReadValuesCTRL.AddValueIdAsync(reference); } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void MoveBTN_Click(object sender, EventArgs e) + private async void MoveBTN_ClickAsync(object sender, EventArgs e) { try { if (sender == NextBTN) { - Read(); + await ReadAsync(); - BackBTN.Visible = true; - NextBTN.Visible = false; - ReadBTN.Visible = true; - ReadValuesCTRL.Visible = true; + BackBTN.Visible = true; + NextBTN.Visible = false; + ReadBTN.Visible = true; + ReadValuesCTRL.Visible = true; ReadResultsCTRL.Visible = true; - BrowseCTRL.Visible = false; + BrowseCTRL.Visible = false; } else if (sender == BackBTN) { - BackBTN.Visible = false; - NextBTN.Visible = true; - ReadBTN.Visible = false; - ReadResultsCTRL.Visible = false; - BrowseCTRL.Visible = true; - ReadValuesCTRL.Visible = true; + BackBTN.Visible = false; + NextBTN.Visible = true; + ReadBTN.Visible = false; + ReadResultsCTRL.Visible = false; + BrowseCTRL.Visible = true; + ReadValuesCTRL.Visible = true; } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void ReadMI_Click(object sender, EventArgs e) + private async void ReadMI_ClickAsync(object sender, EventArgs e) { try { - Read(); + await ReadAsync(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -172,7 +173,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.Designer.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.Designer.cs index 381bec385..554d6b81a 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.Designer.cs @@ -95,21 +95,21 @@ private void InitializeComponent() this.NewMI.Name = "NewMI"; this.NewMI.Size = new System.Drawing.Size(196, 22); this.NewMI.Text = "New..."; - this.NewMI.Click += new System.EventHandler(this.NewMI_Click); + this.NewMI.Click += new System.EventHandler(this.NewMI_ClickAsync); // // EditMI // this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(196, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // DeleteMI // this.DeleteMI.Name = "DeleteMI"; this.DeleteMI.Size = new System.Drawing.Size(196, 22); this.DeleteMI.Text = "Delete"; - this.DeleteMI.Click += new System.EventHandler(this.DeleteMI_Click); + this.DeleteMI.Click += new System.EventHandler(this.DeleteMI_ClickAsync); // // Separator1 // @@ -128,14 +128,14 @@ private void InitializeComponent() this.SetFilterMI.Name = "SetFilterMI"; this.SetFilterMI.Size = new System.Drawing.Size(196, 22); this.SetFilterMI.Text = "Set Filter..."; - this.SetFilterMI.Click += new System.EventHandler(this.SetFilterMI_Click); + this.SetFilterMI.Click += new System.EventHandler(this.SetFilterMI_ClickAsync); // // SetMonitoringModeMI // this.SetMonitoringModeMI.Name = "SetMonitoringModeMI"; this.SetMonitoringModeMI.Size = new System.Drawing.Size(196, 22); this.SetMonitoringModeMI.Text = "Set Monitoring Mode..."; - this.SetMonitoringModeMI.Click += new System.EventHandler(this.SetMonitoringModeMI_Click); + this.SetMonitoringModeMI.Click += new System.EventHandler(this.SetMonitoringModeMI_ClickAsync); // // Separator2 // diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.cs index 215ca9eda..37e6ba888 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -153,7 +154,7 @@ public void SubscriptionChanged(SubscriptionStateChangedEventArgs e) /// public MonitoredItem CreateItem(Subscription subscription) { - if (subscription == null) throw new ArgumentNullException("subscription"); + if (subscription == null) throw new ArgumentNullException(nameof(subscription)); MonitoredItem monitoredItem = new MonitoredItem(subscription.DefaultItem); monitoredItem.QueueSize = 1; @@ -192,7 +193,7 @@ public void UpdateItems() /// /// Returns the parent for the node. /// - private Node FindParent(Node node) + private async Task FindParentAsync(Node node, CancellationToken ct = default) { IList parents = node.ReferenceTable.Find(ReferenceTypeIds.Aggregates, true, true, m_subscription.Session.TypeTree); @@ -202,7 +203,7 @@ private Node FindParent(Node node) foreach (IReference parentReference in parents) { - Node parent = m_subscription.Session.NodeCache.Find(parentReference.TargetId) as Node; + Node parent = await m_subscription.Session.NodeCache.FindAsync(parentReference.TargetId, ct) as Node; if (followToType) { @@ -224,14 +225,14 @@ private Node FindParent(Node node) /// /// Creates an item from a reference. /// - public void AddItem(ReferenceDescription reference) + public async Task AddItemAsync(ReferenceDescription reference, CancellationToken ct = default) { if (reference == null) { return; } - Node node = m_subscription.Session.NodeCache.Find(reference.NodeId) as Node; + Node node = await m_subscription.Session.NodeCache.FindAsync(reference.NodeId, ct) as Node; if (node == null) { @@ -243,7 +244,7 @@ public void AddItem(ReferenceDescription reference) // if the NodeId is of type string and contains '.' do not use relative paths if (node.NodeId.IdType != IdType.String || (node.NodeId.Identifier.ToString().IndexOf('.') == -1 && node.NodeId.Identifier.ToString().IndexOf('/') == -1)) { - parent = FindParent(node); + parent = await FindParentAsync(node, ct); } MonitoredItem monitoredItem = new MonitoredItem(m_subscription.DefaultItem); @@ -267,7 +268,7 @@ public void AddItem(ReferenceDescription reference) while (parent.NodeClass != NodeClass.ObjectType && parent.NodeClass != NodeClass.VariableType) { - parent = FindParent(parent); + parent = await FindParentAsync(parent, ct); if (parent == null) { @@ -305,7 +306,7 @@ public void AddItem(ReferenceDescription reference) /// /// Apply any changes to the set of items. /// - public void ApplyChanges(bool force) + public async Task ApplyChangesAsync(bool force, CancellationToken ct = default) { if (m_batchUpdates && !force) { @@ -314,11 +315,11 @@ public void ApplyChanges(bool force) if (m_subscription != null) { - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); foreach (ListViewItem listItem in ItemsLV.Items) { - UpdateItem(listItem, listItem.Tag); + await UpdateItemAsync(listItem, listItem.Tag, ct); } AdjustColumns(); @@ -368,14 +369,14 @@ protected override void PickItems() MonitorMI_Click(this, null); } - /// - protected override void UpdateItem(ListViewItem listItem, object item) + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { MonitoredItem monitoredItem = item as MonitoredItem; if (monitoredItem == null) { - base.UpdateItem(listItem, item); + await base.UpdateItemAsync(listItem, item, ct); return; } @@ -439,7 +440,7 @@ protected override void UpdateItem(ListViewItem listItem, object item) /// /// Handles a drop event. /// - protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) + protected override async Task OnDragDropAsync(object sender, DragEventArgs e, CancellationToken ct = default) { try { @@ -450,7 +451,7 @@ protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) return; } - AddItem(reference); + await AddItemAsync(reference, ct); AdjustColumns(); } catch (Exception exception) @@ -461,7 +462,7 @@ protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) #endregion #region Event Handlers - private void NewMI_Click(object sender, EventArgs e) + private async void NewMI_ClickAsync(object sender, EventArgs e) { try { @@ -471,7 +472,7 @@ private void NewMI_Click(object sender, EventArgs e) } CreateItem(m_subscription); - ApplyChanges(false); + await ApplyChangesAsync(false); } catch (Exception exception) { @@ -479,7 +480,7 @@ private void NewMI_Click(object sender, EventArgs e) } } - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -500,7 +501,7 @@ private void EditMI_Click(object sender, EventArgs e) return; } - ApplyChanges(false); + await ApplyChangesAsync(false); } catch (Exception exception) { @@ -508,7 +509,7 @@ private void EditMI_Click(object sender, EventArgs e) } } - private void DeleteMI_Click(object sender, EventArgs e) + private async void DeleteMI_ClickAsync(object sender, EventArgs e) { try { @@ -524,7 +525,7 @@ private void DeleteMI_Click(object sender, EventArgs e) m_subscription.RemoveItems(monitoredItems); } - IList deletedItems = m_subscription.DeleteItems(); + IList deletedItems = await m_subscription.DeleteItemsAsync(); string errorString = string.Empty; @@ -538,7 +539,7 @@ private void DeleteMI_Click(object sender, EventArgs e) foreach (ListViewItem listItem in ItemsLV.Items) { - UpdateItem(listItem, listItem.Tag); + await UpdateItemAsync(listItem, listItem.Tag); } AdjustColumns(); @@ -554,7 +555,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } } - private void SetMonitoringModeMI_Click(object sender, EventArgs e) + private async void SetMonitoringModeMI_ClickAsync(object sender, EventArgs e) { try { @@ -574,7 +575,7 @@ private void SetMonitoringModeMI_Click(object sender, EventArgs e) return; } - List errors = m_subscription.SetMonitoringMode(monitoringMode, monitoredItems); + List errors = await m_subscription.SetMonitoringModeAsync(monitoringMode, monitoredItems); if (errors != null) { @@ -595,7 +596,7 @@ private void SetMonitoringModeMI_Click(object sender, EventArgs e) } } - private void SetFilterMI_Click(object sender, EventArgs e) + private async void SetFilterMI_ClickAsync(object sender, EventArgs e) { try { @@ -627,8 +628,8 @@ private void SetFilterMI_Click(object sender, EventArgs e) monitoredItems[0].Filter = filter; } - m_subscription.ModifyItems(); - ApplyChanges(false); + await m_subscription.ModifyItemsAsync(); + await ApplyChangesAsync(false); } } catch (Exception exception) diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.Designer.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.Designer.cs index 98b25fd83..37087e787 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.Designer.cs @@ -134,21 +134,21 @@ private void InitializeComponent() this.MonitoringModeReportingMI.Name = "MonitoringModeReportingMI"; this.MonitoringModeReportingMI.Size = new System.Drawing.Size(126, 22); this.MonitoringModeReportingMI.Text = "Reporting"; - this.MonitoringModeReportingMI.Click += new System.EventHandler(this.MonitoringModeMI_Click); + this.MonitoringModeReportingMI.Click += new System.EventHandler(this.MonitoringModeMI_ClickAsync); // // MonitoringModeSamplingMI // this.MonitoringModeSamplingMI.Name = "MonitoringModeSamplingMI"; this.MonitoringModeSamplingMI.Size = new System.Drawing.Size(126, 22); this.MonitoringModeSamplingMI.Text = "Sampling"; - this.MonitoringModeSamplingMI.Click += new System.EventHandler(this.MonitoringModeMI_Click); + this.MonitoringModeSamplingMI.Click += new System.EventHandler(this.MonitoringModeMI_ClickAsync); // // MonitoringModeDisabledMI // this.MonitoringModeDisabledMI.Name = "MonitoringModeDisabledMI"; this.MonitoringModeDisabledMI.Size = new System.Drawing.Size(126, 22); this.MonitoringModeDisabledMI.Text = "Disabled"; - this.MonitoringModeDisabledMI.Click += new System.EventHandler(this.MonitoringModeMI_Click); + this.MonitoringModeDisabledMI.Click += new System.EventHandler(this.MonitoringModeMI_ClickAsync); // // WindowMI // diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.cs index 93bfef1e0..ded84287c 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -50,7 +50,7 @@ public MonitoredItemDlg() this.Icon = ClientUtils.GetAppIcon(); m_SubscriptionStateChanged = new SubscriptionStateChangedEventHandler(Subscription_StateChanged); - m_MonitoredItemNotification = new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); + m_MonitoredItemNotification = new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); m_PublishStatusChanged = new PublishStateChangedEventHandler(Subscription_PublishStatusChanged); } #endregion @@ -69,7 +69,7 @@ public MonitoredItemDlg() /// public void Show(MonitoredItem monitoredItem) { - if (monitoredItem == null) throw new ArgumentNullException("monitoredItem"); + if (monitoredItem == null) throw new ArgumentNullException(nameof(monitoredItem)); Show(); BringToFront(); @@ -99,8 +99,8 @@ public void Show(MonitoredItem monitoredItem) MonitoredItemsCTRL.Initialize(m_monitoredItem); EventsCTRL.Initialize(m_subscription, m_monitoredItem); - DataChangesCTRL.Initialize(m_subscription, m_monitoredItem); - LatestValueCTRL.ShowValue(m_monitoredItem, false); + DataChangesCTRL.InitializeAsync(m_subscription, m_monitoredItem); + LatestValueCTRL.ShowValueAsync(m_monitoredItem, false); } #endregion @@ -148,7 +148,7 @@ private void UpdateStatus() /// /// Processes a Publish repsonse from the server. /// - void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) + private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (InvokeRequired) { @@ -170,11 +170,11 @@ void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotifi // notify controls of the change. EventsCTRL.NotificationReceived(e); - DataChangesCTRL.NotificationReceived(e); + await DataChangesCTRL.NotificationReceivedAsync(e); if (e != null) { MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; - LatestValueCTRL.ShowValue(notification, true); + await LatestValueCTRL.ShowValueAsync(notification, true); } // update item status. UpdateStatus(); @@ -188,7 +188,7 @@ void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotifi /// /// Handles a change to the state of the subscription. /// - void Subscription_StateChanged(Subscription subscription, SubscriptionStateChangedEventArgs e) + private void Subscription_StateChanged(Subscription subscription, SubscriptionStateChangedEventArgs e) { if (InvokeRequired) { @@ -225,7 +225,7 @@ void Subscription_StateChanged(Subscription subscription, SubscriptionStateChang /// /// Handles a change to the publish status for the subscription. /// - void Subscription_PublishStatusChanged(object subscription, PublishStateChangedEventArgs e) + private void Subscription_PublishStatusChanged(object subscription, PublishStateChangedEventArgs e) { if (InvokeRequired) { @@ -296,7 +296,7 @@ private void WindowMI_Click(object sender, EventArgs e) } } - private void MonitoringModeMI_Click(object sender, EventArgs e) + private async void MonitoringModeMI_ClickAsync(object sender, EventArgs e) { try { @@ -317,7 +317,7 @@ private void MonitoringModeMI_Click(object sender, EventArgs e) monitoringMode = MonitoringMode.Disabled; } - m_monitoredItem.Subscription.SetMonitoringMode(monitoringMode, new MonitoredItem[] { m_monitoredItem }); + await m_monitoredItem.Subscription.SetMonitoringModeAsync(monitoringMode, new MonitoredItem[] { m_monitoredItem }); } catch (Exception exception) { diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.Designer.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.Designer.cs index af29e9463..0e8801922 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.Designer.cs @@ -203,7 +203,7 @@ private void InitializeComponent() this.NodeIdCTRL.Name = "NodeIdCTRL"; this.NodeIdCTRL.Size = new System.Drawing.Size(259, 20); this.NodeIdCTRL.TabIndex = 22; - this.NodeIdCTRL.IdentifierChanged += new System.EventHandler(this.NodeIdCTRL_IdentifierChanged); + this.NodeIdCTRL.IdentifierChanged += new System.EventHandler(this.NodeIdCTRL_IdentifierChangedAsync); // // MonitoringModeCB // diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.cs index 4bb3e2d87..f860efd8a 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,7 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; @@ -48,8 +49,8 @@ public MonitoredItemEditDlg() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); - AttributeIdCB.Items.AddRange(Attributes.GetBrowseNames()); - + AttributeIdCB.Items.AddRange(Attributes.BrowseNames.ToArray()); + foreach (MonitoringMode value in Enum.GetValues(typeof(MonitoringMode))) { MonitoringModeCB.Items.Add(value); @@ -76,7 +77,7 @@ public bool ShowDialog(Session session, MonitoredItem monitoredItem) ///
public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool editMonitoredItem) { - if (monitoredItem == null) throw new ArgumentNullException("monitoredItem"); + if (monitoredItem == null) throw new ArgumentNullException(nameof(monitoredItem)); m_session = session; @@ -84,7 +85,7 @@ public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool editMo if (editMonitoredItem) { - // Disable the not changeable values + // Disable the not changeable values NodeIdCTRL.Enabled = false; RelativePathTB.Enabled = false; NodeClassCB.Enabled = false; @@ -152,16 +153,16 @@ public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool editMo } private void OkBTN_Click(object sender, EventArgs e) - { + { try { NodeId nodeId = NodeIdCTRL.Identifier; } catch (Exception) { - MessageBox.Show("Please enter a valid node id.", this.Text); + MessageBox.Show("Please enter a valid node id.", this.Text); } - + try { if (!String.IsNullOrEmpty(RelativePathTB.Text)) @@ -171,7 +172,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception) { - MessageBox.Show("Please enter a valid relative path.", this.Text); + MessageBox.Show("Please enter a valid relative path.", this.Text); } try @@ -183,17 +184,17 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception) { - MessageBox.Show("Please enter a valid index range.", this.Text); + MessageBox.Show("Please enter a valid index range.", this.Text); } DialogResult = DialogResult.OK; } - private void NodeIdCTRL_IdentifierChanged(object sender, EventArgs e) + private async void NodeIdCTRL_IdentifierChangedAsync(object sender, EventArgs e) { if (NodeIdCTRL.Reference != null) { - DisplayNameTB.Text = m_session.NodeCache.GetDisplayText(NodeIdCTRL.Reference); + DisplayNameTB.Text = await m_session.NodeCache.GetDisplayTextAsync(NodeIdCTRL.Reference); NodeClassCB.SelectedItem = (NodeClass)NodeIdCTRL.Reference.NodeClass; } } diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemStatusCtrl.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemStatusCtrl.cs index 04561224a..396720fb9 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemStatusCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemStatusCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -52,27 +53,27 @@ public MonitoredItemStatusCtrl() InitializeComponent(); SetColumns(m_ColumnNames); } - #endregion + #endregion #region Private Fields private Subscription m_subscription; private MonitoredItem m_monitoredItem; - + /// - /// The columns to display in the control. - /// - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "ID", HorizontalAlignment.Center, null }, - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "Class", HorizontalAlignment.Left, "Variable" }, - new object[] { "Sampling Rate", HorizontalAlignment.Center, null }, - new object[] { "Queue Size", HorizontalAlignment.Center, "0" }, - new object[] { "Value", HorizontalAlignment.Left, "", 200 }, - new object[] { "Status", HorizontalAlignment.Left, "", }, - new object[] { "Timestamp", HorizontalAlignment.Center, "" }, - }; - #endregion + /// The columns to display in the control. + ///
+ private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "ID", HorizontalAlignment.Center, null }, + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "Class", HorizontalAlignment.Left, "Variable" }, + new object[] { "Sampling Rate", HorizontalAlignment.Center, null }, + new object[] { "Queue Size", HorizontalAlignment.Center, "0" }, + new object[] { "Value", HorizontalAlignment.Left, "", 200 }, + new object[] { "Status", HorizontalAlignment.Left, "", }, + new object[] { "Timestamp", HorizontalAlignment.Center, "" }, + }; + #endregion #region Public Interface /// @@ -96,13 +97,13 @@ public void Initialize(MonitoredItem monitoredItem) } m_monitoredItem = monitoredItem; - m_subscription = null; + m_subscription = null; Clear(); - + if (m_monitoredItem != null) { - m_subscription = monitoredItem.Subscription; + m_subscription = monitoredItem.Subscription; UpdateItems(); } } @@ -119,16 +120,16 @@ public void Initialize(Subscription subscription) } m_monitoredItem = null; - m_subscription = subscription; + m_subscription = subscription; Clear(); - + if (m_subscription != null) { UpdateItems(); } } - + /// /// Called when the subscription changes. /// @@ -159,49 +160,49 @@ public void UpdateItems() AdjustColumns(); } } - + /// /// Apply any changes to the set of items. /// - public void ApplyChanges() + public async Task ApplyChangesAsync(CancellationToken ct = default) { if (m_subscription != null) { - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); foreach (ListViewItem listItem in ItemsLV.Items) { - UpdateItem(listItem, listItem.Tag); + await UpdateItemAsync(listItem, listItem.Tag, ct); } AdjustColumns(); } } #endregion - + #region Overridden Methods /// - protected override void EnableMenuItems(ListViewItem clickedItem) - { + protected override void EnableMenuItems(ListViewItem clickedItem) + { // no menu defined at this time. - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item) + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - MonitoredItem monitoredItem = item as MonitoredItem; + MonitoredItem monitoredItem = item as MonitoredItem; - if (monitoredItem == null) - { - base.UpdateItem(listItem, item); - return; - } + if (monitoredItem == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } - listItem.SubItems[0].Text = String.Format("{0}", monitoredItem.Status.Id); - listItem.SubItems[1].Text = String.Format("{0}", monitoredItem.DisplayName); - listItem.SubItems[2].Text = String.Format("{0}", monitoredItem.NodeClass); + listItem.SubItems[0].Text = String.Format("{0}", monitoredItem.Status.Id); + listItem.SubItems[1].Text = String.Format("{0}", monitoredItem.DisplayName); + listItem.SubItems[2].Text = String.Format("{0}", monitoredItem.NodeClass); listItem.SubItems[3].Text = String.Format("{0}", monitoredItem.Status.SamplingInterval); - listItem.SubItems[4].Text = String.Format("{0}", monitoredItem.Status.QueueSize); + listItem.SubItems[4].Text = String.Format("{0}", monitoredItem.Status.QueueSize); listItem.SubItems[5].Text = String.Empty; listItem.SubItems[6].Text = String.Format("{0}", monitoredItem.Status.Error); listItem.SubItems[7].Text = String.Empty; @@ -226,13 +227,13 @@ protected override void UpdateItem(ListViewItem listItem, object item) if (eventFields != null) { - listItem.SubItems[5].Text = String.Format("{0}", monitoredItem.GetEventType(eventFields)); - listItem.SubItems[7].Text = String.Format("{0:HH:mm:ss.fff}", monitoredItem.GetEventTime(eventFields).ToLocalTime()); + listItem.SubItems[5].Text = String.Format("{0}", await monitoredItem.GetEventTypeAsync(eventFields, ct)); + listItem.SubItems[7].Text = String.Format("{0:HH:mm:ss.fff}", monitoredItem.GetEventTime(eventFields).ToLocalTime()); } } - - listItem.Tag = item; + + listItem.Tag = item; } - #endregion + #endregion } } diff --git a/Samples/Controls.Net4/Subscriptions/NotificationMessageListCtrl.cs b/Samples/Controls.Net4/Subscriptions/NotificationMessageListCtrl.cs index 190bcb869..36e30e99f 100644 --- a/Samples/Controls.Net4/Subscriptions/NotificationMessageListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/NotificationMessageListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -51,33 +52,33 @@ public NotificationMessageListCtrl() { MaxMessageCount = 10; - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); ItemsLV.Sorting = SortOrder.Descending; m_SessionNotification = new NotificationEventHandler(Session_Notification); } - #endregion + #endregion #region Private Fields private Session m_session; private Subscription m_subscription; private NotificationEventHandler m_SessionNotification; private int m_maxMessageCount; - + /// - /// The columns to display in the control. - /// - private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Subscription", HorizontalAlignment.Left, null }, - new object[] { "Message ID", HorizontalAlignment.Center, null }, - new object[] { "Publish Time", HorizontalAlignment.Center, null }, - new object[] { "Notifications", HorizontalAlignment.Center, null }, - new object[] { "Data Changes", HorizontalAlignment.Center, null }, - new object[] { "EventTypes", HorizontalAlignment.Center, null } - }; - #endregion + /// The columns to display in the control. + /// + private readonly object[][] m_ColumnNames = new object[][] + { + new object[] { "Subscription", HorizontalAlignment.Left, null }, + new object[] { "Message ID", HorizontalAlignment.Center, null }, + new object[] { "Publish Time", HorizontalAlignment.Center, null }, + new object[] { "Notifications", HorizontalAlignment.Center, null }, + new object[] { "Data Changes", HorizontalAlignment.Center, null }, + new object[] { "EventTypes", HorizontalAlignment.Center, null } + }; + #endregion #region Public Interface /// @@ -85,7 +86,7 @@ public NotificationMessageListCtrl() /// public int MaxMessageCount { - get { return m_maxMessageCount; } + get { return m_maxMessageCount; } set { m_maxMessageCount = value; } } @@ -132,8 +133,8 @@ public void Initialize(Session session, Subscription subscription) if (m_session == null) { return; - } - + } + List tags = new List(); // display only items for current subscription. @@ -156,26 +157,26 @@ public void Initialize(Session session, Subscription subscription) } } } - + // update control. Update(tags); } #endregion - + #region ItemData Class /// /// Stores the data associated with a list view item. /// public class ItemData { - public Subscription Subscription; + public Subscription Subscription; public NotificationMessage NotificationMessage; public ItemData( - Subscription subscription, + Subscription subscription, NotificationMessage notificationMessage) { - Subscription = subscription; + Subscription = subscription; NotificationMessage = notificationMessage; } } @@ -184,11 +185,11 @@ public ItemData( #region Overridden Methods /// protected override void EnableMenuItems(ListViewItem clickedItem) - { + { if (m_session != null) { - OptionsMI.Enabled = true; - ClearMI.Enabled = true; + OptionsMI.Enabled = true; + ClearMI.Enabled = true; RepublishMI.Enabled = m_subscription != null; if (clickedItem != null) @@ -197,28 +198,28 @@ protected override void EnableMenuItems(ListViewItem clickedItem) if (itemData != null) { - ViewMI.Enabled = true; + ViewMI.Enabled = true; DeleteMI.Enabled = true; } } } - } + } - /// - protected override void UpdateItem(ListViewItem listItem, object item) + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { ItemData itemData = item as ItemData; - if (itemData == null) - { - base.UpdateItem(listItem, item); - return; - } + if (itemData == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } + + listItem.SubItems[0].Text = String.Format("{0}", itemData.Subscription.DisplayName); + listItem.SubItems[1].Text = String.Format("{0}", itemData.NotificationMessage.SequenceNumber); + listItem.SubItems[2].Text = String.Format("{0:HH:mm:ss.fff}", itemData.NotificationMessage.PublishTime.ToLocalTime()); - listItem.SubItems[0].Text = String.Format("{0}", itemData.Subscription.DisplayName); - listItem.SubItems[1].Text = String.Format("{0}", itemData.NotificationMessage.SequenceNumber); - listItem.SubItems[2].Text = String.Format("{0:HH:mm:ss.fff}", itemData.NotificationMessage.PublishTime.ToLocalTime()); - int events = 0; int datachanges = 0; int notifications = 0; @@ -247,23 +248,23 @@ protected override void UpdateItem(ListViewItem listItem, object item) } } - listItem.SubItems[3].Text = String.Format("{0}", notifications); - listItem.SubItems[4].Text = String.Format("{0}", datachanges); - listItem.SubItems[5].Text = String.Format("{0}", events); + listItem.SubItems[3].Text = String.Format("{0}", notifications); + listItem.SubItems[4].Text = String.Format("{0}", datachanges); + listItem.SubItems[5].Text = String.Format("{0}", events); - listItem.Tag = item; + listItem.Tag = item; } - #endregion + #endregion private void Update(List tags) { if (tags.Count > MaxMessageCount) { - tags.RemoveRange(MaxMessageCount, tags.Count-MaxMessageCount); + tags.RemoveRange(MaxMessageCount, tags.Count - MaxMessageCount); } - + BeginUpdate(); - + foreach (ItemData tag in tags) { AddItem(tag); @@ -283,7 +284,7 @@ private void Session_Notification(ISession sender, NotificationEventArgs e) { return; } - + try { if (m_subscription != null) @@ -306,7 +307,7 @@ private void Session_Notification(ISession sender, NotificationEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -317,7 +318,7 @@ private void ViewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -332,7 +333,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -344,7 +345,7 @@ private void ClearMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -367,7 +368,7 @@ private void RepublishMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Subscriptions/ReadDlg.Designer.cs b/Samples/Controls.Net4/Subscriptions/ReadDlg.Designer.cs index 7b3e0c2a1..03757b714 100644 --- a/Samples/Controls.Net4/Subscriptions/ReadDlg.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/ReadDlg.Designer.cs @@ -98,7 +98,7 @@ private void InitializeComponent() this.BackBTN.TabIndex = 3; this.BackBTN.Text = "< Back"; this.BackBTN.UseVisualStyleBackColor = true; - this.BackBTN.Click += new System.EventHandler(this.MoveBTN_Click); + this.BackBTN.Click += new System.EventHandler(this.MoveBTN_ClickAsync); // // CancelBTN // @@ -121,7 +121,7 @@ private void InitializeComponent() this.NextBTN.TabIndex = 2; this.NextBTN.Text = "Next >"; this.NextBTN.UseVisualStyleBackColor = true; - this.NextBTN.Click += new System.EventHandler(this.MoveBTN_Click); + this.NextBTN.Click += new System.EventHandler(this.MoveBTN_ClickAsync); // // ReadBTN // @@ -132,7 +132,7 @@ private void InitializeComponent() this.ReadBTN.TabIndex = 4; this.ReadBTN.Text = "Read"; this.ReadBTN.UseVisualStyleBackColor = true; - this.ReadBTN.Click += new System.EventHandler(this.ReadMI_Click); + this.ReadBTN.Click += new System.EventHandler(this.ReadMI_ClickAsync); // // SplitterPN // @@ -173,7 +173,7 @@ private void InitializeComponent() this.BrowseCTRL.SessionTreeCtrl = null; this.BrowseCTRL.Size = new System.Drawing.Size(291, 392); this.BrowseCTRL.TabIndex = 1; - this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelected); + this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelectedAsync); // // ReadResultsCTRL // diff --git a/Samples/Controls.Net4/Subscriptions/ReadDlg.cs b/Samples/Controls.Net4/Subscriptions/ReadDlg.cs index c72f2f6dd..ce2d3b0e6 100644 --- a/Samples/Controls.Net4/Subscriptions/ReadDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/ReadDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -54,27 +56,27 @@ public ReadDlg() #region Private Fields private Session m_session; #endregion - + #region Public Interface /// /// Displays the dialog. /// - public void Show(Session session, ReadValueIdCollection valueIds) + public async Task ShowAsync(Session session, ReadValueIdCollection valueIds, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + m_session = session; - BrowseCTRL.SetView(m_session, BrowseViewType.Objects, null); + await BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, ct); ReadValuesCTRL.Initialize(session, valueIds); - MoveBTN_Click(BackBTN, null); + MoveBTN_ClickAsync(BackBTN, null); Show(); BringToFront(); } - private void Read() + private async Task ReadAsync(CancellationToken ct = default) { ReadValueIdCollection nodesToRead = ReadValuesCTRL.GetValueIds(); @@ -83,26 +85,25 @@ private void Read() return; } - DataValueCollection values = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Both, nodesToRead, - out values, - out diagnosticInfos); + ct); + + DataValueCollection values = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(values, nodesToRead); - ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); - - ReadResultsCTRL.ShowValue(values, true); + ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); + + await ReadResultsCTRL.ShowValueAsync(values, true, ct); } #endregion - + #region Event Handlers - private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) + private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEventArgs e) { try { @@ -110,61 +111,61 @@ private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) { if (reference.ReferenceTypeId == ReferenceTypeIds.HasProperty || reference.IsForward) { - ReadValuesCTRL.AddValueId(reference); + await ReadValuesCTRL.AddValueIdAsync(reference); } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void MoveBTN_Click(object sender, EventArgs e) + private async void MoveBTN_ClickAsync(object sender, EventArgs e) { try { if (sender == NextBTN) { - Read(); + await ReadAsync(); - ReadValuesCTRL.Parent = SplitterPN.Panel1; + ReadValuesCTRL.Parent = SplitterPN.Panel1; - BackBTN.Visible = true; - NextBTN.Visible = false; - ReadBTN.Visible = true; - ReadValuesCTRL.Visible = true; + BackBTN.Visible = true; + NextBTN.Visible = false; + ReadBTN.Visible = true; + ReadValuesCTRL.Visible = true; ReadResultsCTRL.Visible = true; - BrowseCTRL.Visible = false; + BrowseCTRL.Visible = false; } else if (sender == BackBTN) { - ReadValuesCTRL.Parent = SplitterPN.Panel2; - - BackBTN.Visible = false; - NextBTN.Visible = true; - ReadBTN.Visible = false; - ReadResultsCTRL.Visible = false; - BrowseCTRL.Visible = true; - ReadValuesCTRL.Visible = true; + ReadValuesCTRL.Parent = SplitterPN.Panel2; + + BackBTN.Visible = false; + NextBTN.Visible = true; + ReadBTN.Visible = false; + ReadResultsCTRL.Visible = false; + BrowseCTRL.Visible = true; + ReadValuesCTRL.Visible = true; } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void ReadMI_Click(object sender, EventArgs e) + private async void ReadMI_ClickAsync(object sender, EventArgs e) { try { - Read(); + await ReadAsync(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -176,7 +177,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/ReadValueEditDlg.cs b/Samples/Controls.Net4/Subscriptions/ReadValueEditDlg.cs index 2ba9d23fe..1c3cc96fa 100644 --- a/Samples/Controls.Net4/Subscriptions/ReadValueEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/ReadValueEditDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Data; +using System.Linq; using System.Drawing; using System.Text; using System.Windows.Forms; @@ -38,6 +39,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -47,40 +50,40 @@ public ReadValueEditDlg() { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); - AttributeIdCB.Items.AddRange(Attributes.GetBrowseNames()); + AttributeIdCB.Items.AddRange(Attributes.BrowseNames.ToArray()); } /// /// Prompts the user to specify the browse options. /// - public bool ShowDialog(Session session, ReadValueId valueId) + public async Task ShowDialogAsync(Session session, ReadValueId valueId, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - if (valueId == null) throw new ArgumentNullException("valueId"); + if (session == null) throw new ArgumentNullException(nameof(session)); + if (valueId == null) throw new ArgumentNullException(nameof(valueId)); NodeIdCTRL.Browser = new Browser(session); - INode node = session.NodeCache.Find(valueId.NodeId); + INode node = await session.NodeCache.FindAsync(valueId.NodeId, ct); if (node != null) { DisplayNameTB.Text = node.ToString(); } - NodeIdCTRL.Identifier = valueId.NodeId; + NodeIdCTRL.Identifier = valueId.NodeId; AttributeIdCB.SelectedItem = Attributes.GetBrowseName(valueId.AttributeId); - IndexRangeTB.Text = valueId.IndexRange; - EncodingCB.Text = (valueId.DataEncoding != null)?valueId.DataEncoding.Name:null; - + IndexRangeTB.Text = valueId.IndexRange; + EncodingCB.Text = (valueId.DataEncoding != null) ? valueId.DataEncoding.Name : null; + if (ShowDialog() != DialogResult.OK) { return false; } - valueId.NodeId = NodeIdCTRL.Identifier; + valueId.NodeId = NodeIdCTRL.Identifier; valueId.AttributeId = Attributes.GetIdentifier((string)AttributeIdCB.SelectedItem); - valueId.IndexRange = IndexRangeTB.Text; - + valueId.IndexRange = IndexRangeTB.Text; + if (String.IsNullOrEmpty(EncodingCB.Text)) { valueId.DataEncoding = new QualifiedName(EncodingCB.Text); @@ -90,16 +93,16 @@ public bool ShowDialog(Session session, ReadValueId valueId) } private void OkBTN_Click(object sender, EventArgs e) - { + { try { NodeId nodeId = NodeIdCTRL.Identifier; } catch (Exception) { - MessageBox.Show("Please enter a valid node id.", this.Text); + MessageBox.Show("Please enter a valid node id.", this.Text); } - + try { if (!String.IsNullOrEmpty(IndexRangeTB.Text)) @@ -109,7 +112,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception) { - MessageBox.Show("Please enter a valid index range.", this.Text); + MessageBox.Show("Please enter a valid index range.", this.Text); } DialogResult = DialogResult.OK; diff --git a/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.Designer.cs b/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.Designer.cs index ca2a4328a..81ec7efc2 100644 --- a/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.Designer.cs @@ -87,14 +87,14 @@ private void InitializeComponent() this.NewMI.Name = "NewMI"; this.NewMI.Size = new System.Drawing.Size(174, 22); this.NewMI.Text = "New..."; - this.NewMI.Click += new System.EventHandler(this.NewMI_Click); + this.NewMI.Click += new System.EventHandler(this.NewMI_ClickAsync); // // EditMI // this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(174, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // DeleteMI // diff --git a/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.cs b/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.cs index 422c9f99b..cd1523774 100644 --- a/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -45,8 +46,8 @@ public partial class ReadValueListCtrl : Opc.Ua.Client.Controls.BaseListCtrl { public ReadValueListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -56,14 +57,14 @@ public ReadValueListCtrl() /// The columns to display in the control. ///
private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "NodeId", HorizontalAlignment.Left, null }, - new object[] { "Attribute", HorizontalAlignment.Left, "Value" }, - new object[] { "IndexRange", HorizontalAlignment.Left, "" }, - new object[] { "Encoding", HorizontalAlignment.Left, "" } - }; - #endregion + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "NodeId", HorizontalAlignment.Left, null }, + new object[] { "Attribute", HorizontalAlignment.Left, "Value" }, + new object[] { "IndexRange", HorizontalAlignment.Left, "" }, + new object[] { "Encoding", HorizontalAlignment.Left, "" } + }; + #endregion #region Public Interface /// @@ -80,10 +81,10 @@ public void Clear() /// public void Initialize(Session session, ReadValueIdCollection valueIds) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); - + m_session = session; foreach (ReadValueId valueId in valueIds) @@ -97,9 +98,9 @@ public void Initialize(Session session, ReadValueIdCollection valueIds) /// /// Adds a value to the control. /// - public void AddValueId(ReferenceDescription reference) + public async Task AddValueIdAsync(ReferenceDescription reference, CancellationToken ct = default) { - Node node = m_session.NodeCache.Find(reference.NodeId) as Node; + Node node = await m_session.NodeCache.FindAsync(reference.NodeId, ct) as Node; if (node == null) { @@ -108,15 +109,15 @@ public void AddValueId(ReferenceDescription reference) ReadValueId valueId = new ReadValueId(); - valueId.NodeId = node.NodeId; - valueId.AttributeId = Attributes.Value; - valueId.IndexRange = null; + valueId.NodeId = node.NodeId; + valueId.AttributeId = Attributes.Value; + valueId.IndexRange = null; valueId.DataEncoding = null; // read the display name for non-variables. if ((node.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0) { - valueId.AttributeId = Attributes.DisplayName; + valueId.AttributeId = Attributes.DisplayName; } AddItem(valueId); @@ -142,38 +143,38 @@ public ReadValueIdCollection GetValueIds() return valueIds; } - #endregion - + #endregion + #region Overridden Methods /// protected override void PickItems() { base.PickItems(); - EditMI_Click(this, null); + EditMI_ClickAsync(this, null); } /// protected override void EnableMenuItems(ListViewItem clickedItem) - { - NewMI.Enabled = true; - EditMI.Enabled = ItemsLV.SelectedItems.Count == 1; - DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; + { + NewMI.Enabled = true; + EditMI.Enabled = ItemsLV.SelectedItems.Count == 1; + DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; SetAttributeMI.Enabled = ItemsLV.SelectedItems.Count > 0; - SetEncodingMI.Enabled = ItemsLV.SelectedItems.Count == 1; - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item) + SetEncodingMI.Enabled = ItemsLV.SelectedItems.Count == 1; + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - ReadValueId valueId = item as ReadValueId; + ReadValueId valueId = item as ReadValueId; - if (valueId == null) - { - base.UpdateItem(listItem, item); - return; - } + if (valueId == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } - INode node = m_session.NodeCache.Find(valueId.NodeId); + INode node = await m_session.NodeCache.FindAsync(valueId.NodeId, ct); if (node != null) { @@ -183,21 +184,21 @@ protected override void UpdateItem(ListViewItem listItem, object item) { listItem.SubItems[0].Text = String.Format("{0}", valueId.NodeId); } - + listItem.SubItems[1].Text = String.Format("{0}", valueId.NodeId); listItem.SubItems[2].Text = String.Format("{0}", Attributes.GetBrowseName(valueId.AttributeId)); listItem.SubItems[3].Text = String.Format("{0}", valueId.IndexRange); listItem.SubItems[4].Text = String.Format("{0}", valueId.DataEncoding); - listItem.Tag = item; + listItem.Tag = item; listItem.ImageKey = "Method"; } /// /// Handles a drop event. /// - protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) - { + protected override async Task OnDragDropAsync(object sender, DragEventArgs e, CancellationToken ct = default) + { try { ReferenceDescription reference = e.Data.GetData(typeof(ReferenceDescription)) as ReferenceDescription; @@ -206,24 +207,24 @@ protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) { return; } - - AddValueId(reference); + + await AddValueIdAsync(reference, ct); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion - + #region Event Handlers - private void NewMI_Click(object sender, EventArgs e) + private async void NewMI_ClickAsync(object sender, EventArgs e) { try { ReadValueId valueId = new ReadValueId(); - if (new ReadValueEditDlg().ShowDialog(m_session, valueId)) + if (await new ReadValueEditDlg().ShowDialogAsync(m_session, valueId)) { AddItem(valueId); } @@ -232,11 +233,11 @@ private void NewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -247,14 +248,14 @@ private void EditMI_Click(object sender, EventArgs e) return; } - if (new ReadValueEditDlg().ShowDialog(m_session, valueId)) + if (await new ReadValueEditDlg().ShowDialogAsync(m_session, valueId)) { - UpdateItem(ItemsLV.SelectedItems[0], valueId); + await UpdateItemAsync(ItemsLV.SelectedItems[0], valueId); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -266,7 +267,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.Designer.cs b/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.Designer.cs index 0fe416d48..f9839e538 100644 --- a/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.Designer.cs @@ -101,7 +101,7 @@ private void InitializeComponent() this.OkBTN.TabIndex = 1; this.OkBTN.Text = "OK"; this.OkBTN.UseVisualStyleBackColor = true; - this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click); + this.OkBTN.Click += new System.EventHandler(this.OkBTN_ClickAsync); // // CancelBTN // diff --git a/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.cs b/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.cs index 4cf9a9c25..18a149821 100644 --- a/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -50,19 +50,19 @@ public RepublishNotificationMessageDlg() this.Icon = ClientUtils.GetAppIcon(); } #endregion - + #region Private Fields private Subscription m_subscription; private NotificationMessage m_message; #endregion - + #region Public Interface /// /// Displays the dialog. /// public NotificationMessage ShowDialog(Subscription subscription) { - if (subscription == null) throw new ArgumentNullException("subscription"); + if (subscription == null) throw new ArgumentNullException(nameof(subscription)); m_subscription = subscription; @@ -86,16 +86,16 @@ public NotificationMessage ShowDialog(Subscription subscription) #endregion #region Event Handlers - private void OkBTN_Click(object sender, EventArgs e) - { + private async void OkBTN_ClickAsync(object sender, EventArgs e) + { try { - m_message = m_subscription.Republish((uint)SequenceNumberNC.Value); + m_message = await m_subscription.RepublishAsync((uint)SequenceNumberNC.Value); DialogResult = DialogResult.OK; } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/SelectClauseListCtrl.cs b/Samples/Controls.Net4/Subscriptions/SelectClauseListCtrl.cs index 1f485fb6b..2a4532244 100644 --- a/Samples/Controls.Net4/Subscriptions/SelectClauseListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/SelectClauseListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -45,8 +46,8 @@ public partial class SelectClauseListCtrl : Opc.Ua.Client.Controls.BaseListCtrl { public SelectClauseListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -57,12 +58,12 @@ public SelectClauseListCtrl() /// The columns to display in the control. ///
private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Event Type", HorizontalAlignment.Left, null }, - new object[] { "Field Name", HorizontalAlignment.Left, null }, - new object[] { "Index Range", HorizontalAlignment.Left, null } - }; - #endregion + { + new object[] { "Event Type", HorizontalAlignment.Left, null }, + new object[] { "Field Name", HorizontalAlignment.Left, null }, + new object[] { "Index Range", HorizontalAlignment.Left, null } + }; + #endregion #region Public Interface /// @@ -79,16 +80,16 @@ public void Clear() /// public void Initialize(Session session, SimpleAttributeOperandCollection selectClauses) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); - - m_session = session; + + m_session = session; m_selectClauses = selectClauses; if (selectClauses == null) { - return; + return; } foreach (SimpleAttributeOperand clause in selectClauses) @@ -105,28 +106,28 @@ public void Initialize(Session session, SimpleAttributeOperandCollection selectC /// /// Adds a select clause to the control. /// - public void AddSelectClause(ReferenceDescription reference) + public async Task AddSelectClauseAsync(ReferenceDescription reference, CancellationToken ct = default) { if (reference == null) { return; } - ILocalNode node = m_session.NodeCache.Find(reference.NodeId) as ILocalNode; + ILocalNode node = await m_session.NodeCache.FindAsync(reference.NodeId, ct) as ILocalNode; if (node == null) { return; } - + SimpleAttributeOperand clause = new SimpleAttributeOperand(); - + clause.TypeDefinitionId = m_session.NodeCache.BuildBrowsePath(node, clause.BrowsePath); - clause.AttributeId = Attributes.Value; - + clause.AttributeId = Attributes.Value; + AddItem(clause, "Property", -1); - AdjustColumns(); + AdjustColumns(); } /// @@ -148,28 +149,28 @@ public SimpleAttributeOperandCollection GetSelectClauses() return clauses; } - #endregion - + #endregion + #region Overridden Methods /// - protected override void EnableMenuItems(ListViewItem clickedItem) - { - ViewMI.Enabled = ItemsLV.SelectedItems.Count == 1; + protected override void EnableMenuItems(ListViewItem clickedItem) + { + ViewMI.Enabled = ItemsLV.SelectedItems.Count == 1; DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item) + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) { - SimpleAttributeOperand clause = item as SimpleAttributeOperand; + SimpleAttributeOperand clause = item as SimpleAttributeOperand; - if (clause == null) - { - base.UpdateItem(listItem, item); - return; - } + if (clause == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } - INode eventType = m_session.NodeCache.Find(clause.TypeDefinitionId); + INode eventType = await m_session.NodeCache.FindAsync(clause.TypeDefinitionId, ct); if (eventType != null) { @@ -180,17 +181,17 @@ protected override void UpdateItem(ListViewItem listItem, object item) listItem.SubItems[0].Text = String.Format("(unspecified)"); } - listItem.SubItems[1].Text = String.Format("{0}", SimpleAttributeOperand.Format(clause.BrowsePath)); - listItem.SubItems[2].Text = String.Format("{0}", clause.IndexRange); + listItem.SubItems[1].Text = String.Format("{0}", SimpleAttributeOperand.Format(clause.BrowsePath)); + listItem.SubItems[2].Text = String.Format("{0}", clause.IndexRange); - listItem.Tag = item; + listItem.Tag = item; } /// /// Handles a drop event. /// - protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) - { + protected override async Task OnDragDropAsync(object sender, DragEventArgs e, CancellationToken ct = default) + { try { ReferenceDescription reference = e.Data.GetData(typeof(ReferenceDescription)) as ReferenceDescription; @@ -199,16 +200,16 @@ protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) { return; } - - AddSelectClause(reference); + + await AddSelectClauseAsync(reference, ct); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion - + #region Event Handlers private void ViewMI_Click(object sender, EventArgs e) { @@ -223,7 +224,7 @@ private void ViewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -245,7 +246,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.Designer.cs b/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.Designer.cs index 77f95ce15..c776d4874 100644 --- a/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.Designer.cs @@ -119,7 +119,7 @@ private void InitializeComponent() this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(306, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // SubscriptionEnablePublishingMI // @@ -127,7 +127,7 @@ private void InitializeComponent() this.SubscriptionEnablePublishingMI.Name = "SubscriptionEnablePublishingMI"; this.SubscriptionEnablePublishingMI.Size = new System.Drawing.Size(306, 22); this.SubscriptionEnablePublishingMI.Text = "Enable Publishing"; - this.SubscriptionEnablePublishingMI.Click += new System.EventHandler(this.SubscriptionEnablePublishingMI_Click); + this.SubscriptionEnablePublishingMI.Click += new System.EventHandler(this.SubscriptionEnablePublishingMI_ClickAsync); // // SubscriptionCreateItemMI // @@ -187,7 +187,7 @@ private void InitializeComponent() this.ConditionRefreshMI.Name = "ConditionRefreshMI"; this.ConditionRefreshMI.Size = new System.Drawing.Size(122, 22); this.ConditionRefreshMI.Text = "Refresh..."; - this.ConditionRefreshMI.Click += new System.EventHandler(this.ConditionRefreshMI_Click); + this.ConditionRefreshMI.Click += new System.EventHandler(this.ConditionRefreshMI_ClickAsync); // // StatusBarCTRL // diff --git a/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.cs b/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.cs index e5c9aa484..fc7fc434e 100644 --- a/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,10 +33,11 @@ using System.Data; using System.Drawing; using System.Linq; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -50,9 +51,9 @@ public SubscriptionDlg() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); - m_SessionNotification = new NotificationEventHandler(Session_Notification); + m_SessionNotification = new NotificationEventHandler(Session_NotificationAsync); m_SubscriptionStateChanged = new SubscriptionStateChangedEventHandler(Subscription_StateChanged); - m_PublishStatusChanged = new PublishStateChangedEventHandler(Subscription_PublishStatusChanged); + m_PublishStatusChanged = new PublishStateChangedEventHandler(Subscription_PublishStatusChangedAsync); } #endregion @@ -68,19 +69,19 @@ public SubscriptionDlg() /// /// Creates a new subscription. /// - public Subscription New(Session session) + public async Task NewAsync(Session session, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); + if (session == null) throw new ArgumentNullException(nameof(session)); Subscription subscription = new Subscription(session.DefaultSubscription); - if (!new SubscriptionEditDlg().ShowDialog(subscription)) + if (!await new SubscriptionEditDlg().ShowDialogAsync(subscription, ct)) { return null; } session.AddSubscription(subscription); - subscription.Create(); + await subscription.CreateAsync(ct); Subscription duplicateSubscription = session.Subscriptions.FirstOrDefault(s => s.Id != 0 && s.Id.Equals(subscription.Id) && s != subscription); if (duplicateSubscription != null) @@ -90,8 +91,8 @@ public Subscription New(Session session) DialogResult result = MessageBox.Show("Duplicate subscription was created with the id: " + duplicateSubscription.Id + ". Do you want to keep it?", "Warning", MessageBoxButtons.YesNo); if (result == System.Windows.Forms.DialogResult.No) { - duplicateSubscription.Delete(false); - session.RemoveSubscription(subscription); + await duplicateSubscription.DeleteAsync(false, ct); + await session.RemoveSubscriptionAsync(subscription, ct); return null; } @@ -107,7 +108,7 @@ public Subscription New(Session session) /// public void Show(Subscription subscription) { - if (subscription == null) throw new ArgumentNullException("subscription"); + if (subscription == null) throw new ArgumentNullException(nameof(subscription)); Show(); BringToFront(); @@ -132,7 +133,7 @@ public void Show(Subscription subscription) MonitoredItemsCTRL.Initialize(subscription); EventsCTRL.Initialize(subscription, null); - DataChangesCTRL.Initialize(subscription, null); + DataChangesCTRL.InitializeAsync(subscription, null); WindowMI_Click(WindowDataChangesMI, null); @@ -213,7 +214,7 @@ private void UpdateStatus() /// /// Processes a Publish repsonse from the server. /// - void Session_Notification(ISession session, NotificationEventArgs e) + private async void Session_NotificationAsync(ISession session, NotificationEventArgs e) { if (InvokeRequired) { @@ -235,7 +236,7 @@ void Session_Notification(ISession session, NotificationEventArgs e) // notify controls of the change. EventsCTRL.NotificationReceived(e); - DataChangesCTRL.NotificationReceived(e); + await DataChangesCTRL.NotificationReceivedAsync(e); // update subscription status. UpdateStatus(); @@ -249,7 +250,7 @@ void Session_Notification(ISession session, NotificationEventArgs e) /// /// Handles a change to the state of the subscription. /// - void Subscription_StateChanged(Subscription subscription, SubscriptionStateChangedEventArgs e) + private void Subscription_StateChanged(Subscription subscription, SubscriptionStateChangedEventArgs e) { if (InvokeRequired) { @@ -286,7 +287,7 @@ void Subscription_StateChanged(Subscription subscription, SubscriptionStateChang /// /// Handles a change to the publish status for the subscription. /// - void Subscription_PublishStatusChanged(object subscription, EventArgs e) + private async void Subscription_PublishStatusChangedAsync(object subscription, EventArgs e) { if (InvokeRequired) { @@ -307,7 +308,7 @@ void Subscription_PublishStatusChanged(object subscription, EventArgs e) } // notify controls of the change. - DataChangesCTRL.PublishStatusChanged(); + await DataChangesCTRL.PublishStatusChangedAsync(); } catch (Exception exception) { @@ -367,11 +368,11 @@ private void WindowMI_Click(object sender, EventArgs e) } } - private void SubscriptionEnablePublishingMI_Click(object sender, EventArgs e) + private async void SubscriptionEnablePublishingMI_ClickAsync(object sender, EventArgs e) { try { - m_subscription.SetPublishingMode(SubscriptionEnablePublishingMI.Checked); + await m_subscription.SetPublishingModeAsync(SubscriptionEnablePublishingMI.Checked); } catch (Exception exception) { @@ -396,16 +397,16 @@ private void SubscriptionDlg_FormClosing(object sender, FormClosingEventArgs e) } } - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { - if (!new SubscriptionEditDlg().ShowDialog(m_subscription)) + if (!await new SubscriptionEditDlg().ShowDialogAsync(m_subscription)) { return; } - m_subscription.Modify(); + await m_subscription.ModifyAsync(); } catch (Exception exception) { @@ -464,11 +465,11 @@ private void SubscriptionCreateItemFromTypeMI_Click(object sender, EventArgs e) } } - private void ConditionRefreshMI_Click(object sender, EventArgs e) + private async void ConditionRefreshMI_ClickAsync(object sender, EventArgs e) { try { - m_subscription.ConditionRefresh(); + await m_subscription.ConditionRefreshAsync(); } catch (Exception exception) { diff --git a/Samples/Controls.Net4/Subscriptions/SubscriptionEditDlg.cs b/Samples/Controls.Net4/Subscriptions/SubscriptionEditDlg.cs index 5ae319ac2..c80e5c643 100644 --- a/Samples/Controls.Net4/Subscriptions/SubscriptionEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/SubscriptionEditDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,10 +32,11 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; namespace Opc.Ua.Sample.Controls @@ -50,32 +51,32 @@ public SubscriptionEditDlg() /// /// Prompts the user to specify the browse options. /// - public bool ShowDialog(Subscription subscription) + public async Task ShowDialogAsync(Subscription subscription, CancellationToken ct = default) { - if (subscription == null) throw new ArgumentNullException("subscription"); + if (subscription == null) throw new ArgumentNullException(nameof(subscription)); - DisplayNameTB.Text = subscription.DisplayName; - PublishingIntervalNC.Value = subscription.Created ? (decimal)subscription.CurrentPublishingInterval : (decimal)subscription.PublishingInterval; - KeepAliveCountNC.Value = subscription.Created ? subscription.CurrentKeepAliveCount : subscription.KeepAliveCount; - LifetimeCountCTRL.Value = subscription.Created ? subscription.CurrentLifetimeCount: subscription.LifetimeCount; - MaxNotificationsCTRL.Value = subscription.MaxNotificationsPerPublish; - PriorityNC.Value = subscription.Created ? subscription.CurrentPriority : subscription.Priority; + DisplayNameTB.Text = subscription.DisplayName; + PublishingIntervalNC.Value = subscription.Created ? (decimal)subscription.CurrentPublishingInterval : (decimal)subscription.PublishingInterval; + KeepAliveCountNC.Value = subscription.Created ? subscription.CurrentKeepAliveCount : subscription.KeepAliveCount; + LifetimeCountCTRL.Value = subscription.Created ? subscription.CurrentLifetimeCount : subscription.LifetimeCount; + MaxNotificationsCTRL.Value = subscription.MaxNotificationsPerPublish; + PriorityNC.Value = subscription.Created ? subscription.CurrentPriority : subscription.Priority; PublishingEnabledCK.Checked = subscription.Created ? subscription.CurrentPublishingEnabled : subscription.PublishingEnabled; - + if (ShowDialog() != DialogResult.OK) { return false; } - subscription.DisplayName = DisplayNameTB.Text; - subscription.PublishingInterval = (int)PublishingIntervalNC.Value; - subscription.KeepAliveCount = (uint)KeepAliveCountNC.Value; - subscription.LifetimeCount = (uint)LifetimeCountCTRL.Value; + subscription.DisplayName = DisplayNameTB.Text; + subscription.PublishingInterval = (int)PublishingIntervalNC.Value; + subscription.KeepAliveCount = (uint)KeepAliveCountNC.Value; + subscription.LifetimeCount = (uint)LifetimeCountCTRL.Value; subscription.MaxNotificationsPerPublish = (uint)MaxNotificationsCTRL.Value; - subscription.Priority = (byte)PriorityNC.Value; + subscription.Priority = (byte)PriorityNC.Value; if (subscription.Created) { - subscription.SetPublishingMode(PublishingEnabledCK.Checked); + await subscription.SetPublishingModeAsync(PublishingEnabledCK.Checked, ct); } else { diff --git a/Samples/Controls.Net4/Subscriptions/WriteDlg.Designer.cs b/Samples/Controls.Net4/Subscriptions/WriteDlg.Designer.cs index 6d9490479..9c41fd53d 100644 --- a/Samples/Controls.Net4/Subscriptions/WriteDlg.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/WriteDlg.Designer.cs @@ -98,7 +98,7 @@ private void InitializeComponent() this.BackBTN.TabIndex = 3; this.BackBTN.Text = "< Back"; this.BackBTN.UseVisualStyleBackColor = true; - this.BackBTN.Click += new System.EventHandler(this.MoveBTN_Click); + this.BackBTN.Click += new System.EventHandler(this.MoveBTN_ClickAsync); // // CancelBTN // @@ -121,7 +121,7 @@ private void InitializeComponent() this.NextBTN.TabIndex = 2; this.NextBTN.Text = "Next >"; this.NextBTN.UseVisualStyleBackColor = true; - this.NextBTN.Click += new System.EventHandler(this.MoveBTN_Click); + this.NextBTN.Click += new System.EventHandler(this.MoveBTN_ClickAsync); // // WriteBTN // @@ -132,7 +132,7 @@ private void InitializeComponent() this.WriteBTN.TabIndex = 4; this.WriteBTN.Text = "Write"; this.WriteBTN.UseVisualStyleBackColor = true; - this.WriteBTN.Click += new System.EventHandler(this.WriteMI_Click); + this.WriteBTN.Click += new System.EventHandler(this.WriteMI_ClickAsync); // // SplitterPN // @@ -163,7 +163,7 @@ private void InitializeComponent() this.BrowseCTRL.SessionTreeCtrl = null; this.BrowseCTRL.Size = new System.Drawing.Size(297, 392); this.BrowseCTRL.TabIndex = 1; - this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelected); + this.BrowseCTRL.ItemsSelected += new Opc.Ua.Sample.Controls.NodesSelectedEventHandler(this.BrowseCTRL_ItemsSelectedAsync); // // WriteResultsCTRL // diff --git a/Samples/Controls.Net4/Subscriptions/WriteDlg.cs b/Samples/Controls.Net4/Subscriptions/WriteDlg.cs index 5de42e5fb..17f2e9ff0 100644 --- a/Samples/Controls.Net4/Subscriptions/WriteDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/WriteDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading; +using System.Threading.Tasks; namespace Opc.Ua.Sample.Controls { @@ -54,21 +56,21 @@ public WriteDlg() #region Private Fields private Session m_session; #endregion - + #region Public Interface /// /// Displays the dialog. /// - public void Show(Session session, WriteValueCollection values) + public async Task ShowAsync(Session session, WriteValueCollection values, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + m_session = session; - BrowseCTRL.SetView(m_session, BrowseViewType.Objects, null); + await BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, ct); WriteValuesCTRL.Initialize(session, values); - MoveBTN_Click(BackBTN, null); + MoveBTN_ClickAsync(BackBTN, null); Show(); BringToFront(); @@ -77,7 +79,7 @@ public void Show(Session session, WriteValueCollection values) /// /// Writes the valus to the server. /// - private void Write() + private async Task WriteAsync(CancellationToken ct = default) { WriteValueCollection nodesToWrite = Utils.Clone(WriteValuesCTRL.GetValues()) as WriteValueCollection; @@ -105,24 +107,23 @@ private void Write() } } - StatusCodeCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_session.Write( + WriteResponse response = await m_session.WriteAsync( null, nodesToWrite, - out results, - out diagnosticInfos); + ct); + + StatusCodeCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); - WriteResultsCTRL.ShowValue(results, true); + await WriteResultsCTRL.ShowValueAsync(results, true, ct); } #endregion - + #region Event Handlers - private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) + private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEventArgs e) { try { @@ -130,61 +131,61 @@ private void BrowseCTRL_ItemsSelected(object sender, NodesSelectedEventArgs e) { if (reference.ReferenceTypeId == ReferenceTypeIds.HasProperty || reference.IsForward) { - WriteValuesCTRL.AddValue(reference); + await WriteValuesCTRL.AddValueAsync(reference); } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void MoveBTN_Click(object sender, EventArgs e) + private async void MoveBTN_ClickAsync(object sender, EventArgs e) { try { if (sender == NextBTN) { - Write(); + await WriteAsync(); - WriteValuesCTRL.Parent = SplitterPN.Panel1; + WriteValuesCTRL.Parent = SplitterPN.Panel1; - BackBTN.Visible = true; - NextBTN.Visible = false; - WriteBTN.Visible = true; - WriteValuesCTRL.Visible = true; + BackBTN.Visible = true; + NextBTN.Visible = false; + WriteBTN.Visible = true; + WriteValuesCTRL.Visible = true; WriteResultsCTRL.Visible = true; - BrowseCTRL.Visible = false; + BrowseCTRL.Visible = false; } else if (sender == BackBTN) { - WriteValuesCTRL.Parent = SplitterPN.Panel2; - - BackBTN.Visible = false; - NextBTN.Visible = true; - WriteBTN.Visible = false; - WriteResultsCTRL.Visible = false; - BrowseCTRL.Visible = true; - WriteValuesCTRL.Visible = true; + WriteValuesCTRL.Parent = SplitterPN.Panel2; + + BackBTN.Visible = false; + NextBTN.Visible = true; + WriteBTN.Visible = false; + WriteResultsCTRL.Visible = false; + BrowseCTRL.Visible = true; + WriteValuesCTRL.Visible = true; } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void WriteMI_Click(object sender, EventArgs e) + private async void WriteMI_ClickAsync(object sender, EventArgs e) { try { - Write(); + await WriteAsync(); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -196,7 +197,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/WriteValueEditDlg.cs b/Samples/Controls.Net4/Subscriptions/WriteValueEditDlg.cs index e1ef102a2..deb5d7f27 100644 --- a/Samples/Controls.Net4/Subscriptions/WriteValueEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/WriteValueEditDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,10 +33,13 @@ using System.Data; using System.Drawing; using System.Text; +using System.Linq; using System.Windows.Forms; using System.Reflection; using Opc.Ua.Client; +using System.Threading; +using System.Threading.Tasks; namespace Opc.Ua.Sample.Controls { @@ -46,54 +49,54 @@ public WriteValueEditDlg() { InitializeComponent(); - AttributeIdCB.Items.AddRange(Attributes.GetBrowseNames()); + AttributeIdCB.Items.AddRange(Attributes.BrowseNames.ToArray()); } /// /// Prompts the user to specify the browse options. /// - public bool ShowDialog(Session session, WriteValue value) + public async Task ShowDialogAsync(Session session, WriteValue value, CancellationToken ct = default) { - if (session == null) throw new ArgumentNullException("session"); - if (value == null) throw new ArgumentNullException("value"); + if (session == null) throw new ArgumentNullException(nameof(session)); + if (value == null) throw new ArgumentNullException(nameof(value)); + - NodeIdCTRL.Browser = new Browser(session); - INode node = session.NodeCache.Find(value.NodeId); + INode node = await session.NodeCache.FindAsync(value.NodeId, ct); if (node != null) { DisplayNameTB.Text = node.ToString(); } - NodeIdCTRL.Identifier = value.NodeId; + NodeIdCTRL.Identifier = value.NodeId; AttributeIdCB.SelectedItem = Attributes.GetBrowseName(value.AttributeId); - IndexRangeTB.Text = value.IndexRange; - + IndexRangeTB.Text = value.IndexRange; + if (ShowDialog() != DialogResult.OK) { return false; } - value.NodeId = NodeIdCTRL.Identifier; + value.NodeId = NodeIdCTRL.Identifier; value.AttributeId = Attributes.GetIdentifier((string)AttributeIdCB.SelectedItem); - value.IndexRange = IndexRangeTB.Text; - + value.IndexRange = IndexRangeTB.Text; + return true; } private void OkBTN_Click(object sender, EventArgs e) - { + { try { NodeId nodeId = NodeIdCTRL.Identifier; } catch (Exception) { - MessageBox.Show("Please enter a valid node id.", this.Text); + MessageBox.Show("Please enter a valid node id.", this.Text); } - + try { if (!String.IsNullOrEmpty(IndexRangeTB.Text)) @@ -103,7 +106,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception) { - MessageBox.Show("Please enter a valid index range.", this.Text); + MessageBox.Show("Please enter a valid index range.", this.Text); } DialogResult = DialogResult.OK; diff --git a/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.Designer.cs b/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.Designer.cs index 1a4cd5510..d2bba53a4 100644 --- a/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.Designer.cs +++ b/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.Designer.cs @@ -85,21 +85,21 @@ private void InitializeComponent() this.NewMI.Name = "NewMI"; this.NewMI.Size = new System.Drawing.Size(152, 22); this.NewMI.Text = "New..."; - this.NewMI.Click += new System.EventHandler(this.NewMI_Click); + this.NewMI.Click += new System.EventHandler(this.NewMI_ClickAsync); // // EditMI // this.EditMI.Name = "EditMI"; this.EditMI.Size = new System.Drawing.Size(152, 22); this.EditMI.Text = "Edit..."; - this.EditMI.Click += new System.EventHandler(this.EditMI_Click); + this.EditMI.Click += new System.EventHandler(this.EditMI_ClickAsync); // // EditValueMI // this.EditValueMI.Name = "EditValueMI"; this.EditValueMI.Size = new System.Drawing.Size(152, 22); this.EditValueMI.Text = "Edit Value..."; - this.EditValueMI.Click += new System.EventHandler(this.EditValueMI_Click); + this.EditValueMI.Click += new System.EventHandler(this.EditValueMI_ClickAsync); // // DeleteMI // diff --git a/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.cs b/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.cs index c9fdab190..47475f5b3 100644 --- a/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -38,6 +38,8 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Sample.Controls { @@ -45,8 +47,8 @@ public partial class WriteValueListCtrl : Opc.Ua.Client.Controls.BaseListCtrl { public WriteValueListCtrl() { - InitializeComponent(); - SetColumns(m_ColumnNames); + InitializeComponent(); + SetColumns(m_ColumnNames); } #region Private Fields @@ -56,16 +58,16 @@ public WriteValueListCtrl() /// The columns to display in the control. ///
private readonly object[][] m_ColumnNames = new object[][] - { - new object[] { "Name", HorizontalAlignment.Left, null }, - new object[] { "NodeId", HorizontalAlignment.Left, null }, - new object[] { "Attribute", HorizontalAlignment.Left, "Value" }, - new object[] { "IndexRange", HorizontalAlignment.Left, "" }, - new object[] { "Value", HorizontalAlignment.Left, "" }, - new object[] { "Status", HorizontalAlignment.Left, "" }, - new object[] { "Timestamp", HorizontalAlignment.Left, "" } - }; - #endregion + { + new object[] { "Name", HorizontalAlignment.Left, null }, + new object[] { "NodeId", HorizontalAlignment.Left, null }, + new object[] { "Attribute", HorizontalAlignment.Left, "Value" }, + new object[] { "IndexRange", HorizontalAlignment.Left, "" }, + new object[] { "Value", HorizontalAlignment.Left, "" }, + new object[] { "Status", HorizontalAlignment.Left, "" }, + new object[] { "Timestamp", HorizontalAlignment.Left, "" } + }; + #endregion #region Public Interface /// @@ -82,10 +84,10 @@ public void Clear() /// public void Initialize(Session session, WriteValueCollection values) { - if (session == null) throw new ArgumentNullException("session"); - + if (session == null) throw new ArgumentNullException(nameof(session)); + Clear(); - + m_session = session; if (values != null) @@ -102,9 +104,9 @@ public void Initialize(Session session, WriteValueCollection values) /// /// Adds a value to the control. /// - public void AddValue(ReferenceDescription reference) + public async Task AddValueAsync(ReferenceDescription reference, CancellationToken ct = default) { - Node node = m_session.NodeCache.Find(reference.NodeId) as Node; + Node node = await m_session.NodeCache.FindAsync(reference.NodeId, ct) as Node; if (node == null) { @@ -113,17 +115,17 @@ public void AddValue(ReferenceDescription reference) WriteValue value = new WriteValue(); - value.NodeId = node.NodeId; + value.NodeId = node.NodeId; value.AttributeId = Attributes.Value; - value.IndexRange = null; + value.IndexRange = null; // read the display name for non-variables. if ((node.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0) { - value.AttributeId = Attributes.DisplayName; + value.AttributeId = Attributes.DisplayName; } - value.Value = GetDefaultValue(value.NodeId, value.AttributeId); + value.Value = await GetDefaultValueAsync(value.NodeId, value.AttributeId, ct); AddItem(value); AdjustColumns(); @@ -157,10 +159,10 @@ public WriteValueCollection GetValues() /// /// Returns a default value for the node. /// - private DataValue GetDefaultValue(NodeId nodeId, uint attributeId) + private async Task GetDefaultValueAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) { // find the node. - Node node = m_session.NodeCache.Find(nodeId) as Node; + Node node = await m_session.NodeCache.FindAsync(nodeId, ct) as Node; if (node == null) { @@ -176,13 +178,13 @@ private DataValue GetDefaultValue(NodeId nodeId, uint attributeId) { value.Value = GuiUtils.GetDefaultValue(Attributes.GetDataTypeId(attributeId), ValueRanks.Scalar); } - + // update the value attribute. if (attributeId == Attributes.Value) { try { - return m_session.ReadValue(node.NodeId); + return await m_session.ReadValueAsync(node.NodeId, ct); } catch (Exception) { @@ -194,50 +196,50 @@ private DataValue GetDefaultValue(NodeId nodeId, uint attributeId) } } } - + return value; } - #endregion - + #endregion + #region Overridden Methods /// protected override void PickItems() { base.PickItems(); - EditValueMI_Click(this, null); + EditValueMI_ClickAsync(this, null); } /// protected override void EnableMenuItems(ListViewItem clickedItem) - { - NewMI.Enabled = true; - EditMI.Enabled = ItemsLV.SelectedItems.Count == 1; - EditValueMI.Enabled = ItemsLV.SelectedItems.Count == 1; - DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; - } - - /// - protected override void UpdateItem(ListViewItem listItem, object item) { - WriteValue value = item as WriteValue; - - if (value == null) - { - base.UpdateItem(listItem, item); - return; - } - + NewMI.Enabled = true; + EditMI.Enabled = ItemsLV.SelectedItems.Count == 1; + EditValueMI.Enabled = ItemsLV.SelectedItems.Count == 1; + DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; + } + + /// + protected override async Task UpdateItemAsync(ListViewItem listItem, object item, CancellationToken ct = default) + { + WriteValue value = item as WriteValue; + + if (value == null) + { + await base.UpdateItemAsync(listItem, item, ct); + return; + } + if (value.Value == null) { value.Value = new DataValue(); } - + if (value.Value.Value == null) { - value.Value = GetDefaultValue(value.NodeId, value.AttributeId); + value.Value = await GetDefaultValueAsync(value.NodeId, value.AttributeId, ct); } - - Node node = m_session.NodeCache.Find(value.NodeId) as Node; + + Node node = await m_session.NodeCache.FindAsync(value.NodeId, ct) as Node; if (node != null) { @@ -247,23 +249,23 @@ protected override void UpdateItem(ListViewItem listItem, object item) { listItem.SubItems[0].Text = String.Format("{0}", value.NodeId); } - + listItem.SubItems[1].Text = String.Format("{0}", value.NodeId); listItem.SubItems[2].Text = String.Format("{0}", Attributes.GetBrowseName(value.AttributeId)); listItem.SubItems[3].Text = String.Format("{0}", value.IndexRange); listItem.SubItems[4].Text = String.Format("{0}", value.Value.Value); listItem.SubItems[5].Text = String.Format("{0}", value.Value.StatusCode); listItem.SubItems[6].Text = String.Format("{0}", value.Value.SourceTimestamp); - - listItem.Tag = item; + + listItem.Tag = item; listItem.ImageKey = "DataType"; } /// /// Handles a drop event. /// - protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) - { + protected override async Task OnDragDropAsync(object sender, DragEventArgs e, CancellationToken ct = default) + { try { ReferenceDescription reference = e.Data.GetData(typeof(ReferenceDescription)) as ReferenceDescription; @@ -272,24 +274,24 @@ protected override void ItemsLV_DragDrop(object sender, DragEventArgs e) { return; } - - AddValue(reference); + + await AddValueAsync(reference, ct); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion - + #region Event Handlers - private void NewMI_Click(object sender, EventArgs e) + private async void NewMI_ClickAsync(object sender, EventArgs e) { try { WriteValue value = new WriteValue(); - if (new WriteValueEditDlg().ShowDialog(m_session, value)) + if (await new WriteValueEditDlg().ShowDialogAsync(m_session, value)) { AddItem(value); } @@ -298,11 +300,11 @@ private void NewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void EditMI_Click(object sender, EventArgs e) + private async void EditMI_ClickAsync(object sender, EventArgs e) { try { @@ -313,9 +315,9 @@ private void EditMI_Click(object sender, EventArgs e) return; } - if (new WriteValueEditDlg().ShowDialog(m_session, values[0])) + if (await new WriteValueEditDlg().ShowDialogAsync(m_session, values[0])) { - Node node = m_session.NodeCache.Find(values[0].NodeId) as Node; + Node node = await m_session.NodeCache.FindAsync(values[0].NodeId) as Node; if (node != null) { @@ -329,16 +331,16 @@ private void EditMI_Click(object sender, EventArgs e) } } - UpdateItem(ItemsLV.SelectedItems[0], values[0]); + await UpdateItemAsync(ItemsLV.SelectedItems[0], values[0]); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void EditValueMI_Click(object sender, EventArgs e) + private async void EditValueMI_ClickAsync(object sender, EventArgs e) { try { @@ -354,7 +356,7 @@ private void EditValueMI_Click(object sender, EventArgs e) if (values[0].AttributeId == Attributes.Value) { - VariableNode node = m_session.NodeCache.Find(values[0].NodeId) as VariableNode; + VariableNode node = await m_session.NodeCache.FindAsync(values[0].NodeId) as VariableNode; if (node != null) { @@ -399,7 +401,7 @@ private void EditValueMI_Click(object sender, EventArgs e) values[0].Value.Value = value; values[0].Value.StatusCode = StatusCodes.Good; - UpdateItem(ItemsLV.SelectedItems[0], values[0]); + await UpdateItemAsync(ItemsLV.SelectedItems[0], values[0]); AdjustColumns(); } @@ -430,7 +432,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/UA Sample Controls.csproj b/Samples/Controls.Net4/UA Sample Controls.csproj index 59a25e85a..38d474d6a 100644 --- a/Samples/Controls.Net4/UA Sample Controls.csproj +++ b/Samples/Controls.Net4/UA Sample Controls.csproj @@ -46,6 +46,7 @@ 4 AnyCPU false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 AnyCPU false + AllRules.ruleset @@ -200,12 +202,6 @@ SelectClauseListCtrl.cs - - Form - - - DataEncodingDlg.cs - UserControl @@ -519,10 +515,6 @@ SelectClauseListCtrl.cs Designer - - DataEncodingDlg.cs - Designer - Designer PerformanceResultsListCtrl.cs @@ -707,8 +699,11 @@ + + 1.5.377.11-preview + - 1.5.376.244 + 1.5.377.11-preview diff --git a/Samples/GDS/Client/Controls/ApplicationCertificateControl.cs b/Samples/GDS/Client/Controls/ApplicationCertificateControl.cs index 5c09a8a09..523f8e065 100644 --- a/Samples/GDS/Client/Controls/ApplicationCertificateControl.cs +++ b/Samples/GDS/Client/Controls/ApplicationCertificateControl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,7 @@ using System.Drawing; using System.IO; using System.Security.Cryptography.X509Certificates; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; @@ -52,12 +53,13 @@ public ApplicationCertificateControl() private bool m_temporaryCertificateCreated; private string m_certificatePassword; - public async Task Initialize( + public async Task InitializeAsync( GlobalDiscoveryClientConfiguration configuration, GlobalDiscoveryServerClient gds, ServerPushConfigurationClient server, RegisteredApplication application, - bool isHttps) + bool isHttps, + CancellationToken ct = default) { m_configuration = configuration; m_gds = gds; @@ -100,7 +102,7 @@ public async Task Initialize( id.StoreType = CertificateStoreIdentifier.DetermineStoreType(id.StorePath); id.SubjectName = application.CertificateSubjectName.Replace("localhost", Utils.GetHostName()); - certificate = await id.Find(true); + certificate = await id.FindAsync(true, ct: ct); } } } @@ -131,7 +133,7 @@ public async Task Initialize( SubjectName = "CN=" + url.DnsSafeHost }; - certificate = await id.Find(); + certificate = await id.FindAsync(ct: ct); } } } @@ -170,31 +172,31 @@ private async void RequestNewButton_Click(object sender, EventArgs e) { if (m_application.RegistrationType == RegistrationType.ServerPush) { - RequestNewCertificatePushMode(sender, e); + await RequestNewCertificatePushModeAsync(sender, e); } else { - await RequestNewCertificatePullMode(sender, e); + await RequestNewCertificatePullModeAsync(sender, e); } } - private void RequestNewCertificatePushMode(object sender, EventArgs e) + private async Task RequestNewCertificatePushModeAsync(object sender, EventArgs e) { try { - NodeId trustListId = m_gds.GetTrustList(m_application.ApplicationId, NodeId.Null); - var trustList = m_gds.ReadTrustList(trustListId); - bool applyChanges = m_server.UpdateTrustList(trustList); + NodeId trustListId = await m_gds.GetTrustListAsync(m_application.ApplicationId, NodeId.Null); + var trustList = await m_gds.ReadTrustListAsync(trustListId); + bool applyChanges = await m_server.UpdateTrustListAsync(trustList); - byte[] unusedNonce = new byte[0]; - byte[] certificateRequest = m_server.CreateSigningRequest( + byte[] unusedNonce = Array.Empty(); + byte[] certificateRequest = await m_server.CreateSigningRequestAsync( NodeId.Null, m_server.ApplicationCertificateType, string.Empty, false, unusedNonce); var domainNames = m_application.GetDomainNames(m_certificate); - NodeId requestId = m_gds.StartSigningRequest( + NodeId requestId = await m_gds.StartSigningRequestAsync( m_application.ApplicationId, NodeId.Null, NodeId.Null, @@ -223,7 +225,7 @@ private void RequestNewCertificatePushMode(object sender, EventArgs e) } } - private async Task RequestNewCertificatePullMode(object sender, EventArgs e) + private async Task RequestNewCertificatePullModeAsync(object sender, EventArgs e) { try { @@ -236,7 +238,7 @@ private async Task RequestNewCertificatePullMode(object sender, EventArgs e) StorePath = m_application.CertificateStorePath, SubjectName = Utils.ReplaceDCLocalhost(m_application.CertificateSubjectName) }; - m_certificate = await id.Find(true); + m_certificate = await id.FindAsync(true); //test if private key is available & exportable, else create new temporary certificate for csr if (m_certificate != null && m_certificate.HasPrivateKey) @@ -246,7 +248,7 @@ private async Task RequestNewCertificatePullMode(object sender, EventArgs e) //this line fails with a CryptographicException if export of private key is not allowed _ = m_certificate.GetRSAPrivateKey().ExportParameters(true); //proceed with a CSR using the exportable private key - m_certificate = await id.LoadPrivateKey(m_certificatePassword); + m_certificate = await id.LoadPrivateKeyAsync(m_certificatePassword); } catch { @@ -276,7 +278,7 @@ private async Task RequestNewCertificatePullMode(object sender, EventArgs e) if (m_certificate == null) { // no private key - requestId = m_gds.StartNewKeyPairRequest( + requestId = await m_gds.StartNewKeyPairRequestAsync( m_application.ApplicationId, NodeId.Null, NodeId.Null, @@ -296,7 +298,7 @@ private async Task RequestNewCertificatePullMode(object sender, EventArgs e) { string absoluteCertificatePrivateKeyPath = Utils.GetAbsoluteFilePath(m_application.CertificatePrivateKeyPath, true, false, false); byte[] pkcsData = File.ReadAllBytes(absoluteCertificatePrivateKeyPath); - if (m_application.GetPrivateKeyFormat(m_server?.GetSupportedKeyFormats()) == "PFX") + if (m_application.GetPrivateKeyFormat(await m_server?.GetSupportedKeyFormatsAsync()) == "PFX") { csrCertificate = X509PfxUtils.CreateCertificateFromPKCS12(pkcsData, m_certificatePassword); } @@ -306,7 +308,7 @@ private async Task RequestNewCertificatePullMode(object sender, EventArgs e) } } byte[] certificateRequest = CertificateFactory.CreateSigningRequest(csrCertificate, domainNames); - requestId = m_gds.StartSigningRequest(m_application.ApplicationId, NodeId.Null, NodeId.Null, certificateRequest); + requestId = await m_gds.StartSigningRequestAsync(m_application.ApplicationId, NodeId.Null, NodeId.Null, certificateRequest); } m_application.CertificateRequestId = requestId.ToString(); @@ -326,14 +328,9 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) { NodeId requestId = NodeId.Parse(m_application.CertificateRequestId); - byte[] privateKeyPFX = null; - byte[][] issuerCertificates = null; - - byte[] certificate = m_gds.FinishRequest( + (byte[] certificate, byte[] privateKeyPFX, byte[][] issuerCertificates) = await m_gds.FinishRequestAsync( m_application.ApplicationId, - requestId, - out privateKeyPFX, - out issuerCertificates); + requestId); if (certificate == null) { @@ -365,12 +362,12 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) // in this case, privateKey is null if (privateKeyPFX == null) { - X509Certificate2 oldCertificate = await cid.Find(true); + X509Certificate2 oldCertificate = await cid.FindAsync(true); if (oldCertificate != null && oldCertificate.HasPrivateKey) { - oldCertificate = await cid.LoadPrivateKey(string.Empty); + oldCertificate = await cid.LoadPrivateKeyAsync(string.Empty); newCert = CertificateFactory.CreateCertificateWithPrivateKey(newCert, m_temporaryCertificateCreated ? m_certificate : oldCertificate); - await store.Delete(oldCertificate.Thumbprint); + await store.DeleteAsync(oldCertificate.Thumbprint); } else { @@ -382,7 +379,7 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) newCert = new X509Certificate2(privateKeyPFX, string.Empty, X509KeyStorageFlags.Exportable); newCert = CertificateFactory.Load(newCert, true); } - await store.Add(newCert); + await store.AddAsync(newCert); if (m_temporaryCertificateCreated) { m_certificate.Dispose(); @@ -423,7 +420,7 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) } // if we provided a PFX or P12 with the private key, we need to merge the new cert with the private key - if (m_application.GetPrivateKeyFormat(m_server?.GetSupportedKeyFormats()) == "PFX") + if (m_application.GetPrivateKeyFormat(await m_server?.GetSupportedKeyFormatsAsync()) == "PFX") { string absoluteCertificatePrivateKeyPath = Utils.GetAbsoluteFilePath(m_application.CertificatePrivateKeyPath, true, false, false) ?? m_application.CertificatePrivateKeyPath; file = new FileInfo(absoluteCertificatePrivateKeyPath); @@ -471,10 +468,10 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) foreach (byte[] issuerCertificate in issuerCertificates) { X509Certificate2 x509 = new X509Certificate2(issuerCertificate); - X509Certificate2Collection certs = await store.FindByThumbprint(x509.Thumbprint); + X509Certificate2Collection certs = await store.FindByThumbprintAsync(x509.Thumbprint); if (certs.Count == 0) { - await store.Add(new X509Certificate2(issuerCertificate)); + await store.AddAsync(new X509Certificate2(issuerCertificate)); } } } @@ -491,8 +488,8 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) privateKeyPFX = x509.Export(X509ContentType.Pfx); } - byte[] unusedPrivateKey = new byte[0]; - bool applyChanges = m_server.UpdateCertificate( + byte[] unusedPrivateKey = Array.Empty(); + bool applyChanges = await m_server.UpdateCertificateAsync( NodeId.Null, m_server.ApplicationCertificateType, certificate, @@ -528,12 +525,12 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) } } - private void ApplyChangesButton_Click(object sender, EventArgs e) + private async void ApplyChangesButton_Click(object sender, EventArgs e) { ApplyChangesButton.Enabled = false; try { - m_server.ApplyChanges(); + await m_server.ApplyChangesAsync(); } catch (Exception exception) { @@ -547,9 +544,9 @@ private void ApplyChangesButton_Click(object sender, EventArgs e) try { - m_server.Disconnect(); + await m_server.DisconnectAsync(); } - catch (Exception) + catch { // ignore. } diff --git a/Samples/GDS/Client/Controls/ApplicationTrustListControl.Designer.cs b/Samples/GDS/Client/Controls/ApplicationTrustListControl.Designer.cs index 413ea3055..f2b31ce46 100644 --- a/Samples/GDS/Client/Controls/ApplicationTrustListControl.Designer.cs +++ b/Samples/GDS/Client/Controls/ApplicationTrustListControl.Designer.cs @@ -167,7 +167,7 @@ private void InitializeComponent() this.ReadTrustListButton.Text = "Reload"; this.ToolTips.SetToolTip(this.ReadTrustListButton, "Reloads the Trust List from disk or by reading it from the remote Server."); this.ReadTrustListButton.UseVisualStyleBackColor = false; - this.ReadTrustListButton.Click += new System.EventHandler(this.ReloadTrustListButton_Click); + this.ReadTrustListButton.Click += new System.EventHandler(this.ReloadTrustListButton_ClickAsync); this.ReadTrustListButton.MouseEnter += new System.EventHandler(this.Button_MouseEnter); this.ReadTrustListButton.MouseLeave += new System.EventHandler(this.Button_MouseLeave); // diff --git a/Samples/GDS/Client/Controls/ApplicationTrustListControl.cs b/Samples/GDS/Client/Controls/ApplicationTrustListControl.cs index a896d3de0..beb658b60 100644 --- a/Samples/GDS/Client/Controls/ApplicationTrustListControl.cs +++ b/Samples/GDS/Client/Controls/ApplicationTrustListControl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -35,6 +35,7 @@ using Opc.Ua.Gds; using System.Threading.Tasks; using Opc.Ua.Security.Certificates; +using System.Threading; namespace Opc.Ua.Gds.Client { @@ -53,7 +54,7 @@ public ApplicationTrustListControl() private string m_trustListStorePath; private string m_issuerListStorePath; - public void Initialize(GlobalDiscoveryServerClient gds, ServerPushConfigurationClient server, RegisteredApplication application, bool isHttps) + public async Task Initialize(GlobalDiscoveryServerClient gds, ServerPushConfigurationClient server, RegisteredApplication application, bool isHttps, CancellationToken ct = default) { m_gds = gds; m_server = server; @@ -64,14 +65,14 @@ public void Initialize(GlobalDiscoveryServerClient gds, ServerPushConfigurationC { m_trustListStorePath = (isHttps) ? m_application.HttpsTrustListStorePath : m_application.TrustListStorePath; m_issuerListStorePath = (isHttps) ? m_application.HttpsIssuerListStorePath : m_application.IssuerListStorePath; - CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null); + await CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null, ct); MergeWithGdsButton.Enabled = !String.IsNullOrEmpty(m_trustListStorePath) || m_application.RegistrationType == RegistrationType.ServerPush; } ApplyChangesButton.Enabled = false; } - private void ReloadTrustListButton_Click(object sender, EventArgs e) + private async void ReloadTrustListButton_ClickAsync(object sender, EventArgs e) { try { @@ -83,18 +84,18 @@ private void ReloadTrustListButton_Click(object sender, EventArgs e) if (!Enum.TryParse(TrustListMasksComboBox.SelectedItem.ToString(), out masks)) masks = TrustListMasks.All; - var trustList = m_server.ReadTrustList(masks); - var rejectedList = m_server.GetRejectedList(); + var trustList = await m_server.ReadTrustListAsync(masks); + var rejectedList = await m_server.GetRejectedListAsync(); CertificateStoreControl.Initialize(trustList, rejectedList, true); } else { - CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null); + await CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null); } } else { - CertificateStoreControl.Initialize(null, null, null); + await CertificateStoreControl.Initialize(null, null, null); } } catch (Exception ex) @@ -103,17 +104,31 @@ private void ReloadTrustListButton_Click(object sender, EventArgs e) } } - private void MergeWithGdsButton_Click(object sender, EventArgs e) + private async void MergeWithGdsButton_Click(object sender, EventArgs e) { - PullFromGds(false); + try + { + await PullFromGdsAsync(false); + } + catch (Exception ex) + { + Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + } } - private void PullFromGdsButton_Click(object sender, EventArgs e) + private async void PullFromGdsButton_Click(object sender, EventArgs e) { - PullFromGds(true); + try + { + await PullFromGdsAsync(true); + } + catch (Exception ex) + { + Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + } } - private async Task DeleteExistingFromStore(string storePath) + private async Task DeleteExistingFromStoreAsync(string storePath, CancellationToken ct = default) { if (String.IsNullOrEmpty(storePath)) { @@ -123,7 +138,7 @@ private async Task DeleteExistingFromStore(string storePath) var certificateStoreIdentifier = new CertificateStoreIdentifier(storePath); using (var store = certificateStoreIdentifier.OpenStore()) { - X509Certificate2Collection certificates = await store.Enumerate(); + X509Certificate2Collection certificates = await store.EnumerateAsync(ct); foreach (var certificate in certificates) { List fields = X509Utils.ParseDistinguishedName(certificate.Subject); @@ -162,24 +177,24 @@ private async Task DeleteExistingFromStore(string storePath) } } - await store.Delete(certificate.Thumbprint); + await store.DeleteAsync(certificate.Thumbprint, ct); } } } - private void PullFromGds(bool deleteBeforeAdd) + private async Task PullFromGdsAsync(bool deleteBeforeAdd, CancellationToken ct = default) { try { - NodeId trustListId = m_gds.GetTrustList(m_application.ApplicationId, NodeId.Null); + NodeId trustListId = await m_gds.GetTrustListAsync(m_application.ApplicationId, NodeId.Null, ct); if (trustListId == null) { - CertificateStoreControl.Initialize(null, null, null); + await CertificateStoreControl.Initialize(null, null, null, ct); return; } - var trustList = m_gds.ReadTrustList(trustListId); + var trustList = await m_gds.ReadTrustListAsync(trustListId, ct); if (m_application.RegistrationType == RegistrationType.ServerPush) { @@ -199,8 +214,8 @@ private void PullFromGds(bool deleteBeforeAdd) { if (deleteBeforeAdd) { - DeleteExistingFromStore(m_trustListStorePath).Wait(); - DeleteExistingFromStore(m_issuerListStorePath).Wait(); ; + await DeleteExistingFromStoreAsync(m_trustListStorePath, ct); + await DeleteExistingFromStoreAsync(m_issuerListStorePath, ct); } } @@ -215,10 +230,10 @@ private void PullFromGds(bool deleteBeforeAdd) { var x509 = new X509Certificate2(certificate); - X509Certificate2Collection certs = store.FindByThumbprint(x509.Thumbprint).Result; + X509Certificate2Collection certs = await store.FindByThumbprintAsync(x509.Thumbprint, ct); if (certs.Count == 0) { - store.Add(x509).Wait(); + await store.AddAsync(x509, ct: ct); } } } @@ -227,7 +242,7 @@ private void PullFromGds(bool deleteBeforeAdd) { foreach (var crl in trustList.TrustedCrls) { - store.AddCRL(new X509CRL(crl)); + await store.AddCRLAsync(new X509CRL(crl), ct); } } } @@ -244,10 +259,10 @@ private void PullFromGds(bool deleteBeforeAdd) { var x509 = new X509Certificate2(certificate); - X509Certificate2Collection certs = store.FindByThumbprint(x509.Thumbprint).Result; + X509Certificate2Collection certs = await store.FindByThumbprintAsync(x509.Thumbprint, ct); if (certs.Count == 0) { - store.Add(x509).Wait(); + await store.AddAsync(x509, ct: ct); } } } @@ -256,13 +271,13 @@ private void PullFromGds(bool deleteBeforeAdd) { foreach (var crl in trustList.IssuerCrls) { - store.AddCRL(new X509CRL(crl)); + await store.AddCRLAsync(new X509CRL(crl), ct); } } } } - CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null); + await CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null, ct); MessageBox.Show( Parent, @@ -277,7 +292,7 @@ private void PullFromGds(bool deleteBeforeAdd) } } - private void PushToServerButton_Click(object sender, EventArgs e) + private async void PushToServerButton_Click(object sender, EventArgs e) { try { @@ -287,7 +302,7 @@ private void PushToServerButton_Click(object sender, EventArgs e) { var trustList = CertificateStoreControl.GetTrustLists(); - bool applyChanges = m_server.UpdateTrustList(trustList); + bool applyChanges = await m_server.UpdateTrustListAsync(trustList); if (applyChanges) { @@ -319,11 +334,11 @@ private void Button_MouseLeave(object sender, EventArgs e) ((Control)sender).BackColor = Color.MidnightBlue; } - private void ApplyChangesButton_Click(object sender, EventArgs e) + private async void ApplyChangesButton_Click(object sender, EventArgs e) { try { - m_server.ApplyChanges(); + await m_server.ApplyChangesAsync(); } catch (Exception exception) { @@ -337,9 +352,9 @@ private void ApplyChangesButton_Click(object sender, EventArgs e) try { - m_server.Disconnect(); + await m_server.DisconnectAsync(); } - catch (Exception) + catch { // ignore. } diff --git a/Samples/GDS/Client/Controls/RegisterApplicationControl.cs b/Samples/GDS/Client/Controls/RegisterApplicationControl.cs index 4dd24030c..3c187de5f 100644 --- a/Samples/GDS/Client/Controls/RegisterApplicationControl.cs +++ b/Samples/GDS/Client/Controls/RegisterApplicationControl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -34,7 +34,9 @@ using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Threading.Tasks; using System.Windows.Forms; +using System.Xml; using System.Xml.Serialization; using Opc.Ua.Gds.Client.Controls; @@ -93,8 +95,8 @@ public RegisteredApplication RegisteredApplication return m_application; } } - - public void Initialize(GlobalDiscoveryServerClient gds, ServerPushConfigurationClient pushClient, EndpointDescription endpoint, GlobalDiscoveryClientConfiguration configuration) + + public async Task InitializeAsync(GlobalDiscoveryServerClient gds, ServerPushConfigurationClient pushClient, EndpointDescription endpoint, GlobalDiscoveryClientConfiguration configuration) { m_gds = gds; m_pushClient = pushClient; @@ -105,10 +107,10 @@ public void Initialize(GlobalDiscoveryServerClient gds, ServerPushConfigurationC m_externalEditor = configuration.ExternalEditor; } - InitializeEndpoint(endpoint); + await InitializeEndpointAsync(endpoint); } - private void InitializeEndpoint(EndpointDescription endpoint) + private async Task InitializeEndpointAsync(EndpointDescription endpoint) { if (endpoint != null) { @@ -118,7 +120,7 @@ private void InitializeEndpoint(EndpointDescription endpoint) var server = endpoint.Server; ApplicationUriTextBox.Text = server.ApplicationUri; - ReadRegistration(true); + await ReadRegistrationAsync(true); ApplicationNameTextBox.Text = (server.ApplicationName != null) ? server.ApplicationName.Text : ""; ProductUriTextBox.Text = server.ProductUri; @@ -471,7 +473,7 @@ private void SetRegistrationTypeNoTrigger(RegistrationType registrationType) } } - private void InitializePullConfiguration(string configurationFilePath) + private async void InitializePullConfiguration(string configurationFilePath) { string path = Utils.GetAbsoluteFilePath(configurationFilePath, true, true, false); @@ -484,7 +486,8 @@ private void InitializePullConfiguration(string configurationFilePath) using (FileStream reader = File.Open(path, FileMode.Open, FileAccess.Read)) { XmlSerializer serializer = new XmlSerializer(typeof(RegisteredApplication)); - application = serializer.Deserialize(reader) as RegisteredApplication; + using XmlReader xml = XmlReader.Create(reader, new XmlReaderSettings() { XmlResolver = null }); + application = serializer.Deserialize(xml) as RegisteredApplication; } if (application != null) @@ -492,7 +495,7 @@ private void InitializePullConfiguration(string configurationFilePath) SetRegistrationTypeNoTrigger(application.RegistrationType); ApplicationUriTextBox.Text = ReplaceLocalhost(application.ApplicationUri); - ReadRegistration(true); + await ReadRegistrationAsync(true); ApplicationNameTextBox.Text = application.ApplicationName; ProductUriTextBox.Text = application.ProductUri; @@ -562,18 +565,19 @@ private void InitializePullConfiguration(string configurationFilePath) #endif if (application.Domains != null) { - DomainsTextBox.Text = ReplaceLocalhost(application.Domains); + DomainsTextBox.Text = ReplaceLocalhost(application.Domains); } return; } } - catch (Exception) + catch { // ignore. } - try { + try + { var configuration = new Opc.Ua.Security.SecurityConfigurationManager().ReadConfiguration(path); if (configuration.ApplicationType == Security.ApplicationType.Client_1) @@ -586,11 +590,11 @@ private void InitializePullConfiguration(string configurationFilePath) } ApplicationUriTextBox.Text = ReplaceLocalhost(configuration.ApplicationUri); - ReadRegistration(true); + await ReadRegistrationAsync(true); ApplicationNameTextBox.Text = configuration.ApplicationName; ProductUriTextBox.Text = configuration.ProductName; - + if (configuration.ApplicationType != Security.ApplicationType.Client_1) { SetDiscoveryUrls(configuration.BaseAddresses); @@ -613,7 +617,7 @@ private void InitializePullConfiguration(string configurationFilePath) IssuerListStorePathTextBox.Text = configuration.IssuerCertificateStore.StorePath; } } - catch (Exception) + catch { // ignore. } @@ -647,8 +651,7 @@ private void ConfigurationFileButton_Click(object sender, EventArgs e) directory = new FileInfo(configurationFile).Directory; } - OpenFileDialog dialog = new OpenFileDialog - { + OpenFileDialog dialog = new OpenFileDialog { CheckFileExists = true, CheckPathExists = true, DefaultExt = ".xml", @@ -747,8 +750,7 @@ private void CertificateStorePathButton_Click(object sender, EventArgs e) directory = new DirectoryInfo(storePath); } - FolderBrowserDialog dialog = new FolderBrowserDialog - { + FolderBrowserDialog dialog = new FolderBrowserDialog { RootFolder = Environment.SpecialFolder.MyComputer, SelectedPath = directory.FullName, ShowNewFolderButton = true, @@ -857,8 +859,7 @@ private void CertificatePublicKeyPathButton_Click(object sender, EventArgs e) } } - OpenFileDialog dialog = new OpenFileDialog - { + OpenFileDialog dialog = new OpenFileDialog { CheckFileExists = true, CheckPathExists = true, DefaultExt = ".der", @@ -878,7 +879,7 @@ private void CertificatePublicKeyPathButton_Click(object sender, EventArgs e) m_lastDirPath = new FileInfo(dialog.FileName).Directory.FullName; CertificatePublicKeyPathTextBox.Text = AddSpecialFolders(dialog.FileName); - + X509Certificate2 certificate = new X509Certificate2(RemoveSpecialFolders(CertificatePublicKeyPathTextBox.Text)); try @@ -936,8 +937,7 @@ private void CertificatePrivateKeyPathButton_Click(object sender, EventArgs e) } } - OpenFileDialog dialog = new OpenFileDialog - { + OpenFileDialog dialog = new OpenFileDialog { CheckFileExists = true, CheckPathExists = true, DefaultExt = ".pfx", @@ -984,8 +984,7 @@ private void HttpsCertificatePublicKeyPathButton_Click(object sender, EventArgs } } - OpenFileDialog dialog = new OpenFileDialog - { + OpenFileDialog dialog = new OpenFileDialog { CheckFileExists = true, CheckPathExists = true, DefaultExt = ".der", @@ -1054,8 +1053,7 @@ private void HttpsCertificatePrivateKeyPathButton_Click(object sender, EventArgs } } - OpenFileDialog dialog = new OpenFileDialog - { + OpenFileDialog dialog = new OpenFileDialog { CheckFileExists = true, CheckPathExists = true, DefaultExt = ".pfx", @@ -1101,8 +1099,7 @@ private void TrustListStorePathButton_Click(object sender, EventArgs e) } - FolderBrowserDialog dialog = new FolderBrowserDialog - { + FolderBrowserDialog dialog = new FolderBrowserDialog { RootFolder = Environment.SpecialFolder.MyComputer, SelectedPath = directory.FullName, ShowNewFolderButton = true, @@ -1146,8 +1143,7 @@ private void IssuerListStorePathButton_Click(object sender, EventArgs e) directory = new DirectoryInfo(storePath); } - FolderBrowserDialog dialog = new FolderBrowserDialog - { + FolderBrowserDialog dialog = new FolderBrowserDialog { RootFolder = Environment.SpecialFolder.MyComputer, SelectedPath = directory.FullName, ShowNewFolderButton = true, @@ -1191,8 +1187,7 @@ private void HttpsTrustListStorePathButton_Click(object sender, EventArgs e) directory = new DirectoryInfo(storePath); } - FolderBrowserDialog dialog = new FolderBrowserDialog - { + FolderBrowserDialog dialog = new FolderBrowserDialog { RootFolder = Environment.SpecialFolder.MyComputer, SelectedPath = directory.FullName, ShowNewFolderButton = true, @@ -1236,8 +1231,7 @@ private void HttpsIssuerListStorePathButton_Click(object sender, EventArgs e) directory = new DirectoryInfo(storePath); } - FolderBrowserDialog dialog = new FolderBrowserDialog - { + FolderBrowserDialog dialog = new FolderBrowserDialog { RootFolder = Environment.SpecialFolder.MyComputer, SelectedPath = directory.FullName, ShowNewFolderButton = true, @@ -1268,10 +1262,11 @@ private void HttpsIssuerListStorePathButton_Click(object sender, EventArgs e) } } - private void RegisterApplicationButton_Click(object sender, EventArgs e) + private async void RegisterApplicationButton_Click(object sender, EventArgs e) { try - { string applicationName = ApplicationNameTextBox.Text.Trim(); + { + string applicationName = ApplicationNameTextBox.Text.Trim(); if (String.IsNullOrEmpty(applicationName)) { @@ -1338,7 +1333,7 @@ private void RegisterApplicationButton_Click(object sender, EventArgs e) ApplicationRecordDataType recordToReplace = ApplicationIdTextBox.Tag as ApplicationRecordDataType; - var records = m_gds.FindApplication(applicationUri); + var records = await m_gds.FindApplicationAsync(applicationUri); if (records != null) { @@ -1368,13 +1363,13 @@ private void RegisterApplicationButton_Click(object sender, EventArgs e) } recordToReplace.ApplicationUri = applicationUri; - recordToReplace.ApplicationType = (RegistrationTypeComboBox.SelectedIndex != ClientPullManagement)?ApplicationType.Server:ApplicationType.Client; + recordToReplace.ApplicationType = (RegistrationTypeComboBox.SelectedIndex != ClientPullManagement) ? ApplicationType.Server : ApplicationType.Client; recordToReplace.ApplicationNames = new LocalizedText[] { applicationName }; recordToReplace.ProductUri = productUri; recordToReplace.DiscoveryUrls = urls; - recordToReplace.ServerCapabilities = (capabilities != null)?new StringCollection(capabilities):new StringCollection(); + recordToReplace.ServerCapabilities = (capabilities != null) ? new StringCollection(capabilities) : new StringCollection(); - var applicationId = m_gds.RegisterApplication(recordToReplace); + var applicationId = await m_gds.RegisterApplicationAsync(recordToReplace); recordToReplace.ApplicationId = applicationId; @@ -1415,7 +1410,7 @@ private void RegisterApplicationButton_Click(object sender, EventArgs e) } } - private void ReadRegistration(bool silent) + private async Task ReadRegistrationAsync(bool silent) { string applicationUri = ApplicationUriTextBox.Text.Trim(); @@ -1445,7 +1440,7 @@ private void ReadRegistration(bool silent) try { - var records = m_gds.FindApplication(applicationUri); + var records = await m_gds.FindApplicationAsync(applicationUri); if (records != null) { @@ -1524,13 +1519,13 @@ private void ApplyChangesButton_Click(object sender, EventArgs e) } } - private void UnregisterApplicationButton_Click(object sender, EventArgs e) + private async void UnregisterApplicationButton_Click(object sender, EventArgs e) { try { if (ApplicationIdTextBox.Tag is ApplicationRecordDataType record) { - m_gds.UnregisterApplication(record.ApplicationId); + await m_gds.UnregisterApplicationAsync(record.ApplicationId); ApplicationIdTextBox.Text = null; ApplicationIdTextBox.Tag = null; @@ -1580,17 +1575,17 @@ private void RegistrationTypeComboBox_SelectedIndexChanged(object sender, EventA IssuerListStorePathTextBox.Visible = RegistrationTypeComboBox.SelectedIndex != ServerPushManagement; IssuerListStorePathButton.Visible = RegistrationTypeComboBox.SelectedIndex != ServerPushManagement; #if NO_HTTPS - HttpsCertificatePublicKeyPathLabel.Visible = - HttpsCertificatePublicKeyPathTextBox.Visible = - HttpsCertificatePublicKeyPathButton.Visible = - HttpsCertificatePrivateKeyPathLabel.Visible = - HttpsCertificatePrivateKeyPathTextBox.Visible = - HttpsCertificatePrivateKeyPathButton.Visible = - HttpsTrustListStorePathLabel.Visible = - HttpsTrustListStorePathTextBox.Visible = - HttpsTrustListStorePathButton.Visible = - HttpsIssuerListStorePathLabel.Visible = - HttpsIssuerListStorePathTextBox.Visible = + HttpsCertificatePublicKeyPathLabel.Visible = + HttpsCertificatePublicKeyPathTextBox.Visible = + HttpsCertificatePublicKeyPathButton.Visible = + HttpsCertificatePrivateKeyPathLabel.Visible = + HttpsCertificatePrivateKeyPathTextBox.Visible = + HttpsCertificatePrivateKeyPathButton.Visible = + HttpsTrustListStorePathLabel.Visible = + HttpsTrustListStorePathTextBox.Visible = + HttpsTrustListStorePathButton.Visible = + HttpsIssuerListStorePathLabel.Visible = + HttpsIssuerListStorePathTextBox.Visible = HttpsIssuerListStorePathButton.Visible = false; #else HttpsCertificatePublicKeyPathLabel.Visible = RegistrationTypeComboBox.SelectedIndex != ClientPullManagement; @@ -1656,8 +1651,7 @@ private void SaveButton_Click(object sender, EventArgs e) name = buffer.ToString(); } - SaveFileDialog dialog = new SaveFileDialog - { + SaveFileDialog dialog = new SaveFileDialog { OverwritePrompt = true, CheckFileExists = false, CheckPathExists = true, @@ -1745,8 +1739,7 @@ private void LoadButton_Click(object sender, EventArgs e) DirectoryInfo directory = new DirectoryInfo(path); - OpenFileDialog dialog = new OpenFileDialog - { + OpenFileDialog dialog = new OpenFileDialog { CheckFileExists = true, CheckPathExists = true, DefaultExt = ".xml", @@ -1764,7 +1757,7 @@ private void LoadButton_Click(object sender, EventArgs e) } m_lastDirPath = new FileInfo(dialog.FileName).Directory.FullName; - + if (dialog.FileName.EndsWith(".der", StringComparison.OrdinalIgnoreCase)) { ConfigurationFileTextBox.Text = null; @@ -1778,7 +1771,7 @@ private void LoadButton_Click(object sender, EventArgs e) ControlToData(); RaiseRegisteredApplicationChangedEvent(m_application); - + } catch (Exception ex) { @@ -1791,7 +1784,7 @@ private void OpenConfigurationButton_Click(object sender, EventArgs e) try { var pathToFile = Utils.GetAbsoluteFilePath(ConfigurationFileTextBox.Text.Trim(), true, true, false); - System.Diagnostics.Process.Start((m_externalEditor)??@"devenv.exe", "\"" + pathToFile + "\""); + System.Diagnostics.Process.Start((m_externalEditor) ?? @"devenv.exe", "\"" + pathToFile + "\""); } catch (Exception ex) { @@ -1852,13 +1845,20 @@ private void ClearButton_Click(object sender, EventArgs e) } } - private void PickServerButton_Click(object sender, EventArgs e) + private async void PickServerButton_Click(object sender, EventArgs e) { - string uri = new SelectPushServerDialog().ShowDialog(null, m_pushClient, m_gds.GetDefaultServerUrls(null)); - if (uri != null && m_pushClient.IsConnected) + try { - EndpointDescription endpoint = m_pushClient.Endpoint.Description; - InitializeEndpoint(endpoint); + string uri = new SelectPushServerDialog().ShowDialog(null, m_pushClient, await m_gds.GetDefaultServerUrlsAsync(null)); + if (uri != null && m_pushClient.IsConnected) + { + EndpointDescription endpoint = m_pushClient.Endpoint.Description; + await InitializeEndpointAsync(endpoint); + } + } + catch (Exception ex) + { + Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); } } } diff --git a/Samples/GDS/Client/GlobalDiscoveryClient.csproj b/Samples/GDS/Client/GlobalDiscoveryClient.csproj index 080cd8929..c3decd33d 100644 --- a/Samples/GDS/Client/GlobalDiscoveryClient.csproj +++ b/Samples/GDS/Client/GlobalDiscoveryClient.csproj @@ -27,6 +27,7 @@ 4 false false + AllRules.ruleset AnyCPU @@ -37,6 +38,7 @@ prompt 4 false + AllRules.ruleset false @@ -139,10 +141,10 @@ - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview diff --git a/Samples/GDS/Client/MainForm.cs b/Samples/GDS/Client/MainForm.cs index 7e732fa56..1fbfd82f5 100644 --- a/Samples/GDS/Client/MainForm.cs +++ b/Samples/GDS/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,13 +29,15 @@ using System; using System.Drawing; +using System.Reflection; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua.Client; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; using Opc.Ua.Gds; using Opc.Ua.Gds.Client.Controls; -using System.Threading.Tasks; +using static System.Net.Mime.MediaTypeNames; namespace Opc.Ua.Gds.Client { @@ -70,9 +72,9 @@ public MainForm(ApplicationInstance application) m_server.AdminCredentialsRequired += Server_AdminCredentialsRequired; m_server.KeepAlive += Server_KeepAlive; m_server.ServerStatusChanged += Server_StatusNotification; - m_server.ConnectionStatusChanged += Server_ConnectionStatusChanged; + m_server.ConnectionStatusChanged += Server_ConnectionStatusChangedAsync; - RegistrationPanel.Initialize(m_gds, m_server, null, m_configuration); + RegistrationPanel.InitializeAsync(m_gds, m_server, null, m_configuration).GetAwaiter().GetResult(); m_application.ApplicationConfiguration.CertificateValidator.CertificateValidation += CertificateValidator_CertificateValidation; UpdateStatus(true, DateTime.MinValue, "---"); @@ -114,25 +116,32 @@ private enum Panel Discovery } - private void Server_ConnectionStatusChanged(object sender, EventArgs e) + private async void Server_ConnectionStatusChangedAsync(object sender, EventArgs e) { - if (InvokeRequired) - { - BeginInvoke(new EventHandler(Server_ConnectionStatusChanged), sender, e); - return; - } - - if (Object.ReferenceEquals(sender, m_server)) + try { - if (m_server.IsConnected) + if (InvokeRequired) { - ServerStatusPanel.Initialize(m_server); + BeginInvoke(new EventHandler(Server_ConnectionStatusChangedAsync), sender, e); + return; } - else + + if (Object.ReferenceEquals(sender, m_server)) { - ServerStatusPanel.Initialize(null); + if (m_server.IsConnected) + { + await ServerStatusPanel.InitializeAsync(m_server); + } + else + { + await ServerStatusPanel.InitializeAsync(null); + } } } + catch (Exception exception) + { + GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + } } private void ShowPanel(Panel panel) @@ -217,7 +226,7 @@ private void SetServer(EndpointDescription endpoint) ServerStatusButton.Enabled = endpoint != null; } - private void SelectServerButton_Click(object sender, EventArgs e) + private async void SelectServerButton_Click(object sender, EventArgs e) { try { @@ -226,7 +235,7 @@ private void SelectServerButton_Click(object sender, EventArgs e) if (endpoint != null) { SetServer(endpoint); - RegistrationPanel.Initialize(m_gds, m_server, endpoint, m_configuration); + await RegistrationPanel.InitializeAsync(m_gds, m_server, endpoint, m_configuration); SelectGdsButton.Visible = true; return; } @@ -248,10 +257,10 @@ private async void ConnectButton_ClickAsync(object sender, EventArgs e) return; } - await m_server.Connect(endpoint.Description.EndpointUrl); + await m_server.ConnectAsync(endpoint.Description.EndpointUrl); - ServerStatusPanel.Initialize(m_server); - await CertificatePanel.Initialize(m_configuration, m_gds, m_server, m_registeredApplication, false); + await ServerStatusPanel.InitializeAsync(m_server); + await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, m_registeredApplication, false); } catch (Exception exception) { @@ -429,15 +438,15 @@ private void UpdateStatus(bool error, DateTime time, string status, params objec ServerStatusTime.ForeColor = (error) ? Color.Red : Color.Empty; } - private void DisconnectButton_Click(object sender, EventArgs e) + private async void DisconnectButton_Click(object sender, EventArgs e) { try { if (m_server.IsConnected) { - m_server.Disconnect(); + m_server.DisconnectAsync().GetAwaiter().GetResult(); UpdateStatus(true, DateTime.UtcNow, "Disconnected {0}", m_server.Endpoint); - ServerStatusPanel.Initialize(null); + await ServerStatusPanel.InitializeAsync(null); } } catch (Exception exception) @@ -452,7 +461,7 @@ private void RegistrationButton_Click(object sender, EventArgs e) { if (!m_gdsConfigured) { - string uri = new SelectGdsDialog().ShowDialog(null, m_gds, m_gds.GetDefaultGdsUrls(m_lds)); + string uri = new SelectGdsDialog().ShowDialog(null, m_gds, m_gds.GetDefaultGdsUrlsAsync(m_lds).GetAwaiter().GetResult()); if (uri != null) { m_configuration.GlobalDiscoveryServerUrl = m_gds.EndpointUrl; @@ -485,7 +494,7 @@ private async void CertificateButton_ClickAsync(object sender, EventArgs e) { try { - await CertificatePanel.Initialize(m_configuration, m_gds, m_server, m_registeredApplication, false); + await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, m_registeredApplication, false); ShowPanel(Panel.Certificate); } catch (Exception ex) @@ -498,7 +507,7 @@ private async void HttpsCertificateButton_ClickAsync(object sender, EventArgs e) { try { - await CertificatePanel.Initialize(m_configuration, m_gds, m_server, m_registeredApplication, true); + await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, m_registeredApplication, true); ShowPanel(Panel.HttpsCertificate); } catch (Exception ex) @@ -507,11 +516,11 @@ private async void HttpsCertificateButton_ClickAsync(object sender, EventArgs e) } } - private void TrustListButton_Click(object sender, EventArgs e) + private async void TrustListButton_Click(object sender, EventArgs e) { try { - TrustListPanel.Initialize(m_gds, m_server, m_registeredApplication, false); + await TrustListPanel.Initialize(m_gds, m_server, m_registeredApplication, false); ShowPanel(Panel.TrustList); } catch (Exception ex) @@ -520,11 +529,11 @@ private void TrustListButton_Click(object sender, EventArgs e) } } - private void HttpsTrustListButton_Click(object sender, EventArgs e) + private async void HttpsTrustListButton_Click(object sender, EventArgs e) { try { - TrustListPanel.Initialize(m_gds, m_server, m_registeredApplication, true); + await TrustListPanel.Initialize(m_gds, m_server, m_registeredApplication, true); ShowPanel(Panel.HttpsTrustList); } catch (Exception ex) @@ -590,8 +599,8 @@ private async void RegistrationPanel_RegisteredApplicationChangedAsync(object se HttpsCertificateButton.Visible = (e.Application != null && !String.IsNullOrEmpty(e.Application.GetHttpsDomainName())); HttpsTrustListButton.Visible = (e.Application != null && !String.IsNullOrEmpty(e.Application.HttpsTrustListStorePath)); #endif - await CertificatePanel.Initialize(m_configuration, m_gds, m_server, e.Application, false); - TrustListPanel.Initialize(m_gds, m_server, e.Application, false); + await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, e.Application, false); + await TrustListPanel.Initialize(m_gds, m_server, e.Application, false); UpdateMainFormHeader(); } catch (Exception ex) @@ -608,11 +617,11 @@ private void ConfigurationButton_Click(object sender, EventArgs e) private void SelectGdsButton_Click(object sender, EventArgs e) { m_gds.AdminCredentials = null; - m_gds.Disconnect(); + m_gds.DisconnectAsync().GetAwaiter().GetResult(); m_gdsConfigured = false; UpdateGdsStatus(true, DateTime.UtcNow, "Disconnected"); - string uri = new SelectGdsDialog().ShowDialog(null, m_gds, m_gds.GetDefaultGdsUrls(m_lds)); + string uri = new SelectGdsDialog().ShowDialog(null, m_gds, m_gds.GetDefaultGdsUrlsAsync(m_lds).GetAwaiter().GetResult()); if (uri != null) { m_configuration.GlobalDiscoveryServerUrl = m_gds.EndpointUrl; diff --git a/Samples/GDS/Client/Program.cs b/Samples/GDS/Client/Program.cs index deef60908..a339b70ec 100644 --- a/Samples/GDS/Client/Program.cs +++ b/Samples/GDS/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -54,10 +54,10 @@ static void Main() try { // load the application configuration. - ApplicationConfiguration config = application.LoadApplicationConfiguration(false).Result; + ApplicationConfiguration config = application.LoadApplicationConfigurationAsync(false).AsTask().GetAwaiter().GetResult(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().GetAwaiter().GetResult(); // run the application interactively. Application.Run(new MainForm(application)); diff --git a/Samples/GDS/ClientControls/Controls/DiscoveryControl.Designer.cs b/Samples/GDS/ClientControls/Controls/DiscoveryControl.Designer.cs index 4d774fad1..93da51751 100644 --- a/Samples/GDS/ClientControls/Controls/DiscoveryControl.Designer.cs +++ b/Samples/GDS/ClientControls/Controls/DiscoveryControl.Designer.cs @@ -1,4 +1,4 @@ -namespace Opc.Ua.Gds.Client.Controls +namespace Opc.Ua.Gds.Client.Controls { partial class DiscoveryControl { @@ -37,6 +37,10 @@ private void InitializeComponent() this.AddEndpointSeparatorMenuItem = new System.Windows.Forms.ToolStripSeparator(); this.AddEndpointMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MainPanel = new System.Windows.Forms.SplitContainer(); + this.EndpointsGridView = new System.Windows.Forms.DataGridView(); + this.EndpointUrlColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.SecurityModeColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.SecurityProfileColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ServersGridView = new System.Windows.Forms.DataGridView(); this.ServerNameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ServerCapabilitiesColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); @@ -53,19 +57,15 @@ private void InitializeComponent() this.FilterPanel = new System.Windows.Forms.Panel(); this.FilterTextBox = new System.Windows.Forms.TextBox(); this.FilterLabel = new System.Windows.Forms.Label(); - this.EndpointsGridView = new System.Windows.Forms.DataGridView(); - this.EndpointUrlColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.SecurityModeColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.SecurityProfileColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.PopupMenuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.MainPanel)).BeginInit(); this.MainPanel.Panel1.SuspendLayout(); this.MainPanel.Panel2.SuspendLayout(); this.MainPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.EndpointsGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ServersGridView)).BeginInit(); this.ApplicationDescriptionPanel.SuspendLayout(); this.FilterPanel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.EndpointsGridView)).BeginInit(); this.SuspendLayout(); // // DiscoveryTreeView @@ -73,8 +73,9 @@ private void InitializeComponent() this.DiscoveryTreeView.ContextMenuStrip = this.PopupMenuStrip; this.DiscoveryTreeView.Dock = System.Windows.Forms.DockStyle.Fill; this.DiscoveryTreeView.Location = new System.Drawing.Point(0, 0); + this.DiscoveryTreeView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.DiscoveryTreeView.Name = "DiscoveryTreeView"; - this.DiscoveryTreeView.Size = new System.Drawing.Size(296, 584); + this.DiscoveryTreeView.Size = new System.Drawing.Size(444, 898); this.DiscoveryTreeView.TabIndex = 0; this.DiscoveryTreeView.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.DiscoveryTreeView_BeforeExpand); this.DiscoveryTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.DiscoveryTreeView_AfterSelect); @@ -83,6 +84,7 @@ private void InitializeComponent() // // PopupMenuStrip // + this.PopupMenuStrip.ImageScalingSize = new System.Drawing.Size(24, 24); this.PopupMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.RefreshMenuItem, this.RefreshWithParametersMenuItem, @@ -90,39 +92,39 @@ private void InitializeComponent() this.AddEndpointSeparatorMenuItem, this.AddEndpointMenuItem}); this.PopupMenuStrip.Name = "PopupMenuStrip"; - this.PopupMenuStrip.Size = new System.Drawing.Size(211, 98); + this.PopupMenuStrip.Size = new System.Drawing.Size(285, 138); this.PopupMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.PopupMenuStrip_Opening); // // RefreshMenuItem // this.RefreshMenuItem.Name = "RefreshMenuItem"; - this.RefreshMenuItem.Size = new System.Drawing.Size(210, 22); + this.RefreshMenuItem.Size = new System.Drawing.Size(284, 32); this.RefreshMenuItem.Text = "Refresh"; this.RefreshMenuItem.Click += new System.EventHandler(this.RefreshMenuItem_Click); // // RefreshWithParametersMenuItem // this.RefreshWithParametersMenuItem.Name = "RefreshWithParametersMenuItem"; - this.RefreshWithParametersMenuItem.Size = new System.Drawing.Size(210, 22); + this.RefreshWithParametersMenuItem.Size = new System.Drawing.Size(284, 32); this.RefreshWithParametersMenuItem.Text = "Refresh with Parameters..."; this.RefreshWithParametersMenuItem.Click += new System.EventHandler(this.RefreshWithParametersMenuItem_Click); // // DeleteMenuItem // this.DeleteMenuItem.Name = "DeleteMenuItem"; - this.DeleteMenuItem.Size = new System.Drawing.Size(210, 22); + this.DeleteMenuItem.Size = new System.Drawing.Size(284, 32); this.DeleteMenuItem.Text = "Delete..."; this.DeleteMenuItem.Click += new System.EventHandler(this.DeleteMenuItem_Click); // // AddEndpointSeparatorMenuItem // this.AddEndpointSeparatorMenuItem.Name = "AddEndpointSeparatorMenuItem"; - this.AddEndpointSeparatorMenuItem.Size = new System.Drawing.Size(207, 6); + this.AddEndpointSeparatorMenuItem.Size = new System.Drawing.Size(281, 6); // // AddEndpointMenuItem // this.AddEndpointMenuItem.Name = "AddEndpointMenuItem"; - this.AddEndpointMenuItem.Size = new System.Drawing.Size(210, 22); + this.AddEndpointMenuItem.Size = new System.Drawing.Size(284, 32); this.AddEndpointMenuItem.Text = "Add Endpoint..."; this.AddEndpointMenuItem.Click += new System.EventHandler(this.DiscoveryTreeView_DoubleClick); // @@ -130,6 +132,7 @@ private void InitializeComponent() // this.MainPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.MainPanel.Location = new System.Drawing.Point(0, 0); + this.MainPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.MainPanel.Name = "MainPanel"; // // MainPanel.Panel1 @@ -142,29 +145,89 @@ private void InitializeComponent() this.MainPanel.Panel2.Controls.Add(this.ServersGridView); this.MainPanel.Panel2.Controls.Add(this.ApplicationDescriptionPanel); this.MainPanel.Panel2.Controls.Add(this.FilterPanel); - this.MainPanel.Size = new System.Drawing.Size(888, 584); - this.MainPanel.SplitterDistance = 296; + this.MainPanel.Size = new System.Drawing.Size(1332, 898); + this.MainPanel.SplitterDistance = 444; + this.MainPanel.SplitterWidth = 6; this.MainPanel.TabIndex = 3; // + // EndpointsGridView + // + this.EndpointsGridView.AllowUserToAddRows = false; + this.EndpointsGridView.AllowUserToDeleteRows = false; + this.EndpointsGridView.AllowUserToResizeRows = false; + this.EndpointsGridView.BackgroundColor = System.Drawing.SystemColors.Window; + this.EndpointsGridView.ColumnHeadersHeight = 34; + this.EndpointsGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; + this.EndpointsGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.EndpointUrlColumn3, + this.SecurityModeColumn, + this.SecurityProfileColumn}); + this.EndpointsGridView.Dock = System.Windows.Forms.DockStyle.Fill; + this.EndpointsGridView.Location = new System.Drawing.Point(0, 212); + this.EndpointsGridView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.EndpointsGridView.MultiSelect = false; + this.EndpointsGridView.Name = "EndpointsGridView"; + this.EndpointsGridView.ReadOnly = true; + this.EndpointsGridView.RowHeadersVisible = false; + this.EndpointsGridView.RowHeadersWidth = 62; + this.EndpointsGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; + this.EndpointsGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.EndpointsGridView.Size = new System.Drawing.Size(882, 686); + this.EndpointsGridView.TabIndex = 2; + this.EndpointsGridView.VisibleChanged += new System.EventHandler(this.EndpointsGridView_VisibleChanged); + this.EndpointsGridView.DoubleClick += new System.EventHandler(this.EndpointsGridView_DoubleClick); + // + // EndpointUrlColumn3 + // + this.EndpointUrlColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; + this.EndpointUrlColumn3.DataPropertyName = "EndpointUrl"; + this.EndpointUrlColumn3.HeaderText = "Endpoint URL"; + this.EndpointUrlColumn3.MinimumWidth = 8; + this.EndpointUrlColumn3.Name = "EndpointUrlColumn3"; + this.EndpointUrlColumn3.ReadOnly = true; + // + // SecurityModeColumn + // + this.SecurityModeColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells; + this.SecurityModeColumn.DataPropertyName = "SecurityMode"; + this.SecurityModeColumn.HeaderText = "Security Mode"; + this.SecurityModeColumn.MinimumWidth = 8; + this.SecurityModeColumn.Name = "SecurityModeColumn"; + this.SecurityModeColumn.ReadOnly = true; + this.SecurityModeColumn.Width = 146; + // + // SecurityProfileColumn + // + this.SecurityProfileColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells; + this.SecurityProfileColumn.DataPropertyName = "SecurityProfile"; + this.SecurityProfileColumn.HeaderText = "Security Profile"; + this.SecurityProfileColumn.MinimumWidth = 8; + this.SecurityProfileColumn.Name = "SecurityProfileColumn"; + this.SecurityProfileColumn.ReadOnly = true; + this.SecurityProfileColumn.Width = 150; + // // ServersGridView // this.ServersGridView.AllowUserToAddRows = false; this.ServersGridView.AllowUserToDeleteRows = false; this.ServersGridView.AllowUserToResizeRows = false; this.ServersGridView.BackgroundColor = System.Drawing.SystemColors.Window; + this.ServersGridView.ColumnHeadersHeight = 34; this.ServersGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.ServersGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ServerNameColumn, this.ServerCapabilitiesColumn, this.EndpointUrlColumn}); this.ServersGridView.Dock = System.Windows.Forms.DockStyle.Fill; - this.ServersGridView.Location = new System.Drawing.Point(0, 138); + this.ServersGridView.Location = new System.Drawing.Point(0, 212); + this.ServersGridView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ServersGridView.Name = "ServersGridView"; this.ServersGridView.ReadOnly = true; this.ServersGridView.RowHeadersVisible = false; + this.ServersGridView.RowHeadersWidth = 62; this.ServersGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; this.ServersGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; - this.ServersGridView.Size = new System.Drawing.Size(588, 446); + this.ServersGridView.Size = new System.Drawing.Size(882, 686); this.ServersGridView.TabIndex = 3; this.ServersGridView.DoubleClick += new System.EventHandler(this.ServersGridView_DoubleClick); // @@ -173,24 +236,27 @@ private void InitializeComponent() this.ServerNameColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells; this.ServerNameColumn.DataPropertyName = "ServerName"; this.ServerNameColumn.HeaderText = "Server Name"; + this.ServerNameColumn.MinimumWidth = 8; this.ServerNameColumn.Name = "ServerNameColumn"; this.ServerNameColumn.ReadOnly = true; - this.ServerNameColumn.Width = 94; + this.ServerNameColumn.Width = 137; // // ServerCapabilitiesColumn // this.ServerCapabilitiesColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells; this.ServerCapabilitiesColumn.DataPropertyName = "ServerCapabilities"; this.ServerCapabilitiesColumn.HeaderText = "Server Capabilities"; + this.ServerCapabilitiesColumn.MinimumWidth = 8; this.ServerCapabilitiesColumn.Name = "ServerCapabilitiesColumn"; this.ServerCapabilitiesColumn.ReadOnly = true; - this.ServerCapabilitiesColumn.Width = 119; + this.ServerCapabilitiesColumn.Width = 176; // // EndpointUrlColumn // this.EndpointUrlColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.EndpointUrlColumn.DataPropertyName = "EndpointUrl"; this.EndpointUrlColumn.HeaderText = "Endpoint URL"; + this.EndpointUrlColumn.MinimumWidth = 8; this.EndpointUrlColumn.Name = "EndpointUrlColumn"; this.EndpointUrlColumn.ReadOnly = true; // @@ -210,14 +276,15 @@ private void InitializeComponent() this.ApplicationDescriptionPanel.Controls.Add(this.ApplicationUriLabel, 0, 1); this.ApplicationDescriptionPanel.Controls.Add(this.ApplicationNameTextBox, 1, 0); this.ApplicationDescriptionPanel.Dock = System.Windows.Forms.DockStyle.Top; - this.ApplicationDescriptionPanel.Location = new System.Drawing.Point(0, 32); + this.ApplicationDescriptionPanel.Location = new System.Drawing.Point(0, 49); + this.ApplicationDescriptionPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ApplicationDescriptionPanel.Name = "ApplicationDescriptionPanel"; this.ApplicationDescriptionPanel.RowCount = 4; - this.ApplicationDescriptionPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 24F)); - this.ApplicationDescriptionPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 24F)); - this.ApplicationDescriptionPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 24F)); - this.ApplicationDescriptionPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 24F)); - this.ApplicationDescriptionPanel.Size = new System.Drawing.Size(588, 106); + this.ApplicationDescriptionPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 37F)); + this.ApplicationDescriptionPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 37F)); + this.ApplicationDescriptionPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 37F)); + this.ApplicationDescriptionPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 37F)); + this.ApplicationDescriptionPanel.Size = new System.Drawing.Size(882, 163); this.ApplicationDescriptionPanel.TabIndex = 1; // // ApplicationNameLabel @@ -225,10 +292,10 @@ private void InitializeComponent() this.ApplicationNameLabel.AllowDrop = true; this.ApplicationNameLabel.AutoSize = true; this.ApplicationNameLabel.Dock = System.Windows.Forms.DockStyle.Fill; - this.ApplicationNameLabel.Location = new System.Drawing.Point(5, 5); - this.ApplicationNameLabel.Margin = new System.Windows.Forms.Padding(3); + this.ApplicationNameLabel.Location = new System.Drawing.Point(6, 7); + this.ApplicationNameLabel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ApplicationNameLabel.Name = "ApplicationNameLabel"; - this.ApplicationNameLabel.Size = new System.Drawing.Size(90, 18); + this.ApplicationNameLabel.Size = new System.Drawing.Size(133, 27); this.ApplicationNameLabel.TabIndex = 0; this.ApplicationNameLabel.Text = "Application Name"; this.ApplicationNameLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -238,10 +305,10 @@ private void InitializeComponent() this.ProductUriTextBox.AllowDrop = true; this.ProductUriTextBox.AutoSize = true; this.ProductUriTextBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.ProductUriTextBox.Location = new System.Drawing.Point(103, 83); - this.ProductUriTextBox.Margin = new System.Windows.Forms.Padding(3); + this.ProductUriTextBox.Location = new System.Drawing.Point(149, 124); + this.ProductUriTextBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ProductUriTextBox.Name = "ProductUriTextBox"; - this.ProductUriTextBox.Size = new System.Drawing.Size(480, 18); + this.ProductUriTextBox.Size = new System.Drawing.Size(727, 32); this.ProductUriTextBox.TabIndex = 7; this.ProductUriTextBox.Text = "---"; this.ProductUriTextBox.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -251,10 +318,10 @@ private void InitializeComponent() this.ProductUriLabel.AllowDrop = true; this.ProductUriLabel.AutoSize = true; this.ProductUriLabel.Dock = System.Windows.Forms.DockStyle.Fill; - this.ProductUriLabel.Location = new System.Drawing.Point(5, 83); - this.ProductUriLabel.Margin = new System.Windows.Forms.Padding(3); + this.ProductUriLabel.Location = new System.Drawing.Point(6, 124); + this.ProductUriLabel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ProductUriLabel.Name = "ProductUriLabel"; - this.ProductUriLabel.Size = new System.Drawing.Size(90, 18); + this.ProductUriLabel.Size = new System.Drawing.Size(133, 32); this.ProductUriLabel.TabIndex = 6; this.ProductUriLabel.Text = "Product URI"; this.ProductUriLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -264,10 +331,10 @@ private void InitializeComponent() this.ApplicationTypeTextBox.AllowDrop = true; this.ApplicationTypeTextBox.AutoSize = true; this.ApplicationTypeTextBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.ApplicationTypeTextBox.Location = new System.Drawing.Point(103, 57); - this.ApplicationTypeTextBox.Margin = new System.Windows.Forms.Padding(3); + this.ApplicationTypeTextBox.Location = new System.Drawing.Point(149, 85); + this.ApplicationTypeTextBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ApplicationTypeTextBox.Name = "ApplicationTypeTextBox"; - this.ApplicationTypeTextBox.Size = new System.Drawing.Size(480, 18); + this.ApplicationTypeTextBox.Size = new System.Drawing.Size(727, 27); this.ApplicationTypeTextBox.TabIndex = 5; this.ApplicationTypeTextBox.Text = "---"; this.ApplicationTypeTextBox.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -277,10 +344,10 @@ private void InitializeComponent() this.ApplicationTypeLabel.AllowDrop = true; this.ApplicationTypeLabel.AutoSize = true; this.ApplicationTypeLabel.Dock = System.Windows.Forms.DockStyle.Fill; - this.ApplicationTypeLabel.Location = new System.Drawing.Point(5, 57); - this.ApplicationTypeLabel.Margin = new System.Windows.Forms.Padding(3); + this.ApplicationTypeLabel.Location = new System.Drawing.Point(6, 85); + this.ApplicationTypeLabel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ApplicationTypeLabel.Name = "ApplicationTypeLabel"; - this.ApplicationTypeLabel.Size = new System.Drawing.Size(90, 18); + this.ApplicationTypeLabel.Size = new System.Drawing.Size(133, 27); this.ApplicationTypeLabel.TabIndex = 4; this.ApplicationTypeLabel.Text = "Application Type"; this.ApplicationTypeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -290,10 +357,10 @@ private void InitializeComponent() this.ApplicationUriTextBox.AllowDrop = true; this.ApplicationUriTextBox.AutoSize = true; this.ApplicationUriTextBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.ApplicationUriTextBox.Location = new System.Drawing.Point(103, 31); - this.ApplicationUriTextBox.Margin = new System.Windows.Forms.Padding(3); + this.ApplicationUriTextBox.Location = new System.Drawing.Point(149, 46); + this.ApplicationUriTextBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ApplicationUriTextBox.Name = "ApplicationUriTextBox"; - this.ApplicationUriTextBox.Size = new System.Drawing.Size(480, 18); + this.ApplicationUriTextBox.Size = new System.Drawing.Size(727, 27); this.ApplicationUriTextBox.TabIndex = 3; this.ApplicationUriTextBox.Text = "---"; this.ApplicationUriTextBox.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -303,10 +370,10 @@ private void InitializeComponent() this.ApplicationUriLabel.AllowDrop = true; this.ApplicationUriLabel.AutoSize = true; this.ApplicationUriLabel.Dock = System.Windows.Forms.DockStyle.Fill; - this.ApplicationUriLabel.Location = new System.Drawing.Point(5, 31); - this.ApplicationUriLabel.Margin = new System.Windows.Forms.Padding(3); + this.ApplicationUriLabel.Location = new System.Drawing.Point(6, 46); + this.ApplicationUriLabel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ApplicationUriLabel.Name = "ApplicationUriLabel"; - this.ApplicationUriLabel.Size = new System.Drawing.Size(90, 18); + this.ApplicationUriLabel.Size = new System.Drawing.Size(133, 27); this.ApplicationUriLabel.TabIndex = 2; this.ApplicationUriLabel.Text = "Application URI"; this.ApplicationUriLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -316,10 +383,10 @@ private void InitializeComponent() this.ApplicationNameTextBox.AllowDrop = true; this.ApplicationNameTextBox.AutoSize = true; this.ApplicationNameTextBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.ApplicationNameTextBox.Location = new System.Drawing.Point(103, 5); - this.ApplicationNameTextBox.Margin = new System.Windows.Forms.Padding(3); + this.ApplicationNameTextBox.Location = new System.Drawing.Point(149, 7); + this.ApplicationNameTextBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.ApplicationNameTextBox.Name = "ApplicationNameTextBox"; - this.ApplicationNameTextBox.Size = new System.Drawing.Size(480, 18); + this.ApplicationNameTextBox.Size = new System.Drawing.Size(727, 27); this.ApplicationNameTextBox.TabIndex = 1; this.ApplicationNameTextBox.Text = "---"; this.ApplicationNameTextBox.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -333,17 +400,17 @@ private void InitializeComponent() this.FilterPanel.Location = new System.Drawing.Point(0, 0); this.FilterPanel.Margin = new System.Windows.Forms.Padding(0); this.FilterPanel.Name = "FilterPanel"; - this.FilterPanel.Padding = new System.Windows.Forms.Padding(2, 6, 6, 6); - this.FilterPanel.Size = new System.Drawing.Size(588, 32); + this.FilterPanel.Padding = new System.Windows.Forms.Padding(3, 9, 9, 9); + this.FilterPanel.Size = new System.Drawing.Size(882, 49); this.FilterPanel.TabIndex = 0; // // FilterTextBox // this.FilterTextBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.FilterTextBox.Location = new System.Drawing.Point(77, 6); - this.FilterTextBox.Margin = new System.Windows.Forms.Padding(0, 2, 0, 2); + this.FilterTextBox.Location = new System.Drawing.Point(115, 9); + this.FilterTextBox.Margin = new System.Windows.Forms.Padding(0, 3, 0, 3); this.FilterTextBox.Name = "FilterTextBox"; - this.FilterTextBox.Size = new System.Drawing.Size(505, 20); + this.FilterTextBox.Size = new System.Drawing.Size(758, 26); this.FilterTextBox.TabIndex = 1; this.FilterTextBox.TextChanged += new System.EventHandler(this.FilterTextBox_TextChanged); // @@ -353,81 +420,33 @@ private void InitializeComponent() this.FilterLabel.Dock = System.Windows.Forms.DockStyle.Left; this.FilterLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FilterLabel.ForeColor = System.Drawing.Color.White; - this.FilterLabel.Location = new System.Drawing.Point(2, 6); - this.FilterLabel.Margin = new System.Windows.Forms.Padding(3); + this.FilterLabel.Location = new System.Drawing.Point(3, 9); + this.FilterLabel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.FilterLabel.Name = "FilterLabel"; - this.FilterLabel.Size = new System.Drawing.Size(75, 20); + this.FilterLabel.Size = new System.Drawing.Size(112, 31); this.FilterLabel.TabIndex = 0; this.FilterLabel.Text = "Text Filter"; this.FilterLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // - // EndpointsGridView - // - this.EndpointsGridView.AllowUserToAddRows = false; - this.EndpointsGridView.AllowUserToDeleteRows = false; - this.EndpointsGridView.AllowUserToResizeRows = false; - this.EndpointsGridView.BackgroundColor = System.Drawing.SystemColors.Window; - this.EndpointsGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; - this.EndpointsGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { - this.EndpointUrlColumn3, - this.SecurityModeColumn, - this.SecurityProfileColumn}); - this.EndpointsGridView.Dock = System.Windows.Forms.DockStyle.Fill; - this.EndpointsGridView.Location = new System.Drawing.Point(0, 138); - this.EndpointsGridView.MultiSelect = false; - this.EndpointsGridView.Name = "EndpointsGridView"; - this.EndpointsGridView.ReadOnly = true; - this.EndpointsGridView.RowHeadersVisible = false; - this.EndpointsGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; - this.EndpointsGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; - this.EndpointsGridView.Size = new System.Drawing.Size(588, 446); - this.EndpointsGridView.TabIndex = 2; - this.EndpointsGridView.VisibleChanged += new System.EventHandler(this.EndpointsGridView_VisibleChanged); - this.EndpointsGridView.DoubleClick += new System.EventHandler(this.EndpointsGridView_DoubleClick); - // - // EndpointUrlColumn3 - // - this.EndpointUrlColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; - this.EndpointUrlColumn3.DataPropertyName = "EndpointUrl"; - this.EndpointUrlColumn3.HeaderText = "Endpoint URL"; - this.EndpointUrlColumn3.Name = "EndpointUrlColumn3"; - this.EndpointUrlColumn3.ReadOnly = true; - // - // SecurityModeColumn - // - this.SecurityModeColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells; - this.SecurityModeColumn.DataPropertyName = "SecurityMode"; - this.SecurityModeColumn.HeaderText = "Security Mode"; - this.SecurityModeColumn.Name = "SecurityModeColumn"; - this.SecurityModeColumn.ReadOnly = true; - // - // SecurityProfileColumn - // - this.SecurityProfileColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells; - this.SecurityProfileColumn.DataPropertyName = "SecurityProfile"; - this.SecurityProfileColumn.HeaderText = "Security Profile"; - this.SecurityProfileColumn.Name = "SecurityProfileColumn"; - this.SecurityProfileColumn.ReadOnly = true; - this.SecurityProfileColumn.Width = 102; - // // DiscoveryControl // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.MainPanel); + this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.Name = "DiscoveryControl"; - this.Size = new System.Drawing.Size(888, 584); + this.Size = new System.Drawing.Size(1332, 898); this.PopupMenuStrip.ResumeLayout(false); this.MainPanel.Panel1.ResumeLayout(false); this.MainPanel.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.MainPanel)).EndInit(); this.MainPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.EndpointsGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ServersGridView)).EndInit(); this.ApplicationDescriptionPanel.ResumeLayout(false); this.ApplicationDescriptionPanel.PerformLayout(); this.FilterPanel.ResumeLayout(false); this.FilterPanel.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.EndpointsGridView)).EndInit(); this.ResumeLayout(false); } diff --git a/Samples/GDS/ClientControls/Controls/DiscoveryControl.cs b/Samples/GDS/ClientControls/Controls/DiscoveryControl.cs index 93a34ec29..653bfdde5 100644 --- a/Samples/GDS/ClientControls/Controls/DiscoveryControl.cs +++ b/Samples/GDS/ClientControls/Controls/DiscoveryControl.cs @@ -1,4 +1,4 @@ -/* ======================================================================== +/* ======================================================================== * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 @@ -33,6 +33,8 @@ using System.Data; using System.Text; using System.Windows.Forms; +using System.Threading.Tasks; +using System.Threading; namespace Opc.Ua.Gds.Client.Controls { @@ -83,12 +85,6 @@ private enum RootFolders Add } - private class ExpandNodeData - { - public TreeNode Parent; - public LocalDiscoveryServerClient Lds; - } - [DefaultValue(300)] [SettingsBindable(true)] public int SplitterDistance @@ -125,7 +121,7 @@ public EndpointDescription SelectedEndpoint { var endpoint = new EndpointDescription(server.DiscoveryUrl) { - Server = GetApplicationDescription(server) + Server = GetApplicationDescriptionAsync(server).GetAwaiter().GetResult() }; return endpoint; } @@ -159,7 +155,7 @@ public EndpointDescription SelectedEndpoint if (ce.Description.EndpointUrl == ce.Description.Server.ApplicationUri) { - ce.Description.Server = GetApplicationDescription(new ServerOnNetwork() { DiscoveryUrl = ce.Description.EndpointUrl }); + ce.Description.Server = GetApplicationDescriptionAsync(new ServerOnNetwork() { DiscoveryUrl = ce.Description.EndpointUrl }).GetAwaiter().GetResult(); } endpoint = ce.Description; @@ -193,7 +189,7 @@ public EndpointDescription SelectedEndpoint ServerOnNetwork server = (ServerOnNetwork)node.Tag; endpoint = new EndpointDescription(server.DiscoveryUrl) { - Server = GetApplicationDescription(server) + Server = GetApplicationDescriptionAsync(server).GetAwaiter().GetResult() }; } @@ -205,13 +201,13 @@ public EndpointDescription SelectedEndpoint } } - private ApplicationDescription GetApplicationDescription(ServerOnNetwork server) + private async Task GetApplicationDescriptionAsync(ServerOnNetwork server) { ApplicationDescription fallback = null; try { - foreach (var application in m_lds.FindServers(server.DiscoveryUrl, null)) + foreach (var application in await m_lds.FindServersAsync(server.DiscoveryUrl, null)) { if (fallback == null) { @@ -350,7 +346,7 @@ private string SelectDiscoveryUrl(ApplicationDescription server) return url; } - private void DiscoveryTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e) + private async void DiscoveryTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e) { if (e.Node.Nodes.Count != 1 || !String.IsNullOrEmpty(e.Node.Nodes[0].Text)) { @@ -361,21 +357,15 @@ private void DiscoveryTreeView_BeforeExpand(object sender, TreeViewCancelEventAr if (RootFolders.LocalMachine.Equals(e.Node.Tag)) { - m_lds.BeginFindServers( - OnFindServersComplete, - new ExpandNodeData() { Parent = e.Node, Lds = m_lds }); - + // async replace for BeginFindServers + await PopulateServersNodeAsync(e.Node, null); return; } if (RootFolders.LocalNetwork.Equals(e.Node.Tag)) { - m_lds.BeginFindServersOnNetwork( - 0, - 100, - OnFindServersOnNetworkComplete, - new ExpandNodeData() { Parent = e.Node, Lds = m_lds }); - + // async replace for BeginFindServersOnNetwork + await PopulateServersOnNetworkNodeAsync(e.Node, 0, 100); return; } @@ -405,32 +395,61 @@ private void DiscoveryTreeView_BeforeExpand(object sender, TreeViewCancelEventAr if (e.Node.Tag is Uri) { - m_lds.BeginFindServers( - e.Node.Tag.ToString(), - null, - null, - null, - null, - OnFindServersComplete, - new ExpandNodeData() { Parent = e.Node, Lds = m_lds }); - + await PopulateServersNodeAsync(e.Node, e.Node.Tag.ToString()); return; } } - private void OnFindServersComplete(IAsyncResult result) + private async Task PopulateServersOnNetworkNodeAsync(TreeNode parent, uint startingRecordId, uint maxRecordsToReturn) { - if (InvokeRequired) + try { - BeginInvoke(new AsyncCallback(OnFindServersComplete), result); - return; + var (servers, lastCounterResetTime) = await m_lds.FindServersOnNetworkAsync( + null, + null, + startingRecordId, + maxRecordsToReturn, + null, + CancellationToken.None); + + foreach (ServerOnNetwork server in servers) + { + if (server.ServerCapabilities != null && server.ServerCapabilities.Contains("LDS")) + { + continue; + } + + TreeNode node = new TreeNode(String.Format("{0}", server.ServerName)); + node.SelectedImageIndex = node.ImageIndex = ImageIndex.Server; + node.Tag = server; + node.Nodes.Add(new TreeNode()); + parent.Nodes.Add(node); + } + + if (DiscoveryTreeView.SelectedNode == parent) + { + ShowServerOnNetworks(parent.Nodes); + } + else + { + parent.Expand(); + } } + catch (Exception ex) + { + Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + } + } + private async Task PopulateServersNodeAsync(TreeNode parent, string discoveryUrl) + { try { - ExpandNodeData data = (ExpandNodeData)result.AsyncState; - - List servers = data.Lds.EndFindServers(result); + List servers = new List(); + foreach (var s in await m_lds.FindServersAsync(discoveryUrl, null)) + { + servers.Add(s); + } foreach (ApplicationDescription server in servers) { @@ -443,24 +462,24 @@ private void OnFindServersComplete(IAsyncResult result) node.SelectedImageIndex = node.ImageIndex = (server.ApplicationType == ApplicationType.DiscoveryServer) ? ImageIndex.LocalNetwork : ImageIndex.Server; node.Tag = server; node.Nodes.Add(new TreeNode()); - data.Parent.Nodes.Add(node); + parent.Nodes.Add(node); } - if (DiscoveryTreeView.SelectedNode == data.Parent) + if (DiscoveryTreeView.SelectedNode == parent) { - ShowApplicationDescriptions(data.Parent.Nodes); + ShowApplicationDescriptions(parent.Nodes); } else { - data.Parent.Expand(); + parent.Expand(); } } - catch (Exception e) + catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, e); + Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); } } - + private void ShowApplicationDescriptions(TreeNodeCollection nodes) { ServersTable.Rows.Clear(); @@ -509,50 +528,6 @@ private void ShowApplicationDescriptions(TreeNodeCollection nodes) } } - private void OnFindServersOnNetworkComplete(IAsyncResult result) - { - if (InvokeRequired) - { - BeginInvoke(new AsyncCallback(OnFindServersOnNetworkComplete), result); - return; - } - - try - { - ExpandNodeData data = (ExpandNodeData)result.AsyncState; - - DateTime lastCounterResetTime; - List servers = data.Lds.EndFindServersOnNetwork(result, out lastCounterResetTime); - - foreach (ServerOnNetwork server in servers) - { - if (server.ServerCapabilities.Contains("LDS")) - { - continue; - } - - TreeNode node = new TreeNode(String.Format("{0}", server.ServerName)); - node.SelectedImageIndex = node.ImageIndex = ImageIndex.Server; - node.Tag = server; - node.Nodes.Add(new TreeNode()); - data.Parent.Nodes.Add(node); - } - - if (DiscoveryTreeView.SelectedNode == data.Parent) - { - ShowServerOnNetworks(data.Parent.Nodes); - } - else - { - data.Parent.Expand(); - } - } - catch (Exception e) - { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, e); - } - } - private void ShowServerOnNetworks(TreeNodeCollection nodes) { ServersTable.Rows.Clear(); @@ -601,37 +576,6 @@ private void ShowServerOnNetworks(TreeNodeCollection nodes) } } - private class GetEndpointsData - { - public TreeNode Parent; - public LocalDiscoveryServerClient Lds; - } - - private void OnGetEndpointsComplete(IAsyncResult result) - { - if (InvokeRequired) - { - BeginInvoke(new AsyncCallback(OnGetEndpointsComplete), result); - return; - } - - GetEndpointsData data = (GetEndpointsData)result.AsyncState; - - try - { - List endpoints = data.Lds.EndGetEndpoints(result); - - if (DiscoveryTreeView.SelectedNode == data.Parent) - { - ShowEndpointDescriptions(endpoints); - } - } - catch (Exception e) - { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, e); - } - } - private void ShowEndpointDescriptions(List endpoints) { EndpointsTable.Rows.Clear(); @@ -845,7 +789,7 @@ private void ShowPanel(bool list) } } - private void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArgs e) + private async void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArgs e) { try { @@ -858,9 +802,7 @@ private void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArgs e) { e.Node.Nodes.Clear(); - m_lds.BeginFindServers( - OnFindServersComplete, - new ExpandNodeData() { Parent = e.Node, Lds = m_lds }); + await PopulateServersNodeAsync(e.Node, null); } else { @@ -879,11 +821,7 @@ private void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArgs e) { e.Node.Nodes.Clear(); - m_lds.BeginFindServersOnNetwork( - 0, - 1000, - OnFindServersOnNetworkComplete, - new ExpandNodeData() { Parent = e.Node, Lds = m_lds }); + await PopulateServersOnNetworkNodeAsync(e.Node, 0, 1000); } else { @@ -945,11 +883,7 @@ private void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArgs e) if (discoveryUrl != null) { - m_lds.BeginGetEndpoints( - discoveryUrl, - null, - OnGetEndpointsComplete, - new GetEndpointsData() { Parent = e.Node, Lds = m_lds }); + await LoadEndpointsAndShowAsync(e.Node, discoveryUrl); } } @@ -969,11 +903,7 @@ private void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArgs e) { Cursor = Cursors.WaitCursor; - m_lds.BeginGetEndpoints( - server.DiscoveryUrl, - null, - OnGetEndpointsComplete, - new GetEndpointsData() { Parent = e.Node, Lds = m_lds }); + await LoadEndpointsAndShowAsync(e.Node, server.DiscoveryUrl); } finally { @@ -993,11 +923,7 @@ private void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArgs e) ApplicationUriTextBox.Text = "---"; ProductUriTextBox.Text = "---"; - m_lds.BeginGetEndpoints( - server.EndpointUrl.ToString(), - null, - OnGetEndpointsComplete, - new GetEndpointsData() { Parent = e.Node, Lds = m_lds }); + await LoadEndpointsAndShowAsync(e.Node, server.EndpointUrl.ToString()); } } catch (Exception ex) @@ -1006,6 +932,23 @@ private void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArgs e) } } + private async Task LoadEndpointsAndShowAsync(TreeNode parent, string discoveryUrl) + { + try + { + var endpoints = await m_lds.GetEndpointsAsync(discoveryUrl, null); + + if (DiscoveryTreeView.SelectedNode == parent) + { + ShowEndpointDescriptions(endpoints); + } + } + catch (Exception e) + { + Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, e); + } + } + private void FilterTextBox_TextChanged(object sender, EventArgs e) { try diff --git a/Samples/GDS/ClientControls/Controls/EditValueCtrl.cs b/Samples/GDS/ClientControls/Controls/EditValueCtrl.cs index 88118a946..433ce6733 100644 --- a/Samples/GDS/ClientControls/Controls/EditValueCtrl.cs +++ b/Samples/GDS/ClientControls/Controls/EditValueCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -58,7 +58,7 @@ public EditValueCtrl() MaxDisplayTextLength = 100; ValuesDV.AutoGenerateColumns = false; ImageList = new ImageListControl().ImageList; - + m_dataset = new DataSet(); m_dataset.Tables.Add("Values"); @@ -81,7 +81,7 @@ public EditValueCtrl() #endregion #region AccessInfo Class - private class AccessInfo + private sealed class AccessInfo { public AccessInfo Parent; public PropertyInfo PropertyInfo; @@ -161,7 +161,7 @@ public bool CanChangeType { return false; } - + if (ButtonPanel.Controls.Count > 0) { AccessInfo info = ButtonPanel.Controls[ButtonPanel.Controls.Count - 1].Tag as AccessInfo; @@ -186,7 +186,7 @@ public BuiltInType CurrentType if (ButtonPanel.Controls.Count > 0) { AccessInfo info = ButtonPanel.Controls[ButtonPanel.Controls.Count - 1].Tag as AccessInfo; - + if (info != null) { Variant? value = info.Value as Variant?; @@ -263,7 +263,7 @@ public void SetArraySize() if (currentValue == null) { - dimensions = new int[0]; + dimensions = Array.Empty(); } Array array = currentValue as Array; @@ -384,7 +384,7 @@ public void SetType(BuiltInType builtInType) { return; } - + AccessInfo info = ButtonPanel.Controls[ButtonPanel.Controls.Count - 1].Tag as AccessInfo; Opc.Ua.TypeInfo currentType = info.TypeInfo; @@ -485,7 +485,8 @@ private object Clone(object value) MemoryStream mstrm = new MemoryStream(); serializer.Serialize(mstrm, value); mstrm.Position = 0; - return serializer.Deserialize(mstrm); + using XmlReader reader = XmlReader.Create(mstrm, new XmlReaderSettings() { XmlResolver = null }); + return serializer.Deserialize(reader); } } @@ -536,7 +537,7 @@ public void ShowValue( } } } - + AccessInfo info = new AccessInfo(); info.Value = value; info.TypeInfo = expectedType; @@ -645,7 +646,7 @@ private void ShowValueNoNotify(AccessInfo parent) if (parent.Parent != null || ButtonPanel.Controls.Count == 0) { item = new Button(); - + item.AutoSize = true; item.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; item.FlatStyle = FlatStyle.Standard; @@ -1033,7 +1034,7 @@ private void ShowIndexedValue(AccessInfo info) DataRow row = m_dataset.Tables[0].NewRow(); StringBuilder buffer = new StringBuilder(); - buffer.Append("["); + buffer.Append('['); if (info.Indexes != null) { @@ -1041,14 +1042,14 @@ private void ShowIndexedValue(AccessInfo info) { if (ii > 0) { - buffer.Append(","); + buffer.Append(','); } buffer.Append(info.Indexes[ii]); } } - buffer.Append("]"); + buffer.Append(']'); info.Name = buffer.ToString(); row[0] = info; @@ -1421,7 +1422,7 @@ private bool IsSimpleValue(AccessInfo info) { return false; } - + switch (typeInfo.BuiltInType) { case BuiltInType.String: diff --git a/Samples/GDS/ClientControls/Controls/SelectGdsDialog.cs b/Samples/GDS/ClientControls/Controls/SelectGdsDialog.cs index cf4268e59..c70188302 100644 --- a/Samples/GDS/ClientControls/Controls/SelectGdsDialog.cs +++ b/Samples/GDS/ClientControls/Controls/SelectGdsDialog.cs @@ -77,7 +77,7 @@ private void ServerUrlTextBox_TextChanged(object sender, EventArgs e) OkButton.Enabled = Uri.IsWellFormedUriString(ServerUrlTextBox.Text.Trim(), UriKind.Absolute); } - private void OkButton_Click(object sender, EventArgs e) + private async void OkButton_Click(object sender, EventArgs e) { try { @@ -92,7 +92,7 @@ private void OkButton_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; - var endpoint = CoreClientUtils.SelectEndpoint(m_gds.Configuration, url, true, 5000); + var endpoint = await CoreClientUtils.SelectEndpointAsync(m_gds.Configuration, url, true, 5000); if (UserNameCredentialsRB.Checked) { @@ -109,7 +109,7 @@ private void OkButton_Click(object sender, EventArgs e) } } - m_gds.Connect(url); + await m_gds.ConnectAsync(url); } finally { diff --git a/Samples/GDS/ClientControls/Controls/SelectPushServerDialog.cs b/Samples/GDS/ClientControls/Controls/SelectPushServerDialog.cs index 746c89d5d..f36dfad2d 100644 --- a/Samples/GDS/ClientControls/Controls/SelectPushServerDialog.cs +++ b/Samples/GDS/ClientControls/Controls/SelectPushServerDialog.cs @@ -77,7 +77,7 @@ private void ServerUrlTextBox_TextChanged(object sender, EventArgs e) OkButton.Enabled = Uri.IsWellFormedUriString(ServerUrlTextBox.Text.Trim(), UriKind.Absolute); } - private void OkButton_Click(object sender, EventArgs e) + private async void OkButton_Click(object sender, EventArgs e) { try { @@ -92,7 +92,7 @@ private void OkButton_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; - var endpoint = CoreClientUtils.SelectEndpoint(m_pushServer.Configuration, url, false, 5000); + var endpoint = await CoreClientUtils.SelectEndpointAsync(m_pushServer.Configuration, url, false, 5000); if (UserNameCredentialsRB.Checked) { @@ -109,7 +109,7 @@ private void OkButton_Click(object sender, EventArgs e) } } - m_pushServer.Connect(url).Wait(); + await m_pushServer.ConnectAsync(url); } finally { diff --git a/Samples/GDS/ClientControls/Controls/ServerStatusControl.cs b/Samples/GDS/ClientControls/Controls/ServerStatusControl.cs index 4ae86a773..301dfce37 100644 --- a/Samples/GDS/ClientControls/Controls/ServerStatusControl.cs +++ b/Samples/GDS/ClientControls/Controls/ServerStatusControl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,6 +29,8 @@ using System; using System.Drawing; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua.Client; @@ -43,10 +45,10 @@ public ServerStatusControl() private ServerPushConfigurationClient m_server; - public void Initialize(ServerPushConfigurationClient server) + public Task InitializeAsync(ServerPushConfigurationClient server, CancellationToken ct = default) { m_server = server; - ServerBrowseControl.Initialize((server != null) ? server.Session as Session : null, Opc.Ua.ObjectIds.ObjectsFolder, ReferenceTypeIds.HierarchicalReferences); + return ServerBrowseControl.InitializeAsync((server != null) ? server.Session as Session : null, Opc.Ua.ObjectIds.ObjectsFolder, ct, ReferenceTypeIds.HierarchicalReferences); } public void SetServerStatus(ServerStatusDataType status) @@ -82,8 +84,8 @@ public void SetServerStatus(ServerStatusDataType status) StateTextBox.Text = status.State.ToString(); } } - - private void ApplyChangesButton_Click(object sender, EventArgs e) + + private async void ApplyChangesButton_Click(object sender, EventArgs e) { if (m_server == null) { @@ -92,7 +94,7 @@ private void ApplyChangesButton_Click(object sender, EventArgs e) try { - m_server.ApplyChanges(); + await m_server.ApplyChangesAsync(); } catch (Exception exception) { @@ -106,9 +108,9 @@ private void ApplyChangesButton_Click(object sender, EventArgs e) try { - m_server.Disconnect(); + await m_server.DisconnectAsync(); } - catch (Exception) + catch { // ignore. } diff --git a/Samples/GDS/ClientControls/Controls/TrustListControl.cs b/Samples/GDS/ClientControls/Controls/TrustListControl.cs index 1633bbc8d..acc2ec25f 100644 --- a/Samples/GDS/ClientControls/Controls/TrustListControl.cs +++ b/Samples/GDS/ClientControls/Controls/TrustListControl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -34,6 +34,8 @@ using System.Drawing; using System.IO; using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua.Security.Certificates; @@ -87,7 +89,7 @@ private ICertificateStore CreateStore(string storePath) return store; } - public async void Initialize(string trustedStorePath, string issuerStorePath, string rejectedStorePath) + public async Task Initialize(string trustedStorePath, string issuerStorePath, string rejectedStorePath, CancellationToken ct = default) { CertificatesTable.Rows.Clear(); @@ -99,14 +101,14 @@ public async void Initialize(string trustedStorePath, string issuerStorePath, st { using (ICertificateStore store = CreateStore(trustedStorePath)) { - X509CertificateCollection certificates = await store.Enumerate(); + X509CertificateCollection certificates = await store.EnumerateAsync(ct); foreach (X509Certificate2 certificate in certificates) { var crls = new X509CRLCollection(); if (store.SupportsCRLs) { - foreach (X509CRL crl in await store.EnumerateCRLs(certificate)) + foreach (X509CRL crl in await store.EnumerateCRLsAsync(certificate, ct: ct)) { crls.Add(crl); } @@ -126,19 +128,19 @@ public async void Initialize(string trustedStorePath, string issuerStorePath, st { using (ICertificateStore store = CreateStore(issuerStorePath)) { - X509Certificate2Collection certificates = await store.Enumerate(); + X509Certificate2Collection certificates = await store.EnumerateAsync(ct); foreach (X509Certificate2 certificate in certificates) { var crls = new X509CRLCollection(); if (store.SupportsCRLs) { - foreach (X509CRL crl in await store.EnumerateCRLs(certificate)) + foreach (X509CRL crl in await store.EnumerateCRLsAsync(certificate, ct: ct)) { crls.Add(crl); } } - + AddCertificate(certificate, Status.Issuer, crls); } } @@ -149,7 +151,7 @@ public async void Initialize(string trustedStorePath, string issuerStorePath, st { using (ICertificateStore store = CreateStore(rejectedStorePath)) { - X509Certificate2Collection certificates = await store.Enumerate(); + X509Certificate2Collection certificates = await store.EnumerateAsync(ct); foreach (X509Certificate2 certificate in certificates) { AddCertificate(certificate, Status.Rejected, null); @@ -183,7 +185,7 @@ public void Initialize(TrustListDataType trustList, X509Certificate2Collection r foreach (var crlBytes in trustList.TrustedCrls) { X509CRL crl = new X509CRL(crlBytes); - + if (X509Utils.CompareDistinguishedName(crl.Issuer, certificate.Subject) && crl.VerifySignature(certificate, false)) { @@ -385,15 +387,15 @@ private void MoveCertificate(DataRow row, Status status) { using (ICertificateStore store = CreateStore(targetStorePath)) { - store.Add(certificate); + store.AddAsync(certificate); } } - + if (!String.IsNullOrEmpty(oldStorePath)) { using (ICertificateStore store = CreateStore(oldStorePath)) { - store.Delete(certificate.Thumbprint); + store.DeleteAsync(certificate.Thumbprint); } } } @@ -443,7 +445,7 @@ private void DeleteMenuItem_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); } } @@ -544,7 +546,7 @@ private void ImportMenuItem_Click(object sender, EventArgs e) { using (ICertificateStore store = CreateStore(m_trustedStorePath)) { - store.Add(certificate); + store.AddAsync(certificate); } } } diff --git a/Samples/GDS/ClientControls/Controls/TrustListDialog.cs b/Samples/GDS/ClientControls/Controls/TrustListDialog.cs index 95ecd3e94..9e8e30cc4 100644 --- a/Samples/GDS/ClientControls/Controls/TrustListDialog.cs +++ b/Samples/GDS/ClientControls/Controls/TrustListDialog.cs @@ -1,8 +1,8 @@ -/* ======================================================================== +/* ======================================================================== * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -27,6 +27,8 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; namespace Opc.Ua.Gds.Client.Controls @@ -39,12 +41,13 @@ public CertificatesStoreDialog() Icon = ImageListControl.AppIcon; } - public void ShowDialog(ApplicationConfiguration configuration) + public async Task ShowDialogAsync(ApplicationConfiguration configuration, CancellationToken ct = default) { - CertificatesControl.Initialize( + await CertificatesControl.Initialize( configuration.SecurityConfiguration.TrustedPeerCertificates.StorePath, configuration.SecurityConfiguration.TrustedIssuerCertificates.StorePath, - configuration.SecurityConfiguration.RejectedCertificateStore.StorePath); + configuration.SecurityConfiguration.RejectedCertificateStore.StorePath, + ct); ApplicationNameLabel.Text = configuration.ApplicationName; ApplicationUriLabel.Text = configuration.ApplicationUri; diff --git a/Samples/GDS/ClientControls/Controls/ViewApplicationRecordsDialog.cs b/Samples/GDS/ClientControls/Controls/ViewApplicationRecordsDialog.cs index b8c1fc771..1bfe9ca88 100644 --- a/Samples/GDS/ClientControls/Controls/ViewApplicationRecordsDialog.cs +++ b/Samples/GDS/ClientControls/Controls/ViewApplicationRecordsDialog.cs @@ -1,4 +1,4 @@ -/* ======================================================================== +/* ======================================================================== * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 @@ -158,7 +158,7 @@ public ApplicationRecordDataType ShowDialog(IWin32Window owner, IList ShowDialog(IWin32Window owner, ref QueryServersFilt ApplicationUriTextBox.Text = filters.ApplicationUri; ApplicationNameTextBox.Text = filters.ApplicationName; ProductUriTextBox.Text = filters.ProductUri; - + if (base.ShowDialog(owner) != DialogResult.OK) { return null; @@ -103,7 +103,7 @@ private void ApplicationRecordDataGridView_SelectionChanged(object sender, Event } } - private void SearchButton_Click(object sender, EventArgs e) + private async void SearchButton_Click(object sender, EventArgs e) { try { @@ -111,12 +111,12 @@ private void SearchButton_Click(object sender, EventArgs e) if (!m_gds.IsConnected) { - new SelectGdsDialog().ShowDialog(null, m_gds, m_gds.GetDefaultGdsUrls(null)); + new SelectGdsDialog().ShowDialog(null, m_gds, await m_gds.GetDefaultGdsUrlsAsync(null)); } uint maxNoOfRecords = (uint)NumberOfRecordsUpDown.Value; - var servers = m_gds.QueryServers( + var servers = await m_gds.QueryServersAsync( 0, ApplicationNameTextBox.Text.Trim(), ApplicationUriTextBox.Text.Trim(), @@ -180,7 +180,7 @@ private void SearchButton_Click(object sender, EventArgs e) if (ServersTable.Rows.Count == 0) { - MessageBox.Show(ParentForm, "No servers available that meet the filter criteria.", Text, MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show(ParentForm, "No servers available that meet the filter criteria.", Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) @@ -310,7 +310,7 @@ private void ServerCapabilitiesButton_Click(object sender, EventArgs e) { if (buffer.Length > 0) { - buffer.Append(","); + buffer.Append(','); } buffer.Append(capability); diff --git a/Samples/GDS/ClientControls/GlobalDiscoveryClientControls.csproj b/Samples/GDS/ClientControls/GlobalDiscoveryClientControls.csproj index 95ef330c3..91b09414d 100644 --- a/Samples/GDS/ClientControls/GlobalDiscoveryClientControls.csproj +++ b/Samples/GDS/ClientControls/GlobalDiscoveryClientControls.csproj @@ -25,6 +25,7 @@ DEBUG;TRACE prompt 4 + AllRules.ruleset pdbonly @@ -33,6 +34,7 @@ TRACE prompt 4 + AllRules.ruleset @@ -217,10 +219,10 @@ - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview diff --git a/Samples/GDS/ConsoleServer/NetCoreGlobalDiscoveryServer.csproj b/Samples/GDS/ConsoleServer/NetCoreGlobalDiscoveryServer.csproj index aad804d8b..074cc88b8 100644 --- a/Samples/GDS/ConsoleServer/NetCoreGlobalDiscoveryServer.csproj +++ b/Samples/GDS/ConsoleServer/NetCoreGlobalDiscoveryServer.csproj @@ -1,4 +1,4 @@ - + Exe @@ -12,10 +12,10 @@ - + - - + + diff --git a/Samples/GDS/ConsoleServer/Program.cs b/Samples/GDS/ConsoleServer/Program.cs index 61e362d61..02eb7d7df 100644 --- a/Samples/GDS/ConsoleServer/Program.cs +++ b/Samples/GDS/ConsoleServer/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -27,11 +27,6 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ -using Mono.Options; -using Opc.Ua.Configuration; -using Opc.Ua.Gds.Server.Database.Linq; -using Opc.Ua.Server; -using Opc.Ua.Server.UserDatabase; using System; using System.Collections.Generic; using System.Data; @@ -40,33 +35,37 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -using System.Xml.Linq; +using Mono.Options; +using Opc.Ua.Configuration; +using Opc.Ua.Gds.Server.Database.Linq; +using Opc.Ua.Server; +using Opc.Ua.Server.UserDatabase; namespace Opc.Ua.Gds.Server { public class ApplicationMessageDlg : IApplicationMessageDlg { - private string message = string.Empty; - private bool ask = false; + private string m_message = string.Empty; + private bool m_ask = false; public override void Message(string text, bool ask) { - this.message = text; - this.ask = ask; + this.m_message = text; + this.m_ask = ask; } public override async Task ShowAsync() { - if (ask) + if (m_ask) { - message += " (y/n, default y): "; - Console.Write(message); + m_message += " (y/n, default y): "; + Console.Write(m_message); } else { - Console.WriteLine(message); + Console.WriteLine(m_message); } - if (ask) + if (m_ask) { try { @@ -95,7 +94,7 @@ public enum ExitCode : int public static class Program { - public static int Main(string[] args) + public static async Task Main(string[] args) { Console.WriteLine(".Net Core OPC UA Global Discovery Server"); @@ -131,8 +130,8 @@ public static int Main(string[] args) return (int)ExitCode.ErrorInvalidCommandLine; } - NetCoreGlobalDiscoveryServer server = new NetCoreGlobalDiscoveryServer(); - server.Run(); + var server = new NetCoreGlobalDiscoveryServer(); + await server.RunAsync().ConfigureAwait(false); return (int)NetCoreGlobalDiscoveryServer.ExitCode; } @@ -140,22 +139,22 @@ public static int Main(string[] args) public class NetCoreGlobalDiscoveryServer { - GlobalDiscoverySampleServer server; - Task status; - DateTime lastEventTime; - static ExitCode exitCode; + private GlobalDiscoverySampleServer server; + private Task status; + private DateTime lastEventTime; + public static ExitCode exitCode; public NetCoreGlobalDiscoveryServer() { } - public void Run() + public async Task RunAsync() { try { exitCode = ExitCode.ErrorServerNotStarted; - ConsoleGlobalDiscoveryServer().Wait(); + await ConsoleGlobalDiscoveryServerAsync().ConfigureAwait(false); Console.WriteLine("Server started. Press Ctrl-C to exit..."); exitCode = ExitCode.ErrorServerRunning; } @@ -192,7 +191,7 @@ public void Run() { // Stop status thread server = null; - status.Wait(); + await status.ConfigureAwait(false); // Stop server and dispose _server.Stop(); } @@ -201,7 +200,7 @@ public void Run() exitCode = ExitCode.Ok; } - public static ExitCode ExitCode { get => exitCode; } + public static ExitCode ExitCode => exitCode; private static void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { @@ -213,21 +212,20 @@ private static void CertificateValidator_CertificateValidation(CertificateValida } } - private async Task ConsoleGlobalDiscoveryServer() + private async Task ConsoleGlobalDiscoveryServerAsync() { ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance - { + var application = new ApplicationInstance { ApplicationName = "Global Discovery Server", ApplicationType = ApplicationType.Server, ConfigSectionName = "Opc.Ua.GlobalDiscoveryServer" }; // load the application configuration. - ApplicationConfiguration config = await application.LoadApplicationConfiguration(false).ConfigureAwait(false); + ApplicationConfiguration config = await application.LoadApplicationConfigurationAsync(false).ConfigureAwait(false); // check the application certificate. - bool haveAppCertificate = await application.CheckApplicationInstanceCertificates(false).ConfigureAwait(false); + bool haveAppCertificate = await application.CheckApplicationInstanceCertificatesAsync(false).ConfigureAwait(false); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); @@ -256,17 +254,17 @@ private async Task ConsoleGlobalDiscoveryServer() userDatabase, true, createStandardUsers); - await application.Start(server).ConfigureAwait(false); + await application.StartAsync(server).ConfigureAwait(false); // print endpoint info - var endpoints = application.Server.GetEndpoints().Select(e => e.EndpointUrl).Distinct(); - foreach (var endpoint in endpoints) + IEnumerable endpoints = application.Server.GetEndpoints().Select(e => e.EndpointUrl).Distinct(); + foreach (string endpoint in endpoints) { Console.WriteLine(endpoint); } // start the status thread - status = Task.Run(new Action(StatusThread)); + status = Task.Run(new Action(StatusThreadAsync)); // print notification on session events server.CurrentInstance.SessionManager.SessionActivated += EventStatus; @@ -278,7 +276,7 @@ private async Task ConsoleGlobalDiscoveryServer() private bool ConfigureUsers(JsonUserDatabase userDatabase) { ApplicationInstance.MessageDlg.Message("Use default users?", true); - bool createStandardUsers = ApplicationInstance.MessageDlg.ShowAsync().Result; + bool createStandardUsers = ApplicationInstance.MessageDlg.ShowAsync().GetAwaiter().GetResult(); if (!createStandardUsers) { @@ -310,13 +308,13 @@ private bool ConfigureUsers(JsonUserDatabase userDatabase) return createStandardUsers; } - private void EventStatus(Session session, SessionEventReason reason) + private void EventStatus(ISession session, SessionEventReason reason) { lastEventTime = DateTime.UtcNow; PrintSessionStatus(session, reason.ToString()); } - void PrintSessionStatus(Session session, string reason, bool lastContact = false) + private void PrintSessionStatus(ISession session, string reason, bool lastContact = false) { lock (session.DiagnosticsLock) { @@ -337,16 +335,16 @@ void PrintSessionStatus(Session session, string reason, bool lastContact = false } } - private async void StatusThread() + private async void StatusThreadAsync() { while (server != null) { if (DateTime.UtcNow - lastEventTime > TimeSpan.FromMilliseconds(6000)) { - IList sessions = server.CurrentInstance.SessionManager.GetSessions(); + IList sessions = server.CurrentInstance.SessionManager.GetSessions(); for (int ii = 0; ii < sessions.Count; ii++) { - Session session = sessions[ii]; + ISession session = sessions[ii]; PrintSessionStatus(session, "-Status-", true); } lastEventTime = DateTime.UtcNow; diff --git a/Samples/GDS/Server/GlobalDiscoveryServer.csproj b/Samples/GDS/Server/GlobalDiscoveryServer.csproj index d00c45fcb..164615771 100644 --- a/Samples/GDS/Server/GlobalDiscoveryServer.csproj +++ b/Samples/GDS/Server/GlobalDiscoveryServer.csproj @@ -235,10 +235,10 @@ 6.5.1 - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview diff --git a/Samples/GDS/Server/Program.cs b/Samples/GDS/Server/Program.cs index d84a17bbd..f782a8a34 100644 --- a/Samples/GDS/Server/Program.cs +++ b/Samples/GDS/Server/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -61,23 +61,23 @@ static void Main() try { // load the application configuration. - var config = application.LoadApplicationConfiguration(false).Result; + var config = application.LoadApplicationConfigurationAsync(false).AsTask().GetAwaiter().GetResult(); // check the application certificate. - bool haveAppCertificate = application.CheckApplicationInstanceCertificates(false).Result; + bool haveAppCertificate = application.CheckApplicationInstanceCertificatesAsync(false).AsTask().GetAwaiter().GetResult(); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } - + // load the user database. var userDatabase = new SqlUsersDatabase(); //initialize users Database userDatabase.Initialize(); bool createStandardUsers = ConfigureUsers(userDatabase); - + // start the server. var database = new SqlApplicationsDatabase(); @@ -88,7 +88,7 @@ static void Main() userDatabase, true, createStandardUsers); - application.Start(server).Wait(); + application.StartAsync(server).Wait(); // run the application interactively. System.Windows.Forms.Application.Run(new ServerForm(server, application.ApplicationConfiguration)); @@ -102,7 +102,7 @@ static void Main() private static bool ConfigureUsers(SqlUsersDatabase userDatabase) { ApplicationInstance.MessageDlg.Message("Use default users?", true); - bool createStandardUsers = ApplicationInstance.MessageDlg.ShowAsync().Result; + bool createStandardUsers = ApplicationInstance.MessageDlg.ShowAsync().GetAwaiter().GetResult(); if (!createStandardUsers) { //Delete existing standard users diff --git a/Samples/Opc.Ua.Sample/Base/CustomNodeManager.cs b/Samples/Opc.Ua.Sample/Base/CustomNodeManager.cs index 6fd88fb7b..9f6acc759 100644 --- a/Samples/Opc.Ua.Sample/Base/CustomNodeManager.cs +++ b/Samples/Opc.Ua.Sample/Base/CustomNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -59,7 +59,7 @@ public CustomNodeManager2(IServerInternal server) m_systemContext.SystemHandle = null; m_systemContext.NodeIdFactory = this; - // create the table of nodes. + // create the table of nodes. m_predefinedNodes = new NodeIdDictionary(); m_rootNotifiers = new List(); m_sampledItems = new List(); @@ -341,7 +341,7 @@ protected set /// /// The externalReferences is an out parameter that allows the node manager to link to nodes /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and - /// should have a reference to the root folder node(s) exposed by this node manager. + /// should have a reference to the root folder node(s) exposed by this node manager. /// public virtual void CreateAddressSpace(IDictionary> externalReferences) { @@ -519,7 +519,7 @@ protected virtual void RemovePredefinedNode( ///
protected virtual void OnNodeRemoved(NodeState node) { - // overridden by the sub-class. + // overridden by the sub-class. } /// @@ -721,7 +721,7 @@ protected void AddTypesToTypeTree(NodeId typeId) } /// - /// Finds the specified and checks if it is of the expected type. + /// Finds the specified and checks if it is of the expected type. /// /// Returns null if not found or not of the correct type. public NodeState FindPredefinedNode(NodeId nodeId, Type expectedType) @@ -765,7 +765,7 @@ public virtual void DeleteAddressSpace() /// Returns a unique handle for the node. /// /// - /// This must efficiently determine whether the node belongs to the node manager. If it does belong to + /// This must efficiently determine whether the node belongs to the node manager. If it does belong to /// NodeManager it should return a handle that does not require the NodeId to be validated again when /// the handle is passed into other methods such as 'Read' or 'Write'. /// @@ -781,7 +781,7 @@ public virtual object GetManagerHandle(NodeId nodeId) /// Returns a unique handle for the node. ///
/// - /// This must efficiently determine whether the node belongs to the node manager. If it does belong to + /// This must efficiently determine whether the node belongs to the node manager. If it does belong to /// NodeManager it should return a handle that does not require the NodeId to be validated again when /// the handle is passed into other methods such as 'Read' or 'Write'. /// @@ -1030,7 +1030,7 @@ public virtual void Browse( // apply filters to references. for (IReference reference = browser.Next(); reference != null; reference = browser.Next()) { - // create the type definition reference. + // create the type definition reference. ReferenceDescription description = GetReferenceDescription(context, reference, continuationPoint); if (description == null) @@ -1064,7 +1064,7 @@ private ReferenceDescription GetReferenceDescription( IReference reference, ContinuationPoint continuationPoint) { - // create the type definition reference. + // create the type definition reference. ReferenceDescription description = new ReferenceDescription(); description.NodeId = reference.TargetId; @@ -1146,9 +1146,9 @@ private ReferenceDescription GetReferenceDescription( /// Returns the target of the specified browse path fragment(s). ///
/// - /// If reference exists but the node manager does not know the browse name it must + /// If reference exists but the node manager does not know the browse name it must /// return the NodeId as an unresolvedTargetIds. The caller will try to check the - /// browse name. + /// browse name. /// public virtual void TranslateBrowsePath( OperationContext context, @@ -1970,8 +1970,8 @@ protected virtual ServiceResult Call( /// Subscribes or unsubscribes to events produced by the specified source. ///
/// - /// This method is called when a event subscription is created or deletes. The node manager - /// must start/stop reporting events for the specified object and all objects below it in + /// This method is called when a event subscription is created or deletes. The node manager + /// must start/stop reporting events for the specified object and all objects below it in /// the notifier hierarchy. /// public virtual ServiceResult SubscribeToEvents( @@ -2037,7 +2037,7 @@ public virtual ServiceResult SubscribeToEvents( /// Subscribes or unsubscribes to events produced by all event sources. ///
/// - /// This method is called when a event subscription is created or deleted. The node + /// This method is called when a event subscription is created or deleted. The node /// manager must start/stop reporting events for all objects that it manages. /// public virtual ServiceResult SubscribeToAllEvents( @@ -2544,15 +2544,14 @@ protected virtual ServiceResult CreateMonitoredItem( /// Reads the initial value for a monitored item. ///
/// The context. - /// The item handle. + /// The monitored node. /// The monitored item. protected virtual ServiceResult ReadInitialValue( ISystemContext context, MonitoredNode monitoredNode, IDataChangeMonitoredItem2 monitoredItem) { - DataValue initialValue = new DataValue - { + DataValue initialValue = new DataValue { Value = null, ServerTimestamp = DateTime.UtcNow, SourceTimestamp = DateTime.MinValue, @@ -2629,7 +2628,7 @@ private void DeleteSampledItem(DataChangeMonitoredItem monitoredItem) } /// - /// Polls each monitored item which requires sample. + /// Polls each monitored item which requires sample. /// private void DoSample(object state) { diff --git a/Samples/Opc.Ua.Sample/Base/DataChangeMonitoredItem.cs b/Samples/Opc.Ua.Sample/Base/DataChangeMonitoredItem.cs index d73d9f382..1a70ec592 100644 --- a/Samples/Opc.Ua.Sample/Base/DataChangeMonitoredItem.cs +++ b/Samples/Opc.Ua.Sample/Base/DataChangeMonitoredItem.cs @@ -30,7 +30,7 @@ using System; using System.Collections.Generic; using System.Text; -using Opc.Ua.Server; +using Opc.Ua.Server; namespace Opc.Ua.Sample { @@ -111,10 +111,10 @@ public DataChangeMonitoredItem( m_filter = filter; m_range = 0; m_alwaysReportUpdates = alwaysReportUpdates; - + if (range != null) { - m_range = range.High - range.Low; + m_range = range.High - range.Low; } if (queueSize > 1) @@ -156,7 +156,7 @@ public QualifiedName DataEncoding ///
public bool AlwaysReportUpdates { - get { return m_alwaysReportUpdates; } + get { return m_alwaysReportUpdates; } set { m_alwaysReportUpdates = value; } } @@ -181,7 +181,7 @@ public int TimeToNextSample return 0; } - return (int)((m_nextSampleTime - now.Ticks)/TimeSpan.TicksPerMillisecond); + return (int)((m_nextSampleTime - now.Ticks) / TimeSpan.TicksPerMillisecond); } } } @@ -202,7 +202,7 @@ public MonitoringMode MonitoringMode ///
public double SamplingInterval { - get + get { lock (m_lock) { @@ -210,7 +210,7 @@ public double SamplingInterval } } } - + /// /// Modifies the monitored item parameters, /// @@ -222,7 +222,7 @@ public ServiceResult Modify( { return Modify(diagnosticsMasks, timestampsToReturn, clientHandle, samplingInterval, 0, false, null, null); } - + /// /// Modifies the monitored item parameters, /// @@ -243,17 +243,17 @@ public ServiceResult Modify( m_clientHandle = clientHandle; // subtract the previous sampling interval. - long oldSamplingInterval = (long)(m_samplingInterval*TimeSpan.TicksPerMillisecond); + long oldSamplingInterval = (long)(m_samplingInterval * TimeSpan.TicksPerMillisecond); if (oldSamplingInterval < m_nextSampleTime) { m_nextSampleTime -= oldSamplingInterval; } - + m_samplingInterval = samplingInterval; // calculate the next sampling interval. - long newSamplingInterval = (long)(m_samplingInterval*TimeSpan.TicksPerMillisecond); + long newSamplingInterval = (long)(m_samplingInterval * TimeSpan.TicksPerMillisecond); if (m_samplingInterval > 0) { @@ -270,7 +270,7 @@ public ServiceResult Modify( if (range != null) { - m_range = range.High - range.Low; + m_range = range.High - range.Low; } // update the queue size. @@ -292,7 +292,7 @@ public ServiceResult Modify( return ServiceResult.Good; } } - + /// /// Called when the attribute being monitored changed. Reads and queues the value. /// @@ -322,10 +322,15 @@ public INodeManager NodeManager get { return m_source.NodeManager; } } + public NodeId NodeId + { + get { return m_source.Node.NodeId; } + } + /// /// The session for the monitored item. /// - public Session Session + public ISession Session { get { @@ -494,7 +499,7 @@ public ServiceResult GetCreateResult(out MonitoredItemCreateResult result) result.RevisedSamplingInterval = m_samplingInterval; result.RevisedQueueSize = 0; result.FilterResult = null; - + if (m_queue != null) { result.RevisedQueueSize = m_queue.QueueSize; @@ -574,7 +579,7 @@ public void QueueValue(DataValue value, ServiceResult error, bool ignoreFilters) copy.SourcePicoseconds = value.SourcePicoseconds; copy.ServerTimestamp = value.ServerTimestamp; copy.ServerPicoseconds = value.ServerPicoseconds; - + value = copy; // ensure the data value matches the error status code. @@ -611,8 +616,8 @@ public void SetSemanticsChanged() { m_semanticsChanged = true; } - } - + } + /// /// Sets a flag indicating that the structure of the monitored node has changed. /// @@ -625,8 +630,8 @@ public void SetStructureChanged() { m_structureChanged = true; } - } - + } + /// /// Changes the monitoring mode. /// @@ -649,7 +654,7 @@ public MonitoringMode SetMonitoringMode(MonitoringMode monitoringMode) } m_monitoringMode = monitoringMode; - + if (monitoringMode == MonitoringMode.Disabled) { m_readyToPublish = false; @@ -685,8 +690,8 @@ public IUserIdentity EffectiveIdentity private void IncrementSampleTime() { // update next sample time. - long now = DateTime.UtcNow.Ticks; - long samplingInterval = (long)(m_samplingInterval*TimeSpan.TicksPerMillisecond); + long now = DateTime.UtcNow.Ticks; + long samplingInterval = (long)(m_samplingInterval * TimeSpan.TicksPerMillisecond); if (m_nextSampleTime > 0) { @@ -694,7 +699,7 @@ private void IncrementSampleTime() if (samplingInterval > 0 && delta >= 0) { - m_nextSampleTime += ((delta/samplingInterval)+1)*samplingInterval; + m_nextSampleTime += ((delta / samplingInterval) + 1) * samplingInterval; } } @@ -757,15 +762,15 @@ public bool Publish(OperationContext context, Queue n return true; } } - + /// /// Publishes a value. /// private void Publish( - OperationContext context, + OperationContext context, DataValue value, ServiceResult error, - Queue notifications, + Queue notifications, Queue diagnostics) { // set semantics changed bit. @@ -779,7 +784,7 @@ private void Publish( if (error != null) { error = new ServiceResult( - error.StatusCode.SetSemanticsChanged(true), + error.StatusCode.SetSemanticsChanged(true), error.SymbolicId, error.NamespaceUri, error.LocalizedText, @@ -789,7 +794,7 @@ private void Publish( m_semanticsChanged = false; } - + // set structure changed bit. if (m_structureChanged) { @@ -801,7 +806,7 @@ private void Publish( if (error != null) { error = new ServiceResult( - error.StatusCode.SetStructureChanged(true), + error.StatusCode.SetStructureChanged(true), error.SymbolicId, error.NamespaceUri, error.LocalizedText, @@ -884,7 +889,7 @@ public void Dispose() private bool m_readyToTrigger; private bool m_alwaysReportUpdates; private bool m_semanticsChanged; - private bool m_structureChanged; + private bool m_structureChanged; private bool m_resendData; #endregion } diff --git a/Samples/Opc.Ua.Sample/Base/MonitoredItemQueue.cs b/Samples/Opc.Ua.Sample/Base/MonitoredItemQueue.cs index 4f0532fab..5804eec82 100644 --- a/Samples/Opc.Ua.Sample/Base/MonitoredItemQueue.cs +++ b/Samples/Opc.Ua.Sample/Base/MonitoredItemQueue.cs @@ -52,24 +52,24 @@ public MonitoredItemQueue() m_nextSampleTime = 0; m_samplingInterval = 0; } - + #region Public Methods /// /// Gets the current queue size. /// public uint QueueSize { - get + get { if (m_values == null) { return 0; } - return (uint)m_values.Length; + return (uint)m_values.Length; } } - + /// /// Gets number of elements actually contained in value queue. /// @@ -104,7 +104,7 @@ public void SetSamplingInterval(double samplingInterval) } // calculate the next sampling interval. - m_samplingInterval = (long)(samplingInterval*TimeSpan.TicksPerMillisecond); + m_samplingInterval = (long)(samplingInterval * TimeSpan.TicksPerMillisecond); if (m_samplingInterval > 0) { @@ -135,14 +135,14 @@ public void SetQueueSize(uint queueSize, bool discardOldest, DiagnosticsMasks di int end = m_end; // create new queue. - DataValue[] values = new DataValue[length]; + DataValue[] values = new DataValue[length]; ServiceResult[] errors = null; if ((diagnosticsMasks & DiagnosticsMasks.OperationAll) != 0) { errors = new ServiceResult[length]; } - + // copy existing values. List existingValues = null; List existingErrors = null; @@ -179,7 +179,7 @@ public void SetQueueSize(uint queueSize, bool discardOldest, DiagnosticsMasks di } } } - + /// /// Adds the value to the queue. /// @@ -194,11 +194,11 @@ public void QueueValue(DataValue value, ServiceResult error) // check if too soon for another sample. if (now < m_nextSampleTime) { - int last = m_end-1; + int last = m_end - 1; if (last < 0) { - last = m_values.Length-1; + last = m_values.Length - 1; } // replace last value and error. @@ -220,7 +220,7 @@ public void QueueValue(DataValue value, ServiceResult error) if (m_samplingInterval > 0 && delta >= 0) { - m_nextSampleTime += ((delta/m_samplingInterval)+1)*m_samplingInterval; + m_nextSampleTime += ((delta / m_samplingInterval) + 1) * m_samplingInterval; } } else @@ -243,7 +243,7 @@ public bool Publish(out DataValue value, out ServiceResult error) return Dequeue(out value, out error); } #endregion - + #region Private Methods /// /// Adds the value to the queue. Discards values if the queue is full. @@ -282,7 +282,7 @@ private void Enqueue(DataValue value, ServiceResult error) { if (!m_discardOldest) { - m_overflow = m_end-1; + m_overflow = m_end - 1; return; } @@ -306,7 +306,7 @@ private void Enqueue(DataValue value, ServiceResult error) m_errors[next] = error; } - m_end = next+1; + m_end = next + 1; } /// @@ -328,7 +328,7 @@ private bool Dequeue(out DataValue value, out ServiceResult error) value = m_values[m_start]; m_values[m_start] = null; - + if (m_errors != null) { error = m_errors[m_start]; @@ -343,7 +343,7 @@ private bool Dequeue(out DataValue value, out ServiceResult error) } m_start++; - + // check if queue has been emptied. if (m_start == m_end) { @@ -356,7 +356,7 @@ private bool Dequeue(out DataValue value, out ServiceResult error) { m_start = 0; } - + return true; } diff --git a/Samples/Opc.Ua.Sample/Base/SampleNodeManager.cs b/Samples/Opc.Ua.Sample/Base/SampleNodeManager.cs index cd0a03dbb..5ad6bef8a 100644 --- a/Samples/Opc.Ua.Sample/Base/SampleNodeManager.cs +++ b/Samples/Opc.Ua.Sample/Base/SampleNodeManager.cs @@ -31,7 +31,7 @@ using System.Collections.Generic; using System.Threading; using System.Reflection; -using Opc.Ua.Server; +using Opc.Ua.Server; using System.Linq; namespace Opc.Ua.Sample @@ -48,8 +48,8 @@ public class SampleNodeManager : INodeManager, INodeIdFactory, IDisposable public SampleNodeManager(IServerInternal server) { // save a reference to the server that owns the node manager. - m_server = server; - + m_server = server; + // create the default context. m_systemContext = m_server.DefaultSystemContext.Copy(); @@ -63,13 +63,13 @@ public SampleNodeManager(IServerInternal server) m_minimumSamplingInterval = 100; } #endregion - + #region IDisposable Members /// /// Frees any unmanaged resources. /// public void Dispose() - { + { Dispose(true); GC.SuppressFinalize(this); } @@ -78,7 +78,7 @@ public void Dispose() /// An overrideable version of the Dispose. /// protected virtual void Dispose(bool disposing) - { + { if (disposing) { lock (m_lock) @@ -314,11 +314,11 @@ protected void AddEncodeableNodeManagerTypes(Assembly assembly, string filter) /// public virtual IEnumerable NamespaceUris { - get - { - return m_namespaceUris; + get + { + return m_namespaceUris; } - + protected set { if (value != null) @@ -361,10 +361,10 @@ public virtual void CreateAddressSpace(IDictionary> ex /// Loads a node set from a file or resource and addes them to the set of predefined nodes. /// public virtual void LoadPredefinedNodes( - ISystemContext context, + ISystemContext context, Assembly assembly, string resourcePath, - IDictionary> externalReferences) + IDictionary> externalReferences) { // load the predefined nodes from an XML document. NodeStateCollection predefinedNodes = new NodeStateCollection(); @@ -392,8 +392,8 @@ protected virtual NodeStateCollection LoadPredefinedNodes(ISystemContext context /// Loads a node set from a file or resource and addes them to the set of predefined nodes. ///
protected virtual void LoadPredefinedNodes( - ISystemContext context, - IDictionary> externalReferences) + ISystemContext context, + IDictionary> externalReferences) { // load the predefined nodes from an XML document. NodeStateCollection predefinedNodes = LoadPredefinedNodes(context); @@ -413,8 +413,8 @@ protected virtual void LoadPredefinedNodes( /// protected virtual NodeState AddBehaviourToPredefinedNode(ISystemContext context, NodeState predefinedNode) { - BaseObjectState passiveNode = predefinedNode as BaseObjectState; - + BaseObjectState passiveNode = predefinedNode as BaseObjectState; + if (passiveNode == null) { return predefinedNode; @@ -430,7 +430,7 @@ protected virtual void AddPredefinedNode(ISystemContext context, NodeState node) { NodeState activeNode = AddBehaviourToPredefinedNode(context, node); m_predefinedNodes[activeNode.NodeId] = activeNode; - + BaseTypeState type = activeNode as BaseTypeState; if (type != null) @@ -451,8 +451,8 @@ protected virtual void AddPredefinedNode(ISystemContext context, NodeState node) /// Recursively indexes the node and its children. /// protected virtual void RemovePredefinedNode( - ISystemContext context, - NodeState node, + ISystemContext context, + NodeState node, List referencesToRemove) { m_predefinedNodes.Remove(node.NodeId); @@ -481,7 +481,7 @@ protected virtual void RemovePredefinedNode( { RemovePredefinedNode(context, children[ii], referencesToRemove); } - + // remove from type table. BaseTypeState type = node as BaseTypeState; @@ -489,7 +489,7 @@ protected virtual void RemovePredefinedNode( { m_server.TypeTree.Remove(type.NodeId); } - + // remove inverse references. List references = new List(); node.GetReferences(context, references); @@ -579,8 +579,8 @@ protected virtual void AddReverseReferences(IDictionary - protected virtual object GetManagerHandle(ISystemContext context, NodeId nodeId, IDictionary cache) + protected virtual object GetManagerHandle(ISystemContext context, NodeId nodeId, IDictionary cache) { lock (Lock) { @@ -836,15 +836,15 @@ public virtual void AddReferences(IDictionary> referen } } } - + /// /// This method is used to delete bi-directional references to nodes from other node managers. /// public virtual ServiceResult DeleteReference( - object sourceHandle, - NodeId referenceTypeId, - bool isInverse, - ExpandedNodeId targetId, + object sourceHandle, + NodeId referenceTypeId, + bool isInverse, + ExpandedNodeId targetId, bool deleteBidirectional) { lock (Lock) @@ -884,8 +884,8 @@ public virtual ServiceResult DeleteReference( /// This method validates any placeholder handle. /// public virtual NodeMetadata GetNodeMetadata( - OperationContext context, - object targetHandle, + OperationContext context, + object targetHandle, BrowseResultMask resultMask) { ServerSystemContext systemContext = m_systemContext.Copy(context); @@ -897,7 +897,7 @@ public virtual NodeMetadata GetNodeMetadata( if (target == null) { - return null; + return null; } // validate node. @@ -941,7 +941,7 @@ public virtual NodeMetadata GetNodeMetadata( } metadata.ArrayDimensions = (IList)values[4]; - + if (values[5] != null && values[6] != null) { metadata.AccessLevel = (byte)(((byte)values[5]) & ((byte)values[6])); @@ -979,8 +979,8 @@ public virtual NodeMetadata GetNodeMetadata( /// The node manager can store its state information in the Data and Index properties. /// public virtual void Browse( - OperationContext context, - ref ContinuationPoint continuationPoint, + OperationContext context, + ref ContinuationPoint continuationPoint, IList references) { if (continuationPoint == null) throw new ArgumentNullException(nameof(continuationPoint)); @@ -1152,14 +1152,14 @@ private ReferenceDescription GetReferenceDescription( /// browse name. /// public virtual void TranslateBrowsePath( - OperationContext context, - object sourceHandle, - RelativePathElement relativePath, - IList targetIds, - IList unresolvedTargetIds) + OperationContext context, + object sourceHandle, + RelativePathElement relativePath, + IList targetIds, + IList unresolvedTargetIds) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); lock (Lock) { @@ -1246,25 +1246,25 @@ public virtual void TranslateBrowsePath( } } } - + /// /// Reads the value for the specified attribute. /// public virtual void Read( - OperationContext context, - double maxAge, - IList nodesToRead, - IList values, + OperationContext context, + double maxAge, + IList nodesToRead, + IList values, IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToValidate = new List(); lock (Lock) { for (int ii = 0; ii < nodesToRead.Count; ii++) - { + { ReadValueId nodeToRead = nodesToRead[ii]; // skip items that have already been processed. @@ -1272,7 +1272,7 @@ public virtual void Read( { continue; } - + // check for valid handle. NodeState source = GetManagerHandle(systemContext, nodeToRead.NodeId, operationCache) as NodeState; @@ -1283,28 +1283,28 @@ public virtual void Read( // owned by this node manager. nodeToRead.Processed = true; - + // create an initial value. DataValue value = values[ii] = new DataValue(); - - value.Value = null; + + value.Value = null; value.ServerTimestamp = DateTime.UtcNow; value.SourceTimestamp = DateTime.MinValue; - value.StatusCode = StatusCodes.Good; + value.StatusCode = StatusCodes.Good; // check if the node is ready for reading. if (source.ValidationRequired) { errors[ii] = StatusCodes.BadNodeIdUnknown; - + // must validate node in a seperate operation. ReadWriteOperationState operation = new ReadWriteOperationState(); - + operation.Source = source; operation.Index = ii; nodesToValidate.Add(operation); - + continue; } @@ -1332,7 +1332,7 @@ public virtual void Read( { continue; } - + ReadValueId nodeToRead = nodesToRead[operation.Index]; DataValue value = values[operation.Index]; @@ -1345,8 +1345,8 @@ public virtual void Read( value); } } - } - + } + /// /// Stores the state of a call method operation. /// @@ -1354,8 +1354,8 @@ private struct ReadWriteOperationState { public NodeState Source; public int Index; - } - + } + /// /// Verifies that the specified node exists. /// @@ -1369,28 +1369,28 @@ protected virtual bool ValidateNode(ServerSystemContext context, NodeState node) return true; } - + /// /// Reads the history for the specified nodes. /// public virtual void HistoryRead( - OperationContext context, - HistoryReadDetails details, - TimestampsToReturn timestampsToReturn, - bool releaseContinuationPoints, - IList nodesToRead, - IList results, - IList errors) + OperationContext context, + HistoryReadDetails details, + TimestampsToReturn timestampsToReturn, + bool releaseContinuationPoints, + IList nodesToRead, + IList results, + IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToValidate = new List(); List readsToComplete = new List(); lock (Lock) { for (int ii = 0; ii < nodesToRead.Count; ii++) - { + { HistoryReadValueId nodeToRead = nodesToRead[ii]; // skip items that have already been processed. @@ -1398,7 +1398,7 @@ public virtual void HistoryRead( { continue; } - + // check for valid handle. NodeState source = GetManagerHandle(systemContext, nodeToRead.NodeId, operationCache) as NodeState; @@ -1418,11 +1418,11 @@ public virtual void HistoryRead( errors[ii] = StatusCodes.BadHistoryOperationUnsupported; continue; } - + results[ii] = new HistoryReadResult(); - + ReadWriteOperationState operation = new ReadWriteOperationState(); - + operation.Source = source; operation.Index = ii; @@ -1431,7 +1431,7 @@ public virtual void HistoryRead( { // must validate node in a seperate operation. errors[ii] = StatusCodes.BadNodeIdUnknown; - nodesToValidate.Add(operation); + nodesToValidate.Add(operation); continue; } @@ -1473,13 +1473,13 @@ public virtual void HistoryRead( /// Reads the history for a single node which has already been validated. /// protected virtual ServiceResult HistoryRead( - ISystemContext context, - NodeState source, - HistoryReadDetails details, - TimestampsToReturn timestampsToReturn, - bool releaseContinuationPoints, - HistoryReadValueId nodesToRead, - HistoryReadResult result) + ISystemContext context, + NodeState source, + HistoryReadDetails details, + TimestampsToReturn timestampsToReturn, + bool releaseContinuationPoints, + HistoryReadValueId nodesToRead, + HistoryReadResult result) { // check for variable. BaseVariableState variable = source as BaseVariableState; @@ -1542,72 +1542,72 @@ protected virtual ServiceResult HistoryRead( nodesToRead, result); } - + return StatusCodes.BadHistoryOperationUnsupported; } - + /// /// Reads the raw history for the variable value. /// protected virtual ServiceResult HistoryReadRaw( - ISystemContext context, - BaseVariableState source, - ReadRawModifiedDetails details, - TimestampsToReturn timestampsToReturn, - bool releaseContinuationPoints, - HistoryReadValueId nodeToRead, - HistoryReadResult result) + ISystemContext context, + BaseVariableState source, + ReadRawModifiedDetails details, + TimestampsToReturn timestampsToReturn, + bool releaseContinuationPoints, + HistoryReadValueId nodeToRead, + HistoryReadResult result) { return StatusCodes.BadHistoryOperationUnsupported; } - + /// /// Reads the processed history for the variable value. /// protected virtual ServiceResult HistoryReadProcessed( - ISystemContext context, - BaseVariableState source, - ReadProcessedDetails details, - TimestampsToReturn timestampsToReturn, - bool releaseContinuationPoints, - HistoryReadValueId nodeToRead, - HistoryReadResult result) + ISystemContext context, + BaseVariableState source, + ReadProcessedDetails details, + TimestampsToReturn timestampsToReturn, + bool releaseContinuationPoints, + HistoryReadValueId nodeToRead, + HistoryReadResult result) { return StatusCodes.BadHistoryOperationUnsupported; } - + /// /// Reads the history for the variable value. /// protected virtual ServiceResult HistoryReadAtTime( - ISystemContext context, - BaseVariableState source, - ReadAtTimeDetails details, - TimestampsToReturn timestampsToReturn, - bool releaseContinuationPoints, - HistoryReadValueId nodeToRead, - HistoryReadResult result) + ISystemContext context, + BaseVariableState source, + ReadAtTimeDetails details, + TimestampsToReturn timestampsToReturn, + bool releaseContinuationPoints, + HistoryReadValueId nodeToRead, + HistoryReadResult result) { return StatusCodes.BadHistoryOperationUnsupported; } - - + + /// /// Writes the value for the specified attributes. /// public virtual void Write( - OperationContext context, - IList nodesToWrite, + OperationContext context, + IList nodesToWrite, IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToValidate = new List(); lock (Lock) { for (int ii = 0; ii < nodesToWrite.Count; ii++) - { + { WriteValue nodeToWrite = nodesToWrite[ii]; // skip items that have already been processed. @@ -1615,7 +1615,7 @@ public virtual void Write( { continue; } - + // check for valid handle. NodeState source = GetManagerHandle(systemContext, nodeToWrite.NodeId, operationCache) as NodeState; @@ -1633,20 +1633,20 @@ public virtual void Write( errors[ii] = StatusCodes.BadWriteNotSupported; continue; } - + // check if the node is ready for reading. if (source.ValidationRequired) { errors[ii] = StatusCodes.BadNodeIdUnknown; - + // must validate node in a seperate operation. ReadWriteOperationState operation = new ReadWriteOperationState(); - + operation.Source = source; operation.Index = ii; nodesToValidate.Add(operation); - + continue; } @@ -1676,7 +1676,7 @@ public virtual void Write( { continue; } - + WriteValue nodeToWrite = nodesToWrite[operation.Index]; // write the attribute value. @@ -1691,25 +1691,25 @@ public virtual void Write( } } } - + /// /// Updates the history for the specified nodes. /// public virtual void HistoryUpdate( - OperationContext context, - Type detailsType, - IList nodesToUpdate, - IList results, - IList errors) + OperationContext context, + Type detailsType, + IList nodesToUpdate, + IList results, + IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToValidate = new List(); lock (Lock) { for (int ii = 0; ii < nodesToUpdate.Count; ii++) - { + { HistoryUpdateDetails nodeToUpdate = nodesToUpdate[ii]; // skip items that have already been processed. @@ -1717,7 +1717,7 @@ public virtual void HistoryUpdate( { continue; } - + // check for valid handle. NodeState source = GetManagerHandle(systemContext, nodeToUpdate.NodeId, operationCache) as NodeState; @@ -1728,20 +1728,20 @@ public virtual void HistoryUpdate( // owned by this node manager. nodeToUpdate.Processed = true; - + // check if the node is ready for reading. if (source.ValidationRequired) { errors[ii] = StatusCodes.BadNodeIdUnknown; - + // must validate node in a seperate operation. ReadWriteOperationState operation = new ReadWriteOperationState(); - + operation.Source = source; operation.Index = ii; nodesToValidate.Add(operation); - + continue; } @@ -1764,7 +1764,7 @@ public virtual void HistoryUpdate( { continue; } - + // historical data not available. errors[ii] = StatusCodes.BadHistoryOperationUnsupported; } @@ -1775,19 +1775,19 @@ public virtual void HistoryUpdate( /// Calls a method on the specified nodes. /// public virtual void Call( - OperationContext context, - IList methodsToCall, - IList results, - IList errors) + OperationContext context, + IList methodsToCall, + IList results, + IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToValidate = new List(); lock (Lock) { for (int ii = 0; ii < methodsToCall.Count; ii++) - { + { CallMethodRequest methodToCall = methodsToCall[ii]; // skip items that have already been processed. @@ -1795,7 +1795,7 @@ public virtual void Call( { continue; } - + // check for valid handle. NodeState source = GetManagerHandle(systemContext, methodToCall.ObjectId, operationCache) as NodeState; @@ -1831,10 +1831,10 @@ public virtual void Call( if (source.ValidationRequired) { errors[ii] = StatusCodes.BadNodeIdUnknown; - + // must validate node in a seperate operation. CallOperationState operation = new CallOperationState(); - + operation.Source = source; operation.Method = method; operation.Index = ii; @@ -1843,7 +1843,7 @@ public virtual void Call( continue; } - + // call the method. errors[ii] = Call( systemContext, @@ -1852,7 +1852,7 @@ public virtual void Call( method, result); } - + // check for nothing to do. if (nodesToValidate.Count == 0) { @@ -1869,7 +1869,7 @@ public virtual void Call( { continue; } - + // call the method. CallMethodResult result = results[operation.Index]; @@ -1882,7 +1882,7 @@ public virtual void Call( } } } - + /// /// Stores the state of a call method operation. /// @@ -1892,7 +1892,7 @@ private struct CallOperationState public MethodState Method; public int Index; } - + /// /// Calls a method on an object. /// @@ -1929,7 +1929,7 @@ protected virtual ServiceResult Call( if (argumentError != null) { result.InputArgumentResults.Add(argumentError.StatusCode); - + if (ServiceResult.IsBad(argumentError)) { argumentsValid = false; @@ -1980,11 +1980,11 @@ protected virtual ServiceResult Call( /// the notifier hierarchy. /// public virtual ServiceResult SubscribeToEvents( - OperationContext context, - object sourceId, - uint subscriptionId, - IEventMonitoredItem monitoredItem, - bool unsubscribe) + OperationContext context, + object sourceId, + uint subscriptionId, + IEventMonitoredItem monitoredItem, + bool unsubscribe) { ServerSystemContext systemContext = m_systemContext.Copy(context); @@ -2036,7 +2036,7 @@ public virtual ServiceResult SubscribeToEvents( return ServiceResult.Good; } } - + /// /// Subscribes or unsubscribes to events produced by all event sources. /// @@ -2045,10 +2045,10 @@ public virtual ServiceResult SubscribeToEvents( /// manager must start/stop reporting events for all objects that it manages. /// public virtual ServiceResult SubscribeToAllEvents( - OperationContext context, - uint subscriptionId, - IEventMonitoredItem monitoredItem, - bool unsubscribe) + OperationContext context, + uint subscriptionId, + IEventMonitoredItem monitoredItem, + bool unsubscribe) { ServerSystemContext systemContext = m_systemContext.Copy(context); @@ -2072,10 +2072,10 @@ public virtual ServiceResult SubscribeToAllEvents( /// Subscribes/unsubscribes to all events produced by the specified node. /// protected void SubscribeToAllEvents( - ISystemContext systemContext, - IEventMonitoredItem monitoredItem, - bool unsubscribe, - NodeState source) + ISystemContext systemContext, + IEventMonitoredItem monitoredItem, + bool unsubscribe, + NodeState source) { MonitoredNode monitoredNode = source.Handle as MonitoredNode; @@ -2135,7 +2135,7 @@ protected virtual void OnUnsubscribeToEvents( /// The node manager must create a refresh event for each condition monitored by the subscription. /// public virtual ServiceResult ConditionRefresh( - OperationContext context, + OperationContext context, IList monitoredItems) { ServerSystemContext systemContext = m_systemContext.Copy(context); @@ -2150,7 +2150,7 @@ public virtual ServiceResult ConditionRefresh( { continue; } - + // check for global subscription. if (monitoredItem.MonitoringAllEvents) { @@ -2170,20 +2170,20 @@ public virtual ServiceResult ConditionRefresh( // check for subscription to local node. else { - NodeState source = IsHandleInNamespace(monitoredItem.ManagerHandle ); + NodeState source = IsHandleInNamespace(monitoredItem.ManagerHandle); if (source == null) { continue; } - + MonitoredNode monitoredNode = source.Handle as MonitoredNode; - + if (monitoredNode == null) { continue; } - + monitoredNode.ConditionRefresh(systemContext, monitoredItem); } } @@ -2199,25 +2199,25 @@ public virtual ServiceResult ConditionRefresh( /// This method only handles data change subscriptions. Event subscriptions are created by the SDK. /// public virtual void CreateMonitoredItems( - OperationContext context, - uint subscriptionId, - double publishingInterval, - TimestampsToReturn timestampsToReturn, - IList itemsToCreate, - IList errors, - IList filterErrors, - IList monitoredItems, - bool createDurable, - ref long globalIdCounter) + OperationContext context, + uint subscriptionId, + double publishingInterval, + TimestampsToReturn timestampsToReturn, + IList itemsToCreate, + IList errors, + IList filterErrors, + IList monitoredItems, + bool createDurable, + ref long globalIdCounter) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToValidate = new List(); lock (Lock) { for (int ii = 0; ii < itemsToCreate.Count; ii++) - { + { MonitoredItemCreateRequest itemToCreate = itemsToCreate[ii]; // skip items that have already been processed. @@ -2227,7 +2227,7 @@ public virtual void CreateMonitoredItems( } ReadValueId itemToMonitor = itemToCreate.ItemToMonitor; - + // check for valid handle. NodeState source = GetManagerHandle(systemContext, itemToMonitor.NodeId, operationCache) as NodeState; @@ -2243,10 +2243,10 @@ public virtual void CreateMonitoredItems( if (source.ValidationRequired) { errors[ii] = StatusCodes.BadNodeIdUnknown; - + // must validate node in a seperate operation. ReadWriteOperationState operation = new ReadWriteOperationState(); - + operation.Source = source; operation.Index = ii; @@ -2281,7 +2281,7 @@ public virtual void CreateMonitoredItems( // save the monitored item. monitoredItems[ii] = monitoredItem; } - + // check for nothing to do. if (nodesToValidate.Count == 0) { @@ -2298,7 +2298,7 @@ public virtual void CreateMonitoredItems( { continue; } - + MonitoredItemCreateRequest itemToCreate = itemsToCreate[operation.Index]; MonitoringFilterResult filterError = null; @@ -2399,7 +2399,7 @@ protected ServiceResult ValidateDataChangeFilter( // only supported for variables. BaseVariableState variable = source as BaseVariableState; - + if (variable == null) { return StatusCodes.BadMonitoredItemFilterUnsupported; @@ -2415,7 +2415,7 @@ protected ServiceResult ValidateDataChangeFilter( return StatusCodes.BadMonitoredItemFilterUnsupported; } } - + // validate filter. ServiceResult error = filter.Validate(); @@ -2424,7 +2424,7 @@ protected ServiceResult ValidateDataChangeFilter( return error; } - if (filter.DeadbandType ==(uint)DeadbandType.Percent) + if (filter.DeadbandType == (uint)DeadbandType.Percent) { BaseVariableState euRange = variable.FindChild(context, BrowseNames.EURange) as BaseVariableState; @@ -2434,7 +2434,7 @@ protected ServiceResult ValidateDataChangeFilter( } range = euRange.Value as Range; - + if (range == null) { return StatusCodes.BadMonitoredItemFilterUnsupported; @@ -2466,7 +2466,7 @@ protected virtual ServiceResult CreateMonitoredItem( filterError = null; monitoredItem = null; ServiceResult error = null; - + // read initial value. DataValue initialValue = new DataValue { Value = null, @@ -2494,7 +2494,7 @@ protected virtual ServiceResult CreateMonitoredItem( initialValue.StatusCode = error.StatusCode; error = ServiceResult.Good; } - + // validate parameters. MonitoringParameters parameters = itemToCreate.RequestedParameters; @@ -2598,14 +2598,14 @@ private double CalculateSamplingInterval(BaseVariableState variable, double samp if ((samplingInterval % m_minimumSamplingInterval) != 0) { - samplingInterval = Math.Truncate(samplingInterval/m_minimumSamplingInterval); + samplingInterval = Math.Truncate(samplingInterval / m_minimumSamplingInterval); samplingInterval += 1; samplingInterval *= m_minimumSamplingInterval; } return samplingInterval; } - + /// /// Creates a new sampled item. /// @@ -2618,7 +2618,7 @@ private void CreateSampledItem(double samplingInterval, DataChangeMonitoredItem m_samplingTimer = new Timer(DoSample, null, (int)m_minimumSamplingInterval, (int)m_minimumSamplingInterval); } } - + /// /// Deletes a sampled item. /// @@ -2675,7 +2675,7 @@ private void DoSample(object state) protected virtual void OnCreateMonitoredItem( ISystemContext systemContext, MonitoredItemCreateRequest itemToCreate, - MonitoredNode monitoredNode, + MonitoredNode monitoredNode, DataChangeMonitoredItem monitoredItem) { // does nothing. @@ -2685,19 +2685,19 @@ protected virtual void OnCreateMonitoredItem( /// Modifies the parameters for a set of monitored items. /// public virtual void ModifyMonitoredItems( - OperationContext context, - TimestampsToReturn timestampsToReturn, - IList monitoredItems, - IList itemsToModify, - IList errors, - IList filterErrors) + OperationContext context, + TimestampsToReturn timestampsToReturn, + IList monitoredItems, + IList itemsToModify, + IList errors, + IList filterErrors) { ServerSystemContext systemContext = m_systemContext.Copy(context); lock (Lock) { for (int ii = 0; ii < monitoredItems.Count; ii++) - { + { MonitoredItemModifyRequest itemToModify = itemsToModify[ii]; // skip items that have already been processed. @@ -2780,7 +2780,7 @@ protected virtual ServiceResult ModifyMonitoredItem( } double previousSamplingInterval = datachangeItem.SamplingInterval; - + // check if the variable needs to be sampled. double samplingInterval = itemToModify.RequestedParameters.SamplingInterval; @@ -2807,9 +2807,9 @@ protected virtual ServiceResult ModifyMonitoredItem( // do any post processing. OnModifyMonitoredItem( - context, - itemToModify, - monitoredNode, + context, + itemToModify, + monitoredNode, datachangeItem, previousSamplingInterval); @@ -2833,9 +2833,9 @@ protected virtual void OnModifyMonitoredItem( /// Deletes a set of monitored items. /// public virtual void DeleteMonitoredItems( - OperationContext context, - IList monitoredItems, - IList processedItems, + OperationContext context, + IList monitoredItems, + IList processedItems, IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); @@ -2895,7 +2895,7 @@ protected virtual ServiceResult DeleteMonitoredItem( // check for valid monitored item. DataChangeMonitoredItem datachangeItem = monitoredItem as DataChangeMonitoredItem; - + // check if the variable needs to be sampled. if (datachangeItem.AttributeId == Attributes.Value) { @@ -2996,10 +2996,10 @@ IList monitoredItems /// Changes the monitoring mode for a set of monitored items. /// public virtual void SetMonitoringMode( - OperationContext context, - MonitoringMode monitoringMode, - IList monitoredItems, - IList processedItems, + OperationContext context, + MonitoringMode monitoringMode, + IList monitoredItems, + IList processedItems, IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); @@ -3035,7 +3035,7 @@ public virtual void SetMonitoringMode( protected virtual ServiceResult SetMonitoringMode( ISystemContext context, IMonitoredItem monitoredItem, - MonitoringMode monitoringMode, + MonitoringMode monitoringMode, out bool processed) { processed = false; @@ -3067,7 +3067,7 @@ protected virtual ServiceResult SetMonitoringMode( { ReadInitialValue(context, monitoredNode, datachangeItem, false); } - + // do any post processing. OnSetMonitoringMode(context, monitoredNode, datachangeItem, previousMode, monitoringMode); @@ -3101,7 +3101,7 @@ public void RestoreMonitoredItems(IList itemsToRestore, IL private ushort[] m_namespaceIndexes; private NodeIdDictionary m_predefinedNodes; private List m_rootNotifiers; - + private Timer m_samplingTimer; private List m_sampledItems; private double m_minimumSamplingInterval; diff --git a/Samples/Opc.Ua.Sample/Boiler/BoilerState.cs b/Samples/Opc.Ua.Sample/Boiler/BoilerState.cs index 5ca5f202c..f831a2c99 100644 --- a/Samples/Opc.Ua.Sample/Boiler/BoilerState.cs +++ b/Samples/Opc.Ua.Sample/Boiler/BoilerState.cs @@ -49,7 +49,7 @@ protected override void OnAfterCreate(ISystemContext context, NodeState node) m_random = new Random(); } #endregion - + #region IDisposeable Methods /// /// Cleans up when the object is disposed. @@ -66,7 +66,7 @@ protected override void Dispose(bool disposing) } } #endregion - + #region Private Methods /// /// Changes the state of the simulation. @@ -110,7 +110,7 @@ private ServiceResult OnControlSimulation( m_simulationTimer.Dispose(); m_simulationTimer = null; } - + m_simulationContext = context; break; } @@ -122,15 +122,15 @@ private ServiceResult OnControlSimulation( m_simulationTimer.Dispose(); m_simulationTimer = null; } - + m_simulationContext = context; break; } } - + return ServiceResult.Good; } - + /// /// Rounds a value to the significate digits specified and adds a random perturbation. /// @@ -150,20 +150,20 @@ private double RoundAndPerturb(double value, byte significantDigits) offsetToApply -= 1; } } - + // round value to significant digits. double perturbedValue = Math.Round(value * Math.Pow(10.0, offsetToApply)); - + // apply the perturbation. - perturbedValue += (m_random.NextDouble()-0.5)*5; + perturbedValue += (m_random.NextDouble() - 0.5) * 5; // restore original exponent. - perturbedValue = Math.Round(perturbedValue)*Math.Pow(10.0, -offsetToApply); + perturbedValue = Math.Round(perturbedValue) * Math.Pow(10.0, -offsetToApply); // return value. return perturbedValue; } - + /// /// Moves the value towards the target. /// @@ -174,7 +174,7 @@ private double Adjust(double value, double target, double step, Opc.Ua.Range ran { step = step * range.Magnitude; } - + double difference = target - value; if (difference < 0) @@ -183,7 +183,7 @@ private double Adjust(double value, double target, double step, Opc.Ua.Range ran if (value < target) { - return target; + return target; } } else @@ -192,13 +192,13 @@ private double Adjust(double value, double target, double step, Opc.Ua.Range ran if (value > target) { - return target; + return target; } } return value; } - + /// /// Returns the value as a percentage of the range. /// @@ -219,7 +219,7 @@ private double GetPercentage(AnalogItemState value) return percentage; } - + /// /// Returns the value as a percentage of the range. /// @@ -242,37 +242,37 @@ private void DoSimulation(object state) { // adjust level. m_drum.LevelIndicator.Output.Value = Adjust( - m_drum.LevelIndicator.Output.Value, - m_levelController.SetPoint.Value, - 0.1, + m_drum.LevelIndicator.Output.Value, + m_levelController.SetPoint.Value, + 0.1, m_drum.LevelIndicator.Output.EURange.Value); - + // calculate inputs for custom controller. m_customController.Input1.Value = m_levelController.UpdateMeasurement(m_drum.LevelIndicator.Output); m_customController.Input2.Value = GetPercentage(m_inputPipe.FlowTransmitter1.Output); m_customController.Input3.Value = GetPercentage(m_outputPipe.FlowTransmitter2.Output); - + // calculate output for custom controller. - m_customController.ControlOut.Value = (m_customController.Input1.Value + m_customController.Input3.Value - m_customController.Input2.Value)/2; - + m_customController.ControlOut.Value = (m_customController.Input1.Value + m_customController.Input3.Value - m_customController.Input2.Value) / 2; + // update flow controller set point. - m_flowController.SetPoint.Value = GetValue((m_customController.ControlOut.Value+1)/2, m_inputPipe.FlowTransmitter1.Output.EURange.Value); - + m_flowController.SetPoint.Value = GetValue((m_customController.ControlOut.Value + 1) / 2, m_inputPipe.FlowTransmitter1.Output.EURange.Value); + double error = m_flowController.UpdateMeasurement(m_inputPipe.FlowTransmitter1.Output); - + // adjust the input valve. - m_inputPipe.Valve.Input.Value = Adjust(m_inputPipe.Valve.Input.Value, (error>0)?100:0, 10, null); - + m_inputPipe.Valve.Input.Value = Adjust(m_inputPipe.Valve.Input.Value, (error > 0) ? 100 : 0, 10, null); + // adjust the input flow. m_inputPipe.FlowTransmitter1.Output.Value = Adjust( - m_inputPipe.FlowTransmitter1.Output.Value, - m_flowController.SetPoint.Value, - 0.6, + m_inputPipe.FlowTransmitter1.Output.Value, + m_flowController.SetPoint.Value, + 0.6, m_inputPipe.FlowTransmitter1.Output.EURange.Value); - + // add pertubations. - m_drum.LevelIndicator.Output.Value = RoundAndPerturb(m_drum.LevelIndicator.Output.Value, 3); - m_inputPipe.FlowTransmitter1.Output.Value = RoundAndPerturb(m_inputPipe.FlowTransmitter1.Output.Value, 3); + m_drum.LevelIndicator.Output.Value = RoundAndPerturb(m_drum.LevelIndicator.Output.Value, 3); + m_inputPipe.FlowTransmitter1.Output.Value = RoundAndPerturb(m_inputPipe.FlowTransmitter1.Output.Value, 3); m_outputPipe.FlowTransmitter2.Output.Value = RoundAndPerturb(m_outputPipe.FlowTransmitter2.Output.Value, 3); this.ClearChangeMasks(m_simulationContext, true); diff --git a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferBrowser.cs b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferBrowser.cs index 275f7bc10..eeda438ea 100644 --- a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferBrowser.cs +++ b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferBrowser.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -39,7 +39,7 @@ namespace MemoryBuffer { /// - /// A class to browse the references for a memory buffer. + /// A class to browse the references for a memory buffer. /// public class MemoryBufferBrowser : NodeBrowser { @@ -104,7 +104,7 @@ public override IReference Next() { return null; } - + // enumerate components. if (m_stage == Stage.Components) { @@ -162,7 +162,7 @@ private IReference NextChild() } m_position = Convert.ToUInt32(name, 16); - + // check for memory overflow. if (m_position >= m_buffer.SizeInBytes.Value) { diff --git a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferConfiguration.cs b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferConfiguration.cs index aaf3c00a4..a0fe44fe4 100644 --- a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferConfiguration.cs +++ b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferConfiguration.cs @@ -119,7 +119,7 @@ private void Initialize() m_dataType = null; } #endregion - + #region Public Properties /// /// The browse name for the instance. @@ -158,7 +158,7 @@ public string DataType private string m_dataType; #endregion } - + #region MemoryBufferInstanceCollection Class /// /// A collection of MemoryBufferInstances. diff --git a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferMonitoredItem.cs b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferMonitoredItem.cs index 09737394a..dcec8d76c 100644 --- a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferMonitoredItem.cs +++ b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferMonitoredItem.cs @@ -40,28 +40,28 @@ namespace MemoryBuffer /// public class MemoryBufferMonitoredItem : MonitoredItem { - /// - /// Initializes the object with its node type. - /// + /// + /// Initializes the object with its node type. + /// public MemoryBufferMonitoredItem( - IServerInternal server, - INodeManager nodeManager, - object mangerHandle, - uint offset, - uint subscriptionId, - uint id, - ReadValueId itemToMonitor, - DiagnosticsMasks diagnosticsMasks, - TimestampsToReturn timestampsToReturn, - MonitoringMode monitoringMode, - uint clientHandle, - MonitoringFilter originalFilter, - MonitoringFilter filterToUse, - Opc.Ua.Range range, - double samplingInterval, - uint queueSize, - bool discardOldest, - double minimumSamplingInterval) + IServerInternal server, + INodeManager nodeManager, + object mangerHandle, + uint offset, + uint subscriptionId, + uint id, + ReadValueId itemToMonitor, + DiagnosticsMasks diagnosticsMasks, + TimestampsToReturn timestampsToReturn, + MonitoringMode monitoringMode, + uint clientHandle, + MonitoringFilter originalFilter, + MonitoringFilter filterToUse, + Opc.Ua.Range range, + double samplingInterval, + uint queueSize, + bool discardOldest, + double minimumSamplingInterval) : base( server, @@ -81,7 +81,7 @@ public MemoryBufferMonitoredItem( queueSize, discardOldest, minimumSamplingInterval) - { + { m_offset = offset; } @@ -115,7 +115,7 @@ public uint Offset return m_offset; } } - + private uint m_offset; /* diff --git a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferNodeManager.cs b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferNodeManager.cs index ab653fdfc..592f15ff6 100644 --- a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferNodeManager.cs +++ b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferNodeManager.cs @@ -80,7 +80,7 @@ public MemoryBufferNodeManager(IServerInternal server, ApplicationConfiguration base(server) { NamespaceUris = namespaceUris; - + AddEncodeableNodeManagerTypes(typeof(MemoryBufferNodeManager).Assembly, typeof(MemoryBufferNodeManager).Namespace); // get the configuration for the node manager. @@ -110,14 +110,14 @@ public override void CreateAddressSpace(IDictionary> e lock (Lock) { base.CreateAddressSpace(externalReferences); - + // create the nodes from configuration. ushort namespaceIndex = Server.NamespaceUris.GetIndexOrAppend(Namespaces.MemoryBuffer); BaseInstanceState root = (BaseInstanceState)FindPredefinedNode( - new NodeId(Objects.MemoryBuffers, namespaceIndex), + new NodeId(Objects.MemoryBuffers, namespaceIndex), typeof(BaseInstanceState)); - + // create the nodes from configuration. namespaceIndex = Server.NamespaceUris.GetIndexOrAppend(Namespaces.MemoryBuffer + "/Instance"); @@ -132,12 +132,12 @@ public override void CreateAddressSpace(IDictionary> e // assign node ids. bufferNode.Create( - SystemContext, - new NodeId(bufferNode.SymbolicName, namespaceIndex), + SystemContext, + new NodeId(bufferNode.SymbolicName, namespaceIndex), new QualifiedName(bufferNode.SymbolicName, namespaceIndex), - null, + null, true); - + bufferNode.CreateBuffer(instance.DataType, instance.TagCount); bufferNode.InitializeMonitoring(Server, this); @@ -180,7 +180,7 @@ public override void DeleteAddressSpace() /// NodeManager it should return a handle that does not require the NodeId to be validated again when /// the handle is passed into other methods such as 'Read' or 'Write'. /// - protected override object GetManagerHandle(ISystemContext context, NodeId nodeId, IDictionary cache) + protected override object GetManagerHandle(ISystemContext context, NodeId nodeId, IDictionary cache) { lock (Lock) { @@ -195,14 +195,14 @@ protected override object GetManagerHandle(ISystemContext context, NodeId nodeId { // check for a reference to the buffer. MemoryBufferState buffer = null; - + if (m_buffers.TryGetValue(id, out buffer)) { return buffer; } // tag ids have the syntax [
] - if (id[id.Length-1] != ']') + if (id[id.Length - 1] != ']') { return null; } @@ -223,7 +223,7 @@ protected override object GetManagerHandle(ISystemContext context, NodeId nodeId } // validate the address. - string offsetText = id.Substring(index+1, id.Length-index-2); + string offsetText = id.Substring(index + 1, id.Length - index - 2); for (int ii = 0; ii < offsetText.Length; ii++) { @@ -240,7 +240,7 @@ protected override object GetManagerHandle(ISystemContext context, NodeId nodeId { return null; } - + // the tags contain all of the metadata required to support the UA // operations and pointers to functions in the buffer object that // allow the value to be accessed. These tags are ephemeral and are @@ -303,7 +303,7 @@ protected override ServiceResult CreateMonitoredItem( { return StatusCodes.BadFilterNotAllowed; } - + // index range not supported. if (itemToCreate.ItemToMonitor.ParsedIndexRange != NumericRange.Empty) { @@ -354,7 +354,7 @@ protected override ServiceResult CreateMonitoredItem( { samplingInterval = publishingInterval; } - + // create the item. MemoryBufferMonitoredItem datachangeItem = buffer.CreateDataChangeItem( context as ServerSystemContext, @@ -434,7 +434,7 @@ protected override ServiceResult ModifyMonitoredItem( itemToModify.RequestedParameters.SamplingInterval); return ServiceResult.Good; - } + } /// /// Deletes a monitored item. @@ -480,7 +480,7 @@ protected override ServiceResult DeleteMonitoredItem( protected override ServiceResult SetMonitoringMode( ISystemContext context, IMonitoredItem monitoredItem, - MonitoringMode monitoringMode, + MonitoringMode monitoringMode, out bool processed) { processed = false; @@ -510,7 +510,7 @@ protected override ServiceResult SetMonitoringMode( // delete the item. MonitoringMode previousMode = datachangeItem.SetMonitoringMode(monitoringMode); - + // need to provide an immediate update after enabling. if (previousMode == MonitoringMode.Disabled && monitoringMode != MonitoringMode.Disabled) { @@ -520,7 +520,7 @@ protected override ServiceResult SetMonitoringMode( initialValue.ServerTimestamp = DateTime.UtcNow; initialValue.SourceTimestamp = DateTime.MinValue; initialValue.StatusCode = StatusCodes.Good; - + MemoryTagState tag = new MemoryTagState(buffer, datachangeItem.Offset); ServiceResult error = tag.ReadAttribute( @@ -532,7 +532,7 @@ protected override ServiceResult SetMonitoringMode( datachangeItem.QueueValue(initialValue, error); } - + return ServiceResult.Good; } #endregion diff --git a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferState.cs b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferState.cs index 07a746311..93c33a430 100644 --- a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferState.cs +++ b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferState.cs @@ -38,7 +38,7 @@ using System.Diagnostics; namespace MemoryBuffer -{ +{ public partial class MemoryBufferState { #region Constructors @@ -59,17 +59,17 @@ public MemoryBufferState(ISystemContext context, MemoryBufferInstance configurat if (!String.IsNullOrEmpty(configuration.DataType)) { - dataType = configuration.DataType; + dataType = configuration.DataType; } if (!String.IsNullOrEmpty(configuration.Name)) { - name = dataType; + name = dataType; } } this.SymbolicName = name; - + BuiltInType elementType = BuiltInType.UInt32; switch (dataType) @@ -139,7 +139,7 @@ public void CreateBuffer(string elementName, int noOfElements) { elementName = "UInt32"; } - + BuiltInType elementType = BuiltInType.UInt32; switch (elementName) @@ -180,7 +180,7 @@ public void CreateBuffer(BuiltInType elementType, int noOfElements) break; } } - + m_lastScanTime = DateTime.UtcNow; m_maximumScanRate = 1000; @@ -193,11 +193,11 @@ public void CreateBuffer(BuiltInType elementType, int noOfElements) /// Creates an object which can browser the tags in the buffer. /// public override INodeBrowser CreateBrowser( - ISystemContext context, - ViewDescription view, - NodeId referenceType, - bool includeSubtypes, - BrowseDirection browseDirection, + ISystemContext context, + ViewDescription view, + NodeId referenceType, + bool includeSubtypes, + BrowseDirection browseDirection, QualifiedName browseName, IEnumerable additionalReferences, bool internalOnly) @@ -438,26 +438,26 @@ public void InitializeMonitoring( ///
public MemoryBufferMonitoredItem CreateDataChangeItem( ServerSystemContext context, - MemoryTagState tag, - uint subscriptionId, - uint monitoredItemId, - ReadValueId itemToMonitor, - DiagnosticsMasks diagnosticsMasks, - TimestampsToReturn timestampsToReturn, - MonitoringMode monitoringMode, - uint clientHandle, - double samplingInterval) - - /* - ISystemContext context, MemoryTagState tag, + uint subscriptionId, uint monitoredItemId, - uint attributeId, + ReadValueId itemToMonitor, DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn, MonitoringMode monitoringMode, uint clientHandle, - double samplingInterval)*/ + double samplingInterval) + + /* + ISystemContext context, + MemoryTagState tag, + uint monitoredItemId, + uint attributeId, + DiagnosticsMasks diagnosticsMasks, + TimestampsToReturn timestampsToReturn, + MonitoringMode monitoringMode, + uint clientHandle, + double samplingInterval)*/ { lock (m_dataLock) { @@ -551,8 +551,8 @@ void DoScan(object state) } DateTime end1 = DateTime.UtcNow; - - double delta1 = ((double)(end1.Ticks-start1.Ticks))/TimeSpan.TicksPerMillisecond; + + double delta1 = ((double)(end1.Ticks - start1.Ticks)) / TimeSpan.TicksPerMillisecond; if (delta1 > 100) { @@ -646,12 +646,12 @@ public void OnBufferChanged(int offset) } } } - + void ScanTimer_Tick(object sender, EventArgs e) { DoScan(null); } - + void PublishTimer_Tick(object sender, EventArgs e) { DateTime start1 = DateTime.UtcNow; @@ -667,8 +667,8 @@ void PublishTimer_Tick(object sender, EventArgs e) } DateTime end1 = DateTime.UtcNow; - - double delta1 = ((double)(end1.Ticks-start1.Ticks))/TimeSpan.TicksPerMillisecond; + + double delta1 = ((double)(end1.Ticks - start1.Ticks)) / TimeSpan.TicksPerMillisecond; if (delta1 > 100) { @@ -682,7 +682,7 @@ void PublishTimer_Tick(object sender, EventArgs e) private IServerInternal m_server; private INodeManager m_nodeManager; private MemoryBufferMonitoredItem[][] m_monitoringTable; - private Dictionary m_nonValueMonitoredItems; + private Dictionary m_nonValueMonitoredItems; private BuiltInType m_elementType; private int m_elementSize; private DateTime m_lastScanTime; diff --git a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryTagState.cs b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryTagState.cs index 23c20a8ab..d5aa82771 100644 --- a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryTagState.cs +++ b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryTagState.cs @@ -75,7 +75,7 @@ public MemoryTagState(MemoryBufferState parent, uint offet) : base(parent) m_offset = offet; } #endregion - + #region Public Properties /// /// The offset of the tag address in the memory buffer. diff --git a/Samples/Opc.Ua.Sample/Opc.Ua.Sample.csproj b/Samples/Opc.Ua.Sample/Opc.Ua.Sample.csproj index bf76fb925..2d9e32e5d 100644 --- a/Samples/Opc.Ua.Sample/Opc.Ua.Sample.csproj +++ b/Samples/Opc.Ua.Sample/Opc.Ua.Sample.csproj @@ -1,9 +1,8 @@ - + $(LibTargetFrameworks) Opc.Ua.Sample - 7.3 Opc.Ua.Sample Opc.Ua.Sample OPC UA Sample Class Library @@ -19,12 +18,8 @@ - - - - - - + + diff --git a/Samples/Opc.Ua.Sample/SampleServer.UserAuthentication.cs b/Samples/Opc.Ua.Sample/SampleServer.UserAuthentication.cs index b88d74c82..f7673cd3f 100644 --- a/Samples/Opc.Ua.Sample/SampleServer.UserAuthentication.cs +++ b/Samples/Opc.Ua.Sample/SampleServer.UserAuthentication.cs @@ -68,7 +68,7 @@ private void CreateUserIdentityValidators(ApplicationConfiguration configuration /// /// Called when a client tries to change its user identity. /// - private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) + private void SessionManager_ImpersonateUser(ISession session, ImpersonateEventArgs args) { // check for a WSS token. IssuedIdentityToken wssToken = args.NewIdentity as IssuedIdentityToken; diff --git a/Samples/Opc.Ua.Sample/SampleServer.cs b/Samples/Opc.Ua.Sample/SampleServer.cs index de797cb34..eecebea8c 100644 --- a/Samples/Opc.Ua.Sample/SampleServer.cs +++ b/Samples/Opc.Ua.Sample/SampleServer.cs @@ -53,7 +53,7 @@ protected override void OnServerStarting(ApplicationConfiguration configuration) Utils.Trace("The server is starting."); base.OnServerStarting(configuration); - + // it is up to the application to decide how to validate user identity tokens. // this function creates validator for X509 identity tokens. CreateUserIdentityValidators(configuration); @@ -65,7 +65,7 @@ protected override void OnServerStarting(ApplicationConfiguration configuration) protected override void OnServerStarted(IServerInternal server) { base.OnServerStarted(server); - + // request notifications when the user identity is changed. all valid users are accepted by default. server.SessionManager.ImpersonateUser += new ImpersonateEventHandler(SessionManager_ImpersonateUser); } @@ -81,13 +81,13 @@ protected override void OnServerStopping() Debug.WriteLine("The Server is stopping."); base.OnServerStopping(); - - #if INCLUDE_Sample + +#if INCLUDE_Sample CleanSampleModel(); - #endif +#endif } - - #if CUSTOM_NODE_MANAGER + +#if CUSTOM_NODE_MANAGER /// /// Creates the node managers for the server. /// @@ -114,11 +114,11 @@ protected override MasterNodeManager CreateMasterNodeManager(IServerInternal ser nodeManagers.Add(factory.Create(server, configuration)); factory = new global::Boiler.BoilerNodeManagerFactory(); nodeManagers.Add(factory.Create(server, configuration)); - + // create master node manager. return new MasterNodeManager(server, configuration, null, nodeManagers.ToArray()); } - #endif +#endif /// /// Loads the non-configurable properties for the application. @@ -131,11 +131,11 @@ protected override ServerProperties LoadServerProperties() ServerProperties properties = new ServerProperties(); properties.ManufacturerName = "OPC Foundation"; - properties.ProductName = "OPC UA SDK Samples"; - properties.ProductUri = "http://opcfoundation.org/UA/Samples/v1.0"; - properties.SoftwareVersion = Utils.GetAssemblySoftwareVersion(); - properties.BuildNumber = Utils.GetAssemblyBuildNumber(); - properties.BuildDate = Utils.GetAssemblyTimestamp(); + properties.ProductName = "OPC UA SDK Samples"; + properties.ProductUri = "http://opcfoundation.org/UA/Samples/v1.0"; + properties.SoftwareVersion = Utils.GetAssemblySoftwareVersion(); + properties.BuildNumber = Utils.GetAssemblyBuildNumber(); + properties.BuildDate = Utils.GetAssemblyTimestamp(); // TBD - All applications have software certificates that need to added to the properties. @@ -144,7 +144,7 @@ protected override ServerProperties LoadServerProperties() // properties.SoftwareCertificates.Add(certificates[ii]); // } - return properties; + return properties; } /// @@ -158,15 +158,15 @@ protected override void OnNodeManagerStarted(IServerInternal server) Debug.WriteLine("The NodeManagers have started."); // allow base class processing to happen first. - base.OnNodeManagerStarted(server); - + base.OnNodeManagerStarted(server); + // adds the sample information models to the core node manager. - #if INCLUDE_Sample +#if INCLUDE_Sample InitializeSampleModel(); - #endif +#endif } - - #if USER_AUTHENTICATION + +#if USER_AUTHENTICATION /// /// Creates the resource manager for the server. /// @@ -183,7 +183,7 @@ protected override ResourceManager CreateResourceManager(IServerInternal server, return resourceManager; } - #endif +#endif #endregion } } diff --git a/Samples/Opc.Ua.Sample/TestData/AnalogArrayValueObjectState.cs b/Samples/Opc.Ua.Sample/TestData/AnalogArrayValueObjectState.cs index f278410e1..131f01e10 100644 --- a/Samples/Opc.Ua.Sample/TestData/AnalogArrayValueObjectState.cs +++ b/Samples/Opc.Ua.Sample/TestData/AnalogArrayValueObjectState.cs @@ -95,7 +95,7 @@ protected override ServiceResult OnGenerateValues( GenerateValue(system, UIntegerValue); return base.OnGenerateValues(context, method, objectId, count); - } + } #endregion } } diff --git a/Samples/Opc.Ua.Sample/TestData/AnalogScalarValueObjectState.cs b/Samples/Opc.Ua.Sample/TestData/AnalogScalarValueObjectState.cs index 9fafe24d3..2c528b09b 100644 --- a/Samples/Opc.Ua.Sample/TestData/AnalogScalarValueObjectState.cs +++ b/Samples/Opc.Ua.Sample/TestData/AnalogScalarValueObjectState.cs @@ -45,7 +45,7 @@ public partial class AnalogScalarValueObjectState protected override void OnAfterCreate(ISystemContext context, NodeState node) { base.OnAfterCreate(context, node); - + InitializeVariable(context, SByteValue, TestData.Variables.AnalogScalarValueObjectType_SByteValue); InitializeVariable(context, ByteValue, TestData.Variables.AnalogScalarValueObjectType_ByteValue); InitializeVariable(context, Int16Value, TestData.Variables.AnalogScalarValueObjectType_Int16Value); @@ -95,7 +95,7 @@ protected override ServiceResult OnGenerateValues( GenerateValue(system, UIntegerValue); return base.OnGenerateValues(context, method, objectId, count); - } + } #endregion } } diff --git a/Samples/Opc.Ua.Sample/TestData/ArrayValueObjectState.cs b/Samples/Opc.Ua.Sample/TestData/ArrayValueObjectState.cs index 6c2db91e8..f75067c6d 100644 --- a/Samples/Opc.Ua.Sample/TestData/ArrayValueObjectState.cs +++ b/Samples/Opc.Ua.Sample/TestData/ArrayValueObjectState.cs @@ -123,7 +123,7 @@ protected override ServiceResult OnGenerateValues( GenerateValue(system, UIntegerValue); return base.OnGenerateValues(context, method, objectId, count); - } + } #endregion } } diff --git a/Samples/Opc.Ua.Sample/TestData/HistoryArchive.cs b/Samples/Opc.Ua.Sample/TestData/HistoryArchive.cs index 9768115db..f91fbf7f0 100644 --- a/Samples/Opc.Ua.Sample/TestData/HistoryArchive.cs +++ b/Samples/Opc.Ua.Sample/TestData/HistoryArchive.cs @@ -55,7 +55,7 @@ public void Dispose() /// An overrideable version of the Dispose. /// protected virtual void Dispose(bool disposing) - { + { if (disposing) { if (m_updateTimer != null) @@ -66,7 +66,7 @@ protected virtual void Dispose(bool disposing) } } #endregion - + #region Public Interface /// /// Returns an object that can be used to browse the archive. @@ -86,7 +86,7 @@ public HistoryFile GetHistoryFile(NodeId nodeId) { return null; } - + return new HistoryFile(m_lock, record.RawData); } } @@ -99,7 +99,7 @@ public void CreateRecord(NodeId nodeId, BuiltInType dataType) lock (m_lock) { HistoryRecord record = new HistoryRecord(); - + record.RawData = new List(); record.Historizing = true; record.DataType = dataType; @@ -111,7 +111,7 @@ public void CreateRecord(NodeId nodeId, BuiltInType dataType) HistoryEntry entry = new HistoryEntry(); entry.Value = new DataValue(); - entry.Value.ServerTimestamp = now.AddSeconds(-(ii*10)); + entry.Value.ServerTimestamp = now.AddSeconds(-(ii * 10)); entry.Value.SourceTimestamp = entry.Value.ServerTimestamp.AddMilliseconds(1234); entry.IsModified = false; @@ -129,7 +129,7 @@ public void CreateRecord(NodeId nodeId, BuiltInType dataType) if (m_records == null) { - m_records = new Dictionary(); + m_records = new Dictionary(); } m_records[nodeId] = record; @@ -139,9 +139,9 @@ public void CreateRecord(NodeId nodeId, BuiltInType dataType) m_updateTimer = new Timer(OnUpdate, null, 10000, 10000); } } - } + } #endregion - + #region Private Methods /// /// Periodically adds new values into the archive. @@ -160,7 +160,7 @@ private void OnUpdate(object state) { continue; } - + HistoryEntry entry = new HistoryEntry(); entry.Value = new DataValue(); @@ -172,8 +172,8 @@ private void OnUpdate(object state) { case BuiltInType.Int32: { - int lastValue = (int)record.RawData[record.RawData.Count-1].Value.Value; - entry.Value.Value = lastValue+1; + int lastValue = (int)record.RawData[record.RawData.Count - 1].Value.Value; + entry.Value.Value = lastValue + 1; break; } } @@ -192,10 +192,10 @@ private void OnUpdate(object state) #region Private Fields private object m_lock = new object(); private Timer m_updateTimer; - private Dictionary m_records; + private Dictionary m_records; #endregion } - + #region HistoryEntry Class /// /// A single entry in the archive. @@ -206,7 +206,7 @@ internal class HistoryEntry public bool IsModified; } #endregion - + #region HistoryRecord Class /// /// A record in the archive. diff --git a/Samples/Opc.Ua.Sample/TestData/HistoryDataReader.cs b/Samples/Opc.Ua.Sample/TestData/HistoryDataReader.cs index 49f152335..924b913c7 100644 --- a/Samples/Opc.Ua.Sample/TestData/HistoryDataReader.cs +++ b/Samples/Opc.Ua.Sample/TestData/HistoryDataReader.cs @@ -63,7 +63,7 @@ public HistoryDataReader(NodeId variableId, IHistoryDataSource source) /// Frees any unmanaged resources. /// public void Dispose() - { + { Dispose(true); } @@ -75,7 +75,7 @@ protected virtual void Dispose(bool disposing) // nothing to do. } #endregion - + #region Public Interface /// /// A globally unique identifier for the instance. @@ -92,7 +92,7 @@ public NodeId VariableId { get { return m_variableId; } } - + /// /// Starts reading raw values. /// @@ -104,8 +104,8 @@ public NodeId VariableId /// The values to return. public void BeginReadRaw( ServerSystemContext context, - ReadRawModifiedDetails request, - TimestampsToReturn timestampsToReturn, + ReadRawModifiedDetails request, + TimestampsToReturn timestampsToReturn, NumericRange indexRange, QualifiedName dataEncoding, DataValueCollection values) @@ -124,21 +124,21 @@ public void BeginReadRaw( // check the direction. m_isForward = m_startTime < m_endTime; m_position = -1; - + DataValue value = null; - + // get first bound. if (m_request.ReturnBounds) { value = m_source.FirstRaw(m_startTime, !m_isForward, m_request.IsReadModified, out m_position); - + if (value != null) { AddValue(timestampsToReturn, indexRange, dataEncoding, values, value); } } } - + /// /// Continues a read raw operation. /// @@ -156,7 +156,7 @@ public bool NextReadRaw( DataValueCollection values) { DataValue value = null; - + do { // check for limit. @@ -166,7 +166,7 @@ public bool NextReadRaw( } value = m_source.NextRaw(m_lastTime, m_isForward, m_request.IsReadModified, ref m_position); - + // no more data. if (value == null) { @@ -175,32 +175,32 @@ public bool NextReadRaw( // check for bound. if ((m_isForward && value.ServerTimestamp >= m_endTime) || (!m_isForward && value.ServerTimestamp <= m_endTime)) - { + { if (m_request.ReturnBounds) { AddValue(timestampsToReturn, indexRange, dataEncoding, values, value); return true; } } - + // add value. AddValue(timestampsToReturn, indexRange, dataEncoding, values, value); } while (value != null); - + return true; } #endregion - + #region Private Methods /// /// Adds a DataValue to a list of values to return. /// private void AddValue( - TimestampsToReturn timestampsToReturn, + TimestampsToReturn timestampsToReturn, NumericRange indexRange, QualifiedName dataEncoding, - DataValueCollection values, + DataValueCollection values, DataValue value) { // ignore invalid case. @@ -211,12 +211,12 @@ private void AddValue( // save the last timestamp returned. m_lastTime = value.ServerTimestamp; - + // check if the index range or data encoding can be applied. if (StatusCode.IsGood(value.StatusCode)) { object valueToReturn = value.Value; - + // apply the index range. if (indexRange != NumericRange.Empty) { diff --git a/Samples/Opc.Ua.Sample/TestData/HistoryFile.cs b/Samples/Opc.Ua.Sample/TestData/HistoryFile.cs index 1f3ff60d0..ace1d7560 100644 --- a/Samples/Opc.Ua.Sample/TestData/HistoryFile.cs +++ b/Samples/Opc.Ua.Sample/TestData/HistoryFile.cs @@ -55,7 +55,7 @@ internal HistoryFile(object dataLock, List entries) m_entries = entries; } #endregion - + #region IHistoryReader Members /// /// Returns the next value in the archive. @@ -68,7 +68,7 @@ internal HistoryFile(object dataLock, List entries) public DataValue FirstRaw(DateTime startTime, bool isForward, bool isReadModified, out int position) { position = -1; - + lock (m_lock) { if (isForward) @@ -84,7 +84,7 @@ public DataValue FirstRaw(DateTime startTime, bool isForward, bool isReadModifie } else { - for (int ii = m_entries.Count-1; ii >= 0; ii--) + for (int ii = m_entries.Count - 1; ii >= 0; ii--) { if (m_entries[ii].Value.ServerTimestamp <= startTime) { @@ -111,7 +111,7 @@ public DataValue FirstRaw(DateTime startTime, bool isForward, bool isReadModifie return value; } } - + /// /// Returns the next value in the archive. /// @@ -144,7 +144,7 @@ public DataValue NextRaw(DateTime lastTime, bool isForward, bool isReadModified, } } #endregion - + #region Private Fields private object m_lock = new object(); private List m_entries; diff --git a/Samples/Opc.Ua.Sample/TestData/MethodTestState.cs b/Samples/Opc.Ua.Sample/TestData/MethodTestState.cs index 91cd3e012..0ed135073 100644 --- a/Samples/Opc.Ua.Sample/TestData/MethodTestState.cs +++ b/Samples/Opc.Ua.Sample/TestData/MethodTestState.cs @@ -58,7 +58,7 @@ protected override void OnAfterCreate(ISystemContext context, NodeState node) this.UserArrayMethod2.OnCall = OnUserArrayValue2; } #endregion - + private ServiceResult OnScalarValue1( ISystemContext context, MethodState method, @@ -100,7 +100,7 @@ private ServiceResult OnScalarValue1( return ServiceResult.Good; } - + private ServiceResult OnScalarValue2( ISystemContext context, MethodState method, @@ -199,7 +199,7 @@ private ServiceResult OnArrayValue1( return ServiceResult.Good; } - + private ServiceResult OnArrayValue2( ISystemContext context, MethodState method, @@ -239,7 +239,7 @@ private ServiceResult OnArrayValue2( return ServiceResult.Good; } - private ServiceResult OnArrayValue3( + private ServiceResult OnArrayValue3( ISystemContext context, MethodState method, NodeId objectId, @@ -255,8 +255,8 @@ private ServiceResult OnArrayValue3( structureOut = structureIn; return ServiceResult.Good; - } - + } + private ServiceResult OnUserScalarValue1( ISystemContext context, MethodState method, @@ -301,7 +301,7 @@ private ServiceResult OnUserScalarValue1( return ServiceResult.Good; } - + private ServiceResult OnUserScalarValue2( ISystemContext context, MethodState method, @@ -385,7 +385,7 @@ private ServiceResult OnUserArrayValue1( return ServiceResult.Good; } - + private ServiceResult OnUserArrayValue2( ISystemContext context, MethodState method, diff --git a/Samples/Opc.Ua.Sample/TestData/ScalarValueObjectState.cs b/Samples/Opc.Ua.Sample/TestData/ScalarValueObjectState.cs index 733ac36e6..d419178f8 100644 --- a/Samples/Opc.Ua.Sample/TestData/ScalarValueObjectState.cs +++ b/Samples/Opc.Ua.Sample/TestData/ScalarValueObjectState.cs @@ -45,7 +45,7 @@ public partial class ScalarValueObjectState protected override void OnAfterCreate(ISystemContext context, NodeState node) { base.OnAfterCreate(context, node); - + InitializeVariable(context, BooleanValue, TestData.Variables.ScalarValueObjectType_BooleanValue); InitializeVariable(context, SByteValue, TestData.Variables.ScalarValueObjectType_SByteValue); InitializeVariable(context, ByteValue, TestData.Variables.ScalarValueObjectType_ByteValue); @@ -123,7 +123,7 @@ protected override ServiceResult OnGenerateValues( GenerateValue(system, UIntegerValue); return base.OnGenerateValues(context, method, objectId, count); - } + } #endregion } } diff --git a/Samples/Opc.Ua.Sample/TestData/TestDataNodeManager.cs b/Samples/Opc.Ua.Sample/TestData/TestDataNodeManager.cs index 76b68bf13..4d1ffbc89 100644 --- a/Samples/Opc.Ua.Sample/TestData/TestDataNodeManager.cs +++ b/Samples/Opc.Ua.Sample/TestData/TestDataNodeManager.cs @@ -546,7 +546,7 @@ private static bool SystemScanRequired(MonitoredNode2 monitoredNode, IDataChange protected override void OnMonitoredItemCreated( ServerSystemContext context, NodeHandle handle, - MonitoredItem monitoredItem) + ISampledDataChangeMonitoredItem monitoredItem) { if (SystemScanRequired(handle.MonitoredNode, monitoredItem)) { @@ -569,7 +569,7 @@ protected override void OnMonitoredItemCreated( protected override void OnMonitoredItemModified( ServerSystemContext context, NodeHandle handle, - MonitoredItem monitoredItem) + ISampledDataChangeMonitoredItem monitoredItem) { if (SystemScanRequired(handle.MonitoredNode, monitoredItem)) { @@ -591,7 +591,7 @@ protected override void OnMonitoredItemModified( protected override void OnMonitoredItemDeleted( ServerSystemContext context, NodeHandle handle, - MonitoredItem monitoredItem) + ISampledDataChangeMonitoredItem monitoredItem) { // check for variables that need to be scanned. if (SystemScanRequired(handle.MonitoredNode, monitoredItem)) @@ -611,7 +611,7 @@ protected override void OnMonitoredItemDeleted( protected override void OnMonitoringModeChanged( ServerSystemContext context, NodeHandle handle, - MonitoredItem monitoredItem, + ISampledDataChangeMonitoredItem monitoredItem, MonitoringMode previousMode, MonitoringMode monitoringMode) { diff --git a/Samples/Opc.Ua.Sample/TestData/TestDataObjectState.cs b/Samples/Opc.Ua.Sample/TestData/TestDataObjectState.cs index 18d984a17..bee3c390a 100644 --- a/Samples/Opc.Ua.Sample/TestData/TestDataObjectState.cs +++ b/Samples/Opc.Ua.Sample/TestData/TestDataObjectState.cs @@ -153,7 +153,7 @@ public ServiceResult OnWriteAnalogValue( } catch (Exception) { - throw ; + throw; } } diff --git a/Samples/Opc.Ua.Sample/TestData/TestDataSystem.cs b/Samples/Opc.Ua.Sample/TestData/TestDataSystem.cs index 2a692f388..26138c965 100644 --- a/Samples/Opc.Ua.Sample/TestData/TestDataSystem.cs +++ b/Samples/Opc.Ua.Sample/TestData/TestDataSystem.cs @@ -37,7 +37,7 @@ using Opc.Ua.Server; namespace TestData -{ +{ public interface ITestDataSystemCallback { void OnDataChange( @@ -46,14 +46,14 @@ void OnDataChange( StatusCode statusCode, DateTime timestamp); } - + public class TestDataSystem { public TestDataSystem(ITestDataSystemCallback callback, NamespaceTable namespaceUris, StringTable serverUris) { m_callback = callback; m_minimumSamplingInterval = Int32.MaxValue; - m_monitoredNodes = new Dictionary(); + m_monitoredNodes = new Dictionary(); m_generator = new Opc.Ua.Test.DataGenerator(null); m_generator.NamespaceUris = namespaceUris; m_generator.ServerUris = serverUris; @@ -100,7 +100,7 @@ public StatusCode SystemStatus } } } - + /// /// Creates an archive for the variable. /// @@ -110,7 +110,7 @@ public void EnableHistoryArchiving(BaseVariableState variable) { return; } - + if (variable.ValueRank == ValueRanks.Scalar) { m_historyArchive.CreateRecord(variable.NodeId, TypeInfo.GetBuiltInType(variable.DataType)); @@ -153,7 +153,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_SByteValue: { - return (sbyte)(((int)(m_generator.GetRandom(false)%201)) - 100); + return (sbyte)(((int)(m_generator.GetRandom(false) % 201)) - 100); } case TestData.Variables.ScalarValueObjectType_ByteValue: @@ -164,7 +164,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_ByteValue: { - return (byte)((m_generator.GetRandom(false)%201) + 50); + return (byte)((m_generator.GetRandom(false) % 201) + 50); } case TestData.Variables.ScalarValueObjectType_Int16Value: @@ -175,7 +175,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_Int16Value: { - return (short)(((int)(m_generator.GetRandom(false)%201)) - 100); + return (short)(((int)(m_generator.GetRandom(false) % 201)) - 100); } case TestData.Variables.ScalarValueObjectType_UInt16Value: @@ -186,7 +186,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_UInt16Value: { - return (ushort)((m_generator.GetRandom(false)%201) + 50); + return (ushort)((m_generator.GetRandom(false) % 201) + 50); } case TestData.Variables.ScalarValueObjectType_Int32Value: @@ -198,7 +198,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_Int32Value: case TestData.Variables.AnalogScalarValueObjectType_IntegerValue: { - return (int)(((int)(m_generator.GetRandom(false)%201)) - 100); + return (int)(((int)(m_generator.GetRandom(false) % 201)) - 100); } case TestData.Variables.ScalarValueObjectType_UInt32Value: @@ -210,7 +210,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_UInt32Value: case TestData.Variables.AnalogScalarValueObjectType_UIntegerValue: { - return (uint)((m_generator.GetRandom(false)%201) + 50); + return (uint)((m_generator.GetRandom(false) % 201) + 50); } case TestData.Variables.ScalarValueObjectType_Int64Value: @@ -221,7 +221,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_Int64Value: { - return (long)(((int)(m_generator.GetRandom(false)%201)) - 100); + return (long)(((int)(m_generator.GetRandom(false) % 201)) - 100); } case TestData.Variables.ScalarValueObjectType_UInt64Value: @@ -232,7 +232,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_UInt64Value: { - return (ulong)((m_generator.GetRandom(false)%201) + 50); + return (ulong)((m_generator.GetRandom(false) % 201) + 50); } case TestData.Variables.ScalarValueObjectType_FloatValue: @@ -243,7 +243,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_FloatValue: { - return (float)(((int)(m_generator.GetRandom(false)%201)) - 100); + return (float)(((int)(m_generator.GetRandom(false) % 201)) - 100); } case TestData.Variables.ScalarValueObjectType_DoubleValue: @@ -255,7 +255,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.AnalogScalarValueObjectType_DoubleValue: case TestData.Variables.AnalogScalarValueObjectType_NumberValue: { - return (double)(((int)(m_generator.GetRandom(false)%201)) - 100); + return (double)(((int)(m_generator.GetRandom(false) % 201)) - 100); } case TestData.Variables.ScalarValueObjectType_StringValue: @@ -359,7 +359,7 @@ public object ReadValue(BaseVariableState variable) case TestData.Variables.UserArrayValueObjectType_SByteValue: { return m_generator.GetRandomArray(false, 100, false); - } + } case TestData.Variables.AnalogArrayValueObjectType_SByteValue: { @@ -367,12 +367,12 @@ public object ReadValue(BaseVariableState variable) for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (sbyte)(((int)(m_generator.GetRandom(false)%201)) - 100); + values[ii] = (sbyte)(((int)(m_generator.GetRandom(false) % 201)) - 100); } return values; } - + case TestData.Variables.ArrayValueObjectType_ByteValue: case TestData.Variables.UserArrayValueObjectType_ByteValue: { @@ -385,7 +385,7 @@ public object ReadValue(BaseVariableState variable) for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (byte)((m_generator.GetRandom(false)%201) + 50); + values[ii] = (byte)((m_generator.GetRandom(false) % 201) + 50); } return values; @@ -403,7 +403,7 @@ public object ReadValue(BaseVariableState variable) for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (short)(((int)(m_generator.GetRandom(false)%201)) - 100); + values[ii] = (short)(((int)(m_generator.GetRandom(false) % 201)) - 100); } return values; @@ -421,7 +421,7 @@ public object ReadValue(BaseVariableState variable) for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (ushort)((m_generator.GetRandom(false)%201) + 50); + values[ii] = (ushort)((m_generator.GetRandom(false) % 201) + 50); } return values; @@ -440,7 +440,7 @@ public object ReadValue(BaseVariableState variable) for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (int)(((int)(m_generator.GetRandom(false)%201)) - 100); + values[ii] = (int)(((int)(m_generator.GetRandom(false) % 201)) - 100); } return values; @@ -451,7 +451,7 @@ public object ReadValue(BaseVariableState variable) { return m_generator.GetRandomArray(false, 100, false); } - + case TestData.Variables.AnalogArrayValueObjectType_UInt32Value: case TestData.Variables.AnalogArrayValueObjectType_UIntegerValue: { @@ -459,7 +459,7 @@ public object ReadValue(BaseVariableState variable) for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (uint)((m_generator.GetRandom(false)%201) + 50); + values[ii] = (uint)((m_generator.GetRandom(false) % 201) + 50); } return values; @@ -470,14 +470,14 @@ public object ReadValue(BaseVariableState variable) { return m_generator.GetRandomArray(false, 100, false); } - + case TestData.Variables.AnalogArrayValueObjectType_Int64Value: { long[] values = m_generator.GetRandomArray(false, 100, false); for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (long)(((int)(m_generator.GetRandom(false)%201)) - 100); + values[ii] = (long)(((int)(m_generator.GetRandom(false) % 201)) - 100); } return values; @@ -495,7 +495,7 @@ public object ReadValue(BaseVariableState variable) for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (ulong)((m_generator.GetRandom(false)%201) + 50); + values[ii] = (ulong)((m_generator.GetRandom(false) % 201) + 50); } return values; @@ -513,18 +513,18 @@ public object ReadValue(BaseVariableState variable) for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (float)(((int)(m_generator.GetRandom(false)%201)) - 100); + values[ii] = (float)(((int)(m_generator.GetRandom(false) % 201)) - 100); } return values; } - + case TestData.Variables.ArrayValueObjectType_DoubleValue: case TestData.Variables.UserArrayValueObjectType_DoubleValue: { return m_generator.GetRandomArray(false, 100, false); } - + case TestData.Variables.AnalogArrayValueObjectType_DoubleValue: case TestData.Variables.AnalogArrayValueObjectType_NumberValue: { @@ -532,7 +532,7 @@ public object ReadValue(BaseVariableState variable) for (int ii = 0; ii < values.Length; ii++) { - values[ii] = (double)(((int)(m_generator.GetRandom(false)%201)) - 100); + values[ii] = (double)(((int)(m_generator.GetRandom(false) % 201)) - 100); } return values; @@ -612,7 +612,7 @@ public object ReadValue(BaseVariableState variable) { values[ii] = GetRandomStructure(); } - + return values; } @@ -649,7 +649,7 @@ private ExtensionObject GetRandomStructure() if (m_generator.GetRandomBoolean()) { ScalarValueDataType value = new ScalarValueDataType(); - + value.BooleanValue = m_generator.GetRandom(false); value.SByteValue = m_generator.GetRandom(false); value.ByteValue = m_generator.GetRandom(false); @@ -678,7 +678,7 @@ private ExtensionObject GetRandomStructure() else { ArrayValueDataType value = new ArrayValueDataType(); - + value.BooleanValue = m_generator.GetRandomArray(false, 10, false); value.SByteValue = m_generator.GetRandomArray(false, 10, false); value.ByteValue = m_generator.GetRandomArray(false, 10, false); @@ -718,7 +718,7 @@ public void StartMonitoringValue(uint monitoredItemId, double samplingInterval, { if (m_monitoredNodes == null) { - m_monitoredNodes = new Dictionary(); + m_monitoredNodes = new Dictionary(); } m_monitoredNodes[monitoredItemId] = variable; @@ -741,7 +741,7 @@ public void SetSamplingInterval(double samplingInterval) m_timer.Dispose(); m_timer = null; } - + return; } @@ -753,13 +753,13 @@ public void SetSamplingInterval(double samplingInterval) { m_minimumSamplingInterval = 100; } - + if (m_timer != null) { m_timer.Dispose(); m_timer = null; } - + m_timer = new Timer(DoSample, null, m_minimumSamplingInterval, m_minimumSamplingInterval); } } @@ -820,7 +820,7 @@ public void StopMonitoringValue(uint monitoredItemId) } } } - + private class Sample { public BaseVariableState Variable; @@ -828,13 +828,13 @@ private class Sample public StatusCode StatusCode; public DateTime Timestamp; } - + #region Private Fields private object m_lock = new object(); private ITestDataSystemCallback m_callback; private Opc.Ua.Test.DataGenerator m_generator; private int m_minimumSamplingInterval; - private Dictionary m_monitoredNodes; + private Dictionary m_monitoredNodes; private Timer m_timer; private StatusCode m_systemStatus; private HistoryArchive m_historyArchive; diff --git a/Samples/Opc.Ua.Sample/TestData/TestSystemConditionState.cs b/Samples/Opc.Ua.Sample/TestData/TestSystemConditionState.cs index d4ae32cae..462831809 100644 --- a/Samples/Opc.Ua.Sample/TestData/TestSystemConditionState.cs +++ b/Samples/Opc.Ua.Sample/TestData/TestSystemConditionState.cs @@ -54,8 +54,8 @@ protected override void OnAfterCreate(ISystemContext context, NodeState node) /// Reads the value for the MonitoredNodeCount. /// protected virtual ServiceResult OnReadMonitoredNodeCount( - ISystemContext context, - NodeState node, + ISystemContext context, + NodeState node, ref object value) { TestDataSystem system = context?.SystemHandle as TestDataSystem; diff --git a/Samples/Opc.Ua.Sample/TestData/UserArrayValueObjectState.cs b/Samples/Opc.Ua.Sample/TestData/UserArrayValueObjectState.cs index e31bd2e16..19956cd4b 100644 --- a/Samples/Opc.Ua.Sample/TestData/UserArrayValueObjectState.cs +++ b/Samples/Opc.Ua.Sample/TestData/UserArrayValueObjectState.cs @@ -113,7 +113,7 @@ protected override ServiceResult OnGenerateValues( GenerateValue(system, VariantValue); return base.OnGenerateValues(context, method, objectId, count); - } + } #endregion } } diff --git a/Samples/Opc.Ua.Sample/TestData/UserScalarValueObjectState.cs b/Samples/Opc.Ua.Sample/TestData/UserScalarValueObjectState.cs index 9add788e8..2efaeef32 100644 --- a/Samples/Opc.Ua.Sample/TestData/UserScalarValueObjectState.cs +++ b/Samples/Opc.Ua.Sample/TestData/UserScalarValueObjectState.cs @@ -113,7 +113,7 @@ protected override ServiceResult OnGenerateValues( GenerateValue(system, VariantValue); return base.OnGenerateValues(context, method, objectId, count); - } + } #endregion } } diff --git a/Samples/ReferenceClient/MainForm.Designer.cs b/Samples/ReferenceClient/MainForm.Designer.cs index b4e220f7e..d3f2bc0b3 100644 --- a/Samples/ReferenceClient/MainForm.Designer.cs +++ b/Samples/ReferenceClient/MainForm.Designer.cs @@ -125,7 +125,7 @@ private void InitializeComponent() this.Server_ConnectMI.Name = "Server_ConnectMI"; this.Server_ConnectMI.Size = new System.Drawing.Size(127, 22); this.Server_ConnectMI.Text = "Connect"; - this.Server_ConnectMI.Click += new System.EventHandler(this.Server_ConnectMI_Click); + this.Server_ConnectMI.Click += new System.EventHandler(this.Server_ConnectMI_ClickAsync); // // Server_DisconnectMI // @@ -173,9 +173,9 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 6; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); - this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); - this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); + this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStartingAsync); + this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectCompleteAsync); // // BrowseCTRL // diff --git a/Samples/ReferenceClient/MainForm.cs b/Samples/ReferenceClient/MainForm.cs index aebcdaa15..3de02159a 100644 --- a/Samples/ReferenceClient/MainForm.cs +++ b/Samples/ReferenceClient/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -68,7 +68,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private bool m_connectedOnce; #endregion @@ -79,11 +79,11 @@ public MainForm(ApplicationConfiguration configuration) /// /// Connects to a server. /// - private async void Server_ConnectMI_Click(object sender, EventArgs e) + private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -124,7 +124,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -137,7 +137,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) } // browse the instances in the server. - BrowseCTRL.Initialize(m_session, ObjectIds.ObjectsFolder, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); + await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); } catch (Exception exception) { @@ -148,11 +148,11 @@ private void Server_ConnectComplete(object sender, EventArgs e) /// /// Updates the application after a communicate error was detected. /// - private void Server_ReconnectStarting(object sender, EventArgs e) + private async void Server_ReconnectStartingAsync(object sender, EventArgs e) { try { - BrowseCTRL.ChangeSession(null); + await BrowseCTRL.ChangeSessionAsync(null); } catch (Exception exception) { @@ -163,12 +163,12 @@ private void Server_ReconnectStarting(object sender, EventArgs e) /// /// Updates the application after reconnecting to the server. /// - private void Server_ReconnectComplete(object sender, EventArgs e) + private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) { try { m_session = ConnectServerCTRL.Session; - BrowseCTRL.ChangeSession(m_session); + await BrowseCTRL.ChangeSessionAsync(m_session); } catch (Exception exception) { @@ -197,7 +197,7 @@ private void Help_ContentsMI_Click(object sender, EventArgs e) { try { - System.Diagnostics.Process.Start( Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\overview_-_reference_client.htm"); + System.Diagnostics.Process.Start(Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\overview_-_reference_client.htm"); } catch (Exception ex) { diff --git a/Samples/ReferenceClient/Program.cs b/Samples/ReferenceClient/Program.cs index 8627ef9c4..006e84591 100644 --- a/Samples/ReferenceClient/Program.cs +++ b/Samples/ReferenceClient/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -50,17 +50,17 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); application.ApplicationName = "UA Reference Client"; - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.ReferenceClient"; try { - + // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + _ = application.LoadApplicationConfigurationAsync(false).AsTask().Result; // check the application certificate. - var certOK = application.CheckApplicationInstanceCertificates(false).Result; + var certOK = application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Result; if (!certOK) { throw new Exception("Application instance certificate invalid!"); diff --git a/Samples/ReferenceClient/Reference Client.csproj b/Samples/ReferenceClient/Reference Client.csproj index 848a4617a..7604f7040 100644 --- a/Samples/ReferenceClient/Reference Client.csproj +++ b/Samples/ReferenceClient/Reference Client.csproj @@ -48,6 +48,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -58,6 +59,7 @@ 4 false false + AllRules.ruleset @@ -127,16 +129,16 @@ - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview diff --git a/Samples/ReferenceServer/MonitoredItemEventLogDlg.cs b/Samples/ReferenceServer/MonitoredItemEventLogDlg.cs index 11d82379b..fa417ea54 100644 --- a/Samples/ReferenceServer/MonitoredItemEventLogDlg.cs +++ b/Samples/ReferenceServer/MonitoredItemEventLogDlg.cs @@ -45,7 +45,7 @@ public MonitoredItemEventLogDlg() InitializeComponent(); DataGridCTRL.AutoGenerateColumns = false; } - + public void Display() { ServerUtils.EventsEnabled = true; @@ -65,7 +65,7 @@ private void RefreshTimer_Tick(object sender, EventArgs e) } m_dataset = ServerUtils.EmptyQueue(m_dataset); - + if (count != m_dataset.Tables[0].Rows.Count) { DataGridCTRL.DataSource = m_dataset.Tables[0]; diff --git a/Samples/ReferenceServer/Program.cs b/Samples/ReferenceServer/Program.cs index a511d9007..06737b9a2 100644 --- a/Samples/ReferenceServer/Program.cs +++ b/Samples/ReferenceServer/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -51,22 +51,24 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.ReferenceServer"; try { // load the application configuration. - ApplicationConfiguration config = application.LoadApplicationConfiguration(false).Result; + ApplicationConfiguration config = application.LoadApplicationConfigurationAsync(false).AsTask().Result; LoggerConfiguration loggerConfiguration = new LoggerConfiguration(); #if DEBUG +#pragma warning disable CA1305 // Specify IFormatProvider loggerConfiguration.WriteTo.Debug(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning); +#pragma warning restore CA1305 // Specify IFormatProvider #endif SerilogTraceLogger.Create(loggerConfiguration, config); // check the application certificate. - bool certOk = application.CheckApplicationInstanceCertificates(false).Result; + bool certOk = application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Result; if (!certOk) { throw new Exception("Application instance certificate invalid!"); @@ -77,7 +79,7 @@ static void Main() Quickstarts.Servers.Utils.AddDefaultNodeManagers(server); // start the server. - application.Start(server).Wait(); + application.StartAsync(server).Wait(); // check whether the invalid certificates dialog should be displayed. bool showCertificateValidationDialog = false; diff --git a/Samples/ReferenceServer/Reference Server.csproj b/Samples/ReferenceServer/Reference Server.csproj index fe26e5b65..d904c38d8 100644 --- a/Samples/ReferenceServer/Reference Server.csproj +++ b/Samples/ReferenceServer/Reference Server.csproj @@ -48,6 +48,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -58,6 +59,7 @@ 4 false false + AllRules.ruleset Always @@ -139,13 +141,13 @@ - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview - 1.5.374.118 + 1.5.377.11-preview 4.3.0 diff --git a/Samples/ReferenceServer/ReferenceServerUtils.cs b/Samples/ReferenceServer/ReferenceServerUtils.cs index d8c009ed6..cd353481d 100644 --- a/Samples/ReferenceServer/ReferenceServerUtils.cs +++ b/Samples/ReferenceServer/ReferenceServerUtils.cs @@ -51,7 +51,7 @@ private enum EventType PublishValue } - private class Event + private sealed class Event { public DateTime Timestamp; public EventType EventType; @@ -71,8 +71,8 @@ private class Event public static bool EventsEnabled { get { return m_eventsEnabled; } - - set + + set { if (m_eventsEnabled != value) { @@ -85,7 +85,7 @@ public static bool EventsEnabled } } - m_eventsEnabled = value; + m_eventsEnabled = value; } } @@ -289,7 +289,7 @@ public static void ReportPublishValue(NodeId nodeId, uint serverHandle, DataValu /// Reports a new monitored item. /// public static void ReportCreateMonitoredItem( - NodeId nodeId, + NodeId nodeId, uint serverHandle, double samplingInterval, uint queueSize, @@ -360,13 +360,13 @@ public static void ReportModifyMonitoredItem( /// Fills in the diagnostic information after an error. /// public static uint CreateError( - uint code, - OperationContext context, - DiagnosticInfoCollection diagnosticInfos, - int index) + uint code, + OperationContext context, + DiagnosticInfoCollection diagnosticInfos, + int index) { ServiceResult error = new ServiceResult(code); - + if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { diagnosticInfos[index] = new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable); @@ -374,19 +374,19 @@ public static uint CreateError( return error.Code; } - + /// /// Fills in the diagnostic information after an error. /// public static bool CreateError( - uint code, - StatusCodeCollection results, - DiagnosticInfoCollection diagnosticInfos, - OperationContext context) + uint code, + StatusCodeCollection results, + DiagnosticInfoCollection diagnosticInfos, + OperationContext context) { ServiceResult error = new ServiceResult(code); results.Add(error.Code); - + if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { diagnosticInfos.Add(new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable)); @@ -395,20 +395,20 @@ public static bool CreateError( return false; } - + /// /// Fills in the diagnostic information after an error. /// public static bool CreateError( - uint code, - StatusCodeCollection results, - DiagnosticInfoCollection diagnosticInfos, - int index, - OperationContext context) + uint code, + StatusCodeCollection results, + DiagnosticInfoCollection diagnosticInfos, + int index, + OperationContext context) { ServiceResult error = new ServiceResult(code); results[index] = error.Code; - + if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { diagnosticInfos[index] = new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable); @@ -417,28 +417,28 @@ public static bool CreateError( return false; } - + /// /// Creates a place holder in the lists for the results. /// public static void CreateSuccess( - StatusCodeCollection results, + StatusCodeCollection results, DiagnosticInfoCollection diagnosticInfos, - OperationContext context) + OperationContext context) { results.Add(StatusCodes.Good); - + if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { diagnosticInfos.Add(null); } } - + /// /// Creates a collection of diagnostics from a set of errors. /// public static DiagnosticInfoCollection CreateDiagnosticInfoCollection( - OperationContext context, + OperationContext context, IList errors) { // all done if no diagnostics requested. @@ -446,7 +446,7 @@ public static DiagnosticInfoCollection CreateDiagnosticInfoCollection( { return null; } - + // create diagnostics. DiagnosticInfoCollection results = new DiagnosticInfoCollection(errors.Count); @@ -464,13 +464,13 @@ public static DiagnosticInfoCollection CreateDiagnosticInfoCollection( return results; } - + /// /// Creates a collection of status codes and diagnostics from a set of errors. /// public static StatusCodeCollection CreateStatusCodeCollection( - OperationContext context, - IList errors, + OperationContext context, + IList errors, out DiagnosticInfoCollection diagnosticInfos) { diagnosticInfos = null; @@ -496,7 +496,7 @@ public static StatusCodeCollection CreateStatusCodeCollection( { diagnosticInfos = CreateDiagnosticInfoCollection(context, errors); } - + return results; } @@ -508,9 +508,9 @@ public static StatusCodeCollection CreateStatusCodeCollection( /// The error to translate. /// The diagnostics with references to the strings in the context string table. public static DiagnosticInfo CreateDiagnosticInfo( - IServerInternal server, + IServerInternal server, OperationContext context, - ServiceResult error) + ServiceResult error) { if (error == null) { @@ -525,9 +525,9 @@ public static DiagnosticInfo CreateDiagnosticInfo( } DiagnosticInfo diagnosticInfo = new DiagnosticInfo( - translatedError, - context.DiagnosticsMask, - false, + translatedError, + context.DiagnosticsMask, + false, context.StringTable); return diagnosticInfo; diff --git a/Samples/ReferenceServer/SerilogTraceLogger.cs b/Samples/ReferenceServer/SerilogTraceLogger.cs index b8e15d1c5..829bfc7d7 100644 --- a/Samples/ReferenceServer/SerilogTraceLogger.cs +++ b/Samples/ReferenceServer/SerilogTraceLogger.cs @@ -125,7 +125,7 @@ public void TraceEventHandler(object sender, TraceEventArgs e) case Utils.TraceMasks.StartStop: case Utils.TraceMasks.Information: m_logger.Information(e.Format, e.Arguments); break; case Utils.TraceMasks.Error: m_logger.Error(e.Format, e.Arguments); break; - case Utils.TraceMasks.StackTrace: + case Utils.TraceMasks.StackTrace: case Utils.TraceMasks.Security: m_logger.Warning(e.Format, e.Arguments); break; default: m_logger.Verbose(e.Format, e.Arguments); break; } diff --git a/Samples/Server.Net4/Program.cs b/Samples/Server.Net4/Program.cs index f7d40cc4a..99c889c34 100644 --- a/Samples/Server.Net4/Program.cs +++ b/Samples/Server.Net4/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -49,22 +49,22 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); application.ApplicationName = "UA Sample Server"; - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Opc.Ua.SampleServer"; try { - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().GetAwaiter().GetResult(); // check the application certificate. - bool certOK = application.CheckApplicationInstanceCertificates(false).Result; + bool certOK = application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Result; if (!certOK) { throw new Exception("Application instance certificate invalid!"); } // start the server. - application.Start(new SampleServer()).Wait(); + application.StartAsync(new SampleServer()).Wait(); // run the application interactively. Application.Run(new ServerForm(application)); diff --git a/Samples/Server.Net4/ServerDiagnosticsCtrl.cs b/Samples/Server.Net4/ServerDiagnosticsCtrl.cs index 7715b4f7c..e00bd1fb8 100644 --- a/Samples/Server.Net4/ServerDiagnosticsCtrl.cs +++ b/Samples/Server.Net4/ServerDiagnosticsCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -58,7 +58,7 @@ public ServerDiagnosticsCtrl() private StandardServer m_server; private ApplicationConfiguration m_configuration; #endregion - + #region Public Interface /// /// Creates a form which displays the status for a UA server. @@ -70,7 +70,7 @@ public void Initialize(StandardServer server, ApplicationConfiguration configura m_server = server; m_configuration = configuration; UpdateTimerCTRL.Enabled = true; - + // add the urls to the drop down. UrlCB.Items.Clear(); @@ -97,11 +97,11 @@ private void UpdateSessions() { SessionsLV.Items.Clear(); - IList sessions = m_server.CurrentInstance.SessionManager.GetSessions(); + IList sessions = m_server.CurrentInstance.SessionManager.GetSessions(); for (int ii = 0; ii < sessions.Count; ii++) { - Session session = sessions[ii]; + ISession session = sessions[ii]; lock (session.DiagnosticsLock) { @@ -123,7 +123,7 @@ private void UpdateSessions() } } - // adjust + // adjust for (int ii = 0; ii < SessionsLV.Columns.Count; ii++) { SessionsLV.Columns[ii].Width = -2; @@ -137,11 +137,11 @@ private void UpdateSubscriptions() { SubscriptionsLV.Items.Clear(); - IList subscriptions = m_server.CurrentInstance.SubscriptionManager.GetSubscriptions(); + IList subscriptions = m_server.CurrentInstance.SubscriptionManager.GetSubscriptions(); for (int ii = 0; ii < subscriptions.Count; ii++) { - Subscription subscription = subscriptions[ii]; + ISubscription subscription = subscriptions[ii]; ListViewItem item = new ListViewItem(subscription.Id.ToString()); @@ -176,7 +176,7 @@ private void UpdateTimerCTRL_Tick(object sender, EventArgs e) UpdateSessions(); UpdateSubscriptions(); } - catch (Exception) + catch { // MessageBox.Show(exception.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } diff --git a/Samples/Server.Net4/ServerForm.cs b/Samples/Server.Net4/ServerForm.cs index 88bea4700..597c869be 100644 --- a/Samples/Server.Net4/ServerForm.cs +++ b/Samples/Server.Net4/ServerForm.cs @@ -50,7 +50,7 @@ public ServerForm() { InitializeComponent(); } - + /// /// Creates a form which displays the status for a UA server. /// @@ -135,7 +135,7 @@ private void TrayIcon_MouseMove(object sender, MouseEventArgs e) if (server != null) { TrayIcon.Text = String.Format( - "{0} [{1} {2:HH:mm:ss}]", + "{0} [{1} {2:HH:mm:ss}]", m_application.ApplicationName, server.CurrentInstance.CurrentState, DateTime.Now); @@ -150,7 +150,7 @@ private void TrayIcon_MouseMove(object sender, MouseEventArgs e) private void exitToolStripMenuItem_Click(object sender, EventArgs e) { - if (MessageBox.Show("Quit this application", "Generic Server", MessageBoxButtons.YesNoCancel)== DialogResult.Yes) + if (MessageBox.Show("Quit this application", "Generic Server", MessageBoxButtons.YesNoCancel) == DialogResult.Yes) { Application.Exit(); } @@ -160,7 +160,7 @@ private void contentsToolStripMenuItem_Click(object sender, EventArgs e) { try { - System.Diagnostics.Process.Start( Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "WebHelp" + Path.DirectorySeparatorChar + "ua_sample_server.htm"); + System.Diagnostics.Process.Start(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "WebHelp" + Path.DirectorySeparatorChar + "ua_sample_server.htm"); } catch (Exception ex) { diff --git a/Samples/Server.Net4/UA Sample Server.csproj b/Samples/Server.Net4/UA Sample Server.csproj index a79066597..d0e329266 100644 --- a/Samples/Server.Net4/UA Sample Server.csproj +++ b/Samples/Server.Net4/UA Sample Server.csproj @@ -37,6 +37,7 @@ AnyCPU false false + AllRules.ruleset pdbonly @@ -48,6 +49,7 @@ AnyCPU false false + AllRules.ruleset @@ -143,10 +145,10 @@ - 9.0.6 + 9.0.8 - 1.5.376.244 + 1.5.377.11-preview diff --git a/Samples/ServerControls.Net4/ExceptionDlg.cs b/Samples/ServerControls.Net4/ExceptionDlg.cs index 88187a338..72ec00038 100644 --- a/Samples/ServerControls.Net4/ExceptionDlg.cs +++ b/Samples/ServerControls.Net4/ExceptionDlg.cs @@ -91,7 +91,7 @@ private void AddBlock(StringBuilder buffer, string text, int level) } buffer.Append("color:#FFFFFF;font-weight:bold;font-size:10pt;font-family:Verdana'>"); - buffer.Append("

"); + buffer.Append("

"); } else { @@ -183,7 +183,7 @@ public static void Show(string caption, Exception e) Utils.LogError(e, "Unexpected error in '{0}'.", caption); return; } - + new ExceptionDlg().ShowDialog(caption, e); } @@ -198,12 +198,12 @@ public void ShowDialog(string caption, Exception e) } m_exception = e; - - #if _DEBUG + +#if _DEBUG ShowStackTracesCK.Checked = true; - #else +#else ShowStackTracesCK.Checked = false; - #endif +#endif Show(ShowStackTracesCK.Checked); ShowDialog(); diff --git a/Samples/ServerControls.Net4/InputDlg.cs b/Samples/ServerControls.Net4/InputDlg.cs index d0907eaa3..97b0d078f 100644 --- a/Samples/ServerControls.Net4/InputDlg.cs +++ b/Samples/ServerControls.Net4/InputDlg.cs @@ -30,7 +30,7 @@ public static string Show(string text, bool hideInput) } private void buttonOk_Click(object sender, EventArgs e) - { + { Close(); } } diff --git a/Samples/ServerControls.Net4/MessageDlg.cs b/Samples/ServerControls.Net4/MessageDlg.cs index 90f0ef88d..b13f391a5 100644 --- a/Samples/ServerControls.Net4/MessageDlg.cs +++ b/Samples/ServerControls.Net4/MessageDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -52,10 +52,10 @@ public override void Message(string text, bool ask) } } - public override async Task ShowAsync() + public override Task ShowAsync() { DialogResult result = MessageBox.Show(message, "OPC UA", buttons); - return await Task.FromResult((result == DialogResult.OK) || (result == DialogResult.Yes)); + return Task.FromResult((result == DialogResult.OK) || (result == DialogResult.Yes)); } } } diff --git a/Samples/ServerControls.Net4/ServerDiagnosticsCtrl.cs b/Samples/ServerControls.Net4/ServerDiagnosticsCtrl.cs index afd7b9f49..bb5ce9ea5 100644 --- a/Samples/ServerControls.Net4/ServerDiagnosticsCtrl.cs +++ b/Samples/ServerControls.Net4/ServerDiagnosticsCtrl.cs @@ -57,7 +57,7 @@ public ServerDiagnosticsCtrl() private StandardServer m_server; private ApplicationConfiguration m_configuration; #endregion - + #region Public Interface ///

/// Creates a form which displays the status for a UA server. @@ -69,7 +69,7 @@ public void Initialize(StandardServer server, ApplicationConfiguration configura m_server = server; m_configuration = configuration; UpdateTimerCTRL.Enabled = true; - + // add the urls to the drop down. UrlCB.Items.Clear(); @@ -96,11 +96,11 @@ private void UpdateSessions() { SessionsLV.Items.Clear(); - IList sessions = m_server.CurrentInstance.SessionManager.GetSessions(); + IList sessions = m_server.CurrentInstance.SessionManager.GetSessions(); for (int ii = 0; ii < sessions.Count; ii++) { - Session session = sessions[ii]; + ISession session = sessions[ii]; lock (session.DiagnosticsLock) { @@ -136,11 +136,11 @@ private void UpdateSubscriptions() { SubscriptionsLV.Items.Clear(); - IList subscriptions = m_server.CurrentInstance.SubscriptionManager.GetSubscriptions(); + IList subscriptions = m_server.CurrentInstance.SubscriptionManager.GetSubscriptions(); for (int ii = 0; ii < subscriptions.Count; ii++) { - Subscription subscription = subscriptions[ii]; + ISubscription subscription = subscriptions[ii]; ListViewItem item = new ListViewItem(subscription.Id.ToString()); @@ -173,15 +173,15 @@ private void UpdateTimerCTRL_Tick(object sender, EventArgs e) ServerStateLB.Text = m_server.CurrentInstance.CurrentState.ToString(); ServerTimeLB.Text = String.Format("{0:HH:mm:ss}", DateTime.Now); UpdateSessions(); - sessionsLB.Text = Convert.ToString( SessionsLV.Items.Count ); + sessionsLB.Text = Convert.ToString(SessionsLV.Items.Count); UpdateSubscriptions(); - subscriptionsLB.Text = Convert.ToString( SubscriptionsLV.Items.Count ); + subscriptionsLB.Text = Convert.ToString(SubscriptionsLV.Items.Count); int itemTotal = 0; - for ( int i = 0; i < SubscriptionsLV.Items.Count; i++ ) + for (int i = 0; i < SubscriptionsLV.Items.Count; i++) { - itemTotal += Convert.ToInt32( SubscriptionsLV.Items[i].SubItems[2].Text ); + itemTotal += Convert.ToInt32(SubscriptionsLV.Items[i].SubItems[2].Text); } - itemsLB.Text = Convert.ToString( itemTotal ); + itemsLB.Text = Convert.ToString(itemTotal); } catch (Exception exception) { diff --git a/Samples/ServerControls.Net4/ServerForm.cs b/Samples/ServerControls.Net4/ServerForm.cs index f9e3ca137..04ba5b59a 100644 --- a/Samples/ServerControls.Net4/ServerForm.cs +++ b/Samples/ServerControls.Net4/ServerForm.cs @@ -55,7 +55,7 @@ public ServerForm() { InitializeComponent(); } - + /// /// Creates a form which displays the status for a UA server. /// @@ -184,7 +184,7 @@ private void ContentsToolStripMenuItem_Click(object sender, EventArgs e) { try { - System.Diagnostics.Process.Start( Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "WebHelp" + Path.DirectorySeparatorChar + "index.htm"); + System.Diagnostics.Process.Start(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "WebHelp" + Path.DirectorySeparatorChar + "index.htm"); } catch (Exception ex) { @@ -218,7 +218,7 @@ public static void HandleCertificateValidationError(Form caller, CertificateVali ServiceResult error = e.Error; while (error != null) { - buffer.AppendFormat("- {0}\r\n", error.ToString().Split('\r','\n').FirstOrDefault()); + buffer.AppendFormat("- {0}\r\n", error.ToString().Split('\r', '\n').FirstOrDefault()); error = error.InnerResult; } buffer.AppendFormat("\r\nSubject: {0}\r\n", e.Certificate.Subject); diff --git a/Samples/ServerControls.Net4/UA Server Controls.csproj b/Samples/ServerControls.Net4/UA Server Controls.csproj index 6596d8db2..a6bce4eae 100644 --- a/Samples/ServerControls.Net4/UA Server Controls.csproj +++ b/Samples/ServerControls.Net4/UA Server Controls.csproj @@ -47,6 +47,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -57,6 +58,7 @@ 4 false false + AllRules.ruleset @@ -148,13 +150,13 @@ - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview diff --git a/UA Quickstart Applications.sln b/UA Quickstart Applications.sln index cc2169dd8..92b4aa4e9 100644 --- a/UA Quickstart Applications.sln +++ b/UA Quickstart Applications.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2010 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36414.22 d17.14 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SampleLibraries", "SampleLibraries", "{5465661E-783E-4350-98D8-DDE8AB935E21}" EndProject @@ -89,6 +89,18 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UA Client Controls", "Sampl EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UA Server Controls", "Samples\ServerControls.Net4\UA Server Controls.csproj", "{80056988-44E7-4EF4-9F59-50BCF215CB03}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8EC462FD-D22E-90A8-E5CE-7E832BA40C5D}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + .gitattributes = .gitattributes + .gitignore = .gitignore + .whitesource = .whitesource + Directory.Build.props = Directory.Build.props + Nuget.Config = Nuget.Config + README.md = README.md + targets.props = targets.props + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/UA Sample Applications.sln b/UA Sample Applications.sln index b2e8e0a6c..96d094926 100644 --- a/UA Sample Applications.sln +++ b/UA Sample Applications.sln @@ -18,6 +18,18 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Reference Client", "Samples\ReferenceClient\Reference Client.csproj", "{9C1E7F15-2EE3-440D-8E17-00C38073822A}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{792419FF-6D50-432A-97A6-6C2A6AB7F1A7}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + .gitattributes = .gitattributes + .gitignore = .gitignore + .whitesource = .whitesource + azure-pipelines.yml = azure-pipelines.yml + Directory.Build.props = Directory.Build.props + managed.ruleset = managed.ruleset + README.md = README.md + SECURITY.md = SECURITY.md + targets.props = targets.props + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Reference Server", "Samples\ReferenceServer\Reference Server.csproj", "{42EF4F25-29BF-4AB7-B403-8523694A3B36}" EndProject diff --git a/Workshop/Aggregation/Client/Aggregation Client.csproj b/Workshop/Aggregation/Client/Aggregation Client.csproj index 92d508785..8c18c9190 100644 --- a/Workshop/Aggregation/Client/Aggregation Client.csproj +++ b/Workshop/Aggregation/Client/Aggregation Client.csproj @@ -32,6 +32,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -42,6 +43,7 @@ 4 false false + AllRules.ruleset @@ -134,7 +136,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Aggregation/Client/MainForm.Designer.cs b/Workshop/Aggregation/Client/MainForm.Designer.cs index 2e5694103..c586e5fc2 100644 --- a/Workshop/Aggregation/Client/MainForm.Designer.cs +++ b/Workshop/Aggregation/Client/MainForm.Designer.cs @@ -124,7 +124,7 @@ private void InitializeComponent() this.Server_ConnectMI.Name = "Server_ConnectMI"; this.Server_ConnectMI.Size = new System.Drawing.Size(196, 22); this.Server_ConnectMI.Text = "Connect"; - this.Server_ConnectMI.Click += new System.EventHandler(this.Server_ConnectMI_Click); + this.Server_ConnectMI.Click += new System.EventHandler(this.Server_ConnectMI_ClickAsync); // // Server_ChangeUserOrLocaleMI // @@ -239,9 +239,9 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); - this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); - this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); + this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStartingAsync); + this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectCompleteAsync); // // clientHeaderBranding1 // diff --git a/Workshop/Aggregation/Client/MainForm.cs b/Workshop/Aggregation/Client/MainForm.cs index 345791ecc..1fe94fa31 100644 --- a/Workshop/Aggregation/Client/MainForm.cs +++ b/Workshop/Aggregation/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -53,7 +53,7 @@ private MainForm() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } - + /// /// Creates a form which uses the specified client configuration. /// @@ -71,7 +71,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; #endregion #region Private Methods @@ -81,11 +81,11 @@ public MainForm(ApplicationConfiguration configuration) /// /// Connects to a server. /// - private async void Server_ConnectMI_Click(object sender, EventArgs e) + private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -126,14 +126,14 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { m_session = ConnectServerCTRL.Session; // browse the instances in the server. - BrowseCTRL.Initialize(m_session, ObjectIds.ObjectsFolder, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); + await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); } catch (Exception exception) { @@ -144,11 +144,11 @@ private void Server_ConnectComplete(object sender, EventArgs e) /// /// Updates the application after a communicate error was detected. /// - private void Server_ReconnectStarting(object sender, EventArgs e) + private async void Server_ReconnectStartingAsync(object sender, EventArgs e) { try { - BrowseCTRL.ChangeSession(null); + await BrowseCTRL.ChangeSessionAsync(null); } catch (Exception exception) { @@ -159,12 +159,12 @@ private void Server_ReconnectStarting(object sender, EventArgs e) /// /// Updates the application after reconnecting to the server. /// - private void Server_ReconnectComplete(object sender, EventArgs e) + private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) { try { m_session = ConnectServerCTRL.Session; - BrowseCTRL.ChangeSession(m_session); + await BrowseCTRL.ChangeSessionAsync(m_session); } catch (Exception exception) { diff --git a/Workshop/Aggregation/Client/Program.cs b/Workshop/Aggregation/Client/Program.cs index f5a29f4da..07a94251b 100644 --- a/Workshop/Aggregation/Client/Program.cs +++ b/Workshop/Aggregation/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -55,10 +55,10 @@ static void Main() try { // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().GetAwaiter().GetResult(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().GetAwaiter().GetResult(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/Aggregation/Client/SetUserAndLocaleDlg.cs b/Workshop/Aggregation/Client/SetUserAndLocaleDlg.cs index 7f16748a4..386e23419 100644 --- a/Workshop/Aggregation/Client/SetUserAndLocaleDlg.cs +++ b/Workshop/Aggregation/Client/SetUserAndLocaleDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -34,6 +34,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace AggregationClient { @@ -51,24 +53,24 @@ public SetUserAndLocaleDlg() InitializeComponent(); } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; #endregion - + #region Public Interface /// /// Prompts the user to specify the user name and locale. /// - public bool ShowDialog(Session session) + public async Task ShowDialogAsync(ISession session, CancellationToken ct = default) { m_session = session; #region Task #D3 - Change Locale and User Identity UpdateUserIdentity(session); - UpdateLocale(session); + await UpdateLocaleAsync(session, ct); #endregion - + // display the dialog. if (ShowDialog() != DialogResult.OK) { @@ -83,7 +85,7 @@ public bool ShowDialog(Session session) /// /// Updates the local displayed in the control. /// - private void UpdateUserIdentity(Session session) + private void UpdateUserIdentity(ISession session) { UserNameTB.Text = null; PasswordTB.Text = null; @@ -106,12 +108,12 @@ private void UpdateUserIdentity(Session session) /// /// Updates the local displayed in the control. /// - private void UpdateLocale(Session session) + private async Task UpdateLocaleAsync(ISession session, CancellationToken ct = default) { LocaleCB.Items.Clear(); // get the locales from the server. - DataValue value = m_session.ReadValue(VariableIds.Server_ServerCapabilities_LocaleIdArray); + DataValue value = await m_session.ReadValueAsync(VariableIds.Server_ServerCapabilities_LocaleIdArray, ct); if (value != null) { @@ -183,7 +185,7 @@ private void OkBTN_Click(object sender, EventArgs e) { // update the session. m_session.ReturnDiagnostics = DiagnosticsMasks.ServiceSymbolicIdAndText; - m_session.UpdateSession(identity, preferredLocales); + m_session.UpdateSessionAsync(identity, preferredLocales).GetAwaiter().GetResult(); } finally { diff --git a/Workshop/Aggregation/Client/ShowReferencesDlg.cs b/Workshop/Aggregation/Client/ShowReferencesDlg.cs index 75b955f56..6592fe8e7 100644 --- a/Workshop/Aggregation/Client/ShowReferencesDlg.cs +++ b/Workshop/Aggregation/Client/ShowReferencesDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -34,6 +34,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace AggregationClient { @@ -51,20 +53,20 @@ public ShowReferencesDlg() InitializeComponent(); } #endregion - + #region Private Fields private Session m_session; private NodeId m_nodeId; private ReferenceDescription m_reference; #endregion - + #region Public Interface - public ReferenceDescription ShowDialog(Session session, NodeId nodeId) + public async Task ShowDialogAsync(Session session, NodeId nodeId, CancellationToken ct = default) { m_session = session; #region Task #B1 - Browse References - UpdateList(session, nodeId); + await UpdateListAsync(session, nodeId, ct); #endregion // display the dialog. @@ -81,18 +83,18 @@ public ReferenceDescription ShowDialog(Session session, NodeId nodeId) /// /// Updates the list of references. /// - private void UpdateList(Session session, NodeId nodeId) + private async Task UpdateListAsync(Session session, NodeId nodeId, CancellationToken ct = default) { m_nodeId = nodeId; ReferencesLV.Items.Clear(); - List references = Browse(session, nodeId); - DisplayReferences(session, references); + List references = await BrowseAsync(session, nodeId, ct); + await DisplayReferencesAsync(session, references, ct); } /// /// Fetches the references for the node. /// - private List Browse(Session session, NodeId nodeId) + private async Task> BrowseAsync(Session session, NodeId nodeId, CancellationToken ct = default) { List references = new List(); @@ -108,18 +110,18 @@ private List Browse(Session session, NodeId nodeId) BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); - - // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - ResponseHeader responseHeader = session.Browse( + // start the browse operation. + BrowseResponse response = await session.BrowseAsync( null, null, 2, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, nodesToBrowse); @@ -142,16 +144,19 @@ private List Browse(Session session, NodeId nodeId) continuationPoints.Add(results[0].ContinuationPoint); // continue browse operation. - responseHeader = session.BrowseNext( + BrowseNextResponse response2 = await session.BrowseNextAsync( null, false, continuationPoints, - out results, - out diagnosticInfos); + ct); + + responseHeader = response2.ResponseHeader; + results = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); - + // check status. if (StatusCode.IsBad(results[0].StatusCode)) { @@ -171,7 +176,7 @@ private List Browse(Session session, NodeId nodeId) /// /// Displays the references in the control. /// - private void DisplayReferences(Session session, List references) + private async Task DisplayReferencesAsync(Session session, List references, CancellationToken ct = default) { ReferencesLV.Items.Clear(); @@ -182,7 +187,7 @@ private void DisplayReferences(Session session, List refer string referenceType = null; // look up the name for the reference - IReferenceType referenceTypeNode = session.NodeCache.Find(reference.ReferenceTypeId) as IReferenceType; + IReferenceType referenceTypeNode = await session.NodeCache.FindAsync(reference.ReferenceTypeId, ct) as IReferenceType; if (referenceTypeNode != null) { @@ -195,7 +200,7 @@ private void DisplayReferences(Session session, List refer } // the node cache is used to store the type model so it can be accessed locally. - string typeDefinition = session.NodeCache.GetDisplayText(reference.TypeDefinition); + string typeDefinition = await session.NodeCache.GetDisplayTextAsync(reference.TypeDefinition, ct); ListViewItem item = new ListViewItem(referenceType); diff --git a/Workshop/Aggregation/ConsoleAggregationServer/ConsoleAggregationServer.csproj b/Workshop/Aggregation/ConsoleAggregationServer/ConsoleAggregationServer.csproj index 13eb2664f..f5fd334f2 100644 --- a/Workshop/Aggregation/ConsoleAggregationServer/ConsoleAggregationServer.csproj +++ b/Workshop/Aggregation/ConsoleAggregationServer/ConsoleAggregationServer.csproj @@ -1,4 +1,4 @@ - + net8.0 @@ -48,15 +48,15 @@ - - - + + + - + diff --git a/Workshop/Aggregation/ConsoleAggregationServer/Program.cs b/Workshop/Aggregation/ConsoleAggregationServer/Program.cs index b93c68a8b..1878e3877 100644 --- a/Workshop/Aggregation/ConsoleAggregationServer/Program.cs +++ b/Workshop/Aggregation/ConsoleAggregationServer/Program.cs @@ -97,7 +97,7 @@ public void Start() try { - Task t = ConsoleAggregationServer(); + Task t = ConsoleAggregationServerAsync(); t.Wait(); Console.WriteLine("Server started. Press any key to exit..."); } @@ -137,7 +137,7 @@ private static void CertificateValidator_CertificateValidation(CertificateValida } } - private async Task ConsoleAggregationServer() + private async Task ConsoleAggregationServerAsync() { ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); @@ -147,10 +147,10 @@ private async Task ConsoleAggregationServer() application.ConfigSectionName = "Quickstarts.AggregationServer"; // load the application configuration. - ApplicationConfiguration config = await application.LoadApplicationConfiguration(false).ConfigureAwait(false); + ApplicationConfiguration config = await application.LoadApplicationConfigurationAsync(false).ConfigureAwait(false); // check the application certificate. - bool haveAppCertificate = await application.CheckApplicationInstanceCertificates(false).ConfigureAwait(false); + bool haveAppCertificate = await application.CheckApplicationInstanceCertificatesAsync(false).ConfigureAwait(false); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); @@ -163,7 +163,7 @@ private async Task ConsoleAggregationServer() // start the server. server = new AggregationServer(); - await application.Start(server).ConfigureAwait(false); + await application.StartAsync(server).ConfigureAwait(false); // print reverse connect info Console.WriteLine("Reverse Connect Clients:"); @@ -195,7 +195,7 @@ private async Task ConsoleAggregationServer() } // start the status thread - status = Task.Run(async () => await StatusThread().ConfigureAwait(false)); + status = Task.Run(async () => await StatusThreadAsync().ConfigureAwait(false)); // print notification on session events server.CurrentInstance.SessionManager.SessionActivated += EventStatus; @@ -203,13 +203,13 @@ private async Task ConsoleAggregationServer() server.CurrentInstance.SessionManager.SessionCreated += EventStatus; } - private void EventStatus(Session session, SessionEventReason reason) + private void EventStatus(ISession session, SessionEventReason reason) { lastEventTime = DateTime.UtcNow; PrintSessionStatus(session, reason.ToString()); } - void PrintSessionStatus(Session session, string reason, bool lastContact = false) + private void PrintSessionStatus(ISession session, string reason, bool lastContact = false) { lock (session.DiagnosticsLock) { @@ -230,17 +230,17 @@ void PrintSessionStatus(Session session, string reason, bool lastContact = false } } - private async Task StatusThread() + private async Task StatusThreadAsync() { AggregationServer serverStatus = server; while (serverStatus != null) { if (DateTime.UtcNow - lastEventTime > TimeSpan.FromMilliseconds(6000)) { - IList sessions = serverStatus.CurrentInstance.SessionManager.GetSessions(); + IList sessions = serverStatus.CurrentInstance.SessionManager.GetSessions(); for (int ii = 0; ii < sessions.Count; ii++) { - Session session = sessions[ii]; + ISession session = sessions[ii]; PrintSessionStatus(session, "-Status-", true); } lastEventTime = DateTime.UtcNow; diff --git a/Workshop/Aggregation/Server/AggregatedTypeCache.cs b/Workshop/Aggregation/Server/AggregatedTypeCache.cs index b9649aeac..e49811329 100644 --- a/Workshop/Aggregation/Server/AggregatedTypeCache.cs +++ b/Workshop/Aggregation/Server/AggregatedTypeCache.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,6 +29,8 @@ using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; using Opc.Ua; using Opc.Ua.Server; @@ -47,26 +49,26 @@ internal sealed class AggregatedTypeCache /// /// Fetches the event type information from the AE server. /// - public void LoadTypes(Opc.Ua.Client.Session client, IServerInternal server, NamespaceMapper mapper) + public async Task LoadTypesAsync(Opc.Ua.Client.ISession client, IServerInternal server, NamespaceMapper mapper, CancellationToken ct = default) { TypeNodes = new NodeIdDictionary(); - LoadTypes(client, server, mapper, Opc.Ua.ObjectTypeIds.BaseObjectType); - LoadTypes(client, server, mapper, Opc.Ua.VariableTypeIds.BaseVariableType); - LoadTypes(client, server, mapper, Opc.Ua.DataTypeIds.BaseDataType); - LoadTypes(client, server, mapper, Opc.Ua.ReferenceTypeIds.References); + await LoadTypesAsync(client, server, mapper, Opc.Ua.ObjectTypeIds.BaseObjectType, ct); + await LoadTypesAsync(client, server, mapper, Opc.Ua.VariableTypeIds.BaseVariableType, ct); + await LoadTypesAsync(client, server, mapper, Opc.Ua.DataTypeIds.BaseDataType, ct); + await LoadTypesAsync(client, server, mapper, Opc.Ua.ReferenceTypeIds.References, ct); } /// /// Fetches the event categories for the specified event type. /// - private void LoadTypes(Opc.Ua.Client.Session client, IServerInternal server, NamespaceMapper mapper, NodeId parentId) + private async Task LoadTypesAsync(Opc.Ua.Client.ISession client, IServerInternal server, NamespaceMapper mapper, NodeId parentId, CancellationToken ct = default) { List references = null; // find references to subtypes. try { - references = BrowseSubTypes(client, parentId); + references = await BrowseSubTypesAsync(client, parentId, ct); } catch (Exception e) { @@ -87,7 +89,7 @@ private void LoadTypes(Opc.Ua.Client.Session client, IServerInternal server, Nam // recursively browse until a non-UA node is found. if (reference.NodeId.NamespaceIndex == 0) { - LoadTypes(client, server, mapper, (NodeId)reference.NodeId); + await LoadTypesAsync(client, server, mapper, (NodeId)reference.NodeId, ct); continue; } @@ -106,7 +108,7 @@ private void LoadTypes(Opc.Ua.Client.Session client, IServerInternal server, Nam /// /// Fetches the subtypes for the node. /// - private List BrowseSubTypes(Opc.Ua.Client.Session client, NodeId nodeId) + private async Task> BrowseSubTypesAsync(Opc.Ua.Client.ISession client, NodeId nodeId, CancellationToken ct = default) { List references = new List(); @@ -124,16 +126,16 @@ private List BrowseSubTypes(Opc.Ua.Client.Session client, nodesToBrowse.Add(nodeToBrowse); // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = client.Browse( + BrowseResponse response = await client.BrowseAsync( null, null, 0, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, nodesToBrowse); @@ -156,12 +158,15 @@ private List BrowseSubTypes(Opc.Ua.Client.Session client, continuationPoints.Add(results[0].ContinuationPoint); // continue browse operation. - responseHeader = client.BrowseNext( + BrowseNextResponse response2 = await client.BrowseNextAsync( null, false, continuationPoints, - out results, - out diagnosticInfos); + ct); + + responseHeader = response2.ResponseHeader; + results = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); diff --git a/Workshop/Aggregation/Server/Aggregation Server.csproj b/Workshop/Aggregation/Server/Aggregation Server.csproj index 6d91c309e..edc93a633 100644 --- a/Workshop/Aggregation/Server/Aggregation Server.csproj +++ b/Workshop/Aggregation/Server/Aggregation Server.csproj @@ -34,6 +34,7 @@ false x86 false + AllRules.ruleset pdbonly @@ -44,6 +45,7 @@ 4 false false + AllRules.ruleset true @@ -54,7 +56,7 @@ false 7.3 prompt - MinimumRecommendedRules.ruleset + AllRules.ruleset @@ -129,16 +131,16 @@ - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Aggregation/Server/AggregationNodeManager.cs b/Workshop/Aggregation/Server/AggregationNodeManager.cs index ec844521a..651a5b588 100644 --- a/Workshop/Aggregation/Server/AggregationNodeManager.cs +++ b/Workshop/Aggregation/Server/AggregationNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -53,7 +53,7 @@ public AggregationClientSession(NodeId sessionId, bool isMetaDataSession) public NodeId ClientSessionId { get; } public NodeId SessionSessionId { get; private set; } public bool IsMetaDataSession { get; } - public Opc.Ua.Client.Session Session + public Opc.Ua.Client.ISession Session { get => m_session; set @@ -65,7 +65,7 @@ public Opc.Ua.Client.Session Session public Opc.Ua.Client.SessionReconnectHandler ReconnectHandler { get; set; } public DateTime LastUsed { get; set; } - private Opc.Ua.Client.Session m_session; + private Opc.Ua.Client.ISession m_session; } /// @@ -98,7 +98,7 @@ public AggregationNodeManager( if (endpoint.ReverseConnect != null && endpoint.ReverseConnect.Enabled) { - // reverse connect manager endpoint is required + // reverse connect manager endpoint is required if (reverseConnectManager == null) throw new ArgumentNullException(nameof(reverseConnectManager)); m_reverseConnectManager = reverseConnectManager; } @@ -148,7 +148,7 @@ public override NodeId New(ISystemContext context, NodeState node) /// /// The externalReferences is an out parameter that allows the node manager to link to nodes /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and - /// should have a reference to the root folder node(s) exposed by this node manager. + /// should have a reference to the root folder node(s) exposed by this node manager. /// public override void CreateAddressSpace(IDictionary> externalReferences) { @@ -217,7 +217,7 @@ public override void CreateAddressSpace(IDictionary> e AddPredefinedNode(SystemContext, status); - StartMetadataUpdates(DoMetadataUpdate, null, DefaultMetadataInitDelay, DefaultMetadataRefresh); + StartMetadataUpdates(DoMetadataUpdateAsync, null, DefaultMetadataInitDelay, DefaultMetadataRefresh); } } @@ -239,7 +239,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node { lock (Lock) { - // quickly exclude nodes that are not in the namespace. + // quickly exclude nodes that are not in the namespace. if (!IsNodeIdInNamespace(nodeId)) { return null; @@ -337,18 +337,18 @@ protected override void Read( // send request to external system. try { - Opc.Ua.Client.Session client = GetClientSession(context); + Opc.Ua.Client.ISession client = GetClientSession(context); - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = client.Read( + ReadResponse response = client.ReadAsync( null, 0, TimestampsToReturn.Both, requests, - out results, - out diagnosticInfos); + default).Result; + + ResponseHeader responseHeader = response.ResponseHeader; + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, requests); @@ -434,16 +434,16 @@ protected override void Write( // send request to external system. try { - Opc.Ua.Client.Session client = GetClientSession(context); + Opc.Ua.Client.ISession client = GetClientSession(context); - StatusCodeCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = client.Write( + WriteResponse response = client.WriteAsync( null, requests, - out results, - out diagnosticInfos); + default).Result; + + ResponseHeader responseHeader = response.ResponseHeader; + StatusCodeCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, requests); @@ -575,16 +575,16 @@ public override void Call( // send request to external system. try { - Opc.Ua.Client.Session client = GetClientSession(systemContext); + Opc.Ua.Client.ISession client = GetClientSession(systemContext); - CallMethodResultCollection results2 = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = client.Call( + CallResponse response = client.CallAsync( null, requests, - out results2, - out diagnosticInfos); + default).Result; + + ResponseHeader responseHeader = response.ResponseHeader; + CallMethodResultCollection results2 = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results2, requests); @@ -662,7 +662,7 @@ protected override void OnCreateMonitoredItemsComplete(ServerSystemContext conte // send request to external system. try { - Opc.Ua.Client.Session client = GetClientSession(context); + Opc.Ua.Client.ISession client = GetClientSession(context); lock (client) { @@ -683,7 +683,7 @@ protected override void OnCreateMonitoredItemsComplete(ServerSystemContext conte subscription.FastEventCallback = OnEventNotification; client.AddSubscription(subscription); - subscription.Create(); + subscription.CreateAsync().GetAwaiter().GetResult(); } // add items. @@ -700,7 +700,7 @@ protected override void OnCreateMonitoredItemsComplete(ServerSystemContext conte target.AddItem(requests[ii]); } - target.ApplyChanges(); + target.ApplyChangesAsync().GetAwaiter().GetResult(); // check status. int index = 0; @@ -731,7 +731,7 @@ protected override void OnCreateMonitoredItemsComplete(ServerSystemContext conte /// protected override void OnModifyMonitoredItemsComplete(ServerSystemContext context, IList monitoredItems) { - Opc.Ua.Client.Session client = GetClientSession(context); + Opc.Ua.Client.ISession client = GetClientSession(context); List remoteItems = new List(); lock (client) @@ -784,7 +784,7 @@ protected override void OnModifyMonitoredItemsComplete(ServerSystemContext conte // send request to external system. try { - target.ApplyChanges(); + target.ApplyChangesAsync().GetAwaiter().GetResult(); // check status. foreach (Opc.Ua.Client.MonitoredItem monitoredItem in remoteItems) @@ -813,7 +813,7 @@ protected override void OnModifyMonitoredItemsComplete(ServerSystemContext conte /// protected override void OnDeleteMonitoredItemsComplete(ServerSystemContext context, IList monitoredItems) { - Opc.Ua.Client.Session client = GetClientSession(context); + Opc.Ua.Client.ISession client = GetClientSession(context); lock (client) { @@ -862,11 +862,11 @@ protected override void OnDeleteMonitoredItemsComplete(ServerSystemContext conte // send request to external system. try { - target.ApplyChanges(); + target.ApplyChangesAsync().GetAwaiter().GetResult(); if (target.MonitoredItemCount == 0) { - client.RemoveSubscription(target); + client.RemoveSubscriptionAsync(target).GetAwaiter().GetResult(); } } catch (Exception e) @@ -881,7 +881,7 @@ protected override void OnDeleteMonitoredItemsComplete(ServerSystemContext conte ///
protected override void OnSetMonitoringModeComplete(ServerSystemContext context, IList monitoredItems) { - Opc.Ua.Client.Session client = GetClientSession(context); + Opc.Ua.Client.ISession client = GetClientSession(context); List remoteItems = new List(); lock (client) @@ -932,7 +932,7 @@ protected override void OnSetMonitoringModeComplete(ServerSystemContext context, // send request to external system. try { - target.ApplyChanges(); + target.ApplyChangesAsync().GetAwaiter().GetResult(); // check status. foreach (Opc.Ua.Client.MonitoredItem monitoredItem in remoteItems) @@ -990,7 +990,7 @@ public override ServiceResult SubscribeToEvents( return ServiceResult.Good; } - Opc.Ua.Client.Session client = GetClientSession(systemContext); + Opc.Ua.Client.ISession client = GetClientSession(systemContext); if (unsubscribe) { @@ -1020,11 +1020,11 @@ public override ServiceResult SubscribeToEvents( // apply changes. target.RemoveItem(remoteItem); - target.ApplyChanges(); + target.ApplyChangesAsync().GetAwaiter().GetResult(); if (target.MonitoredItemCount == 0) { - target.Session.RemoveSubscription(target); + target.Session.RemoveSubscriptionAsync(target).GetAwaiter().GetResult(); } } @@ -1070,7 +1070,7 @@ public override ServiceResult SubscribeToEvents( subscription.FastEventCallback = OnEventNotification; client.AddSubscription(subscription); - subscription.Create(); + subscription.CreateAsync().GetAwaiter().GetResult(); } // get the subscription. @@ -1088,7 +1088,7 @@ public override ServiceResult SubscribeToEvents( } target.AddItem(request); - target.ApplyChanges(); + target.ApplyChangesAsync().GetAwaiter().GetResult(); if (ServiceResult.IsBad(request.Status.Error)) { @@ -1176,7 +1176,7 @@ public void OnEventNotification(Opc.Ua.Client.Subscription subscription, EventNo /// /// Get a cached client session or create a new one per server connection. /// - Opc.Ua.Client.Session GetClientSession(ServerSystemContext context) + Opc.Ua.Client.ISession GetClientSession(ServerSystemContext context) { NodeId sessionId; string sessionName; @@ -1233,7 +1233,7 @@ Opc.Ua.Client.Session GetClientSession(ServerSystemContext context) { // the client session is stale and not reconnecting m_clients.Remove(sessionId); - session.Close(); + session.CloseAsync().GetAwaiter().GetResult(); session.Dispose(); clientSession = null; } @@ -1262,7 +1262,7 @@ Opc.Ua.Client.Session GetClientSession(ServerSystemContext context) try { Utils.Trace($"Create Connect Session: {m_endpoint} for {sessionName}"); - var session = Opc.Ua.Client.Session.Create( + var session = Opc.Ua.Client.Session.CreateAsync( m_configuration, m_reverseConnectManager, m_endpoint, @@ -1341,7 +1341,7 @@ private void StartMetadataUpdates(WaitCallback callback, object callbackData, in m_metadataUpdateCallback = callback; m_timerPeriod = period; m_initialDelay = initialDelay; - m_metadataUpdateTimer = new Timer(DoMetadataUpdate, callbackData, initialDelay, -1); + m_metadataUpdateTimer = new Timer(DoMetadataUpdateAsync, callbackData, initialDelay, -1); } } @@ -1363,10 +1363,10 @@ private void CleanupTimer() /// /// Updates the metadata. /// - private void DoMetadataUpdate(object state) + private async void DoMetadataUpdateAsync(object state) { int nextTimerPeriod = m_initialDelay; - Opc.Ua.Client.Session client = null; + Opc.Ua.Client.ISession client = null; try { if (!Server.IsRunning) @@ -1422,7 +1422,7 @@ private void DoMetadataUpdate(object state) } AggregatedTypeCache cache = new AggregatedTypeCache(); - cache.LoadTypes(client, Server, m_mapper); + await cache.LoadTypesAsync(client, Server, m_mapper); lock (Lock) { @@ -1483,11 +1483,11 @@ protected override NodeState ValidateNode( try { - Opc.Ua.Client.Session client = GetClientSession(context); + Opc.Ua.Client.ISession client = GetClientSession(context); // get remote node. NodeId targetId = m_mapper.ToRemoteId(handle.NodeId); - ILocalNode node = client.ReadNode(targetId) as ILocalNode; + ILocalNode node = client.ReadNodeAsync(targetId).GetAwaiter().GetResult(); if (node == null) { diff --git a/Workshop/Aggregation/Server/Browser.cs b/Workshop/Aggregation/Server/Browser.cs index ce2f33394..3082f750d 100644 --- a/Workshop/Aggregation/Server/Browser.cs +++ b/Workshop/Aggregation/Server/Browser.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,6 +29,8 @@ using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; using Opc.Ua; namespace AggregationServer @@ -51,7 +53,7 @@ public Browser( QualifiedName browseName, IEnumerable additionalReferences, bool internalOnly, - Opc.Ua.Client.Session client, + Opc.Ua.Client.ISession client, NamespaceMapper mapper, NodeState source, NodeId rootId) @@ -83,39 +85,105 @@ public override IReference Next() { lock (DataLock) { - IReference reference = null; + return NextAsync().Result; + } + } - // enumerate pre-defined references. - // always call first to ensure any pushed-back references are returned first. - reference = base.Next(); + public async Task NextAsync(CancellationToken ct = default) + { + IReference reference = null; - if (reference != null) - { - return reference; - } + // enumerate pre-defined references. + // always call first to ensure any pushed-back references are returned first. + reference = base.Next(); + + if (reference != null) + { + return reference; + } - // don't start browsing huge number of references when only internal references are requested. - if (InternalOnly) + // don't start browsing huge number of references when only internal references are requested. + if (InternalOnly) + { + return null; + } + + if (m_stage == Stage.Begin) + { + // construct request. + BrowseDescription nodeToBrowse = new BrowseDescription(); + + NodeId startId = ObjectIds.ObjectsFolder; + + if (m_source != null) { - return null; + startId = m_mapper.ToRemoteId(m_source.NodeId); } - if (m_stage == Stage.Begin) + nodeToBrowse.NodeId = startId; + nodeToBrowse.BrowseDirection = this.BrowseDirection; + nodeToBrowse.ReferenceTypeId = this.ReferenceType; + nodeToBrowse.IncludeSubtypes = this.IncludeSubtypes; + nodeToBrowse.NodeClassMask = 0; + nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; + + BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); + nodesToBrowse.Add(nodeToBrowse); + + // start the browse operation. + BrowseResponse response = await m_client.BrowseAsync( + null, + null, + 0, + nodesToBrowse, + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; + + // these do sanity checks on the result - make sure response matched the request. + ClientBase.ValidateResponse(results, nodesToBrowse); + ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); + + m_position = 0; + m_references = null; + m_continuationPoint = null; + m_stage = Stage.References; + + // check status. + if (StatusCode.IsGood(results[0].StatusCode)) { - // construct request. - BrowseDescription nodeToBrowse = new BrowseDescription(); + m_references = results[0].References; + m_continuationPoint = results[0].ContinuationPoint; - NodeId startId = ObjectIds.ObjectsFolder; + reference = await NextChildAsync(ct); - if (m_source != null) + if (reference != null) { - startId = m_mapper.ToRemoteId(m_source.NodeId); + return reference; } + } + } + + if (m_stage == Stage.References) + { + reference = await NextChildAsync(ct); - nodeToBrowse.NodeId = startId; - nodeToBrowse.BrowseDirection = this.BrowseDirection; - nodeToBrowse.ReferenceTypeId = this.ReferenceType; - nodeToBrowse.IncludeSubtypes = this.IncludeSubtypes; + if (reference != null) + { + return reference; + } + + if (m_source == null && IsRequired(ReferenceTypes.HasNotifier, false)) + { + // construct request. + BrowseDescription nodeToBrowse = new BrowseDescription(); + + nodeToBrowse.NodeId = ObjectIds.Server; + nodeToBrowse.BrowseDirection = BrowseDirection.Forward; + nodeToBrowse.ReferenceTypeId = ReferenceTypes.HasNotifier; + nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; @@ -123,16 +191,16 @@ public override IReference Next() nodesToBrowse.Add(nodeToBrowse); // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_client.Browse( + BrowseResponse response = await m_client.BrowseAsync( null, null, 0, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, nodesToBrowse); @@ -141,94 +209,33 @@ public override IReference Next() m_position = 0; m_references = null; m_continuationPoint = null; - m_stage = Stage.References; + m_stage = Stage.Notifiers; // check status. if (StatusCode.IsGood(results[0].StatusCode)) { m_references = results[0].References; m_continuationPoint = results[0].ContinuationPoint; - - reference = NextChild(); - - if (reference != null) - { - return reference; - } } } - if (m_stage == Stage.References) - { - reference = NextChild(); - - if (reference != null) - { - return reference; - } - - if (m_source == null && IsRequired(ReferenceTypes.HasNotifier, false)) - { - // construct request. - BrowseDescription nodeToBrowse = new BrowseDescription(); - - nodeToBrowse.NodeId = ObjectIds.Server; - nodeToBrowse.BrowseDirection = BrowseDirection.Forward; - nodeToBrowse.ReferenceTypeId = ReferenceTypes.HasNotifier; - nodeToBrowse.IncludeSubtypes = true; - nodeToBrowse.NodeClassMask = 0; - nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; - - BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); - nodesToBrowse.Add(nodeToBrowse); - - // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_client.Browse( - null, - null, - 0, - nodesToBrowse, - out results, - out diagnosticInfos); - - // these do sanity checks on the result - make sure response matched the request. - ClientBase.ValidateResponse(results, nodesToBrowse); - ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); - - m_position = 0; - m_references = null; - m_continuationPoint = null; - m_stage = Stage.Notifiers; - - // check status. - if (StatusCode.IsGood(results[0].StatusCode)) - { - m_references = results[0].References; - m_continuationPoint = results[0].ContinuationPoint; - } - } + m_stage = Stage.Notifiers; + } - m_stage = Stage.Notifiers; - } + if (m_stage == Stage.Notifiers) + { + reference = await NextChildAsync(ct); - if (m_stage == Stage.Notifiers) + if (reference != null) { - reference = NextChild(); - - if (reference != null) - { - return reference; - } - - m_stage = Stage.Done; + return reference; } - // all done. - return null; + m_stage = Stage.Done; } + + // all done. + return null; } #endregion @@ -236,7 +243,7 @@ public override IReference Next() /// /// Fetches the next batch of references. /// - private bool BrowseNext() + private async Task BrowseNextAsync(CancellationToken ct = default) { if (m_continuationPoint != null) { @@ -244,15 +251,15 @@ private bool BrowseNext() continuationPoints.Add(m_continuationPoint); // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_client.BrowseNext( + BrowseNextResponse response = await m_client.BrowseNextAsync( null, false, continuationPoints, - out results, - out diagnosticInfos); + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, continuationPoints); @@ -278,7 +285,7 @@ private bool BrowseNext() /// /// Converts a ReferenceDescription to an IReference. /// - private IReference ToReference(ReferenceDescription reference) + private NodeStateReference ToReference(ReferenceDescription reference) { if (reference.NodeId.IsAbsolute || reference.TypeDefinition.IsAbsolute) { @@ -319,7 +326,7 @@ private IReference ToReference(ReferenceDescription reference) /// /// Returns the next child. /// - private IReference NextChild() + private async Task NextChildAsync(CancellationToken ct = default) { // check if a specific browse name is requested. if (!QualifiedName.IsNull(base.BrowseName)) @@ -348,7 +355,7 @@ private IReference NextChild() } } } - while (BrowseNext()); + while (await BrowseNextAsync(ct)); } } @@ -369,7 +376,7 @@ private IReference NextChild() } } } - while (BrowseNext()); + while (await BrowseNextAsync(ct)); } } @@ -393,7 +400,7 @@ private enum Stage #region Private Fields private Stage m_stage; private int m_position; - private Opc.Ua.Client.Session m_client; + private Opc.Ua.Client.ISession m_client; private NamespaceMapper m_mapper; private NodeState m_source; private byte[] m_continuationPoint; diff --git a/Workshop/Aggregation/Server/Program.cs b/Workshop/Aggregation/Server/Program.cs index d63877526..eb075ac4d 100644 --- a/Workshop/Aggregation/Server/Program.cs +++ b/Workshop/Aggregation/Server/Program.cs @@ -44,9 +44,9 @@ static class Program [STAThread] static void Main() { - MyMain().Wait(); + MyMainAsync().Wait(); } - static async Task MyMain() + static async Task MyMainAsync() { // Initialize the user interface. Application.EnableVisualStyles(); @@ -60,13 +60,13 @@ static async Task MyMain() try { // load the application configuration. - await application.LoadApplicationConfiguration(false); + await application.LoadApplicationConfigurationAsync(false); // check the application certificate. - await application.CheckApplicationInstanceCertificates(false); + await application.CheckApplicationInstanceCertificatesAsync(false); // start the server. - await application.Start(new AggregationServer()); + await application.StartAsync(new AggregationServer()); // run the application interactively. Application.Run(new ServerForm(application)); diff --git a/Workshop/AlarmCondition/Client/AddCommentDlg.cs b/Workshop/AlarmCondition/Client/AddCommentDlg.cs index 0c61d3cf3..24f5b2336 100644 --- a/Workshop/AlarmCondition/Client/AddCommentDlg.cs +++ b/Workshop/AlarmCondition/Client/AddCommentDlg.cs @@ -47,10 +47,10 @@ public AddCommentDlg() InitializeComponent(); } #endregion - + #region Private Fields #endregion - + #region Public Interface /// /// Prompts the user to enter a comment. @@ -68,10 +68,10 @@ public string ShowDialog(string comment) return CommentTB.Text; } #endregion - + #region Private Methods #endregion - + #region Event Handlers #endregion } diff --git a/Workshop/AlarmCondition/Client/AlarmCondition Client.csproj b/Workshop/AlarmCondition/Client/AlarmCondition Client.csproj index 93fabd33d..34ded4319 100644 --- a/Workshop/AlarmCondition/Client/AlarmCondition Client.csproj +++ b/Workshop/AlarmCondition/Client/AlarmCondition Client.csproj @@ -48,6 +48,7 @@ false false + AllRules.ruleset pdbonly @@ -60,6 +61,7 @@ false false + AllRules.ruleset @@ -215,7 +217,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/AlarmCondition/Client/AuditEventForm.cs b/Workshop/AlarmCondition/Client/AuditEventForm.cs index ef8f81ffd..3619da710 100644 --- a/Workshop/AlarmCondition/Client/AuditEventForm.cs +++ b/Workshop/AlarmCondition/Client/AuditEventForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,6 +29,8 @@ using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -45,7 +47,7 @@ public partial class AuditEventForm : Form /// /// Creates an empty form. /// - private AuditEventForm() + public AuditEventForm() { InitializeComponent(); } @@ -55,7 +57,8 @@ private AuditEventForm() /// /// The session. /// The subscription. - public AuditEventForm(Session session, Subscription subscription) + /// The cancellation token. + public async Task InitializeAsync(ISession session, Subscription subscription, CancellationToken ct = default) { InitializeComponent(); @@ -74,10 +77,10 @@ public AuditEventForm(Session session, Subscription subscription) m_filter.EventTypes = new NodeId[] { ObjectTypeIds.AuditUpdateMethodEventType }; // find the fields of interest. - m_filter.SelectClauses = m_filter.ConstructSelectClauses(m_session, ObjectTypeIds.AuditUpdateMethodEventType); + m_filter.SelectClauses = await m_filter.ConstructSelectClausesAsync(m_session, ct, ObjectTypeIds.AuditUpdateMethodEventType); // declate callback. - m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); + m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); // create a monitored item based on the current filter settings. m_monitoredItem = m_filter.CreateMonitoredItem(m_session); @@ -86,7 +89,7 @@ public AuditEventForm(Session session, Subscription subscription) m_monitoredItem.Notification += m_MonitoredItem_Notification; m_subscription.AddItem(m_monitoredItem); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); } #endregion @@ -96,7 +99,7 @@ public AuditEventForm(Session session, Subscription subscription) ///
/// The new session. /// The new subscription. - public void ReconnectComplete(Session session, Subscription subscription) + public void ReconnectComplete(ISession session, Subscription subscription) { m_session = session; m_subscription = subscription; @@ -113,11 +116,11 @@ public void ReconnectComplete(Session session, Subscription subscription) #endregion #region Private Fields - private Session m_session; + private ISession m_session; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private FilterDefinition m_filter; - private Dictionary m_eventTypeMappings; + private Dictionary m_eventTypeMappings; private MonitoredItemNotificationEventHandler m_MonitoredItem_Notification; #endregion @@ -126,13 +129,13 @@ public void ReconnectComplete(Session session, Subscription subscription) #region Event Handlers /// - /// Updates the display with a new value for a monitored variable. + /// Updates the display with a new value for a monitored variable. /// - private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) + private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (this.InvokeRequired) { - this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_Notification), monitoredItem, e); + this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync), monitoredItem, e); return; } @@ -155,9 +158,9 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt } // construct the audit object. - AuditUpdateMethodEventState audit = FormUtils.ConstructEvent( - m_session, - monitoredItem, + AuditUpdateMethodEventState audit = await FormUtils.ConstructEventAsync( + m_session, + monitoredItem, notification, m_eventTypeMappings) as AuditUpdateMethodEventState; @@ -175,9 +178,9 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt item.SubItems.Add(String.Empty); // Time item.SubItems.Add(String.Empty); // Message item.SubItems.Add(String.Empty); // Arguments - + // look up the condition type metadata in the local cache. - INode type = m_session.NodeCache.Find(audit.TypeDefinitionId); + INode type = await m_session.NodeCache.FindAsync(audit.TypeDefinitionId); // Source if (audit.SourceName != null) @@ -200,7 +203,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt } // look up the method metadata in the local cache. - INode method = m_session.NodeCache.Find(BaseVariableState.GetValue(audit.MethodId)); + INode method = await m_session.NodeCache.FindAsync(BaseVariableState.GetValue(audit.MethodId)); // Method if (method != null) diff --git a/Workshop/AlarmCondition/Client/DialogResponseDlg.cs b/Workshop/AlarmCondition/Client/DialogResponseDlg.cs index 7f89ed3e6..b2e341c83 100644 --- a/Workshop/AlarmCondition/Client/DialogResponseDlg.cs +++ b/Workshop/AlarmCondition/Client/DialogResponseDlg.cs @@ -48,7 +48,7 @@ public DialogResponseDlg() InitializeComponent(); } #endregion - + #region Public Interface /// /// Prompts the user to enter a comment. @@ -58,11 +58,11 @@ public int ShowDialog(DialogConditionState dialog) // set the prompt. PromptLB.Text = Utils.Format("{0}", BaseVariableState.GetValue(dialog.Prompt)); - Dictionary resultMapping = new Dictionary(); + Dictionary resultMapping = new Dictionary(); // configure the buttons. LocalizedText[] options = BaseVariableState.GetValue(dialog.ResponseOptionSet); - + switch (options.Length) { case 1: @@ -74,7 +74,7 @@ public int ShowDialog(DialogConditionState dialog) ButtonsPN.ColumnStyles[2].Width = 0; ButtonsPN.ColumnStyles[3].Width = 0; ButtonsPN.ColumnStyles[4].Width = 50; - + resultMapping.Add(DialogResult.OK, 0); break; } diff --git a/Workshop/AlarmCondition/Client/FilterDefinition.cs b/Workshop/AlarmCondition/Client/FilterDefinition.cs index 587b76153..9d2248c2f 100644 --- a/Workshop/AlarmCondition/Client/FilterDefinition.cs +++ b/Workshop/AlarmCondition/Client/FilterDefinition.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,6 +29,8 @@ using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; using Opc.Ua; using Opc.Ua.Client; @@ -49,7 +51,7 @@ public class FilterDefinition /// The minimum severity for the events of interest. /// public EventSeverity Severity; - + /// /// The types for the events of interest. /// @@ -59,18 +61,18 @@ public class FilterDefinition /// Whether suppressed or shelved condition events are of interest. ///
public bool IgnoreSuppressedOrShelved; - + /// /// The select clauses to use with the filter. /// public SimpleAttributeOperandCollection SelectClauses; - + /// /// Creates the monitored item based on the current definition. /// /// The session. /// The monitored item. - public MonitoredItem CreateMonitoredItem(Session session) + public MonitoredItem CreateMonitoredItem(ISession session) { // choose the server object by default. if (AreaId == null) @@ -109,13 +111,14 @@ public MonitoredItem CreateMonitoredItem(Session session) /// /// Each event type is an ObjectType in the address space. The fields supported by the /// server are defined as children of the ObjectType. Many of the fields are manadatory - /// and are defined by the UA information model, however, indiviudual servers many not + /// and are defined by the UA information model, however, indiviudual servers many not /// support all of the optional fields. - /// - /// This method browses the type model and + /// + /// This method browses the type model and /// - public SimpleAttributeOperandCollection ConstructSelectClauses( - Session session, + public async Task ConstructSelectClausesAsync( + ISession session, + CancellationToken ct, params NodeId[] eventTypeIds) { // browse the type model in the server address space to find the fields available for the event type. @@ -136,14 +139,14 @@ public SimpleAttributeOperandCollection ConstructSelectClauses( { for (int ii = 0; ii < eventTypeIds.Length; ii++) { - CollectFields(session, eventTypeIds[ii], selectClauses); + await CollectFieldsAsync(session, eventTypeIds[ii], selectClauses, ct); } } // use BaseEventType as the default if no EventTypes specified. else { - CollectFields(session, ObjectTypeIds.BaseEventType, selectClauses); + await CollectFieldsAsync(session, ObjectTypeIds.BaseEventType, selectClauses, ct); } return selectClauses; @@ -153,7 +156,7 @@ public SimpleAttributeOperandCollection ConstructSelectClauses( /// Constructs the event filter for the subscription. ///
/// The event filter. - public EventFilter ConstructFilter(Session session) + public EventFilter ConstructFilter(ISession session) { EventFilter filter = new EventFilter(); @@ -203,7 +206,7 @@ public EventFilter ConstructFilter(Session session) // specify that the Severity property must Equal the value specified. element2 = whereClause.Push(FilterOperator.Equals, operand1, operand2); - + // chain multiple elements together with an AND clause. if (element1 != null) { @@ -223,7 +226,7 @@ public EventFilter ConstructFilter(Session session) // save the last element. for (int ii = 0; ii < EventTypes.Count; ii++) { - // for this example uses the 'OfType' operator to limit events to thoses with specified event type. + // for this example uses the 'OfType' operator to limit events to thoses with specified event type. LiteralOperand operand1 = new LiteralOperand(); operand1.Value = new Variant(EventTypes[ii]); ContentFilterElement element3 = whereClause.Push(FilterOperator.OfType, operand1); @@ -252,7 +255,7 @@ public EventFilter ConstructFilter(Session session) return filter; } #endregion - + #region Private Methods /// /// Collects the fields for the event type. @@ -260,10 +263,11 @@ public EventFilter ConstructFilter(Session session) /// The session. /// The event type id. /// The event fields. - private void CollectFields(Session session, NodeId eventTypeId, SimpleAttributeOperandCollection eventFields) + /// The token to cancel the request + private async Task CollectFieldsAsync(ISession session, NodeId eventTypeId, SimpleAttributeOperandCollection eventFields, CancellationToken ct = default) { // get the supertypes. - ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes(session, eventTypeId, false); + ReferenceDescriptionCollection supertypes = await FormUtils.BrowseSuperTypesAsync(session, eventTypeId, false, ct); if (supertypes == null) { @@ -271,16 +275,16 @@ private void CollectFields(Session session, NodeId eventTypeId, SimpleAttributeO } // process the types starting from the top of the tree. - Dictionary foundNodes = new Dictionary(); + Dictionary foundNodes = new Dictionary(); QualifiedNameCollection parentPath = new QualifiedNameCollection(); - for (int ii = supertypes.Count-1; ii >= 0; ii--) + for (int ii = supertypes.Count - 1; ii >= 0; ii--) { - CollectFields(session, (NodeId)supertypes[ii].NodeId, parentPath, eventFields, foundNodes); + await CollectFieldsAsync(session, (NodeId)supertypes[ii].NodeId, parentPath, eventFields, foundNodes, ct); } // collect the fields for the selected type. - CollectFields(session, eventTypeId, parentPath, eventFields, foundNodes); + await CollectFieldsAsync(session, eventTypeId, parentPath, eventFields, foundNodes, ct); } /// @@ -291,12 +295,14 @@ private void CollectFields(Session session, NodeId eventTypeId, SimpleAttributeO /// The parent path. /// The event fields. /// The table of found nodes. - private void CollectFields( - Session session, + /// The token to cancel the request + private async Task CollectFieldsAsync( + ISession session, NodeId nodeId, QualifiedNameCollection parentPath, SimpleAttributeOperandCollection eventFields, - Dictionary foundNodes) + Dictionary foundNodes, + CancellationToken ct = default) { // find all of the children of the field. BrowseDescription nodeToBrowse = new BrowseDescription(); @@ -308,7 +314,7 @@ private void CollectFields( nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; - ReferenceDescriptionCollection children = FormUtils.Browse(session, nodeToBrowse, false); + ReferenceDescriptionCollection children = await FormUtils.BrowseAsync(session, nodeToBrowse, false, ct); if (children == null) { @@ -336,7 +342,7 @@ private void CollectFields( field.TypeDefinitionId = ObjectTypeIds.BaseEventType; field.BrowsePath = browsePath; - field.AttributeId = (child.NodeClass == NodeClass.Variable)?Attributes.Value:Attributes.NodeId; + field.AttributeId = (child.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId; eventFields.Add(field); } @@ -348,7 +354,7 @@ private void CollectFields( if (!foundNodes.ContainsKey(targetId)) { foundNodes.Add(targetId, browsePath); - CollectFields(session, (NodeId)child.NodeId, browsePath, eventFields, foundNodes); + await CollectFieldsAsync(session, (NodeId)child.NodeId, browsePath, eventFields, foundNodes, ct); } } } diff --git a/Workshop/AlarmCondition/Client/FormUtils.cs b/Workshop/AlarmCondition/Client/FormUtils.cs index 77d84965a..4c75780ed 100644 --- a/Workshop/AlarmCondition/Client/FormUtils.cs +++ b/Workshop/AlarmCondition/Client/FormUtils.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,6 +29,8 @@ using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; using Opc.Ua; using Opc.Ua.Client; @@ -42,7 +44,7 @@ public static class FormUtils /// /// The known event types which can be constructed by ConstructEvent() /// - public static NodeId[] KnownEventTypes = new NodeId[] + public static NodeId[] KnownEventTypes = new NodeId[] { ObjectTypeIds.BaseEventType, ObjectTypeIds.ConditionType, @@ -60,7 +62,7 @@ public static class FormUtils /// The discovery URL. /// if set to true select an endpoint that uses security. /// The best available endpoint. - public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSecurity) + public static async Task SelectEndpointAsync(string discoveryUrl, bool useSecurity, CancellationToken ct = default) { // needs to add the '/discovery' back onto non-UA TCP URLs. if (!discoveryUrl.StartsWith(Utils.UriSchemeOpcTcp)) @@ -83,9 +85,9 @@ public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSe // Connect to the server's discovery endpoint and find the available configuration. using (DiscoveryClient client = DiscoveryClient.Create(uri, configuration)) { - EndpointDescriptionCollection endpoints = client.GetEndpoints(null); + EndpointDescriptionCollection endpoints = await client.GetEndpointsAsync(null, ct); - // select the best endpoint to use based on the selected URL and the UseSecurity checkbox. + // select the best endpoint to use based on the selected URL and the UseSecurity checkbox. for (int ii = 0; ii < endpoints.Count; ii++) { EndpointDescription endpoint = endpoints[ii]; @@ -104,7 +106,7 @@ public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSe { if (endpoint.SecurityMode != MessageSecurityMode.None) { - // The security level is a relative measure assigned by the server to the + // The security level is a relative measure assigned by the server to the // endpoints that it returns. Clients should always pick the highest level // unless they have a reason not too. if (endpoint.SecurityLevel > selectedEndpoint.SecurityLevel) @@ -133,7 +135,7 @@ public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSe } // if a server is behind a firewall it may return URLs that are not accessible to the client. - // This problem can be avoided by assuming that the domain in the URL used to call + // This problem can be avoided by assuming that the domain in the URL used to call // GetEndpoints can be used to access any of the endpoints. This code makes that conversion. // Note that the conversion only makes sense if discovery uses the same protocol as the endpoint. @@ -184,14 +186,16 @@ public static NodeId FindEventType(MonitoredItem monitoredItem, EventFieldList n /// The monitored item that produced the notification. /// The notification. /// Mapping between event types and known event types. + /// The token to cancel the request /// /// The event object. Null if the notification is not a valid event type. /// - public static BaseEventState ConstructEvent( - Session session, + public static async Task ConstructEventAsync( + ISession session, MonitoredItem monitoredItem, EventFieldList notification, - Dictionary eventTypeMappings) + Dictionary eventTypeMappings, + CancellationToken ct = default) { // find the event type. NodeId eventTypeId = FindEventType(monitoredItem, notification); @@ -216,11 +220,11 @@ public static BaseEventState ConstructEvent( break; } } - + // browse for the supertypes of the event type. if (knownTypeId == null) { - ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes(session, eventTypeId, false); + ReferenceDescriptionCollection supertypes = await FormUtils.BrowseSuperTypesAsync(session, eventTypeId, false, ct); // can't do anything with unknown types. if (supertypes == null) @@ -293,7 +297,7 @@ public static BaseEventState ConstructEvent( return e; } - + /// /// Browses the address space and returns the references found. /// @@ -303,7 +307,7 @@ public static BaseEventState ConstructEvent( /// /// The references found. Null if an error occurred. /// - public static ReferenceDescriptionCollection Browse(Session session, BrowseDescription nodeToBrowse, bool throwOnError) + public static async Task BrowseAsync(ISession session, BrowseDescription nodeToBrowse, bool throwOnError, CancellationToken ct = default) { try { @@ -314,16 +318,15 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr nodesToBrowse.Add(nodeToBrowse); // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - session.Browse( + BrowseResponse response = await session.BrowseAsync( null, null, 0, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); @@ -352,12 +355,14 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); - session.BrowseNext( + BrowseNextResponse response2 = await session.BrowseNextAsync( null, false, continuationPoints, - out results, - out diagnosticInfos); + ct); + + results = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); @@ -387,7 +392,7 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr /// /// The references found. Null if an error occurred. /// - public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, NodeId typeId, bool throwOnError) + public static async Task BrowseSuperTypesAsync(ISession session, NodeId typeId, bool throwOnError, CancellationToken ct = default) { ReferenceDescriptionCollection supertypes = new ReferenceDescriptionCollection(); @@ -400,15 +405,15 @@ public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, N nodeToBrowse.BrowseDirection = BrowseDirection.Inverse; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype; nodeToBrowse.IncludeSubtypes = false; // more efficient to use IncludeSubtypes=False when possible. - nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. + nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; - - ReferenceDescriptionCollection references = Browse(session, nodeToBrowse, throwOnError); + + ReferenceDescriptionCollection references = await BrowseAsync(session, nodeToBrowse, throwOnError, ct); while (references != null && references.Count > 0) { // should never be more than one supertype. - supertypes.Add(references[0]); + supertypes.Add(references[0]); // only follow references within this server. if (references[0].NodeId.IsAbsolute) @@ -418,7 +423,7 @@ public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, N // get the references for the next level up. nodeToBrowse.NodeId = (NodeId)references[0].NodeId; - references = Browse(session, nodeToBrowse, throwOnError); + references = await BrowseAsync(session, nodeToBrowse, throwOnError, ct); } // return complete list. diff --git a/Workshop/AlarmCondition/Client/MainForm.Designer.cs b/Workshop/AlarmCondition/Client/MainForm.Designer.cs index c77f7e4a7..8254ecca1 100644 --- a/Workshop/AlarmCondition/Client/MainForm.Designer.cs +++ b/Workshop/AlarmCondition/Client/MainForm.Designer.cs @@ -208,7 +208,7 @@ private void InitializeComponent() this.Conditions_RefreshMI.Name = "Conditions_RefreshMI"; this.Conditions_RefreshMI.Size = new System.Drawing.Size(157, 22); this.Conditions_RefreshMI.Text = "Refresh"; - this.Conditions_RefreshMI.Click += new System.EventHandler(this.Conditions_RefreshMI_Click); + this.Conditions_RefreshMI.Click += new System.EventHandler(this.Conditions_RefreshMI_ClickAsync); // // toolStripSeparator2 // @@ -220,7 +220,7 @@ private void InitializeComponent() this.Conditions_SetAreaFilterMI.Name = "Conditions_SetAreaFilterMI"; this.Conditions_SetAreaFilterMI.Size = new System.Drawing.Size(157, 22); this.Conditions_SetAreaFilterMI.Text = "Set Area Filter..."; - this.Conditions_SetAreaFilterMI.Click += new System.EventHandler(this.Conditions_SetAreaFilterMI_Click); + this.Conditions_SetAreaFilterMI.Click += new System.EventHandler(this.Conditions_SetAreaFilterMI_ClickAsync); // // Conditions_SetTypeMI // @@ -241,35 +241,35 @@ private void InitializeComponent() this.Condition_Type_AllMI.Name = "Condition_Type_AllMI"; this.Condition_Type_AllMI.Size = new System.Drawing.Size(148, 22); this.Condition_Type_AllMI.Text = "All"; - this.Condition_Type_AllMI.Click += new System.EventHandler(this.Conditions_TypeMI_Click); + this.Condition_Type_AllMI.Click += new System.EventHandler(this.Conditions_TypeMI_ClickAsync); // // Condition_Type_DialogsMI // this.Condition_Type_DialogsMI.Name = "Condition_Type_DialogsMI"; this.Condition_Type_DialogsMI.Size = new System.Drawing.Size(148, 22); this.Condition_Type_DialogsMI.Text = "Dialogs"; - this.Condition_Type_DialogsMI.Click += new System.EventHandler(this.Conditions_TypeMI_Click); + this.Condition_Type_DialogsMI.Click += new System.EventHandler(this.Conditions_TypeMI_ClickAsync); // // Condition_Type_AlarmsMI // this.Condition_Type_AlarmsMI.Name = "Condition_Type_AlarmsMI"; this.Condition_Type_AlarmsMI.Size = new System.Drawing.Size(148, 22); this.Condition_Type_AlarmsMI.Text = "Alarms"; - this.Condition_Type_AlarmsMI.Click += new System.EventHandler(this.Conditions_TypeMI_Click); + this.Condition_Type_AlarmsMI.Click += new System.EventHandler(this.Conditions_TypeMI_ClickAsync); // // Condition_Type_LimitAlarmsMI // this.Condition_Type_LimitAlarmsMI.Name = "Condition_Type_LimitAlarmsMI"; this.Condition_Type_LimitAlarmsMI.Size = new System.Drawing.Size(148, 22); this.Condition_Type_LimitAlarmsMI.Text = "Limit Alarms"; - this.Condition_Type_LimitAlarmsMI.Click += new System.EventHandler(this.Conditions_TypeMI_Click); + this.Condition_Type_LimitAlarmsMI.Click += new System.EventHandler(this.Conditions_TypeMI_ClickAsync); // // Condition_Type_DiscreteAlarmsMI // this.Condition_Type_DiscreteAlarmsMI.Name = "Condition_Type_DiscreteAlarmsMI"; this.Condition_Type_DiscreteAlarmsMI.Size = new System.Drawing.Size(148, 22); this.Condition_Type_DiscreteAlarmsMI.Text = "Discrete Alarms"; - this.Condition_Type_DiscreteAlarmsMI.Click += new System.EventHandler(this.Conditions_TypeMI_Click); + this.Condition_Type_DiscreteAlarmsMI.Click += new System.EventHandler(this.Conditions_TypeMI_ClickAsync); // // Conditions_SetSeverityMI // @@ -289,28 +289,28 @@ private void InitializeComponent() this.Conditions_Severity_AllMI.Name = "Conditions_Severity_AllMI"; this.Conditions_Severity_AllMI.Size = new System.Drawing.Size(110, 22); this.Conditions_Severity_AllMI.Text = "All"; - this.Conditions_Severity_AllMI.Click += new System.EventHandler(this.Conditions_SeverityMI_Click); + this.Conditions_Severity_AllMI.Click += new System.EventHandler(this.Conditions_SeverityMI_ClickAsync); // // Conditions_Severity_LowMI // this.Conditions_Severity_LowMI.Name = "Conditions_Severity_LowMI"; this.Conditions_Severity_LowMI.Size = new System.Drawing.Size(110, 22); this.Conditions_Severity_LowMI.Text = "Low"; - this.Conditions_Severity_LowMI.Click += new System.EventHandler(this.Conditions_SeverityMI_Click); + this.Conditions_Severity_LowMI.Click += new System.EventHandler(this.Conditions_SeverityMI_ClickAsync); // // Conditions_Severity_MediumMI // this.Conditions_Severity_MediumMI.Name = "Conditions_Severity_MediumMI"; this.Conditions_Severity_MediumMI.Size = new System.Drawing.Size(110, 22); this.Conditions_Severity_MediumMI.Text = "Medium"; - this.Conditions_Severity_MediumMI.Click += new System.EventHandler(this.Conditions_SeverityMI_Click); + this.Conditions_Severity_MediumMI.Click += new System.EventHandler(this.Conditions_SeverityMI_ClickAsync); // // Conditions_Severity_HighMI // this.Conditions_Severity_HighMI.Name = "Conditions_Severity_HighMI"; this.Conditions_Severity_HighMI.Size = new System.Drawing.Size(110, 22); this.Conditions_Severity_HighMI.Text = "High"; - this.Conditions_Severity_HighMI.Click += new System.EventHandler(this.Conditions_SeverityMI_Click); + this.Conditions_Severity_HighMI.Click += new System.EventHandler(this.Conditions_SeverityMI_ClickAsync); // // toolStripSeparator1 // @@ -322,42 +322,42 @@ private void InitializeComponent() this.Conditions_EnableMI.Name = "Conditions_EnableMI"; this.Conditions_EnableMI.Size = new System.Drawing.Size(157, 22); this.Conditions_EnableMI.Text = "Enable"; - this.Conditions_EnableMI.Click += new System.EventHandler(this.Conditions_EnableMI_Click); + this.Conditions_EnableMI.Click += new System.EventHandler(this.Conditions_EnableMI_ClickAsync); // // Conditions_DisableMI // this.Conditions_DisableMI.Name = "Conditions_DisableMI"; this.Conditions_DisableMI.Size = new System.Drawing.Size(157, 22); this.Conditions_DisableMI.Text = "Disable"; - this.Conditions_DisableMI.Click += new System.EventHandler(this.Conditions_DisableMI_Click); + this.Conditions_DisableMI.Click += new System.EventHandler(this.Conditions_DisableMI_ClickAsync); // // Conditions_AddCommentMI // this.Conditions_AddCommentMI.Name = "Conditions_AddCommentMI"; this.Conditions_AddCommentMI.Size = new System.Drawing.Size(157, 22); this.Conditions_AddCommentMI.Text = "Add Comment..."; - this.Conditions_AddCommentMI.Click += new System.EventHandler(this.Conditions_AddCommentMI_Click); + this.Conditions_AddCommentMI.Click += new System.EventHandler(this.Conditions_AddCommentMI_ClickAsync); // // Conditions_AcknowledgeMI // this.Conditions_AcknowledgeMI.Name = "Conditions_AcknowledgeMI"; this.Conditions_AcknowledgeMI.Size = new System.Drawing.Size(157, 22); this.Conditions_AcknowledgeMI.Text = "Acknowledge..."; - this.Conditions_AcknowledgeMI.Click += new System.EventHandler(this.Conditions_AcknowledgeMI_Click); + this.Conditions_AcknowledgeMI.Click += new System.EventHandler(this.Conditions_AcknowledgeMI_ClickAsync); // // Conditions_ConfirmMI // this.Conditions_ConfirmMI.Name = "Conditions_ConfirmMI"; this.Conditions_ConfirmMI.Size = new System.Drawing.Size(157, 22); this.Conditions_ConfirmMI.Text = "Confirm..."; - this.Conditions_ConfirmMI.Click += new System.EventHandler(this.Conditions_ConfirmMI_Click); + this.Conditions_ConfirmMI.Click += new System.EventHandler(this.Conditions_ConfirmMI_ClickAsync); // // Conditions_RespondMI // this.Conditions_RespondMI.Name = "Conditions_RespondMI"; this.Conditions_RespondMI.Size = new System.Drawing.Size(157, 22); this.Conditions_RespondMI.Text = "Respond..."; - this.Conditions_RespondMI.Click += new System.EventHandler(this.Conditions_RespondMI_Click); + this.Conditions_RespondMI.Click += new System.EventHandler(this.Conditions_RespondMI_ClickAsync); // // Conditions_ShelvingMI // @@ -375,28 +375,28 @@ private void InitializeComponent() this.Conditions_UnshelveMI.Name = "Conditions_UnshelveMI"; this.Conditions_UnshelveMI.Size = new System.Drawing.Size(154, 22); this.Conditions_UnshelveMI.Text = "Unshelve"; - this.Conditions_UnshelveMI.Click += new System.EventHandler(this.Conditions_UnshelveMI_Click); + this.Conditions_UnshelveMI.Click += new System.EventHandler(this.Conditions_UnshelveMI_ClickAsync); // // Conditions_ManualShelveMI // this.Conditions_ManualShelveMI.Name = "Conditions_ManualShelveMI"; this.Conditions_ManualShelveMI.Size = new System.Drawing.Size(154, 22); this.Conditions_ManualShelveMI.Text = "Manual Shelve"; - this.Conditions_ManualShelveMI.Click += new System.EventHandler(this.Conditions_ManualShelveMI_Click); + this.Conditions_ManualShelveMI.Click += new System.EventHandler(this.Conditions_ManualShelveMI_ClickAsync); // // Conditions_OneShotShelveMI // this.Conditions_OneShotShelveMI.Name = "Conditions_OneShotShelveMI"; this.Conditions_OneShotShelveMI.Size = new System.Drawing.Size(154, 22); this.Conditions_OneShotShelveMI.Text = "One Shot Shelve"; - this.Conditions_OneShotShelveMI.Click += new System.EventHandler(this.Conditions_OneShotShelveMI_Click); + this.Conditions_OneShotShelveMI.Click += new System.EventHandler(this.Conditions_OneShotShelveMI_ClickAsync); // // Conditions_TimedShelveMI // this.Conditions_TimedShelveMI.Name = "Conditions_TimedShelveMI"; this.Conditions_TimedShelveMI.Size = new System.Drawing.Size(154, 22); this.Conditions_TimedShelveMI.Text = "Timed Shelve..."; - this.Conditions_TimedShelveMI.Click += new System.EventHandler(this.Conditions_TimedShelveMI_Click); + this.Conditions_TimedShelveMI.Click += new System.EventHandler(this.Conditions_TimedShelveMI_ClickAsync); // // ViewMI // @@ -411,7 +411,7 @@ private void InitializeComponent() this.View_AuditEventsMI.Name = "View_AuditEventsMI"; this.View_AuditEventsMI.Size = new System.Drawing.Size(147, 22); this.View_AuditEventsMI.Text = "Audit Events..."; - this.View_AuditEventsMI.Click += new System.EventHandler(this.View_AuditEventsMI_Click); + this.View_AuditEventsMI.Click += new System.EventHandler(this.View_AuditEventsMI_ClickAsync); // // HelpMI // @@ -521,9 +521,9 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); - this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); + this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectCompleteAsync); // // clientHeaderBranding1 // diff --git a/Workshop/AlarmCondition/Client/MainForm.cs b/Workshop/AlarmCondition/Client/MainForm.cs index caa6f89b3..cb4272cb7 100644 --- a/Workshop/AlarmCondition/Client/MainForm.cs +++ b/Workshop/AlarmCondition/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -37,6 +37,7 @@ using Opc.Ua.Client; using Opc.Ua.Client.Controls; using System.Threading.Tasks; +using System.Threading; namespace Quickstarts.AlarmConditionClient { @@ -80,7 +81,7 @@ public MainForm(ApplicationConfiguration configuration) m_filter.EventTypes = new NodeId[] { ObjectTypeIds.ConditionType }; // declate callback. - m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); + m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); // initialize controls. Conditions_Severity_AllMI.Checked = true; @@ -99,7 +100,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private FilterDefinition m_filter; @@ -120,7 +121,7 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -161,7 +162,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -197,11 +198,12 @@ private void Server_ConnectComplete(object sender, EventArgs e) m_subscription.TimestampsToReturn = TimestampsToReturn.Both; m_session.AddSubscription(m_subscription); - m_subscription.Create(); + await m_subscription.CreateAsync(); // must specify the fields that the form is interested in. - m_filter.SelectClauses = m_filter.ConstructSelectClauses( + m_filter.SelectClauses = await m_filter.ConstructSelectClausesAsync( m_session, + default, NodeId.Parse("ns=2;s=4:2"), NodeId.Parse("ns=2;s=4:1"), ObjectTypeIds.DialogConditionType, @@ -215,10 +217,10 @@ private void Server_ConnectComplete(object sender, EventArgs e) m_monitoredItem.Notification += m_MonitoredItem_Notification; m_subscription.AddItem(m_monitoredItem); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(); // send an initial refresh. - Conditions_RefreshMI_Click(sender, e); + Conditions_RefreshMI_ClickAsync(sender, e); ConditionsMI.Enabled = true; ViewMI.Enabled = true; @@ -248,7 +250,7 @@ private void Server_ReconnectStarting(object sender, EventArgs e) /// /// Updates the application after reconnecting to the server. /// - private void Server_ReconnectComplete(object sender, EventArgs e) + private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) { try { @@ -277,7 +279,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } // send a refresh. - m_subscription.ConditionRefresh(); + await m_subscription.ConditionRefreshAsync(); ConditionsMI.Enabled = true; ViewMI.Enabled = true; @@ -301,11 +303,11 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) /// /// Updates the filter. /// - private void UpdateFilter() + private async Task UpdateFilterAsync(CancellationToken ct = default) { if (m_subscription != null) { - // changing the filter changes the fields requested. this makes it + // changing the filter changes the fields requested. this makes it // impossible to process notifications sent before the change. // to avoid this problem we create a new item and remove the old one. MonitoredItem monitoredItem = m_filter.CreateMonitoredItem(m_session); @@ -315,14 +317,14 @@ private void UpdateFilter() m_subscription.AddItem(monitoredItem); m_subscription.RemoveItem(m_monitoredItem); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); // replace monitored item. m_monitoredItem.Notification -= m_MonitoredItem_Notification; m_monitoredItem = monitoredItem; // send a refresh since previously filtered conditions may be now available. - Conditions_RefreshMI_Click(this, null); + Conditions_RefreshMI_ClickAsync(this, null); } } @@ -330,22 +332,22 @@ private void UpdateFilter() /// Enables or disables the selected conditions. /// /// if set to true the conditions are enabled. - private void EnableDisableCondition(bool enable) + private async Task EnableDisableConditionAsync(bool enable, CancellationToken ct = default) { if (enable) { - CallMethod(MethodIds.ConditionType_Enable, null); + await CallMethodAsync(MethodIds.ConditionType_Enable, null, ct); } else { - CallMethod(MethodIds.ConditionType_Disable, null); + await CallMethodAsync(MethodIds.ConditionType_Disable, null, ct); } } /// /// Adds a comment to the selected conditions. /// - private void AddComment() + private async Task AddCommentAsync(CancellationToken ct = default) { string comment = new AddCommentDlg().ShowDialog(String.Empty); @@ -354,13 +356,13 @@ private void AddComment() return; } - CallMethod(MethodIds.ConditionType_AddComment, comment); + await CallMethodAsync(MethodIds.ConditionType_AddComment, comment, ct); } /// /// Acknowledges the selected conditions. /// - private void Acknowledge() + private async Task AcknowledgeAsync(CancellationToken ct = default) { string comment = new AddCommentDlg().ShowDialog(String.Empty); @@ -369,13 +371,13 @@ private void Acknowledge() return; } - CallMethod(MethodIds.AcknowledgeableConditionType_Acknowledge, comment); + await CallMethodAsync(MethodIds.AcknowledgeableConditionType_Acknowledge, comment, ct); } /// /// Confirms the selected conditions. /// - private void Confirm() + private async Task ConfirmAsync(CancellationToken ct = default) { string comment = new AddCommentDlg().ShowDialog(String.Empty); @@ -384,13 +386,13 @@ private void Confirm() return; } - CallMethod(MethodIds.AcknowledgeableConditionType_Confirm, comment); + await CallMethodAsync(MethodIds.AcknowledgeableConditionType_Confirm, comment, ct); } /// /// Confirms the selected conditions. /// - private void Shelve(bool shelving, bool oneShot, double shelvingTime) + private async Task ShelveAsync(bool shelving, bool oneShot, double shelvingTime, CancellationToken ct = default) { // build list of methods to call. CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection(); @@ -439,14 +441,12 @@ private void Shelve(bool shelving, bool oneShot, double shelvingTime) } // call the methods. - CallMethodResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Call( + CallResponse response = await m_session.CallAsync( null, methodsToCall, - out results, - out diagnosticInfos); + ct); + CallMethodResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, methodsToCall); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, methodsToCall); @@ -460,11 +460,11 @@ private void Shelve(bool shelving, bool oneShot, double shelvingTime) } } } - + /// /// Responds to the dialog. /// - private void Respond(int selectedResponse) + private async Task RespondAsync(int selectedResponse, CancellationToken ct = default) { // build list of dialogs to respond to (caller should always make sure that only one is selected). CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection(); @@ -494,14 +494,13 @@ private void Respond(int selectedResponse) } // call the methods. - CallMethodResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Call( + CallResponse response = await m_session.CallAsync( null, methodsToCall, - out results, - out diagnosticInfos); + ct); + + CallMethodResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, methodsToCall); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, methodsToCall); @@ -521,7 +520,8 @@ private void Respond(int selectedResponse) /// /// The NodeId for the method to call. /// The comment to pass as an argument. - private void CallMethod(NodeId methodId, string comment) + /// The token to cancel the request + private async Task CallMethodAsync(NodeId methodId, string comment, CancellationToken ct = default) { // build list of methods to call. CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection(); @@ -551,14 +551,13 @@ private void CallMethod(NodeId methodId, string comment) } // call the methods. - CallMethodResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Call( + CallResponse response = await m_session.CallAsync( null, methodsToCall, - out results, - out diagnosticInfos); + ct); + + CallMethodResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, methodsToCall); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, methodsToCall); @@ -576,13 +575,13 @@ private void CallMethod(NodeId methodId, string comment) #region Event Handlers /// - /// Updates the display with a new value for a monitored variable. + /// Updates the display with a new value for a monitored variable. /// - private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) + private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (this.InvokeRequired) { - this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_Notification), monitoredItem, e); + this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync), monitoredItem, e); return; } @@ -603,7 +602,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt { return; } - + // check for refresh start. if (eventTypeId == ObjectTypeIds.RefreshStartEventType) { @@ -616,11 +615,11 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt { return; } - + // construct the condition object. - ConditionState condition = FormUtils.ConstructEvent( - m_session, - monitoredItem, + ConditionState condition = await FormUtils.ConstructEventAsync( + m_session, + monitoredItem, notification, m_eventTypeMappings) as ConditionState; @@ -636,7 +635,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt { ConditionState current = (ConditionState)ConditionsLV.Items[ii].Tag; - // the combination of a condition and branch id uniquely identify an item in the display. + // the combination of a condition and branch id uniquely identify an item in the display. if (current.NodeId == condition.NodeId && BaseVariableState.GetValue(current.BranchId) == BaseVariableState.GetValue(condition.BranchId)) { // match found but watch out for out of order events (async processing can cause this to happen). @@ -649,7 +648,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt break; } } - + // create a new entry. if (item == null) { @@ -668,7 +667,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt } // look up the condition type metadata in the local cache. - INode type = m_session.NodeCache.Find(condition.TypeDefinitionId); + INode type = await m_session.NodeCache.FindAsync(condition.TypeDefinitionId); // Source if (condition.SourceName != null) @@ -796,7 +795,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt ///
/// The source of the event. /// The instance containing the event data. - private void Conditions_RefreshMI_Click(object sender, EventArgs e) + private async void Conditions_RefreshMI_ClickAsync(object sender, EventArgs e) { try { @@ -805,18 +804,17 @@ private void Conditions_RefreshMI_Click(object sender, EventArgs e) request.ObjectId = ObjectTypeIds.ConditionType; request.MethodId = MethodIds.ConditionType_ConditionRefresh; request.InputArguments.Add(new Variant(m_subscription.Id)); - + CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection(); methodsToCall.Add(request); - CallMethodResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Call( + CallResponse response = await m_session.CallAsync( null, methodsToCall, - out results, - out diagnosticInfos); + default); + + CallMethodResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, methodsToCall); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, methodsToCall); @@ -837,11 +835,11 @@ private void Conditions_RefreshMI_Click(object sender, EventArgs e) ///
/// The source of the event. /// The instance containing the event data. - private void Conditions_EnableMI_Click(object sender, EventArgs e) + private async void Conditions_EnableMI_ClickAsync(object sender, EventArgs e) { try { - EnableDisableCondition(true); + await EnableDisableConditionAsync(true); } catch (Exception exception) { @@ -854,11 +852,11 @@ private void Conditions_EnableMI_Click(object sender, EventArgs e) ///
/// The source of the event. /// The instance containing the event data. - private void Conditions_DisableMI_Click(object sender, EventArgs e) + private async void Conditions_DisableMI_ClickAsync(object sender, EventArgs e) { try { - EnableDisableCondition(false); + await EnableDisableConditionAsync(false); } catch (Exception exception) { @@ -919,11 +917,11 @@ private void ConditionsMI_DropDownOpening(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_AddCommentMI_Click(object sender, EventArgs e) + private async void Conditions_AddCommentMI_ClickAsync(object sender, EventArgs e) { try { - AddComment(); + await AddCommentAsync(); } catch (Exception exception) { @@ -936,11 +934,11 @@ private void Conditions_AddCommentMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_AcknowledgeMI_Click(object sender, EventArgs e) + private async void Conditions_AcknowledgeMI_ClickAsync(object sender, EventArgs e) { try { - Acknowledge(); + await AcknowledgeAsync(); } catch (Exception exception) { @@ -953,11 +951,11 @@ private void Conditions_AcknowledgeMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_ConfirmMI_Click(object sender, EventArgs e) + private async void Conditions_ConfirmMI_ClickAsync(object sender, EventArgs e) { try { - Confirm(); + await ConfirmAsync(); } catch (Exception exception) { @@ -970,11 +968,11 @@ private void Conditions_ConfirmMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_UnshelveMI_Click(object sender, EventArgs e) + private async void Conditions_UnshelveMI_ClickAsync(object sender, EventArgs e) { try { - Shelve(false, false, 0); + await ShelveAsync(false, false, 0); } catch (Exception exception) { @@ -987,11 +985,11 @@ private void Conditions_UnshelveMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_ManualShelveMI_Click(object sender, EventArgs e) + private async void Conditions_ManualShelveMI_ClickAsync(object sender, EventArgs e) { try { - Shelve(true, false, 0); + await ShelveAsync(true, false, 0); } catch (Exception exception) { @@ -1004,11 +1002,11 @@ private void Conditions_ManualShelveMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_OneShotShelveMI_Click(object sender, EventArgs e) + private async void Conditions_OneShotShelveMI_ClickAsync(object sender, EventArgs e) { try { - Shelve(true, true, 0); + await ShelveAsync(true, true, 0); } catch (Exception exception) { @@ -1021,11 +1019,11 @@ private void Conditions_OneShotShelveMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_TimedShelveMI_Click(object sender, EventArgs e) + private async void Conditions_TimedShelveMI_ClickAsync(object sender, EventArgs e) { try { - Shelve(true, false, 30000); + await ShelveAsync(true, false, 30000); } catch (Exception exception) { @@ -1061,7 +1059,7 @@ private void Conditions_MonitorMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_SeverityMI_Click(object sender, EventArgs e) + private async void Conditions_SeverityMI_ClickAsync(object sender, EventArgs e) { try { @@ -1072,7 +1070,7 @@ private void Conditions_SeverityMI_Click(object sender, EventArgs e) m_filter.Severity = (EventSeverity)((ToolStripMenuItem)sender).Tag; - UpdateFilter(); + await UpdateFilterAsync(); } catch (Exception exception) { @@ -1085,7 +1083,7 @@ private void Conditions_SeverityMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_TypeMI_Click(object sender, EventArgs e) + private async void Conditions_TypeMI_ClickAsync(object sender, EventArgs e) { try { @@ -1125,7 +1123,7 @@ private void Conditions_TypeMI_Click(object sender, EventArgs e) m_filter.EventTypes = selectedTypes; - UpdateFilter(); + await UpdateFilterAsync(); } catch (Exception exception) { @@ -1138,7 +1136,7 @@ private void Conditions_TypeMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_SetAreaFilterMI_Click(object sender, EventArgs e) + private async void Conditions_SetAreaFilterMI_ClickAsync(object sender, EventArgs e) { try { @@ -1151,7 +1149,7 @@ private void Conditions_SetAreaFilterMI_Click(object sender, EventArgs e) m_filter.AreaId = areaId; - UpdateFilter(); + await UpdateFilterAsync(); } catch (Exception exception) { @@ -1164,13 +1162,15 @@ private void Conditions_SetAreaFilterMI_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void View_AuditEventsMI_Click(object sender, EventArgs e) + private async void View_AuditEventsMI_ClickAsync(object sender, EventArgs e) { try { if (m_auditEventForm == null) { - m_auditEventForm = new AuditEventForm(m_session, m_subscription); + m_auditEventForm = new AuditEventForm(); + await m_auditEventForm.InitializeAsync(m_session, m_subscription); + m_auditEventForm.FormClosing += new FormClosingEventHandler(AuditEventForm_FormClosing); } @@ -1201,7 +1201,7 @@ void AuditEventForm_FormClosing(object sender, FormClosingEventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Conditions_RespondMI_Click(object sender, EventArgs e) + private async void Conditions_RespondMI_ClickAsync(object sender, EventArgs e) { try { @@ -1221,7 +1221,7 @@ private void Conditions_RespondMI_Click(object sender, EventArgs e) if (selectedResponse != -1) { - Respond(selectedResponse); + await RespondAsync(selectedResponse); } } catch (Exception exception) @@ -1239,7 +1239,7 @@ private void Help_ContentsMI_Click(object sender, EventArgs e) { try { - System.Diagnostics.Process.Start( Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\acclientoverview.htm"); + System.Diagnostics.Process.Start(Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\acclientoverview.htm"); } catch (Exception ex) { diff --git a/Workshop/AlarmCondition/Client/Program.cs b/Workshop/AlarmCondition/Client/Program.cs index cccdcde69..51d607db2 100644 --- a/Workshop/AlarmCondition/Client/Program.cs +++ b/Workshop/AlarmCondition/Client/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "AlarmConditionClient"; try @@ -63,10 +63,10 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/AlarmCondition/Client/SetAreaFilterDlg.Designer.cs b/Workshop/AlarmCondition/Client/SetAreaFilterDlg.Designer.cs index d44986c28..0dfb548eb 100644 --- a/Workshop/AlarmCondition/Client/SetAreaFilterDlg.Designer.cs +++ b/Workshop/AlarmCondition/Client/SetAreaFilterDlg.Designer.cs @@ -93,7 +93,7 @@ private void InitializeComponent() this.BrowseTV.Name = "BrowseTV"; this.BrowseTV.Size = new System.Drawing.Size(595, 575); this.BrowseTV.TabIndex = 6; - this.BrowseTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.BrowseTV_BeforeExpand); + this.BrowseTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.BrowseTV_BeforeExpandAsync); this.BrowseTV.DoubleClick += new System.EventHandler(this.BrowseTV_DoubleClick); this.BrowseTV.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.BrowseTV_AfterSelect); // diff --git a/Workshop/AlarmCondition/Client/SetAreaFilterDlg.cs b/Workshop/AlarmCondition/Client/SetAreaFilterDlg.cs index 694d535e3..7777992e9 100644 --- a/Workshop/AlarmCondition/Client/SetAreaFilterDlg.cs +++ b/Workshop/AlarmCondition/Client/SetAreaFilterDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -50,18 +50,18 @@ public SetAreaFilterDlg() InitializeComponent(); } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; #endregion - + #region Public Interface /// /// Displays the available areas in a tree view. /// /// The session. /// - public NodeId ShowDialog(Session session) + public NodeId ShowDialog(ISession session) { m_session = session; @@ -94,7 +94,7 @@ public NodeId ShowDialog(Session session) return (NodeId)reference.NodeId; } #endregion - + #region Private Methods #endregion @@ -160,7 +160,7 @@ private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void BrowseTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) + private async void BrowseTV_BeforeExpandAsync(object sender, TreeViewCancelEventArgs e) { try { @@ -181,10 +181,10 @@ private void BrowseTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) { nodeToBrowse.NodeId = (NodeId)reference.NodeId; } - + // add the childen to the control. - ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodeToBrowse, false); - + ReferenceDescriptionCollection references = await FormUtils.BrowseAsync(m_session, nodeToBrowse, false); + for (int ii = 0; ii < references.Count; ii++) { reference = references[ii]; diff --git a/Workshop/AlarmCondition/Client/ViewEventDetailsDlg.cs b/Workshop/AlarmCondition/Client/ViewEventDetailsDlg.cs index 38189cbf1..b7f3502ab 100644 --- a/Workshop/AlarmCondition/Client/ViewEventDetailsDlg.cs +++ b/Workshop/AlarmCondition/Client/ViewEventDetailsDlg.cs @@ -49,10 +49,10 @@ public ViewEventDetailsDlg() InitializeComponent(); } #endregion - + #region Private Fields #endregion - + #region Public Interface /// /// Shows all fields for the current condition. diff --git a/Workshop/AlarmCondition/Server/AlarmCondition Server.csproj b/Workshop/AlarmCondition/Server/AlarmCondition Server.csproj index 9667af321..25cda0133 100644 --- a/Workshop/AlarmCondition/Server/AlarmCondition Server.csproj +++ b/Workshop/AlarmCondition/Server/AlarmCondition Server.csproj @@ -48,6 +48,7 @@ false false + AllRules.ruleset pdbonly @@ -60,6 +61,7 @@ false false + AllRules.ruleset @@ -178,7 +180,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/AlarmCondition/Server/AlarmConditionNodeManager.cs b/Workshop/AlarmCondition/Server/AlarmConditionNodeManager.cs index 68e00d9dd..32623e1f8 100644 --- a/Workshop/AlarmCondition/Server/AlarmConditionNodeManager.cs +++ b/Workshop/AlarmCondition/Server/AlarmConditionNodeManager.cs @@ -74,13 +74,13 @@ public AlarmConditionServerNodeManager(IServerInternal server, ApplicationConfig m_sources = new Dictionary(); } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { if (m_system != null) @@ -200,18 +200,18 @@ private void OnRaiseSystemEvents(object state) private AreaState CreateAndIndexAreas(AreaState parent, AreaConfiguration configuration) { // create a unique path to the area. - string areaPath = Utils.Format("{0}/{1}", (parent != null)?parent.SymbolicName:String.Empty, configuration.Name); + string areaPath = Utils.Format("{0}/{1}", (parent != null) ? parent.SymbolicName : String.Empty, configuration.Name); NodeId areaId = ModelUtils.ConstructIdForArea(areaPath, NamespaceIndex); - + // create the object that will be used to access the area and any variables contained within it. AreaState area = new AreaState(SystemContext, parent, areaId, configuration); m_areas[areaPath] = area; - + if (parent != null) { parent.AddChild(area); } - + // create an index any sub-areas defined for the area. if (configuration.SubAreas != null) { @@ -266,7 +266,7 @@ public override void DeleteAddressSpace() /// /// Returns a unique handle for the node. /// - protected override NodeHandle GetManagerHandle(ServerSystemContext context, NodeId nodeId, IDictionary cache) + protected override NodeHandle GetManagerHandle(ServerSystemContext context, NodeId nodeId, IDictionary cache) { lock (Lock) { @@ -308,14 +308,14 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node return null; } } - + /// /// Verifies that the specified node exists. /// protected override NodeState ValidateNode( - ServerSystemContext context, + ServerSystemContext context, NodeHandle handle, - IDictionary cache) + IDictionary cache) { // not valid if no root. if (handle == null) @@ -428,8 +428,8 @@ protected override NodeState ValidateNode( #region Private Fields private UnderlyingSystem m_system; private AlarmConditionServerConfiguration m_configuration; - private Dictionary m_areas; - private Dictionary m_sources; + private Dictionary m_areas; + private Dictionary m_sources; private Timer m_simulationTimer; #endregion } diff --git a/Workshop/AlarmCondition/Server/AlarmConditionServer.cs b/Workshop/AlarmCondition/Server/AlarmConditionServer.cs index 5d9f73f04..cf50b2eea 100644 Binary files a/Workshop/AlarmCondition/Server/AlarmConditionServer.cs and b/Workshop/AlarmCondition/Server/AlarmConditionServer.cs differ diff --git a/Workshop/AlarmCondition/Server/AlarmConditionServerConfiguration.cs b/Workshop/AlarmCondition/Server/AlarmConditionServerConfiguration.cs index ee2a75355..a4f6d932e 100644 --- a/Workshop/AlarmCondition/Server/AlarmConditionServerConfiguration.cs +++ b/Workshop/AlarmCondition/Server/AlarmConditionServerConfiguration.cs @@ -118,7 +118,7 @@ private void Initialize() m_sourcePaths = null; } #endregion - + #region Public Properties /// /// The browse name for the instance. @@ -157,7 +157,7 @@ public StringCollection SourcePaths private StringCollection m_sourcePaths; #endregion } - + #region AreaConfigurationCollection Class /// /// A collection of AreaConfiguration objects. diff --git a/Workshop/AlarmCondition/Server/Model/AreaState.cs b/Workshop/AlarmCondition/Server/Model/AreaState.cs index 627943558..8f555f521 100644 --- a/Workshop/AlarmCondition/Server/Model/AreaState.cs +++ b/Workshop/AlarmCondition/Server/Model/AreaState.cs @@ -46,8 +46,8 @@ public AreaState( ISystemContext context, AreaState parent, NodeId nodeId, - AreaConfiguration configuration) - : + AreaConfiguration configuration) + : base(parent) { Initialize(context); diff --git a/Workshop/AlarmCondition/Server/Model/ModelUtils.cs b/Workshop/AlarmCondition/Server/Model/ModelUtils.cs index 6a9ba01f2..2e10c487e 100644 --- a/Workshop/AlarmCondition/Server/Model/ModelUtils.cs +++ b/Workshop/AlarmCondition/Server/Model/ModelUtils.cs @@ -107,7 +107,7 @@ public static NodeId ConstructIdForComponent(NodeState component, ushort namespa // parent must have a string identifier. string parentId = instance.Parent.NodeId.Identifier as string; - + if (parentId == null) { return null; @@ -115,7 +115,7 @@ public static NodeId ConstructIdForComponent(NodeState component, ushort namespa StringBuilder buffer = new StringBuilder(); buffer.Append(parentId); - + // check if the parent is another component. int index = parentId.IndexOf('?'); diff --git a/Workshop/AlarmCondition/Server/Model/SourceState.cs b/Workshop/AlarmCondition/Server/Model/SourceState.cs index e0948dd44..484950a8e 100644 --- a/Workshop/AlarmCondition/Server/Model/SourceState.cs +++ b/Workshop/AlarmCondition/Server/Model/SourceState.cs @@ -32,7 +32,7 @@ using Opc.Ua; namespace Quickstarts.AlarmConditionServer -{ +{ /// /// Maps an alarm source to a UA object node. /// @@ -45,8 +45,8 @@ public partial class SourceState : BaseObjectState public SourceState( QuickstartNodeManager nodeManager, NodeId nodeId, - string sourcePath) - : + string sourcePath) + : base(null) { Initialize(nodeManager.SystemContext); @@ -56,7 +56,7 @@ public SourceState( // create the source with the underlying system. m_source = ((UnderlyingSystem)nodeManager.SystemContext.SystemHandle).CreateSource(sourcePath, OnAlarmChanged); - + // initialize the area with the fixed metadata. this.SymbolicName = m_source.Name; this.NodeId = nodeId; @@ -74,7 +74,7 @@ public SourceState( m_alarms = new Dictionary(); m_events = new Dictionary(); m_branches = new Dictionary(); - + // request an updated for all alarms. m_source.Refresh(); } @@ -163,7 +163,7 @@ private void OnAlarmChanged(UnderlyingSystemAlarm alarm) if (alarm.RecordNumber != 0) { NodeId branchId = new NodeId(alarm.RecordNumber, this.NodeId.NamespaceIndex); - + // find the alarm branch. AlarmConditionState branch = null; @@ -198,7 +198,7 @@ private void OnAlarmChanged(UnderlyingSystemAlarm alarm) ReportChanges(node); } } - + /// /// Creates a new dialog condition /// @@ -315,7 +315,7 @@ private AlarmConditionState CreateAlarm(UnderlyingSystemAlarm alarm, NodeId bran break; } - + case "TripAlarm": { node = new TripAlarmState(this); @@ -391,7 +391,7 @@ private AlarmConditionState CreateAlarm(UnderlyingSystemAlarm alarm, NodeId bran node.Time.Value = DateTime.UtcNow; node.ReceiveTime.Value = node.Time.Value; node.BranchId.Value = branchId; - + // set up method handlers. node.OnEnableDisable = OnEnableDisableAlarm; node.OnAcknowledge = OnAcknowledge; @@ -426,7 +426,7 @@ private void UpdateAlarm(AlarmConditionState node, UnderlyingSystemAlarm alarm) // save the event for later lookup. m_events[Utils.ToHexString(node.EventId.Value)] = node; - + // determine the retain state. node.Retain.Value = true; @@ -510,7 +510,7 @@ private void UpdateAlarm(AlarmConditionState node, UnderlyingSystemAlarm alarm) node.Retain.Value = false; } } - + /// /// Called when the alarm is enabled or disabled. /// @@ -738,9 +738,9 @@ private string GetUserName(ISystemContext context) #region Private Fields private QuickstartNodeManager m_nodeManager; private UnderlyingSystemSource m_source; - private Dictionary m_alarms; - private Dictionary m_events; - private Dictionary m_branches; + private Dictionary m_alarms; + private Dictionary m_events; + private Dictionary m_branches; private DialogConditionState m_dialog; #endregion } diff --git a/Workshop/AlarmCondition/Server/Program.cs b/Workshop/AlarmCondition/Server/Program.cs index eceff0558..6bd59a7e6 100644 --- a/Workshop/AlarmCondition/Server/Program.cs +++ b/Workshop/AlarmCondition/Server/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "AlarmConditionServer"; try @@ -70,13 +70,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // start the server. - application.Start(new AlarmConditionServer()).Wait(); + application.StartAsync(new AlarmConditionServer()).Wait(); // run the application interactively. Application.Run(new ServerForm(application)); diff --git a/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystem.cs b/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystem.cs index de24f2ca4..c2b5e1f94 100644 --- a/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystem.cs +++ b/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystem.cs @@ -48,21 +48,21 @@ public UnderlyingSystem() m_sources = new Dictionary(); } #endregion - + #region IDisposable Members /// /// The finializer implementation. /// - ~UnderlyingSystem() + ~UnderlyingSystem() { Dispose(false); } - + /// /// Frees any unmanaged resources. /// public void Dispose() - { + { Dispose(true); GC.SuppressFinalize(this); } @@ -71,7 +71,7 @@ public void Dispose() /// An overrideable version of the Dispose. /// protected virtual void Dispose(bool disposing) - { + { if (disposing) { if (m_simulationTimer != null) @@ -106,7 +106,7 @@ public UnderlyingSystemSource CreateSource(string sourcePath, AlarmChangedEventH if (index != -1) { - name = name.Substring(index+1); + name = name.Substring(index + 1); } // extract the type from the path. @@ -226,7 +226,7 @@ private void DoSimulation(object state) #region Private Fields private object m_lock = new object(); - private Dictionary m_sources; + private Dictionary m_sources; private Timer m_simulationTimer; private long m_simulationCounter; #endregion diff --git a/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystemSource.cs b/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystemSource.cs index ee1fbf7e5..4da2a08a2 100644 --- a/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystemSource.cs +++ b/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystemSource.cs @@ -54,7 +54,7 @@ public UnderlyingSystemSource() /// Used to receive events when the state of an alarm changed. /// public AlarmChangedEventHandler OnAlarmChanged; - + /// /// Gets or sets the name of the source. /// @@ -149,7 +149,7 @@ public void EnableAlarm(string alarmName, bool enabling) if (alarm.SetStateBits(UnderlyingSystemAlarmStates.Enabled, enabling)) { alarm.Time = alarm.EnableTime = DateTime.UtcNow; - alarm.Reason = "The alarm was " + ((enabling)?"enabled.":"disabled."); + alarm.Reason = "The alarm was " + ((enabling) ? "enabled." : "disabled."); snapshots.Add(alarm.CreateSnapshot()); } @@ -164,7 +164,7 @@ public void EnableAlarm(string alarmName, bool enabling) if (record.SetStateBits(UnderlyingSystemAlarmStates.Enabled, enabling)) { record.Time = alarm.EnableTime = DateTime.UtcNow; - record.Reason = "The alarm was " + ((enabling)?"enabled.":"disabled."); + record.Reason = "The alarm was " + ((enabling) ? "enabled." : "disabled."); snapshots.Add(alarm.CreateSnapshot()); } } @@ -239,7 +239,7 @@ public void AcknowledgeAlarm(string alarmName, uint recordNumber, LocalizedText alarm.Reason = "The alarm was acknoweledged."; alarm.Comment = Utils.Format("{0}", comment); alarm.UserName = userName; - + alarm.SetStateBits(UnderlyingSystemAlarmStates.Confirmed, false); } @@ -338,21 +338,21 @@ public void SetOfflineState(bool offline) for (int ii = 0; ii < m_alarms.Count; ii++) { UnderlyingSystemAlarm alarm = m_alarms[ii]; - + if (alarm.SetStateBits(UnderlyingSystemAlarmStates.Suppressed, offline)) { alarm.Time = alarm.EnableTime = DateTime.UtcNow; - alarm.Reason = "The alarm was " + ((offline)?"suppressed.":"unsuppressed."); - + alarm.Reason = "The alarm was " + ((offline) ? "suppressed." : "unsuppressed."); + // check if the alarm change should be reported. if ((alarm.State & UnderlyingSystemAlarmStates.Enabled) != 0) { snapshots.Add(alarm.CreateSnapshot()); } - } + } } } - + // report any alarm changes after releasing the lock. for (int ii = 0; ii < snapshots.Count; ii++) { @@ -390,7 +390,7 @@ public void DoSimulation(long counter, int index) { for (int ii = 0; ii < m_alarms.Count; ii++) { - UpdateAlarm(m_alarms[ii], counter, ii+index, snapshots); + UpdateAlarm(m_alarms[ii], counter, ii + index, snapshots); } } @@ -471,7 +471,7 @@ private void ReportAlarmChange(UnderlyingSystemAlarm alarm) private void UpdateAlarm(UnderlyingSystemAlarm alarm, long counter, int index, List snapshots) { string reason = null; - + // ignore disabled alarms. if ((alarm.State & UnderlyingSystemAlarmStates.Enabled) == 0) { @@ -479,7 +479,7 @@ private void UpdateAlarm(UnderlyingSystemAlarm alarm, long counter, int index, L } // check if the alarm needs to be updated this cycle. - if (counter % (8 + (index%4)) == 0) + if (counter % (8 + (index % 4)) == 0) { // check if it is time to activate. if ((alarm.State & UnderlyingSystemAlarmStates.Active) == 0) @@ -599,7 +599,7 @@ private void UpdateAlarm(UnderlyingSystemAlarm alarm, long counter, int index, L private string m_sourcePath; private string m_sourceType; private List m_alarms; - private Dictionary m_archive; + private Dictionary m_archive; private bool m_isOffline; private uint m_nextRecordNumber; #endregion diff --git a/Workshop/Boiler/Client/Boiler Client.csproj b/Workshop/Boiler/Client/Boiler Client.csproj index f084f5af6..b681daadd 100644 --- a/Workshop/Boiler/Client/Boiler Client.csproj +++ b/Workshop/Boiler/Client/Boiler Client.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -141,7 +143,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Boiler/Client/MainForm.Designer.cs b/Workshop/Boiler/Client/MainForm.Designer.cs index d2ba406f3..9517f98a4 100644 --- a/Workshop/Boiler/Client/MainForm.Designer.cs +++ b/Workshop/Boiler/Client/MainForm.Designer.cs @@ -234,7 +234,7 @@ private void InitializeComponent() this.BoilerCB.Name = "BoilerCB"; this.BoilerCB.Size = new System.Drawing.Size(164, 21); this.BoilerCB.TabIndex = 2; - this.BoilerCB.SelectedIndexChanged += new System.EventHandler(this.BoilerCB_SelectedIndexChanged); + this.BoilerCB.SelectedIndexChanged += new System.EventHandler(this.BoilerCB_SelectedIndexChangedAsync); // // BoilerLB // @@ -257,7 +257,7 @@ private void InitializeComponent() this.ConnectServerCTRL.StatusStrip = this.StatusBar; this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); // diff --git a/Workshop/Boiler/Client/MainForm.cs b/Workshop/Boiler/Client/MainForm.cs index d72c77939..5c41668a2 100644 --- a/Workshop/Boiler/Client/MainForm.cs +++ b/Workshop/Boiler/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Quickstarts.Boiler.Client { @@ -71,7 +73,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private Subscription m_subscription; private bool m_connectedOnce; #endregion @@ -87,7 +89,7 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -130,7 +132,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -152,7 +154,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) BoilerCB.Enabled = true; // update list of boilers - GetBoilers(); + await GetBoilersAsync(); } catch (Exception exception) { @@ -206,12 +208,12 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) ConnectServerCTRL.Disconnect(); } #endregion - + #region Private Methods /// /// Gets the boilers. /// - private void GetBoilers() + private async Task GetBoilersAsync(CancellationToken ct = default) { BoilerCB.Items.Clear(); @@ -224,10 +226,11 @@ private void GetBoilers() nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object); nodeToBrowse.ResultMask = (uint)(BrowseResultMask.All); - ReferenceDescriptionCollection references = ClientUtils.Browse( + ReferenceDescriptionCollection references = await ClientUtils.BrowseAsync( m_session, nodeToBrowse, - false); + false, + ct); if (references != null) { @@ -250,7 +253,7 @@ private void GetBoilers() #endregion #region Event Handlers - private void BoilerCB_SelectedIndexChanged(object sender, EventArgs e) + private async void BoilerCB_SelectedIndexChangedAsync(object sender, EventArgs e) { try { @@ -261,17 +264,17 @@ private void BoilerCB_SelectedIndexChanged(object sender, EventArgs e) if (m_subscription != null) { - m_session.RemoveSubscription(m_subscription); + await m_session.RemoveSubscriptionAsync(m_subscription); m_subscription = null; } - + ReferenceDescription boiler = (ReferenceDescription)BoilerCB.SelectedItem; if (boiler == null) { return; } - + m_subscription = new Subscription(); m_subscription.PublishingEnabled = true; @@ -282,12 +285,12 @@ private void BoilerCB_SelectedIndexChanged(object sender, EventArgs e) m_subscription.MaxNotificationsPerPublish = 1000; m_session.AddSubscription(m_subscription); - m_subscription.Create(); + await m_subscription.CreateAsync(); NamespaceTable wellKnownNamespaceUris = new NamespaceTable(); wellKnownNamespaceUris.Append(Namespaces.Boiler); - string[] browsePaths = new string[] + string[] browsePaths = new string[] { "1:PipeX001/1:FTX001/1:Output", "1:DrumX001/1:LIX001/1:Output", @@ -295,13 +298,14 @@ private void BoilerCB_SelectedIndexChanged(object sender, EventArgs e) "1:LCX001/1:SetPoint", }; - List nodes = ClientUtils.TranslateBrowsePaths( + List nodes = await ClientUtils.TranslateBrowsePathsAsync( m_session, (NodeId)boiler.NodeId, wellKnownNamespaceUris, + default, browsePaths); - Control[] controls = new Control[] + Control[] controls = new Control[] { InputPipeFlowTB, DrumLevelTB, @@ -324,7 +328,7 @@ private void BoilerCB_SelectedIndexChanged(object sender, EventArgs e) } } - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(); } catch (Exception exception) { diff --git a/Workshop/Boiler/Client/Program.cs b/Workshop/Boiler/Client/Program.cs index 051f43820..86e41f196 100644 --- a/Workshop/Boiler/Client/Program.cs +++ b/Workshop/Boiler/Client/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "BoilerClient"; try @@ -63,10 +63,10 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/Boiler/Client/Quickstarts.Boiler.DataTypes.cs b/Workshop/Boiler/Client/Quickstarts.Boiler.DataTypes.cs index 0c4da47e6..2cc11aa2d 100644 --- a/Workshop/Boiler/Client/Quickstarts.Boiler.DataTypes.cs +++ b/Workshop/Boiler/Client/Quickstarts.Boiler.DataTypes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.Boiler { #region ControllerDataType Class - #if (!OPCUA_EXCLUDE_ControllerDataType) +#if (!OPCUA_EXCLUDE_ControllerDataType) /// /// /// @@ -80,7 +80,7 @@ private void Initialize() [DataMember(Name = "Setpoint", IsRequired = false, Order = 1)] public double Setpoint { - get { return m_setpoint; } + get { return m_setpoint; } set { m_setpoint = value; } } @@ -88,7 +88,7 @@ public double Setpoint [DataMember(Name = "ControllerOut", IsRequired = false, Order = 2)] public double ControllerOut { - get { return m_controllerOut; } + get { return m_controllerOut; } set { m_controllerOut = value; } } @@ -96,7 +96,7 @@ public double ControllerOut [DataMember(Name = "ProcessVariable", IsRequired = false, Order = 3)] public double ProcessVariable { - get { return m_processVariable; } + get { return m_processVariable; } set { m_processVariable = value; } } #endregion @@ -166,13 +166,13 @@ public virtual bool IsEqual(IEncodeable encodeable) return true; } - #if !NET_STANDARD +#if !NET_STANDARD /// public virtual object Clone() { return (ControllerDataType)this.MemberwiseClone(); } - #endif +#endif /// public new object MemberwiseClone() @@ -201,27 +201,27 @@ public virtual object Clone() /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfControllerDataType", Namespace = Quickstarts.Boiler.Namespaces.Boiler, ItemName = "ControllerDataType")] - #if !NET_STANDARD +#if !NET_STANDARD public partial class ControllerDataTypeCollection : List, ICloneable - #else +#else public partial class ControllerDataTypeCollection : List - #endif +#endif { #region Constructors /// /// Initializes the collection with default values. /// - public ControllerDataTypeCollection() {} + public ControllerDataTypeCollection() { } /// /// Initializes the collection with an initial capacity. /// - public ControllerDataTypeCollection(int capacity) : base(capacity) {} + public ControllerDataTypeCollection(int capacity) : base(capacity) { } /// /// Initializes the collection with another collection. /// - public ControllerDataTypeCollection(IEnumerable collection) : base(collection) {} + public ControllerDataTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -252,7 +252,7 @@ public static explicit operator ControllerDataType[](ControllerDataTypeCollectio } #endregion - #if !NET_STANDARD +#if !NET_STANDARD #region ICloneable Methods /// /// Creates a deep copy of the collection. @@ -262,7 +262,7 @@ public object Clone() return (ControllerDataTypeCollection)this.MemberwiseClone(); } #endregion - #endif +#endif /// public new object MemberwiseClone() @@ -278,6 +278,6 @@ public object Clone() } } #endregion - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/Boiler/Server/Boiler Server.csproj b/Workshop/Boiler/Server/Boiler Server.csproj index 862cc741b..4b7282358 100644 --- a/Workshop/Boiler/Server/Boiler Server.csproj +++ b/Workshop/Boiler/Server/Boiler Server.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -139,7 +141,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Boiler/Server/BoilerNodeManager.cs b/Workshop/Boiler/Server/BoilerNodeManager.cs index 652c98f63..d209dc92e 100644 --- a/Workshop/Boiler/Server/BoilerNodeManager.cs +++ b/Workshop/Boiler/Server/BoilerNodeManager.cs @@ -71,13 +71,13 @@ public BoilerNodeManager(IServerInternal server, ApplicationConfiguration config } } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { if (m_simulationTimer != null) @@ -107,9 +107,9 @@ public override NodeId New(ISystemContext context, NodeState node) protected override NodeStateCollection LoadPredefinedNodes(ISystemContext context) { NodeStateCollection predefinedNodes = new NodeStateCollection(); - predefinedNodes.LoadFromBinaryResource(context, + predefinedNodes.LoadFromBinaryResource(context, "Quickstarts.Boiler.Server.Quickstarts.Boiler.PredefinedNodes.uanodes", - typeof(BoilerNodeManager).GetTypeInfo().Assembly, + typeof(BoilerNodeManager).GetTypeInfo().Assembly, true); return predefinedNodes; } @@ -129,7 +129,7 @@ public override void CreateAddressSpace(IDictionary> e lock (Lock) { LoadPredefinedNodes(SystemContext, externalReferences); - + // find the untyped Boiler1 node that was created when the model was loaded. BaseObjectState passiveNode = (BaseObjectState)FindPredefinedNode(new NodeId(Objects.Boiler1, NamespaceIndexes[0]), typeof(BaseObjectState)); @@ -209,7 +209,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node return handle; } } - + return null; } } @@ -233,7 +233,7 @@ protected override NodeState ValidateNode( { return handle.Node; } - + // TBD return null; @@ -250,12 +250,12 @@ private void DoSimulation(object state) try { double value1 = m_boiler1.Drum.LevelIndicator.Output.Value; - value1 = ((int)(++value1))%100; + value1 = ((int)(++value1)) % 100; m_boiler1.Drum.LevelIndicator.Output.Value = value1; m_boiler1.ClearChangeMasks(SystemContext, true); - + double value2 = m_boiler2.Drum.LevelIndicator.Output.Value; - value2 = ((int)(++value2))%20; + value2 = ((int)(++value2)) % 20; m_boiler2.Drum.LevelIndicator.Output.Value = value2; m_boiler2.ClearChangeMasks(SystemContext, true); } diff --git a/Workshop/Boiler/Server/BoilerServer.cs b/Workshop/Boiler/Server/BoilerServer.cs index e2102efad..fb70c8c14 100644 Binary files a/Workshop/Boiler/Server/BoilerServer.cs and b/Workshop/Boiler/Server/BoilerServer.cs differ diff --git a/Workshop/Boiler/Server/BoilerServerConfiguration.cs b/Workshop/Boiler/Server/BoilerServerConfiguration.cs index cbcf045a9..f4b8d5c27 100644 --- a/Workshop/Boiler/Server/BoilerServerConfiguration.cs +++ b/Workshop/Boiler/Server/BoilerServerConfiguration.cs @@ -38,7 +38,7 @@ namespace Quickstarts.Boiler.Server /// /// Stores the configuration the data access node manager. /// - [DataContract(Namespace=Namespaces.Boiler)] + [DataContract(Namespace = Namespaces.Boiler)] public class BoilerServerConfiguration { #region Constructors diff --git a/Workshop/Boiler/Server/Program.cs b/Workshop/Boiler/Server/Program.cs index 9fca05b21..b89335df4 100644 --- a/Workshop/Boiler/Server/Program.cs +++ b/Workshop/Boiler/Server/Program.cs @@ -52,7 +52,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "BoilerServer"; try @@ -71,13 +71,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // start the server. - application.Start(new BoilerServer()).Wait(); + application.StartAsync(new BoilerServer()).Wait(); // run the application interactively. Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); diff --git a/Workshop/Boiler/Server/Quickstarts.Boiler.Classes.cs b/Workshop/Boiler/Server/Quickstarts.Boiler.Classes.cs index 2a24b1d98..922553a64 100644 --- a/Workshop/Boiler/Server/Quickstarts.Boiler.Classes.cs +++ b/Workshop/Boiler/Server/Quickstarts.Boiler.Classes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.Boiler { #region GenericControllerState Class - #if (!OPCUA_EXCLUDE_GenericControllerState) +#if (!OPCUA_EXCLUDE_GenericControllerState) /// /// Stores an instance of the GenericControllerType ObjectType. /// @@ -61,7 +61,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.GenericControllerType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -97,7 +97,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AAgAAABTZXRQb2ludAEBBQAALgBEBQAAAAAL/////wMD/////wAAAAAVYIkKAgAAAAEACgAAAENvbnRy" + "b2xPdXQBAQYAAC4ARAYAAAAAC/////8BAf////8AAAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -284,11 +284,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_controlOut; #endregion } - #endif +#endif #endregion #region GenericSensorState Class - #if (!OPCUA_EXCLUDE_GenericSensorState) +#if (!OPCUA_EXCLUDE_GenericSensorState) /// /// Stores an instance of the GenericSensorType ObjectType. /// @@ -312,7 +312,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.GenericSensorType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -347,7 +347,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AAABAAYAAABPdXRwdXQBAQgAAC8BAEAJCAAAAAAL/////wEB/////wEAAAAVYIkKAgAAAAAABwAAAEVV" + "UmFuZ2UBAQsAAC4ARAsAAAABAHQD/////wEB/////wAAAAA="; #endregion - #endif +#endif #endregion #region Public Properties @@ -442,11 +442,11 @@ protected override BaseInstanceState FindChild( private AnalogItemState m_output; #endregion } - #endif +#endif #endregion #region GenericActuatorState Class - #if (!OPCUA_EXCLUDE_GenericActuatorState) +#if (!OPCUA_EXCLUDE_GenericActuatorState) /// /// Stores an instance of the GenericActuatorType ObjectType. /// @@ -470,7 +470,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.GenericActuatorType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -505,7 +505,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AgAAAAEABQAAAElucHV0AQEPAAAvAQBACQ8AAAAAC/////8CAv////8BAAAAFWCJCgIAAAAAAAcAAABF" + "VVJhbmdlAQESAAAuAEQSAAAAAQB0A/////8BAf////8AAAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -600,11 +600,11 @@ protected override BaseInstanceState FindChild( private AnalogItemState m_input; #endregion } - #endif +#endif #endregion #region CustomControllerState Class - #if (!OPCUA_EXCLUDE_CustomControllerState) +#if (!OPCUA_EXCLUDE_CustomControllerState) /// /// Stores an instance of the CustomControllerType ObjectType. /// @@ -628,7 +628,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.CustomControllerType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -665,7 +665,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "RBgAAAAAC/////8CAv////8AAAAAFWCJCgIAAAABAAoAAABDb250cm9sT3V0AQEZAAAuAEQZAAAAAAv/" + "////AQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -898,11 +898,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_controlOut; #endregion } - #endif +#endif #endregion #region ValveState Class - #if (!OPCUA_EXCLUDE_ValveState) +#if (!OPCUA_EXCLUDE_ValveState) /// /// Stores an instance of the ValveType ObjectType. /// @@ -926,7 +926,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.ValveType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -961,7 +961,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "SW5wdXQBARsAAC8BAEAJGwAAAAAL/////wIC/////wEAAAAVYIkKAgAAAAAABwAAAEVVUmFuZ2UBAR4A" + "AC4ARB4AAAABAHQD/////wEB/////wAAAAA="; #endregion - #endif +#endif #endregion #region Public Properties @@ -973,11 +973,11 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion #region LevelControllerState Class - #if (!OPCUA_EXCLUDE_LevelControllerState) +#if (!OPCUA_EXCLUDE_LevelControllerState) /// /// Stores an instance of the LevelControllerType ObjectType. /// @@ -1001,7 +1001,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.LevelControllerType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -1037,7 +1037,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AAAAU2V0UG9pbnQBASMAAC4ARCMAAAAAC/////8DA/////8AAAAAFWCJCgIAAAABAAoAAABDb250cm9s" + "T3V0AQEkAAAuAEQkAAAAAAv/////AQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -1049,11 +1049,11 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion #region FlowControllerState Class - #if (!OPCUA_EXCLUDE_FlowControllerState) +#if (!OPCUA_EXCLUDE_FlowControllerState) /// /// Stores an instance of the FlowControllerType ObjectType. /// @@ -1077,7 +1077,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.FlowControllerType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -1113,7 +1113,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AABTZXRQb2ludAEBJwAALgBEJwAAAAAL/////wMD/////wAAAAAVYIkKAgAAAAEACgAAAENvbnRyb2xP" + "dXQBASgAAC4ARCgAAAAAC/////8BAf////8AAAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -1125,11 +1125,11 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion #region LevelIndicatorState Class - #if (!OPCUA_EXCLUDE_LevelIndicatorState) +#if (!OPCUA_EXCLUDE_LevelIndicatorState) /// /// Stores an instance of the LevelIndicatorType ObjectType. /// @@ -1153,7 +1153,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.LevelIndicatorType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -1188,7 +1188,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AAAAAQAGAAAAT3V0cHV0AQEqAAAvAQBACSoAAAAAC/////8BAf////8BAAAAFWCJCgIAAAAAAAcAAABF" + "VVJhbmdlAQEtAAAuAEQtAAAAAQB0A/////8BAf////8AAAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -1200,11 +1200,11 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion #region FlowTransmitterState Class - #if (!OPCUA_EXCLUDE_FlowTransmitterState) +#if (!OPCUA_EXCLUDE_FlowTransmitterState) /// /// Stores an instance of the FlowTransmitterType ObjectType. /// @@ -1228,7 +1228,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.FlowTransmitterType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -1263,7 +1263,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AgAAAAEABgAAAE91dHB1dAEBMQAALwEAQAkxAAAAAAv/////AQH/////AQAAABVgiQoCAAAAAAAHAAAA" + "RVVSYW5nZQEBNAAALgBENAAAAAEAdAP/////AQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -1275,11 +1275,11 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion #region BoilerInputPipeState Class - #if (!OPCUA_EXCLUDE_BoilerInputPipeState) +#if (!OPCUA_EXCLUDE_BoilerInputPipeState) /// /// Stores an instance of the BoilerInputPipeType ObjectType. /// @@ -1303,7 +1303,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.BoilerInputPipeType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -1342,7 +1342,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AAAASW5wdXQBAVIAAC8BAEAJUgAAAAAL/////wIC/////wEAAAAVYIkKAgAAAAAABwAAAEVVUmFuZ2UB" + "AVUAAC4ARFUAAAABAHQD/////wEB/////wAAAAA="; #endregion - #endif +#endif #endregion #region Public Properties @@ -1483,11 +1483,11 @@ protected override BaseInstanceState FindChild( private ValveState m_valve; #endregion } - #endif +#endif #endregion #region BoilerDrumState Class - #if (!OPCUA_EXCLUDE_BoilerDrumState) +#if (!OPCUA_EXCLUDE_BoilerDrumState) /// /// Stores an instance of the BoilerDrumType ObjectType. /// @@ -1511,7 +1511,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.BoilerDrumType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -1547,7 +1547,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "WAABAAAAFWCJCgIAAAABAAYAAABPdXRwdXQBAVoAAC8BAEAJWgAAAAAL/////wEB/////wEAAAAVYIkK" + "AgAAAAAABwAAAEVVUmFuZ2UBAV0AAC4ARF0AAAABAHQD/////wEB/////wAAAAA="; #endregion - #endif +#endif #endregion #region Public Properties @@ -1642,11 +1642,11 @@ protected override BaseInstanceState FindChild( private LevelIndicatorState m_levelIndicator; #endregion } - #endif +#endif #endregion #region BoilerOutputPipeState Class - #if (!OPCUA_EXCLUDE_BoilerOutputPipeState) +#if (!OPCUA_EXCLUDE_BoilerOutputPipeState) /// /// Stores an instance of the BoilerOutputPipeType ObjectType. /// @@ -1670,7 +1670,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.BoilerOutputPipeType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -1706,7 +1706,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AAAAADABAQFgAAEAAAAVYIkKAgAAAAEABgAAAE91dHB1dAEBYgAALwEAQAliAAAAAAv/////AQH/////" + "AQAAABVgiQoCAAAAAAAHAAAARVVSYW5nZQEBZQAALgBEZQAAAAEAdAP/////AQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -1801,11 +1801,11 @@ protected override BaseInstanceState FindChild( private FlowTransmitterState m_flowTransmitter2; #endregion } - #endif +#endif #endregion #region BoilerState Class - #if (!OPCUA_EXCLUDE_BoilerState) +#if (!OPCUA_EXCLUDE_BoilerState) /// /// Stores an instance of the BoilerType ObjectType. /// @@ -1829,7 +1829,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Boiler.ObjectTypes.BoilerType, Quickstarts.Boiler.Namespaces.Boiler, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -1891,7 +1891,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "FWCJCgIAAAABAAYAAABJbnB1dDMBAYgAAC4ARIgAAAAAC/////8CAgEAAAABAQIAAQEBdwAAAAAAFWCJ" + "CgIAAAABAAoAAABDb250cm9sT3V0AQGJAAAuAESJAAAAAAv/////AQEBAAAAAQECAAABAX8AAAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -2216,6 +2216,6 @@ protected override BaseInstanceState FindChild( private CustomControllerState m_customController; #endregion } - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/Boiler/Server/Quickstarts.Boiler.DataTypes.cs b/Workshop/Boiler/Server/Quickstarts.Boiler.DataTypes.cs index 0c4da47e6..2cc11aa2d 100644 --- a/Workshop/Boiler/Server/Quickstarts.Boiler.DataTypes.cs +++ b/Workshop/Boiler/Server/Quickstarts.Boiler.DataTypes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.Boiler { #region ControllerDataType Class - #if (!OPCUA_EXCLUDE_ControllerDataType) +#if (!OPCUA_EXCLUDE_ControllerDataType) /// /// /// @@ -80,7 +80,7 @@ private void Initialize() [DataMember(Name = "Setpoint", IsRequired = false, Order = 1)] public double Setpoint { - get { return m_setpoint; } + get { return m_setpoint; } set { m_setpoint = value; } } @@ -88,7 +88,7 @@ public double Setpoint [DataMember(Name = "ControllerOut", IsRequired = false, Order = 2)] public double ControllerOut { - get { return m_controllerOut; } + get { return m_controllerOut; } set { m_controllerOut = value; } } @@ -96,7 +96,7 @@ public double ControllerOut [DataMember(Name = "ProcessVariable", IsRequired = false, Order = 3)] public double ProcessVariable { - get { return m_processVariable; } + get { return m_processVariable; } set { m_processVariable = value; } } #endregion @@ -166,13 +166,13 @@ public virtual bool IsEqual(IEncodeable encodeable) return true; } - #if !NET_STANDARD +#if !NET_STANDARD /// public virtual object Clone() { return (ControllerDataType)this.MemberwiseClone(); } - #endif +#endif /// public new object MemberwiseClone() @@ -201,27 +201,27 @@ public virtual object Clone() /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfControllerDataType", Namespace = Quickstarts.Boiler.Namespaces.Boiler, ItemName = "ControllerDataType")] - #if !NET_STANDARD +#if !NET_STANDARD public partial class ControllerDataTypeCollection : List, ICloneable - #else +#else public partial class ControllerDataTypeCollection : List - #endif +#endif { #region Constructors /// /// Initializes the collection with default values. /// - public ControllerDataTypeCollection() {} + public ControllerDataTypeCollection() { } /// /// Initializes the collection with an initial capacity. /// - public ControllerDataTypeCollection(int capacity) : base(capacity) {} + public ControllerDataTypeCollection(int capacity) : base(capacity) { } /// /// Initializes the collection with another collection. /// - public ControllerDataTypeCollection(IEnumerable collection) : base(collection) {} + public ControllerDataTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -252,7 +252,7 @@ public static explicit operator ControllerDataType[](ControllerDataTypeCollectio } #endregion - #if !NET_STANDARD +#if !NET_STANDARD #region ICloneable Methods /// /// Creates a deep copy of the collection. @@ -262,7 +262,7 @@ public object Clone() return (ControllerDataTypeCollection)this.MemberwiseClone(); } #endregion - #endif +#endif /// public new object MemberwiseClone() @@ -278,6 +278,6 @@ public object Clone() } } #endregion - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/Common/BackwardCompatibility.cs b/Workshop/Common/BackwardCompatibility.cs index c72ff2f2b..6301d7162 100644 --- a/Workshop/Common/BackwardCompatibility.cs +++ b/Workshop/Common/BackwardCompatibility.cs @@ -71,7 +71,7 @@ public partial class SelectNodeDlg : Opc.Ua.Client.Controls.SelectNodeDlg public partial class BrowseNodeCtrl : Opc.Ua.Client.Controls.BrowseNodeCtrl { } - + public partial class ServerForm : Opc.Ua.Server.Controls.ServerForm { /// diff --git a/Workshop/Common/FilterDefinition.cs b/Workshop/Common/FilterDefinition.cs index f1f63d1ce..5ed4c1a77 100644 --- a/Workshop/Common/FilterDefinition.cs +++ b/Workshop/Common/FilterDefinition.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,6 +29,8 @@ using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; using Opc.Ua; using Opc.Ua.Client; @@ -49,17 +51,17 @@ public class FilterDefinition /// The minimum severity for the events of interest. /// public EventSeverity Severity; - + /// /// The types for the events of interest. /// public IList EventTypes; - + /// /// The select clauses to use with the filter. /// public SimpleAttributeOperandCollection SelectClauses; - + /// /// Creates the monitored item based on the current definition. /// @@ -99,18 +101,19 @@ public MonitoredItem CreateMonitoredItem(Session session) /// Constructs the select clauses for a set of event types. /// /// The session. + /// A token to cancel the operation with /// The event type ids. /// The select clauses for all fields discovered. /// /// Each event type is an ObjectType in the address space. The fields supported by the /// server are defined as children of the ObjectType. Many of the fields are manadatory - /// and are defined by the UA information model, however, indiviudual servers many not + /// and are defined by the UA information model, however, indiviudual servers many not /// support all of the optional fields. - /// - /// This method browses the type model and + /// This method browses the type model and /// - public SimpleAttributeOperandCollection ConstructSelectClauses( + public async Task ConstructSelectClausesAsync( Session session, + CancellationToken ct, params NodeId[] eventTypeIds) { // browse the type model in the server address space to find the fields available for the event type. @@ -131,14 +134,14 @@ public SimpleAttributeOperandCollection ConstructSelectClauses( { for (int ii = 0; ii < eventTypeIds.Length; ii++) { - CollectFields(session, eventTypeIds[ii], selectClauses); + await CollectFieldsAsync(session, eventTypeIds[ii], selectClauses, ct); } } // use BaseEventType as the default if no EventTypes specified. else { - CollectFields(session, ObjectTypeIds.BaseEventType, selectClauses); + await CollectFieldsAsync(session, ObjectTypeIds.BaseEventType, selectClauses, ct); } return selectClauses; @@ -191,7 +194,7 @@ public EventFilter ConstructFilter(Session session) // save the last element. for (int ii = 0; ii < EventTypes.Count; ii++) { - // for this example uses the 'OfType' operator to limit events to thoses with specified event type. + // for this example uses the 'OfType' operator to limit events to thoses with specified event type. LiteralOperand operand1 = new LiteralOperand(); operand1.Value = new Variant(EventTypes[ii]); ContentFilterElement element3 = whereClause.Push(FilterOperator.OfType, operand1); @@ -220,7 +223,7 @@ public EventFilter ConstructFilter(Session session) return filter; } #endregion - + #region Private Methods /// /// Collects the fields for the event type. @@ -228,10 +231,11 @@ public EventFilter ConstructFilter(Session session) /// The session. /// The event type id. /// The event fields. - private void CollectFields(Session session, NodeId eventTypeId, SimpleAttributeOperandCollection eventFields) + /// A token to cancel the operation with + private async Task CollectFieldsAsync(Session session, NodeId eventTypeId, SimpleAttributeOperandCollection eventFields, CancellationToken ct = default) { // get the supertypes. - ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes(session, eventTypeId, false); + ReferenceDescriptionCollection supertypes = await FormUtils.BrowseSuperTypesAsync(session, eventTypeId, false, ct); if (supertypes == null) { @@ -239,16 +243,16 @@ private void CollectFields(Session session, NodeId eventTypeId, SimpleAttributeO } // process the types starting from the top of the tree. - Dictionary foundNodes = new Dictionary(); + Dictionary foundNodes = new Dictionary(); QualifiedNameCollection parentPath = new QualifiedNameCollection(); - for (int ii = supertypes.Count-1; ii >= 0; ii--) + for (int ii = supertypes.Count - 1; ii >= 0; ii--) { - CollectFields(session, (NodeId)supertypes[ii].NodeId, parentPath, eventFields, foundNodes); + await CollectFieldsAsync(session, (NodeId)supertypes[ii].NodeId, parentPath, eventFields, foundNodes, ct); } // collect the fields for the selected type. - CollectFields(session, eventTypeId, parentPath, eventFields, foundNodes); + await CollectFieldsAsync(session, eventTypeId, parentPath, eventFields, foundNodes, ct); } /// @@ -259,12 +263,14 @@ private void CollectFields(Session session, NodeId eventTypeId, SimpleAttributeO /// The parent path. /// The event fields. /// The table of found nodes. - private void CollectFields( + /// A token to cancel the operation with + private async Task CollectFieldsAsync( Session session, NodeId nodeId, QualifiedNameCollection parentPath, SimpleAttributeOperandCollection eventFields, - Dictionary foundNodes) + Dictionary foundNodes, + CancellationToken ct = default) { // find all of the children of the field. BrowseDescription nodeToBrowse = new BrowseDescription(); @@ -276,7 +282,7 @@ private void CollectFields( nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; - ReferenceDescriptionCollection children = FormUtils.Browse(session, nodeToBrowse, false); + ReferenceDescriptionCollection children = await FormUtils.BrowseAsync(session, nodeToBrowse, false, ct); if (children == null) { @@ -304,7 +310,7 @@ private void CollectFields( field.TypeDefinitionId = ObjectTypeIds.BaseEventType; field.BrowsePath = browsePath; - field.AttributeId = (child.NodeClass == NodeClass.Variable)?Attributes.Value:Attributes.NodeId; + field.AttributeId = (child.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId; eventFields.Add(field); } @@ -316,7 +322,7 @@ private void CollectFields( if (!foundNodes.ContainsKey(targetId)) { foundNodes.Add(targetId, browsePath); - CollectFields(session, (NodeId)child.NodeId, browsePath, eventFields, foundNodes); + await CollectFieldsAsync(session, (NodeId)child.NodeId, browsePath, eventFields, foundNodes, ct); } } } diff --git a/Workshop/Common/FormUtils.cs b/Workshop/Common/FormUtils.cs index 21d829512..6c09c6f54 100644 --- a/Workshop/Common/FormUtils.cs +++ b/Workshop/Common/FormUtils.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,8 @@ using System.Collections.Generic; using Opc.Ua; using Opc.Ua.Client; +using System.Threading.Tasks; +using System.Threading; namespace Quickstarts { @@ -105,7 +107,7 @@ private static string GetAccessLevelDisplayText(byte accessLevel) /// /// Gets the display text for the event notifier attribute. /// - /// The event notifier. + /// The event notifier. /// The event notifier formatted as a string. private static string GetEventNotifierDisplayText(byte eventNotifier) { @@ -147,7 +149,7 @@ private static string GetEventNotifierDisplayText(byte eventNotifier) /// /// Gets the display text for the value rank attribute. /// - /// The value rank. + /// The value rank. /// The value rank formatted as a string. private static string GetValueRankDisplayText(int valueRank) { @@ -170,8 +172,9 @@ private static string GetValueRankDisplayText(int valueRank) /// The currently active session. /// The id of the attribute. /// The value of the attribute. + /// A cancellation token to cancel the operation /// The attribute formatted as a string. - public static string GetAttributeDisplayText(Session session, uint attributeId, Variant value) + public static async Task GetAttributeDisplayTextAsync(Session session, uint attributeId, Variant value, CancellationToken ct = default) { if (value == Variant.Null) { @@ -184,7 +187,7 @@ public static string GetAttributeDisplayText(Session session, uint attributeId, case Attributes.UserAccessLevel: { byte? field = value.Value as byte?; - + if (field != null) { return GetAccessLevelDisplayText(field.Value); @@ -207,7 +210,7 @@ public static string GetAttributeDisplayText(Session session, uint attributeId, case Attributes.DataType: { - return session.NodeCache.GetDisplayText(value.Value as NodeId); + return await session.NodeCache.GetDisplayTextAsync(value.Value as NodeId, ct); } case Attributes.ValueRank: @@ -254,7 +257,7 @@ public static string GetAttributeDisplayText(Session session, uint attributeId, } // use default format. - return value.ToString(); + return value.ToString(); } /// @@ -262,7 +265,7 @@ public static string GetAttributeDisplayText(Session session, uint attributeId, /// /// The configuration. /// A list of server urls. - public static IList DiscoverServers(ApplicationConfiguration configuration) + public static async Task> DiscoverServersAsync(ApplicationConfiguration configuration, CancellationToken ct = default) { List serverUrls = new List(); @@ -273,7 +276,7 @@ public static IList DiscoverServers(ApplicationConfiguration configurati // Connect to the local discovery server and find the available servers. using (DiscoveryClient client = DiscoveryClient.Create(new Uri("opc.tcp://localhost:4840"), endpointConfiguration)) { - ApplicationDescriptionCollection servers = client.FindServers(null); + ApplicationDescriptionCollection servers = await client.FindServersAsync(null, ct); // populate the drop down list with the discovery URLs for the available servers. for (int ii = 0; ii < servers.Count; ii++) @@ -288,7 +291,7 @@ public static IList DiscoverServers(ApplicationConfiguration configurati string discoveryUrl = servers[ii].DiscoveryUrls[jj]; // Many servers will use the '/discovery' suffix for the discovery endpoint. - // The URL without this prefix should be the base URL for the server. + // The URL without this prefix should be the base URL for the server. if (discoveryUrl.EndsWith("/discovery")) { discoveryUrl = discoveryUrl.Substring(0, discoveryUrl.Length - "/discovery".Length); @@ -311,8 +314,9 @@ public static IList DiscoverServers(ApplicationConfiguration configurati /// /// The discovery URL. /// if set to true select an endpoint that uses security. + /// The token to cancel the operation with /// The best available endpoint. - public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSecurity) + public static async Task SelectEndpointAsync(string discoveryUrl, bool useSecurity, CancellationToken ct = default) { // needs to add the '/discovery' back onto non-UA TCP URLs. if (!discoveryUrl.StartsWith(Utils.UriSchemeOpcTcp)) @@ -335,9 +339,9 @@ public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSe // Connect to the server's discovery endpoint and find the available configuration. using (DiscoveryClient client = DiscoveryClient.Create(uri, configuration)) { - EndpointDescriptionCollection endpoints = client.GetEndpoints(null); + EndpointDescriptionCollection endpoints = await client.GetEndpointsAsync(null, ct); - // select the best endpoint to use based on the selected URL and the UseSecurity checkbox. + // select the best endpoint to use based on the selected URL and the UseSecurity checkbox. for (int ii = 0; ii < endpoints.Count; ii++) { EndpointDescription endpoint = endpoints[ii]; @@ -367,7 +371,7 @@ public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSe selectedEndpoint = endpoint; } - // The security level is a relative measure assigned by the server to the + // The security level is a relative measure assigned by the server to the // endpoints that it returns. Clients should always pick the highest level // unless they have a reason not too. if (endpoint.SecurityLevel > selectedEndpoint.SecurityLevel) @@ -385,7 +389,7 @@ public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSe } // if a server is behind a firewall it may return URLs that are not accessible to the client. - // This problem can be avoided by assuming that the domain in the URL used to call + // This problem can be avoided by assuming that the domain in the URL used to call // GetEndpoints can be used to access any of the endpoints. This code makes that conversion. // Note that the conversion only makes sense if discovery uses the same protocol as the endpoint. @@ -409,10 +413,11 @@ public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSe /// The session. /// The set of browse operations to perform. /// if set to true a exception will be thrown on an error. + /// A cancellation token to cancel the operation /// /// The references found. Null if an error occurred. /// - public static ReferenceDescriptionCollection Browse(Session session, BrowseDescriptionCollection nodesToBrowse, bool throwOnError) + public static async Task BrowseAsync(ISession session, BrowseDescriptionCollection nodesToBrowse, bool throwOnError, CancellationToken ct = default) { try { @@ -422,16 +427,14 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr while (nodesToBrowse.Count > 0) { // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - session.Browse( + BrowseResponse response = await session.BrowseAsync( null, null, 0, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); @@ -443,7 +446,7 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr // check for error. if (StatusCode.IsBad(results[ii].StatusCode)) { - // this error indicates that the server does not have enough simultaneously active + // this error indicates that the server does not have enough simultaneously active // continuation points. This request will need to be resent after the other operations // have been completed and their continuation points released. if (results[ii].StatusCode == StatusCodes.BadNoContinuationPoints) @@ -453,7 +456,7 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr continue; } - + // check if all references have been fetched. if (results[ii].References.Count == 0) { @@ -476,12 +479,14 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr while (continuationPoints.Count > 0) { // continue browse operation. - session.BrowseNext( + BrowseNextResponse response2 = await session.BrowseNextAsync( null, false, continuationPoints, - out results, - out diagnosticInfos); + ct); + + results = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); @@ -531,7 +536,7 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr return null; } } - + /// /// Finds the type of the event for the notification. /// @@ -567,7 +572,7 @@ public static NodeId FindEventType(MonitoredItem monitoredItem, EventFieldList n /// /// The references found. Null if an error occurred. /// - public static ReferenceDescriptionCollection Browse(Session session, BrowseDescription nodeToBrowse, bool throwOnError) + public static async Task BrowseAsync(ISession session, BrowseDescription nodeToBrowse, bool throwOnError, CancellationToken ct = default) { try { @@ -578,16 +583,15 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr nodesToBrowse.Add(nodeToBrowse); // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - session.Browse( + BrowseResponse response = await session.BrowseAsync( null, null, 0, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); @@ -616,12 +620,14 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); - session.BrowseNext( + BrowseNextResponse response2 = await session.BrowseNextAsync( null, false, continuationPoints, - out results, - out diagnosticInfos); + ct); + + results = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); @@ -648,10 +654,11 @@ public static ReferenceDescriptionCollection Browse(Session session, BrowseDescr /// The session. /// The NodeId for a type node in the address space. /// if set to true a exception will be thrown on an error. + /// A cancellation token to cancel the operation /// /// The references found. Null if an error occurred. /// - public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, NodeId typeId, bool throwOnError) + public static async Task BrowseSuperTypesAsync(ISession session, NodeId typeId, bool throwOnError, CancellationToken ct = default) { ReferenceDescriptionCollection supertypes = new ReferenceDescriptionCollection(); @@ -664,10 +671,10 @@ public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, N nodeToBrowse.BrowseDirection = BrowseDirection.Inverse; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype; nodeToBrowse.IncludeSubtypes = false; // more efficient to use IncludeSubtypes=False when possible. - nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. + nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; - ReferenceDescriptionCollection references = Browse(session, nodeToBrowse, throwOnError); + ReferenceDescriptionCollection references = await BrowseAsync(session, nodeToBrowse, throwOnError, ct); while (references != null && references.Count > 0) { @@ -682,7 +689,7 @@ public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, N // get the references for the next level up. nodeToBrowse.NodeId = (NodeId)references[0].NodeId; - references = Browse(session, nodeToBrowse, throwOnError); + references = await BrowseAsync(session, nodeToBrowse, throwOnError, ct); } // return complete list. @@ -707,15 +714,17 @@ public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, N /// The notification. /// The known event types. /// Mapping between event types and known event types. + /// The cancellation token to cancel the operation with /// /// The event object. Null if the notification is not a valid event type. /// - public static BaseEventState ConstructEvent( + public static async Task ConstructEventAsync( Session session, MonitoredItem monitoredItem, EventFieldList notification, Dictionary knownEventTypes, - Dictionary eventTypeMappings) + Dictionary eventTypeMappings, + CancellationToken ct = default) { // find the event type. NodeId eventTypeId = FindEventType(monitoredItem, notification); @@ -748,7 +757,7 @@ public static BaseEventState ConstructEvent( if (knownType == null) { // browse for the supertypes of the event type. - ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes(session, eventTypeId, false); + ReferenceDescriptionCollection supertypes = await FormUtils.BrowseSuperTypesAsync(session, eventTypeId, false, ct); // can't do anything with unknown types. if (supertypes == null) @@ -801,12 +810,14 @@ public static BaseEventState ConstructEvent( /// An open session with the server to use. /// The starting node for the relative paths. /// The namespace URIs referenced by the relative paths. + /// A cancellation token to cancel the operation /// The relative paths. /// A collection of local nodes. - public static List TranslateBrowsePaths( + public static async Task> TranslateBrowsePathsAsync( Session session, NodeId startNodeId, NamespaceTable namespacesUris, + CancellationToken ct, params string[] relativePaths) { // build the list of browse paths to follow by parsing the relative paths. @@ -818,7 +829,7 @@ public static List TranslateBrowsePaths( { BrowsePath browsePath = new BrowsePath(); - // The relative paths used indexes in the namespacesUris table. These must be + // The relative paths used indexes in the namespacesUris table. These must be // converted to indexes used by the server. An error occurs if the relative path // refers to a namespaceUri that the server does not recognize. @@ -838,14 +849,14 @@ public static List TranslateBrowsePaths( } // make the call to the server. - BrowsePathResultCollection results; - DiagnosticInfoCollection diagnosticInfos; - - ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds( + TranslateBrowsePathsToNodeIdsResponse response = await session.TranslateBrowsePathsToNodeIdsAsync( null, browsePaths, - out results, - out diagnosticInfos); + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + BrowsePathResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; // ensure that the server returned valid results. Session.ValidateResponse(results, browsePaths); @@ -880,7 +891,7 @@ public static List TranslateBrowsePaths( continue; } - // The targetId is an ExpandedNodeId because it could be node in another server. + // The targetId is an ExpandedNodeId because it could be node in another server. // The ToNodeId function is used to convert a local NodeId stored in a ExpandedNodeId to a NodeId. nodes.Add(ExpandedNodeId.ToNodeId(target.TargetId, session.NamespaceUris)); } @@ -893,13 +904,14 @@ public static List TranslateBrowsePaths( /// Collects the fields for the type. /// /// The session. - /// The type id. + /// The type id. /// The fields. /// The node id for the declaration of the field. - public static void CollectFieldsForType(Session session, NodeId typeId, SimpleAttributeOperandCollection fields, List fieldNodeIds) + /// The cancellation token to cancel the operation with + public static async Task CollectFieldsForTypeAsync(Session session, NodeId typeId, SimpleAttributeOperandCollection fields, List fieldNodeIds, CancellationToken ct = default) { // get the supertypes. - ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes(session, typeId, false); + ReferenceDescriptionCollection supertypes = await FormUtils.BrowseSuperTypesAsync(session, typeId, false, ct); if (supertypes == null) { @@ -912,25 +924,26 @@ public static void CollectFieldsForType(Session session, NodeId typeId, SimpleAt for (int ii = supertypes.Count - 1; ii >= 0; ii--) { - CollectFields(session, (NodeId)supertypes[ii].NodeId, parentPath, fields, fieldNodeIds, foundNodes); + await CollectFieldsAsync(session, (NodeId)supertypes[ii].NodeId, parentPath, fields, fieldNodeIds, foundNodes, ct); } // collect the fields for the selected type. - CollectFields(session, typeId, parentPath, fields, fieldNodeIds, foundNodes); + await CollectFieldsAsync(session, typeId, parentPath, fields, fieldNodeIds, foundNodes, ct); } /// /// Collects the fields for the instance. /// /// The session. - /// The instance id. + /// The instance id. /// The fields. /// The node id for the declaration of the field. - public static void CollectFieldsForInstance(Session session, NodeId instanceId, SimpleAttributeOperandCollection fields, List fieldNodeIds) + /// The cancellation token to cancel the operation with + public static async Task CollectFieldsForInstanceAsync(Session session, NodeId instanceId, SimpleAttributeOperandCollection fields, List fieldNodeIds, CancellationToken ct = default) { Dictionary foundNodes = new Dictionary(); QualifiedNameCollection parentPath = new QualifiedNameCollection(); - CollectFields(session, instanceId, parentPath, fields, fieldNodeIds, foundNodes); + await CollectFieldsAsync(session, instanceId, parentPath, fields, fieldNodeIds, foundNodes, ct); } /// @@ -942,13 +955,15 @@ public static void CollectFieldsForInstance(Session session, NodeId instanceId, /// The event fields. /// The node id for the declaration of the field. /// The table of found nodes. - private static void CollectFields( + /// The cancellation token to cancel the operation with + private static async Task CollectFieldsAsync( Session session, NodeId nodeId, QualifiedNameCollection parentPath, SimpleAttributeOperandCollection fields, List fieldNodeIds, - Dictionary foundNodes) + Dictionary foundNodes, + CancellationToken ct = default) { // find all of the children of the field. BrowseDescription nodeToBrowse = new BrowseDescription(); @@ -960,7 +975,7 @@ private static void CollectFields( nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; - ReferenceDescriptionCollection children = FormUtils.Browse(session, nodeToBrowse, false); + ReferenceDescriptionCollection children = await FormUtils.BrowseAsync(session, nodeToBrowse, false, ct); if (children == null) { @@ -1003,7 +1018,7 @@ private static void CollectFields( if (!foundNodes.ContainsKey(targetId)) { foundNodes.Add(targetId, browsePath); - CollectFields(session, (NodeId)child.NodeId, browsePath, fields, fieldNodeIds, foundNodes); + await CollectFieldsAsync(session, (NodeId)child.NodeId, browsePath, fields, fieldNodeIds, foundNodes, ct); } } } diff --git a/Workshop/Common/ModelUtils.cs b/Workshop/Common/ModelUtils.cs index a79b402a9..3b3ded71b 100644 --- a/Workshop/Common/ModelUtils.cs +++ b/Workshop/Common/ModelUtils.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,8 @@ using System.Collections.Generic; using Opc.Ua; using Opc.Ua.Client; +using System.Threading; +using System.Threading.Tasks; namespace Quickstarts { @@ -43,25 +45,25 @@ public static class ModelUtils /// /// Collects the instance declarations for a type. /// - public static List CollectInstanceDeclarationsForType(Session session, NodeId typeId) + public static async Task> CollectInstanceDeclarationsForTypeAsync(ISession session, NodeId typeId, CancellationToken ct = default) { // process the types starting from the top of the tree. List instances = new List(); Dictionary map = new Dictionary(); // get the supertypes. - ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes(session, typeId, false); + ReferenceDescriptionCollection supertypes = await FormUtils.BrowseSuperTypesAsync(session, typeId, false, ct); if (supertypes != null) { for (int ii = supertypes.Count - 1; ii >= 0; ii--) { - CollectInstanceDeclarations(session, (NodeId)supertypes[ii].NodeId, null, instances, map); + await CollectInstanceDeclarationsAsync(session, (NodeId)supertypes[ii].NodeId, null, instances, map, ct); } } // collect the fields for the selected type. - CollectInstanceDeclarations(session, typeId, null, instances, map); + await CollectInstanceDeclarationsAsync(session, typeId, null, instances, map, ct); // return the complete list. return instances; @@ -70,12 +72,13 @@ public static List CollectInstanceDeclarationsForType(Sessi /// /// Collects the fields for the instance node. /// - private static void CollectInstanceDeclarations( - Session session, + private static async Task CollectInstanceDeclarationsAsync( + ISession session, NodeId typeId, InstanceDeclaration parent, List instances, - IDictionary map) + IDictionary map, + CancellationToken ct = default) { // find the children. BrowseDescription nodeToBrowse = new BrowseDescription(); @@ -96,7 +99,7 @@ private static void CollectInstanceDeclarations( nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; // ignore any browsing errors. - ReferenceDescriptionCollection references = FormUtils.Browse(session, nodeToBrowse, false); + ReferenceDescriptionCollection references = await FormUtils.BrowseAsync(session, nodeToBrowse, false, ct); if (references == null) { @@ -170,7 +173,7 @@ private static void CollectInstanceDeclarations( } // find the modelling rules. - List modellingRules = FindTargetOfReference(session, nodeIds, Opc.Ua.ReferenceTypeIds.HasModellingRule, false); + List modellingRules = await FindTargetOfReferenceAsync(session, nodeIds, Opc.Ua.ReferenceTypeIds.HasModellingRule, false, ct); if (modellingRules != null) { @@ -187,7 +190,7 @@ private static void CollectInstanceDeclarations( } // update the descriptions. - UpdateInstanceDescriptions(session, children, false); + await UpdateInstanceDescriptionsAsync(session, children, false, ct); // recusively collect instance declarations for the tree below. for (int ii = 0; ii < children.Count; ii++) @@ -195,7 +198,7 @@ private static void CollectInstanceDeclarations( if (!NodeId.IsNull(children[ii].ModellingRule)) { instances.Add(children[ii]); - CollectInstanceDeclarations(session, typeId, children[ii], instances, map); + await CollectInstanceDeclarationsAsync(session, typeId, children[ii], instances, map, ct); } } } @@ -203,7 +206,7 @@ private static void CollectInstanceDeclarations( /// /// Finds the targets for the specified reference. /// - private static List FindTargetOfReference(Session session, List nodeIds, NodeId referenceTypeId, bool throwOnError) + private static async Task> FindTargetOfReferenceAsync(ISession session, List nodeIds, NodeId referenceTypeId, bool throwOnError, CancellationToken ct = default) { try { @@ -223,16 +226,15 @@ private static List FindTargetOfReference(Session session, List } // start the browse operation. - BrowseResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - session.Browse( + BrowseResponse response = await session.BrowseAsync( null, null, 1, nodesToBrowse, - out results, - out diagnosticInfos); + ct); + + BrowseResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); @@ -271,12 +273,14 @@ private static List FindTargetOfReference(Session session, List // release continuation points. if (continuationPoints.Count > 0) { - session.BrowseNext( + BrowseNextResponse response2 = await session.BrowseNextAsync( null, true, continuationPoints, - out results, - out diagnosticInfos); + ct); + + results = response2.Results; + diagnosticInfos = response2.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); @@ -299,7 +303,7 @@ private static List FindTargetOfReference(Session session, List /// /// Finds the targets for the specified reference. /// - private static void UpdateInstanceDescriptions(Session session, List instances, bool throwOnError) + private static async Task UpdateInstanceDescriptionsAsync(ISession session, List instances, bool throwOnError, CancellationToken ct = default) { try { @@ -324,16 +328,15 @@ private static void UpdateInstanceDescriptions(Session session, List= 0) { @@ -621,7 +624,7 @@ public EventFilter GetFilter() filter.WhereClause = GetWhereClause(); return filter; } - + /// /// Adds a simple field to the declaration. /// @@ -676,14 +679,14 @@ public SimpleAttributeOperandCollection GetSelectClause() { operand = new SimpleAttributeOperand(); operand.TypeDefinitionId = field.InstanceDeclaration.RootTypeId; - operand.AttributeId = (field.InstanceDeclaration.NodeClass == NodeClass.Object)?Attributes.NodeId:Attributes.Value; + operand.AttributeId = (field.InstanceDeclaration.NodeClass == NodeClass.Object) ? Attributes.NodeId : Attributes.Value; operand.BrowsePath = field.InstanceDeclaration.BrowsePath; selectClause.Add(operand); } return selectClause; } - + /// /// Returns the where clause defined by the filter declaration. /// @@ -728,12 +731,12 @@ public T GetValue(QualifiedName browseName, VariantCollection fields, T defau { if (this.Fields[ii].InstanceDeclaration.BrowseName == browseName) { - if (ii >= fields.Count+1) + if (ii >= fields.Count + 1) { return defaultValue; } - object value = fields[ii+1].Value; + object value = fields[ii + 1].Value; if (typeof(T).IsInstanceOfType(value)) { diff --git a/Workshop/Common/ParsedNodeId.cs b/Workshop/Common/ParsedNodeId.cs index c375f29a7..09e1e5db4 100644 --- a/Workshop/Common/ParsedNodeId.cs +++ b/Workshop/Common/ParsedNodeId.cs @@ -129,7 +129,7 @@ public static ParsedNodeId Parse(NodeId nodeId) // extract any component path. StringBuilder buffer = new StringBuilder(); - int index = start+1; + int index = start + 1; int end = identifier.Length; bool escaped = false; diff --git a/Workshop/Common/Quickstart Library.csproj b/Workshop/Common/Quickstart Library.csproj index 802208bf9..fd2a59898 100644 --- a/Workshop/Common/Quickstart Library.csproj +++ b/Workshop/Common/Quickstart Library.csproj @@ -44,6 +44,7 @@ prompt 4 false + AllRules.ruleset pdbonly @@ -53,6 +54,7 @@ prompt 4 false + AllRules.ruleset @@ -131,7 +133,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Common/QuickstartNodeManager.cs b/Workshop/Common/QuickstartNodeManager.cs index dedff90aa..ef86b1519 100644 --- a/Workshop/Common/QuickstartNodeManager.cs +++ b/Workshop/Common/QuickstartNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -56,7 +56,7 @@ protected QuickstartNodeManager( params string[] namespaceUris) : this(server, (ApplicationConfiguration)null, namespaceUris) - { + { } /// @@ -81,10 +81,10 @@ protected QuickstartNodeManager( // save a reference to the UA server instance that owns the node manager. m_server = server; - // all operations require information about the system + // all operations require information about the system m_systemContext = m_server.DefaultSystemContext.Copy(); - // the node id factory assigns new node ids to new nodes. + // the node id factory assigns new node ids to new nodes. // the strategy used by a NodeManager depends on what kind of information it provides. m_systemContext.NodeIdFactory = this; @@ -111,13 +111,13 @@ protected QuickstartNodeManager( m_monitoredNodes = new Dictionary(); } #endregion - + #region IDisposable Members /// /// Frees any unmanaged resources. /// public void Dispose() - { + { Dispose(true); } @@ -125,7 +125,7 @@ public void Dispose() /// An overrideable version of the Dispose. /// protected virtual void Dispose(bool disposing) - { + { if (disposing) { lock (m_lock) @@ -239,7 +239,7 @@ protected List RootNotifiers /// /// Gets the table of monitored items. /// - protected Dictionary MonitoredItems + protected Dictionary MonitoredItems { get { return m_monitoredItems; } } @@ -453,14 +453,14 @@ public bool DeleteNode( /// public virtual IEnumerable NamespaceUris { - get - { - return m_namespaceUris; + get + { + return m_namespaceUris; } protected set { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw new ArgumentNullException(nameof(value)); List namespaceUris = new List(value); SetNamespaces(namespaceUris.ToArray()); } @@ -472,11 +472,11 @@ protected set /// /// The externalReferences is an out parameter that allows the node manager to link to nodes /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and - /// should have a reference to the root folder node(s) exposed by this node manager. + /// should have a reference to the root folder node(s) exposed by this node manager. /// public virtual void CreateAddressSpace(IDictionary> externalReferences) { - LoadPredefinedNodes(m_systemContext, externalReferences); + LoadPredefinedNodes(m_systemContext, externalReferences); } #region CreateAddressSpace Support Functions @@ -656,7 +656,7 @@ protected virtual void RemovePredefinedNode( /// protected virtual void OnNodeRemoved(NodeState node) { - // overridden by the sub-class. + // overridden by the sub-class. } /// @@ -817,7 +817,7 @@ protected void AddTypesToTypeTree(NodeId typeId) } /// - /// Finds the specified and checks if it is of the expected type. + /// Finds the specified and checks if it is of the expected type. /// /// Returns null if not found or not of the correct type. public NodeState FindPredefinedNode(NodeId nodeId, Type expectedType) @@ -869,7 +869,7 @@ public virtual void DeleteAddressSpace() /// Returns a unique handle for the node. /// /// - /// This must efficiently determine whether the node belongs to the node manager. If it does belong to + /// This must efficiently determine whether the node belongs to the node manager. If it does belong to /// NodeManager it should return a handle that does not require the NodeId to be validated again when /// the handle is passed into other methods such as 'Read' or 'Write'. /// @@ -884,7 +884,7 @@ public virtual object GetManagerHandle(NodeId nodeId) /// /// Returns a unique handle for the node. /// - protected virtual NodeHandle GetManagerHandle(ServerSystemContext context, NodeId nodeId, IDictionary cache) + protected virtual NodeHandle GetManagerHandle(ServerSystemContext context, NodeId nodeId, IDictionary cache) { if (!IsNodeIdInNamespace(nodeId)) { @@ -930,7 +930,7 @@ public virtual void AddReferences(IDictionary> referen { continue; } - + // add reference to external target. foreach (IReference reference in current.Value) { @@ -942,16 +942,16 @@ public virtual void AddReferences(IDictionary> referen } } } - + /// /// This method is used to delete bi-directional references to nodes from other node managers. /// public virtual ServiceResult DeleteReference( - object sourceHandle, - NodeId referenceTypeId, - bool isInverse, - ExpandedNodeId targetId, - bool deleteBiDirectional) + object sourceHandle, + NodeId referenceTypeId, + bool isInverse, + ExpandedNodeId targetId, + bool deleteBiDirectional) { lock (Lock) { @@ -968,7 +968,7 @@ public virtual ServiceResult DeleteReference( { return StatusCodes.BadNotSupported; } - + // only support references to Source Areas. source.Node.RemoveReference(referenceTypeId, isInverse, targetId); @@ -997,8 +997,8 @@ public virtual ServiceResult DeleteReference( /// This method validates any placeholder handle. /// public virtual NodeMetadata GetNodeMetadata( - OperationContext context, - object targetHandle, + OperationContext context, + object targetHandle, BrowseResultMask resultMask) { ServerSystemContext systemContext = m_systemContext.Copy(context); @@ -1010,9 +1010,9 @@ public virtual NodeMetadata GetNodeMetadata( if (handle == null) { - return null; + return null; } - + // validate node. NodeState target = ValidateNode(systemContext, handle, null); @@ -1055,7 +1055,7 @@ public virtual NodeMetadata GetNodeMetadata( } metadata.ArrayDimensions = (IList)values[4]; - + if (values[5] != null && values[6] != null) { metadata.AccessLevel = (byte)(((byte)values[5]) & ((byte)values[6])); @@ -1093,18 +1093,18 @@ public virtual NodeMetadata GetNodeMetadata( /// The node manager can store its state information in the Data and Index properties. /// public virtual void Browse( - OperationContext context, - ref ContinuationPoint continuationPoint, + OperationContext context, + ref ContinuationPoint continuationPoint, IList references) - { - if (continuationPoint == null) throw new ArgumentNullException("continuationPoint"); - if (references == null) throw new ArgumentNullException("references"); - + { + if (continuationPoint == null) throw new ArgumentNullException(nameof(continuationPoint)); + if (references == null) throw new ArgumentNullException(nameof(references)); + ServerSystemContext systemContext = m_systemContext.Copy(context); // check for valid view. ValidateViewDescription(systemContext, continuationPoint.View); - + INodeBrowser browser = null; lock (Lock) @@ -1114,9 +1114,9 @@ public virtual void Browse( if (handle == null) { - throw new ServiceResultException(StatusCodes.BadNodeIdUnknown); + throw new ServiceResultException(StatusCodes.BadNodeIdUnknown); } - + // validate node. NodeState source = ValidateNode(systemContext, handle, null); @@ -1129,7 +1129,7 @@ public virtual void Browse( if (!IsNodeInView(systemContext, continuationPoint, source)) { throw new ServiceResultException(StatusCodes.BadNodeNotInView); - } + } // check for previous continuation point. browser = continuationPoint.Data as INodeBrowser; @@ -1158,7 +1158,7 @@ public virtual void Browse( for (IReference reference = browser.Next(); reference != null; reference = browser.Next()) { - // create the type definition reference. + // create the type definition reference. ReferenceDescription description = GetReferenceDescription(systemContext, cache, reference, continuationPoint); if (description == null) @@ -1215,18 +1215,18 @@ protected virtual bool IsReferenceInView(ServerSystemContext context, Continuati /// protected virtual ReferenceDescription GetReferenceDescription( ServerSystemContext context, - Dictionary cache, + Dictionary cache, IReference reference, ContinuationPoint continuationPoint) { ServerSystemContext systemContext = m_systemContext.Copy(context); - // create the type definition reference. + // create the type definition reference. ReferenceDescription description = new ReferenceDescription(); description.NodeId = reference.TargetId; description.SetReferenceType(continuationPoint.ResultMask, reference.ReferenceTypeId, !reference.IsInverse); - + // check if reference is in the view. if (!IsReferenceInView(context, continuationPoint, reference)) { @@ -1259,7 +1259,7 @@ protected virtual ReferenceDescription GetReferenceDescription( if (target == null) { NodeHandle handle = GetManagerHandle(context, (NodeId)reference.TargetId, null) as NodeHandle; - + if (handle != null) { target = ValidateNode(context, handle, null); @@ -1313,16 +1313,16 @@ protected virtual ReferenceDescription GetReferenceDescription( /// Returns the target of the specified browse path fragment(s). /// /// - /// If reference exists but the node manager does not know the browse name it must + /// If reference exists but the node manager does not know the browse name it must /// return the NodeId as an unresolvedTargetIds. The caller will try to check the - /// browse name. + /// browse name. /// public virtual void TranslateBrowsePath( - OperationContext context, - object sourceHandle, - RelativePathElement relativePath, - IList targetIds, - IList unresolvedTargetIds) + OperationContext context, + object sourceHandle, + RelativePathElement relativePath, + IList targetIds, + IList unresolvedTargetIds) { ServerSystemContext systemContext = m_systemContext.Copy(context); IDictionary operationCache = new NodeIdDictionary(); @@ -1334,9 +1334,9 @@ public virtual void TranslateBrowsePath( if (handle == null) { - return; + return; } - + // validate node. NodeState source = ValidateNode(systemContext, handle, operationCache); @@ -1421,25 +1421,25 @@ public virtual void TranslateBrowsePath( } } } - + /// /// Reads the value for the specified attribute. /// public virtual void Read( - OperationContext context, - double maxAge, - IList nodesToRead, - IList values, + OperationContext context, + double maxAge, + IList nodesToRead, + IList values, IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToValidate = new List(); lock (Lock) { for (int ii = 0; ii < nodesToRead.Count; ii++) - { + { ReadValueId nodeToRead = nodesToRead[ii]; // skip items that have already been processed. @@ -1447,7 +1447,7 @@ public virtual void Read( { continue; } - + // check for valid handle. NodeHandle handle = GetManagerHandle(systemContext, nodeToRead.NodeId, operationCache); @@ -1458,24 +1458,24 @@ public virtual void Read( // owned by this node manager. nodeToRead.Processed = true; - + // create an initial value. DataValue value = values[ii] = new DataValue(); - - value.Value = null; + + value.Value = null; value.ServerTimestamp = DateTime.UtcNow; value.SourceTimestamp = DateTime.MinValue; - value.StatusCode = StatusCodes.Good; + value.StatusCode = StatusCodes.Good; // check if the node is a area in memory. if (handle.Node == null) { errors[ii] = StatusCodes.BadNodeIdUnknown; - + // must validate node in a seperate operation handle.Index = ii; nodesToValidate.Add(handle); - + continue; } @@ -1594,9 +1594,9 @@ protected virtual NodeState ValidationComplete( /// Verifies that the specified node exists. /// protected virtual NodeState ValidateNode( - ServerSystemContext context, + ServerSystemContext context, NodeHandle handle, - IDictionary cache) + IDictionary cache) { // lookup in cache. NodeState target = FindNodeInCache(context, handle, cache); @@ -1662,18 +1662,18 @@ protected virtual void Read( /// Writes the value for the specified attributes. /// public virtual void Write( - OperationContext context, - IList nodesToWrite, + OperationContext context, + IList nodesToWrite, IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToValidate = new List(); lock (Lock) { for (int ii = 0; ii < nodesToWrite.Count; ii++) - { + { WriteValue nodeToWrite = nodesToWrite[ii]; // skip items that have already been processed. @@ -1681,7 +1681,7 @@ public virtual void Write( { continue; } - + // check for valid handle. NodeHandle handle = GetManagerHandle(systemContext, nodeToWrite.NodeId, operationCache); @@ -1702,16 +1702,16 @@ public virtual void Write( continue; } } - + // check if the node is a area in memory. if (handle.Node == null) { errors[ii] = StatusCodes.BadNodeIdUnknown; - + // must validate node in a seperate operation. handle.Index = ii; nodesToValidate.Add(handle); - + continue; } @@ -1795,16 +1795,16 @@ protected virtual void Write( /// Reads the history for the specified nodes. /// public virtual void HistoryRead( - OperationContext context, - HistoryReadDetails details, - TimestampsToReturn timestampsToReturn, - bool releaseContinuationPoints, - IList nodesToRead, - IList results, - IList errors) + OperationContext context, + HistoryReadDetails details, + TimestampsToReturn timestampsToReturn, + bool releaseContinuationPoints, + IList nodesToRead, + IList results, + IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToProcess = new List(); lock (Lock) @@ -1833,9 +1833,9 @@ public virtual void HistoryRead( // create an initial result. HistoryReadResult result = results[ii] = new HistoryReadResult(); - result.HistoryData = null; + result.HistoryData = null; result.ContinuationPoint = null; - result.StatusCode = StatusCodes.Good; + result.StatusCode = StatusCodes.Good; // check if the node is a area in memory. if (handle.Node == null) @@ -1897,7 +1897,7 @@ public virtual void HistoryRead( nodesToProcess, operationCache); } - + #region HistoryRead Support Functions /// /// Releases the continuation points. @@ -2046,11 +2046,11 @@ protected virtual void HistoryReadEvents( /// protected virtual void HistoryRead( ServerSystemContext context, - HistoryReadDetails details, - TimestampsToReturn timestampsToReturn, - bool releaseContinuationPoints, - IList nodesToRead, - IList results, + HistoryReadDetails details, + TimestampsToReturn timestampsToReturn, + bool releaseContinuationPoints, + IList nodesToRead, + IList results, IList errors, List nodesToProcess, IDictionary cache) @@ -2076,7 +2076,7 @@ protected virtual void HistoryRead( // handle raw data request. ReadRawModifiedDetails readRawModifiedDetails = details as ReadRawModifiedDetails; - + if (readRawModifiedDetails != null) { // at least one must be provided. @@ -2109,7 +2109,7 @@ protected virtual void HistoryRead( // handle processed data request. ReadProcessedDetails readProcessedDetails = details as ReadProcessedDetails; - + if (readProcessedDetails != null) { // check the list of aggregates. @@ -2136,10 +2136,10 @@ protected virtual void HistoryRead( return; } - + // handle raw data at time request. ReadAtTimeDetails readAtTimeDetails = details as ReadAtTimeDetails; - + if (readAtTimeDetails != null) { HistoryReadAtTime( @@ -2204,11 +2204,11 @@ protected virtual void HistoryRead( /// Updates the history for the specified nodes. /// public virtual void HistoryUpdate( - OperationContext context, - Type detailsType, - IList nodesToUpdate, - IList results, - IList errors) + OperationContext context, + Type detailsType, + IList nodesToUpdate, + IList results, + IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); IDictionary operationCache = new NodeIdDictionary(); @@ -2305,11 +2305,11 @@ public virtual void HistoryUpdate( /// protected virtual void HistoryUpdate( ServerSystemContext context, - Type detailsType, - IList nodesToUpdate, - IList results, - IList errors, - List nodesToProcess, + Type detailsType, + IList nodesToUpdate, + IList results, + IList errors, + List nodesToProcess, IDictionary cache) { // handle update data request. @@ -2623,7 +2623,7 @@ public virtual void Call( { continue; } - + MethodState method = null; lock (Lock) @@ -2658,7 +2658,7 @@ public virtual void Call( { method = (MethodState)FindPredefinedNode(methodToCall.MethodId, typeof(MethodState)); } - + if (method == null) { errors[ii] = StatusCodes.BadMethodInvalid; @@ -2763,16 +2763,16 @@ protected virtual ServiceResult Call( /// Subscribes or unsubscribes to events produced by the specified source. /// /// - /// This method is called when a event subscription is created or deletes. The node manager - /// must start/stop reporting events for the specified object and all objects below it in + /// This method is called when a event subscription is created or deletes. The node manager + /// must start/stop reporting events for the specified object and all objects below it in /// the notifier hierarchy. /// public virtual ServiceResult SubscribeToEvents( - OperationContext context, - object sourceId, - uint subscriptionId, - IEventMonitoredItem monitoredItem, - bool unsubscribe) + OperationContext context, + object sourceId, + uint subscriptionId, + IEventMonitoredItem monitoredItem, + bool unsubscribe) { ServerSystemContext systemContext = SystemContext.Copy(context); @@ -2798,19 +2798,19 @@ public virtual ServiceResult SubscribeToEvents( return SubscribeToEvents(systemContext, source, monitoredItem, unsubscribe); } } - + /// /// Subscribes or unsubscribes to events produced by all event sources. /// /// - /// This method is called when a event subscription is created or deleted. The node + /// This method is called when a event subscription is created or deleted. The node /// manager must start/stop reporting events for all objects that it manages. /// public virtual ServiceResult SubscribeToAllEvents( - OperationContext context, - uint subscriptionId, - IEventMonitoredItem monitoredItem, - bool unsubscribe) + OperationContext context, + uint subscriptionId, + IEventMonitoredItem monitoredItem, + bool unsubscribe) { ServerSystemContext systemContext = SystemContext.Copy(context); @@ -2837,7 +2837,7 @@ public virtual ServiceResult SubscribeToAllEvents( /// /// The notifier. /// - /// A root notifier is a notifier owned by the NodeManager that is not the target of a + /// A root notifier is a notifier owned by the NodeManager that is not the target of a /// HasNotifier reference. These nodes need to be linked directly to the Server object. /// protected virtual void AddRootNotifier(NodeState notifier) @@ -2856,7 +2856,7 @@ protected virtual void AddRootNotifier(NodeState notifier) } m_rootNotifiers.Add(notifier); - + // need to prevent recursion with the server object. if (notifier.NodeId != ObjectIds.Server) { @@ -2928,10 +2928,10 @@ protected virtual void OnReportEvent( /// if set to true [unsubscribe]. /// Any error code. protected virtual ServiceResult SubscribeToEvents( - ServerSystemContext context, - NodeState source, - IEventMonitoredItem monitoredItem, - bool unsubscribe) + ServerSystemContext context, + NodeState source, + IEventMonitoredItem monitoredItem, + bool unsubscribe) { MonitoredNode monitoredNode = null; @@ -2986,13 +2986,13 @@ protected virtual ServiceResult SubscribeToEvents( monitoredNode.Add(monitoredItem); // This call recursively updates a reference count all nodes in the notifier - // hierarchy below the area. Sources with a reference count of 0 do not have + // hierarchy below the area. Sources with a reference count of 0 do not have // any active subscriptions so they do not need to report events. source.SetAreEventsMonitored(context, !unsubscribe, true); // signal update. OnSubscribeToEvents(context, monitoredNode, unsubscribe); - + // all done. return ServiceResult.Good; } @@ -3005,8 +3005,8 @@ protected virtual ServiceResult SubscribeToEvents( /// if set to true unsubscribing. protected virtual void OnSubscribeToEvents( ServerSystemContext context, - MonitoredNode monitoredNode, - bool unsubscribe) + MonitoredNode monitoredNode, + bool unsubscribe) { // defined by the sub-class } @@ -3087,26 +3087,26 @@ public virtual ServiceResult ConditionRefresh( /// This method only handles data change subscriptions. Event subscriptions are created by the SDK. /// public virtual void CreateMonitoredItems( - OperationContext context, - uint subscriptionId, - double publishingInterval, - TimestampsToReturn timestampsToReturn, - IList itemsToCreate, - IList errors, - IList filterResults, - IList monitoredItems, - bool createDurable, - ref long globalIdCounter) + OperationContext context, + uint subscriptionId, + double publishingInterval, + TimestampsToReturn timestampsToReturn, + IList itemsToCreate, + IList errors, + IList filterResults, + IList monitoredItems, + bool createDurable, + ref long globalIdCounter) { ServerSystemContext systemContext = m_systemContext.Copy(context); - IDictionary operationCache = new NodeIdDictionary(); + IDictionary operationCache = new NodeIdDictionary(); List nodesToValidate = new List(); List createdItems = new List(); lock (Lock) { for (int ii = 0; ii < itemsToCreate.Count; ii++) - { + { MonitoredItemCreateRequest itemToCreate = itemsToCreate[ii]; // skip items that have already been processed. @@ -3116,7 +3116,7 @@ public virtual void CreateMonitoredItems( } ReadValueId itemToMonitor = itemToCreate.ItemToMonitor; - + // check for valid handle. NodeHandle handle = GetManagerHandle(systemContext, itemToMonitor.NodeId, operationCache); @@ -3130,7 +3130,7 @@ public virtual void CreateMonitoredItems( // must validate node in a seperate operation. errors[ii] = StatusCodes.BadNodeIdUnknown; - + handle.Index = ii; nodesToValidate.Add(handle); } @@ -3140,13 +3140,13 @@ public virtual void CreateMonitoredItems( { return; } - } + } // validates the nodes (reads values from the underlying data source if required). for (int ii = 0; ii < nodesToValidate.Count; ii++) { NodeHandle handle = nodesToValidate[ii]; - + MonitoringFilterResult filterResult = null; IMonitoredItem monitoredItem = null; @@ -3159,7 +3159,7 @@ public virtual void CreateMonitoredItems( { continue; } - + MonitoredItemCreateRequest itemToCreate = itemsToCreate[handle.Index]; // create monitored item. @@ -3281,7 +3281,7 @@ protected virtual ServiceResult CreateMonitoredItem( } // validate the monitoring filter. - Range euRange = null; + Opc.Ua.Range euRange = null; MonitoringFilter filterToUse = null; ServiceResult error = ValidateMonitoringFilter( @@ -3385,13 +3385,13 @@ protected virtual void OnMonitoredItemCreated( /// protected virtual StatusCode ValidateMonitoringFilter( ServerSystemContext context, - NodeHandle handle, + NodeHandle handle, uint attributeId, double samplingInterval, uint queueSize, ExtensionObject filter, out MonitoringFilter filterToUse, - out Range range, + out Opc.Ua.Range range, out MonitoringFilterResult result) { range = null; @@ -3470,7 +3470,7 @@ protected virtual StatusCode ValidateMonitoringFilter( { return StatusCodes.BadFilterNotAllowed; } - + // nothing more to do for absolute filters. if (deadbandFilter.DeadbandType == (uint)DeadbandType.Absolute) { @@ -3487,9 +3487,9 @@ protected virtual StatusCode ValidateMonitoringFilter( { return StatusCodes.BadFilterNotAllowed; } - - range = property.Value as Range; - + + range = property.Value as Opc.Ua.Range; + if (range == null) { return StatusCodes.BadFilterNotAllowed; @@ -3505,7 +3505,7 @@ protected virtual StatusCode ValidateMonitoringFilter( } /// - /// Revises an aggregate filter (may require knowledge of the variable being used). + /// Revises an aggregate filter (may require knowledge of the variable being used). /// /// The context. /// The handle. @@ -3530,7 +3530,7 @@ protected virtual StatusCode ReviseAggregateFilter( filterToUse.ProcessingInterval = Server.AggregateManager.MinimumProcessingInterval; } - DateTime earliestStartTime = DateTime.UtcNow.AddMilliseconds(-(queueSize - 1)*filterToUse.ProcessingInterval); + DateTime earliestStartTime = DateTime.UtcNow.AddMilliseconds(-(queueSize - 1) * filterToUse.ProcessingInterval); if (earliestStartTime > filterToUse.StartTime) { @@ -3550,12 +3550,12 @@ protected virtual StatusCode ReviseAggregateFilter( /// Modifies the parameters for a set of monitored items. /// public virtual void ModifyMonitoredItems( - OperationContext context, - TimestampsToReturn timestampsToReturn, - IList monitoredItems, - IList itemsToModify, - IList errors, - IList filterResults) + OperationContext context, + TimestampsToReturn timestampsToReturn, + IList monitoredItems, + IList itemsToModify, + IList errors, + IList filterResults) { ServerSystemContext systemContext = m_systemContext.Copy(context); List modifiedItems = new List(); @@ -3563,7 +3563,7 @@ public virtual void ModifyMonitoredItems( lock (Lock) { for (int ii = 0; ii < monitoredItems.Count; ii++) - { + { MonitoredItemModifyRequest itemToModify = itemsToModify[ii]; // skip items that have already been processed. @@ -3632,7 +3632,7 @@ protected virtual ServiceResult ModifyMonitoredItem( out MonitoringFilterResult filterResult) { filterResult = null; - + // check for valid monitored item. MonitoredItem datachangeItem = monitoredItem as MonitoredItem; @@ -3640,7 +3640,7 @@ protected virtual ServiceResult ModifyMonitoredItem( MonitoringParameters parameters = itemToModify.RequestedParameters; double previousSamplingInterval = datachangeItem.SamplingInterval; - + // check if the variable needs to be sampled. double samplingInterval = itemToModify.RequestedParameters.SamplingInterval; @@ -3675,7 +3675,7 @@ protected virtual ServiceResult ModifyMonitoredItem( } // validate the monitoring filter. - Range euRange = null; + Opc.Ua.Range euRange = null; MonitoringFilter filterToUse = null; ServiceResult error = ValidateMonitoringFilter( @@ -3705,7 +3705,7 @@ protected virtual ServiceResult ModifyMonitoredItem( samplingInterval, queueSize, itemToModify.RequestedParameters.DiscardOldest); - + // report change. if (ServiceResult.IsGood(error)) { @@ -3734,9 +3734,9 @@ protected virtual void OnMonitoredItemModified( /// Deletes a set of monitored items. /// public virtual void DeleteMonitoredItems( - OperationContext context, - IList monitoredItems, - IList processedItems, + OperationContext context, + IList monitoredItems, + IList processedItems, IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); @@ -3814,7 +3814,7 @@ protected virtual ServiceResult DeleteMonitoredItem( MonitoredNodes.Remove(handle.NodeId); } } - + // remove the monitored item. m_monitoredItems.Remove(monitoredItem.Id); @@ -3913,11 +3913,11 @@ IList monitoredItems /// Flags indicating which items have been processed. /// Any errors. public virtual void SetMonitoringMode( - OperationContext context, - MonitoringMode monitoringMode, - IList monitoredItems, - IList processedItems, - IList errors) + OperationContext context, + MonitoringMode monitoringMode, + IList monitoredItems, + IList processedItems, + IList errors) { ServerSystemContext systemContext = m_systemContext.Copy(context); List changedItems = new List(); @@ -4002,7 +4002,7 @@ protected virtual ServiceResult SetMonitoringMode( previousMode, monitoringMode); } - + return ServiceResult.Good; } @@ -4039,7 +4039,7 @@ public virtual void SessionClosing(OperationContext context, NodeId sessionId, b /// /// Stores a reference count for entries in the component cache. /// - private class CacheEntry + private sealed class CacheEntry { public int RefCount; public NodeState Entry; @@ -4192,9 +4192,9 @@ public void RestoreMonitoredItems(IList itemsToRestore, IL private ServerSystemContext m_systemContext; private string[] m_namespaceUris; private ushort[] m_namespaceIndexes; - private Dictionary m_monitoredItems; - private Dictionary m_monitoredNodes; - private Dictionary m_componentCache; + private Dictionary m_monitoredItems; + private Dictionary m_monitoredNodes; + private Dictionary m_componentCache; private NodeIdDictionary m_predefinedNodes; private List m_rootNotifiers; private uint m_maxQueueSize; diff --git a/Workshop/Common/SelectLocaleDlg.cs b/Workshop/Common/SelectLocaleDlg.cs index a728ef6ea..93749902b 100644 --- a/Workshop/Common/SelectLocaleDlg.cs +++ b/Workshop/Common/SelectLocaleDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,8 @@ using System.Text; using Opc.Ua; using Opc.Ua.Client; +using System.Threading; +using System.Threading.Tasks; namespace Quickstarts { @@ -50,25 +52,25 @@ public SelectLocaleDlg() InitializeComponent(); } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; #endregion - + #region Public Interface /// /// Displays the available areas in a tree view. /// /// The session. /// - public string ShowDialog(Session session) + public async Task ShowDialogAsync(ISession session, CancellationToken ct = default) { m_session = session; LocaleCB.Items.Clear(); // get the locales from the server. - DataValue value = m_session.ReadValue(VariableIds.Server_ServerCapabilities_LocaleIdArray); + DataValue value = await m_session.ReadValueAsync(VariableIds.Server_ServerCapabilities_LocaleIdArray, ct); if (value != null) { @@ -98,7 +100,7 @@ public string ShowDialog(Session session) return LocaleCB.SelectedItem as string; } #endregion - + #region Private Methods #endregion diff --git a/Workshop/DataAccess/Client/DataAccess Client.csproj b/Workshop/DataAccess/Client/DataAccess Client.csproj index dd3cfff15..bef94b08e 100644 --- a/Workshop/DataAccess/Client/DataAccess Client.csproj +++ b/Workshop/DataAccess/Client/DataAccess Client.csproj @@ -48,6 +48,7 @@ false false + AllRules.ruleset pdbonly @@ -60,6 +61,7 @@ false false + AllRules.ruleset @@ -183,7 +185,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/DataAccess/Client/MainForm.Designer.cs b/Workshop/DataAccess/Client/MainForm.Designer.cs index eb155e7c3..497fe72b2 100644 --- a/Workshop/DataAccess/Client/MainForm.Designer.cs +++ b/Workshop/DataAccess/Client/MainForm.Designer.cs @@ -182,7 +182,7 @@ private void InitializeComponent() this.Server_SetLocaleMI.Name = "Server_SetLocaleMI"; this.Server_SetLocaleMI.Size = new System.Drawing.Size(148, 22); this.Server_SetLocaleMI.Text = "Select Locale..."; - this.Server_SetLocaleMI.Click += new System.EventHandler(this.Server_SetLocaleMI_Click); + this.Server_SetLocaleMI.Click += new System.EventHandler(this.Server_SetLocaleMI_ClickAsync); // // Server_SetUserMI // @@ -285,8 +285,8 @@ private void InitializeComponent() this.BrowseNodesTV.Name = "BrowseNodesTV"; this.BrowseNodesTV.Size = new System.Drawing.Size(391, 278); this.BrowseNodesTV.TabIndex = 0; - this.BrowseNodesTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.BrowseNodesTV_BeforeExpand); - this.BrowseNodesTV.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.BrowseNodesTV_AfterSelect); + this.BrowseNodesTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.BrowseNodesTV_BeforeExpandAsync); + this.BrowseNodesTV.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.BrowseNodesTV_AfterSelectAsync); this.BrowseNodesTV.MouseDown += new System.Windows.Forms.MouseEventHandler(this.BrowseNodesTV_MouseDown); // // BrowsingMenu @@ -304,21 +304,21 @@ private void InitializeComponent() this.Browse_MonitorMI.Name = "Browse_MonitorMI"; this.Browse_MonitorMI.Size = new System.Drawing.Size(148, 22); this.Browse_MonitorMI.Text = "Monitor"; - this.Browse_MonitorMI.Click += new System.EventHandler(this.Browse_MonitorMI_Click); + this.Browse_MonitorMI.Click += new System.EventHandler(this.Browse_MonitorMI_ClickAsync); // // Browse_WriteMI // this.Browse_WriteMI.Name = "Browse_WriteMI"; this.Browse_WriteMI.Size = new System.Drawing.Size(148, 22); this.Browse_WriteMI.Text = "Write..."; - this.Browse_WriteMI.Click += new System.EventHandler(this.Browse_WriteMI_Click); + this.Browse_WriteMI.Click += new System.EventHandler(this.Browse_WriteMI_ClickAsync); // // Browse_ReadHistoryMI // this.Browse_ReadHistoryMI.Name = "Browse_ReadHistoryMI"; this.Browse_ReadHistoryMI.Size = new System.Drawing.Size(148, 22); this.Browse_ReadHistoryMI.Text = "Read History..."; - this.Browse_ReadHistoryMI.Click += new System.EventHandler(this.Browse_ReadHistoryMI_Click); + this.Browse_ReadHistoryMI.Click += new System.EventHandler(this.Browse_ReadHistoryMI_ClickAsync); // // AttributesLV // @@ -427,14 +427,14 @@ private void InitializeComponent() this.Monitoring_DeleteMI.Name = "Monitoring_DeleteMI"; this.Monitoring_DeleteMI.Size = new System.Drawing.Size(155, 22); this.Monitoring_DeleteMI.Text = "Delete"; - this.Monitoring_DeleteMI.Click += new System.EventHandler(this.Monitoring_DeleteMI_Click); + this.Monitoring_DeleteMI.Click += new System.EventHandler(this.Monitoring_DeleteMI_ClickAsync); // // Monitoring_WriteMI // this.Monitoring_WriteMI.Name = "Monitoring_WriteMI"; this.Monitoring_WriteMI.Size = new System.Drawing.Size(155, 22); this.Monitoring_WriteMI.Text = "Write..."; - this.Monitoring_WriteMI.Click += new System.EventHandler(this.Monitoring_WriteMI_Click); + this.Monitoring_WriteMI.Click += new System.EventHandler(this.Monitoring_WriteMI_ClickAsync); // // Monitoring_MonitoringModeMI // @@ -451,21 +451,21 @@ private void InitializeComponent() this.Monitoring_MonitoringMode_DisabledMI.Name = "Monitoring_MonitoringMode_DisabledMI"; this.Monitoring_MonitoringMode_DisabledMI.Size = new System.Drawing.Size(121, 22); this.Monitoring_MonitoringMode_DisabledMI.Text = "Disabled"; - this.Monitoring_MonitoringMode_DisabledMI.Click += new System.EventHandler(this.Monitoring_MonitoringMode_Click); + this.Monitoring_MonitoringMode_DisabledMI.Click += new System.EventHandler(this.Monitoring_MonitoringMode_ClickAsync); // // Monitoring_MonitoringMode_SamplingMI // this.Monitoring_MonitoringMode_SamplingMI.Name = "Monitoring_MonitoringMode_SamplingMI"; this.Monitoring_MonitoringMode_SamplingMI.Size = new System.Drawing.Size(121, 22); this.Monitoring_MonitoringMode_SamplingMI.Text = "Sampling"; - this.Monitoring_MonitoringMode_SamplingMI.Click += new System.EventHandler(this.Monitoring_MonitoringMode_Click); + this.Monitoring_MonitoringMode_SamplingMI.Click += new System.EventHandler(this.Monitoring_MonitoringMode_ClickAsync); // // Monitoring_MonitoringMode_ReportingMI // this.Monitoring_MonitoringMode_ReportingMI.Name = "Monitoring_MonitoringMode_ReportingMI"; this.Monitoring_MonitoringMode_ReportingMI.Size = new System.Drawing.Size(121, 22); this.Monitoring_MonitoringMode_ReportingMI.Text = "Reporting"; - this.Monitoring_MonitoringMode_ReportingMI.Click += new System.EventHandler(this.Monitoring_MonitoringMode_Click); + this.Monitoring_MonitoringMode_ReportingMI.Click += new System.EventHandler(this.Monitoring_MonitoringMode_ClickAsync); // // Monitoring_SamplingIntervalMI // @@ -483,28 +483,28 @@ private void InitializeComponent() this.Monitoring_SamplingInterval_FastMI.Name = "Monitoring_SamplingInterval_FastMI"; this.Monitoring_SamplingInterval_FastMI.Size = new System.Drawing.Size(150, 22); this.Monitoring_SamplingInterval_FastMI.Text = "Fast as Possible"; - this.Monitoring_SamplingInterval_FastMI.Click += new System.EventHandler(this.Monitoring_SamplingInterval_Click); + this.Monitoring_SamplingInterval_FastMI.Click += new System.EventHandler(this.Monitoring_SamplingInterval_ClickAsync); // // Monitoring_SamplingInterval_1000MI // this.Monitoring_SamplingInterval_1000MI.Name = "Monitoring_SamplingInterval_1000MI"; this.Monitoring_SamplingInterval_1000MI.Size = new System.Drawing.Size(150, 22); this.Monitoring_SamplingInterval_1000MI.Text = "1000ms"; - this.Monitoring_SamplingInterval_1000MI.Click += new System.EventHandler(this.Monitoring_SamplingInterval_Click); + this.Monitoring_SamplingInterval_1000MI.Click += new System.EventHandler(this.Monitoring_SamplingInterval_ClickAsync); // // Monitoring_SamplingInterval_2500MI // this.Monitoring_SamplingInterval_2500MI.Name = "Monitoring_SamplingInterval_2500MI"; this.Monitoring_SamplingInterval_2500MI.Size = new System.Drawing.Size(150, 22); this.Monitoring_SamplingInterval_2500MI.Text = "2500ms"; - this.Monitoring_SamplingInterval_2500MI.Click += new System.EventHandler(this.Monitoring_SamplingInterval_Click); + this.Monitoring_SamplingInterval_2500MI.Click += new System.EventHandler(this.Monitoring_SamplingInterval_ClickAsync); // // Monitoring_SamplingInterval_5000MI // this.Monitoring_SamplingInterval_5000MI.Name = "Monitoring_SamplingInterval_5000MI"; this.Monitoring_SamplingInterval_5000MI.Size = new System.Drawing.Size(150, 22); this.Monitoring_SamplingInterval_5000MI.Text = "5000ms"; - this.Monitoring_SamplingInterval_5000MI.Click += new System.EventHandler(this.Monitoring_SamplingInterval_Click); + this.Monitoring_SamplingInterval_5000MI.Click += new System.EventHandler(this.Monitoring_SamplingInterval_ClickAsync); // // Monitoring_DeadbandMI // @@ -521,7 +521,7 @@ private void InitializeComponent() this.Monitoring_Deadband_NoneMI.Name = "Monitoring_Deadband_NoneMI"; this.Monitoring_Deadband_NoneMI.Size = new System.Drawing.Size(129, 22); this.Monitoring_Deadband_NoneMI.Text = "None"; - this.Monitoring_Deadband_NoneMI.Click += new System.EventHandler(this.Monitoring_Deadband_Click); + this.Monitoring_Deadband_NoneMI.Click += new System.EventHandler(this.Monitoring_Deadband_ClickAsync); // // Monitoring_Deadband_AbsoluteMI // @@ -538,21 +538,21 @@ private void InitializeComponent() this.Monitoring_Deadband_Absolute_5MI.Name = "Monitoring_Deadband_Absolute_5MI"; this.Monitoring_Deadband_Absolute_5MI.Size = new System.Drawing.Size(86, 22); this.Monitoring_Deadband_Absolute_5MI.Text = "5"; - this.Monitoring_Deadband_Absolute_5MI.Click += new System.EventHandler(this.Monitoring_Deadband_Click); + this.Monitoring_Deadband_Absolute_5MI.Click += new System.EventHandler(this.Monitoring_Deadband_ClickAsync); // // Monitoring_Deadband_Absolute_10MI // this.Monitoring_Deadband_Absolute_10MI.Name = "Monitoring_Deadband_Absolute_10MI"; this.Monitoring_Deadband_Absolute_10MI.Size = new System.Drawing.Size(86, 22); this.Monitoring_Deadband_Absolute_10MI.Text = "10"; - this.Monitoring_Deadband_Absolute_10MI.Click += new System.EventHandler(this.Monitoring_Deadband_Click); + this.Monitoring_Deadband_Absolute_10MI.Click += new System.EventHandler(this.Monitoring_Deadband_ClickAsync); // // Monitoring_Deadband_Absolute_25MI // this.Monitoring_Deadband_Absolute_25MI.Name = "Monitoring_Deadband_Absolute_25MI"; this.Monitoring_Deadband_Absolute_25MI.Size = new System.Drawing.Size(86, 22); this.Monitoring_Deadband_Absolute_25MI.Text = "25"; - this.Monitoring_Deadband_Absolute_25MI.Click += new System.EventHandler(this.Monitoring_Deadband_Click); + this.Monitoring_Deadband_Absolute_25MI.Click += new System.EventHandler(this.Monitoring_Deadband_ClickAsync); // // Monitoring_Deadband_PercentageMI // @@ -569,21 +569,21 @@ private void InitializeComponent() this.Monitoring_Deadband_Percentage_1MI.Name = "Monitoring_Deadband_Percentage_1MI"; this.Monitoring_Deadband_Percentage_1MI.Size = new System.Drawing.Size(97, 22); this.Monitoring_Deadband_Percentage_1MI.Text = "1%"; - this.Monitoring_Deadband_Percentage_1MI.Click += new System.EventHandler(this.Monitoring_Deadband_Click); + this.Monitoring_Deadband_Percentage_1MI.Click += new System.EventHandler(this.Monitoring_Deadband_ClickAsync); // // Monitoring_Deadband_Percentage_5MI // this.Monitoring_Deadband_Percentage_5MI.Name = "Monitoring_Deadband_Percentage_5MI"; this.Monitoring_Deadband_Percentage_5MI.Size = new System.Drawing.Size(97, 22); this.Monitoring_Deadband_Percentage_5MI.Text = "5%"; - this.Monitoring_Deadband_Percentage_5MI.Click += new System.EventHandler(this.Monitoring_Deadband_Click); + this.Monitoring_Deadband_Percentage_5MI.Click += new System.EventHandler(this.Monitoring_Deadband_ClickAsync); // // Monitoring_Deadband_Percentage_10MI // this.Monitoring_Deadband_Percentage_10MI.Name = "Monitoring_Deadband_Percentage_10MI"; this.Monitoring_Deadband_Percentage_10MI.Size = new System.Drawing.Size(97, 22); this.Monitoring_Deadband_Percentage_10MI.Text = "10%"; - this.Monitoring_Deadband_Percentage_10MI.Click += new System.EventHandler(this.Monitoring_Deadband_Click); + this.Monitoring_Deadband_Percentage_10MI.Click += new System.EventHandler(this.Monitoring_Deadband_ClickAsync); // // ConnectServerCTRL // @@ -602,7 +602,7 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); // diff --git a/Workshop/DataAccess/Client/MainForm.cs b/Workshop/DataAccess/Client/MainForm.cs index 98c1818c7..33db946f9 100644 --- a/Workshop/DataAccess/Client/MainForm.cs +++ b/Workshop/DataAccess/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Quickstarts.DataAccessClient { @@ -74,7 +76,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private bool m_connectedOnce; private Subscription m_subscription; private MonitoredItemNotificationEventHandler m_monitoredItem_Notification; @@ -91,7 +93,7 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect().ConfigureAwait(false); + await ConnectServerCTRL.ConnectAsync().ConfigureAwait(false); } catch (Exception exception) { @@ -135,7 +137,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -157,7 +159,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) } // populate the browse view. - PopulateBranch(ObjectIds.ObjectsFolder, BrowseNodesTV.Nodes); + await PopulateBranchAsync(ObjectIds.ObjectsFolder, BrowseNodesTV.Nodes); BrowseNodesTV.Enabled = true; MonitoredItemsLV.Enabled = true; @@ -224,7 +226,7 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) /// /// The NodeId of the Node to browse. /// The node collect to populate. - private void PopulateBranch(NodeId sourceId, TreeNodeCollection nodes) + private async Task PopulateBranchAsync(NodeId sourceId, TreeNodeCollection nodes, CancellationToken ct = default) { try { @@ -239,7 +241,7 @@ private void PopulateBranch(NodeId sourceId, TreeNodeCollection nodes) nodeToBrowse1.IncludeSubtypes = true; nodeToBrowse1.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All; - + // find all nodes organized by the node. BrowseDescription nodeToBrowse2 = new BrowseDescription(); @@ -255,8 +257,8 @@ private void PopulateBranch(NodeId sourceId, TreeNodeCollection nodes) nodesToBrowse.Add(nodeToBrowse2); // fetch references from the server. - ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodesToBrowse, false); - + ReferenceDescriptionCollection references = await FormUtils.BrowseAsync(m_session, nodesToBrowse, false, ct); + // process results. for (int ii = 0; ii < references.Count; ii++) { @@ -270,7 +272,7 @@ private void PopulateBranch(NodeId sourceId, TreeNodeCollection nodes) } // update the attributes display. - DisplayAttributes(sourceId); + await DisplayAttributesAsync(sourceId, ct); } catch (Exception exception) { @@ -282,7 +284,7 @@ private void PopulateBranch(NodeId sourceId, TreeNodeCollection nodes) /// Displays the attributes and properties in the attributes view. /// /// The NodeId of the Node to browse. - private void DisplayAttributes(NodeId sourceId) + private async Task DisplayAttributesAsync(NodeId sourceId, CancellationToken ct = default) { try { @@ -315,7 +317,7 @@ private void DisplayAttributes(NodeId sourceId) nodesToBrowse.Add(nodeToBrowse1); // fetch property references from the server. - ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodesToBrowse, false); + ReferenceDescriptionCollection references = await FormUtils.BrowseAsync(m_session, nodesToBrowse, false, ct); if (references == null) { @@ -337,16 +339,15 @@ private void DisplayAttributes(NodeId sourceId) } // read all values. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -403,7 +404,7 @@ private void DisplayAttributes(NodeId sourceId) } // get the name of the property. - name = Utils.Format("{0}", references[ii-startOfProperties]); + name = Utils.Format("{0}", references[ii - startOfProperties]); // display any unexpected error. if (StatusCode.IsBad(results[ii].StatusCode)) @@ -483,7 +484,7 @@ private void Help_ContentsMI_Click(object sender, EventArgs e) { try { - System.Diagnostics.Process.Start( Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\daclientoverview.htm"); + System.Diagnostics.Process.Start(Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\daclientoverview.htm"); } catch (Exception ex) { @@ -494,7 +495,7 @@ private void Help_ContentsMI_Click(object sender, EventArgs e) /// /// Fetches the children for a node the first time the node is expanded in the tree view. /// - private void BrowseNodesTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) + private async void BrowseNodesTV_BeforeExpandAsync(object sender, TreeViewCancelEventArgs e) { try { @@ -514,7 +515,7 @@ private void BrowseNodesTV_BeforeExpand(object sender, TreeViewCancelEventArgs e } // populate children. - PopulateBranch((NodeId)reference.NodeId, e.Node.Nodes); + await PopulateBranchAsync((NodeId)reference.NodeId, e.Node.Nodes); } catch (Exception exception) { @@ -525,7 +526,7 @@ private void BrowseNodesTV_BeforeExpand(object sender, TreeViewCancelEventArgs e /// /// Updates the display after a node is selected. /// - private void BrowseNodesTV_AfterSelect(object sender, TreeViewEventArgs e) + private async void BrowseNodesTV_AfterSelectAsync(object sender, TreeViewEventArgs e) { try { @@ -538,7 +539,7 @@ private void BrowseNodesTV_AfterSelect(object sender, TreeViewEventArgs e) } // populate children. - PopulateBranch((NodeId)reference.NodeId, e.Node.Nodes); + await PopulateBranchAsync((NodeId)reference.NodeId, e.Node.Nodes); } catch (Exception exception) { @@ -560,23 +561,23 @@ private void BrowseNodesTV_MouseDown(object sender, MouseEventArgs e) ClientUtils.HandleException(this.Text, exception); } } - + /// /// Handles the Click event of the Browse_MonitorMI control. /// /// The source of the event. /// The instance containing the event data. - private void Browse_MonitorMI_Click(object sender, EventArgs e) + private async void Browse_MonitorMI_ClickAsync(object sender, EventArgs e) { try - { + { // check if operation is currently allowed. if (m_session == null || BrowseNodesTV.SelectedNode == null) { return; } - // can only subscribe to local variables. + // can only subscribe to local variables. ReferenceDescription reference = (ReferenceDescription)BrowseNodesTV.SelectedNode.Tag; if (reference.NodeId.IsAbsolute || reference.NodeClass != NodeClass.Variable) @@ -584,12 +585,12 @@ private void Browse_MonitorMI_Click(object sender, EventArgs e) return; } - ListViewItem item = CreateMonitoredItem((NodeId)reference.NodeId, Utils.Format("{0}", reference)); + ListViewItem item = await CreateMonitoredItemAsync((NodeId)reference.NodeId, Utils.Format("{0}", reference)); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(); MonitoredItem monitoredItem = (MonitoredItem)item.Tag; - + if (ServiceResult.IsBad(monitoredItem.Status.Error)) { item.SubItems[8].Text = monitoredItem.Status.Error.StatusCode.ToString(); @@ -599,7 +600,7 @@ private void Browse_MonitorMI_Click(object sender, EventArgs e) item.SubItems[1].Text = monitoredItem.MonitoringMode.ToString(); item.SubItems[2].Text = monitoredItem.SamplingInterval.ToString(); item.SubItems[3].Text = DeadbandFilterToText(monitoredItem.Filter); - + MonitoredItemsLV.Columns[0].Width = -2; MonitoredItemsLV.Columns[1].Width = -2; MonitoredItemsLV.Columns[8].Width = -2; @@ -613,7 +614,7 @@ private void Browse_MonitorMI_Click(object sender, EventArgs e) /// /// Creates the monitored item. /// - private ListViewItem CreateMonitoredItem(NodeId nodeId, string displayName) + private async Task CreateMonitoredItemAsync(NodeId nodeId, string displayName, CancellationToken ct = default) { if (m_subscription == null) { @@ -628,7 +629,7 @@ private ListViewItem CreateMonitoredItem(NodeId nodeId, string displayName) m_session.AddSubscription(m_subscription); - m_subscription.Create(); + await m_subscription.CreateAsync(ct); } // add the new monitored item. @@ -666,14 +667,14 @@ private ListViewItem CreateMonitoredItem(NodeId nodeId, string displayName) { item.SubItems[8].Text = monitoredItem.Status.Error.StatusCode.ToString(); } - + return item; } /// /// Prompts the use to write the value of a varible. /// - private void Browse_WriteMI_Click(object sender, EventArgs e) + private async void Browse_WriteMI_ClickAsync(object sender, EventArgs e) { try { @@ -683,7 +684,7 @@ private void Browse_WriteMI_Click(object sender, EventArgs e) return; } - // can only subscribe to local variables. + // can only subscribe to local variables. ReferenceDescription reference = (ReferenceDescription)BrowseNodesTV.SelectedNode.Tag; if (reference.NodeId.IsAbsolute || reference.NodeClass != NodeClass.Variable) @@ -691,20 +692,20 @@ private void Browse_WriteMI_Click(object sender, EventArgs e) return; } - new WriteValueDlg().ShowDialog(m_session, (NodeId)reference.NodeId, Attributes.Value); + await new WriteValueDlg().ShowDialogAsync(m_session, (NodeId)reference.NodeId, Attributes.Value); } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } } - + /// /// Handles the Click event of the Browse_ReadHistoryMI control. /// /// The source of the event. /// The instance containing the event data. - private void Browse_ReadHistoryMI_Click(object sender, EventArgs e) + private async void Browse_ReadHistoryMI_ClickAsync(object sender, EventArgs e) { try { @@ -714,7 +715,7 @@ private void Browse_ReadHistoryMI_Click(object sender, EventArgs e) return; } - // can only subscribe to local variables. + // can only subscribe to local variables. ReferenceDescription reference = (ReferenceDescription)BrowseNodesTV.SelectedNode.Tag; if (reference.NodeId.IsAbsolute || reference.NodeClass != NodeClass.Variable) @@ -722,7 +723,7 @@ private void Browse_ReadHistoryMI_Click(object sender, EventArgs e) return; } - new ReadHistoryDlg().ShowDialog(m_session, (NodeId)reference.NodeId); + await new ReadHistoryDlg().ShowDialogAsync(m_session, (NodeId)reference.NodeId); } catch (Exception exception) { @@ -731,7 +732,7 @@ private void Browse_ReadHistoryMI_Click(object sender, EventArgs e) } /// - /// Updates the display with a new value for a monitored variable. + /// Updates the display with a new value for a monitored variable. /// private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { @@ -770,7 +771,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt /// /// Changes the monitoring mode for the currently selected monitored items. /// - private void Monitoring_MonitoringMode_Click(object sender, EventArgs e) + private async void Monitoring_MonitoringMode_ClickAsync(object sender, EventArgs e) { try { @@ -807,7 +808,7 @@ private void Monitoring_MonitoringMode_Click(object sender, EventArgs e) } // apply the changes to the server. - m_subscription.SetMonitoringMode(monitoringMode, itemsToChange); + await m_subscription.SetMonitoringModeAsync(monitoringMode, itemsToChange); // update the display. for (int ii = 0; ii < itemsToChange.Count; ii++) @@ -836,7 +837,7 @@ private void Monitoring_MonitoringMode_Click(object sender, EventArgs e) /// /// Changes the sampling interval for the currently selected monitored items. /// - private void Monitoring_SamplingInterval_Click(object sender, EventArgs e) + private async void Monitoring_SamplingInterval_ClickAsync(object sender, EventArgs e) { try { @@ -877,7 +878,7 @@ private void Monitoring_SamplingInterval_Click(object sender, EventArgs e) } // apply the changes to the server. - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(); // update the display. for (int ii = 0; ii < itemsToChange.Count; ii++) @@ -906,7 +907,7 @@ private void Monitoring_SamplingInterval_Click(object sender, EventArgs e) /// /// Changes the deadband for the currently selected monitored items. /// - private void Monitoring_Deadband_Click(object sender, EventArgs e) + private async void Monitoring_Deadband_ClickAsync(object sender, EventArgs e) { try { @@ -970,7 +971,7 @@ private void Monitoring_Deadband_Click(object sender, EventArgs e) } // apply the changes to the server. - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(); // update the display. for (int ii = 0; ii < itemsToChange.Count; ii++) @@ -1002,7 +1003,7 @@ private void Monitoring_Deadband_Click(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void Monitoring_DeleteMI_Click(object sender, EventArgs e) + private async void Monitoring_DeleteMI_ClickAsync(object sender, EventArgs e) { try { @@ -1034,7 +1035,7 @@ private void Monitoring_DeleteMI_Click(object sender, EventArgs e) // update the server. if (m_subscription != null) { - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(); // check the status. for (int ii = 0; ii < itemsToDelete.Count; ii++) @@ -1090,7 +1091,7 @@ private void BrowsingMenu_Opening(object sender, System.ComponentModel.CancelEve } } - private void Monitoring_WriteMI_Click(object sender, EventArgs e) + private async void Monitoring_WriteMI_ClickAsync(object sender, EventArgs e) { try { @@ -1104,7 +1105,7 @@ private void Monitoring_WriteMI_Click(object sender, EventArgs e) if (monitoredItem != null) { - new WriteValueDlg().ShowDialog(m_session, (NodeId)monitoredItem.ResolvedNodeId, Attributes.Value); + await new WriteValueDlg().ShowDialogAsync(m_session, (NodeId)monitoredItem.ResolvedNodeId, Attributes.Value); } } catch (Exception exception) @@ -1144,7 +1145,7 @@ private void File_SaveMI_Click(object sender, EventArgs e) /// /// Sets the locale to use. /// - private void Server_SetLocaleMI_Click(object sender, EventArgs e) + private async void Server_SetLocaleMI_ClickAsync(object sender, EventArgs e) { try @@ -1154,7 +1155,7 @@ private void Server_SetLocaleMI_Click(object sender, EventArgs e) return; } - string locale = new SelectLocaleDlg().ShowDialog(m_session); + string locale = await new SelectLocaleDlg().ShowDialogAsync(m_session); if (locale == null) { diff --git a/Workshop/DataAccess/Client/Program.cs b/Workshop/DataAccess/Client/Program.cs index 37a24caf3..9cf739b86 100644 --- a/Workshop/DataAccess/Client/Program.cs +++ b/Workshop/DataAccess/Client/Program.cs @@ -50,7 +50,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "DataAccessClient"; try @@ -62,10 +62,10 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/DataAccess/Client/ReadHistoryDlg.Designer.cs b/Workshop/DataAccess/Client/ReadHistoryDlg.Designer.cs index 2ece8ed07..1a0ad9912 100644 --- a/Workshop/DataAccess/Client/ReadHistoryDlg.Designer.cs +++ b/Workshop/DataAccess/Client/ReadHistoryDlg.Designer.cs @@ -173,7 +173,7 @@ private void InitializeComponent() this.StopBTN.TabIndex = 19; this.StopBTN.Text = "Stop"; this.StopBTN.UseVisualStyleBackColor = true; - this.StopBTN.Click += new System.EventHandler(this.StopBTN_Click); + this.StopBTN.Click += new System.EventHandler(this.StopBTN_ClickAsync); // // NextBTN // @@ -357,7 +357,7 @@ private void InitializeComponent() this.ReadTypeCB.Name = "ReadTypeCB"; this.ReadTypeCB.Size = new System.Drawing.Size(138, 21); this.ReadTypeCB.TabIndex = 1; - this.ReadTypeCB.SelectedIndexChanged += new System.EventHandler(this.ReadTypeCB_SelectedIndexChanged); + this.ReadTypeCB.SelectedIndexChanged += new System.EventHandler(this.ReadTypeCB_SelectedIndexChangedAsync); // // ReadTypeLB // diff --git a/Workshop/DataAccess/Client/ReadHistoryDlg.cs b/Workshop/DataAccess/Client/ReadHistoryDlg.cs index 8d26a3e72..b377b9e09 100644 --- a/Workshop/DataAccess/Client/ReadHistoryDlg.cs +++ b/Workshop/DataAccess/Client/ReadHistoryDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,12 +36,12 @@ using System.ServiceModel; using System.Reflection; using System.Security.Cryptography.X509Certificates; -using System.ServiceModel.Security; -using System.ServiceModel.Channels; using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Quickstarts.DataAccessClient { @@ -79,7 +79,7 @@ private enum ReadType Processed } - private Session m_session; + private ISession m_session; private NodeId m_nodeId; private HistoryReadResult m_result; private int m_index; @@ -87,13 +87,13 @@ private enum ReadType /// /// Displays the dialog. /// - public bool ShowDialog(Session session, NodeId nodeId) + public async Task ShowDialogAsync(ISession session, NodeId nodeId, CancellationToken ct = default) { m_session = session; m_nodeId = nodeId; // update the title. - string displayText = session.NodeCache.GetDisplayText(nodeId); + string displayText = await session.NodeCache.GetDisplayTextAsync(nodeId, ct); if (!String.IsNullOrEmpty(displayText)) { @@ -105,7 +105,7 @@ public bool ShowDialog(Session session, NodeId nodeId) try { - startTime = ReadFirstDate().ToLocalTime(); + startTime = (await ReadFirstDateAsync(ct)).ToLocalTime(); } catch (Exception) { @@ -127,12 +127,7 @@ public bool ShowDialog(Session session, NodeId nodeId) NextBTN.Visible = false; StopBTN.Enabled = false; - if (ShowDialog() != DialogResult.OK) - { - return false; - } - - return true; + return ShowDialog() == DialogResult.OK; } private void ShowResults() @@ -180,7 +175,7 @@ private void ShowResults() } } - private void ReleaseContinuationPoints() + private async Task ReleaseContinuationPointsAsync(CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); @@ -195,17 +190,16 @@ private void ReleaseContinuationPoints() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -215,7 +209,7 @@ private void ReleaseContinuationPoints() ShowResults(); } - private DateTime ReadFirstDate() + private async Task ReadFirstDateAsync(CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); @@ -230,17 +224,16 @@ private DateTime ReadFirstDate() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -263,14 +256,16 @@ private DateTime ReadFirstDate() { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; - m_session.HistoryRead( + response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -279,7 +274,7 @@ private DateTime ReadFirstDate() return startTime; } - private void ReadRaw(bool isReadModified) + private async Task ReadRawAsync(bool isReadModified, CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = DateTime.MinValue; @@ -314,17 +309,16 @@ private void ReadRaw(bool isReadModified) HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -339,11 +333,12 @@ private void ReadRaw(bool isReadModified) ShowResults(); } - private void ReadAtTime() + private Task ReadAtTimeAsync(CancellationToken ct = default) { + return Task.CompletedTask; } - private void ReadProcessed() + private async Task ReadProcessedAsync(CancellationToken ct = default) { ReadProcessedDetails details = new ReadProcessedDetails(); details.StartTime = StartTimeDP.Value.ToUniversalTime(); @@ -376,17 +371,16 @@ private void ReadProcessed() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -401,34 +395,31 @@ private void ReadProcessed() ShowResults(); } - private void Read() + private Task ReadAsync(CancellationToken ct = default) { switch ((ReadType)ReadTypeCB.SelectedItem) { case ReadType.Raw: { - ReadRaw(false); - break; + return ReadRawAsync(false, ct); } case ReadType.Modified: { - ReadRaw(true); - break; + return ReadRawAsync(true, ct); } case ReadType.AtTime: { - ReadAtTime(); - break; + return ReadAtTimeAsync(ct); } case ReadType.Processed: { - ReadProcessed(); - break; + return ReadProcessedAsync(ct); } } + return Task.CompletedTask; } private void GoBTN_Click(object sender, EventArgs e) @@ -439,7 +430,7 @@ private void GoBTN_Click(object sender, EventArgs e) ResultsLV.Items.Clear(); m_result = null; - Read(); + ReadAsync(); } catch (Exception exception) { @@ -451,7 +442,7 @@ private void NextBTN_Click(object sender, EventArgs e) { try { - Read(); + ReadAsync(); } catch (Exception exception) { @@ -459,11 +450,11 @@ private void NextBTN_Click(object sender, EventArgs e) } } - private void StopBTN_Click(object sender, EventArgs e) + private async void StopBTN_ClickAsync(object sender, EventArgs e) { try { - ReleaseContinuationPoints(); + await ReleaseContinuationPointsAsync(); } catch (Exception exception) { @@ -471,13 +462,13 @@ private void StopBTN_Click(object sender, EventArgs e) } } - private void ReadTypeCB_SelectedIndexChanged(object sender, EventArgs e) + private async void ReadTypeCB_SelectedIndexChangedAsync(object sender, EventArgs e) { try { - ReleaseContinuationPoints(); + await ReleaseContinuationPointsAsync(); } - catch (Exception) + catch { // ignore is ok. } diff --git a/Workshop/DataAccess/Client/WriteValueDlg.Designer.cs b/Workshop/DataAccess/Client/WriteValueDlg.Designer.cs index dc5eb4102..186b23d08 100644 --- a/Workshop/DataAccess/Client/WriteValueDlg.Designer.cs +++ b/Workshop/DataAccess/Client/WriteValueDlg.Designer.cs @@ -83,7 +83,7 @@ private void InitializeComponent() this.OkBTN.TabIndex = 4; this.OkBTN.Text = "OK"; this.OkBTN.UseVisualStyleBackColor = true; - this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click); + this.OkBTN.Click += new System.EventHandler(this.OkBTN_ClickAsync); // // ValueLB // diff --git a/Workshop/DataAccess/Client/WriteValueDlg.cs b/Workshop/DataAccess/Client/WriteValueDlg.cs index 3ea4e81ee..cf0f3a125 100644 --- a/Workshop/DataAccess/Client/WriteValueDlg.cs +++ b/Workshop/DataAccess/Client/WriteValueDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,8 @@ using System.ComponentModel; using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -53,14 +55,14 @@ public WriteValueDlg() InitializeComponent(); } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; private NodeId m_nodeId; private uint m_attributeId; private DataValue m_value; #endregion - + #region Public Interface /// /// Prompts the user to enter a value to write. @@ -68,11 +70,12 @@ public WriteValueDlg() /// The session to use. /// The identifier for the node to write to. /// The attribute being written. + /// The token to cancel the request /// True if successful. False if the operation was cancelled. - public bool ShowDialog(Session session, NodeId nodeId, uint attributeId) + public async Task ShowDialogAsync(ISession session, NodeId nodeId, uint attributeId, CancellationToken ct = default) { m_session = session; - m_nodeId = nodeId; + m_nodeId = nodeId; m_attributeId = attributeId; ReadValueId nodeToRead = new ReadValueId(); @@ -81,25 +84,24 @@ public bool ShowDialog(Session session, NodeId nodeId, uint attributeId) ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); nodesToRead.Add(nodeToRead); - - // read current value. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.Read( + // read current value. + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); m_value = results[0]; ValueTB.Text = Utils.Format("{0}", m_value.WrappedValue); - + // display the dialog. if (ShowDialog() != DialogResult.OK) { @@ -109,7 +111,7 @@ public bool ShowDialog(Session session, NodeId nodeId, uint attributeId) return true; } #endregion - + #region Private Methods /// /// Changes the value in the text box to the data type required for the write operation. @@ -117,8 +119,8 @@ public bool ShowDialog(Session session, NodeId nodeId, uint attributeId) /// A value with the correct type. private object ChangeType() { - object value = (m_value != null)?m_value.Value:null; - + object value = (m_value != null) ? m_value.Value : null; + switch (m_value.WrappedValue.TypeInfo.BuiltInType) { case BuiltInType.Boolean: @@ -197,15 +199,15 @@ private object ChangeType() return value; } #endregion - + #region Event Handlers /// /// Parses the value and writes it to server. Closes the dialog if successful. /// - private void OkBTN_Click(object sender, EventArgs e) + private async void OkBTN_ClickAsync(object sender, EventArgs e) { try - { + { WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = m_nodeId; @@ -214,23 +216,22 @@ private void OkBTN_Click(object sender, EventArgs e) valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; - + WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. - StatusCodeCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Write( + WriteResponse response = await m_session.WriteAsync( null, valuesToWrite, - out results, - out diagnosticInfos); + default); + + StatusCodeCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); - + if (StatusCode.IsBad(results[0])) { throw new ServiceResultException(results[0]); diff --git a/Workshop/DataAccess/Server/DataAccess Server.csproj b/Workshop/DataAccess/Server/DataAccess Server.csproj index 884f90cb9..3c3e68499 100644 --- a/Workshop/DataAccess/Server/DataAccess Server.csproj +++ b/Workshop/DataAccess/Server/DataAccess Server.csproj @@ -48,6 +48,7 @@ false false + AllRules.ruleset pdbonly @@ -60,6 +61,7 @@ false false + AllRules.ruleset @@ -166,7 +168,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/DataAccess/Server/DataAccessNodeManager.cs b/Workshop/DataAccess/Server/DataAccessNodeManager.cs index 6975bd42c..b2b2d61a7 100644 --- a/Workshop/DataAccess/Server/DataAccessNodeManager.cs +++ b/Workshop/DataAccess/Server/DataAccessNodeManager.cs @@ -71,13 +71,13 @@ public DataAccessServerNodeManager(IServerInternal server, ApplicationConfigurat m_blocks = new Dictionary(); } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { m_system.Dispose(); @@ -214,7 +214,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node return handle; } - + return null; } } @@ -399,7 +399,7 @@ protected override void OnMonitoredItemDeleted(ServerSystemContext context, Node #region Private Fields private UnderlyingSystem m_system; private DataAccessServerConfiguration m_configuration; - private Dictionary m_blocks; + private Dictionary m_blocks; #endregion } } diff --git a/Workshop/DataAccess/Server/DataAccessServer.cs b/Workshop/DataAccess/Server/DataAccessServer.cs index e3cc0d2c6..12115c8f6 100644 Binary files a/Workshop/DataAccess/Server/DataAccessServer.cs and b/Workshop/DataAccess/Server/DataAccessServer.cs differ diff --git a/Workshop/DataAccess/Server/Model/BlockState.cs b/Workshop/DataAccess/Server/Model/BlockState.cs index 2309af2bc..13730fde1 100644 --- a/Workshop/DataAccess/Server/Model/BlockState.cs +++ b/Workshop/DataAccess/Server/Model/BlockState.cs @@ -37,7 +37,7 @@ using Opc.Ua.Server; namespace Quickstarts.DataAccessServer -{ +{ /// /// A object which maps a block to a UA object. /// @@ -51,8 +51,8 @@ public partial class BlockState : BaseObjectState /// The node id. /// The block. public BlockState( - DataAccessServerNodeManager nodeManager, - NodeId nodeId, + DataAccessServerNodeManager nodeManager, + NodeId nodeId, UnderlyingSystemBlock block) : base(null) { m_blockId = block.Id; @@ -152,10 +152,10 @@ public ServiceResult OnWriteTagValue( UnderlyingSystemBlock block = system.FindBlock(m_blockId); if (block == null) - { + { return StatusCodes.BadNodeIdUnknown; } - + uint error = block.WriteTagValue(node.SymbolicName, value); if (error != 0) @@ -244,7 +244,7 @@ private BaseVariableState CreateVariable(ISystemContext context, UnderlyingSyste if (tag.EuRange.Length >= 4) { - node.InstrumentRange = new PropertyState(node); + node.InstrumentRange = new PropertyState(node); } variable = node; @@ -293,7 +293,7 @@ private BaseVariableState CreateVariable(ISystemContext context, UnderlyingSyste // update the variable values. UpdateVariable(context, tag, variable); - + return variable; } @@ -311,11 +311,11 @@ private void UpdateVariable(ISystemContext context, UnderlyingSystemTag tag, Bas switch (tag.DataType) { - case UnderlyingSystemDataType.Integer1: { variable.DataType = DataTypes.SByte; break; } - case UnderlyingSystemDataType.Integer2: { variable.DataType = DataTypes.Int16; break; } - case UnderlyingSystemDataType.Integer4: { variable.DataType = DataTypes.Int32; break; } - case UnderlyingSystemDataType.Real4: { variable.DataType = DataTypes.Float; break; } - case UnderlyingSystemDataType.String: { variable.DataType = DataTypes.String; break; } + case UnderlyingSystemDataType.Integer1: { variable.DataType = DataTypes.SByte; break; } + case UnderlyingSystemDataType.Integer2: { variable.DataType = DataTypes.Int16; break; } + case UnderlyingSystemDataType.Integer4: { variable.DataType = DataTypes.Int32; break; } + case UnderlyingSystemDataType.Real4: { variable.DataType = DataTypes.Float; break; } + case UnderlyingSystemDataType.String: { variable.DataType = DataTypes.String; break; } } variable.ValueRank = ValueRanks.Scalar; @@ -334,7 +334,7 @@ private void UpdateVariable(ISystemContext context, UnderlyingSystemTag tag, Bas variable.MinimumSamplingInterval = MinimumSamplingIntervals.Continuous; variable.Historizing = false; - + switch (tag.TagType) { case UnderlyingSystemTagType.Analog: @@ -345,14 +345,14 @@ private void UpdateVariable(ISystemContext context, UnderlyingSystemTag tag, Bas { if (tag.EuRange.Length >= 2 && node.EURange != null) { - Range range = new Range(tag.EuRange[0], tag.EuRange[1]); + Opc.Ua.Range range = new Opc.Ua.Range(tag.EuRange[0], tag.EuRange[1]); node.EURange.Value = range; node.EURange.Timestamp = tag.Block.Timestamp; } if (tag.EuRange.Length >= 4 && node.InstrumentRange != null) { - Range range = new Range(tag.EuRange[2], tag.EuRange[3]); + Opc.Ua.Range range = new Opc.Ua.Range(tag.EuRange[2], tag.EuRange[3]); node.InstrumentRange.Value = range; node.InstrumentRange.Timestamp = tag.Block.Timestamp; } diff --git a/Workshop/DataAccess/Server/Model/ModelUtils.cs b/Workshop/DataAccess/Server/Model/ModelUtils.cs index f6fe9589a..5719cff64 100644 --- a/Workshop/DataAccess/Server/Model/ModelUtils.cs +++ b/Workshop/DataAccess/Server/Model/ModelUtils.cs @@ -107,7 +107,7 @@ public static NodeId ConstructIdForComponent(NodeState component, ushort namespa // parent must have a string identifier. string parentId = instance.Parent.NodeId.Identifier as string; - + if (parentId == null) { return null; @@ -115,7 +115,7 @@ public static NodeId ConstructIdForComponent(NodeState component, ushort namespa StringBuilder buffer = new StringBuilder(); buffer.Append(parentId); - + // check if the parent is another component. int index = parentId.IndexOf('?'); diff --git a/Workshop/DataAccess/Server/Model/SegmentBrowser.cs b/Workshop/DataAccess/Server/Model/SegmentBrowser.cs index 10068a9c5..d670d4443 100644 --- a/Workshop/DataAccess/Server/Model/SegmentBrowser.cs +++ b/Workshop/DataAccess/Server/Model/SegmentBrowser.cs @@ -81,7 +81,7 @@ public SegmentBrowser( m_stage = Stage.Begin; } #endregion - + #region Overridden Methods /// /// Returns the next reference. @@ -116,7 +116,7 @@ public override IReference Next() { return null; } - + // enumerate segments. if (m_stage == Stage.Segments) { @@ -134,7 +134,7 @@ public override IReference Next() m_stage = Stage.Blocks; m_position = 0; } - + // enumerate blocks. if (m_stage == Stage.Blocks) { diff --git a/Workshop/DataAccess/Server/Model/SegmentState.cs b/Workshop/DataAccess/Server/Model/SegmentState.cs index 5410ed0ec..92623e0fb 100644 --- a/Workshop/DataAccess/Server/Model/SegmentState.cs +++ b/Workshop/DataAccess/Server/Model/SegmentState.cs @@ -37,7 +37,7 @@ using Opc.Ua.Server; namespace Quickstarts.DataAccessServer -{ +{ /// /// A object which maps a segment to a UA object. /// @@ -89,11 +89,11 @@ public string SegmentPath /// If true the browser should not making blocking calls to external systems. /// The browse object (must be disposed). public override INodeBrowser CreateBrowser( - ISystemContext context, - ViewDescription view, - NodeId referenceType, - bool includeSubtypes, - BrowseDirection browseDirection, + ISystemContext context, + ViewDescription view, + NodeId referenceType, + bool includeSubtypes, + BrowseDirection browseDirection, QualifiedName browseName, IEnumerable additionalReferences, bool internalOnly) diff --git a/Workshop/DataAccess/Server/Program.cs b/Workshop/DataAccess/Server/Program.cs index c2da48a54..0a69f2713 100644 --- a/Workshop/DataAccess/Server/Program.cs +++ b/Workshop/DataAccess/Server/Program.cs @@ -52,7 +52,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "DataAccessServer"; try @@ -71,13 +71,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // start the server. - application.Start(new DataAccessServer()).Wait(); + application.StartAsync(new DataAccessServer()).Wait(); // run the application interactively. Application.Run(new ServerForm(application)); diff --git a/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystem.cs b/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystem.cs index d3e2397c2..4c057caf3 100644 --- a/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystem.cs +++ b/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystem.cs @@ -48,21 +48,21 @@ public UnderlyingSystem() m_blocks = new Dictionary(); } #endregion - + #region IDisposable Members /// /// The finializer implementation. /// - ~UnderlyingSystem() + ~UnderlyingSystem() { Dispose(false); } - + /// /// Frees any unmanaged reblocks. /// public void Dispose() - { + { Dispose(true); GC.SuppressFinalize(this); } @@ -71,7 +71,7 @@ public void Dispose() /// An overrideable version of the Dispose. /// protected virtual void Dispose(bool disposing) - { + { if (disposing) { if (m_simulationTimer != null) @@ -97,27 +97,27 @@ protected virtual void Dispose(bool disposing) /// private string[] s_BlockPathDatabase = new string[] { - "Factory/East/Boiler1/Pipe1001", - "Factory/East/Boiler1/Drum1002", - "Factory/East/Boiler1/Pipe1002", + "Factory/East/Boiler1/Pipe1001", + "Factory/East/Boiler1/Drum1002", + "Factory/East/Boiler1/Pipe1002", "Factory/East/Boiler1/FC1001", "Factory/East/Boiler1/LC1001", "Factory/East/Boiler1/CC1001", - "Factory/West/Boiler2/Pipe2001", - "Factory/West/Boiler2/Drum2002", - "Factory/West/Boiler2/Pipe2002", + "Factory/West/Boiler2/Pipe2001", + "Factory/West/Boiler2/Drum2002", + "Factory/West/Boiler2/Pipe2002", "Factory/West/Boiler2/FC2001", "Factory/West/Boiler2/LC2001", "Factory/West/Boiler2/CC2001", - "Assets/Sensors/Flow/Pipe1001", - "Assets/Sensors/Level/Drum1002", - "Assets/Sensors/Flow/Pipe1002", + "Assets/Sensors/Flow/Pipe1001", + "Assets/Sensors/Level/Drum1002", + "Assets/Sensors/Flow/Pipe1002", "Assets/Controllers/Flow/FC1001", "Assets/Controllers/Level/LC1001", "Assets/Controllers/Custom/CC1001", - "Assets/Sensors/Flow/Pipe2001", - "Assets/Sensors/Level/Drum2002", - "Assets/Sensors/Flow/Pipe2002", + "Assets/Sensors/Flow/Pipe2001", + "Assets/Sensors/Level/Drum2002", + "Assets/Sensors/Flow/Pipe2002", "Assets/Controllers/Flow/FC2001", "Assets/Controllers/Level/LC2001", "Assets/Controllers/Custom/CC2001", @@ -141,17 +141,17 @@ protected virtual void Dispose(bool disposing) /// private string[] s_BlockDatabase = new string[] { - "Pipe1001/FlowSensor", - "Drum1002/LevelSensor", - "Pipe1002/FlowSensor", - "Pipe2001/FlowSensor", - "Drum2002/LevelSensor", - "Pipe2002/FlowSensor", - "FC1001/Controller", - "LC1001/Controller", - "CC1001/CustomController", - "FC2001/Controller", - "LC2001/Controller", + "Pipe1001/FlowSensor", + "Drum1002/LevelSensor", + "Pipe1002/FlowSensor", + "Pipe2001/FlowSensor", + "Drum2002/LevelSensor", + "Pipe2002/FlowSensor", + "FC1001/Controller", + "LC1001/Controller", + "CC1001/CustomController", + "FC2001/Controller", + "LC2001/Controller", "CC2001/CustomController" }; @@ -177,7 +177,7 @@ public UnderlyingSystemSegment FindSegment(string segmentPath) if (index != -1) { - segmentName = segmentName.Substring(index+1); + segmentName = segmentName.Substring(index + 1); } if (string.IsNullOrEmpty(segmentName)) @@ -201,7 +201,7 @@ public UnderlyingSystemSegment FindSegment(string segmentPath) if (blockPath.StartsWith(segmentPath)) { UnderlyingSystemSegment segment = new UnderlyingSystemSegment(); - + segment.Id = segmentPath; segment.Name = segmentName; segment.SegmentType = null; @@ -229,7 +229,7 @@ public IList FindSegments(string segmentPath) segmentPath = String.Empty; } - Dictionary segments = new Dictionary(); + Dictionary segments = new Dictionary(); // find all block paths that start with the specified segment. int length = segmentPath.Length; @@ -251,7 +251,7 @@ public IList FindSegments(string segmentPath) continue; } - blockPath = blockPath.Substring(length+1); + blockPath = blockPath.Substring(length + 1); } // extract segment name. @@ -325,7 +325,7 @@ public IList FindBlocks(string segmentPath) continue; } - blockPath = blockPath.Substring(length+1); + blockPath = blockPath.Substring(length + 1); } // check if there are no more segments in the path. @@ -333,7 +333,7 @@ public IList FindBlocks(string segmentPath) if (index == -1) { - blockPath = blockPath.Substring(index+1); + blockPath = blockPath.Substring(index + 1); if (!blocks.Contains(blockPath)) { @@ -370,7 +370,7 @@ public UnderlyingSystemSegment FindParentForSegment(string segmentPath) { return null; } - + // construct the parent. UnderlyingSystemSegment parent = new UnderlyingSystemSegment(); @@ -431,7 +431,7 @@ public UnderlyingSystemBlock FindBlock(string blockId) if (blockType.StartsWith(blockId)) { - blockType = blockType.Substring(length+1); + blockType = blockType.Substring(length + 1); break; } @@ -443,7 +443,7 @@ public UnderlyingSystemBlock FindBlock(string blockId) { return null; } - + // create a new block. block = new UnderlyingSystemBlock(); @@ -521,7 +521,7 @@ public IList FindSegmentsForBlock(string blockId) { string blockPath = s_BlockPathDatabase[ii]; - if (length >= blockPath.Length || blockPath[blockPath.Length-length] != '/') + if (length >= blockPath.Length || blockPath[blockPath.Length - length] != '/') { continue; } @@ -531,7 +531,7 @@ public IList FindSegmentsForBlock(string blockId) continue; } - string segmentPath = blockPath.Substring(0, blockPath.Length-length-1); + string segmentPath = blockPath.Substring(0, blockPath.Length - length - 1); // construct segment. UnderlyingSystemSegment segment = new UnderlyingSystemSegment(); @@ -629,7 +629,7 @@ private void DoSimulation(object state) #region Private Fields private object m_lock = new object(); - private Dictionary m_blocks; + private Dictionary m_blocks; private Timer m_simulationTimer; private long m_simulationCounter; private Opc.Ua.Test.DataGenerator m_generator; diff --git a/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystemBlock.cs b/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystemBlock.cs index e8d9ac39d..e0209f7a3 100644 --- a/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystemBlock.cs +++ b/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystemBlock.cs @@ -98,9 +98,9 @@ public DateTime Timestamp /// The engineering units. /// if set to true the tag is writeable. public void CreateTag( - string tagName, - UnderlyingSystemDataType dataType, - UnderlyingSystemTagType tagType, + string tagName, + UnderlyingSystemDataType dataType, + UnderlyingSystemTagType tagType, string engineeringUnits, bool writeable) { @@ -186,7 +186,7 @@ public IList GetTags() return tags; } } - + /// /// Starts the monitoring. /// @@ -216,7 +216,7 @@ public uint WriteTagValue(string tagName, object value) // find the tag. tag = FindTag(tagName); - + if (tag == null) { return StatusCodes.BadNodeIdUnknown; @@ -321,8 +321,8 @@ public void DoSimulation(long counter, int index, Opc.Ua.Test.DataGenerator gene value.Value = tag.Value; value.StatusCode = StatusCodes.Good; value.SourceTimestamp = tag.Timestamp; - - if (counter % (8 + (index%4)) == 0) + + if (counter % (8 + (index % 4)) == 0) { UpdateTagMetadata(tag, generator); } @@ -410,7 +410,7 @@ private bool UpdateTagValue( { if (tag.Labels != null && tag.Labels.Length > 0) { - high = tag.Labels.Length-1; + high = tag.Labels.Length - 1; low = 0; } @@ -423,7 +423,7 @@ private bool UpdateTagValue( if (high > low) { - value = (generator.GetRandomUInt16()%(high - low + 1)) + low; + value = (generator.GetRandomUInt16() % (high - low + 1)) + low; } // cast value to correct type or generate a random value. @@ -495,7 +495,7 @@ private bool UpdateTagValue( tag.Timestamp = DateTime.UtcNow; return true; } - + /// /// Updates the metadata for a tag. /// @@ -513,7 +513,7 @@ private bool UpdateTagMetadata( for (int ii = 0; ii < tag.EuRange.Length; ii++) { - range[ii] = tag.EuRange[ii]+1; + range[ii] = tag.EuRange[ii] + 1; } tag.EuRange = range; diff --git a/Workshop/DataTypes/Client/DataTypes Client.csproj b/Workshop/DataTypes/Client/DataTypes Client.csproj index 10f62e586..d4ea737fb 100644 --- a/Workshop/DataTypes/Client/DataTypes Client.csproj +++ b/Workshop/DataTypes/Client/DataTypes Client.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -123,7 +125,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/DataTypes/Client/MainForm.Designer.cs b/Workshop/DataTypes/Client/MainForm.Designer.cs index 8fefeb8e9..378670961 100644 --- a/Workshop/DataTypes/Client/MainForm.Designer.cs +++ b/Workshop/DataTypes/Client/MainForm.Designer.cs @@ -189,7 +189,7 @@ private void InitializeComponent() this.Browse_ViewValueMI.Name = "Browse_ViewValueMI"; this.Browse_ViewValueMI.Size = new System.Drawing.Size(137, 22); this.Browse_ViewValueMI.Text = "View Value..."; - this.Browse_ViewValueMI.Click += new System.EventHandler(this.Browse_ViewValueMI_Click); + this.Browse_ViewValueMI.Click += new System.EventHandler(this.Browse_ViewValueMI_ClickAsync); // // ConnectServerCTRL // @@ -208,9 +208,9 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); - this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); - this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); + this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStartingAsync); + this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectCompleteAsync); // // clientHeaderBranding1 // diff --git a/Workshop/DataTypes/Client/MainForm.cs b/Workshop/DataTypes/Client/MainForm.cs index 4f9f9b7cc..dc8e73f72 100644 --- a/Workshop/DataTypes/Client/MainForm.cs +++ b/Workshop/DataTypes/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -54,7 +54,7 @@ private MainForm() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } - + /// /// Creates a form which uses the specified client configuration. /// @@ -72,7 +72,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; #endregion #region Private Methods @@ -86,7 +86,7 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -127,23 +127,24 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { m_session = ConnectServerCTRL.Session; // browse the instances in the server. - BrowseCTRL.Initialize(m_session, - ObjectIds.RootFolder, - ReferenceTypeIds.Organizes, + await BrowseCTRL.InitializeAsync(m_session, + ObjectIds.RootFolder, + default, + ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates, ReferenceTypeIds.HierarchicalReferences); if (m_session != null) { var typeSystem = new ComplexTypeSystem(m_session); - typeSystem.Load().Wait(); + await typeSystem.LoadAsync(); } } catch (Exception exception) @@ -155,11 +156,11 @@ private void Server_ConnectComplete(object sender, EventArgs e) /// /// Updates the application after a communicate error was detected. /// - private void Server_ReconnectStarting(object sender, EventArgs e) + private async void Server_ReconnectStartingAsync(object sender, EventArgs e) { try { - BrowseCTRL.ChangeSession(null); + await BrowseCTRL.ChangeSessionAsync(null); } catch (Exception exception) { @@ -170,12 +171,12 @@ private void Server_ReconnectStarting(object sender, EventArgs e) /// /// Updates the application after reconnecting to the server. /// - private void Server_ReconnectComplete(object sender, EventArgs e) + private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) { try { m_session = ConnectServerCTRL.Session; - BrowseCTRL.ChangeSession(m_session); + await BrowseCTRL.ChangeSessionAsync(m_session); } catch (Exception exception) { @@ -191,7 +192,7 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) ConnectServerCTRL.Disconnect(); } - private void Browse_ViewValueMI_Click(object sender, EventArgs e) + private async void Browse_ViewValueMI_ClickAsync(object sender, EventArgs e) { try { @@ -199,7 +200,7 @@ private void Browse_ViewValueMI_Click(object sender, EventArgs e) if (reference != null) { - new EditComplexValue2Dlg().ShowDialog(m_session, (NodeId)reference.NodeId, Variant.Null, "Read/Write Value"); + await new EditComplexValue2Dlg().ShowDialogAsync(m_session, (NodeId)reference.NodeId, Variant.Null, "Read/Write Value"); } } catch (Exception exception) diff --git a/Workshop/DataTypes/Client/Program.cs b/Workshop/DataTypes/Client/Program.cs index ce946e412..855ba19c8 100644 --- a/Workshop/DataTypes/Client/Program.cs +++ b/Workshop/DataTypes/Client/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "DataTypesClient"; try @@ -61,15 +61,15 @@ static void Main() { return; } - + // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // add the encodable types defined in the shared information model library. EncodeableFactory.GlobalFactory.AddEncodeableTypes(typeof(Quickstarts.DataTypes.Types.Namespaces).Assembly); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/DataTypes/Common/DataTypes Library.csproj b/Workshop/DataTypes/Common/DataTypes Library.csproj index 49d8d0212..77697ece4 100644 --- a/Workshop/DataTypes/Common/DataTypes Library.csproj +++ b/Workshop/DataTypes/Common/DataTypes Library.csproj @@ -44,6 +44,7 @@ prompt 4 false + AllRules.ruleset pdbonly @@ -53,6 +54,7 @@ prompt 4 false + AllRules.ruleset @@ -102,7 +104,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/DataTypes/Common/Types/Quickstarts.DataTypes.Types.Classes.cs b/Workshop/DataTypes/Common/Types/Quickstarts.DataTypes.Types.Classes.cs index 9ab2f13a2..35ccd51b4 100644 --- a/Workshop/DataTypes/Common/Types/Quickstarts.DataTypes.Types.Classes.cs +++ b/Workshop/DataTypes/Common/Types/Quickstarts.DataTypes.Types.Classes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.DataTypes.Types { #region DriverState Class - #if (!OPCUA_EXCLUDE_DriverState) +#if (!OPCUA_EXCLUDE_DriverState) /// /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] @@ -55,7 +55,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.DataTypes.Types.ObjectTypes.DriverType, Quickstarts.DataTypes.Types.Namespaces.DataTypes, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// protected override void Initialize(ISystemContext context) { @@ -100,7 +100,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "Z2luZT5FbGVjdHJpY18zPC9FbmdpbmU+PE5vT2ZQYXNzZW5nZXJzPjQ8L05vT2ZQYXNzZW5nZXJzPjwv" + "VmVoaWNsZVR5cGU+AQE6AQEAAAABAAAAAAAAAAMD/////wAAAAA="; #endregion - #endif +#endif #endregion #region Public Properties @@ -161,7 +161,7 @@ public override void GetChildren( base.GetChildren(context, children); } - + /// protected override BaseInstanceState FindChild( ISystemContext context, @@ -235,6 +235,6 @@ protected override BaseInstanceState FindChild( private PropertyState m_ownedVehicles; #endregion } - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/DataTypes/Common/Types/Quickstarts.DataTypes.Types.DataTypes.cs b/Workshop/DataTypes/Common/Types/Quickstarts.DataTypes.Types.DataTypes.cs index 18926e7b8..d7cce50d2 100644 --- a/Workshop/DataTypes/Common/Types/Quickstarts.DataTypes.Types.DataTypes.cs +++ b/Workshop/DataTypes/Common/Types/Quickstarts.DataTypes.Types.DataTypes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.DataTypes.Types { #region EngineType Enumeration - #if (!OPCUA_EXCLUDE_EngineType) +#if (!OPCUA_EXCLUDE_EngineType) /// /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] @@ -74,13 +74,13 @@ public partial class EngineTypeCollection : List, ICloneable { #region Constructors /// - public EngineTypeCollection() {} + public EngineTypeCollection() { } /// - public EngineTypeCollection(int capacity) : base(capacity) {} + public EngineTypeCollection(int capacity) : base(capacity) { } /// - public EngineTypeCollection(IEnumerable collection) : base(collection) {} + public EngineTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -129,11 +129,11 @@ public object Clone() } } #endregion - #endif +#endif #endregion #region VehicleType Class - #if (!OPCUA_EXCLUDE_VehicleType) +#if (!OPCUA_EXCLUDE_VehicleType) /// /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] @@ -146,13 +146,13 @@ public VehicleType() { Initialize(); } - + [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } - + private void Initialize() { m_make = null; @@ -166,7 +166,7 @@ private void Initialize() [DataMember(Name = "Make", IsRequired = false, Order = 1)] public string Make { - get { return m_make; } + get { return m_make; } set { m_make = value; } } @@ -174,7 +174,7 @@ public string Make [DataMember(Name = "Model", IsRequired = false, Order = 2)] public string Model { - get { return m_model; } + get { return m_model; } set { m_model = value; } } @@ -182,23 +182,23 @@ public string Model [DataMember(Name = "Engine", IsRequired = false, Order = 3)] public EngineType Engine { - get { return m_engine; } + get { return m_engine; } set { m_engine = value; } } #endregion #region IEncodeable Members /// - public virtual ExpandedNodeId TypeId => DataTypeIds.VehicleType; + public virtual ExpandedNodeId TypeId => DataTypeIds.VehicleType; /// public virtual ExpandedNodeId BinaryEncodingId => ObjectIds.VehicleType_Encoding_DefaultBinary; /// public virtual ExpandedNodeId XmlEncodingId => ObjectIds.VehicleType_Encoding_DefaultXml; - + /// - public virtual ExpandedNodeId JsonEncodingId => ObjectIds.VehicleType_Encoding_DefaultJson; + public virtual ExpandedNodeId JsonEncodingId => ObjectIds.VehicleType_Encoding_DefaultJson; /// public virtual void Encode(IEncoder encoder) @@ -281,13 +281,13 @@ public partial class VehicleTypeCollection : List, ICloneable { #region Constructors /// - public VehicleTypeCollection() {} + public VehicleTypeCollection() { } /// - public VehicleTypeCollection(int capacity) : base(capacity) {} + public VehicleTypeCollection(int capacity) : base(capacity) { } /// - public VehicleTypeCollection(IEnumerable collection) : base(collection) {} + public VehicleTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -336,11 +336,11 @@ public object Clone() } } #endregion - #endif +#endif #endregion #region CarType Class - #if (!OPCUA_EXCLUDE_CarType) +#if (!OPCUA_EXCLUDE_CarType) /// /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] @@ -371,23 +371,23 @@ private void Initialize() [DataMember(Name = "NoOfPassengers", IsRequired = false, Order = 1)] public uint NoOfPassengers { - get { return m_noOfPassengers; } + get { return m_noOfPassengers; } set { m_noOfPassengers = value; } } #endregion #region IEncodeable Members /// - public override ExpandedNodeId TypeId => DataTypeIds.CarType; + public override ExpandedNodeId TypeId => DataTypeIds.CarType; /// public override ExpandedNodeId BinaryEncodingId => ObjectIds.CarType_Encoding_DefaultBinary; /// public override ExpandedNodeId XmlEncodingId => ObjectIds.CarType_Encoding_DefaultXml; - + /// - public override ExpandedNodeId JsonEncodingId => ObjectIds.CarType_Encoding_DefaultJson; + public override ExpandedNodeId JsonEncodingId => ObjectIds.CarType_Encoding_DefaultJson; /// public override void Encode(IEncoder encoder) @@ -431,7 +431,7 @@ public override bool IsEqual(IEncodeable encodeable) if (!Utils.IsEqual(m_noOfPassengers, value.m_noOfPassengers)) return false; return base.IsEqual(encodeable); - } + } /// public override object Clone() @@ -464,13 +464,13 @@ public partial class CarTypeCollection : List, ICloneable { #region Constructors /// - public CarTypeCollection() {} + public CarTypeCollection() { } /// - public CarTypeCollection(int capacity) : base(capacity) {} + public CarTypeCollection(int capacity) : base(capacity) { } /// - public CarTypeCollection(IEnumerable collection) : base(collection) {} + public CarTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -519,11 +519,11 @@ public object Clone() } } #endregion - #endif +#endif #endregion #region TruckType Class - #if (!OPCUA_EXCLUDE_TruckType) +#if (!OPCUA_EXCLUDE_TruckType) /// /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] @@ -554,23 +554,23 @@ private void Initialize() [DataMember(Name = "CargoCapacity", IsRequired = false, Order = 1)] public uint CargoCapacity { - get { return m_cargoCapacity; } + get { return m_cargoCapacity; } set { m_cargoCapacity = value; } } #endregion #region IEncodeable Members /// - public override ExpandedNodeId TypeId => DataTypeIds.TruckType; + public override ExpandedNodeId TypeId => DataTypeIds.TruckType; /// public override ExpandedNodeId BinaryEncodingId => ObjectIds.TruckType_Encoding_DefaultBinary; /// public override ExpandedNodeId XmlEncodingId => ObjectIds.TruckType_Encoding_DefaultXml; - + /// - public override ExpandedNodeId JsonEncodingId => ObjectIds.TruckType_Encoding_DefaultJson; + public override ExpandedNodeId JsonEncodingId => ObjectIds.TruckType_Encoding_DefaultJson; /// public override void Encode(IEncoder encoder) @@ -614,7 +614,7 @@ public override bool IsEqual(IEncodeable encodeable) if (!Utils.IsEqual(m_cargoCapacity, value.m_cargoCapacity)) return false; return base.IsEqual(encodeable); - } + } /// public override object Clone() @@ -647,13 +647,13 @@ public partial class TruckTypeCollection : List, ICloneable { #region Constructors /// - public TruckTypeCollection() {} + public TruckTypeCollection() { } /// - public TruckTypeCollection(int capacity) : base(capacity) {} + public TruckTypeCollection(int capacity) : base(capacity) { } /// - public TruckTypeCollection(IEnumerable collection) : base(collection) {} + public TruckTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -702,6 +702,6 @@ public object Clone() } } #endregion - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/DataTypes/Server/DataTypes Server.csproj b/Workshop/DataTypes/Server/DataTypes Server.csproj index fc12937f2..1ff188a65 100644 --- a/Workshop/DataTypes/Server/DataTypes Server.csproj +++ b/Workshop/DataTypes/Server/DataTypes Server.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset false @@ -143,7 +145,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/DataTypes/Server/DataTypesNodeManager.cs b/Workshop/DataTypes/Server/DataTypesNodeManager.cs index 89ec4cba4..70c826754 100644 --- a/Workshop/DataTypes/Server/DataTypesNodeManager.cs +++ b/Workshop/DataTypes/Server/DataTypesNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -51,7 +51,7 @@ public class DataTypesNodeManager : CustomNodeManager2 /// public DataTypesNodeManager(IServerInternal server, ApplicationConfiguration configuration) : - base(server, configuration) + base(server, configuration) { SystemContext.NodeIdFactory = this; @@ -70,13 +70,13 @@ public DataTypesNodeManager(IServerInternal server, ApplicationConfiguration con } } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { // TBD @@ -109,7 +109,7 @@ public override NodeId New(ISystemContext context, NodeState node) /// /// The externalReferences is an out parameter that allows the node manager to link to nodes /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and - /// should have a reference to the root folder node(s) exposed by this node manager. + /// should have a reference to the root folder node(s) exposed by this node manager. /// public override void CreateAddressSpace(IDictionary> externalReferences) { @@ -124,7 +124,7 @@ public override void CreateAddressSpace(IDictionary> e /// public byte[] LoadSchemaFromResource(string resourcePath, Assembly assembly) { - if (resourcePath == null) throw new ArgumentNullException("resourcePath"); + if (resourcePath == null) throw new ArgumentNullException(nameof(resourcePath)); if (assembly == null) { @@ -139,7 +139,11 @@ public byte[] LoadSchemaFromResource(string resourcePath, Assembly assembly) } byte[] buffer = new byte[istrm.Length]; - istrm.Read(buffer, 0, (int)istrm.Length); + var read = istrm.Read(buffer, 0, (int)istrm.Length); + if (read != istrm.Length) + { + throw ServiceResultException.Create(StatusCodes.BadDecodingError, "Could not read entire resource: {0}", resourcePath); + } return buffer; } @@ -149,14 +153,14 @@ public byte[] LoadSchemaFromResource(string resourcePath, Assembly assembly) protected override NodeStateCollection LoadPredefinedNodes(ISystemContext context) { NodeStateCollection predefinedNodes = new NodeStateCollection(); - - predefinedNodes.LoadFromBinaryResource(context, - "Quickstarts.DataTypes.Types.Quickstarts.DataTypes.Types.PredefinedNodes.uanodes", - typeof(Quickstarts.DataTypes.Types.VehicleType).Assembly, + + predefinedNodes.LoadFromBinaryResource(context, + "Quickstarts.DataTypes.Types.Quickstarts.DataTypes.Types.PredefinedNodes.uanodes", + typeof(Quickstarts.DataTypes.Types.VehicleType).Assembly, true); - predefinedNodes.LoadFromBinaryResource(context, + predefinedNodes.LoadFromBinaryResource(context, "Quickstarts.DataTypes.Instances.Quickstarts.DataTypes.Instances.PredefinedNodes.uanodes", - typeof(DataTypesNodeManager).GetTypeInfo().Assembly, + typeof(DataTypesNodeManager).GetTypeInfo().Assembly, true); return predefinedNodes; @@ -180,7 +184,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node { lock (Lock) { - // quickly exclude nodes that are not in the namespace. + // quickly exclude nodes that are not in the namespace. if (!IsNodeIdInNamespace(nodeId)) { return null; @@ -212,7 +216,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node // node not found. return null; - } + } } /// diff --git a/Workshop/DataTypes/Server/DataTypesServer.cs b/Workshop/DataTypes/Server/DataTypesServer.cs index 2b33cddd3..5702ff117 100644 Binary files a/Workshop/DataTypes/Server/DataTypesServer.cs and b/Workshop/DataTypes/Server/DataTypesServer.cs differ diff --git a/Workshop/DataTypes/Server/DataTypesServerConfiguration.cs b/Workshop/DataTypes/Server/DataTypesServerConfiguration.cs index f595cddc9..54fa7ce95 100644 --- a/Workshop/DataTypes/Server/DataTypesServerConfiguration.cs +++ b/Workshop/DataTypes/Server/DataTypesServerConfiguration.cs @@ -38,7 +38,7 @@ namespace Quickstarts.DataTypes /// /// Stores the configuration the data access node manager. /// - [DataContract(Namespace=Namespaces.DataTypes)] + [DataContract(Namespace = Namespaces.DataTypes)] public class DataTypesServerConfiguration { #region Constructors diff --git a/Workshop/DataTypes/Server/Instances/Quickstarts.DataTypes.Instances.DataTypes.cs b/Workshop/DataTypes/Server/Instances/Quickstarts.DataTypes.Instances.DataTypes.cs index cd78e2dad..7c7414fe5 100644 --- a/Workshop/DataTypes/Server/Instances/Quickstarts.DataTypes.Instances.DataTypes.cs +++ b/Workshop/DataTypes/Server/Instances/Quickstarts.DataTypes.Instances.DataTypes.cs @@ -38,7 +38,7 @@ namespace Quickstarts.DataTypes.Instances { #region ParkingLotType Enumeration - #if (!OPCUA_EXCLUDE_ParkingLotType) +#if (!OPCUA_EXCLUDE_ParkingLotType) /// /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] @@ -63,13 +63,13 @@ public partial class ParkingLotTypeCollection : List, ICloneable { #region Constructors /// - public ParkingLotTypeCollection() {} + public ParkingLotTypeCollection() { } /// - public ParkingLotTypeCollection(int capacity) : base(capacity) {} + public ParkingLotTypeCollection(int capacity) : base(capacity) { } /// - public ParkingLotTypeCollection(IEnumerable collection) : base(collection) {} + public ParkingLotTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -118,11 +118,11 @@ public object Clone() } } #endregion - #endif +#endif #endregion #region TwoWheelerType Class - #if (!OPCUA_EXCLUDE_TwoWheelerType) +#if (!OPCUA_EXCLUDE_TwoWheelerType) /// /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] @@ -153,23 +153,23 @@ private void Initialize() [DataMember(Name = "ManufacturerName", IsRequired = false, Order = 1)] public string ManufacturerName { - get { return m_manufacturerName; } + get { return m_manufacturerName; } set { m_manufacturerName = value; } } #endregion #region IEncodeable Members /// - public override ExpandedNodeId TypeId => DataTypeIds.TwoWheelerType; + public override ExpandedNodeId TypeId => DataTypeIds.TwoWheelerType; /// public override ExpandedNodeId BinaryEncodingId => ObjectIds.TwoWheelerType_Encoding_DefaultBinary; /// public override ExpandedNodeId XmlEncodingId => ObjectIds.TwoWheelerType_Encoding_DefaultXml; - + /// - public override ExpandedNodeId JsonEncodingId => ObjectIds.TwoWheelerType_Encoding_DefaultJson; + public override ExpandedNodeId JsonEncodingId => ObjectIds.TwoWheelerType_Encoding_DefaultJson; /// public override void Encode(IEncoder encoder) @@ -214,7 +214,7 @@ public override bool IsEqual(IEncodeable encodeable) if (!Utils.IsEqual(m_manufacturerName, value.m_manufacturerName)) return false; return base.IsEqual(encodeable); - } + } /// public override object Clone() @@ -247,13 +247,13 @@ public partial class TwoWheelerTypeCollection : List, ICloneable { #region Constructors /// - public TwoWheelerTypeCollection() {} + public TwoWheelerTypeCollection() { } /// - public TwoWheelerTypeCollection(int capacity) : base(capacity) {} + public TwoWheelerTypeCollection(int capacity) : base(capacity) { } /// - public TwoWheelerTypeCollection(IEnumerable collection) : base(collection) {} + public TwoWheelerTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -302,11 +302,11 @@ public object Clone() } } #endregion - #endif +#endif #endregion #region BicycleType Class - #if (!OPCUA_EXCLUDE_BicycleType) +#if (!OPCUA_EXCLUDE_BicycleType) /// /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] @@ -337,23 +337,23 @@ private void Initialize() [DataMember(Name = "NoOfGears", IsRequired = false, Order = 1)] public uint NoOfGears { - get { return m_noOfGears; } + get { return m_noOfGears; } set { m_noOfGears = value; } } #endregion #region IEncodeable Members /// - public override ExpandedNodeId TypeId => DataTypeIds.BicycleType; + public override ExpandedNodeId TypeId => DataTypeIds.BicycleType; /// public override ExpandedNodeId BinaryEncodingId => ObjectIds.BicycleType_Encoding_DefaultBinary; /// public override ExpandedNodeId XmlEncodingId => ObjectIds.BicycleType_Encoding_DefaultXml; - + /// - public override ExpandedNodeId JsonEncodingId => ObjectIds.BicycleType_Encoding_DefaultJson; + public override ExpandedNodeId JsonEncodingId => ObjectIds.BicycleType_Encoding_DefaultJson; /// public override void Encode(IEncoder encoder) @@ -398,7 +398,7 @@ public override bool IsEqual(IEncodeable encodeable) if (!Utils.IsEqual(m_noOfGears, value.m_noOfGears)) return false; return base.IsEqual(encodeable); - } + } /// public override object Clone() @@ -431,13 +431,13 @@ public partial class BicycleTypeCollection : List, ICloneable { #region Constructors /// - public BicycleTypeCollection() {} + public BicycleTypeCollection() { } /// - public BicycleTypeCollection(int capacity) : base(capacity) {} + public BicycleTypeCollection(int capacity) : base(capacity) { } /// - public BicycleTypeCollection(IEnumerable collection) : base(collection) {} + public BicycleTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -486,11 +486,11 @@ public object Clone() } } #endregion - #endif +#endif #endregion #region ScooterType Class - #if (!OPCUA_EXCLUDE_ScooterType) +#if (!OPCUA_EXCLUDE_ScooterType) /// /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] @@ -521,23 +521,23 @@ private void Initialize() [DataMember(Name = "NoOfSeats", IsRequired = false, Order = 1)] public uint NoOfSeats { - get { return m_noOfSeats; } + get { return m_noOfSeats; } set { m_noOfSeats = value; } } #endregion #region IEncodeable Members /// - public override ExpandedNodeId TypeId => DataTypeIds.ScooterType; + public override ExpandedNodeId TypeId => DataTypeIds.ScooterType; /// public override ExpandedNodeId BinaryEncodingId => ObjectIds.ScooterType_Encoding_DefaultBinary; /// public override ExpandedNodeId XmlEncodingId => ObjectIds.ScooterType_Encoding_DefaultXml; - + /// - public override ExpandedNodeId JsonEncodingId => ObjectIds.ScooterType_Encoding_DefaultJson; + public override ExpandedNodeId JsonEncodingId => ObjectIds.ScooterType_Encoding_DefaultJson; /// public override void Encode(IEncoder encoder) @@ -582,7 +582,7 @@ public override bool IsEqual(IEncodeable encodeable) if (!Utils.IsEqual(m_noOfSeats, value.m_noOfSeats)) return false; return base.IsEqual(encodeable); - } + } /// public override object Clone() @@ -615,13 +615,13 @@ public partial class ScooterTypeCollection : List, ICloneable { #region Constructors /// - public ScooterTypeCollection() {} + public ScooterTypeCollection() { } /// - public ScooterTypeCollection(int capacity) : base(capacity) {} + public ScooterTypeCollection(int capacity) : base(capacity) { } /// - public ScooterTypeCollection(IEnumerable collection) : base(collection) {} + public ScooterTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -670,6 +670,6 @@ public object Clone() } } #endregion - #endif +#endif #endregion } diff --git a/Workshop/DataTypes/Server/Program.cs b/Workshop/DataTypes/Server/Program.cs index a60faa7ff..1fbc12191 100644 --- a/Workshop/DataTypes/Server/Program.cs +++ b/Workshop/DataTypes/Server/Program.cs @@ -53,7 +53,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "DataTypesServer"; try @@ -72,13 +72,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // start the server. - application.Start(new DataTypesServer()).Wait(); + application.StartAsync(new DataTypesServer()).Wait(); // run the application interactively. Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); diff --git a/Workshop/Empty/Client/Empty Client.csproj b/Workshop/Empty/Client/Empty Client.csproj index 629ad91f4..ed8facaff 100644 --- a/Workshop/Empty/Client/Empty Client.csproj +++ b/Workshop/Empty/Client/Empty Client.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -132,7 +134,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Empty/Client/MainForm.Designer.cs b/Workshop/Empty/Client/MainForm.Designer.cs index e381439e5..024e2eb64 100644 --- a/Workshop/Empty/Client/MainForm.Designer.cs +++ b/Workshop/Empty/Client/MainForm.Designer.cs @@ -175,9 +175,9 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); - this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); - this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); + this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStartingAsync); + this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectCompleteAsync); // // clientHeaderBranding1 // diff --git a/Workshop/Empty/Client/MainForm.cs b/Workshop/Empty/Client/MainForm.cs index e59eb5381..24929d095 100644 --- a/Workshop/Empty/Client/MainForm.cs +++ b/Workshop/Empty/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -53,7 +53,7 @@ private MainForm() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } - + /// /// Creates a form which uses the specified client configuration. /// @@ -71,7 +71,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private bool m_connectedOnce; #endregion @@ -86,7 +86,7 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -127,7 +127,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -140,7 +140,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) } // browse the instances in the server. - BrowseCTRL.Initialize(m_session, ObjectIds.ObjectsFolder, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); + await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); } catch (Exception exception) { @@ -151,11 +151,11 @@ private void Server_ConnectComplete(object sender, EventArgs e) /// /// Updates the application after a communicate error was detected. /// - private void Server_ReconnectStarting(object sender, EventArgs e) + private async void Server_ReconnectStartingAsync(object sender, EventArgs e) { try { - BrowseCTRL.ChangeSession(null); + await BrowseCTRL.ChangeSessionAsync(null); } catch (Exception exception) { @@ -166,12 +166,12 @@ private void Server_ReconnectStarting(object sender, EventArgs e) /// /// Updates the application after reconnecting to the server. /// - private void Server_ReconnectComplete(object sender, EventArgs e) + private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) { try { m_session = ConnectServerCTRL.Session; - BrowseCTRL.ChangeSession(m_session); + await BrowseCTRL.ChangeSessionAsync(m_session); } catch (Exception exception) { diff --git a/Workshop/Empty/Client/Program.cs b/Workshop/Empty/Client/Program.cs index 4ff495e81..66290ca7b 100644 --- a/Workshop/Empty/Client/Program.cs +++ b/Workshop/Empty/Client/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.EmptyClient"; try @@ -61,12 +61,12 @@ static void Main() { return; } - + // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/Empty/Server/Empty Server.csproj b/Workshop/Empty/Server/Empty Server.csproj index 77783f4ff..88b6ef1a9 100644 --- a/Workshop/Empty/Server/Empty Server.csproj +++ b/Workshop/Empty/Server/Empty Server.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -129,7 +131,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Empty/Server/EmptyNodeManager.cs b/Workshop/Empty/Server/EmptyNodeManager.cs index 4b8db372f..fcbc5df7d 100644 --- a/Workshop/Empty/Server/EmptyNodeManager.cs +++ b/Workshop/Empty/Server/EmptyNodeManager.cs @@ -65,13 +65,13 @@ public EmptyNodeManager(IServerInternal server, ApplicationConfiguration configu } } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { // TBD @@ -107,7 +107,7 @@ public override void CreateAddressSpace(IDictionary> e trigger.NodeId = new NodeId(1, NamespaceIndex); trigger.BrowseName = new QualifiedName("Trigger", NamespaceIndex); trigger.DisplayName = trigger.BrowseName.Name; - trigger.TypeDefinitionId = ObjectTypeIds.BaseObjectType; + trigger.TypeDefinitionId = ObjectTypeIds.BaseObjectType; // ensure trigger can be found via the server object. IList references = null; @@ -154,7 +154,7 @@ public override void CreateAddressSpace(IDictionary> e // save in dictionary. AddPredefinedNode(SystemContext, referenceType); - } + } } /// @@ -195,7 +195,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node handle.Validated = true; return handle; - } + } } /// @@ -217,7 +217,7 @@ protected override NodeState ValidateNode( { return handle.Node; } - + // TBD return null; diff --git a/Workshop/Empty/Server/EmptyServer.cs b/Workshop/Empty/Server/EmptyServer.cs index c53747828..c63ac9308 100644 Binary files a/Workshop/Empty/Server/EmptyServer.cs and b/Workshop/Empty/Server/EmptyServer.cs differ diff --git a/Workshop/Empty/Server/EmptyServerConfiguration.cs b/Workshop/Empty/Server/EmptyServerConfiguration.cs index bdda0c6ab..3bf4bee51 100644 --- a/Workshop/Empty/Server/EmptyServerConfiguration.cs +++ b/Workshop/Empty/Server/EmptyServerConfiguration.cs @@ -38,7 +38,7 @@ namespace Quickstarts.EmptyServer /// /// Stores the configuration the data access node manager. /// - [DataContract(Namespace=Namespaces.Empty)] + [DataContract(Namespace = Namespaces.Empty)] public class EmptyServerConfiguration { #region Constructors diff --git a/Workshop/Empty/Server/Program.cs b/Workshop/Empty/Server/Program.cs index 345da0710..8e29cd38a 100644 --- a/Workshop/Empty/Server/Program.cs +++ b/Workshop/Empty/Server/Program.cs @@ -52,7 +52,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.EmptyServer"; try @@ -71,13 +71,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); - + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); + // start the server. - application.Start(new EmptyServer()).Wait(); + application.StartAsync(new EmptyServer()).Wait(); // run the application interactively. Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); diff --git a/Workshop/HistoricalAccess/Client/HistoricalAccess Client.csproj b/Workshop/HistoricalAccess/Client/HistoricalAccess Client.csproj index 0b290b873..db12cdb68 100644 --- a/Workshop/HistoricalAccess/Client/HistoricalAccess Client.csproj +++ b/Workshop/HistoricalAccess/Client/HistoricalAccess Client.csproj @@ -48,6 +48,7 @@ false false + AllRules.ruleset pdbonly @@ -60,6 +61,7 @@ false false + AllRules.ruleset @@ -178,7 +180,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/HistoricalAccess/Client/MainForm.Designer.cs b/Workshop/HistoricalAccess/Client/MainForm.Designer.cs index ee992b24b..aa36b8ca3 100644 --- a/Workshop/HistoricalAccess/Client/MainForm.Designer.cs +++ b/Workshop/HistoricalAccess/Client/MainForm.Designer.cs @@ -174,7 +174,7 @@ private void InitializeComponent() this.Aggregates_SelectVariableMI.Name = "Aggregates_SelectVariableMI"; this.Aggregates_SelectVariableMI.Size = new System.Drawing.Size(222, 22); this.Aggregates_SelectVariableMI.Text = "Select Variable..."; - this.Aggregates_SelectVariableMI.Click += new System.EventHandler(this.Aggregates_SelectVariableMI_Click); + this.Aggregates_SelectVariableMI.Click += new System.EventHandler(this.Aggregates_SelectVariableMI_ClickAsync); // // Aggregates_SelectAggregateTypeMI // @@ -187,7 +187,7 @@ private void InitializeComponent() this.ViewHistoricalConfigurationMI.Name = "ViewHistoricalConfigurationMI"; this.ViewHistoricalConfigurationMI.Size = new System.Drawing.Size(222, 22); this.ViewHistoricalConfigurationMI.Text = "View Historical Configuration..."; - this.ViewHistoricalConfigurationMI.Click += new System.EventHandler(this.ViewHistoricalConfigurationMI_Click); + this.ViewHistoricalConfigurationMI.Click += new System.EventHandler(this.ViewHistoricalConfigurationMI_ClickAsync); // // Aggregates_ModifyAggregateFilterMI // @@ -229,7 +229,7 @@ private void InitializeComponent() this.ReadCTRL.Location = new System.Drawing.Point(2, 25); this.ReadCTRL.MaxReturnValues = ((uint)(0u)); this.ReadCTRL.Name = "ReadCTRL"; - this.ReadCTRL.NodeId = null; + this.ReadCTRL.ClearNodeId(); this.ReadCTRL.ProcessingInterval = 5000; this.ReadCTRL.ReadType = Opc.Ua.Client.Controls.HistoryDataListView.HistoryReadType.Raw; this.ReadCTRL.ReturnBounds = false; @@ -254,7 +254,7 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 3; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); // // StatusBar diff --git a/Workshop/HistoricalAccess/Client/MainForm.cs b/Workshop/HistoricalAccess/Client/MainForm.cs index bf15446ef..433df25d8 100644 --- a/Workshop/HistoricalAccess/Client/MainForm.cs +++ b/Workshop/HistoricalAccess/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -53,7 +53,7 @@ private MainForm() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } - + /// /// Creates a form which uses the specified client configuration. /// @@ -69,10 +69,10 @@ public MainForm(ApplicationConfiguration configuration) this.Text = m_configuration.ApplicationName; } #endregion - + #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private bool m_connectedOnce; #endregion @@ -84,10 +84,10 @@ public MainForm(ApplicationConfiguration configuration) /// Connects to a server. /// private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) - { + { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -128,7 +128,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -140,7 +140,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) m_connectedOnce = true; } - ReadCTRL.ChangeSession(m_session); + await ReadCTRL.ChangeSessionAsync(m_session); } catch (Exception exception) { @@ -175,7 +175,7 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) /// /// Selects the variable to display. /// - private void Aggregates_SelectVariableMI_Click(object sender, EventArgs e) + private async void Aggregates_SelectVariableMI_ClickAsync(object sender, EventArgs e) { try { @@ -184,16 +184,17 @@ private void Aggregates_SelectVariableMI_Click(object sender, EventArgs e) return; } - NodeId nodeId = new Opc.Ua.Client.Controls.SelectNodeDlg().ShowDialog( + NodeId nodeId = await new Opc.Ua.Client.Controls.SelectNodeDlg().ShowDialogAsync( m_session, Opc.Ua.ObjectIds.ObjectsFolder, "Select Variable to Monitor", + default, ReferenceTypes.Organizes, ReferenceTypes.Aggregates); if (nodeId != null) { - ReadCTRL.ChangeNode(nodeId); + await ReadCTRL.ChangeNodeAsync(nodeId); } } catch (Exception exception) @@ -202,7 +203,7 @@ private void Aggregates_SelectVariableMI_Click(object sender, EventArgs e) } } - private void ViewHistoricalConfigurationMI_Click(object sender, EventArgs e) + private async void ViewHistoricalConfigurationMI_ClickAsync(object sender, EventArgs e) { try { @@ -211,7 +212,7 @@ private void ViewHistoricalConfigurationMI_Click(object sender, EventArgs e) return; } - ReadCTRL.ShowConfiguration(); + await ReadCTRL.ShowConfigurationAsync(); } catch (Exception exception) { @@ -232,7 +233,7 @@ private void Help_ContentsMI_Click(object sender, EventArgs e) { try { - System.Diagnostics.Process.Start( Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\haclientoverview.htm"); + System.Diagnostics.Process.Start(Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\haclientoverview.htm"); } catch (Exception ex) { diff --git a/Workshop/HistoricalAccess/Client/Program.cs b/Workshop/HistoricalAccess/Client/Program.cs index a43c38a0c..5af2cb8a6 100644 --- a/Workshop/HistoricalAccess/Client/Program.cs +++ b/Workshop/HistoricalAccess/Client/Program.cs @@ -50,7 +50,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "HistoricalAccessClient"; try @@ -62,10 +62,10 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/HistoricalAccess/Client/ReadHistoryDlg.Designer.cs b/Workshop/HistoricalAccess/Client/ReadHistoryDlg.Designer.cs index 0af01cfde..aef669d15 100644 --- a/Workshop/HistoricalAccess/Client/ReadHistoryDlg.Designer.cs +++ b/Workshop/HistoricalAccess/Client/ReadHistoryDlg.Designer.cs @@ -173,7 +173,7 @@ private void InitializeComponent() this.StopBTN.TabIndex = 19; this.StopBTN.Text = "Stop"; this.StopBTN.UseVisualStyleBackColor = true; - this.StopBTN.Click += new System.EventHandler(this.StopBTN_Click); + this.StopBTN.Click += new System.EventHandler(this.StopBTN_ClickAsync); // // NextBTN // @@ -357,7 +357,7 @@ private void InitializeComponent() this.ReadTypeCB.Name = "ReadTypeCB"; this.ReadTypeCB.Size = new System.Drawing.Size(138, 21); this.ReadTypeCB.TabIndex = 1; - this.ReadTypeCB.SelectedIndexChanged += new System.EventHandler(this.ReadTypeCB_SelectedIndexChanged); + this.ReadTypeCB.SelectedIndexChanged += new System.EventHandler(this.ReadTypeCB_SelectedIndexChangedAsync); // // ReadTypeLB // diff --git a/Workshop/HistoricalAccess/Client/ReadHistoryDlg.cs b/Workshop/HistoricalAccess/Client/ReadHistoryDlg.cs index 89eb31324..5cc4b504e 100644 --- a/Workshop/HistoricalAccess/Client/ReadHistoryDlg.cs +++ b/Workshop/HistoricalAccess/Client/ReadHistoryDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -42,6 +42,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading; +using System.Threading.Tasks; namespace Quickstarts.HistoricalAccess.Client { @@ -68,7 +70,7 @@ public ReadHistoryDlg() AggregateCB.Items.Add(BrowseNames.AggregateFunction_Count); AggregateCB.Items.Add(BrowseNames.AggregateFunction_Maximum); AggregateCB.Items.Add(BrowseNames.AggregateFunction_Minimum); - AggregateCB.Items.Add(BrowseNames.AggregateFunction_Total); + AggregateCB.Items.Add(BrowseNames.AggregateFunction_Total); } private enum ReadType @@ -83,17 +85,17 @@ private enum ReadType private NodeId m_nodeId; private HistoryReadResult m_result; private int m_index; - + /// /// Displays the dialog. /// - public bool ShowDialog(Session session, NodeId nodeId) + public async Task ShowDialogAsync(Session session, NodeId nodeId, CancellationToken ct = default) { m_session = session; m_nodeId = nodeId; // update the title. - string displayText = session.NodeCache.GetDisplayText(nodeId); + string displayText = await session.NodeCache.GetDisplayTextAsync(nodeId, ct); if (!String.IsNullOrEmpty(displayText)) { @@ -105,13 +107,13 @@ public bool ShowDialog(Session session, NodeId nodeId) try { - startTime = ReadFirstDate().ToLocalTime(); + startTime = (await ReadFirstDateAsync(ct)).ToLocalTime(); } catch (Exception) { startTime = new DateTime(2000, 1, 1); } - + ReadTypeCB.SelectedItem = ReadType.Raw; StartTimeDP.Value = startTime; StartTimeCK.Checked = true; @@ -130,7 +132,7 @@ public bool ShowDialog(Session session, NodeId nodeId) { return false; } - + return true; } @@ -178,8 +180,8 @@ private void ShowResults() ResultsLV.Columns[ii].Width = -2; } } - - private void ReleaseContinuationPoints() + + private async Task ReleaseContinuationPointsAsync(CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); @@ -194,17 +196,16 @@ private void ReleaseContinuationPoints() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -214,7 +215,7 @@ private void ReleaseContinuationPoints() ShowResults(); } - private DateTime ReadFirstDate() + private async Task ReadFirstDateAsync(CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = new DateTime(1970, 1, 1); @@ -229,17 +230,16 @@ private DateTime ReadFirstDate() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -262,14 +262,16 @@ private DateTime ReadFirstDate() { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; - m_session.HistoryRead( + response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -278,7 +280,7 @@ private DateTime ReadFirstDate() return startTime; } - private void ReadRaw(bool isReadModified) + private async Task ReadRawAsync(bool isReadModified, CancellationToken ct = default) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = DateTime.MinValue; @@ -313,36 +315,36 @@ private void ReadRaw(bool isReadModified) HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); - + if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(results[0].StatusCode); } m_result = results[0]; - + ShowResults(); } - private void ReadAtTime() + private Task ReadAtTimeAsync(CancellationToken ct = default) { + return Task.CompletedTask; } - private void ReadProcessed() + private async Task ReadProcessedAsync(CancellationToken ct = default) { ReadProcessedDetails details = new ReadProcessedDetails(); details.StartTime = StartTimeDP.Value.ToUniversalTime(); @@ -375,17 +377,16 @@ private void ReadProcessed() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -400,34 +401,31 @@ private void ReadProcessed() ShowResults(); } - private void Read() + private Task ReadAsync(CancellationToken ct = default) { switch ((ReadType)ReadTypeCB.SelectedItem) { case ReadType.Raw: { - ReadRaw(false); - break; + return ReadRawAsync(false, ct); } case ReadType.Modified: { - ReadRaw(true); - break; + return ReadRawAsync(true, ct); } case ReadType.AtTime: { - ReadAtTime(); - break; + return ReadAtTimeAsync(ct); } case ReadType.Processed: { - ReadProcessed(); - break; + return ReadProcessedAsync(ct); } } + return Task.CompletedTask; } private void GoBTN_Click(object sender, EventArgs e) @@ -438,7 +436,7 @@ private void GoBTN_Click(object sender, EventArgs e) ResultsLV.Items.Clear(); m_result = null; - Read(); + ReadAsync(); } catch (Exception exception) { @@ -450,7 +448,7 @@ private void NextBTN_Click(object sender, EventArgs e) { try { - Read(); + ReadAsync(); } catch (Exception exception) { @@ -458,11 +456,11 @@ private void NextBTN_Click(object sender, EventArgs e) } } - private void StopBTN_Click(object sender, EventArgs e) + private async void StopBTN_ClickAsync(object sender, EventArgs e) { try { - ReleaseContinuationPoints(); + await ReleaseContinuationPointsAsync(); } catch (Exception exception) { @@ -470,13 +468,13 @@ private void StopBTN_Click(object sender, EventArgs e) } } - private void ReadTypeCB_SelectedIndexChanged(object sender, EventArgs e) + private async void ReadTypeCB_SelectedIndexChangedAsync(object sender, EventArgs e) { try { - ReleaseContinuationPoints(); + await ReleaseContinuationPointsAsync(); } - catch (Exception) + catch { // ignore is ok. } diff --git a/Workshop/HistoricalAccess/Client/WriteValueDlg.Designer.cs b/Workshop/HistoricalAccess/Client/WriteValueDlg.Designer.cs index 2358c499f..0137b1905 100644 --- a/Workshop/HistoricalAccess/Client/WriteValueDlg.Designer.cs +++ b/Workshop/HistoricalAccess/Client/WriteValueDlg.Designer.cs @@ -83,7 +83,7 @@ private void InitializeComponent() this.OkBTN.TabIndex = 4; this.OkBTN.Text = "OK"; this.OkBTN.UseVisualStyleBackColor = true; - this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click); + this.OkBTN.Click += new System.EventHandler(this.OkBTN_ClickAsync); // // ValueLB // diff --git a/Workshop/HistoricalAccess/Client/WriteValueDlg.cs b/Workshop/HistoricalAccess/Client/WriteValueDlg.cs index 032498dd4..7e1d3302c 100644 --- a/Workshop/HistoricalAccess/Client/WriteValueDlg.cs +++ b/Workshop/HistoricalAccess/Client/WriteValueDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,8 @@ using System.ComponentModel; using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -53,14 +55,14 @@ public WriteValueDlg() InitializeComponent(); } #endregion - + #region Private Fields private Session m_session; private NodeId m_nodeId; private uint m_attributeId; private DataValue m_value; #endregion - + #region Public Interface /// /// Prompts the user to enter a value to write. @@ -68,11 +70,12 @@ public WriteValueDlg() /// The session to use. /// The identifier for the node to write to. /// The attribute being written. + /// The token to cancel the request /// True if successful. False if the operation was cancelled. - public bool ShowDialog(Session session, NodeId nodeId, uint attributeId) + public async Task ShowDialogAsync(Session session, NodeId nodeId, uint attributeId, CancellationToken ct = default) { m_session = session; - m_nodeId = nodeId; + m_nodeId = nodeId; m_attributeId = attributeId; ReadValueId nodeToRead = new ReadValueId(); @@ -81,25 +84,25 @@ public bool ShowDialog(Session session, NodeId nodeId, uint attributeId) ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); nodesToRead.Add(nodeToRead); - + // read current value. - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, nodesToRead, - out results, - out diagnosticInfos); + ct); + + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); - + m_value = results[0]; ValueTB.Text = Utils.Format("{0}", m_value.Value); - + // display the dialog. if (ShowDialog() != DialogResult.OK) { @@ -109,7 +112,7 @@ public bool ShowDialog(Session session, NodeId nodeId, uint attributeId) return true; } #endregion - + #region Private Methods /// /// Changes the value in the text box to the data type required for the write operation. @@ -118,7 +121,7 @@ public bool ShowDialog(Session session, NodeId nodeId, uint attributeId) private object ChangeType() { object value = m_value.Value; - + switch (m_value.WrappedValue.TypeInfo.BuiltInType) { case BuiltInType.Boolean: @@ -197,15 +200,15 @@ private object ChangeType() return value; } #endregion - + #region Event Handlers /// /// Parses the value and writes it to server. Closes the dialog if successful. /// - private void OkBTN_Click(object sender, EventArgs e) + private async void OkBTN_ClickAsync(object sender, EventArgs e) { try - { + { WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = m_nodeId; @@ -214,23 +217,22 @@ private void OkBTN_Click(object sender, EventArgs e) valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; - + WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. - StatusCodeCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.Write( + WriteResponse response = await m_session.WriteAsync( null, valuesToWrite, - out results, - out diagnosticInfos); + default); + + StatusCodeCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); - + if (StatusCode.IsBad(results[0])) { throw new ServiceResultException(results[0]); diff --git a/Workshop/HistoricalAccess/Server/HistoricalAccess Server.csproj b/Workshop/HistoricalAccess/Server/HistoricalAccess Server.csproj index db355c63b..4076566cd 100644 --- a/Workshop/HistoricalAccess/Server/HistoricalAccess Server.csproj +++ b/Workshop/HistoricalAccess/Server/HistoricalAccess Server.csproj @@ -48,6 +48,7 @@ false false + AllRules.ruleset pdbonly @@ -60,6 +61,7 @@ false false + AllRules.ruleset @@ -192,7 +194,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/HistoricalAccess/Server/HistoricalAccessNodeManager.cs b/Workshop/HistoricalAccess/Server/HistoricalAccessNodeManager.cs index afdeca1a1..cd5dc7c19 100644 --- a/Workshop/HistoricalAccess/Server/HistoricalAccessNodeManager.cs +++ b/Workshop/HistoricalAccess/Server/HistoricalAccessNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -69,13 +69,13 @@ public HistoricalAccessServerNodeManager(IServerInternal server, ApplicationConf SystemContext.NodeIdFactory = this; } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { // TBD @@ -92,7 +92,7 @@ protected override void Dispose(bool disposing) /// The new NodeId. /// /// This method is called by the NodeState.Create() method which initializes a Node from - /// the type model. During initialization a number of child nodes are created and need to + /// the type model. During initialization a number of child nodes are created and need to /// have NodeIds assigned to them. This implementation constructs NodeIds by constructing /// strings. Other implementations could assign unique integers or Guids and save the new /// Node in a dictionary for later lookup. @@ -247,7 +247,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node return handle; } - + return null; } } @@ -259,7 +259,7 @@ protected override NodeState ValidateNode( ServerSystemContext context, NodeHandle handle, IDictionary cache) - { + { // lookup in cache. NodeState target = FindNodeInCache(context, handle, cache); @@ -332,7 +332,7 @@ protected override void Read( IList values, IList errors, List nodesToValidate, - IDictionary cache) + IDictionary cache) { for (int ii = 0; ii < nodesToValidate.Count; ii++) { @@ -375,7 +375,7 @@ protected override void Read( /// /// The context. /// The item handle. - /// The monitored item. + /// The monitored item. protected override ServiceResult ReadInitialValue( ISystemContext context, NodeHandle handle, @@ -440,7 +440,7 @@ protected override ServiceResult ReadInitialValue( /// /// Called after creating a MonitoredItem. /// - protected override void OnMonitoredItemCreated(ServerSystemContext context, NodeHandle handle, MonitoredItem monitoredItem) + protected override void OnMonitoredItemCreated(ServerSystemContext context, NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem) { lock (Lock) { @@ -461,7 +461,7 @@ protected override void OnMonitoredItemCreated(ServerSystemContext context, Node { m_monitoredItems.Add(item.ArchiveItem.UniquePath, item); } - + item.SubscribeCount++; if (m_simulationTimer == null) @@ -472,9 +472,9 @@ protected override void OnMonitoredItemCreated(ServerSystemContext context, Node } } } - + /// - /// Revises an aggregate filter (may require knowledge of the variable being used). + /// Revises an aggregate filter (may require knowledge of the variable being used). /// /// The context. /// The handle. @@ -523,7 +523,7 @@ protected override StatusCode ReviseAggregateFilter( } // ensure the buffer does not get overfilled. - while (filterToUse.StartTime.AddMilliseconds(queueSize*filterToUse.ProcessingInterval) < DateTime.UtcNow) + while (filterToUse.StartTime.AddMilliseconds(queueSize * filterToUse.ProcessingInterval) < DateTime.UtcNow) { filterToUse.StartTime = filterToUse.StartTime.AddMilliseconds(filterToUse.ProcessingInterval); } @@ -576,7 +576,7 @@ private void ReviseAggregateConfiguration( /// /// Called after deleting a MonitoredItem. /// - protected override void OnMonitoredItemDeleted(ServerSystemContext context, NodeHandle handle, MonitoredItem monitoredItem) + protected override void OnMonitoredItemDeleted(ServerSystemContext context, NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem) { lock (Lock) { @@ -619,13 +619,13 @@ protected override void OnMonitoredItemDeleted(ServerSystemContext context, Node /// Reads the raw data for an item. /// protected override void HistoryReadRawModified( - ServerSystemContext context, - ReadRawModifiedDetails details, - TimestampsToReturn timestampsToReturn, - IList nodesToRead, - IList results, + ServerSystemContext context, + ReadRawModifiedDetails details, + TimestampsToReturn timestampsToReturn, + IList nodesToRead, + IList results, IList errors, - List nodesToProcess, + List nodesToProcess, IDictionary cache) { for (int ii = 0; ii < nodesToRead.Count; ii++) @@ -845,7 +845,7 @@ protected override void HistoryReadAtTime( HistoryReadResult result = results[handle.Index]; HistoryReadRequest request = null; - + try { // validate node. @@ -1029,9 +1029,9 @@ protected override void HistoryUpdateStructureData( } StatusCode error = item.UpdateAnnotations( - context, + context, annotation, - nodeToUpdate.UpdateValues[jj], + nodeToUpdate.UpdateValues[jj], nodeToUpdate.PerformInsertReplace); result.OperationResults.Add(error); @@ -1203,12 +1203,12 @@ private HistoryReadRequest CreateHistoryReadRequest( modificationInfos = new LinkedList(); } - // read history. + // read history. DataView view = item.ReadHistory(details.StartTime, details.EndTime, details.IsReadModified, handle.Node.BrowseName); int startBound = -1; int endBound = -1; - int ii = (timeFlowsBackward)?view.Count-1:0; + int ii = (timeFlowsBackward) ? view.Count - 1 : 0; while (ii >= 0 && ii < view.Count) { @@ -1221,7 +1221,7 @@ private HistoryReadRequest CreateHistoryReadRequest( { if (timeFlowsBackward) { - if ((details.StartTime != DateTime.MinValue && timestamp >= details.StartTime) || (details.StartTime == DateTime.MinValue && timestamp >= details.EndTime)) + if ((details.StartTime != DateTime.MinValue && timestamp >= details.StartTime) || (details.StartTime == DateTime.MinValue && timestamp >= details.EndTime)) { startBound = ii; @@ -1389,7 +1389,7 @@ private HistoryReadRequest CreateHistoryReadRequest( LinkedList values = new LinkedList(); - // read history. + // read history. DataView view = item.ReadHistory(details.StartTime, details.EndTime, false); int ii = (timeFlowsBackward) ? view.Count - 1 : 0; @@ -1490,7 +1490,7 @@ private HistoryReadRequest CreateHistoryReadRequest( endTime = details.ReqTimes[ii]; } } - + DataView view = item.ReadHistory(startTime, endTime, false); LinkedList values = new LinkedList(); @@ -1515,7 +1515,7 @@ private HistoryReadRequest CreateHistoryReadRequest( values.AddLast((DataValue)view[index].Row[2]); continue; } - + DataValue before = (DataValue)view[index].Row[2]; DataValue value; @@ -1570,8 +1570,8 @@ private HistoryReadRequest CreateHistoryReadRequest( /// Extracts and queues any processed values. /// private void QueueProcessedValues( - ServerSystemContext context, - IAggregateCalculator calculator, + ServerSystemContext context, + IAggregateCalculator calculator, NumericRange indexRange, QualifiedName dataEncoding, bool applyIndexRangeOrEncoding, @@ -1639,7 +1639,7 @@ private DataValue RowToDataValue( /// /// Stores a read history request. /// - private class HistoryReadRequest + private sealed class HistoryReadRequest { public byte[] ContinuationPoint; public LinkedList Values; @@ -1684,7 +1684,7 @@ private HistoryReadRequest LoadContinuationPoint( ServerSystemContext context, byte[] continuationPoint) { - Session session = context.OperationContext.Session; + ISession session = context.OperationContext.Session; if (session == null) { @@ -1708,7 +1708,7 @@ private byte[] SaveContinuationPoint( ServerSystemContext context, HistoryReadRequest request) { - Session session = context.OperationContext.Session; + ISession session = context.OperationContext.Session; if (session == null) { @@ -1761,7 +1761,7 @@ private void DoSimulation(object state) private UnderlyingSystem m_system; private HistoricalAccessServerConfiguration m_configuration; private Timer m_simulationTimer; - private Dictionary m_monitoredItems; + private Dictionary m_monitoredItems; #endregion } } diff --git a/Workshop/HistoricalAccess/Server/HistoricalAccessServer.cs b/Workshop/HistoricalAccess/Server/HistoricalAccessServer.cs index 3686993d0..bbe63aa12 100644 Binary files a/Workshop/HistoricalAccess/Server/HistoricalAccessServer.cs and b/Workshop/HistoricalAccess/Server/HistoricalAccessServer.cs differ diff --git a/Workshop/HistoricalAccess/Server/HistoricalAccessServerConfiguration.cs b/Workshop/HistoricalAccess/Server/HistoricalAccessServerConfiguration.cs index 90aa3bd5e..be82982d6 100644 --- a/Workshop/HistoricalAccess/Server/HistoricalAccessServerConfiguration.cs +++ b/Workshop/HistoricalAccess/Server/HistoricalAccessServerConfiguration.cs @@ -71,7 +71,7 @@ private void Initialize() /// /// The root of the archive. /// - [DataMember(Order = 1)] + [DataMember(Order = 1)] public string ArchiveRoot { get { return m_archiveRoot; } diff --git a/Workshop/HistoricalAccess/Server/Program.cs b/Workshop/HistoricalAccess/Server/Program.cs index a077e3e14..f475508c9 100644 --- a/Workshop/HistoricalAccess/Server/Program.cs +++ b/Workshop/HistoricalAccess/Server/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -57,7 +57,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "HistoricalAccessServer"; try @@ -80,13 +80,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // start the server. - application.Start(new HistoricalAccessServer()).Wait(); + application.StartAsync(new HistoricalAccessServer()).Wait(); // run the application interactively. Application.Run(new ServerForm(application)); @@ -98,7 +98,7 @@ static void Main() } } - class TestCase + internal sealed class TestCase { public int TestId { get; set; } public string DataPath { get; set; } @@ -111,8 +111,7 @@ class TestCase static void DoTests(bool stepped, bool treatUncertainAsBad, string dataPath, string expectedResultsPath) { - TestCase test8 = new TestCase() - { + TestCase test8 = new TestCase() { TestId = 8, DataPath = dataPath, ExpectedResultsPath = expectedResultsPath, @@ -124,8 +123,7 @@ static void DoTests(bool stepped, bool treatUncertainAsBad, string dataPath, str DoTest(test8, "..\\..\\Data\\Results8.csv"); - TestCase test9 = new TestCase() - { + TestCase test9 = new TestCase() { TestId = 9, DataPath = dataPath, ExpectedResultsPath = expectedResultsPath, @@ -137,8 +135,7 @@ static void DoTests(bool stepped, bool treatUncertainAsBad, string dataPath, str DoTest(test9, "..\\..\\Data\\Results9.csv"); - TestCase test7 = new TestCase() - { + TestCase test7 = new TestCase() { TestId = 7, DataPath = dataPath, ExpectedResultsPath = expectedResultsPath, @@ -150,8 +147,7 @@ static void DoTests(bool stepped, bool treatUncertainAsBad, string dataPath, str DoTest(test7, "..\\..\\Data\\Results7.csv"); - TestCase test6 = new TestCase() - { + TestCase test6 = new TestCase() { TestId = 6, DataPath = dataPath, ExpectedResultsPath = expectedResultsPath, @@ -163,8 +159,7 @@ static void DoTests(bool stepped, bool treatUncertainAsBad, string dataPath, str DoTest(test6, "..\\..\\Data\\Results6.csv"); - TestCase test5 = new TestCase() - { + TestCase test5 = new TestCase() { TestId = 5, DataPath = dataPath, ExpectedResultsPath = expectedResultsPath, @@ -176,8 +171,7 @@ static void DoTests(bool stepped, bool treatUncertainAsBad, string dataPath, str DoTest(test5, "..\\..\\Data\\Results5.csv"); - TestCase test1 = new TestCase() - { + TestCase test1 = new TestCase() { TestId = 1, DataPath = dataPath, ExpectedResultsPath = expectedResultsPath, @@ -189,8 +183,7 @@ static void DoTests(bool stepped, bool treatUncertainAsBad, string dataPath, str DoTest(test1, "..\\..\\Data\\Results1.csv"); - TestCase test2 = new TestCase() - { + TestCase test2 = new TestCase() { TestId = 2, DataPath = dataPath, ExpectedResultsPath = expectedResultsPath, @@ -202,8 +195,7 @@ static void DoTests(bool stepped, bool treatUncertainAsBad, string dataPath, str DoTest(test2, "..\\..\\Data\\Results2.csv"); - TestCase test3 = new TestCase() - { + TestCase test3 = new TestCase() { TestId = 3, DataPath = dataPath, ExpectedResultsPath = expectedResultsPath, @@ -215,8 +207,7 @@ static void DoTests(bool stepped, bool treatUncertainAsBad, string dataPath, str DoTest(test3, "..\\..\\Data\\Results3.csv"); - TestCase test4 = new TestCase() - { + TestCase test4 = new TestCase() { TestId = 4, DataPath = dataPath, ExpectedResultsPath = expectedResultsPath, @@ -262,11 +253,11 @@ static List GetExpectedResults(string filePath, int testId) } double time = Convert.ToDouble(fields[0], CultureInfo.InvariantCulture); - double value = Convert.ToDouble(fields[2*testId-1], CultureInfo.InvariantCulture); + double value = Convert.ToDouble(fields[2 * testId - 1], CultureInfo.InvariantCulture); StatusCode statusCode = StatusCodes.Good; - switch (fields[2*testId]) + switch (fields[2 * testId]) { case "GI": { statusCode = statusCode.SetAggregateBits(AggregateBits.Interpolated); break; } case "GC": { statusCode = statusCode.SetAggregateBits(AggregateBits.Calculated); break; } @@ -283,7 +274,7 @@ static List GetExpectedResults(string filePath, int testId) dataValue.SourceTimestamp = startTime.AddSeconds(time); dataValue.ServerTimestamp = dataValue.SourceTimestamp; results.Add(dataValue); - + if (StatusCode.IsBad(statusCode)) { dataValue.Value = null; @@ -374,7 +365,7 @@ static void DoTest(TestCase test, string filePath) } } } - + foreach (DataValue processedValue in values) { buffer.Append(processedValue.SourceTimestamp.ToString("HH:mm:ss")); diff --git a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveFolderBrowser.cs b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveFolderBrowser.cs index 1330ab566..5ff26eca6 100644 --- a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveFolderBrowser.cs +++ b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveFolderBrowser.cs @@ -81,7 +81,7 @@ public ArchiveFolderBrowser( m_stage = Stage.Begin; } #endregion - + #region Overridden Methods /// /// Returns the next reference. @@ -116,7 +116,7 @@ public override IReference Next() { return null; } - + // enumerate folders. if (m_stage == Stage.Folders) { @@ -134,7 +134,7 @@ public override IReference Next() m_stage = Stage.Items; m_position = 0; } - + // enumerate items. if (m_stage == Stage.Items) { diff --git a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveFolderState.cs b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveFolderState.cs index fd2d0a2a0..ce00d0885 100644 --- a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveFolderState.cs +++ b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveFolderState.cs @@ -45,7 +45,7 @@ public class ArchiveFolderState : Opc.Ua.FolderState /// Creates a new instance of a folder. /// public ArchiveFolderState(ISystemContext context, ArchiveFolder folder, ushort namespaceIndex) - : + : base(null) { m_archiveFolder = folder; diff --git a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItem.cs b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItem.cs index a9a9c478d..07326f3c5 100644 --- a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItem.cs +++ b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItem.cs @@ -86,7 +86,7 @@ public ArchiveItem(string uniquePath, Assembly assembly, string resourcePath) if (index > 0) { - Name = Name.Substring(index+1); + Name = Name.Substring(index + 1); } } @@ -129,7 +129,7 @@ public StreamReader OpenArchive() if (ResourceInfo.Assembly != null) { - return new StreamReader(ResourceInfo.Assembly.GetManifestResourceStream(ResourceInfo.ResourcePath), Encoding.UTF8); + return new StreamReader(ResourceInfo.Assembly.GetManifestResourceStream(ResourceInfo.ResourcePath), Encoding.UTF8); } return null; @@ -169,7 +169,7 @@ public StreamReader OpenArchive() /// The period of the simulated data. /// public double Period { get; set; } - + /// /// Whether the simulation is running. /// @@ -194,7 +194,7 @@ public StreamReader OpenArchive() /// The last the dataset was loaded from its source. /// public DateTime LastLoadTime { get; set; } - + /// /// Whether the source is perisistent and needs to be reloaded. /// @@ -224,7 +224,7 @@ private struct ResourceInfoType public string ResourcePath { get; set; } } } - + /// /// The types of simulations. /// diff --git a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItemState.cs b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItemState.cs index c028ec920..1cd65d775 100644 --- a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItemState.cs +++ b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItemState.cs @@ -46,7 +46,7 @@ public class ArchiveItemState : Opc.Ua.DataItemState /// Creates a new instance of a item. /// public ArchiveItemState(ISystemContext context, ArchiveItem item, ushort namespaceIndex) - : + : base(null) { m_archiveItem = item; @@ -166,7 +166,7 @@ public void ReloadFromSource(ISystemContext context) } } - + } /// @@ -500,7 +500,7 @@ public uint DeleteHistory(SystemContext context, DateTime startTime, DateTime en string filter = String.Format( System.Globalization.CultureInfo.InvariantCulture, - "SourceTimestamp >= #{0}# AND SourceTimestamp < #{1}#", + "SourceTimestamp >= #{0}# AND SourceTimestamp < #{1}#", startTime, endTime); @@ -569,7 +569,7 @@ private ModificationInfo GetModificationInfo(SystemContext context, HistoryUpdat return info; } - + /// /// Reads the history for the specified time range. /// @@ -610,7 +610,7 @@ public int FindValueAtOrBefore(DataView view, DateTime timestamp, bool ignoreBad int min = 0; int max = view.Count; - int position = (max-min)/2; + int position = (max - min) / 2; while (position >= 0 && position < view.Count) { @@ -620,7 +620,7 @@ public int FindValueAtOrBefore(DataView view, DateTime timestamp, bool ignoreBad if (current == timestamp) { // skip the first timestamp. - while (position > 0 && (DateTime)view[position-1].Row[0] == timestamp) + while (position > 0 && (DateTime)view[position - 1].Row[0] == timestamp) { position--; } @@ -631,13 +631,13 @@ public int FindValueAtOrBefore(DataView view, DateTime timestamp, bool ignoreBad // move up. if (current < timestamp) { - min = position+1; + min = position + 1; } // move down. if (current > timestamp) { - max = position-1; + max = position - 1; } // not found. @@ -674,7 +674,7 @@ public int FindValueAtOrBefore(DataView view, DateTime timestamp, bool ignoreBad return position; } - position = min + (max - min)/2; + position = min + (max - min) / 2; } return -1; diff --git a/Workshop/HistoricalAccess/Server/UnderlyingSystem/DataFileReader.cs b/Workshop/HistoricalAccess/Server/UnderlyingSystem/DataFileReader.cs index fcb37ce68..aa29e7226 100644 --- a/Workshop/HistoricalAccess/Server/UnderlyingSystem/DataFileReader.cs +++ b/Workshop/HistoricalAccess/Server/UnderlyingSystem/DataFileReader.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -82,7 +82,7 @@ private DataSet CreateDataSet() dataset.Tables[2].Columns.Add("Annotation", typeof(Annotation)); dataset.Tables[2].DefaultView.Sort = "SourceTimestamp"; - + return dataset; } @@ -201,7 +201,7 @@ public bool LoadConfiguration(ISystemContext context, ArchiveItem item) { return false; } - + // update the item. item.DataType = dataType; item.ValueRank = valueRank; @@ -245,7 +245,7 @@ public void CreateData(ArchiveItem item) if (dataset.Tables[0].Rows.Count > 0) { int index = dataset.Tables[0].DefaultView.Count; - DateTime endTime = (DateTime)dataset.Tables[0].DefaultView[index-1].Row[0]; + DateTime endTime = (DateTime)dataset.Tables[0].DefaultView[index - 1].Row[0]; endTime = startTime.AddMilliseconds(item.SamplingInterval); } @@ -268,7 +268,7 @@ public void CreateData(ArchiveItem item) { dataValue.Value = generator.GetRandomArray(item.DataType, false, 10, false); } - + // add record to table. DataRow row = dataset.Tables[0].NewRow(); @@ -320,7 +320,7 @@ public void LoadHistoryData(ISystemContext context, ArchiveItem item) private DataSet LoadData(ISystemContext context, DateTime baseline, StreamReader reader) { DataSet dataset = CreateDataSet(); - + ServiceMessageContext messageContext = new ServiceMessageContext(); if (context != null) @@ -362,7 +362,7 @@ private DataSet LoadData(ISystemContext context, DateTime baseline, StreamReader // ignore blank lines. line = line.Trim(); lineCount++; - + if (String.IsNullOrEmpty(line)) { continue; @@ -391,7 +391,7 @@ private DataSet LoadData(ISystemContext context, DateTime baseline, StreamReader { continue; } - + // get modification type. if (!ExtractField(lineCount, ref line, out recordType)) { @@ -554,7 +554,7 @@ private bool ExtractField(int lineCount, ref string line, out string value) value = field; return true; } - + /// /// Extracts an integer value from the line. /// @@ -664,9 +664,11 @@ private bool ExtractField(int lineCount, ref string line, ServiceMessageContext builder.AppendFormat("", valueType); builder.Append(""); - XmlDocument document = new XmlDocument(); - document.InnerXml = builder.ToString(); - + XmlDocument document = new XmlDocument { XmlResolver = null }; + using (XmlReader reader = XmlReader.Create(builder.ToString(), new XmlReaderSettings() { XmlResolver = null })) + { + document.Load(reader); + } try { XmlDecoder decoder = new XmlDecoder(document.DocumentElement, context); diff --git a/Workshop/HistoricalAccess/Tester/Aggregate Tester.csproj b/Workshop/HistoricalAccess/Tester/Aggregate Tester.csproj index 29cd8bb91..5a532cbed 100644 --- a/Workshop/HistoricalAccess/Tester/Aggregate Tester.csproj +++ b/Workshop/HistoricalAccess/Tester/Aggregate Tester.csproj @@ -45,6 +45,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -55,6 +56,7 @@ 4 false false + AllRules.ruleset @@ -142,10 +144,10 @@ - 1.5.376.244 + 1.5.377.11-preview - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/HistoricalAccess/Tester/MainForm.cs b/Workshop/HistoricalAccess/Tester/MainForm.cs index 4ff99c8ef..fb21e3b15 100644 --- a/Workshop/HistoricalAccess/Tester/MainForm.cs +++ b/Workshop/HistoricalAccess/Tester/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -442,7 +442,7 @@ private void DeleteValuesBTN_Click(object sender, EventArgs e) // clear the expected values. if (m_currentDataSet != null) { - m_currentDataSet.Values = new ValueType[0]; + m_currentDataSet.Values = Array.Empty(); AddDataSetToGrid(m_testData.GetRawValues(m_currentDataSet.DataSetName), true); UpdatesComplete(); } @@ -931,8 +931,9 @@ private void File_LoadDefaultsMI_Click(object sender, EventArgs e) { Stream istrm = Assembly.GetExecutingAssembly().GetManifestResourceStream("Quickstarts.DefaultData.xml"); XmlSerializer serializer = new XmlSerializer(typeof(TestData)); - m_testData = (TestData)serializer.Deserialize(istrm); - m_testData.ProcessedDataSets = new ProcessedDataSetType[0]; + using XmlReader reader = XmlReader.Create(istrm, new XmlReaderSettings() { XmlResolver = null }); + m_testData = (TestData)serializer.Deserialize(reader); + m_testData.ProcessedDataSets = Array.Empty(); GenerateData(); LoadData(m_testData); } @@ -1125,7 +1126,7 @@ private void File_LoadMI_Click(object sender, EventArgs e) { try { - XmlReader reader = XmlReader.Create("TestData.xml"); + using XmlReader reader = XmlReader.Create("TestData.xml", new XmlReaderSettings() { XmlResolver = null }); XmlSerializer serializer = new XmlSerializer(typeof(TestData)); m_testData = (TestData)serializer.Deserialize(reader); reader.Close(); diff --git a/Workshop/HistoricalAccess/Tester/TestData.cs b/Workshop/HistoricalAccess/Tester/TestData.cs index c4560fccf..daa3e7141 100644 --- a/Workshop/HistoricalAccess/Tester/TestData.cs +++ b/Workshop/HistoricalAccess/Tester/TestData.cs @@ -27,96 +27,101 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ -namespace Quickstarts { +namespace Quickstarts +{ using System.Xml.Serialization; - - + + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://opcfoundation.org/UA/HA/TestData")] - [System.Xml.Serialization.XmlRootAttribute(Namespace="http://opcfoundation.org/UA/HA/TestData", IsNullable=false)] - public partial class TestData { - + [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://opcfoundation.org/UA/HA/TestData")] + [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://opcfoundation.org/UA/HA/TestData", IsNullable = false)] + public partial class TestData + { + /// - [System.Xml.Serialization.XmlArrayItemAttribute("DataSet", IsNullable=false)] + [System.Xml.Serialization.XmlArrayItemAttribute("DataSet", IsNullable = false)] public RawDataSetType[] RawDataSets; - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("DataSet", IsNullable=false)] + [System.Xml.Serialization.XmlArrayItemAttribute("DataSet", IsNullable = false)] public ProcessedDataSetType[] ProcessedDataSets; } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://opcfoundation.org/UA/HA/TestData")] - public partial class RawDataSetType { - + [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://opcfoundation.org/UA/HA/TestData")] + public partial class RawDataSetType + { + /// public string Name; - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Value", IsNullable=false)] + [System.Xml.Serialization.XmlArrayItemAttribute("Value", IsNullable = false)] public ValueType[] Values; } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://opcfoundation.org/UA/HA/TestData")] - public partial class ValueType { - + [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://opcfoundation.org/UA/HA/TestData")] + public partial class ValueType + { + /// public string Timestamp; - + /// public string Value; - + /// public string Quality; - + /// public string Comment; } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")] [System.SerializableAttribute()] // [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://opcfoundation.org/UA/HA/TestData")] - public partial class ProcessedDataSetType { - + [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://opcfoundation.org/UA/HA/TestData")] + public partial class ProcessedDataSetType + { + /// public string DataSetName; - + /// public string AggregateName; - + /// public uint ProcessingInterval; - + /// public bool Stepped; - + /// public bool TreatUncertainAsBad; - + /// public ushort PercentBad; - + /// public ushort PercentGood; - + /// public bool UseSlopedExtrapolation; - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Value", IsNullable=false)] + [System.Xml.Serialization.XmlArrayItemAttribute("Value", IsNullable = false)] public ValueType[] Values; } } diff --git a/Workshop/HistoricalAccess/Tester/TestDataHelpers.cs b/Workshop/HistoricalAccess/Tester/TestDataHelpers.cs index df6683a53..73db5de22 100644 --- a/Workshop/HistoricalAccess/Tester/TestDataHelpers.cs +++ b/Workshop/HistoricalAccess/Tester/TestDataHelpers.cs @@ -156,12 +156,12 @@ public static string GetName(ProcessedDataSetType dataset) buffer.Append('/'); buffer.Append((dataset.UseSlopedExtrapolation) ? "Sloped" : "Stepped"); buffer.Append(':'); - buffer.Append((dataset.TreatUncertainAsBad)?"AsBad":"AsUncertain"); + buffer.Append((dataset.TreatUncertainAsBad) ? "AsBad" : "AsUncertain"); buffer.Append(':'); buffer.Append(dataset.PercentBad); buffer.Append('/'); buffer.Append(dataset.PercentGood); - buffer.Append("]"); + buffer.Append(']'); return buffer.ToString(); } @@ -206,7 +206,7 @@ public void RemoveDataSet(ProcessedDataSetType dataset) } int index = datasets.IndexOf(dataset); - + if (index >= 0) { datasets.RemoveAt(index); @@ -214,7 +214,7 @@ public void RemoveDataSet(ProcessedDataSetType dataset) } } } - + /// /// Returns the values in the specified raw dataset. /// @@ -232,7 +232,7 @@ public SortedDictionary GetRawValues(string dataSetName) public class DataValue { - public DataValue() { m_value = new Opc.Ua.DataValue(); } + public DataValue() { m_value = new Opc.Ua.DataValue(); } public DataValue(Opc.Ua.DataValue value) { m_value = value; } public string Comment { get; set; } public object Value { get { return m_value.Value; } set { m_value.Value = value; } } @@ -255,7 +255,7 @@ public SortedDictionary GetProcessedValues(ProcessedDataSet return ToDataValues(dataset.Values); } - return new SortedDictionary(); + return new SortedDictionary(); } /// @@ -263,7 +263,7 @@ public SortedDictionary GetProcessedValues(ProcessedDataSet /// public void UpdateProcessedValues(ProcessedDataSetType dataset, params DataValue[] newValues) { - SortedDictionary existingValues = ToDataValues(dataset.Values); + SortedDictionary existingValues = ToDataValues(dataset.Values); if (newValues != null) { @@ -315,7 +315,7 @@ public static string FormatValue(Variant value) return String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:F4}", doubleValue); } } - + return String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}", value); } @@ -379,7 +379,7 @@ public static DateTime ValidateTimestamp(object formattedValue) throw new FormatException("Timestamp must have format 'HH:MM:SS'"); } - ushort hours = Convert.ToUInt16(fields[0]); + ushort hours = Convert.ToUInt16(fields[0]); timestamp = timestamp.AddHours(hours); if (hours > 23) @@ -402,13 +402,13 @@ public static DateTime ValidateTimestamp(object formattedValue) if (seconds > 60) { - throw new FormatException("The second must be less than 60.'"); + throw new FormatException("The second must be less than 60.'"); } if (secondsWithMs.Length == 2) { - double milliseconds = Convert.ToDouble(secondsWithMs[1]); - timestamp.AddMilliseconds(milliseconds); + double milliseconds = Convert.ToDouble(secondsWithMs[1]); + timestamp.AddMilliseconds(milliseconds); } return timestamp; @@ -435,7 +435,7 @@ public static Variant ValidateValue(object formattedValue) { return new Variant(false, TypeInfo.Scalars.Boolean); } - + try { return new Variant(Convert.ToDouble(value), TypeInfo.Scalars.Double); @@ -504,7 +504,7 @@ public static StatusCode ValidateQuality(object formattedValue) case "Partial": { statusCode = statusCode.SetAggregateBits(statusCode.AggregateBits | AggregateBits.Partial); break; } case "M": { statusCode = statusCode.SetAggregateBits(statusCode.AggregateBits | AggregateBits.MultipleValues); break; } case "MultipleValues": { statusCode = statusCode.SetAggregateBits(statusCode.AggregateBits | AggregateBits.MultipleValues); break; } - + default: { throw new FormatException("Aggregate bits are not valid."); @@ -559,7 +559,7 @@ private ValueType[] ToValueTypes(SortedDictionary values) value.Value = FormatValue(dv.WrappedValue); value.Quality = FormatQuality(dv.StatusCode); value.Comment = dv.Comment; - serializedValues.Add(value); + serializedValues.Add(value); } return serializedValues.ToArray(); diff --git a/Workshop/HistoricalEvents/Client/EventListView.Designer.cs b/Workshop/HistoricalEvents/Client/EventListView.Designer.cs index c209b746b..28a18102f 100644 --- a/Workshop/HistoricalEvents/Client/EventListView.Designer.cs +++ b/Workshop/HistoricalEvents/Client/EventListView.Designer.cs @@ -97,7 +97,7 @@ private void InitializeComponent() this.DeleteHistoryMI.Name = "DeleteHistoryMI"; this.DeleteHistoryMI.Size = new System.Drawing.Size(196, 22); this.DeleteHistoryMI.Text = "Delete from Historian..."; - this.DeleteHistoryMI.Click += new System.EventHandler(this.DeleteHistoryMI_Click); + this.DeleteHistoryMI.Click += new System.EventHandler(this.DeleteHistoryMI_ClickAsync); // // EventListView // diff --git a/Workshop/HistoricalEvents/Client/EventListView.cs b/Workshop/HistoricalEvents/Client/EventListView.cs index 529155c94..cfabeac07 100644 --- a/Workshop/HistoricalEvents/Client/EventListView.cs +++ b/Workshop/HistoricalEvents/Client/EventListView.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,9 +30,11 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Drawing; using System.Data; +using System.Drawing; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; @@ -48,7 +50,7 @@ public EventListView() } #region Private Methods - private Session m_session; + private ISession m_session; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private FilterDeclaration m_filter; @@ -60,26 +62,23 @@ public EventListView() /// /// Whether the control subscribes for new events. /// - public bool IsSubscribed + public bool IsSubscribed => m_isSubscribed; + + public async Task SetSubscribedAsync(bool subscribed, CancellationToken ct = default) { - get { return m_isSubscribed; } - - set + if (m_isSubscribed != subscribed) { - if (m_isSubscribed != value) - { - m_isSubscribed = value; + m_isSubscribed = subscribed; - if (m_session != null) + if (m_session != null) + { + if (m_isSubscribed) { - if (m_isSubscribed) - { - CreateSubscription(); - } - else - { - DeleteSubscription(); - } + await CreateSubscriptionAsync(ct); + } + else + { + await DeleteSubscriptionAsync(ct); } } } @@ -104,7 +103,7 @@ public FilterDeclaration Filter /// /// Changes the session. /// - public void ChangeSession(Session session, bool fetchRecent) + public async Task ChangeSessionAsync(ISession session, bool fetchRecent, CancellationToken ct = default) { if (Object.ReferenceEquals(session, m_session)) { @@ -113,7 +112,7 @@ public void ChangeSession(Session session, bool fetchRecent) if (m_session != null) { - DeleteSubscription(); + await DeleteSubscriptionAsync(ct); m_session = null; } @@ -122,22 +121,22 @@ public void ChangeSession(Session session, bool fetchRecent) if (m_session != null && m_isSubscribed) { - CreateSubscription(); + await CreateSubscriptionAsync(ct); if (fetchRecent) { - ReadRecentHistory(); + await ReadRecentHistoryAsync(ct); } } } - + /// /// Updates the control after the session has reconnected. /// - public void SessionReconnected(Session session) + public void SessionReconnected(ISession session) { m_session = session; - + if (m_isSubscribed) { foreach (Subscription subscription in m_session.Subscriptions) @@ -161,14 +160,14 @@ public void SessionReconnected(Session session) /// /// Changes the area monitored by the control. /// - public void ChangeArea(NodeId areaId, bool fetchRecent) + public async Task ChangeAreaAsync(NodeId areaId, bool fetchRecent, CancellationToken ct = default) { m_areaId = areaId; EventsLV.Items.Clear(); if (fetchRecent) { - ReadRecentHistory(); + await ReadRecentHistoryAsync(ct); } if (m_subscription != null) @@ -180,16 +179,16 @@ public void ChangeArea(NodeId areaId, bool fetchRecent) m_subscription.RemoveItem(m_monitoredItem); m_monitoredItem = monitoredItem; - monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); + monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); } } /// /// Changes the filter used to select the events. /// - public void ChangeFilter(FilterDeclaration filter, bool fetchRecent) + public async Task ChangeFilterAsync(FilterDeclaration filter, bool fetchRecent, CancellationToken ct = default) { m_filter = filter; EventsLV.Items.Clear(); @@ -227,14 +226,14 @@ public void ChangeFilter(FilterDeclaration filter, bool fetchRecent) // fetch recent history. if (fetchRecent) { - ReadRecentHistory(); + await ReadRecentHistoryAsync(ct); } // update subscription. if (m_subscription != null) { m_monitoredItem.Filter = m_filter.GetFilter(); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); } } @@ -255,11 +254,11 @@ public void ClearEventHistory() /// /// Adds the event history to the control. /// - public void AddEventHistory(HistoryEvent events) + public async Task AddEventHistoryAsync(HistoryEvent events, CancellationToken ct = default) { for (int ii = 0; ii < events.Events.Count; ii++) { - ListViewItem item = CreateListItem(m_filter, events.Events[ii].EventFields); + ListViewItem item = await CreateListItemAsync(m_filter, events.Events[ii].EventFields, ct); EventsLV.Items.Add(item); } @@ -275,7 +274,7 @@ public void AddEventHistory(HistoryEvent events) /// /// Creates the subscription. /// - private void CreateSubscription() + private async Task CreateSubscriptionAsync(CancellationToken ct = default) { m_subscription = new Subscription(); m_subscription.Handle = this; @@ -288,7 +287,7 @@ private void CreateSubscription() m_subscription.TimestampsToReturn = TimestampsToReturn.Both; m_session.AddSubscription(m_subscription); - m_subscription.Create(); + await m_subscription.CreateAsync(ct); m_monitoredItem = new MonitoredItem(); m_monitoredItem.StartNodeId = m_areaId; @@ -297,23 +296,23 @@ private void CreateSubscription() m_monitoredItem.QueueSize = 1000; m_monitoredItem.DiscardOldest = true; - ChangeFilter(m_filter, false); + await ChangeFilterAsync(m_filter, false, ct); - m_monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); + m_monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); m_subscription.AddItem(m_monitoredItem); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); } /// /// Deletes the subscription. /// - private void DeleteSubscription() + private async Task DeleteSubscriptionAsync(CancellationToken ct = default) { if (m_subscription != null) { - m_subscription.Delete(true); - m_session.RemoveSubscription(m_subscription); + await m_subscription.DeleteAsync(true, ct); + await m_session.RemoveSubscriptionAsync(m_subscription, ct); m_subscription = null; m_monitoredItem = null; } @@ -322,14 +321,14 @@ private void DeleteSubscription() /// /// Creates list item for an event. /// - private ListViewItem CreateListItem(FilterDeclaration filter, VariantCollection fieldValues) + private async Task CreateListItemAsync(FilterDeclaration filter, VariantCollection fieldValues, CancellationToken ct = default) { ListViewItem item = new ListViewItem(); item.Tag = fieldValues; for (int ii = 1; ii < fieldValues.Count; ii++) { - if (!filter.Fields[ii-1].DisplayInList) + if (!filter.Fields[ii - 1].DisplayInList) { continue; } @@ -345,7 +344,7 @@ private ListViewItem CreateListItem(FilterDeclaration filter, VariantCollection // display the name of a node instead of the node id. else if (fieldValues[ii].TypeInfo.BuiltInType == BuiltInType.NodeId) { - INode node = m_session.NodeCache.Find((NodeId)fieldValues[ii].Value); + INode node = await m_session.NodeCache.FindAsync((NodeId)fieldValues[ii].Value, ct); if (node != null) { @@ -358,7 +357,7 @@ private ListViewItem CreateListItem(FilterDeclaration filter, VariantCollection { DateTime value = (DateTime)fieldValues[ii].Value; - if (m_filter.Fields[ii-1].InstanceDeclaration.DisplayName.Contains("Time")) + if (m_filter.Fields[ii - 1].InstanceDeclaration.DisplayName.Contains("Time")) { text = value.ToLocalTime().ToString("HH:mm:ss.fff"); } @@ -390,13 +389,13 @@ private ListViewItem CreateListItem(FilterDeclaration filter, VariantCollection } /// - /// Updates the display with a new value for a monitored variable. + /// Updates the display with a new value for a monitored variable. /// - private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) + private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (this.InvokeRequired) { - this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_Notification), monitoredItem, e); + this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync), monitoredItem, e); return; } @@ -417,13 +416,13 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt } // check if the filter has changed. - if (notification.EventFields.Count != m_filter.Fields.Count+1) + if (notification.EventFields.Count != m_filter.Fields.Count + 1) { return; } // create an item and add to top of list. - ListViewItem item = CreateListItem(m_filter, notification.EventFields); + ListViewItem item = await CreateListItemAsync(m_filter, notification.EventFields); EventsLV.Items.Insert(0, item); // adjust the width of the columns. @@ -437,17 +436,17 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt ClientUtils.HandleException(this.Text, exception); } } - + /// /// Fetches the recent history. /// - private void ReadRecentHistory() + private async Task ReadRecentHistoryAsync(CancellationToken ct = default) { // check if session is active. if (m_session != null) { // check if area supports history. - IObject area = m_session.NodeCache.Find(m_areaId) as IObject; + IObject area = await m_session.NodeCache.FindAsync(m_areaId, ct) as IObject; if (area != null && ((area.EventNotifier & EventNotifiers.HistoryRead) != 0)) { @@ -459,7 +458,7 @@ private void ReadRecentHistory() details.Filter = m_filter.GetFilter(); // read the history. - ReadHistory(details, m_areaId); + await ReadHistoryAsync(details, m_areaId, ct); } } } @@ -467,24 +466,23 @@ private void ReadRecentHistory() /// /// Fetches the recent history. /// - private void ReadHistory(ReadEventDetails details, NodeId areaId) + private async Task ReadHistoryAsync(ReadEventDetails details, NodeId areaId, CancellationToken ct = default) { HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = areaId; nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Neither, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -495,28 +493,30 @@ private void ReadHistory(ReadEventDetails details, NodeId areaId) } HistoryEvent events = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryEvent; - AddEventHistory(events); + await AddEventHistoryAsync(events, ct); // release continuation points. if (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; - m_session.HistoryRead( + response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Neither, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; } } /// /// Deletes the recent history. /// - private void DeleteHistory(NodeId areaId, List events, FilterDeclaration filter) + private async Task DeleteHistoryAsync(NodeId areaId, List events, FilterDeclaration filter, CancellationToken ct = default) { // find the event id. int index = 0; @@ -557,14 +557,13 @@ private void DeleteHistory(NodeId areaId, List events, Filter ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection(); nodesToUpdate.Add(new ExtensionObject(details)); - HistoryUpdateResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryUpdate( + HistoryUpdateResponse response = await m_session.HistoryUpdateAsync( null, nodesToUpdate, - out results, - out diagnosticInfos); + ct); + + HistoryUpdateResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, nodesToUpdate); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToUpdate); @@ -591,7 +590,7 @@ private void DeleteHistory(NodeId areaId, List events, Filter if (count > 0) { throw ServiceResultException.Create( - StatusCodes.BadEventIdUnknown, + StatusCodes.BadEventIdUnknown, "Error deleting events. Only {0} of {1} deletes succeeded.", events.Count - count, events.Count); @@ -621,7 +620,7 @@ private void ViewDetailsMI_Click(object sender, EventArgs e) } } - private void DeleteHistoryMI_Click(object sender, EventArgs e) + private async void DeleteHistoryMI_ClickAsync(object sender, EventArgs e) { try { @@ -644,7 +643,7 @@ private void DeleteHistoryMI_Click(object sender, EventArgs e) if (events.Count > 0) { - DeleteHistory(m_areaId, events, m_filter); + await DeleteHistoryAsync(m_areaId, events, m_filter); foreach (ListViewItem item in EventsLV.SelectedItems) { diff --git a/Workshop/HistoricalEvents/Client/HistoricalEvents Client.csproj b/Workshop/HistoricalEvents/Client/HistoricalEvents Client.csproj index 8f7664af2..8cc4ae20a 100644 --- a/Workshop/HistoricalEvents/Client/HistoricalEvents Client.csproj +++ b/Workshop/HistoricalEvents/Client/HistoricalEvents Client.csproj @@ -45,6 +45,7 @@ prompt 4 false + AllRules.ruleset pdbonly @@ -54,6 +55,7 @@ prompt 4 false + AllRules.ruleset @@ -187,7 +189,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/HistoricalEvents/Client/MainForm.Designer.cs b/Workshop/HistoricalEvents/Client/MainForm.Designer.cs index 286e518ba..17b22fd28 100644 --- a/Workshop/HistoricalEvents/Client/MainForm.Designer.cs +++ b/Workshop/HistoricalEvents/Client/MainForm.Designer.cs @@ -184,7 +184,7 @@ private void InitializeComponent() this.Server_SelectLocaleMI.Name = "Server_SelectLocaleMI"; this.Server_SelectLocaleMI.Size = new System.Drawing.Size(148, 22); this.Server_SelectLocaleMI.Text = "Select Locale..."; - this.Server_SelectLocaleMI.Click += new System.EventHandler(this.Server_SetLocaleMI_Click); + this.Server_SelectLocaleMI.Click += new System.EventHandler(this.Server_SetLocaleMI_ClickAsync); // // EventsMI // @@ -208,7 +208,7 @@ private void InitializeComponent() this.Events_EnableSubscriptionMI.Name = "Events_EnableSubscriptionMI"; this.Events_EnableSubscriptionMI.Size = new System.Drawing.Size(176, 22); this.Events_EnableSubscriptionMI.Text = "Enable Subscription"; - this.Events_EnableSubscriptionMI.CheckedChanged += new System.EventHandler(this.Events_EnableSubscriptionMI_CheckedChanged); + this.Events_EnableSubscriptionMI.CheckedChanged += new System.EventHandler(this.Events_EnableSubscriptionMI_CheckedChangedAsync); // // toolStripSeparator1 // @@ -220,21 +220,21 @@ private void InitializeComponent() this.Events_SelectEventTypeMI.Name = "Events_SelectEventTypeMI"; this.Events_SelectEventTypeMI.Size = new System.Drawing.Size(176, 22); this.Events_SelectEventTypeMI.Text = "Select Event Type..."; - this.Events_SelectEventTypeMI.Click += new System.EventHandler(this.Events_SelectEventTypeMI_Click); + this.Events_SelectEventTypeMI.Click += new System.EventHandler(this.Events_SelectEventTypeMI_ClickAsync); // // Events_SelectEventAreaMI // this.Events_SelectEventAreaMI.Name = "Events_SelectEventAreaMI"; this.Events_SelectEventAreaMI.Size = new System.Drawing.Size(176, 22); this.Events_SelectEventAreaMI.Text = "Select Event Area..."; - this.Events_SelectEventAreaMI.Click += new System.EventHandler(this.Events_SelectEventAreaMI_Click); + this.Events_SelectEventAreaMI.Click += new System.EventHandler(this.Events_SelectEventAreaMI_ClickAsync); // // Events_ModifyEventFilterMI // this.Events_ModifyEventFilterMI.Name = "Events_ModifyEventFilterMI"; this.Events_ModifyEventFilterMI.Size = new System.Drawing.Size(176, 22); this.Events_ModifyEventFilterMI.Text = "Modify Event Filter..."; - this.Events_ModifyEventFilterMI.Click += new System.EventHandler(this.Events_ModifyEventFilterMI_Click); + this.Events_ModifyEventFilterMI.Click += new System.EventHandler(this.Events_ModifyEventFilterMI_ClickAsync); // // toolStripSeparator2 // @@ -246,7 +246,7 @@ private void InitializeComponent() this.Events_EditEventHistoryMI.Name = "Events_EditEventHistoryMI"; this.Events_EditEventHistoryMI.Size = new System.Drawing.Size(176, 22); this.Events_EditEventHistoryMI.Text = "Edit Event History..."; - this.Events_EditEventHistoryMI.Click += new System.EventHandler(this.Events_EditEventHistoryMI_Click); + this.Events_EditEventHistoryMI.Click += new System.EventHandler(this.Events_EditEventHistoryMI_ClickAsync); // // HelpMI // @@ -278,7 +278,6 @@ private void InitializeComponent() // EventsLV // this.EventsLV.Dock = System.Windows.Forms.DockStyle.Fill; - this.EventsLV.IsSubscribed = false; this.EventsLV.Location = new System.Drawing.Point(2, 25); this.EventsLV.Name = "EventsLV"; this.EventsLV.Size = new System.Drawing.Size(704, 184); @@ -301,7 +300,7 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 3; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); // // StatusBar diff --git a/Workshop/HistoricalEvents/Client/MainForm.cs b/Workshop/HistoricalEvents/Client/MainForm.cs index dad05a230..bb9b72269 100644 --- a/Workshop/HistoricalEvents/Client/MainForm.cs +++ b/Workshop/HistoricalEvents/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,7 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; namespace Quickstarts.HistoricalEvents.Client { @@ -53,7 +54,7 @@ private MainForm() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } - + /// /// Creates a form which uses the specified client configuration. /// @@ -68,10 +69,10 @@ public MainForm(ApplicationConfiguration configuration) this.Text = m_configuration.ApplicationName; } #endregion - + #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private bool m_connectedOnce; #endregion @@ -83,10 +84,10 @@ public MainForm(ApplicationConfiguration configuration) /// Connects to a server. /// private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) - { + { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -127,7 +128,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -136,19 +137,19 @@ private void Server_ConnectComplete(object sender, EventArgs e) // set a suitable initial state. if (m_session != null && !m_connectedOnce) { - EventsLV.IsSubscribed = false; - EventsLV.ChangeArea(ExpandedNodeId.ToNodeId(ObjectIds.Plaforms, m_session.NamespaceUris), true); + await EventsLV.SetSubscribedAsync(false); + await EventsLV.ChangeAreaAsync(ExpandedNodeId.ToNodeId(ObjectIds.Plaforms, m_session.NamespaceUris), true); TypeDeclaration type = new TypeDeclaration(); type.NodeId = ExpandedNodeId.ToNodeId(ObjectTypeIds.WellTestReportType, m_session.NamespaceUris); - type.Declarations = ModelUtils.CollectInstanceDeclarationsForType(m_session, type.NodeId); + type.Declarations = await ModelUtils.CollectInstanceDeclarationsForTypeAsync(m_session, type.NodeId); - EventsLV.ChangeFilter(new FilterDeclaration(type, null), true); + await EventsLV.ChangeFilterAsync(new FilterDeclaration(type, null), true); m_connectedOnce = true; } - EventsLV.IsSubscribed = Events_EnableSubscriptionMI.Checked; - EventsLV.ChangeSession(m_session, true); + await EventsLV.SetSubscribedAsync(Events_EnableSubscriptionMI.Checked); + await EventsLV.ChangeSessionAsync(m_session, true); } catch (Exception exception) { @@ -180,7 +181,7 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) ConnectServerCTRL.Disconnect(); } - private void Events_SelectEventTypeMI_Click(object sender, EventArgs e) + private async void Events_SelectEventTypeMI_ClickAsync(object sender, EventArgs e) { try { @@ -189,14 +190,14 @@ private void Events_SelectEventTypeMI_Click(object sender, EventArgs e) return; } - TypeDeclaration type = new SelectTypeDlg().ShowDialog(m_session, Opc.Ua.ObjectTypeIds.BaseEventType, "Select Event Type"); + TypeDeclaration type = await new SelectTypeDlg().ShowDialogAsync(m_session, Opc.Ua.ObjectTypeIds.BaseEventType, "Select Event Type"); if (type == null) { return; } - EventsLV.ChangeFilter(new FilterDeclaration(type, EventsLV.Filter), true); + await EventsLV.ChangeFilterAsync(new FilterDeclaration(type, EventsLV.Filter), true); } catch (Exception exception) { @@ -204,7 +205,7 @@ private void Events_SelectEventTypeMI_Click(object sender, EventArgs e) } } - private void Events_ModifyEventFilterMI_Click(object sender, EventArgs e) + private async void Events_ModifyEventFilterMI_ClickAsync(object sender, EventArgs e) { try { @@ -218,7 +219,7 @@ private void Events_ModifyEventFilterMI_Click(object sender, EventArgs e) return; } - EventsLV.ChangeFilter(EventsLV.Filter, true); + await EventsLV.ChangeFilterAsync(EventsLV.Filter, true); } catch (Exception exception) { @@ -226,7 +227,7 @@ private void Events_ModifyEventFilterMI_Click(object sender, EventArgs e) } } - private void Events_SelectEventAreaMI_Click(object sender, EventArgs e) + private async void Events_SelectEventAreaMI_ClickAsync(object sender, EventArgs e) { try { @@ -235,14 +236,14 @@ private void Events_SelectEventAreaMI_Click(object sender, EventArgs e) return; } - NodeId areaId = new SelectNodeDlg().ShowDialog(m_session, Opc.Ua.ObjectIds.Server, "Select Event Area", Opc.Ua.ReferenceTypeIds.HasEventSource); + NodeId areaId = await new SelectNodeDlg().ShowDialogAsync(m_session, Opc.Ua.ObjectIds.Server, "Select Event Area", default, Opc.Ua.ReferenceTypeIds.HasEventSource); if (areaId == null) { return; } - EventsLV.ChangeArea(areaId, true); + await EventsLV.ChangeAreaAsync(areaId, true); } catch (Exception exception) { @@ -250,11 +251,11 @@ private void Events_SelectEventAreaMI_Click(object sender, EventArgs e) } } - private void Events_EnableSubscriptionMI_CheckedChanged(object sender, EventArgs e) + private async void Events_EnableSubscriptionMI_CheckedChangedAsync(object sender, EventArgs e) { try { - EventsLV.IsSubscribed = Events_EnableSubscriptionMI.Checked; + await EventsLV.SetSubscribedAsync(Events_EnableSubscriptionMI.Checked); } catch (Exception exception) { @@ -262,7 +263,7 @@ private void Events_EnableSubscriptionMI_CheckedChanged(object sender, EventArgs } } - private void Events_EditEventHistoryMI_Click(object sender, EventArgs e) + private async void Events_EditEventHistoryMI_ClickAsync(object sender, EventArgs e) { try { @@ -271,7 +272,7 @@ private void Events_EditEventHistoryMI_Click(object sender, EventArgs e) return; } - new ReadEventHistoryDlg().ShowDialog(m_session, EventsLV.AreaId, new FilterDeclaration(EventsLV.Filter)); + await new ReadEventHistoryDlg().ShowDialogAsync(m_session, EventsLV.AreaId, new FilterDeclaration(EventsLV.Filter)); } catch (Exception exception) { @@ -282,7 +283,7 @@ private void Events_EditEventHistoryMI_Click(object sender, EventArgs e) /// /// Sets the locale to use. /// - private void Server_SetLocaleMI_Click(object sender, EventArgs e) + private async void Server_SetLocaleMI_ClickAsync(object sender, EventArgs e) { try { @@ -291,7 +292,7 @@ private void Server_SetLocaleMI_Click(object sender, EventArgs e) return; } - string locale = new SelectLocaleDlg().ShowDialog(m_session); + string locale = await new SelectLocaleDlg().ShowDialogAsync(m_session); if (locale == null) { @@ -320,7 +321,7 @@ private void Help_ContentsMI_Click(object sender, EventArgs e) { try { - System.Diagnostics.Process.Start( Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\haeventsclientoverview.htm"); + System.Diagnostics.Process.Start(Path.GetDirectoryName(Application.ExecutablePath) + "\\WebHelp\\haeventsclientoverview.htm"); } catch (Exception ex) { diff --git a/Workshop/HistoricalEvents/Client/ModifyFilterDlg.cs b/Workshop/HistoricalEvents/Client/ModifyFilterDlg.cs index 1ef2d64b6..b8517b635 100644 --- a/Workshop/HistoricalEvents/Client/ModifyFilterDlg.cs +++ b/Workshop/HistoricalEvents/Client/ModifyFilterDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -51,7 +51,7 @@ public ModifyFilterDlg() InitializeComponent(); } #endregion - + #region Private Fields private FilterDeclaration m_filter; @@ -72,7 +72,7 @@ public ModifyFilterDlg() /// /// Stores the state of FilterDeclarationField element. /// - private class FilterItem + private sealed class FilterItem { public FilterItem(FilterDeclarationField declaration) { @@ -82,7 +82,7 @@ public FilterItem(FilterDeclarationField declaration) FilterValue = declaration.FilterValue; Declaration = declaration; } - + public bool DisplayInList; public bool FilterEnabled; public FilterOperator FilterOperator; @@ -90,13 +90,11 @@ public FilterItem(FilterDeclarationField declaration) public FilterDeclarationField Declaration; } #endregion - + #region Public Interface /// /// Displays the available areas in a tree view. /// - /// The session. - /// public bool ShowDialog(FilterDeclaration filter) { m_filter = filter; @@ -133,7 +131,7 @@ public bool ShowDialog(FilterDeclaration filter) return true; } #endregion - + #region Private Methods /// /// Displays an X for a boolean value. @@ -158,7 +156,7 @@ private void Populate() for (int ii = 0; ii < m_filter.Fields.Count; ii++) { FilterDeclarationField field = m_filter.Fields[ii]; - + ListViewItem item = new ListViewItem(field.InstanceDeclaration.DisplayPath); item.SubItems.Add(ToCheck(field.DisplayInList)); @@ -168,7 +166,7 @@ private void Populate() item.SubItems.Add(field.InstanceDeclaration.DataTypeDisplayText); item.Tag = new FilterItem(field); - + EventFieldsLV.Items.Add(item); } @@ -176,7 +174,7 @@ private void Populate() for (int ii = 0; ii < EventFieldsLV.Columns.Count; ii++) { EventFieldsLV.Columns[ii].Width = -2; - } + } } #endregion @@ -189,7 +187,7 @@ private void PopupMenu_Opening(object sender, System.ComponentModel.CancelEventA if (EventFieldsLV.SelectedItems.Count > 0) { FilterItem field = EventFieldsLV.SelectedItems[0].Tag as FilterItem; - + if (field != null) { displayInList = (field.DisplayInList) ? CheckState.Checked : CheckState.Unchecked; diff --git a/Workshop/HistoricalEvents/Client/Program.cs b/Workshop/HistoricalEvents/Client/Program.cs index ae52224c9..b1c28a901 100644 --- a/Workshop/HistoricalEvents/Client/Program.cs +++ b/Workshop/HistoricalEvents/Client/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "HistoricalEventsClient"; try @@ -63,10 +63,10 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/HistoricalEvents/Client/Quickstarts.HistoricalEvents.Classes.cs b/Workshop/HistoricalEvents/Client/Quickstarts.HistoricalEvents.Classes.cs index c3bd73139..b2183f6c2 100644 --- a/Workshop/HistoricalEvents/Client/Quickstarts.HistoricalEvents.Classes.cs +++ b/Workshop/HistoricalEvents/Client/Quickstarts.HistoricalEvents.Classes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.HistoricalEvents { #region WellTestReportState Class - #if (!OPCUA_EXCLUDE_WellTestReportState) +#if (!OPCUA_EXCLUDE_WellTestReportState) /// /// Stores an instance of the WellTestReportType ObjectType. /// @@ -61,7 +61,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.HistoricalEvents.ObjectTypes.WellTestReportType, Quickstarts.HistoricalEvents.Namespaces.HistoricalEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -110,7 +110,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "YXNvbiBmb3IgdGhlIHdlbGwgdGVzdDogaW5pdGlhbCwgcGVyaW9kaWMsIHJldmlzaW9uLgAuAEQIAQAA" + "AAz/////AQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -343,11 +343,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_testReason; #endregion } - #endif +#endif #endregion #region FluidLevelTestReportState Class - #if (!OPCUA_EXCLUDE_FluidLevelTestReportState) +#if (!OPCUA_EXCLUDE_FluidLevelTestReportState) /// /// Stores an instance of the FluidLevelTestReportType ObjectType. /// @@ -371,7 +371,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.HistoricalEvents.ObjectTypes.FluidLevelTestReportType, Quickstarts.HistoricalEvents.Namespaces.HistoricalEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -427,7 +427,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "ZHVjdGVkIHRoZSB0ZXN0LiBUaGlzIGlzIGdlbmVyYWxseSBhIHBlcnNvbi4ALgBEGwEAAAAM/////wEB" + "/////wAAAAA="; #endregion - #endif +#endif #endregion #region Public Properties @@ -568,11 +568,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_testedBy; #endregion } - #endif +#endif #endregion #region InjectionTestReportState Class - #if (!OPCUA_EXCLUDE_InjectionTestReportState) +#if (!OPCUA_EXCLUDE_InjectionTestReportState) /// /// Stores an instance of the InjectionTestReportType ObjectType. /// @@ -596,7 +596,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.HistoricalEvents.ObjectTypes.InjectionTestReportType, Quickstarts.HistoricalEvents.Namespaces.HistoricalEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -650,7 +650,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "ADVgiQoCAAAAAQANAAAASW5qZWN0ZWRGbHVpZAEBLgEDAAAAACMAAABUaGUgZmx1aWQgdGhhdCBpcyBi" + "ZWluZyBpbmplY3RlZC4gLgAuAEQuAQAAAAz/////AQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -791,11 +791,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_injectedFluid; #endregion } - #endif +#endif #endregion #region WellState Class - #if (!OPCUA_EXCLUDE_WellState) +#if (!OPCUA_EXCLUDE_WellState) /// /// Stores an instance of the WellType ObjectType. /// @@ -819,7 +819,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.HistoricalEvents.ObjectTypes.WellType, Quickstarts.HistoricalEvents.Namespaces.HistoricalEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -852,7 +852,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AQAAADUAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvUXVpY2tzdGFydHMvSGlzdG9yaWNhbEV2ZW50" + "c/////8EYIACAQAAAAEAEAAAAFdlbGxUeXBlSW5zdGFuY2UBATQBAQE0ATQBAAD/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -864,6 +864,6 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.Designer.cs b/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.Designer.cs index 9d296b85f..0c79e37d2 100644 --- a/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.Designer.cs +++ b/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.Designer.cs @@ -135,7 +135,6 @@ private void InitializeComponent() // ResultsLV // this.ResultsLV.Dock = System.Windows.Forms.DockStyle.Fill; - this.ResultsLV.IsSubscribed = false; this.ResultsLV.Location = new System.Drawing.Point(260, 0); this.ResultsLV.Name = "ResultsLV"; this.ResultsLV.Size = new System.Drawing.Size(595, 410); @@ -180,7 +179,7 @@ private void InitializeComponent() this.EventFilterBTN.TabIndex = 8; this.EventFilterBTN.Text = "..."; this.EventFilterBTN.UseVisualStyleBackColor = true; - this.EventFilterBTN.Click += new System.EventHandler(this.EventFilterBTN_Click); + this.EventFilterBTN.Click += new System.EventHandler(this.EventFilterBTN_ClickAsync); // // EventFilterTB // @@ -233,7 +232,7 @@ private void InitializeComponent() this.EventTypeBTN.TabIndex = 5; this.EventTypeBTN.Text = "..."; this.EventTypeBTN.UseVisualStyleBackColor = true; - this.EventTypeBTN.Click += new System.EventHandler(this.EventTypeBTN_Click); + this.EventTypeBTN.Click += new System.EventHandler(this.EventTypeBTN_ClickAsync); // // EventAreaLB // @@ -262,7 +261,7 @@ private void InitializeComponent() this.EventAreaBTN.TabIndex = 2; this.EventAreaBTN.Text = "..."; this.EventAreaBTN.UseVisualStyleBackColor = true; - this.EventAreaBTN.Click += new System.EventHandler(this.EventAreaBTN_Click); + this.EventAreaBTN.Click += new System.EventHandler(this.EventAreaBTN_ClickAsync); // // StopBTN // @@ -273,7 +272,7 @@ private void InitializeComponent() this.StopBTN.TabIndex = 19; this.StopBTN.Text = "Stop"; this.StopBTN.UseVisualStyleBackColor = true; - this.StopBTN.Click += new System.EventHandler(this.StopBTN_Click); + this.StopBTN.Click += new System.EventHandler(this.StopBTN_ClickAsync); // // NextBTN // @@ -283,7 +282,7 @@ private void InitializeComponent() this.NextBTN.TabIndex = 18; this.NextBTN.Text = "Next"; this.NextBTN.UseVisualStyleBackColor = true; - this.NextBTN.Click += new System.EventHandler(this.NextBTN_Click); + this.NextBTN.Click += new System.EventHandler(this.NextBTN_ClickAsync); // // GoBTN // @@ -293,7 +292,7 @@ private void InitializeComponent() this.GoBTN.TabIndex = 17; this.GoBTN.Text = "Go"; this.GoBTN.UseVisualStyleBackColor = true; - this.GoBTN.Click += new System.EventHandler(this.GoBTN_Click); + this.GoBTN.Click += new System.EventHandler(this.GoBTN_ClickAsync); // // MaxReturnValuesCK // diff --git a/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.cs b/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.cs index 1cd9adc58..b7c936aaf 100644 --- a/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.cs +++ b/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -31,11 +31,12 @@ using System.Collections.Generic; using System.ComponentModel; using System.Drawing; -using System.Text; -using System.Windows.Forms; using System.Reflection; using System.Security.Cryptography.X509Certificates; - +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -43,7 +44,7 @@ namespace Quickstarts.HistoricalEvents.Client { /// - /// Displays a + /// Displays a /// public partial class ReadEventHistoryDlg : Form { @@ -58,7 +59,7 @@ public ReadEventHistoryDlg() #endregion #region Private Fields - private Session m_session; + private ISession m_session; private NodeId m_areaId; private FilterDeclaration m_filter; private ReadEventDetails m_details; @@ -69,33 +70,33 @@ public ReadEventHistoryDlg() /// /// Displays the dialog. /// - public bool ShowDialog(Session session, NodeId areaId, FilterDeclaration filter) + public async Task ShowDialogAsync(ISession session, NodeId areaId, FilterDeclaration filter, CancellationToken ct = default) { m_session = session; m_areaId = areaId; m_filter = filter; - EventAreaTB.Text = session.NodeCache.GetDisplayText(m_areaId); - EventTypeTB.Text = session.NodeCache.GetDisplayText(filter.EventTypeId); + EventAreaTB.Text = await session.NodeCache.GetDisplayTextAsync(m_areaId, ct); + EventTypeTB.Text = await session.NodeCache.GetDisplayTextAsync(filter.EventTypeId, ct); EventFilterTB.Text = GetFilterFields(m_filter); - ResultsLV.IsSubscribed = false; - ResultsLV.ChangeSession(session, false); - ResultsLV.ChangeArea(areaId, false); - ResultsLV.ChangeFilter(filter, false); - + await ResultsLV.SetSubscribedAsync(false, ct); + await ResultsLV.ChangeSessionAsync(session, false, ct); + await ResultsLV.ChangeAreaAsync(areaId, false, ct); + await ResultsLV.ChangeFilterAsync(filter, false, ct); + // get the beginning of data. DateTime startTime; try { - startTime = ReadFirstDate().ToLocalTime(); + startTime = (await ReadFirstDateAsync(ct)).ToLocalTime(); } catch (Exception) { startTime = new DateTime(2000, 1, 1); } - + StartTimeDP.Value = startTime; StartTimeCK.Checked = true; EndTimeDP.Value = DateTime.Now; @@ -110,7 +111,7 @@ public bool ShowDialog(Session session, NodeId areaId, FilterDeclaration filter) { return false; } - + return true; } #endregion @@ -142,24 +143,23 @@ private string GetFilterFields(FilterDeclaration filter) /// /// Releases any continuation points. /// - private void ReleaseContinuationPoints() + private async Task ReleaseContinuationPointsAsync(CancellationToken ct = default) { if (m_details != null) { HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(m_nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(m_details), TimestampsToReturn.Neither, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -175,7 +175,7 @@ private void ReleaseContinuationPoints() /// /// Returns the UTC timestamp of the first event in the archive. /// - private DateTime ReadFirstDate() + private async Task ReadFirstDateAsync(CancellationToken ct = default) { // read the time of the first event in the archive. ReadEventDetails details = new ReadEventDetails(); @@ -191,17 +191,16 @@ private DateTime ReadFirstDate() HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Neither, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -219,14 +218,16 @@ private DateTime ReadFirstDate() { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; - m_session.HistoryRead( + response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Neither, true, nodesToRead, - out results, - out diagnosticInfos); + ct); + + results = response.Results; + diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -253,7 +254,7 @@ private DateTime ReadFirstDate() /// /// Starts a new read operation. /// - private void ReadFirst() + private async Task ReadFirstAsync(CancellationToken ct = default) { ResultsLV.ClearEventHistory(); @@ -278,33 +279,33 @@ private void ReadFirst() { details.NumValuesPerNode = (uint)MaxReturnValuesNP.Value; } - + // read the events from the server. HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = m_areaId; - ReadNext(details, nodeToRead); + await ReadNextAsync(details, nodeToRead, ct); } /// /// Continues a read operation. /// - private void ReadNext(ReadEventDetails details, HistoryReadValueId nodeToRead) + private async Task ReadNextAsync(ReadEventDetails details, HistoryReadValueId nodeToRead, CancellationToken ct = default) { HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); - HistoryReadResultCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_session.HistoryRead( + HistoryReadResponse response = await m_session.HistoryReadAsync( null, new ExtensionObject(details), TimestampsToReturn.Neither, false, nodesToRead, - out results, - out diagnosticInfos); + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + HistoryReadResultCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); @@ -313,10 +314,10 @@ private void ReadNext(ReadEventDetails details, HistoryReadValueId nodeToRead) { throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable); } - + // display results. HistoryEvent data = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryEvent; - ResultsLV.AddEventHistory(data); + await ResultsLV.AddEventHistoryAsync(data, ct); // check if a continuation point exists. if (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) @@ -343,13 +344,13 @@ private void ReadNext(ReadEventDetails details, HistoryReadValueId nodeToRead) #endregion #region Event Handlers - private void GoBTN_Click(object sender, EventArgs e) + private async void GoBTN_ClickAsync(object sender, EventArgs e) { try { if (m_details == null) { - ReadFirst(); + await ReadFirstAsync(); } } catch (Exception exception) @@ -358,13 +359,13 @@ private void GoBTN_Click(object sender, EventArgs e) } } - private void NextBTN_Click(object sender, EventArgs e) + private async void NextBTN_ClickAsync(object sender, EventArgs e) { try { if (m_details != null) { - ReadNext(m_details, m_nodeToRead); + await ReadNextAsync(m_details, m_nodeToRead); } } catch (Exception exception) @@ -373,11 +374,11 @@ private void NextBTN_Click(object sender, EventArgs e) } } - private void StopBTN_Click(object sender, EventArgs e) + private async void StopBTN_ClickAsync(object sender, EventArgs e) { try { - ReleaseContinuationPoints(); + await ReleaseContinuationPointsAsync(); } catch (Exception exception) { @@ -385,13 +386,13 @@ private void StopBTN_Click(object sender, EventArgs e) } } - private void ReadTypeCB_SelectedIndexChanged(object sender, EventArgs e) + private async void ReadTypeCB_SelectedIndexChangedAsync(object sender, EventArgs e) { try { - ReleaseContinuationPoints(); + await ReleaseContinuationPointsAsync(); } - catch (Exception) + catch { // ignore is ok. } @@ -412,7 +413,7 @@ private void MaxReturnValuesCK_CheckedChanged(object sender, EventArgs e) MaxReturnValuesNP.Enabled = MaxReturnValuesCK.Checked; } - private void EventAreaBTN_Click(object sender, EventArgs e) + private async void EventAreaBTN_ClickAsync(object sender, EventArgs e) { try { @@ -421,7 +422,7 @@ private void EventAreaBTN_Click(object sender, EventArgs e) return; } - NodeId areaId = new SelectNodeDlg().ShowDialog(m_session, Opc.Ua.ObjectIds.Server, "Select Event Area", Opc.Ua.ReferenceTypeIds.HasEventSource); + NodeId areaId = await new SelectNodeDlg().ShowDialogAsync(m_session, Opc.Ua.ObjectIds.Server, "Select Event Area", default, Opc.Ua.ReferenceTypeIds.HasEventSource); if (areaId == null) { @@ -429,8 +430,8 @@ private void EventAreaBTN_Click(object sender, EventArgs e) } m_areaId = areaId; - EventAreaTB.Text = m_session.NodeCache.GetDisplayText(m_areaId); - ResultsLV.ChangeArea(areaId, false); + EventAreaTB.Text = await m_session.NodeCache.GetDisplayTextAsync(m_areaId); + await ResultsLV.ChangeAreaAsync(areaId, false); } catch (Exception exception) { @@ -438,7 +439,7 @@ private void EventAreaBTN_Click(object sender, EventArgs e) } } - private void EventTypeBTN_Click(object sender, EventArgs e) + private async void EventTypeBTN_ClickAsync(object sender, EventArgs e) { try { @@ -447,7 +448,7 @@ private void EventTypeBTN_Click(object sender, EventArgs e) return; } - TypeDeclaration type = new SelectTypeDlg().ShowDialog(m_session, Opc.Ua.ObjectTypeIds.BaseEventType, "Select Event Type"); + TypeDeclaration type = await new SelectTypeDlg().ShowDialogAsync(m_session, Opc.Ua.ObjectTypeIds.BaseEventType, "Select Event Type"); if (type == null) { @@ -455,9 +456,9 @@ private void EventTypeBTN_Click(object sender, EventArgs e) } m_filter = new FilterDeclaration(type, m_filter); - EventTypeTB.Text = m_session.NodeCache.GetDisplayText(m_filter.EventTypeId); + EventTypeTB.Text = await m_session.NodeCache.GetDisplayTextAsync(m_filter.EventTypeId); EventFilterTB.Text = GetFilterFields(m_filter); - ResultsLV.ChangeFilter(m_filter, false); + await ResultsLV.ChangeFilterAsync(m_filter, false); } catch (Exception exception) { @@ -465,7 +466,7 @@ private void EventTypeBTN_Click(object sender, EventArgs e) } } - private void EventFilterBTN_Click(object sender, EventArgs e) + private async void EventFilterBTN_ClickAsync(object sender, EventArgs e) { try { @@ -480,7 +481,7 @@ private void EventFilterBTN_Click(object sender, EventArgs e) } EventFilterTB.Text = GetFilterFields(m_filter); - ResultsLV.ChangeFilter(m_filter, false); + await ResultsLV.ChangeFilterAsync(m_filter, false); } catch (Exception exception) { diff --git a/Workshop/HistoricalEvents/Client/SelectTypeDlg.Designer.cs b/Workshop/HistoricalEvents/Client/SelectTypeDlg.Designer.cs index 6df468fc7..09ab79dbc 100644 --- a/Workshop/HistoricalEvents/Client/SelectTypeDlg.Designer.cs +++ b/Workshop/HistoricalEvents/Client/SelectTypeDlg.Designer.cs @@ -101,9 +101,9 @@ private void InitializeComponent() this.BrowseTV.Name = "BrowseTV"; this.BrowseTV.Size = new System.Drawing.Size(337, 483); this.BrowseTV.TabIndex = 6; - this.BrowseTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.BrowseTV_BeforeExpand); + this.BrowseTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.BrowseTV_BeforeExpandAsync); this.BrowseTV.DoubleClick += new System.EventHandler(this.BrowseTV_DoubleClick); - this.BrowseTV.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.BrowseTV_AfterSelect); + this.BrowseTV.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.BrowseTV_AfterSelectAsync); // // DeclarationsLV // diff --git a/Workshop/HistoricalEvents/Client/SelectTypeDlg.cs b/Workshop/HistoricalEvents/Client/SelectTypeDlg.cs index 9a99df743..c990fc912 100644 --- a/Workshop/HistoricalEvents/Client/SelectTypeDlg.cs +++ b/Workshop/HistoricalEvents/Client/SelectTypeDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -34,6 +34,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading; +using System.Threading.Tasks; namespace Quickstarts.HistoricalEvents.Client { @@ -51,19 +53,19 @@ public SelectTypeDlg() InitializeComponent(); } #endregion - + #region Private Fields - private Session m_session; + private ISession m_session; private NodeId m_rootId; #endregion - + #region Public Interface /// /// Displays the available areas in a tree view. /// /// The session. /// - public TypeDeclaration ShowDialog(Session session, NodeId rootId, string caption) + public async Task ShowDialogAsync(ISession session, NodeId rootId, string caption, CancellationToken ct = default) { m_session = session; @@ -82,7 +84,7 @@ public TypeDeclaration ShowDialog(Session session, NodeId rootId, string caption m_rootId = rootId; // display root. - TreeNode root = new TreeNode(session.NodeCache.GetDisplayText(rootId)); + TreeNode root = new TreeNode(await session.NodeCache.GetDisplayTextAsync(rootId, ct)); root.Nodes.Add(new TreeNode()); BrowseTV.Nodes.Add(root); root.Expand(); @@ -128,7 +130,7 @@ public TypeDeclaration ShowDialog(Session session, NodeId rootId, string caption return declaration; } #endregion - + #region Private Methods #endregion @@ -163,7 +165,7 @@ private void BrowseTV_DoubleClick(object sender, EventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) + private async void BrowseTV_AfterSelectAsync(object sender, TreeViewEventArgs e) { try { @@ -185,9 +187,9 @@ private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) { typeId = (NodeId)reference.NodeId; } - + // get the instance declarations. - List instances = ModelUtils.CollectInstanceDeclarationsForType(m_session, typeId); + List instances = await ModelUtils.CollectInstanceDeclarationsForTypeAsync(m_session, typeId); // populate the list box. for (int ii = 0; ii < instances.Count; ii++) @@ -206,7 +208,7 @@ private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) for (int ii = 0; ii < DeclarationsLV.Columns.Count; ii++) { DeclarationsLV.Columns[ii].Width = -2; - } + } } catch (Exception exception) { @@ -219,7 +221,7 @@ private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) /// /// The source of the event. /// The instance containing the event data. - private void BrowseTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) + private async void BrowseTV_BeforeExpandAsync(object sender, TreeViewCancelEventArgs e) { try { @@ -240,10 +242,10 @@ private void BrowseTV_BeforeExpand(object sender, TreeViewCancelEventArgs e) { nodeToBrowse.NodeId = (NodeId)reference.NodeId; } - + // add the childen to the control. - ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodeToBrowse, false); - + ReferenceDescriptionCollection references = await FormUtils.BrowseAsync(m_session, nodeToBrowse, false); + for (int ii = 0; ii < references.Count; ii++) { reference = references[ii]; diff --git a/Workshop/HistoricalEvents/Client/SetValueDlg.cs b/Workshop/HistoricalEvents/Client/SetValueDlg.cs index 27053661d..6d5291646 100644 --- a/Workshop/HistoricalEvents/Client/SetValueDlg.cs +++ b/Workshop/HistoricalEvents/Client/SetValueDlg.cs @@ -52,10 +52,10 @@ public SetValueDlg() InitializeComponent(); } #endregion - + #region Private Fields #endregion - + #region Public Interface public Variant? ShowDialog(Variant value, BuiltInType builtInType) { @@ -63,7 +63,7 @@ public SetValueDlg() { ValueTB.Text = value.ToString(); } - + if (ShowDialog() != DialogResult.OK) { return null; @@ -77,7 +77,7 @@ public SetValueDlg() return new Variant(TypeInfo.Cast(ValueTB.Text, builtInType)); } #endregion - + #region Event Handlers private void OkBTN_Click(object sender, EventArgs e) { diff --git a/Workshop/HistoricalEvents/Client/ViewEventDetailsDlg.cs b/Workshop/HistoricalEvents/Client/ViewEventDetailsDlg.cs index a2c9cfecf..e633e668d 100644 --- a/Workshop/HistoricalEvents/Client/ViewEventDetailsDlg.cs +++ b/Workshop/HistoricalEvents/Client/ViewEventDetailsDlg.cs @@ -51,10 +51,10 @@ public ViewEventDetailsDlg() InitializeComponent(); } #endregion - + #region Private Fields #endregion - + #region Public Interface /// /// Shows all fields for the current condition. diff --git a/Workshop/HistoricalEvents/Server/HistoricalEvents Server.csproj b/Workshop/HistoricalEvents/Server/HistoricalEvents Server.csproj index 92759d75c..d160c7821 100644 --- a/Workshop/HistoricalEvents/Server/HistoricalEvents Server.csproj +++ b/Workshop/HistoricalEvents/Server/HistoricalEvents Server.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -142,7 +144,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/HistoricalEvents/Server/HistoricalEventsNodeManager.cs b/Workshop/HistoricalEvents/Server/HistoricalEventsNodeManager.cs index 4ab37a56b..33f43b6ee 100644 --- a/Workshop/HistoricalEvents/Server/HistoricalEventsNodeManager.cs +++ b/Workshop/HistoricalEvents/Server/HistoricalEventsNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -75,13 +75,13 @@ public HistoricalEventsNodeManager(IServerInternal server, ApplicationConfigurat m_generator.Initialize(); } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { if (m_simulationTimer != null) @@ -110,7 +110,7 @@ public override NodeId New(ISystemContext context, NodeState node) protected override NodeStateCollection LoadPredefinedNodes(ISystemContext context) { NodeStateCollection predefinedNodes = new NodeStateCollection(); - predefinedNodes.LoadFromBinaryResource(context, + predefinedNodes.LoadFromBinaryResource(context, "Quickstarts.HistoricalEvents.Server.Model.Quickstarts.HistoricalEvents.PredefinedNodes.uanodes", typeof(HistoricalEventsNodeManager).GetTypeInfo().Assembly, true); @@ -125,7 +125,7 @@ protected override NodeStateCollection LoadPredefinedNodes(ISystemContext contex /// /// The externalReferences is an out parameter that allows the node manager to link to nodes /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and - /// should have a reference to the root folder node(s) exposed by this node manager. + /// should have a reference to the root folder node(s) exposed by this node manager. /// public override void CreateAddressSpace(IDictionary> externalReferences) { @@ -146,7 +146,7 @@ public override void CreateAddressSpace(IDictionary> e CreateWell(SystemContext, area, well.Id, well.Name); } } - + // start the simulation. m_simulationTimer = new Timer(this.DoSimulation, null, 10000, 10000); } @@ -232,7 +232,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node return handle; } } - + return null; } } @@ -256,7 +256,7 @@ protected override NodeState ValidateNode( { return handle.Node; } - + // TBD return null; @@ -590,7 +590,7 @@ private HistoryReadRequest CreateHistoryReadRequest( /// /// Stores a read history request. /// - private class HistoryReadRequest + private sealed class HistoryReadRequest { public byte[] ContinuationPoint; public LinkedList Events; @@ -636,7 +636,7 @@ private HistoryReadRequest LoadContinuationPoint( ServerSystemContext context, byte[] continuationPoint) { - Session session = context.OperationContext.Session; + ISession session = context.OperationContext.Session; if (session == null) { @@ -660,7 +660,7 @@ private byte[] SaveContinuationPoint( ServerSystemContext context, HistoryReadRequest request) { - Session session = context.OperationContext.Session; + ISession session = context.OperationContext.Session; if (session == null) { diff --git a/Workshop/HistoricalEvents/Server/HistoricalEventsServer.cs b/Workshop/HistoricalEvents/Server/HistoricalEventsServer.cs index d0f504c9a..4d0ff8b8f 100644 Binary files a/Workshop/HistoricalEvents/Server/HistoricalEventsServer.cs and b/Workshop/HistoricalEvents/Server/HistoricalEventsServer.cs differ diff --git a/Workshop/HistoricalEvents/Server/HistoricalEventsServerConfiguration.cs b/Workshop/HistoricalEvents/Server/HistoricalEventsServerConfiguration.cs index 9209c10ab..ead558e9f 100644 --- a/Workshop/HistoricalEvents/Server/HistoricalEventsServerConfiguration.cs +++ b/Workshop/HistoricalEvents/Server/HistoricalEventsServerConfiguration.cs @@ -38,7 +38,7 @@ namespace Quickstarts.HistoricalEvents.Server /// /// Stores the configuration the data access node manager. /// - [DataContract(Namespace=Namespaces.HistoricalEvents)] + [DataContract(Namespace = Namespaces.HistoricalEvents)] public class HistoricalEventsServerConfiguration { #region Constructors diff --git a/Workshop/HistoricalEvents/Server/Model/Quickstarts.HistoricalEvents.Classes.cs b/Workshop/HistoricalEvents/Server/Model/Quickstarts.HistoricalEvents.Classes.cs index c3bd73139..b2183f6c2 100644 --- a/Workshop/HistoricalEvents/Server/Model/Quickstarts.HistoricalEvents.Classes.cs +++ b/Workshop/HistoricalEvents/Server/Model/Quickstarts.HistoricalEvents.Classes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.HistoricalEvents { #region WellTestReportState Class - #if (!OPCUA_EXCLUDE_WellTestReportState) +#if (!OPCUA_EXCLUDE_WellTestReportState) /// /// Stores an instance of the WellTestReportType ObjectType. /// @@ -61,7 +61,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.HistoricalEvents.ObjectTypes.WellTestReportType, Quickstarts.HistoricalEvents.Namespaces.HistoricalEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -110,7 +110,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "YXNvbiBmb3IgdGhlIHdlbGwgdGVzdDogaW5pdGlhbCwgcGVyaW9kaWMsIHJldmlzaW9uLgAuAEQIAQAA" + "AAz/////AQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -343,11 +343,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_testReason; #endregion } - #endif +#endif #endregion #region FluidLevelTestReportState Class - #if (!OPCUA_EXCLUDE_FluidLevelTestReportState) +#if (!OPCUA_EXCLUDE_FluidLevelTestReportState) /// /// Stores an instance of the FluidLevelTestReportType ObjectType. /// @@ -371,7 +371,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.HistoricalEvents.ObjectTypes.FluidLevelTestReportType, Quickstarts.HistoricalEvents.Namespaces.HistoricalEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -427,7 +427,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "ZHVjdGVkIHRoZSB0ZXN0LiBUaGlzIGlzIGdlbmVyYWxseSBhIHBlcnNvbi4ALgBEGwEAAAAM/////wEB" + "/////wAAAAA="; #endregion - #endif +#endif #endregion #region Public Properties @@ -568,11 +568,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_testedBy; #endregion } - #endif +#endif #endregion #region InjectionTestReportState Class - #if (!OPCUA_EXCLUDE_InjectionTestReportState) +#if (!OPCUA_EXCLUDE_InjectionTestReportState) /// /// Stores an instance of the InjectionTestReportType ObjectType. /// @@ -596,7 +596,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.HistoricalEvents.ObjectTypes.InjectionTestReportType, Quickstarts.HistoricalEvents.Namespaces.HistoricalEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -650,7 +650,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "ADVgiQoCAAAAAQANAAAASW5qZWN0ZWRGbHVpZAEBLgEDAAAAACMAAABUaGUgZmx1aWQgdGhhdCBpcyBi" + "ZWluZyBpbmplY3RlZC4gLgAuAEQuAQAAAAz/////AQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -791,11 +791,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_injectedFluid; #endregion } - #endif +#endif #endregion #region WellState Class - #if (!OPCUA_EXCLUDE_WellState) +#if (!OPCUA_EXCLUDE_WellState) /// /// Stores an instance of the WellType ObjectType. /// @@ -819,7 +819,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.HistoricalEvents.ObjectTypes.WellType, Quickstarts.HistoricalEvents.Namespaces.HistoricalEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -852,7 +852,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AQAAADUAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvUXVpY2tzdGFydHMvSGlzdG9yaWNhbEV2ZW50" + "c/////8EYIACAQAAAAEAEAAAAFdlbGxUeXBlSW5zdGFuY2UBATQBAQE0ATQBAAD/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -864,6 +864,6 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/HistoricalEvents/Server/Program.cs b/Workshop/HistoricalEvents/Server/Program.cs index 12c545606..6a35c10d7 100644 --- a/Workshop/HistoricalEvents/Server/Program.cs +++ b/Workshop/HistoricalEvents/Server/Program.cs @@ -58,7 +58,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "HistoricalEventsServer"; try @@ -77,13 +77,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // start the server. - application.Start(new HistoricalEventsServer()).Wait(); + application.StartAsync(new HistoricalEventsServer()).Wait(); // run the application interactively. Application.Run(new ServerForm(application)); diff --git a/Workshop/HistoricalEvents/Server/ReportGenerator.cs b/Workshop/HistoricalEvents/Server/ReportGenerator.cs index 91fc2e259..b828cfb6e 100644 --- a/Workshop/HistoricalEvents/Server/ReportGenerator.cs +++ b/Workshop/HistoricalEvents/Server/ReportGenerator.cs @@ -51,7 +51,7 @@ public void Initialize() m_dataset.Tables[0].Columns.Add(BrowseNames.FluidLevel, typeof(double)); m_dataset.Tables[0].Columns.Add(Opc.Ua.BrowseNames.EngineeringUnits, typeof(string)); m_dataset.Tables[0].Columns.Add(BrowseNames.TestedBy, typeof(string)); - + m_dataset.Tables.Add("InjectionTests"); m_dataset.Tables[1].Columns.Add(Opc.Ua.BrowseNames.EventId, typeof(string)); m_dataset.Tables[1].Columns.Add(Opc.Ua.BrowseNames.Time, typeof(DateTime)); @@ -80,7 +80,7 @@ public void Initialize() "Area99/Saturn", "Area99/Mars" }; - + static readonly string[] s_WellUIDs = new string[] { "Well_24412", @@ -88,7 +88,7 @@ public void Initialize() "Well_86234", "Well_91423" }; - + static readonly string[] s_TestReasons = new string[] { "initial", @@ -97,7 +97,7 @@ public void Initialize() "unknown", "other" }; - + static readonly string[] s_Testers = new string[] { "Anne", @@ -105,13 +105,13 @@ public void Initialize() "Charley", "Dawn" }; - + static readonly string[] s_UnitLengths = new string[] { "m", "yd" }; - + static readonly string[] s_UnitTimes = new string[] { "s", @@ -142,14 +142,14 @@ public void Initialize() private int GetRandom(int min, int max) { - return (int)(Math.Truncate(m_random.NextDouble()*(max-min+1) + min)); + return (int)(Math.Truncate(m_random.NextDouble() * (max - min + 1) + min)); } private string GetRandom(string[] values) { - return values[GetRandom(0, values.Length-1)]; + return values[GetRandom(0, values.Length - 1)]; } - + public string[] GetAreas() { List area = new List(); @@ -161,7 +161,7 @@ public string[] GetAreas() if (index >= 0) { string areaName = s_WellNames[ii].Substring(0, index); - + if (!area.Contains(areaName)) { area.Add(areaName); @@ -222,7 +222,7 @@ public DataRow GenerateFluidLevelTestReport() row[6] = GetRandom(0, 1000); row[7] = GetRandom(s_UnitLengths); row[8] = GetRandom(s_Testers); - + m_dataset.Tables[0].Rows.Add(row); m_dataset.AcceptChanges(); @@ -394,7 +394,7 @@ public Opc.Ua.BaseEventState GetFluidLevelTestReport(ISystemContext SystemContex e.EventId.Value = new Guid((string)row[Opc.Ua.BrowseNames.EventId]).ToByteArray(); e.Time.Value = (DateTime)row[Opc.Ua.BrowseNames.Time]; - + string nameWell = (string)row[BrowseNames.NameWell]; string uidWell = (string)row[BrowseNames.UidWell]; @@ -429,7 +429,7 @@ public DataRow GenerateInjectionTestReport() row[6] = GetRandom(0, 1000); row[7] = GetRandom(s_UnitTimes); row[8] = GetRandom(s_InjectionFluids); - + m_dataset.Tables[1].Rows.Add(row); m_dataset.AcceptChanges(); diff --git a/Workshop/Methods/Client/MainForm.Designer.cs b/Workshop/Methods/Client/MainForm.Designer.cs index ed9adc297..7b3b0d0af 100644 --- a/Workshop/Methods/Client/MainForm.Designer.cs +++ b/Workshop/Methods/Client/MainForm.Designer.cs @@ -174,7 +174,7 @@ private void InitializeComponent() this.StartBTN.TabIndex = 11; this.StartBTN.Text = "Start"; this.StartBTN.UseVisualStyleBackColor = true; - this.StartBTN.Click += new System.EventHandler(this.StartBTN_Click); + this.StartBTN.Click += new System.EventHandler(this.StartBTN_ClickAsync); // // CurrentStateTB // @@ -276,7 +276,7 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); // diff --git a/Workshop/Methods/Client/MainForm.cs b/Workshop/Methods/Client/MainForm.cs index 63b4d129d..7f845c4a9 100644 --- a/Workshop/Methods/Client/MainForm.cs +++ b/Workshop/Methods/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -71,7 +71,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private Subscription m_subscription; private NodeId m_objectNode; private NodeId m_methodNode; @@ -89,7 +89,7 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -130,7 +130,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -152,17 +152,18 @@ private void Server_ConnectComplete(object sender, EventArgs e) NamespaceTable wellKnownNamespaceUris = new NamespaceTable(); wellKnownNamespaceUris.Append(Namespaces.Methods); - string[] browsePaths = new string[] + string[] browsePaths = new string[] { "1:My Process/1:State", "1:My Process", "1:My Process/1:Start" }; - List nodes = ClientUtils.TranslateBrowsePaths( + List nodes = await ClientUtils.TranslateBrowsePathsAsync( m_session, ObjectIds.ObjectsFolder, wellKnownNamespaceUris, + default, browsePaths); // subscribe to the state if available. @@ -178,7 +179,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) m_subscription.MaxNotificationsPerPublish = 1000; m_session.AddSubscription(m_subscription); - m_subscription.Create(); + await m_subscription.CreateAsync(); MonitoredItem monitoredItem = new MonitoredItem(); monitoredItem.StartNodeId = nodes[0]; @@ -186,7 +187,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); m_subscription.AddItem(monitoredItem); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(); } // save the object/method @@ -237,7 +238,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } StartBTN.Enabled = true; - StartBTN_Click(this, null); + StartBTN_ClickAsync(this, null); } catch (Exception exception) { @@ -255,7 +256,7 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) #endregion #region Event Handlers - private void StartBTN_Click(object sender, EventArgs e) + private async void StartBTN_ClickAsync(object sender, EventArgs e) { try { @@ -270,9 +271,10 @@ private void StartBTN_Click(object sender, EventArgs e) RevisedInitialStateTB.Text = String.Empty; RevisedFinalStateTB.Text = String.Empty; - IList outputArguments = m_session.Call( + IList outputArguments = await m_session.CallAsync( m_objectNode, m_methodNode, + default, initialState, finalState); diff --git a/Workshop/Methods/Client/Methods Client.csproj b/Workshop/Methods/Client/Methods Client.csproj index cfc84751c..f992988fb 100644 --- a/Workshop/Methods/Client/Methods Client.csproj +++ b/Workshop/Methods/Client/Methods Client.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -132,7 +134,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Methods/Client/Program.cs b/Workshop/Methods/Client/Program.cs index f41dd4b06..7054a86b1 100644 --- a/Workshop/Methods/Client/Program.cs +++ b/Workshop/Methods/Client/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.MethodsClient"; try @@ -61,12 +61,12 @@ static void Main() { return; } - + // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/Methods/Server/Methods Server.csproj b/Workshop/Methods/Server/Methods Server.csproj index d172641d0..d9776a9e0 100644 --- a/Workshop/Methods/Server/Methods Server.csproj +++ b/Workshop/Methods/Server/Methods Server.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -131,7 +133,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Methods/Server/MethodsNodeManager.cs b/Workshop/Methods/Server/MethodsNodeManager.cs index 29c1d7d84..9d0047e54 100644 --- a/Workshop/Methods/Server/MethodsNodeManager.cs +++ b/Workshop/Methods/Server/MethodsNodeManager.cs @@ -43,7 +43,7 @@ namespace Quickstarts.MethodsServer /// /// A node manager for a server that exposes several variables. /// - public class MethodsNodeManager :CustomNodeManager2 + public class MethodsNodeManager : CustomNodeManager2 { #region Constructors /// @@ -65,13 +65,13 @@ public MethodsNodeManager(IServerInternal server, ApplicationConfiguration confi } } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { // TBD @@ -108,7 +108,7 @@ public override void CreateAddressSpace(IDictionary> e process.NodeId = new NodeId(1, NamespaceIndex); process.BrowseName = new QualifiedName("My Process", NamespaceIndex); process.DisplayName = process.BrowseName.Name; - process.TypeDefinitionId = ObjectTypeIds.BaseObjectType; + process.TypeDefinitionId = ObjectTypeIds.BaseObjectType; // ensure the process object can be found via the server object. IList references = null; @@ -201,7 +201,7 @@ public override void CreateAddressSpace(IDictionary> e // set up method handlers. start.OnCallMethod = new GenericMethodCalledEventHandler(OnStart); - } + } } private object m_processLock = new object(); @@ -219,9 +219,9 @@ public override void CreateAddressSpace(IDictionary> e /// The output arguments. /// public ServiceResult OnStart( - ISystemContext context, - MethodState method, - IList inputArguments, + ISystemContext context, + MethodState method, + IList inputArguments, IList outputArguments) { // all arguments must be provided. @@ -268,7 +268,7 @@ public ServiceResult OnStart( return ServiceResult.Good; } - + /// /// Called when updating the process. /// @@ -296,7 +296,8 @@ private void OnUpdateProcess(object state) { m_processTimer.Dispose(); m_processTimer = null; - }; + } + ; } // signal update to state node. @@ -350,7 +351,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node handle.Validated = true; return handle; - } + } } /// @@ -372,7 +373,7 @@ protected override NodeState ValidateNode( { return handle.Node; } - + // TBD return null; diff --git a/Workshop/Methods/Server/MethodsServer.cs b/Workshop/Methods/Server/MethodsServer.cs index fe17f95ab..ddd97a712 100644 Binary files a/Workshop/Methods/Server/MethodsServer.cs and b/Workshop/Methods/Server/MethodsServer.cs differ diff --git a/Workshop/Methods/Server/MethodsServerConfiguration.cs b/Workshop/Methods/Server/MethodsServerConfiguration.cs index 52d2c0ebf..1042ee4c3 100644 --- a/Workshop/Methods/Server/MethodsServerConfiguration.cs +++ b/Workshop/Methods/Server/MethodsServerConfiguration.cs @@ -38,7 +38,7 @@ namespace Quickstarts.MethodsServer /// /// Stores the configuration the data access node manager. /// - [DataContract(Namespace=Namespaces.Methods)] + [DataContract(Namespace = Namespaces.Methods)] public class MethodsServerConfiguration { #region Constructors diff --git a/Workshop/Methods/Server/Program.cs b/Workshop/Methods/Server/Program.cs index 40e7a2f62..bbdc1b2ee 100644 --- a/Workshop/Methods/Server/Program.cs +++ b/Workshop/Methods/Server/Program.cs @@ -52,7 +52,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.MethodsServer"; try @@ -71,13 +71,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); - + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); + // start the server. - application.Start(new MethodsServer()).Wait(); + application.StartAsync(new MethodsServer()).Wait(); // run the application interactively. Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); diff --git a/Workshop/PerfTest/Client/MainForm.Designer.cs b/Workshop/PerfTest/Client/MainForm.Designer.cs index dbe7b81f5..eb64ffea6 100644 --- a/Workshop/PerfTest/Client/MainForm.Designer.cs +++ b/Workshop/PerfTest/Client/MainForm.Designer.cs @@ -210,7 +210,7 @@ private void InitializeComponent() this.StopBTN.TabIndex = 28; this.StopBTN.Text = "Stop"; this.StopBTN.UseVisualStyleBackColor = true; - this.StopBTN.Click += new System.EventHandler(this.StopBTN_Click); + this.StopBTN.Click += new System.EventHandler(this.StopBTN_ClickAsync); // // TotalItemUpdateRateLB // @@ -381,7 +381,7 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); // diff --git a/Workshop/PerfTest/Client/MainForm.cs b/Workshop/PerfTest/Client/MainForm.cs index 61edf1876..70f097b16 100644 --- a/Workshop/PerfTest/Client/MainForm.cs +++ b/Workshop/PerfTest/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading.Tasks; +using System.Threading; namespace Quickstarts.PerfTestClient { @@ -68,7 +70,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private bool m_connectedOnce; private Tester m_tester; #endregion @@ -84,7 +86,7 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -125,7 +127,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -135,7 +137,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) { if (m_tester != null) { - StopTest(); + await StopTestAsync(); } return; @@ -152,7 +154,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) m_tester = new Tester(); m_tester.SamplingRate = (int)UpdateRateCTRL.Value; m_tester.ItemCount = (int)ItemCountCTRL.Value; - m_tester.Start(m_session); + await m_tester.StartAsync(m_session); UpdateTimer.Enabled = true; StopBTN.Visible = true; @@ -206,11 +208,11 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) /// /// Stops the test. /// - private void StopTest() + private async Task StopTestAsync(CancellationToken ct = default) { if (m_tester != null) { - m_tester.Stop(); + await m_tester.StopAsync(ct); } UpdateTimer.Enabled = false; @@ -223,8 +225,8 @@ private void UpdateTimer_Tick(object sender, EventArgs e) { try { - int messageCount = 0; - int totalItemUpdateCount = 0; + int messageCount = 0; + int totalItemUpdateCount = 0; DateTime firstMessageTime = DateTime.MinValue; DateTime lastMessageTime = DateTime.MinValue; int minItemUpdateCount = 0; @@ -246,35 +248,35 @@ private void UpdateTimer_Tick(object sender, EventArgs e) LogTB.AppendText(Environment.NewLine); } - MessageCountTB.Text = String.Format("{0}", messageCount); - TotalItemUpdateCountTB.Text = String.Format("{0}", totalItemUpdateCount); - TimeSpan delta = (lastMessageTime - firstMessageTime); + MessageCountTB.Text = String.Format("{0}", messageCount); + TotalItemUpdateCountTB.Text = String.Format("{0}", totalItemUpdateCount); + TimeSpan delta = (lastMessageTime - firstMessageTime); - if (delta.TotalMilliseconds > 0) + if (delta.TotalMilliseconds > 0) { LogTB.AppendText(Utils.Format("Checking Update Counts. Time={0}, Min={1}, Max={2}", DateTime.UtcNow.ToString("mm:ss.fff"), minItemUpdateCount, maxItemUpdateCount)); LogTB.AppendText(Environment.NewLine); - MessageRateTB.Text = String.Format("{0}", delta.TotalSeconds); - TotalItemUpdateRateTB.Text = String.Format("{0}", ((double)totalItemUpdateCount)/delta.TotalSeconds); - } - else - { - MessageRateTB.Text = String.Empty; + MessageRateTB.Text = String.Format("{0}", delta.TotalSeconds); + TotalItemUpdateRateTB.Text = String.Format("{0}", ((double)totalItemUpdateCount) / delta.TotalSeconds); + } + else + { + MessageRateTB.Text = String.Empty; TotalItemUpdateRateTB.Text = String.Empty; - } + } } - catch (Exception) + catch { // TBD } } - private void StopBTN_Click(object sender, EventArgs e) + private async void StopBTN_ClickAsync(object sender, EventArgs e) { try { - StopTest(); + await StopTestAsync(); } catch (Exception exception) { diff --git a/Workshop/PerfTest/Client/PerfTest Client.csproj b/Workshop/PerfTest/Client/PerfTest Client.csproj index 1ab414cca..81da162d2 100644 --- a/Workshop/PerfTest/Client/PerfTest Client.csproj +++ b/Workshop/PerfTest/Client/PerfTest Client.csproj @@ -45,6 +45,7 @@ prompt 4 false + AllRules.ruleset pdbonly @@ -54,6 +55,7 @@ prompt 4 false + AllRules.ruleset @@ -130,7 +132,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/PerfTest/Client/Program.cs b/Workshop/PerfTest/Client/Program.cs index 0f5dc391f..e21327d3c 100644 --- a/Workshop/PerfTest/Client/Program.cs +++ b/Workshop/PerfTest/Client/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "PerfTestClient"; try @@ -63,10 +63,10 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/PerfTest/Client/Tester.cs b/Workshop/PerfTest/Client/Tester.cs index 2c53b6032..ec6a58f71 100644 --- a/Workshop/PerfTest/Client/Tester.cs +++ b/Workshop/PerfTest/Client/Tester.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,46 +30,48 @@ using System; using System.Collections.Generic; using System.Text; +using System.Threading; +using System.Threading.Tasks; using Opc.Ua; using Opc.Ua.Client; namespace Quickstarts.PerfTestClient { - class Tester + internal sealed class Tester { - // gets or sets the update rate. + // gets or sets the update rate. public int SamplingRate { get { return m_samplingRate; } set { m_samplingRate = value; } } - - // gets or sets the item count. + + // gets or sets the item count. public int ItemCount { get { return m_itemCount; } set { m_itemCount = value; } } - // returns the number of callbacks that have arrived. + // returns the number of callbacks that have arrived. public int MessageCount { get { return m_messageCount; } } - // returns the total number of item updates that have arrived. + // returns the total number of item updates that have arrived. public int TotalItemUpdateCount { get { return m_totalItemUpdateCount; } } - // returns the time of the first callback. + // returns the time of the first callback. public DateTime FirstMessageTime { get { return m_firstMessageTime; } } - // returns the time of the last callback. + // returns the time of the last callback. public DateTime LastMessageTime { get { return m_lastMessageTime; } @@ -142,7 +144,7 @@ public void GetStatistics( /// Starts the specified session. /// /// The session. - public void Start(Session session) + public async Task StartAsync(ISession session) { m_NotificationEventHandler = new NotificationEventHandler(Session_Notification); session.Notification += m_NotificationEventHandler; @@ -159,7 +161,7 @@ public void Start(Session session) subscription.DisableMonitoredItemCache = true; session.AddSubscription(subscription); - subscription.Create(); + await subscription.CreateAsync(); DateTime start = HiResClock.UtcNow; @@ -167,7 +169,7 @@ public void Start(Session session) { MonitoredItem monitoredItem = new MonitoredItem((uint)ii); - monitoredItem.StartNodeId = new NodeId((uint)((1<<24) + ii), 2); + monitoredItem.StartNodeId = new NodeId((uint)((1 << 24) + ii), 2); monitoredItem.AttributeId = Attributes.Value; monitoredItem.SamplingInterval = -1; monitoredItem.Filter = null; @@ -178,13 +180,13 @@ public void Start(Session session) subscription.AddItem(monitoredItem); } - subscription.ApplyChanges(); + await subscription.ApplyChangesAsync(); DateTime end = HiResClock.UtcNow; ReportMessage("Time to add {1} items {0}ms.", (end - start).TotalMilliseconds, m_itemCount); start = HiResClock.UtcNow; - subscription.SetPublishingMode(true); + await subscription.SetPublishingModeAsync(true); end = HiResClock.UtcNow; ReportMessage("Time to emable publishing {0}ms.", (end - start).TotalMilliseconds); @@ -193,8 +195,9 @@ public void Start(Session session) /// /// Stops the test. /// - public void Stop() + public async Task StopAsync(CancellationToken ct = default) { + Subscription subscription = null; lock (m_lock) { if (m_subscription != null && m_subscription.Session != null) @@ -204,43 +207,45 @@ public void Stop() m_subscription.Session.Notification -= m_NotificationEventHandler; } - m_subscription.Delete(true); + subscription = m_subscription; + m_subscription = null; } } + await subscription.DeleteAsync(true, ct); } void ReportMessage(string message, params object[] args) { - lock (m_lock) - { - if (m_logMessages == null) - { + lock (m_lock) + { + if (m_logMessages == null) + { m_logMessages = new List(); - } - - if (args != null && args.Length > 0) - { - m_logMessages.Add(Utils.Format(message, args)); - } - else - { + } + + if (args != null && args.Length > 0) + { + m_logMessages.Add(Utils.Format(message, args)); + } + else + { m_logMessages.Add(message); - } - } + } + } } void Session_Notification(ISession session, NotificationEventArgs e) { lock (m_lock) { - if (m_messageCount == 0) - { - m_firstMessageTime = DateTime.UtcNow; - m_totalItemUpdateCount = 0; + if (m_messageCount == 0) + { + m_firstMessageTime = DateTime.UtcNow; + m_totalItemUpdateCount = 0; m_itemUpdateCounts = new int[m_itemCount]; - } + } - m_messageCount++; + m_messageCount++; m_lastMessageTime = DateTime.UtcNow; int count = 0; diff --git a/Workshop/PerfTest/Server/MemoryRegisterState.cs b/Workshop/PerfTest/Server/MemoryRegisterState.cs index 60b300d34..b99c18fd6 100644 --- a/Workshop/PerfTest/Server/MemoryRegisterState.cs +++ b/Workshop/PerfTest/Server/MemoryRegisterState.cs @@ -98,13 +98,13 @@ public MemoryRegister Register } public override INodeBrowser CreateBrowser( - ISystemContext context, - ViewDescription view, - NodeId referenceType, - bool includeSubtypes, - BrowseDirection browseDirection, - QualifiedName browseName, - IEnumerable additionalReferences, + ISystemContext context, + ViewDescription view, + NodeId referenceType, + bool includeSubtypes, + BrowseDirection browseDirection, + QualifiedName browseName, + IEnumerable additionalReferences, bool internalOnly) { MemoryRegisterBrowser browser = new MemoryRegisterBrowser( diff --git a/Workshop/PerfTest/Server/PerfTest Server.csproj b/Workshop/PerfTest/Server/PerfTest Server.csproj index 07feaa585..d136e4097 100644 --- a/Workshop/PerfTest/Server/PerfTest Server.csproj +++ b/Workshop/PerfTest/Server/PerfTest Server.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -133,7 +135,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/PerfTest/Server/PerfTestNodeManager.cs b/Workshop/PerfTest/Server/PerfTestNodeManager.cs index 2d1993535..29e065f93 100644 --- a/Workshop/PerfTest/Server/PerfTestNodeManager.cs +++ b/Workshop/PerfTest/Server/PerfTestNodeManager.cs @@ -66,13 +66,13 @@ public PerfTestNodeManager(IServerInternal server, ApplicationConfiguration conf } } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { // TBD @@ -154,7 +154,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node uint id = (uint)nodeId.Identifier; // find register - int registerId = (int)((id & 0xFF000000)>>24); + int registerId = (int)((id & 0xFF000000) >> 24); int index = (int)(id & 0x00FFFFFF); if (registerId == 0) @@ -213,13 +213,13 @@ protected override NodeState ValidateNode( { return handle.Node; } - + // TBD return null; } #endregion - + #region Overridden Methods protected override void OnCreateMonitoredItemsComplete(ServerSystemContext context, IList monitoredItems) { diff --git a/Workshop/PerfTest/Server/PerfTestServer.cs b/Workshop/PerfTest/Server/PerfTestServer.cs index 25df3eb82..82afbbb51 100644 Binary files a/Workshop/PerfTest/Server/PerfTestServer.cs and b/Workshop/PerfTest/Server/PerfTestServer.cs differ diff --git a/Workshop/PerfTest/Server/PerfTestServerConfiguration.cs b/Workshop/PerfTest/Server/PerfTestServerConfiguration.cs index df8dc1156..e2814342c 100644 --- a/Workshop/PerfTest/Server/PerfTestServerConfiguration.cs +++ b/Workshop/PerfTest/Server/PerfTestServerConfiguration.cs @@ -38,7 +38,7 @@ namespace Quickstarts.PerfTestServer /// /// Stores the configuration the data access node manager. /// - [DataContract(Namespace=Namespaces.PerfTest)] + [DataContract(Namespace = Namespaces.PerfTest)] public class PerfTestServerConfiguration { #region Constructors diff --git a/Workshop/PerfTest/Server/Program.cs b/Workshop/PerfTest/Server/Program.cs index cb8d1769c..7b5efb757 100644 --- a/Workshop/PerfTest/Server/Program.cs +++ b/Workshop/PerfTest/Server/Program.cs @@ -48,7 +48,7 @@ static void Main() { ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "PerfTestServer"; try @@ -67,13 +67,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // start the server. - application.Start(new PerfTestServer()).Wait(); + application.StartAsync(new PerfTestServer()).Wait(); // run the application interactively. Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); diff --git a/Workshop/PerfTest/Server/UnderlyingSystem.cs b/Workshop/PerfTest/Server/UnderlyingSystem.cs index 8dda0f888..d5a9dee5e 100644 --- a/Workshop/PerfTest/Server/UnderlyingSystem.cs +++ b/Workshop/PerfTest/Server/UnderlyingSystem.cs @@ -178,7 +178,7 @@ private void OnUpdate(object state) lock (m_lock) { DateTime start = HiResClock.UtcNow; - int delta = m_values.Length/2; + int delta = m_values.Length / 2; DataValue value = new DataValue(); value.ServerTimestamp = DateTime.UtcNow; @@ -186,7 +186,7 @@ private void OnUpdate(object state) for (int ii = m_start; ii < delta + m_start && ii < m_values.Length; ii++) { - m_values[ii] += (ii+1); + m_values[ii] += (ii + 1); IDataChangeMonitoredItem2[] monitoredItems = m_monitoredItems[ii]; diff --git a/Workshop/SimpleEvents/Client/MainForm.Designer.cs b/Workshop/SimpleEvents/Client/MainForm.Designer.cs index 7e51796e1..85b18efbe 100644 --- a/Workshop/SimpleEvents/Client/MainForm.Designer.cs +++ b/Workshop/SimpleEvents/Client/MainForm.Designer.cs @@ -148,7 +148,7 @@ private void InitializeComponent() this.Server_SelectLocaleMI.Name = "Server_SelectLocaleMI"; this.Server_SelectLocaleMI.Size = new System.Drawing.Size(148, 22); this.Server_SelectLocaleMI.Text = "Select Locale..."; - this.Server_SelectLocaleMI.Click += new System.EventHandler(this.Server_SetLocaleMI_Click); + this.Server_SelectLocaleMI.Click += new System.EventHandler(this.Server_SetLocaleMI_ClickAsync); // // Server_DisconnectMI // @@ -251,7 +251,7 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 2; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); // diff --git a/Workshop/SimpleEvents/Client/MainForm.cs b/Workshop/SimpleEvents/Client/MainForm.cs index 29119ec40..6087e25b2 100644 --- a/Workshop/SimpleEvents/Client/MainForm.cs +++ b/Workshop/SimpleEvents/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -36,6 +36,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading; +using System.Threading.Tasks; namespace Quickstarts.SimpleEvents.Client { @@ -71,7 +73,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private Opc.Ua.Client.Controls.FilterDeclaration m_filter; @@ -92,7 +94,7 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -133,7 +135,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -150,7 +152,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) m_connectedOnce = true; } - CreateSubscription(); + await CreateSubscriptionAsync(); } catch (Exception exception) { @@ -207,12 +209,12 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) ConnectServerCTRL.Disconnect(); } #endregion - + #region Private Methods /// /// Creates the subscription. /// - private void CreateSubscription() + private async Task CreateSubscriptionAsync(CancellationToken ct = default) { // create the default subscription. m_subscription = new Subscription(); @@ -226,7 +228,7 @@ private void CreateSubscription() m_subscription.TimestampsToReturn = TimestampsToReturn.Both; m_session.AddSubscription(m_subscription); - m_subscription.Create(); + await m_subscription.CreateAsync(ct); // a table used to track event types. m_eventTypeMappings = new Dictionary(); @@ -235,18 +237,18 @@ private void CreateSubscription() m_knownEventTypes = new Dictionary(); m_knownEventTypes.Add(knownEventId, typeof(SystemCycleStatusEventState)); - + TypeDeclaration type = new TypeDeclaration(); type.NodeId = ExpandedNodeId.ToNodeId(ObjectTypeIds.SystemCycleStatusEventType, m_session.NamespaceUris); - type.Declarations = ClientUtils.CollectInstanceDeclarationsForType(m_session, type.NodeId); + type.Declarations = await ClientUtils.CollectInstanceDeclarationsForTypeAsync(m_session, type.NodeId, ct); // the filter to use. m_filter = new FilterDeclaration(type, null); // declate callback. - m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); + m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); - // create a monitored item based on the current filter settings. + // create a monitored item based on the current filter settings. m_monitoredItem = new MonitoredItem(); m_monitoredItem.StartNodeId = Opc.Ua.ObjectIds.Server; m_monitoredItem.AttributeId = Attributes.EventNotifier; @@ -259,18 +261,18 @@ private void CreateSubscription() m_monitoredItem.Notification += m_MonitoredItem_Notification; m_subscription.AddItem(m_monitoredItem); - m_subscription.ApplyChanges(); + await m_subscription.ApplyChangesAsync(ct); } /// /// Deletes the subscription. /// - private void DeleteSubscription() + private async Task DeleteSubscriptionAsync(CancellationToken ct = default) { if (m_subscription != null) { - m_subscription.Delete(true); - m_session.RemoveSubscription(m_subscription); + await m_subscription.DeleteAsync(true, ct); + await m_session.RemoveSubscriptionAsync(m_subscription, ct); m_subscription = null; m_filter = null; m_monitoredItem = null; @@ -280,13 +282,13 @@ private void DeleteSubscription() #region Event Handlers /// - /// Updates the display with a new value for a monitored variable. + /// Updates the display with a new value for a monitored variable. /// - private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) + private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (this.InvokeRequired) { - this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_Notification), monitoredItem, e); + this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync), monitoredItem, e); return; } @@ -309,7 +311,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt } // construct the audit object. - SystemCycleStatusEventState status = ClientUtils.ConstructEvent( + SystemCycleStatusEventState status = await ClientUtils.ConstructEventAsync( m_session, monitoredItem, notification, @@ -331,7 +333,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt item.SubItems.Add(String.Empty); // Message // look up the condition type metadata in the local cache. - INode type = m_session.NodeCache.Find(status.TypeDefinitionId); + INode type = await m_session.NodeCache.FindAsync(status.TypeDefinitionId); // Source if (status.SourceName != null) @@ -411,7 +413,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt /// /// Sets the locale to use. /// - private void Server_SetLocaleMI_Click(object sender, EventArgs e) + private async void Server_SetLocaleMI_ClickAsync(object sender, EventArgs e) { try { @@ -420,7 +422,7 @@ private void Server_SetLocaleMI_Click(object sender, EventArgs e) return; } - string locale = new SelectLocaleDlg().ShowDialog(m_session); + string locale = await new SelectLocaleDlg().ShowDialogAsync(m_session); if (locale == null) { diff --git a/Workshop/SimpleEvents/Client/Program.cs b/Workshop/SimpleEvents/Client/Program.cs index 1f7d85c0b..ced77af9d 100644 --- a/Workshop/SimpleEvents/Client/Program.cs +++ b/Workshop/SimpleEvents/Client/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "SimpleEventsClient"; try @@ -63,10 +63,10 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/SimpleEvents/Client/Quickstarts.SimpleEvents.Classes.cs b/Workshop/SimpleEvents/Client/Quickstarts.SimpleEvents.Classes.cs index 421899ddb..f23aa2ad2 100644 --- a/Workshop/SimpleEvents/Client/Quickstarts.SimpleEvents.Classes.cs +++ b/Workshop/SimpleEvents/Client/Quickstarts.SimpleEvents.Classes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.SimpleEvents { #region SystemCycleStatusEventState Class - #if (!OPCUA_EXCLUDE_SystemCycleStatusEventState) +#if (!OPCUA_EXCLUDE_SystemCycleStatusEventState) /// /// Stores an instance of the SystemCycleStatusEventType ObjectType. /// @@ -61,7 +61,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.SimpleEvents.ObjectTypes.SystemCycleStatusEventType, Quickstarts.SimpleEvents.Namespaces.SimpleEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -103,7 +103,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AAAAAQAHAAAAQ3ljbGVJZAEB9QAALgBE9QAAAAAM/////wEB/////wAAAAAVYIkKAgAAAAEACwAAAEN1" + "cnJlbnRTdGVwAQH2AAAuAET2AAAAAQG3AP////8BAf////8AAAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -244,11 +244,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_currentStep; #endregion } - #endif +#endif #endregion #region SystemCycleStartedEventState Class - #if (!OPCUA_EXCLUDE_SystemCycleStartedEventState) +#if (!OPCUA_EXCLUDE_SystemCycleStartedEventState) /// /// Stores an instance of the SystemCycleStartedEventType ObjectType. /// @@ -272,7 +272,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.SimpleEvents.ObjectTypes.SystemCycleStartedEventType, Quickstarts.SimpleEvents.Namespaces.SimpleEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -315,7 +315,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "dXJyZW50U3RlcAEB9wAALgBE9wAAAAEBtwD/////AQH/////AAAAABdgiQoCAAAAAQAFAAAAU3RlcHMB" + "AcQAAC4ARMQAAAABAbcAAQAAAAEAAAAAAAAAAQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -410,11 +410,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_steps; #endregion } - #endif +#endif #endregion #region SystemCycleAbortedEventState Class - #if (!OPCUA_EXCLUDE_SystemCycleAbortedEventState) +#if (!OPCUA_EXCLUDE_SystemCycleAbortedEventState) /// /// Stores an instance of the SystemCycleAbortedEventType ObjectType. /// @@ -438,7 +438,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.SimpleEvents.ObjectTypes.SystemCycleAbortedEventType, Quickstarts.SimpleEvents.Namespaces.SimpleEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -481,7 +481,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "dXJyZW50U3RlcAEB+AAALgBE+AAAAAEBtwD/////AQH/////AAAAABVgiQoCAAAAAQAFAAAARXJyb3IB" + "AfkAAC4ARPkAAAAAE/////8BAf////8AAAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -576,11 +576,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_error; #endregion } - #endif +#endif #endregion #region SystemCycleFinishedEventState Class - #if (!OPCUA_EXCLUDE_SystemCycleFinishedEventState) +#if (!OPCUA_EXCLUDE_SystemCycleFinishedEventState) /// /// Stores an instance of the SystemCycleFinishedEventType ObjectType. /// @@ -604,7 +604,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.SimpleEvents.ObjectTypes.SystemCycleFinishedEventType, Quickstarts.SimpleEvents.Namespaces.SimpleEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -646,7 +646,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "CgIAAAABAAcAAABDeWNsZUlkAQHcAAAuAETcAAAAAAz/////AQH/////AAAAABVgiQoCAAAAAQALAAAA" + "Q3VycmVudFN0ZXABAfoAAC4ARPoAAAABAbcA/////wEB/////wAAAAA="; #endregion - #endif +#endif #endregion #region Public Properties @@ -658,6 +658,6 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/SimpleEvents/Client/Quickstarts.SimpleEvents.DataTypes.cs b/Workshop/SimpleEvents/Client/Quickstarts.SimpleEvents.DataTypes.cs index 7a9156860..fc7876ba5 100644 --- a/Workshop/SimpleEvents/Client/Quickstarts.SimpleEvents.DataTypes.cs +++ b/Workshop/SimpleEvents/Client/Quickstarts.SimpleEvents.DataTypes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.SimpleEvents { #region CycleStepDataType Class - #if (!OPCUA_EXCLUDE_CycleStepDataType) +#if (!OPCUA_EXCLUDE_CycleStepDataType) /// /// /// @@ -79,7 +79,7 @@ private void Initialize() [DataMember(Name = "Name", IsRequired = false, Order = 1)] public string Name { - get { return m_name; } + get { return m_name; } set { m_name = value; } } @@ -87,7 +87,7 @@ public string Name [DataMember(Name = "Duration", IsRequired = false, Order = 2)] public double Duration { - get { return m_duration; } + get { return m_duration; } set { m_duration = value; } } #endregion @@ -154,13 +154,13 @@ public virtual bool IsEqual(IEncodeable encodeable) return true; } - #if !NET_STANDARD +#if !NET_STANDARD /// public virtual object Clone() { return (CycleStepDataType)this.MemberwiseClone(); } - #endif +#endif /// public new object MemberwiseClone() @@ -187,27 +187,27 @@ public virtual object Clone() /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfCycleStepDataType", Namespace = Quickstarts.SimpleEvents.Namespaces.SimpleEvents, ItemName = "CycleStepDataType")] - #if !NET_STANDARD +#if !NET_STANDARD public partial class CycleStepDataTypeCollection : List, ICloneable - #else +#else public partial class CycleStepDataTypeCollection : List - #endif +#endif { #region Constructors /// /// Initializes the collection with default values. /// - public CycleStepDataTypeCollection() {} + public CycleStepDataTypeCollection() { } /// /// Initializes the collection with an initial capacity. /// - public CycleStepDataTypeCollection(int capacity) : base(capacity) {} + public CycleStepDataTypeCollection(int capacity) : base(capacity) { } /// /// Initializes the collection with another collection. /// - public CycleStepDataTypeCollection(IEnumerable collection) : base(collection) {} + public CycleStepDataTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -238,7 +238,7 @@ public static explicit operator CycleStepDataType[](CycleStepDataTypeCollection } #endregion - #if !NET_STANDARD +#if !NET_STANDARD #region ICloneable Methods /// /// Creates a deep copy of the collection. @@ -248,7 +248,7 @@ public object Clone() return (CycleStepDataTypeCollection)this.MemberwiseClone(); } #endregion - #endif +#endif /// public new object MemberwiseClone() @@ -264,6 +264,6 @@ public object Clone() } } #endregion - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/SimpleEvents/Client/SimpleEvents Client.csproj b/Workshop/SimpleEvents/Client/SimpleEvents Client.csproj index 95421d59b..608a55684 100644 --- a/Workshop/SimpleEvents/Client/SimpleEvents Client.csproj +++ b/Workshop/SimpleEvents/Client/SimpleEvents Client.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -119,7 +121,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/SimpleEvents/Server/Program.cs b/Workshop/SimpleEvents/Server/Program.cs index 78d14192a..f4ffe9fbc 100644 --- a/Workshop/SimpleEvents/Server/Program.cs +++ b/Workshop/SimpleEvents/Server/Program.cs @@ -52,7 +52,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "SimpleEventsServer"; try @@ -71,13 +71,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // start the server. - application.Start(new SimpleEventsServer()).Wait(); + application.StartAsync(new SimpleEventsServer()).Wait(); // run the application interactively. Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); diff --git a/Workshop/SimpleEvents/Server/Quickstarts.SimpleEvents.Classes.cs b/Workshop/SimpleEvents/Server/Quickstarts.SimpleEvents.Classes.cs index 421899ddb..f23aa2ad2 100644 --- a/Workshop/SimpleEvents/Server/Quickstarts.SimpleEvents.Classes.cs +++ b/Workshop/SimpleEvents/Server/Quickstarts.SimpleEvents.Classes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.SimpleEvents { #region SystemCycleStatusEventState Class - #if (!OPCUA_EXCLUDE_SystemCycleStatusEventState) +#if (!OPCUA_EXCLUDE_SystemCycleStatusEventState) /// /// Stores an instance of the SystemCycleStatusEventType ObjectType. /// @@ -61,7 +61,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.SimpleEvents.ObjectTypes.SystemCycleStatusEventType, Quickstarts.SimpleEvents.Namespaces.SimpleEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -103,7 +103,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "AAAAAQAHAAAAQ3ljbGVJZAEB9QAALgBE9QAAAAAM/////wEB/////wAAAAAVYIkKAgAAAAEACwAAAEN1" + "cnJlbnRTdGVwAQH2AAAuAET2AAAAAQG3AP////8BAf////8AAAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -244,11 +244,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_currentStep; #endregion } - #endif +#endif #endregion #region SystemCycleStartedEventState Class - #if (!OPCUA_EXCLUDE_SystemCycleStartedEventState) +#if (!OPCUA_EXCLUDE_SystemCycleStartedEventState) /// /// Stores an instance of the SystemCycleStartedEventType ObjectType. /// @@ -272,7 +272,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.SimpleEvents.ObjectTypes.SystemCycleStartedEventType, Quickstarts.SimpleEvents.Namespaces.SimpleEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -315,7 +315,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "dXJyZW50U3RlcAEB9wAALgBE9wAAAAEBtwD/////AQH/////AAAAABdgiQoCAAAAAQAFAAAAU3RlcHMB" + "AcQAAC4ARMQAAAABAbcAAQAAAAEAAAAAAAAAAQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -410,11 +410,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_steps; #endregion } - #endif +#endif #endregion #region SystemCycleAbortedEventState Class - #if (!OPCUA_EXCLUDE_SystemCycleAbortedEventState) +#if (!OPCUA_EXCLUDE_SystemCycleAbortedEventState) /// /// Stores an instance of the SystemCycleAbortedEventType ObjectType. /// @@ -438,7 +438,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.SimpleEvents.ObjectTypes.SystemCycleAbortedEventType, Quickstarts.SimpleEvents.Namespaces.SimpleEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -481,7 +481,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "dXJyZW50U3RlcAEB+AAALgBE+AAAAAEBtwD/////AQH/////AAAAABVgiQoCAAAAAQAFAAAARXJyb3IB" + "AfkAAC4ARPkAAAAAE/////8BAf////8AAAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -576,11 +576,11 @@ protected override BaseInstanceState FindChild( private PropertyState m_error; #endregion } - #endif +#endif #endregion #region SystemCycleFinishedEventState Class - #if (!OPCUA_EXCLUDE_SystemCycleFinishedEventState) +#if (!OPCUA_EXCLUDE_SystemCycleFinishedEventState) /// /// Stores an instance of the SystemCycleFinishedEventType ObjectType. /// @@ -604,7 +604,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.SimpleEvents.ObjectTypes.SystemCycleFinishedEventType, Quickstarts.SimpleEvents.Namespaces.SimpleEvents, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -646,7 +646,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "CgIAAAABAAcAAABDeWNsZUlkAQHcAAAuAETcAAAAAAz/////AQH/////AAAAABVgiQoCAAAAAQALAAAA" + "Q3VycmVudFN0ZXABAfoAAC4ARPoAAAABAbcA/////wEB/////wAAAAA="; #endregion - #endif +#endif #endregion #region Public Properties @@ -658,6 +658,6 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/SimpleEvents/Server/Quickstarts.SimpleEvents.DataTypes.cs b/Workshop/SimpleEvents/Server/Quickstarts.SimpleEvents.DataTypes.cs index 7a9156860..fc7876ba5 100644 --- a/Workshop/SimpleEvents/Server/Quickstarts.SimpleEvents.DataTypes.cs +++ b/Workshop/SimpleEvents/Server/Quickstarts.SimpleEvents.DataTypes.cs @@ -37,7 +37,7 @@ namespace Quickstarts.SimpleEvents { #region CycleStepDataType Class - #if (!OPCUA_EXCLUDE_CycleStepDataType) +#if (!OPCUA_EXCLUDE_CycleStepDataType) /// /// /// @@ -79,7 +79,7 @@ private void Initialize() [DataMember(Name = "Name", IsRequired = false, Order = 1)] public string Name { - get { return m_name; } + get { return m_name; } set { m_name = value; } } @@ -87,7 +87,7 @@ public string Name [DataMember(Name = "Duration", IsRequired = false, Order = 2)] public double Duration { - get { return m_duration; } + get { return m_duration; } set { m_duration = value; } } #endregion @@ -154,13 +154,13 @@ public virtual bool IsEqual(IEncodeable encodeable) return true; } - #if !NET_STANDARD +#if !NET_STANDARD /// public virtual object Clone() { return (CycleStepDataType)this.MemberwiseClone(); } - #endif +#endif /// public new object MemberwiseClone() @@ -187,27 +187,27 @@ public virtual object Clone() /// [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfCycleStepDataType", Namespace = Quickstarts.SimpleEvents.Namespaces.SimpleEvents, ItemName = "CycleStepDataType")] - #if !NET_STANDARD +#if !NET_STANDARD public partial class CycleStepDataTypeCollection : List, ICloneable - #else +#else public partial class CycleStepDataTypeCollection : List - #endif +#endif { #region Constructors /// /// Initializes the collection with default values. /// - public CycleStepDataTypeCollection() {} + public CycleStepDataTypeCollection() { } /// /// Initializes the collection with an initial capacity. /// - public CycleStepDataTypeCollection(int capacity) : base(capacity) {} + public CycleStepDataTypeCollection(int capacity) : base(capacity) { } /// /// Initializes the collection with another collection. /// - public CycleStepDataTypeCollection(IEnumerable collection) : base(collection) {} + public CycleStepDataTypeCollection(IEnumerable collection) : base(collection) { } #endregion #region Static Operators @@ -238,7 +238,7 @@ public static explicit operator CycleStepDataType[](CycleStepDataTypeCollection } #endregion - #if !NET_STANDARD +#if !NET_STANDARD #region ICloneable Methods /// /// Creates a deep copy of the collection. @@ -248,7 +248,7 @@ public object Clone() return (CycleStepDataTypeCollection)this.MemberwiseClone(); } #endregion - #endif +#endif /// public new object MemberwiseClone() @@ -264,6 +264,6 @@ public object Clone() } } #endregion - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/SimpleEvents/Server/SimpleEvents Server.csproj b/Workshop/SimpleEvents/Server/SimpleEvents Server.csproj index e6f69180a..66d1f5aac 100644 --- a/Workshop/SimpleEvents/Server/SimpleEvents Server.csproj +++ b/Workshop/SimpleEvents/Server/SimpleEvents Server.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -137,7 +139,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/SimpleEvents/Server/SimpleEventsNodeManager.cs b/Workshop/SimpleEvents/Server/SimpleEventsNodeManager.cs index 49e9fed20..40dc4ae02 100644 --- a/Workshop/SimpleEvents/Server/SimpleEventsNodeManager.cs +++ b/Workshop/SimpleEvents/Server/SimpleEventsNodeManager.cs @@ -70,13 +70,13 @@ public SimpleEventsNodeManager(IServerInternal server, ApplicationConfiguration } } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { if (m_simulationTimer != null) @@ -107,7 +107,7 @@ protected override NodeStateCollection LoadPredefinedNodes(ISystemContext contex NodeStateCollection predefinedNodes = new NodeStateCollection(); predefinedNodes.LoadFromBinaryResource(context, "Quickstarts.SimpleEvents.Server.Quickstarts.SimpleEvents.PredefinedNodes.uanodes", - typeof(SimpleEventsNodeManager).GetTypeInfo().Assembly, + typeof(SimpleEventsNodeManager).GetTypeInfo().Assembly, true); return predefinedNodes; } @@ -173,7 +173,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node return handle; } } - + return null; } } @@ -197,7 +197,7 @@ protected override NodeState ValidateNode( { return handle.Node; } - + // TBD return null; diff --git a/Workshop/SimpleEvents/Server/SimpleEventsServer.cs b/Workshop/SimpleEvents/Server/SimpleEventsServer.cs index 2df004689..2faaaae75 100644 Binary files a/Workshop/SimpleEvents/Server/SimpleEventsServer.cs and b/Workshop/SimpleEvents/Server/SimpleEventsServer.cs differ diff --git a/Workshop/SimpleEvents/Server/SimpleEventsServerConfiguration.cs b/Workshop/SimpleEvents/Server/SimpleEventsServerConfiguration.cs index 91448b849..389d2c16b 100644 --- a/Workshop/SimpleEvents/Server/SimpleEventsServerConfiguration.cs +++ b/Workshop/SimpleEvents/Server/SimpleEventsServerConfiguration.cs @@ -38,7 +38,7 @@ namespace Quickstarts.SimpleEvents.Server /// /// Stores the configuration the data access node manager. /// - [DataContract(Namespace=Namespaces.SimpleEvents)] + [DataContract(Namespace = Namespaces.SimpleEvents)] public class SimpleEventsServerConfiguration { #region Constructors diff --git a/Workshop/UserAuthentication/Client/MainForm.Designer.cs b/Workshop/UserAuthentication/Client/MainForm.Designer.cs index 1cac18f9d..922240274 100644 --- a/Workshop/UserAuthentication/Client/MainForm.Designer.cs +++ b/Workshop/UserAuthentication/Client/MainForm.Designer.cs @@ -228,7 +228,7 @@ private void InitializeComponent() this.ChangeLogFileBTN.TabIndex = 14; this.ChangeLogFileBTN.Text = "Change"; this.ChangeLogFileBTN.UseVisualStyleBackColor = true; - this.ChangeLogFileBTN.Click += new System.EventHandler(this.ChangeLogFileBTN_Click); + this.ChangeLogFileBTN.Click += new System.EventHandler(this.ChangeLogFileBTN_ClickAsync); // // tabControl1 // @@ -560,7 +560,7 @@ private void InitializeComponent() this.ConnectServerCTRL.StatusStrip = this.StatusBar; this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); // diff --git a/Workshop/UserAuthentication/Client/MainForm.cs b/Workshop/UserAuthentication/Client/MainForm.cs index 9fa0b4828..42ee2cc89 100644 --- a/Workshop/UserAuthentication/Client/MainForm.cs +++ b/Workshop/UserAuthentication/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -41,6 +41,8 @@ using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Client.Controls; +using System.Threading; +using System.Threading.Tasks; namespace Quickstarts.UserAuthenticationClient { @@ -104,7 +106,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private bool m_connectedOnce; @@ -124,7 +126,7 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.Connect(); + await ConnectServerCTRL.ConnectAsync(); } catch (Exception exception) { @@ -165,7 +167,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -186,7 +188,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) // set the available tokens. SetAvailableUserTokens(m_session.ConfiguredEndpoint.Description); - ReadLogFilePath(); + await ReadLogFilePathAsync(); } catch (Exception exception) { @@ -248,7 +250,7 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) /// /// Creates a SAML token for the specified email address. /// - public static async System.Threading.Tasks.Task CreateSAMLTokenAsync(string emailAddress) + public static async Task CreateSAMLTokenAsync(string emailAddress, CancellationToken ct = default) { // Normally this would be done by a server that is capable of verifying that // the user is a legimate holder of email address. Using a local certficate to @@ -259,7 +261,7 @@ public static async System.Threading.Tasks.Task CreateSAMLTokenAsy userid.StorePath = "LocalMachine\\My"; userid.SubjectName = "UA Sample Client"; - X509Certificate2 certificate = await userid.Find(); + X509Certificate2 certificate = await userid.FindAsync(ct: ct); X509SecurityToken signingToken = new X509SecurityToken(certificate); // Create list of confirmation strings @@ -268,7 +270,7 @@ public static async System.Threading.Tasks.Task CreateSAMLTokenAsy // Add holder-of-key string to list of confirmation strings confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer"); - // Create SAML subject statement based on issuer member variable, confirmation string collection + // Create SAML subject statement based on issuer member variable, confirmation string collection // local variable and proof key identifier parameter SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress); @@ -280,7 +282,7 @@ public static async System.Threading.Tasks.Task CreateSAMLTokenAsy // Create list of SAML statements List statements = new List(); - // Add a SAML attribute statement to the list of statements. Attribute statement is based on + // Add a SAML attribute statement to the list of statements. Attribute statement is based on // subject statement and SAML attributes resulting from claims statements.Add(new SamlAttributeStatement(subject, attributes)); @@ -332,9 +334,9 @@ private IUserIdentity GetKerberosToken() // setspn -U -S / // setspn -C -S / - // The latter form is used if the UA server runs a Windows Service using the builtin Windows Service account. + // The latter form is used if the UA server runs a Windows Service using the builtin Windows Service account. - // NOTE: Using the KerberosSecurityTokenProvider without the NetworkCredential parameter will use the + // NOTE: Using the KerberosSecurityTokenProvider without the NetworkCredential parameter will use the // the credentials of the client process, // create the token provider. @@ -422,9 +424,9 @@ private void SetAvailableUserTokens(EndpointDescription endpointDescription) } } } -#endregion + #endregion -#region Event Handlers + #region Event Handlers private void UserNameImpersonateBTN_Click(object sender, EventArgs e) { if (m_session == null) @@ -464,8 +466,8 @@ private void CertificateImpersonateBTN_Click(object sender, EventArgs e) { // load the certficate. X509Certificate2 certificate = new X509Certificate2( - CertificateTB.Text, - CertificatePasswordTB.Text, + CertificateTB.Text, + CertificatePasswordTB.Text, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); // want to get error text for this call. @@ -498,7 +500,7 @@ private void AnonymousImpersonateBTN_Click(object sender, EventArgs e) { // want to get error text for this call. m_session.ReturnDiagnostics = DiagnosticsMasks.All; - + string[] preferredLocales = PreferredLocalesTB.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); m_session.UpdateSession(new UserIdentity(new AnonymousIdentityToken()), preferredLocales); @@ -547,7 +549,7 @@ private void KerberosImpersonateBTN_Click(object sender, EventArgs e) /// /// Reads the log file path. /// - private void ReadLogFilePath() + private async Task ReadLogFilePathAsync(CancellationToken ct = default) { if (m_session == null) { @@ -566,16 +568,16 @@ private void ReadLogFilePath() ReadValueIdCollection valuesToRead = new ReadValueIdCollection(); valuesToRead.Add(value); - DataValueCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_session.Read( + ReadResponse response = await m_session.ReadAsync( null, 0, TimestampsToReturn.Neither, valuesToRead, - out results, - out diagnosticInfos); + ct); + + ResponseHeader responseHeader = response.ResponseHeader; + DataValueCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, valuesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead); @@ -597,7 +599,7 @@ private void ReadLogFilePath() } } - private void ChangeLogFileBTN_Click(object sender, EventArgs e) + private async void ChangeLogFileBTN_ClickAsync(object sender, EventArgs e) { if (m_session == null) { @@ -617,14 +619,14 @@ private void ChangeLogFileBTN_Click(object sender, EventArgs e) WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(value); - StatusCodeCollection results = null; - DiagnosticInfoCollection diagnosticInfos = null; - - ResponseHeader responseHeader = m_session.Write( + WriteResponse response = await m_session.WriteAsync( null, valuesToWrite, - out results, - out diagnosticInfos); + default); + + ResponseHeader responseHeader = response.ResponseHeader; + StatusCodeCollection results = response.Results; + DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos; ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); @@ -643,6 +645,6 @@ private void ChangeLogFileBTN_Click(object sender, EventArgs e) m_session.ReturnDiagnostics = DiagnosticsMasks.None; } } -#endregion + #endregion } } diff --git a/Workshop/UserAuthentication/Client/Program.cs b/Workshop/UserAuthentication/Client/Program.cs index 2c5220137..5ebfe4e9f 100644 --- a/Workshop/UserAuthentication/Client/Program.cs +++ b/Workshop/UserAuthentication/Client/Program.cs @@ -51,7 +51,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.UserAuthenticationClient"; try @@ -61,12 +61,12 @@ static void Main() { return; } - + // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/UserAuthentication/Client/UserAuthentication Client.csproj b/Workshop/UserAuthentication/Client/UserAuthentication Client.csproj index 456b843e0..1436e6332 100644 --- a/Workshop/UserAuthentication/Client/UserAuthentication Client.csproj +++ b/Workshop/UserAuthentication/Client/UserAuthentication Client.csproj @@ -45,6 +45,7 @@ prompt 4 false + AllRules.ruleset pdbonly @@ -54,6 +55,7 @@ prompt 4 false + AllRules.ruleset @@ -125,7 +127,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/UserAuthentication/Server/Program.cs b/Workshop/UserAuthentication/Server/Program.cs index e8ba6591c..f8d191a25 100644 --- a/Workshop/UserAuthentication/Server/Program.cs +++ b/Workshop/UserAuthentication/Server/Program.cs @@ -52,7 +52,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.UserAuthenticationServer"; try @@ -71,13 +71,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); - + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); + // start the server. - application.Start(new UserAuthenticationServer()).Wait(); + application.StartAsync(new UserAuthenticationServer()).Wait(); // run the application interactively. Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); diff --git a/Workshop/UserAuthentication/Server/UserAuthentication Server.csproj b/Workshop/UserAuthentication/Server/UserAuthentication Server.csproj index 1dded9f45..6e15cd90b 100644 --- a/Workshop/UserAuthentication/Server/UserAuthentication Server.csproj +++ b/Workshop/UserAuthentication/Server/UserAuthentication Server.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -154,7 +156,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/UserAuthentication/Server/UserAuthenticationNodeManager.cs b/Workshop/UserAuthentication/Server/UserAuthenticationNodeManager.cs index ddb86266d..bbfa4b3b4 100644 --- a/Workshop/UserAuthentication/Server/UserAuthenticationNodeManager.cs +++ b/Workshop/UserAuthentication/Server/UserAuthenticationNodeManager.cs @@ -65,13 +65,13 @@ public UserAuthenticationNodeManager(IServerInternal server, ApplicationConfigur } } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { // TBD @@ -108,7 +108,7 @@ public override void CreateAddressSpace(IDictionary> e process.NodeId = new NodeId(1, NamespaceIndex); process.BrowseName = new QualifiedName("My Process", NamespaceIndex); process.DisplayName = process.BrowseName.Name; - process.TypeDefinitionId = ObjectTypeIds.BaseObjectType; + process.TypeDefinitionId = ObjectTypeIds.BaseObjectType; // ensure the process object can be found via the server object. IList references = null; @@ -136,13 +136,13 @@ public override void CreateAddressSpace(IDictionary> e state.Value = ".\\Log.txt"; process.AddChild(state); - + state.OnReadUserAccessLevel = OnReadUserAccessLevel; state.OnSimpleWriteValue = OnWriteValue; // save in dictionary. AddPredefinedNode(SystemContext, process); - } + } } public ServiceResult OnWriteValue(ISystemContext context, NodeState node, ref object value) @@ -245,7 +245,7 @@ protected override NodeHandle GetManagerHandle(ServerSystemContext context, Node handle.Validated = true; return handle; - } + } } /// @@ -267,7 +267,7 @@ protected override NodeState ValidateNode( { return handle.Node; } - + // TBD return null; diff --git a/Workshop/UserAuthentication/Server/UserAuthenticationServer.cs b/Workshop/UserAuthentication/Server/UserAuthenticationServer.cs index 1f5329c7c..f1ad99935 100644 --- a/Workshop/UserAuthentication/Server/UserAuthenticationServer.cs +++ b/Workshop/UserAuthentication/Server/UserAuthenticationServer.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -50,7 +50,7 @@ namespace Quickstarts.UserAuthenticationServer /// Each server instance must have one instance of a StandardServer object which is /// responsible for reading the configuration file, creating the endpoints and dispatching /// incoming requests to the appropriate handler. - /// + /// /// This sub-class specifies non-configurable metadata such as Product Name and initializes /// the UserAuthenticationNodeManager which provides access to the data exposed by the Server. /// @@ -61,7 +61,7 @@ public partial class UserAuthenticationServer : StandardServer /// Initializes the server before it starts up. /// /// - /// This method is called before any startup processing occurs. The sub-class may update the + /// This method is called before any startup processing occurs. The sub-class may update the /// configuration object or do any other application specific startup tasks. /// protected override void OnServerStarting(ApplicationConfiguration configuration) @@ -102,7 +102,7 @@ protected override MasterNodeManager CreateMasterNodeManager(IServerInternal ser // create the custom node managers. nodeManagers.Add(new UserAuthenticationNodeManager(server, configuration)); - + // create master node manager. return new MasterNodeManager(server, configuration, null, nodeManagers.ToArray()); } @@ -118,11 +118,11 @@ protected override ServerProperties LoadServerProperties() ServerProperties properties = new ServerProperties(); properties.ManufacturerName = "OPC Foundation"; - properties.ProductName = "OPC UA Quickstarts"; - properties.ProductUri = "http://opcfoundation.org/Quickstarts/UserAuthenticationServer/v1.0"; - properties.SoftwareVersion = Utils.GetAssemblySoftwareVersion(); - properties.BuildNumber = Utils.GetAssemblyBuildNumber(); - properties.BuildDate = Utils.GetAssemblyTimestamp(); + properties.ProductName = "OPC UA Quickstarts"; + properties.ProductUri = "http://opcfoundation.org/Quickstarts/UserAuthenticationServer/v1.0"; + properties.SoftwareVersion = Utils.GetAssemblySoftwareVersion(); + properties.BuildNumber = Utils.GetAssemblyBuildNumber(); + properties.BuildDate = Utils.GetAssemblyTimestamp(); // TBD - All applications have software certificates that need to added to the properties. @@ -134,7 +134,7 @@ protected override ServerProperties LoadServerProperties() /// protected override ResourceManager CreateResourceManager(IServerInternal server, ApplicationConfiguration configuration) { - ResourceManager resourceManager = new ResourceManager(server, configuration); + ResourceManager resourceManager = new ResourceManager(configuration); // add some localized strings to the resource manager to demonstrate that localization occurs. resourceManager.Add("InvalidPassword", "de-DE", "Das Passwort ist nicht gültig für Konto '{0}'."); @@ -145,7 +145,7 @@ protected override ResourceManager CreateResourceManager(IServerInternal server, resourceManager.Add("BadUserAccessDenied", "fr-FR", "Utilisateur ne peut pas changer la valeur."); resourceManager.Add("BadUserAccessDenied", "de-DE", "User nicht ändern können, Wert."); - + return resourceManager; } @@ -186,7 +186,7 @@ private void CreateUserIdentityValidators(ApplicationConfiguration configuration /// /// Called when a client tries to change its user identity. /// - private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) + private void SessionManager_ImpersonateUser(ISession session, ImpersonateEventArgs args) { #if TODO @@ -232,11 +232,11 @@ private SecurityTokenResolver CreateSecurityTokenResolver(CertificateIdentifier { if (issuerCertificate == null) { - throw new ArgumentNullException("issuerCertificate"); + throw new ArgumentNullException(nameof(issuerCertificate)); } // find the certificate. - X509Certificate2 certificate = issuerCertificate.Find(false).Result; + X509Certificate2 certificate = issuerCertificate.FindAsync(false).Result; if (certificate == null) { @@ -319,12 +319,15 @@ private void VerifyCertificate(X509Certificate2 certificate) /// private SecurityToken ParseAndVerifyKerberosToken(byte[] tokenData) { - XmlDocument document = new XmlDocument(); + var document = new XmlDocument { XmlResolver = null }; XmlNodeReader reader = null; - try { - document.InnerXml = new UTF8Encoding().GetString(tokenData).Trim(); + using (var xml = XmlReader.Create(Encoding.UTF8.GetString(tokenData).Trim(), new XmlReaderSettings() { XmlResolver = null })) + { + document.Load(xml); + } + reader = new XmlNodeReader(document.DocumentElement); SecurityToken securityToken = new WSSecurityTokenSerializer().ReadToken(reader, null); @@ -364,56 +367,44 @@ private SecurityToken ParseAndVerifyKerberosToken(byte[] tokenData) } } } -#endregion + #endregion private static class NativeMethods { [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LogonUser( - string lpszUsername, - string lpszDomain, + string lpszUsername, + string lpszDomain, string lpszPassword, - int dwLogonType, - int dwLogonProvider, + int dwLogonType, + int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); } - private class ImpersonationContext : IDisposable + private sealed class ImpersonationContext : IDisposable { public WindowsImpersonationContext Context; public IntPtr Handle; - -#region IDisposable Members + + #region IDisposable Members /// /// The finializer implementation. /// - ~ImpersonationContext() + ~ImpersonationContext() { - Dispose(false); + Dispose(); } - + /// /// Frees any unmanaged resources. /// public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// An overrideable version of the Dispose. - /// - protected virtual void Dispose(bool disposing) { - if (disposing) - { - Utils.SilentDispose(Context); - } + Utils.SilentDispose(Context); if (Handle != IntPtr.Zero) { @@ -421,12 +412,12 @@ protected virtual void Dispose(bool disposing) Handle = IntPtr.Zero; } } -#endregion + #endregion } // need to ensure the contexts are undone. private Dictionary m_contexts = new Dictionary(); - + /// /// Impersonates the windows user identifed by the security token. /// @@ -440,10 +431,10 @@ private void LogonUser(OperationContext context, UserNameSecurityToken securityT // const int LOGON32_LOGON_BATCH = 4; bool result = NativeMethods.LogonUser( - securityToken.UserName, - String.Empty, + securityToken.UserName, + String.Empty, securityToken.Password, - LOGON32_LOGON_NETWORK, + LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ref handle); @@ -524,7 +515,7 @@ protected override OperationContext ValidateRequest(RequestHeader requestHeader, /// protected override void OnRequestComplete(OperationContext context) { - ImpersonationContext impersonationContext = null; + ImpersonationContext impersonationContext = null; lock (this.m_impersonationLock) { @@ -543,9 +534,9 @@ protected override void OnRequestComplete(OperationContext context) base.OnRequestComplete(context); } -#region Private Fields + #region Private Fields private object m_impersonationLock = new object(); private X509CertificateValidator m_certificateValidator; -#endregion + #endregion } } diff --git a/Workshop/UserAuthentication/Server/UserAuthenticationServerConfiguration.cs b/Workshop/UserAuthentication/Server/UserAuthenticationServerConfiguration.cs index 8c15e1ed5..215c8beac 100644 --- a/Workshop/UserAuthentication/Server/UserAuthenticationServerConfiguration.cs +++ b/Workshop/UserAuthentication/Server/UserAuthenticationServerConfiguration.cs @@ -38,7 +38,7 @@ namespace Quickstarts.UserAuthenticationServer /// /// Stores the configuration the data access node manager. /// - [DataContract(Namespace=Namespaces.UserAuthentication)] + [DataContract(Namespace = Namespaces.UserAuthentication)] public class UserAuthenticationServerConfiguration { #region Constructors diff --git a/Workshop/Views/Client/MainForm.Designer.cs b/Workshop/Views/Client/MainForm.Designer.cs index 38fdb8279..1cff2a476 100644 --- a/Workshop/Views/Client/MainForm.Designer.cs +++ b/Workshop/Views/Client/MainForm.Designer.cs @@ -224,9 +224,9 @@ private void InitializeComponent() this.ConnectServerCTRL.TabIndex = 4; this.ConnectServerCTRL.UserIdentity = null; this.ConnectServerCTRL.UseSecurity = true; - this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectComplete); - this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStarting); - this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectComplete); + this.ConnectServerCTRL.ConnectComplete += new System.EventHandler(this.Server_ConnectCompleteAsync); + this.ConnectServerCTRL.ReconnectStarting += new System.EventHandler(this.Server_ReconnectStartingAsync); + this.ConnectServerCTRL.ReconnectComplete += new System.EventHandler(this.Server_ReconnectCompleteAsync); // // clientHeaderBranding1 // diff --git a/Workshop/Views/Client/MainForm.cs b/Workshop/Views/Client/MainForm.cs index 546a9cda3..ef9688236 100644 --- a/Workshop/Views/Client/MainForm.cs +++ b/Workshop/Views/Client/MainForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -53,7 +53,7 @@ private MainForm() InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } - + /// /// Creates a form which uses the specified client configuration. /// @@ -71,7 +71,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; - private Session m_session; + private ISession m_session; private bool m_connectedOnce; #endregion @@ -86,7 +86,7 @@ private void Server_ConnectMI_Click(object sender, EventArgs e) { try { - ConnectServerCTRL.Connect().Wait(); + ConnectServerCTRL.ConnectAsync().Wait(); } catch (Exception exception) { @@ -127,7 +127,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) /// /// Updates the application after connecting to or disconnecting from the server. /// - private void Server_ConnectComplete(object sender, EventArgs e) + private async void Server_ConnectCompleteAsync(object sender, EventArgs e) { try { @@ -147,7 +147,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; - ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, nodeToBrowse, false); + ReferenceDescriptionCollection references = await ClientUtils.BrowseAsync(m_session, nodeToBrowse, false); ViewCB.Items.Clear(); ViewCB.Items.Add(new ReferenceDescription() { NodeId = ExpandedNodeId.Null, DisplayName = "None" }); @@ -164,7 +164,7 @@ private void Server_ConnectComplete(object sender, EventArgs e) } // browse the instances in the server. - BrowseCTRL.Initialize(m_session, ObjectIds.ObjectsFolder, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); + await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); } catch (Exception exception) { @@ -175,11 +175,11 @@ private void Server_ConnectComplete(object sender, EventArgs e) /// /// Updates the application after a communicate error was detected. /// - private void Server_ReconnectStarting(object sender, EventArgs e) + private async void Server_ReconnectStartingAsync(object sender, EventArgs e) { try { - BrowseCTRL.ChangeSession(null); + await BrowseCTRL.ChangeSessionAsync(null); } catch (Exception exception) { @@ -190,12 +190,12 @@ private void Server_ReconnectStarting(object sender, EventArgs e) /// /// Updates the application after reconnecting to the server. /// - private void Server_ReconnectComplete(object sender, EventArgs e) + private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) { try { m_session = ConnectServerCTRL.Session; - BrowseCTRL.ChangeSession(m_session); + await BrowseCTRL.ChangeSessionAsync(m_session); } catch (Exception exception) { diff --git a/Workshop/Views/Client/Program.cs b/Workshop/Views/Client/Program.cs index a619868ae..9a6d65b75 100644 --- a/Workshop/Views/Client/Program.cs +++ b/Workshop/Views/Client/Program.cs @@ -49,7 +49,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Client; + application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.ViewsClient"; try @@ -59,12 +59,12 @@ static void Main() { return; } - + // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. Application.Run(new MainForm(application.ApplicationConfiguration)); diff --git a/Workshop/Views/Client/Views Client.csproj b/Workshop/Views/Client/Views Client.csproj index ace5b6959..2b8a5eb7a 100644 --- a/Workshop/Views/Client/Views Client.csproj +++ b/Workshop/Views/Client/Views Client.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -131,7 +133,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Views/Server/Model/Quickstarts.Views.Classes.cs b/Workshop/Views/Server/Model/Quickstarts.Views.Classes.cs index 48ffae676..f86787da2 100644 --- a/Workshop/Views/Server/Model/Quickstarts.Views.Classes.cs +++ b/Workshop/Views/Server/Model/Quickstarts.Views.Classes.cs @@ -39,7 +39,7 @@ namespace Quickstarts.Views { #region GenericControllerState Class - #if (!OPCUA_EXCLUDE_GenericControllerState) +#if (!OPCUA_EXCLUDE_GenericControllerState) /// /// Stores an instance of the GenericControllerType ObjectType. /// @@ -63,7 +63,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Views.ObjectTypes.GenericControllerType, Quickstarts.Views.Namespaces.Views, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -104,7 +104,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "C/////8BAf////8BAAAAFWCJCgIAAAAAAAcAAABFVVJhbmdlAQNlAQAuAERlAQAAAQB0A/////8BAf//" + "//8AAAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -337,11 +337,11 @@ protected override BaseInstanceState FindChild( private AnalogItemState m_measurement; #endregion } - #endif +#endif #endregion #region FlowControllerState Class - #if (!OPCUA_EXCLUDE_FlowControllerState) +#if (!OPCUA_EXCLUDE_FlowControllerState) /// /// Stores an instance of the FlowControllerType ObjectType. /// @@ -365,7 +365,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Views.ObjectTypes.FlowControllerType, Quickstarts.Views.Namespaces.Views, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -406,7 +406,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "//8BAf////8BAAAAFWCJCgIAAAAAAAcAAABFVVJhbmdlAQN0AQAuAER0AQAAAQB0A/////8BAf////8A" + "AAAA"; #endregion - #endif +#endif #endregion #region Public Properties @@ -418,11 +418,11 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion #region LevelControllerState Class - #if (!OPCUA_EXCLUDE_LevelControllerState) +#if (!OPCUA_EXCLUDE_LevelControllerState) /// /// Stores an instance of the LevelControllerType ObjectType. /// @@ -446,7 +446,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Views.ObjectTypes.LevelControllerType, Quickstarts.Views.Namespaces.Views, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -487,7 +487,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "////AQH/////AQAAABVgiQoCAAAAAAAHAAAARVVSYW5nZQEDgwEALgBEgwEAAAEAdAP/////AQH/////" + "AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -499,11 +499,11 @@ protected override void InitializeOptionalChildren(ISystemContext context) #region Private Fields #endregion } - #endif +#endif #endregion #region BoilerState Class - #if (!OPCUA_EXCLUDE_BoilerState) +#if (!OPCUA_EXCLUDE_BoilerState) /// /// Stores an instance of the BoilerType ObjectType. /// @@ -527,7 +527,7 @@ protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUri return Opc.Ua.NodeId.Create(Quickstarts.Views.ObjectTypes.BoilerType, Quickstarts.Views.Namespaces.Views, namespaceUris); } - #if (!OPCUA_EXCLUDE_InitializationStrings) +#if (!OPCUA_EXCLUDE_InitializationStrings) /// /// Initializes the instance. /// @@ -582,7 +582,7 @@ protected override void InitializeOptionalChildren(ISystemContext context) "ZWFzdXJlbWVudAEDsQEALwEAQAmxAQAAAAv/////AQH/////AQAAABVgiQoCAAAAAAAHAAAARVVSYW5n" + "ZQEDtAEALgBEtAEAAAEAdAP/////AQH/////AAAAAA=="; #endregion - #endif +#endif #endregion #region Public Properties @@ -769,6 +769,6 @@ protected override BaseInstanceState FindChild( private BaseObjectState m_drum; #endregion } - #endif +#endif #endregion } \ No newline at end of file diff --git a/Workshop/Views/Server/Program.cs b/Workshop/Views/Server/Program.cs index 1c28da1ef..622c34d8e 100644 --- a/Workshop/Views/Server/Program.cs +++ b/Workshop/Views/Server/Program.cs @@ -52,7 +52,7 @@ static void Main() ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance(); - application.ApplicationType = ApplicationType.Server; + application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.ViewsServer"; try @@ -71,13 +71,13 @@ static void Main() } // load the application configuration. - application.LoadApplicationConfiguration(false).Wait(); + application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); // check the application certificate. - application.CheckApplicationInstanceCertificates(false).Wait(); - + application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); + // start the server. - application.Start(new ViewsServer()).Wait(); + application.StartAsync(new ViewsServer()).Wait(); // run the application interactively. Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); diff --git a/Workshop/Views/Server/Views Server.csproj b/Workshop/Views/Server/Views Server.csproj index 1fc520912..32a6ff10d 100644 --- a/Workshop/Views/Server/Views Server.csproj +++ b/Workshop/Views/Server/Views Server.csproj @@ -46,6 +46,7 @@ 4 false false + AllRules.ruleset pdbonly @@ -56,6 +57,7 @@ 4 false false + AllRules.ruleset @@ -145,7 +147,7 @@ - 1.5.376.244 + 1.5.377.11-preview diff --git a/Workshop/Views/Server/ViewsNodeManager.cs b/Workshop/Views/Server/ViewsNodeManager.cs index e1a6571f7..c39b9bbd4 100644 --- a/Workshop/Views/Server/ViewsNodeManager.cs +++ b/Workshop/Views/Server/ViewsNodeManager.cs @@ -65,13 +65,13 @@ public ViewsNodeManager(IServerInternal server, ApplicationConfiguration configu } } #endregion - + #region IDisposable Members /// /// An overrideable version of the Dispose. /// protected override void Dispose(bool disposing) - { + { if (disposing) { // TBD @@ -100,7 +100,7 @@ public override NodeId New(ISystemContext context, NodeState node) return node.NodeId; } #endregion - + #region Overridden Methods /// /// Loads a node set from a file or resource and addes them to the set of predefined nodes. @@ -108,9 +108,9 @@ public override NodeId New(ISystemContext context, NodeState node) protected override NodeStateCollection LoadPredefinedNodes(ISystemContext context) { NodeStateCollection predefinedNodes = new NodeStateCollection(); - predefinedNodes.LoadFromBinaryResource(context, + predefinedNodes.LoadFromBinaryResource(context, "Quickstarts.ViewsServer.Model.Quickstarts.Views.PredefinedNodes.uanodes", - typeof(ViewsNodeManager).GetTypeInfo().Assembly, + typeof(ViewsNodeManager).GetTypeInfo().Assembly, true); return predefinedNodes; } @@ -162,7 +162,7 @@ public override void CreateAddressSpace(IDictionary> e root.AddReference(Opc.Ua.ReferenceTypeIds.Organizes, false, boiler2.NodeId); AddPredefinedNode(SystemContext, boiler2); - } + } } /// @@ -264,7 +264,7 @@ protected override Opc.Ua.Server.NodeHandle GetManagerHandle(ServerSystemContext } return null; - } + } } /// diff --git a/Workshop/Views/Server/ViewsServer.cs b/Workshop/Views/Server/ViewsServer.cs index 48cc17010..ed53f28a2 100644 Binary files a/Workshop/Views/Server/ViewsServer.cs and b/Workshop/Views/Server/ViewsServer.cs differ diff --git a/Workshop/Views/Server/ViewsServerConfiguration.cs b/Workshop/Views/Server/ViewsServerConfiguration.cs index 89373ffd9..9612e6dee 100644 --- a/Workshop/Views/Server/ViewsServerConfiguration.cs +++ b/Workshop/Views/Server/ViewsServerConfiguration.cs @@ -38,7 +38,7 @@ namespace Quickstarts.ViewsServer /// /// Stores the configuration the data access node manager. /// - [DataContract(Namespace=Quickstarts.Views.Namespaces.Views)] + [DataContract(Namespace = Quickstarts.Views.Namespaces.Views)] public class ViewsServerConfiguration { #region Constructors diff --git a/targets.props b/targets.props index 93a2c5fd3..71332ef16 100644 --- a/targets.props +++ b/targets.props @@ -1,11 +1,11 @@ - - 7.3 - - + + 13.0 + + - @@ -21,38 +21,28 @@ - - - - - preview-all - $(DotNetTargetFramework)net8.0 - net6.0 - $(DotNetTargetFramework);net8.0 - $(DotNetTargetFramework)netstandard2.0;netstandard2.1;net8.0 - $(DotNetTargetFramework)netstandard2.1;net8.0 - - - - - - latest - $(DotNetTargetFramework)netcoreapp3.1 - netcoreapp3.1 - $(DotNetTargetFramework)netcoreapp2.1;netcoreapp3.1 - $(DotNetTargetFramework)netstandard2.0;netstandard2.1 - $(DotNetTargetFramework)netcoreapp2.1;netstandard2.1 - - - - - $(DotNetTargetFramework)netcoreapp2.1 - netcoreapp2.1 - netcoreapp2.1 - $(DotNetTargetFramework)netstandard2.0 - $(DotNetTargetFramework)netcoreapp2.1 - - - + + $(DotNetTargetFramework)net8.0 + net8.0 + $(DotNetTargetFramework);net8.0 + $(DotNetTargetFramework)netstandard2.0;netstandard2.1;net8.0 + $(DotNetTargetFramework)netstandard2.1;net8.0 + + + true + true + false + preview-all + all + default + + + + + + + + +