diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 00000000..9ae91a66 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,12 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "csharpier": { + "version": "0.18.0", + "commands": [ + "dotnet-csharpier" + ] + } + } +} \ No newline at end of file diff --git a/.csharpierrc b/.csharpierrc new file mode 100644 index 00000000..3f0e3ad1 --- /dev/null +++ b/.csharpierrc @@ -0,0 +1,4 @@ +{ + "printWidth": 150, + "preprocessorSymbolSets": ["", "DEBUG", "DEBUG,CODE_STYLE"] +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..2469c3c7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,555 @@ +# Version: 2.0.1 (Using https://semver.org/) +# Updated: 2020-12-11 +# See https://github.com/RehanSaeed/EditorConfig/releases for release notes. +# See https://github.com/RehanSaeed/EditorConfig for updates to this file. +# See http://EditorConfig.org for more information about .editorconfig files. + +########################################## +# Common Settings +########################################## + +# This file is the top-most EditorConfig file +root = true + +# All Files +[*] +charset = utf-8 +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true + +########################################## +# File Extension Settings +########################################## + +# Visual Studio Solution Files +[*.sln] +indent_style = tab + +# Visual Studio XML Project Files +[*.{csproj,vbproj,vcxproj.filters,proj,projitems,shproj}] +indent_size = 2 + +# XML Configuration Files +[*.{xml,config,props,targets,nuspec,resx,ruleset,vsixmanifest,vsct}] +indent_size = 2 + +# JSON Files +[*.{json,json5,webmanifest}] +indent_size = 2 + +# YAML Files +[*.{yml,yaml}] +indent_size = 2 + +# Markdown Files +[*.md] +trim_trailing_whitespace = false + +# Web Files +[*.{htm,html,js,jsm,ts,tsx,css,sass,scss,less,svg,vue}] +indent_size = 2 + +# Batch Files +[*.{cmd,bat}] +end_of_line = crlf + +# Bash Files +[*.sh] +end_of_line = lf + +# Makefiles +[Makefile] +indent_style = tab + +########################################## +# Default .NET Code Style Severities +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/configuration-options#scope +########################################## + +[*.{cs,csx,cake,vb,vbx}] +# Default Severity for all .NET Code Style rules below +dotnet_analyzer_diagnostic.severity = warning + +########################################## +# File Header (Uncomment to support file headers) +# https://docs.microsoft.com/visualstudio/ide/reference/add-file-header +########################################## + +# [*.{cs,csx,cake,vb,vbx}] +# file_header_template = \n© PROJECT-AUTHOR\n + +# SA1636: File header copyright text should match +# Justification: .editorconfig supports file headers. If this is changed to a value other than "none", a stylecop.json file will need to added to the project. +# dotnet_diagnostic.SA1636.severity = none + +########################################## +# .NET Language Conventions +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions +########################################## + +# .NET Code Style Settings +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#net-code-style-settings +[*.{cs,csx,cake,vb,vbx}] +# "this." and "Me." qualifiers +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#this-and-me +#dotnet_style_qualification_for_field = true:warning +#dotnet_style_qualification_for_property = true:warning +#dotnet_style_qualification_for_method = true:warning +#dotnet_style_qualification_for_event = true:warning +# Language keywords instead of framework type names for type references +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#language-keywords +dotnet_style_predefined_type_for_locals_parameters_members = true:warning +dotnet_style_predefined_type_for_member_access = true:warning +# Modifier preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#normalize-modifiers +dotnet_style_require_accessibility_modifiers = always:warning +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:warning +visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:warning +dotnet_style_readonly_field = true:warning +# Parentheses preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#parentheses-preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_operators = always_for_clarity:suggestion +# Expression-level preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#expression-level-preferences +dotnet_style_object_initializer = true:warning +dotnet_style_collection_initializer = true:warning +dotnet_style_explicit_tuple_names = true:warning +dotnet_style_prefer_inferred_tuple_names = true:warning +dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion +dotnet_diagnostic.IDE0045.severity = suggestion +dotnet_style_prefer_conditional_expression_over_return = false:suggestion +dotnet_diagnostic.IDE0046.severity = suggestion +dotnet_style_prefer_compound_assignment = true:warning +# Null-checking preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#null-checking-preferences +dotnet_style_coalesce_expression = true:warning +dotnet_style_null_propagation = true:warning +# Parameter preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#parameter-preferences +dotnet_code_quality_unused_parameters = all:warning +# More style options (Undocumented) +# https://github.com/MicrosoftDocs/visualstudio-docs/issues/3641 +dotnet_style_operator_placement_when_wrapping = end_of_line +# https://github.com/dotnet/roslyn/pull/40070 +dotnet_style_prefer_simplified_interpolation = true:warning + +# C# Code Style Settings +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#c-code-style-settings +[*.{cs,csx,cake}] +# Implicit and explicit types +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#implicit-and-explicit-types +csharp_style_var_for_built_in_types = true:warning +csharp_style_var_when_type_is_apparent = true:warning +csharp_style_var_elsewhere = true:warning +# Expression-bodied members +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#expression-bodied-members +csharp_style_expression_bodied_methods = true:warning +csharp_style_expression_bodied_constructors = true:warning +csharp_style_expression_bodied_operators = true:warning +csharp_style_expression_bodied_properties = true:warning +csharp_style_expression_bodied_indexers = true:warning +csharp_style_expression_bodied_accessors = true:warning +csharp_style_expression_bodied_lambdas = true:warning +csharp_style_expression_bodied_local_functions = true:warning +# Pattern matching +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#pattern-matching +csharp_style_pattern_matching_over_is_with_cast_check = true:warning +csharp_style_pattern_matching_over_as_with_null_check = true:warning +# Inlined variable declarations +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#inlined-variable-declarations +csharp_style_inlined_variable_declaration = true:warning +# Expression-level preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#expression-level-preferences +csharp_prefer_simple_default_expression = true:warning +# "Null" checking preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#c-null-checking-preferences +csharp_style_throw_expression = true:warning +csharp_style_conditional_delegate_call = true:warning +# Code block preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#code-block-preferences +csharp_prefer_braces = true:warning +# Unused value preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#unused-value-preferences +csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion +dotnet_diagnostic.IDE0058.severity = suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +dotnet_diagnostic.IDE0059.severity = suggestion +# Index and range preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#index-and-range-preferences +csharp_style_prefer_index_operator = true:warning +csharp_style_prefer_range_operator = true:warning +# Miscellaneous preferences +# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#miscellaneous-preferences +csharp_style_deconstructed_variable_declaration = true:warning +csharp_style_pattern_local_over_anonymous_function = true:warning +csharp_using_directive_placement = outside_namespace:warning +csharp_prefer_static_local_function = true:warning +csharp_prefer_simple_using_statement = true:suggestion +dotnet_diagnostic.IDE0063.severity = suggestion + +########################################## +# .NET Formatting Conventions +# https://docs.microsoft.com/visualstudio/ide/editorconfig-code-style-settings-reference#formatting-conventions +########################################## + +# Organize usings +# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#organize-using-directives +dotnet_sort_system_directives_first = true +# Newline options +# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#new-line-options +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true +# Indentation options +# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#indentation-options +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_indent_labels = no_change +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents_when_block = false +# Spacing options +# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#spacing-options +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_parentheses = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_around_binary_operators = before_and_after +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_after_comma = true +csharp_space_before_comma = false +csharp_space_after_dot = false +csharp_space_before_dot = false +csharp_space_after_semicolon_in_for_statement = true +csharp_space_before_semicolon_in_for_statement = false +csharp_space_around_declaration_statements = false +csharp_space_before_open_square_brackets = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_square_brackets = false +# Wrapping options +# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#wrap-options +csharp_preserve_single_line_statements = false +csharp_preserve_single_line_blocks = true + +csharp_style_namespace_declarations = file_scoped + +########################################## +# .NET Naming Conventions +# https://docs.microsoft.com/visualstudio/ide/editorconfig-naming-conventions +########################################## + +[*.{cs,csx,cake,vb,vbx}] +dotnet_diagnostic.CA1000.severity = suggestion +dotnet_diagnostic.CA1001.severity = error +dotnet_diagnostic.CA1018.severity = error +dotnet_diagnostic.CA1036.severity = silent +dotnet_diagnostic.CA1051.severity = suggestion +dotnet_diagnostic.CA1068.severity = error +dotnet_diagnostic.CA1069.severity = error +dotnet_diagnostic.CA1304.severity = error +dotnet_diagnostic.CA1305.severity = suggestion +dotnet_diagnostic.CA1309.severity = suggestion +dotnet_diagnostic.CA1310.severity = error +dotnet_diagnostic.CA1707.severity = suggestion +dotnet_diagnostic.CA1708.severity = suggestion +dotnet_diagnostic.CA1711.severity = suggestion +dotnet_diagnostic.CA1716.severity = suggestion +dotnet_diagnostic.CA1720.severity = suggestion +dotnet_diagnostic.CA1725.severity = suggestion +dotnet_diagnostic.CA1805.severity = suggestion +dotnet_diagnostic.CA1816.severity = suggestion +dotnet_diagnostic.CA1822.severity = suggestion +dotnet_diagnostic.CA1825.severity = error +dotnet_diagnostic.CA1826.severity = silent +dotnet_diagnostic.CA1827.severity = error +dotnet_diagnostic.CA1829.severity = suggestion +dotnet_diagnostic.CA1834.severity = error +dotnet_diagnostic.CA1845.severity = suggestion +dotnet_diagnostic.CA1848.severity = suggestion +dotnet_diagnostic.CA2016.severity = suggestion +dotnet_diagnostic.CA2201.severity = error +dotnet_diagnostic.CA2206.severity = error +dotnet_diagnostic.CA2208.severity = error +dotnet_diagnostic.CA2211.severity = error +dotnet_diagnostic.CA2249.severity = error +dotnet_diagnostic.CA2251.severity = error +dotnet_diagnostic.CA2252.severity = none +dotnet_diagnostic.CA2254.severity = suggestion + +dotnet_diagnostic.CS0169.severity = error +dotnet_diagnostic.CS0219.severity = error +dotnet_diagnostic.CS1998.severity = error +dotnet_diagnostic.CS8602.severity = error +dotnet_diagnostic.CS8604.severity = error +dotnet_diagnostic.CS8618.severity = error +dotnet_diagnostic.CS0618.severity = error +dotnet_diagnostic.CS1998.severity = error +dotnet_diagnostic.CS4014.severity = error +dotnet_diagnostic.CS8600.severity = error +dotnet_diagnostic.CS8603.severity = error +dotnet_diagnostic.CS8625.severity = error + +dotnet_diagnostic.BL0005.severity = suggestion + +dotnet_diagnostic.MVC1000.severity = suggestion + +dotnet_diagnostic.RZ10012.severity = error + +dotnet_diagnostic.IDE0004.severity = error # redundant cast +dotnet_diagnostic.IDE0005.severity = error +dotnet_diagnostic.IDE0007.severity = error # Use var +dotnet_diagnostic.IDE0011.severity = error # Use braces on if statements +dotnet_diagnostic.IDE0010.severity = silent # populate switch +dotnet_diagnostic.IDE0017.severity = suggestion # initialization can be simplified +dotnet_diagnostic.IDE0021.severity = silent # expression body for constructors +dotnet_diagnostic.IDE0022.severity = silent # expression body for methods +dotnet_diagnostic.IDE0023.severity = suggestion # use expression body for operators +dotnet_diagnostic.IDE0024.severity = silent # expression body for operators +dotnet_diagnostic.IDE0025.severity = suggestion # use expression body for properties +dotnet_diagnostic.IDE0027.severity = suggestion # Use expression body for accessors +dotnet_diagnostic.IDE0028.severity = silent +dotnet_diagnostic.IDE0032.severity = suggestion # Use auto property +dotnet_diagnostic.IDE0033.severity = error # prefer tuple name +dotnet_diagnostic.IDE0037.severity = suggestion # simplify anonymous type +dotnet_diagnostic.IDE0040.severity = error # modifiers required +dotnet_diagnostic.IDE0041.severity = error # simplify null +dotnet_diagnostic.IDE0042.severity = error # deconstruct variable +dotnet_diagnostic.IDE0044.severity = suggestion # make field only when possible +dotnet_diagnostic.IDE0047.severity = suggestion # paratemeter name +dotnet_diagnostic.IDE0051.severity = error # unused field +dotnet_diagnostic.IDE0052.severity = error # unused member +dotnet_diagnostic.IDE0055.severity = suggestion # Fix formatting +dotnet_diagnostic.IDE0057.severity = suggestion # substring can be simplified +dotnet_diagnostic.IDE0060.severity = suggestion # unused parameters +dotnet_diagnostic.IDE0061.severity = suggestion # local expression body +dotnet_diagnostic.IDE0062.severity = suggestion # local to static +dotnet_diagnostic.IDE0063.severity = suggestion # simplify using +dotnet_diagnostic.IDE0066.severity = suggestion # switch expression +dotnet_diagnostic.IDE0072.severity = suggestion # Populate switch - forces population of all cases even when default specified +dotnet_diagnostic.IDE0078.severity = suggestion # use pattern matching +dotnet_diagnostic.IDE0090.severity = suggestion # new can be simplified +dotnet_diagnostic.IDE0130.severity = suggestion # namespace folder structure +dotnet_diagnostic.IDE0160.severity = silent # Use block namespaces ARE NOT required +dotnet_diagnostic.IDE0161.severity = suggestion # Please use file namespaces +dotnet_diagnostic.IDE1006.severity = suggestion # Naming rule violation: These words cannot contain lower case characters + +dotnet_diagnostic.NX0001.severity = error +dotnet_diagnostic.NX0002.severity = silent +dotnet_diagnostic.NX0003.severity = silent + +########################################## +# Styles +########################################## + +# camel_case_style - Define the camelCase style +dotnet_naming_style.camel_case_style.capitalization = camel_case +# pascal_case_style - Define the PascalCase style +dotnet_naming_style.pascal_case_style.capitalization = pascal_case +# constant_case - Define the CONSTANT_CASE style +dotnet_naming_style.constant_case.capitalization = all_upper +dotnet_naming_style.constant_case.word_separator = _ +# first_upper_style - The first character must start with an upper-case character +dotnet_naming_style.first_upper_style.capitalization = first_word_upper +# prefix_interface_with_i_style - Interfaces must be PascalCase and the first character of an interface must be an 'I' +dotnet_naming_style.prefix_interface_with_i_style.capitalization = pascal_case +dotnet_naming_style.prefix_interface_with_i_style.required_prefix = I +# prefix_type_parameters_with_t_style - Generic Type Parameters must be PascalCase and the first character must be a 'T' +dotnet_naming_style.prefix_type_parameters_with_t_style.capitalization = pascal_case +dotnet_naming_style.prefix_type_parameters_with_t_style.required_prefix = T +# disallowed_style - Anything that has this style applied is marked as disallowed +dotnet_naming_style.disallowed_style.capitalization = pascal_case +dotnet_naming_style.disallowed_style.required_prefix = ____RULE_VIOLATION____ +dotnet_naming_style.disallowed_style.required_suffix = ____RULE_VIOLATION____ +# internal_error_style - This style should never occur... if it does, it indicates a bug in file or in the parser using the file +dotnet_naming_style.internal_error_style.capitalization = pascal_case +dotnet_naming_style.internal_error_style.required_prefix = ____INTERNAL_ERROR____ +dotnet_naming_style.internal_error_style.required_suffix = ____INTERNAL_ERROR____ + +# prefix_interface_with_i_style - Interfaces must be PascalCase and the first character of an interface must be an 'I' +dotnet_naming_style.underscore_camel_case_style.capitalization = camel_case +dotnet_naming_style.underscore_camel_case_style.required_prefix = _ + +########################################## +# .NET Design Guideline Field Naming Rules +# Naming rules for fields follow the .NET Framework design guidelines +# https://docs.microsoft.com/dotnet/standard/design-guidelines/index +########################################## + +# All public/protected/protected_internal constant fields must be constant_case +# https://docs.microsoft.com/dotnet/standard/design-guidelines/field +dotnet_naming_symbols.public_protected_constant_fields_group.applicable_accessibilities = public, protected, protected_internal +dotnet_naming_symbols.public_protected_constant_fields_group.required_modifiers = const +dotnet_naming_symbols.public_protected_constant_fields_group.applicable_kinds = field +dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.symbols = public_protected_constant_fields_group +dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.style = constant_case +dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.severity = warning + +# All public/protected/protected_internal static readonly fields must be constant_case +# https://docs.microsoft.com/dotnet/standard/design-guidelines/field +dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_accessibilities = public, protected, protected_internal +dotnet_naming_symbols.public_protected_static_readonly_fields_group.required_modifiers = static, readonly +dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_kinds = field +dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.symbols = public_protected_static_readonly_fields_group +dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.style = constant_case +dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.severity = warning + +# No other public/protected/protected_internal fields are allowed +# https://docs.microsoft.com/dotnet/standard/design-guidelines/field +dotnet_naming_symbols.other_public_protected_fields_group.applicable_accessibilities = public, protected, protected_internal +dotnet_naming_symbols.other_public_protected_fields_group.applicable_kinds = field +dotnet_naming_rule.other_public_protected_fields_disallowed_rule.symbols = other_public_protected_fields_group +dotnet_naming_rule.other_public_protected_fields_disallowed_rule.style = disallowed_style +dotnet_naming_rule.other_public_protected_fields_disallowed_rule.severity = error + +########################################## +# StyleCop Field Naming Rules +# Naming rules for fields follow the StyleCop analyzers +# This does not override any rules using disallowed_style above +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers +########################################## + +# All constant fields must be constant_case +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1303.md +dotnet_naming_symbols.stylecop_constant_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private +dotnet_naming_symbols.stylecop_constant_fields_group.required_modifiers = const +dotnet_naming_symbols.stylecop_constant_fields_group.applicable_kinds = field +dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.symbols = stylecop_constant_fields_group +dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.style = constant_case +dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.severity = warning + +# All static readonly fields must be constant_case +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1311.md +dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private +dotnet_naming_symbols.stylecop_static_readonly_fields_group.required_modifiers = static, readonly +dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_kinds = field +dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.symbols = stylecop_static_readonly_fields_group +dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.style = constant_case +dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.severity = warning + +# No non-private instance fields are allowed +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md +dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected +dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_kinds = field +dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.symbols = stylecop_fields_must_be_private_group +dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.style = disallowed_style +dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.severity = error + +# Private fields must be camelCase +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1306.md +dotnet_naming_symbols.stylecop_private_fields_group.applicable_accessibilities = private +dotnet_naming_symbols.stylecop_private_fields_group.applicable_kinds = field +dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.symbols = stylecop_private_fields_group +dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.style = underscore_camel_case_style +dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.severity = warning + +# Local variables must be camelCase +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1312.md +dotnet_naming_symbols.stylecop_local_fields_group.applicable_accessibilities = local +dotnet_naming_symbols.stylecop_local_fields_group.applicable_kinds = local +dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.symbols = stylecop_local_fields_group +dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.style = camel_case_style +dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.severity = warning + +# This rule should never fire. However, it's included for at least two purposes: +# First, it helps to understand, reason about, and root-case certain types of issues, such as bugs in .editorconfig parsers. +# Second, it helps to raise immediate awareness if a new field type is added (as occurred recently in C#). +dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_accessibilities = * +dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_kinds = field +dotnet_naming_rule.sanity_check_uncovered_field_case_rule.symbols = sanity_check_uncovered_field_case_group +dotnet_naming_rule.sanity_check_uncovered_field_case_rule.style = internal_error_style +dotnet_naming_rule.sanity_check_uncovered_field_case_rule.severity = error + + +########################################## +# Other Naming Rules +########################################## + +# All of the following must be PascalCase: +# - Namespaces +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-namespaces +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1300.md +# - Classes and Enumerations +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces +# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1300.md +# - Delegates +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces#names-of-common-types +# - Constructors, Properties, Events, Methods +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-type-members +dotnet_naming_symbols.element_group.applicable_kinds = namespace, class, enum, struct, delegate, event, method, property +dotnet_naming_rule.element_rule.symbols = element_group +dotnet_naming_rule.element_rule.style = pascal_case_style +dotnet_naming_rule.element_rule.severity = warning + +# Interfaces use PascalCase and are prefixed with uppercase 'I' +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces +dotnet_naming_symbols.interface_group.applicable_kinds = interface +dotnet_naming_rule.interface_rule.symbols = interface_group +dotnet_naming_rule.interface_rule.style = prefix_interface_with_i_style +dotnet_naming_rule.interface_rule.severity = warning + +# Generics Type Parameters use PascalCase and are prefixed with uppercase 'T' +# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces +dotnet_naming_symbols.type_parameter_group.applicable_kinds = type_parameter +dotnet_naming_rule.type_parameter_rule.symbols = type_parameter_group +dotnet_naming_rule.type_parameter_rule.style = prefix_type_parameters_with_t_style +dotnet_naming_rule.type_parameter_rule.severity = warning + +# Function parameters use camelCase +# https://docs.microsoft.com/dotnet/standard/design-guidelines/naming-parameters +dotnet_naming_symbols.parameters_group.applicable_kinds = parameter +dotnet_naming_rule.parameters_rule.symbols = parameters_group +dotnet_naming_rule.parameters_rule.style = camel_case_style +dotnet_naming_rule.parameters_rule.severity = warning + +########################################## +# License +########################################## +# The following applies as to the .editorconfig file ONLY, and is +# included below for reference, per the requirements of the license +# corresponding to this .editorconfig file. +# See: https://github.com/RehanSaeed/EditorConfig +# +# MIT License +# +# Copyright (c) 2017-2019 Muhammad Rehan Saeed +# Copyright (c) 2019 Henry Gabryjelski +# +# 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. +########################################## diff --git a/examples/BCC/BCC.csproj b/examples/BCC/BCC.csproj index d91d5ff1..863befdf 100644 --- a/examples/BCC/BCC.csproj +++ b/examples/BCC/BCC.csproj @@ -1,48 +1,9 @@ - - + - Debug - AnyCPU - {16978032-B34C-44B6-8DA1-475D751338F1} + net6.0 Exe - BCC - BCC - v4.5 - - true - full - false - bin\Debug - DEBUG; - prompt - 4 - true - - - full - true - bin\Release - prompt - 4 - true - - - - - - ..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll - - - ..\packages\SparkPost.1.6.2\lib\net45\SparkPost.dll - - - - - - - - + - \ No newline at end of file + diff --git a/examples/BCC/Program.cs b/examples/BCC/Program.cs index aa83bc5f..b9e405d4 100644 --- a/examples/BCC/Program.cs +++ b/examples/BCC/Program.cs @@ -1,60 +1,38 @@ using System; -using System.Configuration; +using SparkPost; -namespace SparkPost.Examples +var apikey = "YOUR_API_KEY"; +var fromAddr = "from-csharp@yourdomain.com"; +var toAddr = "to@you.com"; +var ccAddr = "cc@them.com"; +var bccAddr = "bcc@sneaky.com"; + +var trans = new Transmission(); + +var to = new Recipient { Address = new Address { Email = toAddr } }; +trans.Recipients.Add(to); + +var cc = new Recipient +{ + Address = new Address { Email = ccAddr, HeaderTo = toAddr } +}; +trans.Recipients.Add(cc); + +var bcc = new Recipient { - internal class BCC - { - public static void Main(string[] args) - { - var settings = ConfigurationManager.AppSettings; - var fromAddr = settings["fromaddr"]; - var toAddr = settings["toaddr"]; - var ccAddr = settings["ccaddr"]; - var bccAddr = settings["bccaddr"]; - - var trans = new Transmission(); - - var to = new Recipient - { - Address = new Address {Email = toAddr} - }; - trans.Recipients.Add(to); - - var cc = new Recipient - { - Address = new Address - { - Email = ccAddr, - HeaderTo = toAddr - } - }; - trans.Recipients.Add(cc); - - var bcc = new Recipient - { - Address = new Address - { - Email = bccAddr, - HeaderTo = toAddr - } - }; - trans.Recipients.Add(bcc); - - trans.Content.From.Email = fromAddr; - trans.Content.Subject = "SparkPost BCC / CC example"; - trans.Content.Text = - "This message was sent To 1 recipient, 1 recipient was CC'd and 1 sneaky recipient was BCC'd."; - trans.Content.Headers.Add("CC", ccAddr); - - Console.Write("Sending BCC / CC sample mail..."); - - var client = new Client(settings["apikey"]); - client.CustomSettings.SendingMode = SendingModes.Sync; - - var response = client.Transmissions.Send(trans); - - Console.WriteLine("done"); - } - } -} \ No newline at end of file + Address = new Address { Email = bccAddr, HeaderTo = toAddr } +}; +trans.Recipients.Add(bcc); + +trans.Content.From.Email = fromAddr; +trans.Content.Subject = "SparkPost BCC / CC example"; +trans.Content.Text = "This message was sent To 1 recipient, 1 recipient was CC'd and 1 sneaky recipient was BCC'd."; +trans.Content.Headers.Add("CC", ccAddr); + +Console.Write("Sending BCC / CC sample mail..."); + +var client = new Client(apikey); + +var response = await client.Transmissions.Send(trans); + +Console.WriteLine("done"); diff --git a/examples/BCC/Properties/AssemblyInfo.cs b/examples/BCC/Properties/AssemblyInfo.cs deleted file mode 100644 index a6581ba6..00000000 --- a/examples/BCC/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("BCC")] -[assembly: AssemblyDescription("SparkPost C# BCC Example")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". -// The form "{Major}.{Minor}.*" will automatically update the build and revision, -// and "{Major}.{Minor}.{Build}.*" will update just the revision. - -[assembly: AssemblyVersion("1.0.*")] - -// The following attributes are used to specify the signing key for the assembly, -// if desired. See the Mono documentation for more information about signing. - -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile("")] - diff --git a/examples/BCC/packages.config b/examples/BCC/packages.config deleted file mode 100644 index 6a1b8114..00000000 --- a/examples/BCC/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/examples/CC/CC.csproj b/examples/CC/CC.csproj index 629a6bd0..863befdf 100644 --- a/examples/CC/CC.csproj +++ b/examples/CC/CC.csproj @@ -1,51 +1,9 @@ - - + - Debug - AnyCPU - {2B086611-A56B-4857-9F7F-A8603D7AA3FD} + net6.0 Exe - CC - CC - v4.5 - - true - full - false - bin\Debug - DEBUG; - prompt - 4 - true - - - full - true - bin\Release - prompt - 4 - true - - - - - - ..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll - - - ..\packages\SparkPost.1.6.2\lib\net45\SparkPost.dll - - - - - - - - - app.config - - + - \ No newline at end of file + diff --git a/examples/CC/Program.cs b/examples/CC/Program.cs index 1c569389..f909c7fe 100644 --- a/examples/CC/Program.cs +++ b/examples/CC/Program.cs @@ -1,48 +1,31 @@ using System; -using System.Configuration; +using SparkPost; -namespace SparkPost.Examples +var apikey = "YOUR_API_KEY"; +var fromAddr = "from-csharp@yourdomain.com"; +var toAddr = "to@you.com"; +var ccAddr = "cc@them.com"; + +var trans = new Transmission(); + +var to = new Recipient { Address = new Address { Email = toAddr } }; +trans.Recipients.Add(to); + +var cc = new Recipient { - internal class CC - { - public static void Main(string[] args) - { - var settings = ConfigurationManager.AppSettings; - var fromAddr = settings["fromaddr"]; - var toAddr = settings["toaddr"]; - var ccAddr = settings["ccaddr"]; - - var trans = new Transmission(); - - var to = new Recipient - { - Address = new Address {Email = toAddr} - }; - trans.Recipients.Add(to); - - var cc = new Recipient - { - Address = new Address - { - Email = ccAddr, - HeaderTo = toAddr - } - }; - trans.Recipients.Add(cc); - - trans.Content.From.Email = fromAddr; - trans.Content.Subject = "SparkPost CC example"; - trans.Content.Text = "This message was sent To 1 recipient and 1 recipient was CC'd."; - trans.Content.Headers.Add("CC", ccAddr); - - Console.Write("Sending CC sample mail..."); - - var client = new Client(settings["apikey"]); - client.CustomSettings.SendingMode = SendingModes.Sync; - - var response = client.Transmissions.Send(trans); - - Console.WriteLine("done"); - } - } -} \ No newline at end of file + Address = new Address { Email = ccAddr, HeaderTo = toAddr } +}; +trans.Recipients.Add(cc); + +trans.Content.From.Email = fromAddr; +trans.Content.Subject = "SparkPost CC example"; +trans.Content.Text = "This message was sent To 1 recipient and 1 recipient was CC'd."; +trans.Content.Headers.Add("CC", ccAddr); + +Console.Write("Sending CC sample mail..."); + +var client = new Client(apikey); + +var response = await client.Transmissions.Send(trans); + +Console.WriteLine("done"); diff --git a/examples/CC/Properties/AssemblyInfo.cs b/examples/CC/Properties/AssemblyInfo.cs deleted file mode 100644 index 8b25fd52..00000000 --- a/examples/CC/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("CC")] -[assembly: AssemblyDescription("SparkPost C# CC Example")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". -// The form "{Major}.{Minor}.*" will automatically update the build and revision, -// and "{Major}.{Minor}.{Build}.*" will update just the revision. - -[assembly: AssemblyVersion("1.0.*")] - -// The following attributes are used to specify the signing key for the assembly, -// if desired. See the Mono documentation for more information about signing. - -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile("")] - diff --git a/examples/CC/packages.config b/examples/CC/packages.config deleted file mode 100644 index 6a1b8114..00000000 --- a/examples/CC/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/examples/Examples.sln b/examples/Examples.sln deleted file mode 100644 index 66581834..00000000 --- a/examples/Examples.sln +++ /dev/null @@ -1,35 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SendInline", "SendInline\SendInline.csproj", "{8D45D223-E1FE-4652-A37E-09507AC4E107}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SendTemplate", "SendTemplate\SendTemplate.csproj", "{A85DDE10-EBD6-4B58-93D6-185809C73FE8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CC", "CC\CC.csproj", "{2B086611-A56B-4857-9F7F-A8603D7AA3FD}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BCC", "BCC\BCC.csproj", "{16978032-B34C-44B6-8DA1-475D751338F1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {16978032-B34C-44B6-8DA1-475D751338F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {16978032-B34C-44B6-8DA1-475D751338F1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {16978032-B34C-44B6-8DA1-475D751338F1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {16978032-B34C-44B6-8DA1-475D751338F1}.Release|Any CPU.Build.0 = Release|Any CPU - {2B086611-A56B-4857-9F7F-A8603D7AA3FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2B086611-A56B-4857-9F7F-A8603D7AA3FD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2B086611-A56B-4857-9F7F-A8603D7AA3FD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2B086611-A56B-4857-9F7F-A8603D7AA3FD}.Release|Any CPU.Build.0 = Release|Any CPU - {8D45D223-E1FE-4652-A37E-09507AC4E107}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8D45D223-E1FE-4652-A37E-09507AC4E107}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8D45D223-E1FE-4652-A37E-09507AC4E107}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8D45D223-E1FE-4652-A37E-09507AC4E107}.Release|Any CPU.Build.0 = Release|Any CPU - {A85DDE10-EBD6-4B58-93D6-185809C73FE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A85DDE10-EBD6-4B58-93D6-185809C73FE8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A85DDE10-EBD6-4B58-93D6-185809C73FE8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A85DDE10-EBD6-4B58-93D6-185809C73FE8}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal diff --git a/examples/SendInline/Program.cs b/examples/SendInline/Program.cs index da028f55..96ba9f66 100644 --- a/examples/SendInline/Program.cs +++ b/examples/SendInline/Program.cs @@ -1,49 +1,32 @@ using System; using System.Collections.Generic; -using System.Configuration; +using SparkPost; -namespace SparkPost.Examples +var apikey = "YOUR_API_KEY"; +var fromAddr = "from-csharp@yourdomain.com"; +var toAddr = "to@you.com"; + +var trans = new Transmission(); + +var to = new Recipient { - internal class SendInline - { - public static void Main(string[] args) - { - var settings = ConfigurationManager.AppSettings; - var fromAddr = settings["fromaddr"]; - var toAddr = settings["toaddr"]; - - var trans = new Transmission(); - - var to = new Recipient - { - Address = new Address - { - Email = toAddr - }, - SubstitutionData = new Dictionary - { - {"firstName", "Jane"} - } - }; - - trans.Recipients.Add(to); - - trans.SubstitutionData["firstName"] = "Oh Ye Of Little Name"; - - trans.Content.From.Email = fromAddr; - trans.Content.Subject = "SparkPost online content example"; - trans.Content.Text = "Greetings {{firstName or 'recipient'}}\nHello from C# land."; - trans.Content.Html = - "

Greetings {{firstName or 'recipient'}}

Hello from C# land.

"; - - Console.Write("Sending mail..."); - - var client = new Client(settings["apikey"]); - client.CustomSettings.SendingMode = SendingModes.Sync; - - var response = client.Transmissions.Send(trans); - - Console.WriteLine("done"); - } - } -} \ No newline at end of file + Address = new Address { Email = toAddr }, + SubstitutionData = new Dictionary { { "firstName", "Jane" } } +}; + +trans.Recipients.Add(to); + +trans.SubstitutionData["firstName"] = "Oh Ye Of Little Name"; + +trans.Content.From.Email = fromAddr; +trans.Content.Subject = "SparkPost online content example"; +trans.Content.Text = "Greetings {{firstName or 'recipient'}}\nHello from C# land."; +trans.Content.Html = "

Greetings {{firstName or 'recipient'}}

Hello from C# land.

"; + +Console.Write("Sending mail..."); + +var client = new Client(apikey); + +var response = await client.Transmissions.Send(trans); + +Console.WriteLine("done"); diff --git a/examples/SendInline/Properties/AssemblyInfo.cs b/examples/SendInline/Properties/AssemblyInfo.cs deleted file mode 100644 index 228df2b9..00000000 --- a/examples/SendInline/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("SendInline")] -[assembly: AssemblyDescription("SparkPost C# Send Inline Example")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". -// The form "{Major}.{Minor}.*" will automatically update the build and revision, -// and "{Major}.{Minor}.{Build}.*" will update just the revision. - -[assembly: AssemblyVersion("1.0.*")] - -// The following attributes are used to specify the signing key for the assembly, -// if desired. See the Mono documentation for more information about signing. - -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile("")] - diff --git a/examples/SendInline/SendInline.csproj b/examples/SendInline/SendInline.csproj index 7f38b857..863befdf 100644 --- a/examples/SendInline/SendInline.csproj +++ b/examples/SendInline/SendInline.csproj @@ -1,51 +1,9 @@ - - + - Debug - AnyCPU - {8D45D223-E1FE-4652-A37E-09507AC4E107} + net6.0 Exe - SendInline - SendInline - v4.5 - - true - full - false - bin\Debug - DEBUG; - prompt - 4 - true - - - full - true - bin\Release - prompt - 4 - true - - - - - - ..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll - - - ..\packages\SparkPost.1.6.2\lib\net45\SparkPost.dll - - - - - - - - - app.config - - + - \ No newline at end of file + diff --git a/examples/SendInline/packages.config b/examples/SendInline/packages.config deleted file mode 100644 index 6a1b8114..00000000 --- a/examples/SendInline/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/examples/SendTemplate/Order.cs b/examples/SendTemplate/Order.cs new file mode 100644 index 00000000..4c43160f --- /dev/null +++ b/examples/SendTemplate/Order.cs @@ -0,0 +1,3 @@ +namespace SendTemplate; + +public record Order(int OrderId, string Desc, int Total); diff --git a/examples/SendTemplate/Program.cs b/examples/SendTemplate/Program.cs index 47c2a69e..9d85ce3f 100644 --- a/examples/SendTemplate/Program.cs +++ b/examples/SendTemplate/Program.cs @@ -1,59 +1,33 @@ using System; using System.Collections.Generic; -using System.Configuration; +using SendTemplate; +using SparkPost; -namespace SparkPost.Examples +var fromAddr = "from-csharp@yourdomain.com"; +var toAddr = "to@you.com"; +var apikey = "YOUR_API_KEY"; + +var trans = new Transmission(); + +var to = new Recipient { - internal class Order - { - public int OrderId { get; set; } - public string Desc { get; set; } - public int Total { get; set; } - } - - internal class SendTemplate - { - public static void Main(string[] args) - { - var settings = ConfigurationManager.AppSettings; - var fromAddr = settings["fromaddr"]; - var toAddr = settings["toaddr"]; - - var trans = new Transmission(); - - var to = new Recipient - { - Address = new Address - { - Email = toAddr - }, - SubstitutionData = new Dictionary - { - {"firstName", "Jane"} - } - }; - - trans.Recipients.Add(to); - trans.SubstitutionData["title"] = "Dr"; - trans.SubstitutionData["firstName"] = "Rick"; - trans.SubstitutionData["lastName"] = "Sanchez"; - trans.SubstitutionData["orders"] = new List - { - new Order {OrderId = 101, Desc = "Tomatoes", Total = 5}, - new Order {OrderId = 271, Desc = "Entropy", Total = 314} - }; - - trans.Content.From.Email = fromAddr; - trans.Content.TemplateId = "orderSummary"; - - Console.Write("Sending mail..."); - - var client = new Client(settings["apikey"]); - client.CustomSettings.SendingMode = SendingModes.Sync; - - var response = client.Transmissions.Send(trans); - - Console.WriteLine("done"); - } - } -} \ No newline at end of file + Address = new Address { Email = toAddr }, + SubstitutionData = new Dictionary { { "firstName", "Jane" } } +}; + +trans.Recipients.Add(to); +trans.SubstitutionData["title"] = "Dr"; +trans.SubstitutionData["firstName"] = "Rick"; +trans.SubstitutionData["lastName"] = "Sanchez"; +trans.SubstitutionData["orders"] = new List { new(101, "Tomatoes", 5), new(271, "Entropy", 314) }; + +trans.Content.From.Email = fromAddr; +trans.Content.TemplateId = "orderSummary"; + +Console.Write("Sending mail..."); + +var client = new Client(apikey); + +var response = await client.Transmissions.Send(trans); + +Console.WriteLine("done"); diff --git a/examples/SendTemplate/Properties/AssemblyInfo.cs b/examples/SendTemplate/Properties/AssemblyInfo.cs deleted file mode 100644 index a48e3ac7..00000000 --- a/examples/SendTemplate/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("SendTemplate")] -[assembly: AssemblyDescription("SparkPost C# Send Template Example")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". -// The form "{Major}.{Minor}.*" will automatically update the build and revision, -// and "{Major}.{Minor}.{Build}.*" will update just the revision. - -[assembly: AssemblyVersion("1.0.*")] - -// The following attributes are used to specify the signing key for the assembly, -// if desired. See the Mono documentation for more information about signing. - -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile("")] - diff --git a/examples/SendTemplate/SendTemplate.csproj b/examples/SendTemplate/SendTemplate.csproj index 866d20e4..2abb2588 100644 --- a/examples/SendTemplate/SendTemplate.csproj +++ b/examples/SendTemplate/SendTemplate.csproj @@ -1,53 +1,9 @@ - - + - Debug - AnyCPU - {A85DDE10-EBD6-4B58-93D6-185809C73FE8} + net6.0 Exe - SendTemplate - SendTemplate - v4.5 - - true - full - false - bin\Debug - DEBUG; - prompt - 4 - true - - - full - true - bin\Release - prompt - 4 - true - - - - - - ..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll - - - ..\packages\SparkPost.1.6.2\lib\net45\SparkPost.dll - - - - - PreserveNewest - - - - - - app.config - - + \ No newline at end of file diff --git a/examples/SendTemplate/packages.config b/examples/SendTemplate/packages.config deleted file mode 100644 index 6a1b8114..00000000 --- a/examples/SendTemplate/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/examples/app.config b/examples/app.config deleted file mode 100644 index a69366c3..00000000 --- a/examples/app.config +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/src/SparkPost.Acceptance/ClientSteps.cs b/src/SparkPost.Acceptance/ClientSteps.cs index ec3d2160..a3ca26ad 100644 --- a/src/SparkPost.Acceptance/ClientSteps.cs +++ b/src/SparkPost.Acceptance/ClientSteps.cs @@ -11,7 +11,7 @@ public ClientSteps(ScenarioContext scenarioContext) { _scenarioContext = scenarioContext; } - + [Given(@"my api key is '(.*)'")] public void GivenMyApiKeyIs(string apiKey) { @@ -19,4 +19,4 @@ public void GivenMyApiKeyIs(string apiKey) _scenarioContext.Set(client); } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Acceptance/MessageEventsSteps.cs b/src/SparkPost.Acceptance/MessageEventsSteps.cs index 6b1d1183..2c072aa6 100644 --- a/src/SparkPost.Acceptance/MessageEventsSteps.cs +++ b/src/SparkPost.Acceptance/MessageEventsSteps.cs @@ -18,10 +18,10 @@ public async Task WhenIAskForSamplesOf(string events) { var client = _scenarioContext.Get(); - MessageEventSampleResponse response = await client.MessageEvents.SamplesOf(events); + MessageEventSampleResponse response = await client.MessageEvents.SamplesOf(events); _scenarioContext.Set(response); _scenarioContext.Set(response); } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Acceptance/MetricsSteps.cs b/src/SparkPost.Acceptance/MetricsSteps.cs index ee4616ec..e949fdfa 100644 --- a/src/SparkPost.Acceptance/MetricsSteps.cs +++ b/src/SparkPost.Acceptance/MetricsSteps.cs @@ -14,16 +14,12 @@ public MetricsSteps(ScenarioContext scenarioContext) { _scenarioContext = scenarioContext; } - + [When(@"I query my deliverability for (.*)")] public async Task WhenIQueryMyDeliverability(string metric) { var client = _scenarioContext.Get(); - Response response = await client.Metrics.GetDeliverability(new - { - from = DateTime.MinValue, - metrics = metric - }); + Response response = await client.Metrics.GetDeliverability(new { from = DateTime.MinValue, metrics = metric }); _scenarioContext.Set(response); } @@ -32,10 +28,7 @@ public async Task WhenIQueryMyDeliverability(string metric) public async Task y() { var client = _scenarioContext.Get(); - Response response = await client.Metrics.GetBounceReasons(new - { - from = DateTime.MinValue - }); + Response response = await client.Metrics.GetBounceReasons(new { from = DateTime.MinValue }); _scenarioContext.Set(response); } @@ -47,4 +40,4 @@ public void x() Assert.IsType(response); } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Acceptance/RecipientListSteps.cs b/src/SparkPost.Acceptance/RecipientListSteps.cs index 84adb907..044042a5 100644 --- a/src/SparkPost.Acceptance/RecipientListSteps.cs +++ b/src/SparkPost.Acceptance/RecipientListSteps.cs @@ -27,7 +27,7 @@ public void GivenIHaveANewRecipientListAs(Table table) public void GivenIAddToTheRecipientList(string email) { var recipientList = scenarioContext.Get(); - recipientList.Recipients.Add(new Recipient {Address = new Address {Email = email}}); + recipientList.Recipients.Add(new Recipient { Address = new Address { Email = email } }); } [Given(@"I clear the recipients on the recipient list")] @@ -89,10 +89,8 @@ public void ThenItShouldHaveTheFollowingRecipientListValues(Table table) [Then(@"it should have the following recipients")] public void ThenItShouldHaveTheFollowingRecipients(Table table) { - var recipientLists = scenarioContext.Get() - .Recipients - .Select(x => new {x.Address.Email}); + var recipientLists = scenarioContext.Get().Recipients.Select(x => new { x.Address.Email }); table.CompareToSet(recipientLists); } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Acceptance/ResponseSteps.cs b/src/SparkPost.Acceptance/ResponseSteps.cs index 3d326c7f..162186f2 100644 --- a/src/SparkPost.Acceptance/ResponseSteps.cs +++ b/src/SparkPost.Acceptance/ResponseSteps.cs @@ -12,12 +12,12 @@ public ResponseSteps(ScenarioContext scenarioContext) { _scenarioContext = scenarioContext; } - + [Then(@"it should return a (.*)")] public void ThenItShouldReturnA(int statusCode) { var response = _scenarioContext.Get(); - Assert.Equal(statusCode, response.StatusCode.GetHashCode()); + Assert.Equal(statusCode, response.StatusCode.GetHashCode()); } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Acceptance/SuppressionsSteps.cs b/src/SparkPost.Acceptance/SuppressionsSteps.cs index 2601b78e..53b7d32c 100644 --- a/src/SparkPost.Acceptance/SuppressionsSteps.cs +++ b/src/SparkPost.Acceptance/SuppressionsSteps.cs @@ -29,7 +29,7 @@ public async Task WhenIAddToMySuppressionsList() var client = scenarioContext.Get(); - UpdateSuppressionResponse response = await client.Suppressions.CreateOrUpdate(new [] {email}); + UpdateSuppressionResponse response = await client.Suppressions.CreateOrUpdate(new[] { email }); scenarioContext.Set(response); scenarioContext.Set(response); @@ -46,7 +46,6 @@ public async Task ThenShouldBeOnMySuppressionsList() response = await client.Suppressions.Retrieve(email); Assert.True(response.Suppressions.Any()); - } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Acceptance/TransmissionSteps.cs b/src/SparkPost.Acceptance/TransmissionSteps.cs index 38520632..f8e0326c 100644 --- a/src/SparkPost.Acceptance/TransmissionSteps.cs +++ b/src/SparkPost.Acceptance/TransmissionSteps.cs @@ -26,7 +26,7 @@ public void GivenIHaveANewTransmissionWith() public void GivenTheTransmissionIsMeantToBeSentfrom(string email) { var transmission = scenarioContext.Get(); - transmission.Content.From = new Address {Email = email}; + transmission.Content.From = new Address { Email = email }; scenarioContext.Set(transmission); } @@ -34,7 +34,7 @@ public void GivenTheTransmissionIsMeantToBeSentfrom(string email) public void GivenTheTransmissionIsMeantToBeSentTo(string email) { var transmission = scenarioContext.Get(); - transmission.Recipients.Add(new Recipient {Address = new Address {Email = email}}); + transmission.Recipients.Add(new Recipient { Address = new Address { Email = email } }); scenarioContext.Set(transmission); } @@ -73,11 +73,13 @@ public void GivenTheTransmissionIsMeantToBeCCdTo(string email) { var transmission = scenarioContext.Get(); - transmission.Recipients.Add(new Recipient - { - Type = RecipientType.CC, - Address = new Address {Email = email} - }); + transmission.Recipients.Add( + new Recipient + { + Type = RecipientType.CC, + Address = new Address { Email = email } + } + ); scenarioContext.Set(transmission); } @@ -87,11 +89,13 @@ public void GivenTheTransmissionIsMeantToBeBCCdTo(string email) { var transmission = scenarioContext.Get(); - transmission.Recipients.Add(new Recipient - { - Type = RecipientType.BCC, - Address = new Address {Email = email} - }); + transmission.Recipients.Add( + new Recipient + { + Type = RecipientType.BCC, + Address = new Address { Email = email } + } + ); scenarioContext.Set(transmission); } @@ -108,4 +112,4 @@ public async Task WhenISendTheTransmission() scenarioContext.Set(response); } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/ClientTests.cs b/src/SparkPost.Tests/ClientTests.cs index 8cf7836b..f1902011 100644 --- a/src/SparkPost.Tests/ClientTests.cs +++ b/src/SparkPost.Tests/ClientTests.cs @@ -39,12 +39,6 @@ public void It_should_allow_the_overriding_of_the_http_client_building() Assert.Equal(httpClient, client.CustomSettings.CreateANewHttpClient()); } - [Fact] - public void It_should_default_to_async() - { - Assert.Equal(SendingModes.Async, client.CustomSettings.SendingMode); - } - [Fact] public void it_should_have_inbound_domains() { @@ -58,4 +52,4 @@ public void It_should_set_any_subaccount_id_passed_to_it() } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/DataMapperTests.cs b/src/SparkPost.Tests/DataMapperTests.cs index ab14e862..48d61226 100644 --- a/src/SparkPost.Tests/DataMapperTests.cs +++ b/src/SparkPost.Tests/DataMapperTests.cs @@ -12,23 +12,19 @@ public class RecipientMappingTests private readonly DataMapper mapper; private readonly Recipient recipient; - public RecipientMappingTests() { recipient = new Recipient(); mapper = new DataMapper("v1"); } - + [Fact] public void address() { var value = Guid.NewGuid().ToString(); recipient.Address.Email = value; var x = mapper.ToDictionary(recipient)["address"]; - Assert.Equal(value, mapper.ToDictionary(recipient) - ["address"] - .CastAs>() - ["email"]); + Assert.Equal(value, mapper.ToDictionary(recipient)["address"].CastAs>()["email"]); } [Fact] @@ -48,10 +44,8 @@ public void tags() recipient.Tags.Add(tag2); var theTags = mapper.ToDictionary(recipient)["tags"]; Assert.Equal(2, theTags.CastAs>().Count()); - Assert.Contains(tag1, mapper.ToDictionary(recipient)["tags"] - .CastAs>()); - Assert.Contains(tag2, mapper.ToDictionary(recipient)["tags"] - .CastAs>()); + Assert.Contains(tag1, mapper.ToDictionary(recipient)["tags"].CastAs>()); + Assert.Contains(tag2, mapper.ToDictionary(recipient)["tags"].CastAs>()); } [Fact] @@ -66,8 +60,7 @@ public void metadata() var key = Guid.NewGuid().ToString(); var value = Guid.NewGuid().ToString(); recipient.Metadata[key] = value; - Assert.Equal(value, mapper.ToDictionary(recipient)["metadata"] - .CastAs>()[key]); + Assert.Equal(value, mapper.ToDictionary(recipient)["metadata"].CastAs>()[key]); } [Fact] @@ -82,8 +75,7 @@ public void substitution_data() var key = Guid.NewGuid().ToString(); var value = Guid.NewGuid().ToString(); recipient.SubstitutionData[key] = value; - Assert.Equal(value, mapper.ToDictionary(recipient)["substitution_data"] - .CastAs>()[key]); + Assert.Equal(value, mapper.ToDictionary(recipient)["substitution_data"].CastAs>()[key]); } [Fact] @@ -98,8 +90,7 @@ public void do_not_alter_the_keys_passed_to_substitution_data() var key = "TEST"; var value = Guid.NewGuid().ToString(); recipient.SubstitutionData[key] = value; - Assert.Equal(value, mapper.ToDictionary(recipient)["substitution_data"] - .CastAs>()[key]); + Assert.Equal(value, mapper.ToDictionary(recipient)["substitution_data"].CastAs>()[key]); } [Fact] @@ -110,7 +101,6 @@ public void The_type_should_be_ignored() } } - public class AddressMappingTests { private readonly Address address; @@ -169,9 +159,12 @@ public void It_should_set_the_content_dictionary() { var email = Guid.NewGuid().ToString(); transmission.Content.From = new Address { Email = email }; - Assert.Equal(email, mapper.ToDictionary(transmission)["content"] - .CastAs>()["from"] - .CastAs>()["email"]); + Assert.Equal( + email, + mapper.ToDictionary(transmission)["content"].CastAs>()["from"].CastAs>()[ + "email" + ] + ); } [Fact] @@ -184,12 +177,8 @@ public void It_should_set_the_recipients() var result = mapper.ToDictionary(transmission)["recipients"] as IEnumerable>; Assert.Equal(2, result.Count()); - Assert.Equal(recipient1.Address.Email, result.ToList()[0]["address"] - .CastAs>() - ["email"]); - Assert.Equal(recipient2.Address.Email, result.ToList()[1]["address"] - .CastAs>() - ["email"]); + Assert.Equal(recipient1.Address.Email, result.ToList()[0]["address"].CastAs>()["email"]); + Assert.Equal(recipient2.Address.Email, result.ToList()[1]["address"].CastAs>()["email"]); } [Fact] @@ -238,8 +227,7 @@ public void metadata() var key = Guid.NewGuid().ToString(); var value = Guid.NewGuid().ToString(); transmission.Metadata[key] = value; - Assert.Equal(value, mapper.ToDictionary(transmission)["metadata"] - .CastAs>()[key]); + Assert.Equal(value, mapper.ToDictionary(transmission)["metadata"].CastAs>()[key]); } [Fact] @@ -248,8 +236,7 @@ public void do_not_alter_the_keys_passed_to_metadata() var key = "TEST"; var value = Guid.NewGuid().ToString(); transmission.Metadata[key] = value; - Assert.Equal(value, mapper.ToDictionary(transmission)["metadata"] - .CastAs>()[key]); + Assert.Equal(value, mapper.ToDictionary(transmission)["metadata"].CastAs>()[key]); } [Fact] @@ -264,8 +251,7 @@ public void substitution_data() var key = Guid.NewGuid().ToString(); var value = Guid.NewGuid().ToString(); transmission.SubstitutionData[key] = value; - Assert.Equal(value, mapper.ToDictionary(transmission)["substitution_data"] - .CastAs>()[key]); + Assert.Equal(value, mapper.ToDictionary(transmission)["substitution_data"].CastAs>()[key]); } [Fact] @@ -280,28 +266,23 @@ public void do_not_alter_the_keys_passed_to_substitution_data() var key = "TEST"; var value = Guid.NewGuid().ToString(); transmission.SubstitutionData[key] = value; - Assert.Equal(value, mapper.ToDictionary(transmission)["substitution_data"] - .CastAs>()[key]); + Assert.Equal(value, mapper.ToDictionary(transmission)["substitution_data"].CastAs>()[key]); } [Fact] public void options() { transmission.Options.ClickTracking = true; - Assert.True((bool)mapper.ToDictionary(transmission)["options"] - .CastAs>()["click_tracking"]); + Assert.True((bool)mapper.ToDictionary(transmission)["options"].CastAs>()["click_tracking"]); transmission.Options.ClickTracking = false; - Assert.False((bool)mapper.ToDictionary(transmission)["options"] - .CastAs>()["click_tracking"]); + Assert.False((bool)mapper.ToDictionary(transmission)["options"].CastAs>()["click_tracking"]); transmission.Options.InlineCss = true; - Assert.True((bool)mapper.ToDictionary(transmission)["options"] - .CastAs>()["inline_css"]); + Assert.True((bool)mapper.ToDictionary(transmission)["options"].CastAs>()["inline_css"]); } } - public class MappingCcFields { private readonly Transmission transmission; @@ -318,18 +299,34 @@ public MappingCcFields() [InlineData(false)] public void It_should_set_the_CC_Header_for_only_the_cc_emails(bool useTo) { - var recipient1 = new Recipient { Type = RecipientType.CC, Address = new Address { Email = Guid.NewGuid().ToString() } }; - var recipient2 = new Recipient { Type = RecipientType.BCC, Address = new Address { Email = Guid.NewGuid().ToString() } }; - var recipient3 = new Recipient { Type = RecipientType.CC, Address = new Address { Email = Guid.NewGuid().ToString() } }; + var recipient1 = new Recipient + { + Type = RecipientType.CC, + Address = new Address { Email = Guid.NewGuid().ToString() } + }; + var recipient2 = new Recipient + { + Type = RecipientType.BCC, + Address = new Address { Email = Guid.NewGuid().ToString() } + }; + var recipient3 = new Recipient + { + Type = RecipientType.CC, + Address = new Address { Email = Guid.NewGuid().ToString() } + }; var recipient4 = useTo - ? new Recipient { Type = RecipientType.To, Address = new Address { Email = Guid.NewGuid().ToString() } } - : new Recipient(); + ? new Recipient + { + Type = RecipientType.To, + Address = new Address { Email = Guid.NewGuid().ToString() } + } + : new Recipient(); transmission.Recipients = new List { recipient1, recipient2, recipient3, recipient4 }; - var cc = mapper.ToDictionary(transmission)["content"] - .CastAs>()["headers"] - .CastAs>()["CC"]; + var cc = mapper.ToDictionary(transmission)["content"].CastAs>()["headers"].CastAs< + IDictionary + >()["CC"]; Assert.Equal(recipient1.Address.Email + ", " + recipient3.Address.Email, cc); } @@ -342,17 +339,22 @@ public void It_should_not_overwrite_any_existing_headers(bool useTo) var key = Guid.NewGuid().ToString(); var value = Guid.NewGuid().ToString(); - var recipient1 = new Recipient { Type = RecipientType.CC, Address = new Address { Email = Guid.NewGuid().ToString() } }; - var recipient2 = useTo - ? new Recipient { Type = RecipientType.To, Address = new Address() } - : new Recipient(); + var recipient1 = new Recipient + { + Type = RecipientType.CC, + Address = new Address { Email = Guid.NewGuid().ToString() } + }; + var recipient2 = useTo ? new Recipient { Type = RecipientType.To, Address = new Address() } : new Recipient(); transmission.Recipients = new List { recipient1, recipient2 }; transmission.Content.Headers[key] = value; - Assert.Equal(value, mapper.ToDictionary(transmission)["content"] - .CastAs>()["headers"] - .CastAs>()[key]); + Assert.Equal( + value, + mapper.ToDictionary(transmission)["content"].CastAs>()["headers"].CastAs< + IDictionary + >()[key] + ); } [Theory] @@ -364,17 +366,31 @@ public void It_should_not_set_the_cc_if_there_are_no_cc_emails(bool useTo) var value = Guid.NewGuid().ToString(); var recipient1 = useTo - ? new Recipient { Type = RecipientType.To, Address = new Address { Email = Guid.NewGuid().ToString() } } - : new Recipient(); - var recipient2 = new Recipient { Type = RecipientType.BCC, Address = new Address { Email = Guid.NewGuid().ToString() } }; - var recipient3 = new Recipient { Type = RecipientType.BCC, Address = new Address { Email = Guid.NewGuid().ToString() } }; + ? new Recipient + { + Type = RecipientType.To, + Address = new Address { Email = Guid.NewGuid().ToString() } + } + : new Recipient(); + var recipient2 = new Recipient + { + Type = RecipientType.BCC, + Address = new Address { Email = Guid.NewGuid().ToString() } + }; + var recipient3 = new Recipient + { + Type = RecipientType.BCC, + Address = new Address { Email = Guid.NewGuid().ToString() } + }; transmission.Recipients = new List { recipient1, recipient2, recipient3 }; transmission.Content.Headers[key] = value; - Assert.False(mapper.ToDictionary(transmission)["content"] - .CastAs>()["headers"] - .CastAs>().ContainsKey("CC")); + Assert.False( + mapper.ToDictionary(transmission)["content"].CastAs>()["headers"] + .CastAs>() + .ContainsKey("CC") + ); } [Theory] @@ -383,14 +399,20 @@ public void It_should_not_set_the_cc_if_there_are_no_cc_emails(bool useTo) public void It_should_not_set_a_header_value_if_there_are_no_ccs(bool useTo) { var recipient1 = useTo - ? new Recipient { Type = RecipientType.To, Address = new Address { Email = Guid.NewGuid().ToString() } } - : new Recipient(); - var recipient2 = new Recipient { Type = RecipientType.BCC, Address = new Address { Email = Guid.NewGuid().ToString() } }; + ? new Recipient + { + Type = RecipientType.To, + Address = new Address { Email = Guid.NewGuid().ToString() } + } + : new Recipient(); + var recipient2 = new Recipient + { + Type = RecipientType.BCC, + Address = new Address { Email = Guid.NewGuid().ToString() } + }; transmission.Recipients = new List { recipient1, recipient2 }; - Assert.False(mapper.ToDictionary(transmission)["content"] - .CastAs>() - .ContainsKey("headers")); + Assert.False(mapper.ToDictionary(transmission)["content"].CastAs>().ContainsKey("headers")); } [Theory] @@ -398,16 +420,25 @@ public void It_should_not_set_a_header_value_if_there_are_no_ccs(bool useTo) [InlineData(false)] public void It_should_ignore_empty_ccs(bool useTo) { - var recipient1 = new Recipient { Type = RecipientType.CC, Address = new Address { Email = "" } }; - var recipient2 = new Recipient { Type = RecipientType.CC, Address = new Address { Email = null } }; - var recipient3 = new Recipient { Type = RecipientType.CC, Address = new Address { Email = " " } }; - var toRecipient = useTo - ? new Recipient { Type = RecipientType.To, Address = new Address() } - : new Recipient(); + var recipient1 = new Recipient + { + Type = RecipientType.CC, + Address = new Address { Email = "" } + }; + var recipient2 = new Recipient + { + Type = RecipientType.CC, + Address = new Address { Email = null } + }; + var recipient3 = new Recipient + { + Type = RecipientType.CC, + Address = new Address { Email = " " } + }; + var toRecipient = useTo ? new Recipient { Type = RecipientType.To, Address = new Address() } : new Recipient(); transmission.Recipients = new List { recipient1, recipient2, recipient3, toRecipient }; - Assert.False(mapper.ToDictionary(transmission)["content"] - .CastAs>().ContainsKey("headers")); + Assert.False(mapper.ToDictionary(transmission)["content"].CastAs>().ContainsKey("headers")); } [Theory] @@ -416,15 +447,10 @@ public void It_should_ignore_empty_ccs(bool useTo) public void It_should_ignore_any_cc_recipients_with_no_address(bool useTo) { var recipient1 = new Recipient { Type = RecipientType.CC, Address = null }; - var toRecipient = useTo - ? new Recipient { Type = RecipientType.To, Address = new Address() } - : new Recipient(); + var toRecipient = useTo ? new Recipient { Type = RecipientType.To, Address = new Address() } : new Recipient(); transmission.Recipients = new List { recipient1, toRecipient }; - Assert.False(mapper.ToDictionary(transmission) - ["content"] - .CastAs>() - .ContainsKey("headers")); + Assert.False(mapper.ToDictionary(transmission)["content"].CastAs>().ContainsKey("headers")); } [Fact] @@ -438,11 +464,10 @@ public void It_should_set_the_name_and_header_to_fields() var bccRecipient = new Recipient { Type = RecipientType.BCC, Address = new Address() }; transmission.Recipients = new List() { toRecipient, ccRecipient, bccRecipient }; - var addresses = mapper.ToDictionary(transmission) - ["recipients"] - .CastAs>>() - .Select(r => r["address"]) - .Cast>(); + var addresses = mapper.ToDictionary(transmission)["recipients"] + .CastAs>>() + .Select(r => r["address"]) + .Cast>(); foreach (var address in addresses) { @@ -462,9 +487,12 @@ public void It_should_format_addresses_correctly(string name, string address, st var recipient2 = new Recipient { Type = RecipientType.CC, Address = new Address(address, name) }; transmission.Recipients = new List { recipient1, recipient2 }; - Assert.Equal(result, mapper.ToDictionary(transmission)["content"] - .CastAs>()["headers"] - .CastAs>()["CC"]); + Assert.Equal( + result, + mapper.ToDictionary(transmission)["content"].CastAs>()["headers"].CastAs< + IDictionary + >()["CC"] + ); } [Theory] @@ -476,9 +504,12 @@ public void It_should_handle_white_space_in_the_email(string name, string addres var recipient2 = new Recipient { Type = RecipientType.CC, Address = new Address(address, name) }; transmission.Recipients = new List { recipient1, recipient2 }; - Assert.Equal(result, mapper.ToDictionary(transmission)["content"] - .CastAs>()["headers"] - .CastAs>()["CC"]); + Assert.Equal( + result, + mapper.ToDictionary(transmission)["content"].CastAs>()["headers"].CastAs< + IDictionary + >()["CC"] + ); } [Theory] @@ -495,9 +526,9 @@ public void It_should_use_new_or_legacy_handling(int numOfTos) transmission.Recipients.Add(new Recipient { Type = RecipientType.To, Address = new Address("bob@example.com") }); } - var ccHeader = mapper.ToDictionary(transmission)["content"] - .CastAs>()["headers"] - .CastAs>()["CC"]; + var ccHeader = mapper.ToDictionary(transmission)["content"].CastAs>()["headers"].CastAs< + IDictionary + >()["CC"]; if (numOfTos == 1) { @@ -516,9 +547,9 @@ public void It_should_use_legacy_handling_if_to_address_is_null() transmission.Recipients.Add(new Recipient { Type = RecipientType.CC, Address = new Address(ccAddress) }); transmission.Recipients.Add(new Recipient { Type = RecipientType.To, Address = null }); - var ccHeader = mapper.ToDictionary(transmission)["content"] - .CastAs>()["headers"] - .CastAs>()["CC"]; + var ccHeader = mapper.ToDictionary(transmission)["content"].CastAs>()["headers"].CastAs< + IDictionary + >()["CC"]; Assert.Equal($"<{ccAddress}>", ccHeader); } @@ -534,7 +565,7 @@ public ContentMappingTests() content = new Content(); mapper = new DataMapper("v1"); } - + [Fact] public void from() { @@ -595,8 +626,7 @@ public void headers() var key = Guid.NewGuid().ToString(); var value = Guid.NewGuid().ToString(); content.Headers[key] = value; - Assert.Equal(value, mapper.ToDictionary(content)["headers"] - .CastAs>()[key]); + Assert.Equal(value, mapper.ToDictionary(content)["headers"].CastAs>()[key]); } [Fact] @@ -665,7 +695,7 @@ public OptionsMappingTests() options = new Options(); mapper = new DataMapper("v1"); } - + [Fact] public void It_should_default_to_returning_null() { @@ -676,60 +706,50 @@ public void It_should_default_to_returning_null() public void open_tracking() { options.OpenTracking = true; - Assert.True((bool)mapper.ToDictionary(options).CastAs>() - ["open_tracking"]); + Assert.True((bool)mapper.ToDictionary(options).CastAs>()["open_tracking"]); options.OpenTracking = false; - Assert.False((bool)mapper.ToDictionary(options).CastAs>() - ["open_tracking"]); + Assert.False((bool)mapper.ToDictionary(options).CastAs>()["open_tracking"]); } [Fact] public void click_tracking() { options.ClickTracking = true; - Assert.True((bool)mapper.ToDictionary(options).CastAs>() - ["click_tracking"]); + Assert.True((bool)mapper.ToDictionary(options).CastAs>()["click_tracking"]); options.ClickTracking = false; - Assert.False((bool)mapper.ToDictionary(options).CastAs>() - ["click_tracking"]); + Assert.False((bool)mapper.ToDictionary(options).CastAs>()["click_tracking"]); } [Fact] public void transactional() { options.Transactional = true; - Assert.True((bool)mapper.ToDictionary(options).CastAs>() - ["transactional"]); + Assert.True((bool)mapper.ToDictionary(options).CastAs>()["transactional"]); options.Transactional = false; - Assert.False((bool)mapper.ToDictionary(options).CastAs>() - ["transactional"]); + Assert.False((bool)mapper.ToDictionary(options).CastAs>()["transactional"]); } [Fact] public void sandbox() { options.Sandbox = true; - Assert.True((bool)mapper.ToDictionary(options).CastAs>() - ["sandbox"]); + Assert.True((bool)mapper.ToDictionary(options).CastAs>()["sandbox"]); options.Sandbox = false; - Assert.False((bool)mapper.ToDictionary(options).CastAs>() - ["sandbox"]); + Assert.False((bool)mapper.ToDictionary(options).CastAs>()["sandbox"]); } [Fact] public void skip_suppression() { options.SkipSuppression = true; - Assert.True((bool)mapper.ToDictionary(options).CastAs>() - ["skip_suppression"]); + Assert.True((bool)mapper.ToDictionary(options).CastAs>()["skip_suppression"]); options.SkipSuppression = false; - Assert.False((bool)mapper.ToDictionary(options).CastAs>() - ["skip_suppression"]); + Assert.False((bool)mapper.ToDictionary(options).CastAs>()["skip_suppression"]); } [Fact] @@ -737,33 +757,28 @@ public void start_time() { var startTime = "2015-02-11T08:00:00-04:00"; options.StartTime = DateTimeOffset.Parse(startTime); - Assert.Equal(startTime, mapper.ToDictionary(options).CastAs>() - ["start_time"]); + Assert.Equal(startTime, mapper.ToDictionary(options).CastAs>()["start_time"]); startTime = "2015-02-11T08:00:00-14:00"; options.StartTime = DateTimeOffset.Parse(startTime); - Assert.Equal(startTime, mapper.ToDictionary(options).CastAs>() - ["start_time"]); + Assert.Equal(startTime, mapper.ToDictionary(options).CastAs>()["start_time"]); } [Fact] public void hide_start_time_if_it_is_missing() { options.OpenTracking = true; - Assert.DoesNotContain("start_time", mapper.ToDictionary(options) - .CastAs>().Keys); + Assert.DoesNotContain("start_time", mapper.ToDictionary(options).CastAs>().Keys); } [Fact] public void inline_css() { options.InlineCss = true; - Assert.True((bool)mapper.ToDictionary(options).CastAs>() - ["inline_css"]); + Assert.True((bool)mapper.ToDictionary(options).CastAs>()["inline_css"]); options.InlineCss = false; - Assert.False((bool)mapper.ToDictionary(options).CastAs>() - ["inline_css"]); + Assert.False((bool)mapper.ToDictionary(options).CastAs>()["inline_css"]); } [Fact] @@ -771,8 +786,7 @@ public void ip_pool() { var ipPool = Guid.NewGuid().ToString(); options.IpPool = ipPool; - Assert.Equal(ipPool, mapper.ToDictionary(options).CastAs>() - ["ip_pool"]); + Assert.Equal(ipPool, mapper.ToDictionary(options).CastAs>()["ip_pool"]); } } @@ -882,26 +896,15 @@ public void AuthRequestDetails() var authRequestDetails = dictionary["auth_request_details"].CastAs>(); Assert.Equal("https://oauth.myurl.com/tokens", authRequestDetails["url"]); - Assert.Equal("", authRequestDetails["body"] - .CastAs>() - ["client_id"]); + Assert.Equal("", authRequestDetails["body"].CastAs>()["client_id"]); - Assert.Equal("", authRequestDetails["body"] - .CastAs>() - ["client_secret"]); + Assert.Equal("", authRequestDetails["body"].CastAs>()["client_secret"]); } [Fact] public void AuthCredentials() { - var webhook = new Webhook - { - AuthCredentials = new - { - access_token = "", - ExpiresIn = 3600 - } - }; + var webhook = new Webhook { AuthCredentials = new { access_token = "", ExpiresIn = 3600 } }; var dictionary = dataMapper.ToDictionary(webhook); var authRequestDetails = dictionary["auth_credentials"] as Dictionary; @@ -910,7 +913,6 @@ public void AuthCredentials() } } - public class SubaccountTests { private readonly DataMapper dataMapper; @@ -997,8 +999,7 @@ public void match_domain() { var value = Guid.NewGuid().ToString(); relayWebhook.Match = new RelayWebhookMatch { Domain = value }; - Assert.Equal(value, mapper.ToDictionary(relayWebhook)["match"] - .CastAs>()["domain"]); + Assert.Equal(value, mapper.ToDictionary(relayWebhook)["match"].CastAs>()["domain"]); } [Fact] @@ -1006,8 +1007,7 @@ public void match_protocol() { var value = Guid.NewGuid().ToString(); relayWebhook.Match = new RelayWebhookMatch { Protocol = value }; - Assert.Equal(value, mapper.ToDictionary(relayWebhook)["match"] - .CastAs>()["protocol"]); + Assert.Equal(value, mapper.ToDictionary(relayWebhook)["match"].CastAs>()["protocol"]); } } @@ -1028,9 +1028,7 @@ public void Matches_on_status() sendingDomain.Status = new SendingDomainStatus(); sendingDomain.Status.DkimStatus = DkimStatus.Pending; - Assert.Equal("pending", mapper.ToDictionary(sendingDomain)["status"] - .CastAs>() - ["dkim_status"]); + Assert.Equal("pending", mapper.ToDictionary(sendingDomain)["status"].CastAs>()["dkim_status"]); } [Fact] @@ -1046,17 +1044,14 @@ public void Matches_on_dkim() { var publicKey = Guid.NewGuid().ToString(); sendingDomain.Dkim = new Dkim { PublicKey = publicKey }; - Assert.Equal(publicKey, mapper.ToDictionary(sendingDomain)["dkim"] - .CastAs>() - ["public_key"]); + Assert.Equal(publicKey, mapper.ToDictionary(sendingDomain)["dkim"].CastAs>()["public_key"]); } [Fact] public void Null_dkim_is_is_not_returned() { sendingDomain.Dkim = null; - Assert.False(mapper.ToDictionary(sendingDomain) - .ContainsKey("dkim")); + Assert.False(mapper.ToDictionary(sendingDomain).ContainsKey("dkim")); } } @@ -1246,4 +1241,4 @@ public void limit() } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/FileTests.cs b/src/SparkPost.Tests/FileTests.cs index 14a1ba32..c4118a35 100644 --- a/src/SparkPost.Tests/FileTests.cs +++ b/src/SparkPost.Tests/FileTests.cs @@ -46,6 +46,5 @@ private string EncodeString(string input) { return Convert.ToBase64String(GetBytes(input)); } - } } diff --git a/src/SparkPost.Tests/ListMessageEventsResponseTests.cs b/src/SparkPost.Tests/ListMessageEventsResponseTests.cs index 5f859c3c..a7bc654b 100644 --- a/src/SparkPost.Tests/ListMessageEventsResponseTests.cs +++ b/src/SparkPost.Tests/ListMessageEventsResponseTests.cs @@ -21,4 +21,4 @@ public void It_should_not_have_nil_events() } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/MessageEventsQueryTests.cs b/src/SparkPost.Tests/MessageEventsQueryTests.cs index a7ab717a..91437959 100644 --- a/src/SparkPost.Tests/MessageEventsQueryTests.cs +++ b/src/SparkPost.Tests/MessageEventsQueryTests.cs @@ -53,7 +53,6 @@ public void It_should_have_Transmissions_list() { Assert.NotNull(new MessageEventsQuery().TransmissionIds); } - } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/RelayWebhookTests.cs b/src/SparkPost.Tests/RelayWebhookTests.cs index ebcbf802..8dbf0143 100644 --- a/src/SparkPost.Tests/RelayWebhookTests.cs +++ b/src/SparkPost.Tests/RelayWebhookTests.cs @@ -19,4 +19,4 @@ public void It_should_initialize_match_protocol() } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/RequestMethodFinderTests.cs b/src/SparkPost.Tests/RequestMethodFinderTests.cs index 3641df3a..dc1ec50a 100644 --- a/src/SparkPost.Tests/RequestMethodFinderTests.cs +++ b/src/SparkPost.Tests/RequestMethodFinderTests.cs @@ -17,26 +17,26 @@ public FindForTests() [Fact] public void It_should_return_put_for_put() { - Assert.IsType(finder.FindFor(new Request {Method = "PUT"})); + Assert.IsType(finder.FindFor(new Request { Method = "PUT" })); } [Fact] public void It_should_return_post_for_post() { - Assert.IsType(finder.FindFor(new Request {Method = "POST"})); + Assert.IsType(finder.FindFor(new Request { Method = "POST" })); } [Fact] public void It_should_return_delete_for_delete() { - Assert.IsType(finder.FindFor(new Request {Method = "DELETE"})); + Assert.IsType(finder.FindFor(new Request { Method = "DELETE" })); } [Fact] public void It_should_return_get_for_get() { - Assert.IsType(finder.FindFor(new Request {Method = "GET"})); + Assert.IsType(finder.FindFor(new Request { Method = "GET" })); } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/RequestMethods/DeleteTests.cs b/src/SparkPost.Tests/RequestMethods/DeleteTests.cs index 472ef8b6..57182539 100644 --- a/src/SparkPost.Tests/RequestMethods/DeleteTests.cs +++ b/src/SparkPost.Tests/RequestMethods/DeleteTests.cs @@ -20,37 +20,37 @@ public CanExecuteTests() [Fact] public void It_should_return_true_for_delete() { - var request = new Request {Method = "DELETE"}; + var request = new Request { Method = "DELETE" }; Assert.True(delete.CanExecute(request)); } [Fact] public void It_should_return_true_for_delete_lower() { - var request = new Request {Method = "delete"}; + var request = new Request { Method = "delete" }; Assert.True(delete.CanExecute(request)); } [Fact] public void It_should_return_true_for_delete_spaces() { - var request = new Request {Method = "delete "}; + var request = new Request { Method = "delete " }; Assert.True(delete.CanExecute(request)); } [Fact] public void It_should_return_false_for_others() { - var request = new Request {Method = Guid.NewGuid().ToString()}; + var request = new Request { Method = Guid.NewGuid().ToString() }; Assert.False(delete.CanExecute(request)); } [Fact] public void It_should_return_false_for_null() { - var request = new Request {Method = null}; + var request = new Request { Method = null }; Assert.False(delete.CanExecute(request)); } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/RequestMethods/GetTests.cs b/src/SparkPost.Tests/RequestMethods/GetTests.cs index 34618d53..74b2d577 100644 --- a/src/SparkPost.Tests/RequestMethods/GetTests.cs +++ b/src/SparkPost.Tests/RequestMethods/GetTests.cs @@ -22,37 +22,37 @@ public CanExecuteTests() [Fact] public void It_should_return_true_for_get() { - var request = new Request {Method = "GET"}; + var request = new Request { Method = "GET" }; Assert.True(get.CanExecute(request)); } [Fact] public void It_should_return_true_for_get_lower() { - var request = new Request {Method = "get"}; + var request = new Request { Method = "get" }; Assert.True(get.CanExecute(request)); } [Fact] public void It_should_return_true_for_get_spacing() { - var request = new Request {Method = "get "}; + var request = new Request { Method = "get " }; Assert.True(get.CanExecute(request)); } [Fact] public void It_should_return_false_for_others() { - var request = new Request {Method = Guid.NewGuid().ToString()}; + var request = new Request { Method = Guid.NewGuid().ToString() }; Assert.False(get.CanExecute(request)); } [Fact] public void It_should_return_false_for_null() { - var request = new Request {Method = null}; + var request = new Request { Method = null }; Assert.False(get.CanExecute(request)); } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/RequestMethods/PostTests.cs b/src/SparkPost.Tests/RequestMethods/PostTests.cs index 737fb583..7151c95f 100644 --- a/src/SparkPost.Tests/RequestMethods/PostTests.cs +++ b/src/SparkPost.Tests/RequestMethods/PostTests.cs @@ -20,37 +20,37 @@ public CanExecuteTests() [Fact] public void It_should_return_true_for_post() { - var request = new Request {Method = "POST"}; + var request = new Request { Method = "POST" }; Assert.True(post.CanExecute(request)); } [Fact] public void It_should_return_true_for_post_lower() { - var request = new Request {Method = "post"}; + var request = new Request { Method = "post" }; Assert.True(post.CanExecute(request)); } [Fact] public void It_should_return_true_for_post_spaces() { - var request = new Request {Method = "post "}; + var request = new Request { Method = "post " }; Assert.True(post.CanExecute(request)); } [Fact] public void It_should_return_false_for_others() { - var request = new Request {Method = Guid.NewGuid().ToString()}; + var request = new Request { Method = Guid.NewGuid().ToString() }; Assert.False(post.CanExecute(request)); } [Fact] public void It_should_return_false_for_nil() { - var request = new Request {Method = null}; + var request = new Request { Method = null }; Assert.False(post.CanExecute(request)); } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/RequestMethods/PutTests.cs b/src/SparkPost.Tests/RequestMethods/PutTests.cs index 583a0ee3..1a7ce30d 100644 --- a/src/SparkPost.Tests/RequestMethods/PutTests.cs +++ b/src/SparkPost.Tests/RequestMethods/PutTests.cs @@ -20,37 +20,37 @@ public CanExecuteTests() [Fact] public void It_should_return_true_for_put() { - var request = new Request {Method = "PUT"}; + var request = new Request { Method = "PUT" }; Assert.True(put.CanExecute(request)); } [Fact] public void It_should_return_true_for_put_lower() { - var request = new Request {Method = "put"}; + var request = new Request { Method = "put" }; Assert.True(put.CanExecute(request)); } [Fact] public void It_should_return_true_for_put_json() { - var request = new Request {Method = "PUT JSON"}; + var request = new Request { Method = "PUT JSON" }; Assert.True(put.CanExecute(request)); } [Fact] public void It_should_return_false_for_others() { - var request = new Request {Method = Guid.NewGuid().ToString()}; + var request = new Request { Method = Guid.NewGuid().ToString() }; Assert.False(put.CanExecute(request)); } [Fact] public void It_should_return_false_for_nil() { - var request = new Request {Method = null}; + var request = new Request { Method = null }; Assert.False(put.CanExecute(request)); } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/RequestSenders/AsyncRequestSenderTests.cs b/src/SparkPost.Tests/RequestSenders/AsyncRequestSenderTests.cs deleted file mode 100644 index 2b5a78e5..00000000 --- a/src/SparkPost.Tests/RequestSenders/AsyncRequestSenderTests.cs +++ /dev/null @@ -1,149 +0,0 @@ -using System; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; -using Moq; -using SparkPost.RequestSenders; -using Xunit; - -namespace SparkPost.Tests.RequestSenders -{ - public class AsyncRequestSenderTests - { - public class SendTests - { - private readonly Request request; - private readonly string apiHost; - private readonly string apiKey; - private readonly HttpResponseMessage defaultHttpResponseMessage; - private readonly SendTests.AsyncTesting asyncTesting; - private readonly Mock client; - - public SendTests() - { - var httpClient = new HttpClient(); - apiHost = "http://test.com"; - apiKey = Guid.NewGuid().ToString(); - - var settings = new Client.Settings(); - settings.BuildHttpClientsUsing(() => httpClient); - client = new Mock(); - client.Setup(x => x.CustomSettings).Returns(settings); - client.Setup(x => x.ApiHost).Returns(apiHost); - client.Setup(x => x.ApiKey).Returns(apiKey); - - asyncTesting = new SendTests.AsyncTesting(client.Object); - - request = new Request(); - - defaultHttpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(Guid.NewGuid().ToString()) - }; - } - - - [Fact] - public async void It_should_return_the_http_response_message_info() - { - var content = Guid.NewGuid().ToString(); - asyncTesting.SetupTheResponseWith((r, h) => new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(content) - }); - - var result = await asyncTesting.Send(request); - Assert.Equal(HttpStatusCode.Accepted, result.StatusCode); - Assert.Equal(content, result.Content); - } - - [Fact] - public async Task It_should_return_the_http_response_message_info_take_2() - { - var content = Guid.NewGuid().ToString(); - asyncTesting.SetupTheResponseWith((r, h) => new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent(content) - }); - - var result = await asyncTesting.Send(request); - Assert.Equal(HttpStatusCode.NotFound, result.StatusCode); - Assert.Equal("Not Found", result.ReasonPhrase); - Assert.Equal(content, result.Content); - } - - [Fact] - public async Task It_should_pass_the_api_key() - { - asyncTesting.SetupTheResponseWith((r, h) => - { - Assert.Equal(apiKey, h.DefaultRequestHeaders.Authorization.ToString()); - return defaultHttpResponseMessage; - }); - - await asyncTesting.Send(request); - } - - [Fact] - public async Task It_should_send_the_request_to_the_appropriate_host() - { - asyncTesting.SetupTheResponseWith((r, h) => - { - Assert.Equal(apiHost + "/", h.BaseAddress.ToString()); - return defaultHttpResponseMessage; - }); - - await asyncTesting.Send(request); - } - - [Fact] - public async Task It_should_set_the_subaccount_when_the_subaccount_is_not_zero() - { - client.Setup(x => x.SubaccountId).Returns(345); - asyncTesting.SetupTheResponseWith((r, h) => - { - var match = h.DefaultRequestHeaders.First(x => x.Key == "X-MSYS-SUBACCOUNT"); - Assert.Single(match.Value); - Assert.Equal("345", match.Value.First()); - return defaultHttpResponseMessage; - }); - - await asyncTesting.Send(request); - } - - [Fact] - public async Task It_should_NOT_set_a_subaccount_when_the_subaccount_is_zero() - { - client.Setup(x => x.SubaccountId).Returns(0); - asyncTesting.SetupTheResponseWith((r, h) => - { - var count = h.DefaultRequestHeaders.Count(x => x.Key == "X-MSYS-SUBACCOUNT"); - Assert.Equal(0, count); - return defaultHttpResponseMessage; - }); - - await asyncTesting.Send(request); - } - - public class AsyncTesting : AsyncRequestSender - { - private Func responseBuilder; - - public AsyncTesting(IClient client) : base(client, null) - { - } - - public void SetupTheResponseWith(Func responseBuilder) - { - this.responseBuilder = responseBuilder; - } - - protected override Task GetTheResponse(Request request, HttpClient httpClient) - { - return Task.FromResult(responseBuilder(request, httpClient)); - } - } - } - } -} \ No newline at end of file diff --git a/src/SparkPost.Tests/RequestSenders/RequestSenderTests.cs b/src/SparkPost.Tests/RequestSenders/RequestSenderTests.cs index 2e5e4e4b..5b7e3be0 100644 --- a/src/SparkPost.Tests/RequestSenders/RequestSenderTests.cs +++ b/src/SparkPost.Tests/RequestSenders/RequestSenderTests.cs @@ -1,4 +1,8 @@ -using System.Threading.Tasks; +using System; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; using Moq; using SparkPost.RequestSenders; using Xunit; @@ -7,49 +11,144 @@ namespace SparkPost.Tests.RequestSenders { public class RequestSenderTests { +#pragma warning disable CA1001 public class SendTests +#pragma warning restore CA1001 { - private readonly RequestSender fixture; private readonly Request request; - private readonly Mock async; - private readonly Mock sync; - private readonly Client client; + private readonly string apiHost; + private readonly string apiKey; + private readonly HttpResponseMessage defaultHttpResponseMessage; + private readonly SendTests.AsyncTesting asyncTesting; + private readonly Mock client; public SendTests() { - client = new Client(null); + var httpClient = new HttpClient(); + apiHost = "http://test.com"; + apiKey = Guid.NewGuid().ToString(); + + var settings = new Client.Settings(); + settings.BuildHttpClientsUsing(() => httpClient); + client = new Mock(); + client.Setup(x => x.CustomSettings).Returns(settings); + client.Setup(x => x.ApiHost).Returns(apiHost); + client.Setup(x => x.ApiKey).Returns(apiKey); + + asyncTesting = new SendTests.AsyncTesting(client.Object); request = new Request(); - async = new Mock(null, null); - sync = new Mock(null); + defaultHttpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted) + { + Content = new StringContent(Guid.NewGuid().ToString()) + }; + } - fixture = new RequestSender(async.Object, sync.Object, client); + [Fact] + public async void It_should_return_the_http_response_message_info() + { + var content = Guid.NewGuid().ToString(); + asyncTesting.SetupTheResponseWith( + (r, h) => new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(content) } + ); + + var result = await asyncTesting.Send(request); + Assert.Equal(HttpStatusCode.Accepted, result.StatusCode); + Assert.Equal(content, result.Content); } [Fact] - public void It_should_return_the_result_from_async() + public async Task It_should_return_the_http_response_message_info_take_2() { - client.CustomSettings.SendingMode = SendingModes.Async; + var content = Guid.NewGuid().ToString(); + asyncTesting.SetupTheResponseWith( + (r, h) => new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(content) } + ); - var response = Task.FromResult(new Response()); - async.Setup(x => x.Send(request)).Returns(response); + var result = await asyncTesting.Send(request); + Assert.Equal(HttpStatusCode.NotFound, result.StatusCode); + Assert.Equal("Not Found", result.ReasonPhrase); + Assert.Equal(content, result.Content); + } - var result = fixture.Send(request); - Assert.Equal(response.Result, result.Result); + [Fact] + public async Task It_should_pass_the_api_key() + { + asyncTesting.SetupTheResponseWith( + (r, h) => + { + Assert.Equal(apiKey, h.DefaultRequestHeaders.Authorization.ToString()); + return defaultHttpResponseMessage; + } + ); + + await asyncTesting.Send(request); } [Fact] - public void It_should_return_the_result_from_sync() + public async Task It_should_send_the_request_to_the_appropriate_host() { - client.CustomSettings.SendingMode = SendingModes.Sync; + asyncTesting.SetupTheResponseWith( + (r, h) => + { + Assert.Equal(apiHost + "/", h.BaseAddress.ToString()); + return defaultHttpResponseMessage; + } + ); + + await asyncTesting.Send(request); + } + + [Fact] + public async Task It_should_set_the_subaccount_when_the_subaccount_is_not_zero() + { + client.Setup(x => x.SubaccountId).Returns(345); + asyncTesting.SetupTheResponseWith( + (r, h) => + { + var match = h.DefaultRequestHeaders.First(x => x.Key == "X-MSYS-SUBACCOUNT"); + Assert.Single(match.Value); + Assert.Equal("345", match.Value.First()); + return defaultHttpResponseMessage; + } + ); + + await asyncTesting.Send(request); + } + + [Fact] + public async Task It_should_NOT_set_a_subaccount_when_the_subaccount_is_zero() + { + client.Setup(x => x.SubaccountId).Returns(0); + asyncTesting.SetupTheResponseWith( + (r, h) => + { + var count = h.DefaultRequestHeaders.Count(x => x.Key == "X-MSYS-SUBACCOUNT"); + Assert.Equal(0, count); + return defaultHttpResponseMessage; + } + ); + + await asyncTesting.Send(request); + } + + public class AsyncTesting : RequestSender + { + private Func responseBuilder; + + public AsyncTesting(IClient client) : base(client, null) { } - var response = Task.FromResult(new Response()); - sync.Setup(x => x.Send(request)).Returns(response); + public void SetupTheResponseWith(Func responseBuilder) + { + this.responseBuilder = responseBuilder; + } - var result = fixture.Send(request); - Assert.Equal(response.Result, result.Result); + protected override Task GetTheResponse(Request request, HttpClient httpClient) + { + return Task.FromResult(responseBuilder(request, httpClient)); + } } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/RequestSenders/SyncRequestSenderTests.cs b/src/SparkPost.Tests/RequestSenders/SyncRequestSenderTests.cs deleted file mode 100644 index 282dc20b..00000000 --- a/src/SparkPost.Tests/RequestSenders/SyncRequestSenderTests.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Threading.Tasks; -using Moq; -using SparkPost.RequestSenders; -using Xunit; - -namespace SparkPost.Tests.RequestSenders -{ - public class SyncRequestSenderTests - { - public class SendTests - { - private SyncRequestSender subject; - - [Fact] - public async Task It_should_return_the_result_from_the_parent_request_sender() - { - var request = new Request(); - var response = new Response(); - - var requestSender = new Mock(); - requestSender.Setup(x => x.Send(request)).Returns(Task.FromResult(response)); - subject = new SyncRequestSender(requestSender.Object); - - var result = await subject.Send(request); - - Assert.Equal(response, result); - } - } - } -} \ No newline at end of file diff --git a/src/SparkPost.Tests/SubaccountTest.cs b/src/SparkPost.Tests/SubaccountTest.cs index a0761537..89088670 100644 --- a/src/SparkPost.Tests/SubaccountTest.cs +++ b/src/SparkPost.Tests/SubaccountTest.cs @@ -1,7 +1,4 @@ namespace SparkPost.Tests { - public class SubaccountTests - { - - } -} \ No newline at end of file + public class SubaccountTests { } +} diff --git a/src/SparkPost.Tests/SuppressionTests.cs b/src/SparkPost.Tests/SuppressionTests.cs index a14b2a63..a77ed0b2 100644 --- a/src/SparkPost.Tests/SuppressionTests.cs +++ b/src/SparkPost.Tests/SuppressionTests.cs @@ -24,8 +24,7 @@ public DeleteTests() requestSender = new Mock(); - requestSender.Setup(x => x.Send(It.IsAny())) - .Returns(Task.FromResult(response)); + requestSender.Setup(x => x.Send(It.IsAny())).Returns(Task.FromResult(response)); var dataMapper = new Mock(); @@ -64,17 +63,17 @@ public async Task It_should_build_the_web_request_parameters_correctly() { var version = Guid.NewGuid().ToString(); - client - .Setup(x => x.Version) - .Returns(version); + client.Setup(x => x.Version).Returns(version); requestSender .Setup(x => x.Send(It.IsAny())) - .Callback((Request r) => - { - Assert.Equal($"api/{version}/suppression-list/{email}", r.Url); - Assert.Equal("DELETE", r.Method); - }) + .Callback( + (Request r) => + { + Assert.Equal($"api/{version}/suppression-list/{email}", r.Url); + Assert.Equal("DELETE", r.Method); + } + ) .Returns(Task.FromResult(response)); await suppressions.Delete(email); @@ -87,17 +86,17 @@ public async Task It_should_encode_the_email_address() var email = "testing@test.com"; - client - .Setup(x => x.Version) - .Returns(version); + client.Setup(x => x.Version).Returns(version); requestSender .Setup(x => x.Send(It.IsAny())) - .Callback((Request r) => - { - Assert.Equal($"api/{version}/suppression-list/testing%40test.com", r.Url); - Assert.Equal("DELETE", r.Method); - }) + .Callback( + (Request r) => + { + Assert.Equal($"api/{version}/suppression-list/testing%40test.com", r.Url); + Assert.Equal("DELETE", r.Method); + } + ) .Returns(Task.FromResult(response)); await suppressions.Delete(email); @@ -114,20 +113,12 @@ public class CreateOrUpdateTests public CreateOrUpdateTests() { - response = new Response - { - StatusCode = HttpStatusCode.OK - }; + response = new Response { StatusCode = HttpStatusCode.OK }; - suppressionsList = new List - { - new Suppression(), - new Suppression() - }; + suppressionsList = new List { new Suppression(), new Suppression() }; requestSender = new Mock(); - requestSender.Setup(x => x.Send(It.IsAny())) - .Returns(Task.FromResult(response)); + requestSender.Setup(x => x.Send(It.IsAny())).Returns(Task.FromResult(response)); var dataMapper = new Mock(); @@ -162,15 +153,16 @@ public async Task It_should_return_the_content() [Fact] public async Task It_should_make_a_properly_formed_request() { - client.Setup(x => x.Version) - .Returns(Guid.NewGuid().ToString()); + client.Setup(x => x.Version).Returns(Guid.NewGuid().ToString()); requestSender .Setup(x => x.Send(It.IsAny())) - .Callback((Request r) => - { - Assert.Equal($"api/{client.Object.Version}/suppression-list", r.Url); - Assert.Equal("PUT JSON", r.Method); - }) + .Callback( + (Request r) => + { + Assert.Equal($"api/{client.Object.Version}/suppression-list", r.Url); + Assert.Equal("PUT JSON", r.Method); + } + ) .Returns(Task.FromResult(response)); await suppressions.CreateOrUpdate(suppressionsList); @@ -185,4 +177,4 @@ public async Task It_should_throw_if_the_http_status_code_is_not_ok() } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/TransmissionTests.cs b/src/SparkPost.Tests/TransmissionTests.cs index e3bb16a0..9d761d91 100644 --- a/src/SparkPost.Tests/TransmissionTests.cs +++ b/src/SparkPost.Tests/TransmissionTests.cs @@ -44,7 +44,9 @@ public void It_should_not_be_missing_substition_data() } } +#pragma warning disable CA1001 public class ParseTests +#pragma warning restore CA1001 { private MailMessage mailMessage; private Transmission transmission; @@ -187,4 +189,4 @@ public void It_should_copy_attachments() } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/UserAgentTests.cs b/src/SparkPost.Tests/UserAgentTests.cs index c4d5de86..4ec749b9 100644 --- a/src/SparkPost.Tests/UserAgentTests.cs +++ b/src/SparkPost.Tests/UserAgentTests.cs @@ -29,4 +29,4 @@ public void It_should_allow_the_user_agent_to_be_changed() } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/Utilities/SnakeCaseTests.cs b/src/SparkPost.Tests/Utilities/SnakeCaseTests.cs index 8b62864f..8d337537 100644 --- a/src/SparkPost.Tests/Utilities/SnakeCaseTests.cs +++ b/src/SparkPost.Tests/Utilities/SnakeCaseTests.cs @@ -29,4 +29,4 @@ public void It_should_convert_null_to_null() Assert.Null(SnakeCase.Convert(null)); } } -} \ No newline at end of file +} diff --git a/src/SparkPost.Tests/WebhookTests.cs b/src/SparkPost.Tests/WebhookTests.cs index 51071a93..95bb438f 100644 --- a/src/SparkPost.Tests/WebhookTests.cs +++ b/src/SparkPost.Tests/WebhookTests.cs @@ -13,4 +13,4 @@ public void It_should_initialize_events() } } } -} \ No newline at end of file +} diff --git a/src/SparkPost.sln b/src/SparkPost.sln index 176fb061..c33291fc 100644 --- a/src/SparkPost.sln +++ b/src/SparkPost.sln @@ -9,6 +9,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SparkPost.Tests", "SparkPos EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SparkPost.Acceptance", "SparkPost.Acceptance\SparkPost.Acceptance.csproj", "{8F62193B-1C44-4E92-96C7-8EBD610F7669}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SendTemplate", "..\examples\SendTemplate\SendTemplate.csproj", "{A85DDE10-EBD6-4B58-93D6-185809C73FE8}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{1DC64ED8-82FD-4640-90F3-BD487C809039}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SendInline", "..\examples\SendInline\SendInline.csproj", "{8D45D223-E1FE-4652-A37E-09507AC4E107}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CC", "..\examples\CC\CC.csproj", "{2B086611-A56B-4857-9F7F-A8603D7AA3FD}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BCC", "..\examples\BCC\BCC.csproj", "{16978032-B34C-44B6-8DA1-475D751338F1}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -27,8 +37,30 @@ Global {8F62193B-1C44-4E92-96C7-8EBD610F7669}.Debug|Any CPU.Build.0 = Debug|Any CPU {8F62193B-1C44-4E92-96C7-8EBD610F7669}.Release|Any CPU.ActiveCfg = Release|Any CPU {8F62193B-1C44-4E92-96C7-8EBD610F7669}.Release|Any CPU.Build.0 = Release|Any CPU + {A85DDE10-EBD6-4B58-93D6-185809C73FE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A85DDE10-EBD6-4B58-93D6-185809C73FE8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A85DDE10-EBD6-4B58-93D6-185809C73FE8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A85DDE10-EBD6-4B58-93D6-185809C73FE8}.Release|Any CPU.Build.0 = Release|Any CPU + {8D45D223-E1FE-4652-A37E-09507AC4E107}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8D45D223-E1FE-4652-A37E-09507AC4E107}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8D45D223-E1FE-4652-A37E-09507AC4E107}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8D45D223-E1FE-4652-A37E-09507AC4E107}.Release|Any CPU.Build.0 = Release|Any CPU + {2B086611-A56B-4857-9F7F-A8603D7AA3FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2B086611-A56B-4857-9F7F-A8603D7AA3FD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2B086611-A56B-4857-9F7F-A8603D7AA3FD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2B086611-A56B-4857-9F7F-A8603D7AA3FD}.Release|Any CPU.Build.0 = Release|Any CPU + {16978032-B34C-44B6-8DA1-475D751338F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {16978032-B34C-44B6-8DA1-475D751338F1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {16978032-B34C-44B6-8DA1-475D751338F1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {16978032-B34C-44B6-8DA1-475D751338F1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {A85DDE10-EBD6-4B58-93D6-185809C73FE8} = {1DC64ED8-82FD-4640-90F3-BD487C809039} + {8D45D223-E1FE-4652-A37E-09507AC4E107} = {1DC64ED8-82FD-4640-90F3-BD487C809039} + {2B086611-A56B-4857-9F7F-A8603D7AA3FD} = {1DC64ED8-82FD-4640-90F3-BD487C809039} + {16978032-B34C-44B6-8DA1-475D751338F1} = {1DC64ED8-82FD-4640-90F3-BD487C809039} + EndGlobalSection EndGlobal diff --git a/src/SparkPost/Address.cs b/src/SparkPost/Address.cs index ca5e8c61..ebf9a84e 100644 --- a/src/SparkPost/Address.cs +++ b/src/SparkPost/Address.cs @@ -6,17 +6,11 @@ public class Address public string Email { get; set; } public string HeaderTo { get; set; } - public Address() - { - } + public Address() { } - public Address(string email): this(email, null, null) - { - } + public Address(string email) : this(email, null, null) { } - public Address(string email, string name): this(email, name, null) - { - } + public Address(string email, string name) : this(email, name, null) { } public Address(string email, string name, string headerTo) { @@ -25,4 +19,4 @@ public Address(string email, string name, string headerTo) this.HeaderTo = headerTo; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Attachment.cs b/src/SparkPost/Attachment.cs index 3239a85a..7d386ac8 100644 --- a/src/SparkPost/Attachment.cs +++ b/src/SparkPost/Attachment.cs @@ -1,6 +1,4 @@ namespace SparkPost { - public class Attachment : File - { - } -} \ No newline at end of file + public class Attachment : File { } +} diff --git a/src/SparkPost/Attributes.cs b/src/SparkPost/Attributes.cs index f9d1e02a..5b83b910 100644 --- a/src/SparkPost/Attributes.cs +++ b/src/SparkPost/Attributes.cs @@ -2,13 +2,10 @@ { public class Attributes { - public Attributes() - { - - } + public Attributes() { } public int InternalId { get; set; } public int ListGroupId { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/BounceClassesDetails.cs b/src/SparkPost/BounceClassesDetails.cs index 2c8eb3fb..efc6c124 100644 --- a/src/SparkPost/BounceClassesDetails.cs +++ b/src/SparkPost/BounceClassesDetails.cs @@ -11,27 +11,195 @@ static BounceClassesDetails() // The list was taken from: // https://support.sparkpost.com/customer/portal/articles/1929896 AllBounceClasses = new Dictionary(); - AllBounceClasses[BounceClass.Undefined] = (new BounceClassDetails { BounceClass = BounceClass.Undefined, Name = "Undefined", Description = "Undefined/unknown or unable to parse.", Category = BounceCategory.Undefined }); - AllBounceClasses[BounceClass.Undetermined] = (new BounceClassDetails { BounceClass = BounceClass.Undetermined, Name = "Undetermined", Description = "The response text could not be identified.", Category = BounceCategory.Undetermined }); - AllBounceClasses[BounceClass.InvalidRecipient] = (new BounceClassDetails { BounceClass = BounceClass.InvalidRecipient, Name = "Invalid Recipient", Description = "The recipient is invalid.", Category = BounceCategory.Hard }); - AllBounceClasses[BounceClass.SoftBounce] = (new BounceClassDetails { BounceClass = BounceClass.SoftBounce, Name = "Soft Bounce", Description = "The message soft bounced.", Category = BounceCategory.Soft }); - AllBounceClasses[BounceClass.DnsFailure] = (new BounceClassDetails { BounceClass = BounceClass.DnsFailure, Name = "DNS Failure", Description = "The message bounced due to a DNS failure.", Category = BounceCategory.Soft }); - AllBounceClasses[BounceClass.MailboxFull] = (new BounceClassDetails { BounceClass = BounceClass.MailboxFull, Name = "Mailbox Full", Description = "The message bounced due to the remote mailbox being over quota.", Category = BounceCategory.Soft }); - AllBounceClasses[BounceClass.TooLarge] = (new BounceClassDetails { BounceClass = BounceClass.TooLarge, Name = "Too Large", Description = "The message bounced because it was too large for the recipient.", Category = BounceCategory.Soft }); - AllBounceClasses[BounceClass.Timeout] = (new BounceClassDetails { BounceClass = BounceClass.Timeout, Name = "Timeout", Description = "The message timed out.", Category = BounceCategory.Soft }); - AllBounceClasses[BounceClass.AdminFailure] = (new BounceClassDetails { BounceClass = BounceClass.AdminFailure, Name = "Admin Failure", Description = "The message was failed by Momentum's configured policies.", Category = BounceCategory.Admin }); - AllBounceClasses[BounceClass.GenericBounceNoRecipient] = (new BounceClassDetails { BounceClass = BounceClass.GenericBounceNoRecipient, Name = "Generic Bounce: No RCPT", Description = "No recipient could be determined for the message.", Category = BounceCategory.Hard }); - AllBounceClasses[BounceClass.GenericBounce] = (new BounceClassDetails { BounceClass = BounceClass.GenericBounce, Name = "Generic Bounce", Description = "The message failed for unspecified reasons.", Category = BounceCategory.Soft }); - AllBounceClasses[BounceClass.MailBlock] = (new BounceClassDetails { BounceClass = BounceClass.MailBlock, Name = "Mail Block", Description = "The message was blocked by the receiver.", Category = BounceCategory.Block }); - AllBounceClasses[BounceClass.SpamBlock] = (new BounceClassDetails { BounceClass = BounceClass.SpamBlock, Name = "Spam Block", Description = "The message was blocked by the receiver as coming from a known spam source.", Category = BounceCategory.Block }); - AllBounceClasses[BounceClass.SpamContent] = (new BounceClassDetails { BounceClass = BounceClass.SpamContent, Name = "Spam Content", Description = "The message was blocked by the receiver as spam.", Category = BounceCategory.Block }); - AllBounceClasses[BounceClass.ProhibitedAttachment] = (new BounceClassDetails { BounceClass = BounceClass.ProhibitedAttachment, Name = "Prohibited Attachment", Description = "The message was blocked by the receiver because it contained an attachment.", Category = BounceCategory.Block }); - AllBounceClasses[BounceClass.RelayingDenied] = (new BounceClassDetails { BounceClass = BounceClass.RelayingDenied, Name = "Relaying Denied", Description = "The message was blocked by the receiver because relaying is not allowed.", Category = BounceCategory.Block }); - AllBounceClasses[BounceClass.AutoReply] = (new BounceClassDetails { BounceClass = BounceClass.AutoReply, Name = "Auto-Reply", Description = "The message is an auto-reply/vacation mail.", Category = BounceCategory.Soft }); - AllBounceClasses[BounceClass.TransientFailure] = (new BounceClassDetails { BounceClass = BounceClass.TransientFailure, Name = "Transient Failure", Description = "Message transmission has been temporarily delayed.", Category = BounceCategory.Soft }); - AllBounceClasses[BounceClass.Subscribe] = (new BounceClassDetails { BounceClass = BounceClass.Subscribe, Name = "Subscribe", Description = "The message is a subscribe request.", Category = BounceCategory.Admin }); - AllBounceClasses[BounceClass.Unsubscribe] = (new BounceClassDetails { BounceClass = BounceClass.Unsubscribe, Name = "Unsubscribe", Description = "The message is an unsubscribe request.", Category = BounceCategory.Hard }); - AllBounceClasses[BounceClass.ChallengeResponse] = (new BounceClassDetails { BounceClass = BounceClass.ChallengeResponse, Name = "Challenge-Response", Description = "The message is a challenge-response probe.", Category = BounceCategory.Soft }); + AllBounceClasses[BounceClass.Undefined] = ( + new BounceClassDetails + { + BounceClass = BounceClass.Undefined, + Name = "Undefined", + Description = "Undefined/unknown or unable to parse.", + Category = BounceCategory.Undefined + } + ); + AllBounceClasses[BounceClass.Undetermined] = ( + new BounceClassDetails + { + BounceClass = BounceClass.Undetermined, + Name = "Undetermined", + Description = "The response text could not be identified.", + Category = BounceCategory.Undetermined + } + ); + AllBounceClasses[BounceClass.InvalidRecipient] = ( + new BounceClassDetails + { + BounceClass = BounceClass.InvalidRecipient, + Name = "Invalid Recipient", + Description = "The recipient is invalid.", + Category = BounceCategory.Hard + } + ); + AllBounceClasses[BounceClass.SoftBounce] = ( + new BounceClassDetails + { + BounceClass = BounceClass.SoftBounce, + Name = "Soft Bounce", + Description = "The message soft bounced.", + Category = BounceCategory.Soft + } + ); + AllBounceClasses[BounceClass.DnsFailure] = ( + new BounceClassDetails + { + BounceClass = BounceClass.DnsFailure, + Name = "DNS Failure", + Description = "The message bounced due to a DNS failure.", + Category = BounceCategory.Soft + } + ); + AllBounceClasses[BounceClass.MailboxFull] = ( + new BounceClassDetails + { + BounceClass = BounceClass.MailboxFull, + Name = "Mailbox Full", + Description = "The message bounced due to the remote mailbox being over quota.", + Category = BounceCategory.Soft + } + ); + AllBounceClasses[BounceClass.TooLarge] = ( + new BounceClassDetails + { + BounceClass = BounceClass.TooLarge, + Name = "Too Large", + Description = "The message bounced because it was too large for the recipient.", + Category = BounceCategory.Soft + } + ); + AllBounceClasses[BounceClass.Timeout] = ( + new BounceClassDetails + { + BounceClass = BounceClass.Timeout, + Name = "Timeout", + Description = "The message timed out.", + Category = BounceCategory.Soft + } + ); + AllBounceClasses[BounceClass.AdminFailure] = ( + new BounceClassDetails + { + BounceClass = BounceClass.AdminFailure, + Name = "Admin Failure", + Description = "The message was failed by Momentum's configured policies.", + Category = BounceCategory.Admin + } + ); + AllBounceClasses[BounceClass.GenericBounceNoRecipient] = ( + new BounceClassDetails + { + BounceClass = BounceClass.GenericBounceNoRecipient, + Name = "Generic Bounce: No RCPT", + Description = "No recipient could be determined for the message.", + Category = BounceCategory.Hard + } + ); + AllBounceClasses[BounceClass.GenericBounce] = ( + new BounceClassDetails + { + BounceClass = BounceClass.GenericBounce, + Name = "Generic Bounce", + Description = "The message failed for unspecified reasons.", + Category = BounceCategory.Soft + } + ); + AllBounceClasses[BounceClass.MailBlock] = ( + new BounceClassDetails + { + BounceClass = BounceClass.MailBlock, + Name = "Mail Block", + Description = "The message was blocked by the receiver.", + Category = BounceCategory.Block + } + ); + AllBounceClasses[BounceClass.SpamBlock] = ( + new BounceClassDetails + { + BounceClass = BounceClass.SpamBlock, + Name = "Spam Block", + Description = "The message was blocked by the receiver as coming from a known spam source.", + Category = BounceCategory.Block + } + ); + AllBounceClasses[BounceClass.SpamContent] = ( + new BounceClassDetails + { + BounceClass = BounceClass.SpamContent, + Name = "Spam Content", + Description = "The message was blocked by the receiver as spam.", + Category = BounceCategory.Block + } + ); + AllBounceClasses[BounceClass.ProhibitedAttachment] = ( + new BounceClassDetails + { + BounceClass = BounceClass.ProhibitedAttachment, + Name = "Prohibited Attachment", + Description = "The message was blocked by the receiver because it contained an attachment.", + Category = BounceCategory.Block + } + ); + AllBounceClasses[BounceClass.RelayingDenied] = ( + new BounceClassDetails + { + BounceClass = BounceClass.RelayingDenied, + Name = "Relaying Denied", + Description = "The message was blocked by the receiver because relaying is not allowed.", + Category = BounceCategory.Block + } + ); + AllBounceClasses[BounceClass.AutoReply] = ( + new BounceClassDetails + { + BounceClass = BounceClass.AutoReply, + Name = "Auto-Reply", + Description = "The message is an auto-reply/vacation mail.", + Category = BounceCategory.Soft + } + ); + AllBounceClasses[BounceClass.TransientFailure] = ( + new BounceClassDetails + { + BounceClass = BounceClass.TransientFailure, + Name = "Transient Failure", + Description = "Message transmission has been temporarily delayed.", + Category = BounceCategory.Soft + } + ); + AllBounceClasses[BounceClass.Subscribe] = ( + new BounceClassDetails + { + BounceClass = BounceClass.Subscribe, + Name = "Subscribe", + Description = "The message is a subscribe request.", + Category = BounceCategory.Admin + } + ); + AllBounceClasses[BounceClass.Unsubscribe] = ( + new BounceClassDetails + { + BounceClass = BounceClass.Unsubscribe, + Name = "Unsubscribe", + Description = "The message is an unsubscribe request.", + Category = BounceCategory.Hard + } + ); + AllBounceClasses[BounceClass.ChallengeResponse] = ( + new BounceClassDetails + { + BounceClass = BounceClass.ChallengeResponse, + Name = "Challenge-Response", + Description = "The message is a challenge-response probe.", + Category = BounceCategory.Soft + } + ); } } } diff --git a/src/SparkPost/CcHandling.cs b/src/SparkPost/CcHandling.cs index df7e2058..1d548a00 100644 --- a/src/SparkPost/CcHandling.cs +++ b/src/SparkPost/CcHandling.cs @@ -43,7 +43,8 @@ private static void SetAnyCCsInTheHeader(IEnumerable recipients, IDic { var ccs = GetTheCcEmails(recipients); - if (ccs.Any() == false) return; + if (ccs.Any() == false) + return; string ccHeader = FormatTheCCs(ccs); SetTheCcHeader(result, ccHeader); @@ -79,13 +80,9 @@ private static bool RecipientTypeIsCC(Recipient recipient) return recipient.Type == RecipientType.CC; } - private static void SetFieldsOnRecipients(IEnumerable> recipients, - string name, string email) + private static void SetFieldsOnRecipients(IEnumerable> recipients, string name, string email) { - var addresses = recipients - .Where(r => r.ContainsKey("address")) - .Select(r => r["address"]) - .Cast>(); + var addresses = recipients.Where(r => r.ContainsKey("address")).Select(r => r["address"]).Cast>(); foreach (var address in addresses) { @@ -130,8 +127,7 @@ private static void MakeSureThereIsAHeaderDefinedInTheRequest(IDictionary result, string key, string value) { - ((IDictionary) ((IDictionary) result["content"])["headers"]) - [key] = value; + ((IDictionary)((IDictionary)result["content"])["headers"])[key] = value; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Client.cs b/src/SparkPost/Client.cs index 084d78f5..f581003c 100644 --- a/src/SparkPost/Client.cs +++ b/src/SparkPost/Client.cs @@ -10,20 +10,11 @@ public class Client : IClient { private const string defaultApiHost = "https://api.sparkpost.com"; - public Client(string apiKey) : this(apiKey, defaultApiHost, 0) - { + public Client(string apiKey) : this(apiKey, defaultApiHost, 0) { } - } + public Client(string apiKey, string apiHost) : this(apiKey, apiHost, 0) { } - public Client(string apiKey, string apiHost) : this(apiKey, apiHost, 0) - { - - } - - public Client(string apiKey, long subAccountId) : this(apiKey, defaultApiHost, subAccountId) - { - - } + public Client(string apiKey, long subAccountId) : this(apiKey, defaultApiHost, subAccountId) { } public Client(string apiKey, string apiHost, long subAccountId) { @@ -32,9 +23,7 @@ public Client(string apiKey, string apiHost, long subAccountId) SubaccountId = subAccountId; var dataMapper = new DataMapper(Version); - var asyncRequestSender = new AsyncRequestSender(this, dataMapper); - var syncRequestSender = new SyncRequestSender(asyncRequestSender); - var requestSender = new RequestSender(asyncRequestSender, syncRequestSender, this); + var requestSender = new RequestSender(this, dataMapper); SendingDomains = new SendingDomains(this, requestSender, dataMapper); Transmissions = new Transmissions(this, requestSender, dataMapper); @@ -93,7 +82,6 @@ public Settings() UserAgent = $"csharp-sparkpost/{currentVersion}"; } - public SendingModes SendingMode { get; set; } public string UserAgent { get; set; } public HttpClient CreateANewHttpClient() @@ -120,11 +108,8 @@ private static string GetTheCurrentVersion() private static string AttemptToPullTheVersionNumberOutOf(string value) { - return value.SplitOn("Version=")[1] - .SplitOn(",")[0] - .SplitOn(".").Take(3) - .JoinWith("."); + return value.SplitOn("Version=")[1].SplitOn(",")[0].SplitOn(".").Take(3).JoinWith("."); } } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Content.cs b/src/SparkPost/Content.cs index ab89b095..436e83ee 100644 --- a/src/SparkPost/Content.cs +++ b/src/SparkPost/Content.cs @@ -23,4 +23,4 @@ public Content() public string TemplateId { get; set; } public bool? UseDraftTemplate { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/CreateSendingDomainResponse.cs b/src/SparkPost/CreateSendingDomainResponse.cs index 4a48a81d..acfeefd7 100644 --- a/src/SparkPost/CreateSendingDomainResponse.cs +++ b/src/SparkPost/CreateSendingDomainResponse.cs @@ -3,7 +3,7 @@ public class CreateSendingDomainResponse : Response { public string Domain { get; set; } - + public Dkim Dkim { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/CreateSubaccountResponse.cs b/src/SparkPost/CreateSubaccountResponse.cs index c8b1a2fb..2fd65c7b 100644 --- a/src/SparkPost/CreateSubaccountResponse.cs +++ b/src/SparkPost/CreateSubaccountResponse.cs @@ -7,4 +7,4 @@ public class CreateSubaccountResponse : Response public string Label { get; set; } public string ShortKey { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/DataMapper.cs b/src/SparkPost/DataMapper.cs index ba94e6c0..70378490 100644 --- a/src/SparkPost/DataMapper.cs +++ b/src/SparkPost/DataMapper.cs @@ -86,9 +86,10 @@ public virtual IDictionary ToDictionary(Transmission transmissio { ["substitution_data"] = AlterThisDictionaryToBePassedToSparkpost(transmission.SubstitutionData), ["metadata"] = AlterThisDictionaryToBePassedToSparkpost(transmission.Metadata), - ["recipients"] = transmission.ListId != null - ? (object) new Dictionary {["list_id"] = transmission.ListId} - : transmission.Recipients.Select(ToDictionary) + ["recipients"] = + transmission.ListId != null + ? (object)new Dictionary { ["list_id"] = transmission.ListId } + : transmission.Recipients.Select(ToDictionary) }; var result = WithCommonConventions(transmission, data); @@ -100,21 +101,20 @@ public virtual IDictionary ToDictionary(Transmission transmissio private static IDictionary AlterThisDictionaryToBePassedToSparkpost(IDictionary dictionary) { - return dictionary != null && dictionary.Keys.Any() - ? dictionary - : null; + return dictionary != null && dictionary.Keys.Any() ? dictionary : null; } public virtual IDictionary ToDictionary(Recipient recipient) { - return WithCommonConventions(recipient, new Dictionary() - { - ["type"] = null, - ["substitution_data"] = - recipient.SubstitutionData != null && recipient.SubstitutionData.Keys.Any() - ? recipient.SubstitutionData - : null, - }); + return WithCommonConventions( + recipient, + new Dictionary() + { + ["type"] = null, + ["substitution_data"] = + recipient.SubstitutionData != null && recipient.SubstitutionData.Keys.Any() ? recipient.SubstitutionData : null, + } + ); } public virtual IDictionary ToDictionary(Suppression suppression) @@ -179,34 +179,40 @@ public IDictionary ToDictionary(RelayWebhookMatch relayWebhookMa public IDictionary ToDictionary(MessageEventsQuery query) { - return WithCommonConventions(query, new Dictionary() - { - ["events"] = string.Join(",", query.Events), - ["campaign_ids"] = string.Join(",", query.CampaignIds), - ["bounce_classes"] = string.Join(",", query.BounceClasses), - ["campaign_ids"] = string.Join(",", query.CampaignIds), - ["friendly_froms"] = string.Join(",", query.FriendlyFroms), - ["message_ids"] = string.Join(",", query.MessageIds), - ["recipients"] = string.Join(",", query.Recipients), - ["subaccounts"] = string.Join(",", query.Subaccounts), - ["template_ids"] = string.Join(",", query.TemplateIds), - ["transmission_ids"] = string.Join(",", query.TransmissionIds) - }); + return WithCommonConventions( + query, + new Dictionary() + { + ["events"] = string.Join(",", query.Events), + ["campaign_ids"] = string.Join(",", query.CampaignIds), + ["bounce_classes"] = string.Join(",", query.BounceClasses), + ["campaign_ids"] = string.Join(",", query.CampaignIds), + ["friendly_froms"] = string.Join(",", query.FriendlyFroms), + ["message_ids"] = string.Join(",", query.MessageIds), + ["recipients"] = string.Join(",", query.Recipients), + ["subaccounts"] = string.Join(",", query.Subaccounts), + ["template_ids"] = string.Join(",", query.TemplateIds), + ["transmission_ids"] = string.Join(",", query.TransmissionIds) + } + ); } public IDictionary ToDictionary(MetricsQuery query) { - return WithCommonConventions(query, new Dictionary() - { - ["domains"] = string.Join(",", query.Domains), - ["campaigns"] = string.Join(",", query.Campaigns), - ["templates"] = string.Join(",", query.Templates), - ["sending_ips"] = string.Join(",", query.SendingIps), - ["ip_pools"] = string.Join(",", query.IpPools), - ["sending_domains"] = string.Join(",", query.SendingDomains), - ["subaccounts"] = string.Join(",", query.Subaccounts), - ["metrics"] = string.Join(",", query.Metrics) - }); + return WithCommonConventions( + query, + new Dictionary() + { + ["domains"] = string.Join(",", query.Domains), + ["campaigns"] = string.Join(",", query.Campaigns), + ["templates"] = string.Join(",", query.Templates), + ["sending_ips"] = string.Join(",", query.SendingIps), + ["ip_pools"] = string.Join(",", query.IpPools), + ["sending_domains"] = string.Join(",", query.SendingDomains), + ["subaccounts"] = string.Join(",", query.Subaccounts), + ["metrics"] = string.Join(",", query.Metrics) + } + ); } public virtual IDictionary ToDictionary(Template template) @@ -228,46 +234,46 @@ public IDictionary CatchAll(object anything) { var converters = ToDictionaryMethods(); if (converters.ContainsKey(anything.GetType())) - return converters[anything.GetType()].Invoke(this, BindingFlags.Default, null, - new[] {anything}, CultureInfo.CurrentCulture) as IDictionary; + return converters[anything.GetType()].Invoke(this, BindingFlags.Default, null, new[] { anything }, CultureInfo.CurrentCulture) + as IDictionary; return WithCommonConventions(anything); } public IDictionary ToDictionaryMethods() { - return this.GetType().GetMethods() + return this.GetType() + .GetMethods() .Where(x => x.Name == "ToDictionary") .Where(x => x.GetParameters().Length == 1) - .Select(x => new - { - TheType = x.GetParameters().First().ParameterType, - TheMethod = x - }).ToList() + .Select(x => new { TheType = x.GetParameters().First().ParameterType, TheMethod = x }) + .ToList() .ToDictionary(x => x.TheType, x => x.TheMethod); } private static bool AnyValuesWereSetOn(object target) { - return target.GetType() - .GetProperties() - .Any(x => x.GetValue(target) != null); + return target.GetType().GetProperties().Any(x => x.GetValue(target) != null); } private static IDictionary RemoveNulls(IDictionary dictionary) { var blanks = dictionary.Keys.Where(k => dictionary[k] == null).ToList(); - foreach (var key in blanks) dictionary.Remove(key); + foreach (var key in blanks) + dictionary.Remove(key); return dictionary; } private IDictionary WithCommonConventions(object target, IDictionary results = null) { - if (target == null) return null; - if (results == null) results = new Dictionary(); + if (target == null) + return null; + if (results == null) + results = new Dictionary(); foreach (var property in target.GetType().GetProperties()) { var name = SnakeCase.Convert(property.Name); - if (results.ContainsKey(name)) continue; + if (results.ContainsKey(name)) + continue; results[name] = GetTheValue(property.PropertyType, property.GetValue(target)); } @@ -282,18 +288,21 @@ public object GetTheValue(Type propertyType, object value) public IDictionary ToDictionary(RecipientList recipientList) { - var data = new Dictionary { ["recipients"] = recipientList.Recipients.Select(ToDictionary), - ["attributes"] = recipientList.Attributes != null - ? (object)new Dictionary { - ["internal_id"] = recipientList.Attributes.InternalId - , ["list_group_id"] = recipientList.Attributes.ListGroupId } : null + ["attributes"] = + recipientList.Attributes != null + ? (object) + new Dictionary + { + ["internal_id"] = recipientList.Attributes.InternalId, + ["list_group_id"] = recipientList.Attributes.ListGroupId + } + : null }; var result = WithCommonConventions(recipientList, data); return result; - } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Dkim.cs b/src/SparkPost/Dkim.cs index 9e17e32d..2aca64d7 100644 --- a/src/SparkPost/Dkim.cs +++ b/src/SparkPost/Dkim.cs @@ -30,4 +30,4 @@ public static Dkim ConvertToDkim(dynamic result) : null; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Dns.cs b/src/SparkPost/Dns.cs index e778e1cc..a46f31a4 100644 --- a/src/SparkPost/Dns.cs +++ b/src/SparkPost/Dns.cs @@ -28,4 +28,4 @@ public static Dns ConvertToDns(dynamic result) : null; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Events.cs b/src/SparkPost/Events.cs index d708ce71..8c4ccf1e 100644 --- a/src/SparkPost/Events.cs +++ b/src/SparkPost/Events.cs @@ -21,11 +21,7 @@ public Events(Client client, IRequestSender requestSender) public async Task Get(string cursor = "initial", int perPage = 1000) { - var request = new Request - { - Url = $"api/{client.Version}/events/message?perPage={perPage}&cursor={cursor}", - Method = "GET" - }; + var request = new Request { Url = $"api/{client.Version}/events/message?perPage={perPage}&cursor={cursor}", Method = "GET" }; var response = await requestSender.Send(request); if (response.StatusCode != HttpStatusCode.OK) @@ -35,6 +31,7 @@ public async Task Get(string cursor = "initial", int perPage var results = Jsonification.DeserializeObject(response.Content); return results; } + public async Task GetEventsSince(DateTime fromTime, int perPage = 1000) { var request = new Request @@ -54,11 +51,7 @@ public async Task GetEventsSince(DateTime fromTime, int perPa public async Task GetEventsNext(string nextUri) { - var request = new Request - { - Url = nextUri, - Method = "GET" - }; + var request = new Request { Url = nextUri, Method = "GET" }; var response = await requestSender.Send(request); if (response.StatusCode != HttpStatusCode.OK) @@ -74,15 +67,14 @@ public class JsonEventResponse { [JsonProperty("results")] public JObject[] Results { get; set; } + [JsonProperty("total_count")] public int TotalCount { get; set; } public Links Links { get; set; } - } public class Links { public string Next { get; set; } } - } diff --git a/src/SparkPost/File.cs b/src/SparkPost/File.cs index cf180000..120cc141 100644 --- a/src/SparkPost/File.cs +++ b/src/SparkPost/File.cs @@ -13,7 +13,7 @@ public abstract class File public static T Create(string filename) where T : File, new() { var content = System.IO.File.ReadAllBytes(filename); - return Create(content, Path.GetFileName(filename)); + return Create(content, Path.GetFileName(filename)); } public static T Create(string filename, string name) where T : File, new() @@ -36,7 +36,8 @@ public abstract class File result.Data = Convert.ToBase64String(content); result.Type = MimeMapping.MimeUtility.GetMimeMapping(name); result.Name = name; - }; + } + ; return result; } @@ -54,4 +55,4 @@ public abstract class File } } } -} \ No newline at end of file +} diff --git a/src/SparkPost/GetMetricsResourceResponse.cs b/src/SparkPost/GetMetricsResourceResponse.cs index 6db4efc8..a064b574 100644 --- a/src/SparkPost/GetMetricsResourceResponse.cs +++ b/src/SparkPost/GetMetricsResourceResponse.cs @@ -6,14 +6,14 @@ namespace SparkPost { - public class GetMetricsResourceResponse: Response + public class GetMetricsResourceResponse : Response { public IList Results { get; set; } public GetMetricsResourceResponse() { Results = new List(); - } + } public GetMetricsResourceResponse(Response source) { diff --git a/src/SparkPost/GetMetricsResponse.cs b/src/SparkPost/GetMetricsResponse.cs index c2675f86..a2cbacfb 100644 --- a/src/SparkPost/GetMetricsResponse.cs +++ b/src/SparkPost/GetMetricsResponse.cs @@ -6,7 +6,7 @@ namespace SparkPost { - public class GetMetricsResponse: Response + public class GetMetricsResponse : Response { public IList> Results { get; set; } diff --git a/src/SparkPost/GetSendingDomainResponse.cs b/src/SparkPost/GetSendingDomainResponse.cs index 8156854f..8aae080c 100644 --- a/src/SparkPost/GetSendingDomainResponse.cs +++ b/src/SparkPost/GetSendingDomainResponse.cs @@ -1,8 +1,9 @@ using Newtonsoft.Json; + namespace SparkPost { public class GetSendingDomainResponse : Response { public SendingDomain SendingDomain { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/IClient.cs b/src/SparkPost/IClient.cs index 06f13125..a922c405 100644 --- a/src/SparkPost/IClient.cs +++ b/src/SparkPost/IClient.cs @@ -49,7 +49,7 @@ public interface IClient /// Gets access to the sending domains resource of the SparkPost API. /// ISendingDomains SendingDomains { get; } - + /// /// Gets access to the relay webhooks resource of the SparkPost API. /// diff --git a/src/SparkPost/IMessageEvents.cs b/src/SparkPost/IMessageEvents.cs index a4a58cd9..a82b3e65 100644 --- a/src/SparkPost/IMessageEvents.cs +++ b/src/SparkPost/IMessageEvents.cs @@ -8,4 +8,4 @@ public interface IMessageEvents Task List(object query); Task SamplesOf(string events); } -} \ No newline at end of file +} diff --git a/src/SparkPost/IMetrics.cs b/src/SparkPost/IMetrics.cs index 91d0443e..2cead223 100644 --- a/src/SparkPost/IMetrics.cs +++ b/src/SparkPost/IMetrics.cs @@ -14,108 +14,126 @@ public interface IMetrics /// /// Task GetDeliverability(object query); + /// /// Provides aggregate metrics grouped by domain over the time window specified. /// /// /// Task GetDeliverabilityByDomain(object query); + /// /// Provides aggregate metrics grouped by sending IP over the time window specified. /// /// /// Task GetDeliverabilityBySendingIp(object query); + /// /// Provides aggregate metrics grouped by IP pool over the time window specified. /// /// /// Task GetDeliverabilityByIpPool(object query); + /// /// Provides aggregate metrics grouped by sending domain over the time window specified. /// /// /// Task GetDeliverabilityBySendingDomain(object query); + /// /// Provides aggregate metrics grouped by subaccount over the time window specified. Please note that master account events will be returned grouped by the subaccount_id field containing the value 0. /// /// /// Task GetDeliverabilityBySubaccount(object query); + /// /// Provides aggregate metrics grouped by campaign over the time window specified. /// /// /// Task GetDeliverabilityByCampaign(object query); + /// /// Provides aggregate metrics grouped by template over the time window specified. /// /// /// Task GetDeliverabilityByTemplate(object query); + /// /// Provides aggregate metrics grouped by watched domain over the time window specified. /// /// /// Task GetDeliverabilityByWatchedDomain(object query); + /// /// Provides deliverability metrics ordered by a precision of time. /// /// /// Task GetDeliverabilityByTimeSeries(object query); + /// /// Provides deliverability metrics, specific to bounce events, grouped by the bounce reasons. /// /// /// Task GetBounceReasons(object query); + /// /// Provides deliverability metrics, specific to bounce events, grouped by the domain and bounce reasons. /// /// /// Task GetBounceReasonsByDomain(object query); + /// /// Provides deliverability metrics, specific to bounce events, grouped by the bounce classification. /// /// /// Task GetBounceClassifications(object query); + /// /// Provides deliverability metrics, specific to rejection events, grouped by the rejection reasons. /// /// /// Task GetRejectionReasons(object query); + /// /// Provides deliverability metrics, specific to rejection events, grouped by the domain and rejection reasons. /// /// /// Task GetRejectionReasonsByDomain(object query); + /// /// Provides deliverability metrics, specific to delay events, grouped by the delay reasons. /// /// /// Task GetDelayReasons(object query); + /// /// Provides deliverability metrics, specific to delay events, grouped by the domain and delay reasons. /// /// /// Task GetDelayReasonsByDomain(object query); + /// /// Provides deliverability metrics, specific to engagement events (clicks/opens);, grouped by the link name or URL. /// /// /// Task GetEngagementDetails(object query); + /// /// Provides aggregate count of deliveries grouped by the attempt number. /// @@ -128,45 +146,51 @@ public interface IMetrics /// /// Task GetDomains(); + /// /// Returns a list of domains that the Metrics API contains data on. /// /// /// Task GetDomains(object metricsSimpleQuery); + /// /// Returns a list of IP pools that the Metrics API contains data on. /// /// Task GetIpPools(); + /// - /// Returns a list of IP pools that the Metrics API contains data on. + /// Returns a list of IP pools that the Metrics API contains data on. /// /// /// Task GetIpPools(object metricsSimpleQuery); + /// /// Returns a list of sending IPs that the Metrics API contains data on. /// /// Task GetSendingIps(); + /// /// Returns a list of sending IPs that the Metrics API contains data on. /// /// /// Task GetSendingIps(object metricsSimpleQuery); + /// /// Returns a list of campaigns that the Metrics API contains data on. /// /// Task GetCampaigns(); + /// /// Returns a list of campaigns that the Metrics API contains data on. /// /// /// Task GetCampaigns(object metricsSimpleQuery); - } } diff --git a/src/SparkPost/IRecipientLists.cs b/src/SparkPost/IRecipientLists.cs index 41eaa549..0b93c0ba 100644 --- a/src/SparkPost/IRecipientLists.cs +++ b/src/SparkPost/IRecipientLists.cs @@ -33,4 +33,4 @@ public interface IRecipientLists /// Task Update(RecipientList recipientList); } -} \ No newline at end of file +} diff --git a/src/SparkPost/IRequestMethod.cs b/src/SparkPost/IRequestMethod.cs index 17e5e5ad..dcf09600 100644 --- a/src/SparkPost/IRequestMethod.cs +++ b/src/SparkPost/IRequestMethod.cs @@ -8,4 +8,4 @@ public interface IRequestMethod bool CanExecute(Request request); Task Execute(Request request); } -} \ No newline at end of file +} diff --git a/src/SparkPost/ISendingDomains.cs b/src/SparkPost/ISendingDomains.cs index dcec4766..466dc1c0 100644 --- a/src/SparkPost/ISendingDomains.cs +++ b/src/SparkPost/ISendingDomains.cs @@ -11,4 +11,4 @@ public interface ISendingDomains Task Delete(string domain); Task Verify(VerifySendingDomain verifySendingDomain); } -} \ No newline at end of file +} diff --git a/src/SparkPost/ISubaccounts.cs b/src/SparkPost/ISubaccounts.cs index a944c158..9558fa80 100644 --- a/src/SparkPost/ISubaccounts.cs +++ b/src/SparkPost/ISubaccounts.cs @@ -10,4 +10,4 @@ public interface ISubaccounts Task Update(SubaccountUpdate subaccount); } -} \ No newline at end of file +} diff --git a/src/SparkPost/ISuppressions.cs b/src/SparkPost/ISuppressions.cs index af8b7a49..72f69ed9 100644 --- a/src/SparkPost/ISuppressions.cs +++ b/src/SparkPost/ISuppressions.cs @@ -12,4 +12,4 @@ public interface ISuppressions Task CreateOrUpdate(IEnumerable suppressions); Task Delete(string email); } -} \ No newline at end of file +} diff --git a/src/SparkPost/ITransmissions.cs b/src/SparkPost/ITransmissions.cs index 7dbe7ec1..f13fffbc 100644 --- a/src/SparkPost/ITransmissions.cs +++ b/src/SparkPost/ITransmissions.cs @@ -27,4 +27,4 @@ public interface ITransmissions /// The response from the API. Task List(); } -} \ No newline at end of file +} diff --git a/src/SparkPost/IValueMapper.cs b/src/SparkPost/IValueMapper.cs index f865ad5d..a09fd11e 100644 --- a/src/SparkPost/IValueMapper.cs +++ b/src/SparkPost/IValueMapper.cs @@ -7,4 +7,4 @@ public interface IValueMapper bool CanMap(Type propertyType, object value); object Map(Type propertyType, object value); } -} \ No newline at end of file +} diff --git a/src/SparkPost/InboundDomain.cs b/src/SparkPost/InboundDomain.cs index 6332e9fb..22a9215a 100644 --- a/src/SparkPost/InboundDomain.cs +++ b/src/SparkPost/InboundDomain.cs @@ -4,4 +4,4 @@ public class InboundDomain { public string Domain { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/InboundDomainResponse.cs b/src/SparkPost/InboundDomainResponse.cs index ca0a14b3..eb63eb0d 100644 --- a/src/SparkPost/InboundDomainResponse.cs +++ b/src/SparkPost/InboundDomainResponse.cs @@ -18,4 +18,4 @@ public static InboundDomainResponse CreateFromResponse(Response response) return result; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/InboundDomains.cs b/src/SparkPost/InboundDomains.cs index 11f9c003..aba8ef80 100644 --- a/src/SparkPost/InboundDomains.cs +++ b/src/SparkPost/InboundDomains.cs @@ -27,7 +27,8 @@ public InboundDomains(IClient client, IRequestSender requestSender, IDataMapper public async Task List(object query = null) { - if (query == null) query = new {}; + if (query == null) + query = new { }; var request = new Request { Url = $"/api/{client.Version}/inbound-domains", @@ -36,21 +37,19 @@ public async Task List(object query = null) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return ListInboundDomainResponse.CreateFromResponse(response); } public async Task Retrieve(string domain) { - var request = new Request - { - Url = $"/api/{client.Version}/inbound-domains/{domain}", - Method = "GET" - }; + var request = new Request { Url = $"/api/{client.Version}/inbound-domains/{domain}", Method = "GET" }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return InboundDomainResponse.CreateFromResponse(response); } @@ -65,7 +64,8 @@ public async Task Create(InboundDomain inboundDomain) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var createInboundDomainResponse = new Response(); LeftRight.SetValuesToMatch(createInboundDomainResponse, response); @@ -74,14 +74,10 @@ public async Task Create(InboundDomain inboundDomain) public async Task Delete(string domain) { - var request = new Request - { - Url = $"/api/{client.Version}/inbound-domains/{domain}", - Method = "DELETE" - }; + var request = new Request { Url = $"/api/{client.Version}/inbound-domains/{domain}", Method = "DELETE" }; var response = await requestSender.Send(request); return response.StatusCode == HttpStatusCode.OK; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/InlineImage.cs b/src/SparkPost/InlineImage.cs index 0a92d328..f05f6efe 100644 --- a/src/SparkPost/InlineImage.cs +++ b/src/SparkPost/InlineImage.cs @@ -1,6 +1,4 @@ namespace SparkPost { - public class InlineImage : File - { - } -} \ No newline at end of file + public class InlineImage : File { } +} diff --git a/src/SparkPost/LeftRight.cs b/src/SparkPost/LeftRight.cs index 492fb674..3376b243 100644 --- a/src/SparkPost/LeftRight.cs +++ b/src/SparkPost/LeftRight.cs @@ -22,4 +22,4 @@ public static void SetValuesToMatch(object left, object right) } } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ListInboundDomainResponse.cs b/src/SparkPost/ListInboundDomainResponse.cs index 60b2f517..423e542d 100644 --- a/src/SparkPost/ListInboundDomainResponse.cs +++ b/src/SparkPost/ListInboundDomainResponse.cs @@ -31,10 +31,7 @@ private static IEnumerable BuildTheInboundDomainsFrom(Response re internal static InboundDomain ConvertToAInboundDomain(dynamic item) { - return new InboundDomain - { - Domain = item.domain - }; + return new InboundDomain { Domain = item.domain }; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ListMessageEventsResponse.cs b/src/SparkPost/ListMessageEventsResponse.cs index eaa1d913..2456590d 100644 --- a/src/SparkPost/ListMessageEventsResponse.cs +++ b/src/SparkPost/ListMessageEventsResponse.cs @@ -6,8 +6,8 @@ public class ListMessageEventsResponse : Response { public ListMessageEventsResponse() { - MessageEvents = new MessageEvent[] {}; - Links = new PageLink[] {}; + MessageEvents = new MessageEvent[] { }; + Links = new PageLink[] { }; } public IEnumerable MessageEvents { get; set; } @@ -16,4 +16,4 @@ public ListMessageEventsResponse() public int TotalCount { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ListRelayWebhookResponse.cs b/src/SparkPost/ListRelayWebhookResponse.cs index 75c51cd5..9d349e09 100644 --- a/src/SparkPost/ListRelayWebhookResponse.cs +++ b/src/SparkPost/ListRelayWebhookResponse.cs @@ -37,12 +37,8 @@ internal static RelayWebhook ConvertToARelayWebhook(dynamic item) Name = item.name, Target = item.target, AuthToken = item.auth_token, - Match = new RelayWebhookMatch - { - Protocol = item.match.protocol, - Domain = item.match.domain - } + Match = new RelayWebhookMatch { Protocol = item.match.protocol, Domain = item.match.domain } }; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ListSendingDomainResponse.cs b/src/SparkPost/ListSendingDomainResponse.cs index fc738ff4..460f7149 100644 --- a/src/SparkPost/ListSendingDomainResponse.cs +++ b/src/SparkPost/ListSendingDomainResponse.cs @@ -25,4 +25,4 @@ private static IEnumerable BuildTheSendingDomains(dynamic results return sendingDomains; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ListSubaccountResponse.cs b/src/SparkPost/ListSubaccountResponse.cs index 7669f769..3db36ed3 100644 --- a/src/SparkPost/ListSubaccountResponse.cs +++ b/src/SparkPost/ListSubaccountResponse.cs @@ -33,4 +33,4 @@ private static Subaccount ConvertToSubaccount(dynamic result) }; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ListSuppressionResponse.cs b/src/SparkPost/ListSuppressionResponse.cs index 4ee305e0..66d41fec 100644 --- a/src/SparkPost/ListSuppressionResponse.cs +++ b/src/SparkPost/ListSuppressionResponse.cs @@ -6,4 +6,4 @@ public class ListSuppressionResponse : Response { public IEnumerable Suppressions { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ListTransmissionResponse.cs b/src/SparkPost/ListTransmissionResponse.cs index 77c6b634..5b37b734 100644 --- a/src/SparkPost/ListTransmissionResponse.cs +++ b/src/SparkPost/ListTransmissionResponse.cs @@ -1,6 +1,4 @@ namespace SparkPost { - public class ListTransmissionResponse : Response - { - } -} \ No newline at end of file + public class ListTransmissionResponse : Response { } +} diff --git a/src/SparkPost/ListWebhookResponse.cs b/src/SparkPost/ListWebhookResponse.cs index 4a3a1e89..3169888f 100644 --- a/src/SparkPost/ListWebhookResponse.cs +++ b/src/SparkPost/ListWebhookResponse.cs @@ -14,7 +14,7 @@ public static ListWebhookResponse CreateFromResponse(Response response) var results = Jsonification.DeserializeObject(result.Content).results; var webhooks = new List(); - foreach(var r in results) + foreach (var r in results) webhooks.Add(ConvertToAWebhook(r)); result.Webhooks = webhooks; @@ -42,4 +42,4 @@ internal static Webhook ConvertToAWebhook(dynamic r) return webhook; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/MessageEvent.cs b/src/SparkPost/MessageEvent.cs index 69f9e8b1..7042153e 100644 --- a/src/SparkPost/MessageEvent.cs +++ b/src/SparkPost/MessageEvent.cs @@ -51,12 +51,11 @@ public BounceClass BounceClassEnum get { int bounceClassAsInt; - if (!int.TryParse(BounceClass, out bounceClassAsInt)) return SparkPost.BounceClass.Undefined; + if (!int.TryParse(BounceClass, out bounceClassAsInt)) + return SparkPost.BounceClass.Undefined; // note: these scare me, perhaps we should check that it is valid? var bounceClass = (BounceClass)bounceClassAsInt; - return bounceClass.ToString() == bounceClassAsInt.ToString() - ? SparkPost.BounceClass.Undefined - : bounceClass; + return bounceClass.ToString() == bounceClassAsInt.ToString() ? SparkPost.BounceClass.Undefined : bounceClass; } } @@ -137,7 +136,11 @@ public BounceClass BounceClassEnum [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use MessageEvent.MessageFrom.")] - public string MessageForm { get { return MessageFrom; } set { MessageFrom = value; } } + public string MessageForm + { + get { return MessageFrom; } + set { MessageFrom = value; } + } /// /// "msg_size": { @@ -333,4 +336,4 @@ public override string ToString() return $"{TypeEnum} from {FriendlyFrom} to {RecipientTo}"; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/MessageEventSampleResponse.cs b/src/SparkPost/MessageEventSampleResponse.cs index 887d5dcd..071c2875 100644 --- a/src/SparkPost/MessageEventSampleResponse.cs +++ b/src/SparkPost/MessageEventSampleResponse.cs @@ -1,6 +1,4 @@ namespace SparkPost { - public class MessageEventSampleResponse : Response - { - } -} \ No newline at end of file + public class MessageEventSampleResponse : Response { } +} diff --git a/src/SparkPost/MessageEventType.cs b/src/SparkPost/MessageEventType.cs index c55ecf35..98c48be5 100644 --- a/src/SparkPost/MessageEventType.cs +++ b/src/SparkPost/MessageEventType.cs @@ -144,6 +144,5 @@ public enum MessageEventType /// Relayed message has reached the maximum retry threshold and will be removed from the system. /// RelayPermfail - } } diff --git a/src/SparkPost/MessageEvents.cs b/src/SparkPost/MessageEvents.cs index 2afbaee9..33b9317d 100644 --- a/src/SparkPost/MessageEvents.cs +++ b/src/SparkPost/MessageEvents.cs @@ -24,7 +24,8 @@ public async Task List() public async Task List(object messageEventsQuery) { - if (messageEventsQuery == null) messageEventsQuery = new { }; + if (messageEventsQuery == null) + messageEventsQuery = new { }; var request = new Request { @@ -34,7 +35,8 @@ public async Task List(object messageEventsQuery) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); dynamic content = Jsonification.DeserializeObject(response.Content); @@ -53,14 +55,11 @@ public async Task List(object messageEventsQuery) public async Task SamplesOf(string events) { - var request = new Request - { - Url = $"/api/{client.Version}/message-events/events/samples?events={events}", - Method = "GET" - }; + var request = new Request { Url = $"/api/{client.Version}/message-events/events/samples?events={events}", Method = "GET" }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return new MessageEventSampleResponse { @@ -74,15 +73,12 @@ private static IEnumerable ConvertToLinks(dynamic page_links) { var links = new List(); - if (page_links == null) return links; + if (page_links == null) + return links; foreach (var page_link in page_links) { - links.Add(new PageLink - { - Href = page_link.href, - Type = page_link.rel - }); + links.Add(new PageLink { Href = page_link.href, Type = page_link.rel }); } return links; } @@ -91,55 +87,54 @@ private static IEnumerable ConvertResultsToAListOfMessageEvents(dy { var messageEvents = new List(); - if (results == null) return messageEvents; + if (results == null) + return messageEvents; foreach (var result in results) { - var metadata = - Jsonification.DeserializeObject>( - Jsonification.SerializeObject(result.rcpt_meta)); - var tags = - Jsonification.DeserializeObject>( - Jsonification.SerializeObject(result.rcpt_tags)); - messageEvents.Add(new MessageEvent - { - Type = result.type, - BounceClass = result.bounce_class, - CampaignId = result.campaign_id, - CustomerId = result.customer_id, - DeliveryMethod = result.delv_method, - DeviceToken = result.device_token, - ErrorCode = result.error_code, - IpAddress = result.ip_address, - MessageId = result.message_id, - MessageFrom = result.msg_from, - MessageSize = result.msg_size, - NumberOfRetries = result.num_retries, - RecipientTo = result.rcpt_to, - RecipientType = result.rcpt_type, - RawReason = result.raw_reason, - Reason = result.reason, - RoutingDomain = result.routing_domain, - Subject = result.subject, - TemplateId = result.template_id, - TemplateVersion = result.template_version, - Timestamp = result.timestamp, - TransmissionId = result.transmission_id, - EventId = result.event_id, - FriendlyFrom = result.friendly_from, - IpPool = result.ip_pool, - QueueTime = result.queue_time, - RawRecipientTo = result.raw_rcpt_to, - SendingIp = result.sending_ip, - TDate = result.tdate, - Transactional = result.transactional, - RemoteAddress = result.remote_addr, - Metadata = metadata, - TargetLinkUrl = result.target_link_url, - Tags = tags - }); + var metadata = Jsonification.DeserializeObject>(Jsonification.SerializeObject(result.rcpt_meta)); + var tags = Jsonification.DeserializeObject>(Jsonification.SerializeObject(result.rcpt_tags)); + messageEvents.Add( + new MessageEvent + { + Type = result.type, + BounceClass = result.bounce_class, + CampaignId = result.campaign_id, + CustomerId = result.customer_id, + DeliveryMethod = result.delv_method, + DeviceToken = result.device_token, + ErrorCode = result.error_code, + IpAddress = result.ip_address, + MessageId = result.message_id, + MessageFrom = result.msg_from, + MessageSize = result.msg_size, + NumberOfRetries = result.num_retries, + RecipientTo = result.rcpt_to, + RecipientType = result.rcpt_type, + RawReason = result.raw_reason, + Reason = result.reason, + RoutingDomain = result.routing_domain, + Subject = result.subject, + TemplateId = result.template_id, + TemplateVersion = result.template_version, + Timestamp = result.timestamp, + TransmissionId = result.transmission_id, + EventId = result.event_id, + FriendlyFrom = result.friendly_from, + IpPool = result.ip_pool, + QueueTime = result.queue_time, + RawRecipientTo = result.raw_rcpt_to, + SendingIp = result.sending_ip, + TDate = result.tdate, + Transactional = result.transactional, + RemoteAddress = result.remote_addr, + Metadata = metadata, + TargetLinkUrl = result.target_link_url, + Tags = tags + } + ); } return messageEvents; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/MessageEventsQuery.cs b/src/SparkPost/MessageEventsQuery.cs index 03912fc5..97ec0162 100644 --- a/src/SparkPost/MessageEventsQuery.cs +++ b/src/SparkPost/MessageEventsQuery.cs @@ -7,7 +7,6 @@ namespace SparkPost { public class MessageEventsQuery { - public MessageEventsQuery() { this.Events = new List(); @@ -114,6 +113,5 @@ public MessageEventsQuery() /// Example: 65832150921904138. /// public IList TransmissionIds { get; set; } - } -} \ No newline at end of file +} diff --git a/src/SparkPost/Metrics.cs b/src/SparkPost/Metrics.cs index 5031eb2a..7018996f 100644 --- a/src/SparkPost/Metrics.cs +++ b/src/SparkPost/Metrics.cs @@ -9,13 +9,13 @@ namespace SparkPost { - public class Metrics: IMetrics + public class Metrics : IMetrics { private readonly IClient client; private readonly IRequestSender requestSender; public Metrics(IClient client, IRequestSender requestSender) - { + { this.client = client; this.requestSender = requestSender; } @@ -239,7 +239,7 @@ public async Task GetIpPools() } /// - /// Returns a list of IP pools that the Metrics API contains data on. + /// Returns a list of IP pools that the Metrics API contains data on. /// /// /// @@ -264,7 +264,7 @@ public async Task GetSendingIps() /// public async Task GetSendingIps(object metricsSimpleQuery) { - return await GetMetricsResource("sending-ips", metricsSimpleQuery); + return await GetMetricsResource("sending-ips", metricsSimpleQuery); } /// @@ -294,7 +294,7 @@ private async Task GetMetricsResource(string resourc var result = new GetMetricsResourceResponse(response); result.Results = ConvertToStrings(content.results, resourceName); - return result; + return result; } private async Task GetMetrics(string relUrl, object query) @@ -321,25 +321,28 @@ private async Task GetApiResponse(string relUrl, object query) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return response; } private IList ConvertToStrings(dynamic input, string propName) { var result = new List(); - if (input == null) return result; + if (input == null) + return result; foreach (var item in input[propName]) result.Add((string)item); - + return result; } private IList> ConvertToDictionaries(dynamic input) { var result = new List>(); - if (input == null) return result; + if (input == null) + return result; foreach (var array in input) { @@ -356,4 +359,4 @@ private IList> ConvertToDictionaries(dynamic input) return result; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/MetricsField.cs b/src/SparkPost/MetricsField.cs index ea4674f3..2f1711cc 100644 --- a/src/SparkPost/MetricsField.cs +++ b/src/SparkPost/MetricsField.cs @@ -67,7 +67,8 @@ public static IList AllDeliverability { get { - return new List() { + return new List() + { Injected, Bounce, Rejected, @@ -107,15 +108,7 @@ public static IList AllDeliverability /// public static IList AllBounce { - get - { - return new List() - { - Bounce, - InBandBounce, - OutOfBandBounce - }; - } + get { return new List() { Bounce, InBandBounce, OutOfBandBounce }; } } /// @@ -123,14 +116,7 @@ public static IList AllBounce /// public static IList AllEngagement { - get - { - return new List() - { - Clicked, - RawClicked - }; - } + get { return new List() { Clicked, RawClicked }; } } - } + } } diff --git a/src/SparkPost/MetricsResourceQuery.cs b/src/SparkPost/MetricsResourceQuery.cs index 5244555e..052e39e2 100644 --- a/src/SparkPost/MetricsResourceQuery.cs +++ b/src/SparkPost/MetricsResourceQuery.cs @@ -12,12 +12,14 @@ public class MetricsResourceQuery /// Only return results containing this string /// public string Match { get; set; } + /// /// Maximum number of results to return /// public int? Limit { get; set; } public DateTime? From { get; set; } public DateTime? To { get; set; } + /// /// Standard timezone identification string, defaults to UTC /// diff --git a/src/SparkPost/Options.cs b/src/SparkPost/Options.cs index 3c90d2c6..ae7af41b 100644 --- a/src/SparkPost/Options.cs +++ b/src/SparkPost/Options.cs @@ -13,4 +13,4 @@ public class Options public bool? InlineCss { get; set; } public string IpPool { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/PageLink.cs b/src/SparkPost/PageLink.cs index e8cdd63d..11e02e4e 100644 --- a/src/SparkPost/PageLink.cs +++ b/src/SparkPost/PageLink.cs @@ -5,4 +5,4 @@ public class PageLink public string Href { get; set; } public string Type { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Recipient.cs b/src/SparkPost/Recipient.cs index 5a2a905c..a4cf0469 100644 --- a/src/SparkPost/Recipient.cs +++ b/src/SparkPost/Recipient.cs @@ -20,4 +20,4 @@ public Recipient() public RecipientType Type { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RecipientList.cs b/src/SparkPost/RecipientList.cs index a76dd99d..fbc409c7 100644 --- a/src/SparkPost/RecipientList.cs +++ b/src/SparkPost/RecipientList.cs @@ -20,4 +20,4 @@ public RecipientList() public Attributes Attributes { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RecipientLists.cs b/src/SparkPost/RecipientLists.cs index e946d8ea..d341c596 100644 --- a/src/SparkPost/RecipientLists.cs +++ b/src/SparkPost/RecipientLists.cs @@ -25,13 +25,13 @@ public async Task Retrieve(string recipientLists { var request = new Request { - Url = $"api/{client.Version}/recipient-lists/" + recipientListsId+ "?show_recipients=true", + Url = $"api/{client.Version}/recipient-lists/" + recipientListsId + "?show_recipients=true", Method = "GET", }; var response = await requestSender.Send(request); - if (new[] {HttpStatusCode.OK, HttpStatusCode.NotFound}.Contains(response.StatusCode) == false) + if (new[] { HttpStatusCode.OK, HttpStatusCode.NotFound }.Contains(response.StatusCode) == false) throw new ResponseException(response); var recipientListsResponse = new RetrieveRecipientListsResponse() @@ -41,31 +41,22 @@ public async Task Retrieve(string recipientLists Content = response.Content, }; - var results = JsonConvert.DeserializeObject(response.Content).results; - if (results.recipients == null) return recipientListsResponse; - - recipientListsResponse.Id = results.id; - recipientListsResponse.Name = results.name; - recipientListsResponse.Description = results.description; - recipientListsResponse.Attributes = results.attributes != null - ? new Attributes - { - InternalId = results.attributes.internal_id - , - ListGroupId = results.attributes.list_group_id - } - : null; + if (results.recipients == null) + return recipientListsResponse; + recipientListsResponse.TotalAcceptedRecipients = results.total_accepted_recipients; - recipientListsResponse.RecipientLists = RetrieveRecipientListsResponse.CreateFromResponse(response); recipientListsResponse.RecipientList = new RecipientList { - Id = recipientListsResponse.Id, - Recipients = recipientListsResponse.RecipientLists, - Attributes = recipientListsResponse.Attributes, - Description = recipientListsResponse.Description, - Name = recipientListsResponse.Name + Id = results.id, + Recipients = RetrieveRecipientListsResponse.CreateFromResponse(response), + Attributes = + results.attributes != null + ? new Attributes { InternalId = results.attributes.internal_id, ListGroupId = results.attributes.list_group_id } + : null, + Description = results.description, + Name = results.name }; return recipientListsResponse; @@ -73,11 +64,7 @@ public async Task Retrieve(string recipientLists public async Task Delete(string id) { - var request = new Request - { - Url = $"/api/{client.Version}/recipient-lists/{id}", - Method = "DELETE" - }; + var request = new Request { Url = $"/api/{client.Version}/recipient-lists/{id}", Method = "DELETE" }; var response = await requestSender.Send(request); return response.StatusCode == HttpStatusCode.NoContent; @@ -94,7 +81,7 @@ public async Task Update(RecipientList recipientLis var response = await requestSender.Send(request); - if (new[] {HttpStatusCode.OK, HttpStatusCode.NotFound}.Contains(response.StatusCode) == false) + if (new[] { HttpStatusCode.OK, HttpStatusCode.NotFound }.Contains(response.StatusCode) == false) throw new ResponseException(response); return new UpdateRecipientListResponse() @@ -116,7 +103,8 @@ public async Task Create(RecipientList recipientList var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var results = JsonConvert.DeserializeObject(response.Content).results; return new SendRecipientListsResponse() @@ -131,4 +119,4 @@ public async Task Create(RecipientList recipientList }; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RecipientType.cs b/src/SparkPost/RecipientType.cs index 8b6c2dcf..1344e61e 100644 --- a/src/SparkPost/RecipientType.cs +++ b/src/SparkPost/RecipientType.cs @@ -6,4 +6,4 @@ public enum RecipientType CC, BCC } -} \ No newline at end of file +} diff --git a/src/SparkPost/RecipientValidation.cs b/src/SparkPost/RecipientValidation.cs index 42ec51f6..6aca9a3f 100644 --- a/src/SparkPost/RecipientValidation.cs +++ b/src/SparkPost/RecipientValidation.cs @@ -17,11 +17,7 @@ public RecipientValidation(IClient client, IRequestSender requestSender) public async Task Create(string emailAddress) { - var request = new Request - { - Url = $"/api/{client.Version}/recipient-validation/single/{emailAddress}", - Method = "GET" - }; + var request = new Request { Url = $"/api/{client.Version}/recipient-validation/single/{emailAddress}", Method = "GET" }; var response = await requestSender.Send(request); if (response.StatusCode != HttpStatusCode.OK) diff --git a/src/SparkPost/RelayWebhook.cs b/src/SparkPost/RelayWebhook.cs index d81b208a..61779156 100644 --- a/src/SparkPost/RelayWebhook.cs +++ b/src/SparkPost/RelayWebhook.cs @@ -27,4 +27,4 @@ public RelayWebhookMatch() public string Protocol { get; set; } public string Domain { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RelayWebhooks.cs b/src/SparkPost/RelayWebhooks.cs index e9471fdb..be8f708c 100644 --- a/src/SparkPost/RelayWebhooks.cs +++ b/src/SparkPost/RelayWebhooks.cs @@ -28,7 +28,8 @@ public RelayWebhooks(IClient client, IRequestSender requestSender, IDataMapper d public async Task List(object query = null) { - if (query == null) query = new {}; + if (query == null) + query = new { }; var request = new Request { Url = $"/api/{client.Version}/relay-webhooks", @@ -37,21 +38,19 @@ public async Task List(object query = null) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return ListRelayWebhookResponse.CreateFromResponse(response); } public async Task Retrieve(string id) { - var request = new Request - { - Url = $"/api/{client.Version}/relay-webhooks/{id}", - Method = "GET" - }; + var request = new Request { Url = $"/api/{client.Version}/relay-webhooks/{id}", Method = "GET" }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return RetrieveRelayWebhookResponse.CreateFromResponse(response); } @@ -66,7 +65,8 @@ public async Task Create(RelayWebhook relayWebhook) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var createWebhookResponse = new Response(); LeftRight.SetValuesToMatch(createWebhookResponse, response); @@ -83,7 +83,8 @@ public async Task Update(RelayWebhook relayWebhook) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var createWebhookResponse = new Response(); LeftRight.SetValuesToMatch(createWebhookResponse, response); @@ -92,14 +93,10 @@ public async Task Update(RelayWebhook relayWebhook) public async Task Delete(string id) { - var request = new Request - { - Url = $"/api/{client.Version}/relay-webhooks/{id}", - Method = "DELETE" - }; + var request = new Request { Url = $"/api/{client.Version}/relay-webhooks/{id}", Method = "DELETE" }; var response = await requestSender.Send(request); return response.StatusCode == HttpStatusCode.OK; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Request.cs b/src/SparkPost/Request.cs index 2f202cbc..f6d50670 100644 --- a/src/SparkPost/Request.cs +++ b/src/SparkPost/Request.cs @@ -13,4 +13,4 @@ public string ToJson() return Jsonification.SerializeObject(this); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RequestMethodFinder.cs b/src/SparkPost/RequestMethodFinder.cs index 64f98908..3e7eb251 100644 --- a/src/SparkPost/RequestMethodFinder.cs +++ b/src/SparkPost/RequestMethodFinder.cs @@ -23,13 +23,9 @@ public RequestMethodFinder(HttpClient client, IDataMapper dataMapper) public IRequestMethod FindFor(Request request) { - return new List - { - new Delete(client), - new Post(client), - new Put(client), - new Get(client, dataMapper) - }.First(x => x.CanExecute(request)); + return new List { new Delete(client), new Post(client), new Put(client), new Get(client, dataMapper) }.First( + x => x.CanExecute(request) + ); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RequestMethods/Delete.cs b/src/SparkPost/RequestMethods/Delete.cs index d1c3c8db..caf0a2fb 100644 --- a/src/SparkPost/RequestMethods/Delete.cs +++ b/src/SparkPost/RequestMethods/Delete.cs @@ -17,4 +17,4 @@ public override Task Execute(Request request) return client.DeleteAsync(request.Url); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RequestMethods/Get.cs b/src/SparkPost/RequestMethods/Get.cs index 8fb8259d..f6eec35f 100644 --- a/src/SparkPost/RequestMethods/Get.cs +++ b/src/SparkPost/RequestMethods/Get.cs @@ -23,24 +23,24 @@ public Get(HttpClient client, IDataMapper dataMapper) public override Task Execute(Request request) { - return client.GetAsync(string.Join("?", - new[] {request.Url, ConvertToQueryString(request.Data)} - .Where(x => string.IsNullOrEmpty(x) == false))); + return client.GetAsync( + string.Join("?", new[] { request.Url, ConvertToQueryString(request.Data) }.Where(x => string.IsNullOrEmpty(x) == false)) + ); } private string ConvertToQueryString(object data) { - if (data == null) return null; + if (data == null) + return null; var original = dataMapper.CatchAll(data); var dictionary = new Dictionary(); - foreach(var thing in original.Where(x=>string.IsNullOrEmpty(x.Value.ToString()) == false)) + foreach (var thing in original.Where(x => string.IsNullOrEmpty(x.Value.ToString()) == false)) dictionary[thing.Key] = thing.Value.ToString(); - var values = dictionary - .Select(x => WebUtility.UrlEncode(SnakeCase.Convert(x.Key)) + "=" + WebUtility.UrlEncode(x.Value)); + var values = dictionary.Select(x => WebUtility.UrlEncode(SnakeCase.Convert(x.Key)) + "=" + WebUtility.UrlEncode(x.Value)); return string.Join("&", values); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RequestMethods/Post.cs b/src/SparkPost/RequestMethods/Post.cs index 8ba743c4..b67a5179 100644 --- a/src/SparkPost/RequestMethods/Post.cs +++ b/src/SparkPost/RequestMethods/Post.cs @@ -6,13 +6,11 @@ namespace SparkPost.RequestMethods { public class Post : PutAndPostAreTheSame { - public Post(HttpClient client) : base(client) - { - } + public Post(HttpClient client) : base(client) { } public override Task Execute(string url, StringContent stringContent) { return Client.PostAsync(url, stringContent); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RequestMethods/Put.cs b/src/SparkPost/RequestMethods/Put.cs index 020399ff..e333ce7b 100644 --- a/src/SparkPost/RequestMethods/Put.cs +++ b/src/SparkPost/RequestMethods/Put.cs @@ -5,13 +5,11 @@ namespace SparkPost.RequestMethods { public class Put : PutAndPostAreTheSame { - public Put(HttpClient client) : base(client) - { - } + public Put(HttpClient client) : base(client) { } public override Task Execute(string url, StringContent stringContent) { return Client.PutAsync(url, stringContent); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RequestMethods/PutAndPostAreTheSame.cs b/src/SparkPost/RequestMethods/PutAndPostAreTheSame.cs index 2f79b4f2..6686442f 100644 --- a/src/SparkPost/RequestMethods/PutAndPostAreTheSame.cs +++ b/src/SparkPost/RequestMethods/PutAndPostAreTheSame.cs @@ -31,4 +31,4 @@ private static string SerializeObject(object data) return Jsonification.SerializeObject(data); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RequestMethods/RequestMethod.cs b/src/SparkPost/RequestMethods/RequestMethod.cs index 4a9e1fd9..c6bd943f 100644 --- a/src/SparkPost/RequestMethods/RequestMethod.cs +++ b/src/SparkPost/RequestMethods/RequestMethod.cs @@ -12,4 +12,4 @@ public bool CanExecute(Request request) public abstract Task Execute(Request request); } -} \ No newline at end of file +} diff --git a/src/SparkPost/RequestSenders/AsyncRequestSender.cs b/src/SparkPost/RequestSenders/AsyncRequestSender.cs deleted file mode 100644 index 3eb922c2..00000000 --- a/src/SparkPost/RequestSenders/AsyncRequestSender.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Globalization; -using System.Net.Http; -using System.Threading.Tasks; - -namespace SparkPost.RequestSenders -{ - public class AsyncRequestSender : IRequestSender - { - private readonly IClient client; - private readonly IDataMapper dataMapper; - - public AsyncRequestSender(IClient client, IDataMapper dataMapper) - { - this.client = client; - this.dataMapper = dataMapper; - } - - public virtual async Task Send(Request request) - { - using (var httpClient = client.CustomSettings.CreateANewHttpClient()) - { - httpClient.BaseAddress = new Uri(client.ApiHost); - httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey); - - SetTheUserAgentIfItIsProvided(httpClient); - - if (client.SubaccountId != 0) - httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", - client.SubaccountId.ToString(CultureInfo.InvariantCulture)); - - var result = await GetTheResponse(request, httpClient); - - return new Response - { - StatusCode = result.StatusCode, - ReasonPhrase = result.ReasonPhrase, - Content = await result.Content.ReadAsStringAsync() - }; - } - } - - private void SetTheUserAgentIfItIsProvided(HttpClient httpClient) - { - if (string.IsNullOrEmpty(client.CustomSettings.UserAgent) == false) - httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", client.CustomSettings.UserAgent); - } - - protected virtual async Task GetTheResponse(Request request, HttpClient httpClient) - { - return await new RequestMethodFinder(httpClient, dataMapper) - .FindFor(request) - .Execute(request); - } - } -} \ No newline at end of file diff --git a/src/SparkPost/RequestSenders/RequestSender.cs b/src/SparkPost/RequestSenders/RequestSender.cs index e19db311..a35f2448 100644 --- a/src/SparkPost/RequestSenders/RequestSender.cs +++ b/src/SparkPost/RequestSenders/RequestSender.cs @@ -1,4 +1,7 @@ -using System.Threading.Tasks; +using System; +using System.Globalization; +using System.Net.Http; +using System.Threading.Tasks; namespace SparkPost.RequestSenders { @@ -9,27 +12,47 @@ public interface IRequestSender public class RequestSender : IRequestSender { - private readonly AsyncRequestSender asyncRequestSender; private readonly IClient client; - private readonly SyncRequestSender syncRequestSender; + private readonly IDataMapper dataMapper; - public RequestSender(AsyncRequestSender asyncRequestSender, SyncRequestSender syncRequestSender, IClient client) + public RequestSender(IClient client, IDataMapper dataMapper) { - this.asyncRequestSender = asyncRequestSender; - this.syncRequestSender = syncRequestSender; this.client = client; + this.dataMapper = dataMapper; } - public Task Send(Request request) + public virtual async Task Send(Request request) { - return PickTheRequestSender().Send(request); + using (var httpClient = client.CustomSettings.CreateANewHttpClient()) + { + httpClient.BaseAddress = new Uri(client.ApiHost); + httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey); + + SetTheUserAgentIfItIsProvided(httpClient); + + if (client.SubaccountId != 0) + httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", client.SubaccountId.ToString(CultureInfo.InvariantCulture)); + + var result = await GetTheResponse(request, httpClient); + + return new Response + { + StatusCode = result.StatusCode, + ReasonPhrase = result.ReasonPhrase, + Content = await result.Content.ReadAsStringAsync() + }; + } + } + + private void SetTheUserAgentIfItIsProvided(HttpClient httpClient) + { + if (string.IsNullOrEmpty(client.CustomSettings.UserAgent) == false) + httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", client.CustomSettings.UserAgent); } - private IRequestSender PickTheRequestSender() + protected virtual async Task GetTheResponse(Request request, HttpClient httpClient) { - return client.CustomSettings.SendingMode == SendingModes.Sync - ? syncRequestSender - : asyncRequestSender as IRequestSender; + return await new RequestMethodFinder(httpClient, dataMapper).FindFor(request).Execute(request); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RequestSenders/SyncRequestSender.cs b/src/SparkPost/RequestSenders/SyncRequestSender.cs deleted file mode 100644 index 6363ff32..00000000 --- a/src/SparkPost/RequestSenders/SyncRequestSender.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Threading.Tasks; - -namespace SparkPost.RequestSenders -{ - public class SyncRequestSender : IRequestSender - { - private readonly IRequestSender requestSender; - - public SyncRequestSender(IRequestSender requestSender) - { - this.requestSender = requestSender; - } - - public virtual async Task Send(Request request) - { - Response response = await requestSender.Send(request); - - return response; - } - } -} \ No newline at end of file diff --git a/src/SparkPost/Response.cs b/src/SparkPost/Response.cs index 46fbd492..892f74a5 100644 --- a/src/SparkPost/Response.cs +++ b/src/SparkPost/Response.cs @@ -15,4 +15,4 @@ protected void SetFrom(Response source) this.Content = source.Content; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ResponseException.cs b/src/SparkPost/ResponseException.cs index 2ff873fd..f2f5b892 100644 --- a/src/SparkPost/ResponseException.cs +++ b/src/SparkPost/ResponseException.cs @@ -4,12 +4,12 @@ namespace SparkPost { public class ResponseException : Exception { - public ResponseException(Response response) : - base(string.Format("Response: {0} {1}. Content: {2}.", ((int)response.StatusCode).ToString(), response.ReasonPhrase, response.Content)) + public ResponseException(Response response) + : base(string.Format("Response: {0} {1}. Content: {2}.", ((int)response.StatusCode).ToString(), response.ReasonPhrase, response.Content)) { this.Response = response; } public Response Response { get; private set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RetrieveRecipientListsResponse.cs b/src/SparkPost/RetrieveRecipientListsResponse.cs index 04dc4852..0f2744a1 100644 --- a/src/SparkPost/RetrieveRecipientListsResponse.cs +++ b/src/SparkPost/RetrieveRecipientListsResponse.cs @@ -6,21 +6,6 @@ namespace SparkPost { public class RetrieveRecipientListsResponse : Response { - [Obsolete("Please use Recipients from RecipientList. This will be removed in v2.")] - public List RecipientLists { get; set; } - - [Obsolete("Please use Id from RecipientList. This will be removed in v2.")] - public string Id { get; set; } - - [Obsolete("Please use Name from RecipientList. This will be removed in v2.")] - public string Name { set; get; } - - [Obsolete("Please use Description from RecipientList. This will be removed in v2.")] - public string Description { get; set; } - - [Obsolete("Please use Attributes from RecipientList. This will be removed in v2.")] - public Attributes Attributes { get; set; } - public int TotalAcceptedRecipients { get; set; } public RecipientList RecipientList { get; set; } @@ -53,4 +38,4 @@ private static dynamic ConvertToADictionary(dynamic @object) return JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(@object)); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RetrieveRelayWebhookResponse.cs b/src/SparkPost/RetrieveRelayWebhookResponse.cs index 3668e6f3..11ef8d8e 100644 --- a/src/SparkPost/RetrieveRelayWebhookResponse.cs +++ b/src/SparkPost/RetrieveRelayWebhookResponse.cs @@ -18,4 +18,4 @@ public static RetrieveRelayWebhookResponse CreateFromResponse(Response response) return result; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RetrieveTemplatesResponse.cs b/src/SparkPost/RetrieveTemplatesResponse.cs index 9dd0ed80..8cdc0863 100644 --- a/src/SparkPost/RetrieveTemplatesResponse.cs +++ b/src/SparkPost/RetrieveTemplatesResponse.cs @@ -12,4 +12,4 @@ public RetrieveTemplatesResponse() public List Templates { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RetrieveTransmissionResponse.cs b/src/SparkPost/RetrieveTransmissionResponse.cs index fadf1bd8..d12b2092 100644 --- a/src/SparkPost/RetrieveTransmissionResponse.cs +++ b/src/SparkPost/RetrieveTransmissionResponse.cs @@ -12,4 +12,4 @@ public class RetrieveTransmissionResponse : Response public int NumberRecipients { get; set; } public int NumberGenerated { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/RetrieveWebhookResponse.cs b/src/SparkPost/RetrieveWebhookResponse.cs index 99b42638..c92aab7a 100644 --- a/src/SparkPost/RetrieveWebhookResponse.cs +++ b/src/SparkPost/RetrieveWebhookResponse.cs @@ -1,4 +1,3 @@ - using SparkPost.Utilities; namespace SparkPost @@ -19,4 +18,4 @@ public static RetrieveWebhookResponse CreateFromResponse(Response response) return result; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/SendRecipientListsResponse.cs b/src/SparkPost/SendRecipientListsResponse.cs index 17b19bea..04218e03 100644 --- a/src/SparkPost/SendRecipientListsResponse.cs +++ b/src/SparkPost/SendRecipientListsResponse.cs @@ -7,4 +7,4 @@ public class SendRecipientListsResponse : Response public int TotalRejectedRecipients { get; set; } public string Name { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/SendTransmissionResponse.cs b/src/SparkPost/SendTransmissionResponse.cs index 0c8de546..03c0cc54 100644 --- a/src/SparkPost/SendTransmissionResponse.cs +++ b/src/SparkPost/SendTransmissionResponse.cs @@ -6,4 +6,4 @@ public class SendTransmissionResponse : Response public int TotalAcceptedRecipients { get; set; } public int TotalRejectedRecipients { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/SendingDomain.cs b/src/SparkPost/SendingDomain.cs index 832ae5ca..88412ef3 100644 --- a/src/SparkPost/SendingDomain.cs +++ b/src/SparkPost/SendingDomain.cs @@ -23,12 +23,13 @@ public class SendingDomain /// public static SendingDomain ConvertToSendingDomain(dynamic result) { - return result != null ? new SendingDomain + return result != null + ? new SendingDomain { Domain = result.domain, TrackingDomain = result.tracking_domain, Status = SendingDomainStatus.ConvertToSendingDomainStatus(result.status), - Dkim = Dkim.ConvertToDkim(result.dkim), + Dkim = SparkPost.Dkim.ConvertToDkim(result.dkim), GenerateDkim = result.generate_dkim ?? false, DkimKeyLength = result.dkim_key_length ?? 0, SharedWithSubAccounts = result.shared_with_subaccounts ?? false @@ -36,4 +37,4 @@ public static SendingDomain ConvertToSendingDomain(dynamic result) : null; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/SendingDomainStatus.cs b/src/SparkPost/SendingDomainStatus.cs index 39df5852..bc0bf159 100644 --- a/src/SparkPost/SendingDomainStatus.cs +++ b/src/SparkPost/SendingDomainStatus.cs @@ -23,23 +23,20 @@ public class SendingDomainStatus /// public static SendingDomainStatus ConvertToSendingDomainStatus(dynamic result) { - if (result == null) return null; + if (result == null) + return null; return new SendingDomainStatus { OwnershipVerified = result.ownership_verified ?? false, - DkimStatus = - Enum.Parse(typeof (DkimStatus), (result.dkim_status ?? DkimStatus.Unknowed).ToString(), true), - SpfStatus = - Enum.Parse(typeof (SpfStatus), (result.spf_status ?? SpfStatus.Unknowed).ToString(), true), - AbuseAtStatus = - Enum.Parse(typeof (AbuseAtStatus), (result.abuse_at_status ?? AbuseAtStatus.Unknowed).ToString(), - true), - PostmasterAtStatus = - Enum.Parse(typeof (PostmasterAtStatus), - (result.postmaster_at_status ?? PostmasterAtStatus.Unknowed).ToString(), true), - ComplianceStatus = - Enum.Parse(typeof (ComplianceStatus), - (result.compliance_status ?? ComplianceStatus.Unknowed).ToString(), true) + DkimStatus = Enum.Parse(typeof(DkimStatus), (result.dkim_status ?? DkimStatus.Unknowed).ToString(), true), + SpfStatus = Enum.Parse(typeof(SpfStatus), (result.spf_status ?? SpfStatus.Unknowed).ToString(), true), + AbuseAtStatus = Enum.Parse(typeof(AbuseAtStatus), (result.abuse_at_status ?? AbuseAtStatus.Unknowed).ToString(), true), + PostmasterAtStatus = Enum.Parse( + typeof(PostmasterAtStatus), + (result.postmaster_at_status ?? PostmasterAtStatus.Unknowed).ToString(), + true + ), + ComplianceStatus = Enum.Parse(typeof(ComplianceStatus), (result.compliance_status ?? ComplianceStatus.Unknowed).ToString(), true) }; } } @@ -86,4 +83,4 @@ public enum ComplianceStatus Valid, Unknowed } -} \ No newline at end of file +} diff --git a/src/SparkPost/SendingDomains.cs b/src/SparkPost/SendingDomains.cs index 060f9f11..f08a5985 100644 --- a/src/SparkPost/SendingDomains.cs +++ b/src/SparkPost/SendingDomains.cs @@ -22,14 +22,11 @@ public SendingDomains(IClient client, IRequestSender requestSender, IDataMapper public async Task List() { - var request = new Request - { - Url = $"/api/{client.Version}/sending-domains", - Method = "GET" - }; + var request = new Request { Url = $"/api/{client.Version}/sending-domains", Method = "GET" }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return ListSendingDomainResponse.CreateFromResponse(response); } @@ -38,16 +35,18 @@ public async Task Create(SendingDomain sendingDomai { var request = new Request { - Url = $"/api/{client.Version}/sending-domains", + Url = $"/api/{client.Version}/sending-domains", Method = "POST", Data = dataMapper.ToDictionary(sendingDomain) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var result = Jsonification.DeserializeObject(response.Content).results; - return result != null ? new CreateSendingDomainResponse + return result != null + ? new CreateSendingDomainResponse { ReasonPhrase = response.ReasonPhrase, StatusCode = response.StatusCode, @@ -62,16 +61,18 @@ public async Task Update(SendingDomain sendingDomai { var request = new Request { - Url = $"/api/{client.Version}/sending-domains/{sendingDomain.Domain}", + Url = $"/api/{client.Version}/sending-domains/{sendingDomain.Domain}", Method = "PUT", Data = dataMapper.ToDictionary(sendingDomain) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var result = Jsonification.DeserializeObject(response.Content).results; - return result != null ? new UpdateSendingDomainResponse + return result != null + ? new UpdateSendingDomainResponse { ReasonPhrase = response.ReasonPhrase, StatusCode = response.StatusCode, @@ -85,14 +86,11 @@ public async Task Update(SendingDomain sendingDomai public async Task Retrieve(string domain) { - var request = new Request - { - Url = $"/api/{client.Version}/sending-domains/{domain}", - Method = "GET", - }; + var request = new Request { Url = $"/api/{client.Version}/sending-domains/{domain}", Method = "GET", }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var result = Jsonification.DeserializeObject(response.Content).results; return new GetSendingDomainResponse { @@ -105,11 +103,7 @@ public async Task Retrieve(string domain) public async Task Delete(string domain) { - var request = new Request - { - Url = $"/api/{client.Version}/sending-domains/{domain}", - Method = "DELETE", - }; + var request = new Request { Url = $"/api/{client.Version}/sending-domains/{domain}", Method = "DELETE", }; var response = await requestSender.Send(request); if (response.StatusCode == HttpStatusCode.NoContent) @@ -118,7 +112,8 @@ public async Task Delete(string domain) response.ReasonPhrase = ReasonPhrases.GetReasonPhrase((int)HttpStatusCode.OK); } - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return response; } @@ -132,7 +127,8 @@ public async Task Verify(VerifySendingDomain verify }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var result = Jsonification.DeserializeObject(response.Content).results; @@ -145,4 +141,4 @@ public async Task Verify(VerifySendingDomain verify }; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/SendingModes.cs b/src/SparkPost/SendingModes.cs deleted file mode 100644 index e2243e39..00000000 --- a/src/SparkPost/SendingModes.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SparkPost -{ - public enum SendingModes - { - Async, Sync - } -} \ No newline at end of file diff --git a/src/SparkPost/SubaccountCreate.cs b/src/SparkPost/SubaccountCreate.cs index ae0e9206..35a9ea7c 100644 --- a/src/SparkPost/SubaccountCreate.cs +++ b/src/SparkPost/SubaccountCreate.cs @@ -1,10 +1,9 @@ namespace SparkPost { - public class SubaccountCreate { public string Name { get; set; } public string KeyLabel { get; set; } public string[] KeyGrants { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/SubaccountStatus.cs b/src/SparkPost/SubaccountStatus.cs index 464d7630..d452aa4f 100644 --- a/src/SparkPost/SubaccountStatus.cs +++ b/src/SparkPost/SubaccountStatus.cs @@ -6,4 +6,4 @@ public enum SubaccountStatus Suspended, Terminated } -} \ No newline at end of file +} diff --git a/src/SparkPost/SubaccountUpdate.cs b/src/SparkPost/SubaccountUpdate.cs index 8b56c0c1..69610d16 100644 --- a/src/SparkPost/SubaccountUpdate.cs +++ b/src/SparkPost/SubaccountUpdate.cs @@ -6,4 +6,4 @@ public class SubaccountUpdate public string Name { get; set; } public SubaccountStatus Status { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Subaccounts.cs b/src/SparkPost/Subaccounts.cs index 5cb917a7..34d64edd 100644 --- a/src/SparkPost/Subaccounts.cs +++ b/src/SparkPost/Subaccounts.cs @@ -20,14 +20,11 @@ public Subaccounts(IClient client, IRequestSender requestSender, IDataMapper dat public async Task List() { - var request = new Request - { - Url = $"/api/{client.Version}/subaccounts", - Method = "GET" - }; + var request = new Request { Url = $"/api/{client.Version}/subaccounts", Method = "GET" }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return ListSubaccountResponse.CreateFromResponse(response); } @@ -38,16 +35,12 @@ public async Task Create(SubaccountCreate subaccount) { Url = $"api/{client.Version}/subaccounts", Method = "POST", - Data = new - { - name = subaccount.Name, - key_label = subaccount.KeyLabel, - key_grants = subaccount.KeyGrants - } + Data = new { name = subaccount.Name, key_label = subaccount.KeyLabel, key_grants = subaccount.KeyGrants } }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var results = Jsonification.DeserializeObject(response.Content).results; @@ -69,15 +62,12 @@ public async Task Update(SubaccountUpdate subaccount) { Url = $"api/{client.Version}/subaccounts/{subaccount.Id}", Method = "PUT JSON", - Data = new - { - name = subaccount.Name, - status = subaccount.Status.ToString().ToLowerInvariant() - } + Data = new { name = subaccount.Name, status = subaccount.Status.ToString().ToLowerInvariant() } }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var results = Jsonification.DeserializeObject(response.Content).results; @@ -88,6 +78,5 @@ public async Task Update(SubaccountUpdate subaccount) Content = response.Content }; } - } -} \ No newline at end of file +} diff --git a/src/SparkPost/Suppression.cs b/src/SparkPost/Suppression.cs index 363f9d49..c069a302 100644 --- a/src/SparkPost/Suppression.cs +++ b/src/SparkPost/Suppression.cs @@ -12,4 +12,4 @@ public class Suppression public DateTime? Created { get; set; } public DateTime? Updated { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Suppressions.cs b/src/SparkPost/Suppressions.cs index 861df422..15befd69 100644 --- a/src/SparkPost/Suppressions.cs +++ b/src/SparkPost/Suppressions.cs @@ -28,7 +28,8 @@ public async Task List(SuppressionsQuery supppressionsQ public async Task List(object query = null) { - if (query == null) query = new {}; + if (query == null) + query = new { }; var request = new Request { Url = $"/api/{client.Version}/suppression-list", @@ -37,7 +38,8 @@ public async Task List(object query = null) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var results = Jsonification.DeserializeObject(response.Content).results; @@ -52,20 +54,14 @@ public async Task List(object query = null) public async Task Retrieve(string email) { - var request = new Request - { - Url = $"/api/{client.Version}/suppression-list/{WebUtility.UrlEncode(email)}", - Method = "GET" - }; + var request = new Request { Url = $"/api/{client.Version}/suppression-list/{WebUtility.UrlEncode(email)}", Method = "GET" }; var response = await requestSender.Send(request); - if (new[] {HttpStatusCode.OK, HttpStatusCode.NotFound}.Contains(response.StatusCode) == false) + if (new[] { HttpStatusCode.OK, HttpStatusCode.NotFound }.Contains(response.StatusCode) == false) throw new ResponseException(response); - dynamic results = response.StatusCode == HttpStatusCode.OK - ? Jsonification.DeserializeObject(response.Content).results - : null; + dynamic results = response.StatusCode == HttpStatusCode.OK ? Jsonification.DeserializeObject(response.Content).results : null; return new ListSuppressionResponse { @@ -78,13 +74,15 @@ public async Task Retrieve(string email) public async Task CreateOrUpdate(IEnumerable emails) { - var suppressions = emails.Select(email => - new Suppression - { - Email = email, - Transactional = true, - NonTransactional = true - }); + var suppressions = emails.Select( + email => + new Suppression + { + Email = email, + Transactional = true, + NonTransactional = true + } + ); return await CreateOrUpdate(suppressions); } @@ -95,14 +93,12 @@ public async Task CreateOrUpdate(IEnumerable dataMapper.ToDictionary(x)).ToList() - } + Data = new { recipients = suppressions.Select(x => dataMapper.ToDictionary(x)).ToList() } }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var updateSuppressionResponse = new UpdateSuppressionResponse(); LeftRight.SetValuesToMatch(updateSuppressionResponse, response); @@ -111,11 +107,7 @@ public async Task CreateOrUpdate(IEnumerable Delete(string email) { - var request = new Request - { - Url = $"api/{client.Version}/suppression-list/{WebUtility.UrlEncode(email)}", - Method = "DELETE" - }; + var request = new Request { Url = $"api/{client.Version}/suppression-list/{WebUtility.UrlEncode(email)}", Method = "DELETE" }; var response = await requestSender.Send(request); return response.StatusCode == HttpStatusCode.NoContent; @@ -125,23 +117,25 @@ private static IEnumerable ConvertResultsToAListOfSuppressions(dyna { var suppressions = new List(); - if (results == null) return suppressions; + if (results == null) + return suppressions; foreach (var result in results) { - suppressions.Add(new Suppression - { - Description = result.description, - Transactional = result.transactional == true, - NonTransactional = result.non_transactional == true, - Email = result.recipient, - Source = result.source, - Created = result.created, - Updated = result.updated - }); + suppressions.Add( + new Suppression + { + Description = result.description, + Transactional = result.transactional == true, + NonTransactional = result.non_transactional == true, + Email = result.recipient, + Source = result.source, + Created = result.created, + Updated = result.updated + } + ); } return suppressions; } - } -} \ No newline at end of file +} diff --git a/src/SparkPost/SuppressionsQuery.cs b/src/SparkPost/SuppressionsQuery.cs index 4303c952..df2fceca 100644 --- a/src/SparkPost/SuppressionsQuery.cs +++ b/src/SparkPost/SuppressionsQuery.cs @@ -8,4 +8,4 @@ public class SuppressionsQuery public DateTime? From { get; set; } public int? Limit { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Template.cs b/src/SparkPost/Template.cs index d94e50bc..05784c94 100644 --- a/src/SparkPost/Template.cs +++ b/src/SparkPost/Template.cs @@ -13,7 +13,6 @@ public Template() public TemplateContent Content { get; set; } public TemplateOptions Options { get; set; } - } public class TemplateListItem : TemplateBase diff --git a/src/SparkPost/Templates.cs b/src/SparkPost/Templates.cs index c12a17bb..735d5745 100644 --- a/src/SparkPost/Templates.cs +++ b/src/SparkPost/Templates.cs @@ -30,7 +30,8 @@ public async Task Create(Template template) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var results = JsonConvert.DeserializeObject(response.Content).results; return new CreateTemplateResponse() @@ -44,11 +45,7 @@ public async Task Create(Template template) public async Task Retrieve(string templateId, bool? draft = null) { - var request = new Request - { - Url = $"api/{client.Version}/templates/{templateId}", - Method = "GET" - }; + var request = new Request { Url = $"api/{client.Version}/templates/{templateId}", Method = "GET" }; if (draft != null) { @@ -57,10 +54,11 @@ public async Task Retrieve(string templateId, bool? dr } var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var results = JsonConvert.DeserializeObject(response.Content).results; - + Dictionary Headers = new Dictionary(); if (results.content.headers != null) { @@ -89,11 +87,7 @@ public async Task Retrieve(string templateId, bool? dr }, TemplateContent = new TemplateContent() { - From = new Address() - { - Email = results.content.from.email, - Name = results.content.from.name - }, + From = new Address() { Email = results.content.from.email, Name = results.content.from.name }, Subject = results.content.subject, ReplyTo = (results.content.reply_to == null) ? null : results.content.reply_to, Text = (results.content.text == null) ? null : results.content.text, @@ -105,27 +99,26 @@ public async Task Retrieve(string templateId, bool? dr public async Task List() { - var request = new Request - { - Url = $"api/{client.Version}/templates", - Method = "GET" - }; + var request = new Request { Url = $"api/{client.Version}/templates", Method = "GET" }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var results = JsonConvert.DeserializeObject(response.Content).results; var templates = new List(); foreach (var result in results) - templates.Add(new TemplateListItem - { - Id = result.id, - Name = result.name, - LastUpdateTime = result.last_update_time, - Description = result.description, - Published = result.published - }); + templates.Add( + new TemplateListItem + { + Id = result.id, + Name = result.name, + LastUpdateTime = result.last_update_time, + Description = result.description, + Published = result.published + } + ); return new RetrieveTemplatesResponse { @@ -138,11 +131,7 @@ public async Task List() public async Task Delete(string templateId) { - var request = new Request - { - Url = $"api/{client.Version}/templates/{templateId}", - Method = "DELETE" - }; + var request = new Request { Url = $"api/{client.Version}/templates/{templateId}", Method = "DELETE" }; var response = await requestSender.Send(request); return response.StatusCode == HttpStatusCode.OK; diff --git a/src/SparkPost/Transmission.cs b/src/SparkPost/Transmission.cs index d01dd3db..9cdfe4d8 100644 --- a/src/SparkPost/Transmission.cs +++ b/src/SparkPost/Transmission.cs @@ -43,4 +43,4 @@ public void LoadFrom(MailMessage message) MailMessageMapping.ToTransmission(message, this); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Transmissions.cs b/src/SparkPost/Transmissions.cs index 42c09478..be12019a 100644 --- a/src/SparkPost/Transmissions.cs +++ b/src/SparkPost/Transmissions.cs @@ -30,7 +30,8 @@ public async Task Send(Transmission transmission) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var results = Jsonification.DeserializeObject(response.Content).results; return new SendTransmissionResponse() @@ -46,15 +47,11 @@ public async Task Send(Transmission transmission) public async Task Retrieve(string transmissionId) { - var request = new Request - { - Url = $"api/{client.Version}/transmissions/" + transmissionId, - Method = "GET", - }; + var request = new Request { Url = $"api/{client.Version}/transmissions/" + transmissionId, Method = "GET", }; var response = await requestSender.Send(request); - if (new[] {HttpStatusCode.OK, HttpStatusCode.NotFound}.Contains(response.StatusCode) == false) + if (new[] { HttpStatusCode.OK, HttpStatusCode.NotFound }.Contains(response.StatusCode) == false) throw new ResponseException(response); var transmissionResponse = new RetrieveTransmissionResponse() @@ -67,7 +64,8 @@ public async Task Retrieve(string transmissionId) try { var results = Jsonification.DeserializeObject(response.Content).results; - if (results.transmission == null) return transmissionResponse; + if (results.transmission == null) + return transmissionResponse; transmissionResponse.Id = results.transmission.id; transmissionResponse.Description = results.transmission.description; @@ -87,14 +85,11 @@ public async Task Retrieve(string transmissionId) public async Task List() { - var request = new Request - { - Url = $"api/{client.Version}/transmissions", - Method = "GET", - }; + var request = new Request { Url = $"api/{client.Version}/transmissions", Method = "GET", }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var transmissionResponse = new ListTransmissionResponse() { @@ -106,4 +101,4 @@ public async Task List() return transmissionResponse; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/UpdateRecipientListResponse.cs b/src/SparkPost/UpdateRecipientListResponse.cs index c4362b83..24d50409 100644 --- a/src/SparkPost/UpdateRecipientListResponse.cs +++ b/src/SparkPost/UpdateRecipientListResponse.cs @@ -1,6 +1,4 @@ namespace SparkPost { - public class UpdateRecipientListResponse : Response - { - } -} \ No newline at end of file + public class UpdateRecipientListResponse : Response { } +} diff --git a/src/SparkPost/UpdateSendingDomainResponse.cs b/src/SparkPost/UpdateSendingDomainResponse.cs index 6a68b227..a43c622b 100644 --- a/src/SparkPost/UpdateSendingDomainResponse.cs +++ b/src/SparkPost/UpdateSendingDomainResponse.cs @@ -3,9 +3,9 @@ public class UpdateSendingDomainResponse : Response { public string Domain { get; set; } - + public string TrackingDomain { get; set; } - + public Dkim Dkim { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/UpdateSubaccountResponse.cs b/src/SparkPost/UpdateSubaccountResponse.cs index 6a1cf564..98cf5072 100644 --- a/src/SparkPost/UpdateSubaccountResponse.cs +++ b/src/SparkPost/UpdateSubaccountResponse.cs @@ -1,6 +1,4 @@ namespace SparkPost { - public class UpdateSubaccountResponse: Response - { - } -} \ No newline at end of file + public class UpdateSubaccountResponse : Response { } +} diff --git a/src/SparkPost/UpdateSuppressionResponse.cs b/src/SparkPost/UpdateSuppressionResponse.cs index 9f21a39e..7172f0a2 100644 --- a/src/SparkPost/UpdateSuppressionResponse.cs +++ b/src/SparkPost/UpdateSuppressionResponse.cs @@ -1,6 +1,4 @@ namespace SparkPost { - public class UpdateSuppressionResponse : Response - { - } -} \ No newline at end of file + public class UpdateSuppressionResponse : Response { } +} diff --git a/src/SparkPost/Utilities/Jsonification.cs b/src/SparkPost/Utilities/Jsonification.cs index 7ec2e964..70b89af2 100644 --- a/src/SparkPost/Utilities/Jsonification.cs +++ b/src/SparkPost/Utilities/Jsonification.cs @@ -11,8 +11,7 @@ internal static T DeserializeObject(string json) internal static string SerializeObject(object @object) { - return JsonConvert.SerializeObject(@object, - new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.None}); + return JsonConvert.SerializeObject(@object, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None }); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Utilities/MailMessageMapping.cs b/src/SparkPost/Utilities/MailMessageMapping.cs index 5c466d02..3939e0dc 100644 --- a/src/SparkPost/Utilities/MailMessageMapping.cs +++ b/src/SparkPost/Utilities/MailMessageMapping.cs @@ -18,21 +18,23 @@ public static class MailMessageMapping (t, m) => AddRecipients(t, m.Bcc, RecipientType.BCC), (t, m) => { - if (m.ReplyToList.Any()) t.Content.ReplyTo = m.ReplyToList.First().Address; + if (m.ReplyToList.Any()) + t.Content.ReplyTo = m.ReplyToList.First().Address; }, (t, m) => { - if (m.IsBodyHtml) t.Content.Html = m.Body; + if (m.IsBodyHtml) + t.Content.Html = m.Body; }, (t, m) => { - if (!m.IsBodyHtml) t.Content.Text = m.Body; + if (!m.IsBodyHtml) + t.Content.Text = m.Body; }, (t, m) => { foreach (var attachment in m.Attachments) - t.Content.Attachments - .Add(File.Create(attachment.ContentStream, attachment.ContentType.Name)); + t.Content.Attachments.Add(File.Create(attachment.ContentStream, attachment.ContentType.Name)); }, (t, m) => { @@ -69,9 +71,8 @@ private static string GetTheAlternativeView(AlternateViewCollection views, strin private static bool AlternativeViewsAreAvailable(AlternateViewCollection views) { - var textTypes = new[] {MediaTypeNames.Text.Plain, MediaTypeNames.Text.Html}; - return views.Any() && (views.Count <= 2) && - !views.Select(av => av.ContentType.MediaType).Except(textTypes).Any(); + var textTypes = new[] { MediaTypeNames.Text.Plain, MediaTypeNames.Text.Html }; + return views.Any() && (views.Count <= 2) && !views.Select(av => av.ContentType.MediaType).Except(textTypes).Any(); } private static Address ConvertToAddress(MailAddress address) @@ -108,11 +109,7 @@ private static IEnumerable ConvertToRecipients(MailAddressCollection private static Recipient ConvertToARecipient(RecipientType type, MailAddress address) { - return new Recipient - { - Type = type, - Address = ConvertToAddress(address) - }; + return new Recipient { Type = type, Address = ConvertToAddress(address) }; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Utilities/SnakeCase.cs b/src/SparkPost/Utilities/SnakeCase.cs index 74cb17ef..ab506bea 100644 --- a/src/SparkPost/Utilities/SnakeCase.cs +++ b/src/SparkPost/Utilities/SnakeCase.cs @@ -6,7 +6,8 @@ public static class SnakeCase { public static string Convert(string input) { - if (input == null) return null; + if (input == null) + return null; var regex = new Regex("[A-Z]"); @@ -21,4 +22,4 @@ public static string Convert(string input) return input; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Utilities/StringHelper.cs b/src/SparkPost/Utilities/StringHelper.cs index 5c78dc20..4b037c03 100644 --- a/src/SparkPost/Utilities/StringHelper.cs +++ b/src/SparkPost/Utilities/StringHelper.cs @@ -7,7 +7,7 @@ public static class StringHelper { public static string[] SplitOn(this string value, string separator) { - return value.Split(new[] {separator}, StringSplitOptions.RemoveEmptyEntries); + return value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries); } public static string JoinWith(this IEnumerable value, string separator) @@ -15,4 +15,4 @@ public static string JoinWith(this IEnumerable value, string separator) return string.Join(separator, value); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/AnonymousValueMapper.cs b/src/SparkPost/ValueMappers/AnonymousValueMapper.cs index a89cf3ea..770b528e 100644 --- a/src/SparkPost/ValueMappers/AnonymousValueMapper.cs +++ b/src/SparkPost/ValueMappers/AnonymousValueMapper.cs @@ -27,8 +27,7 @@ public object Map(Type propertyType, object value) private static bool ThisIsAnAnonymousType(object value) { - return value != null && - (value.GetType().Name.Contains("AnonymousType") || value.GetType().Name.Contains("AnonType")); + return value != null && (value.GetType().Name.Contains("AnonymousType") || value.GetType().Name.Contains("AnonType")); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/BooleanValueMapper.cs b/src/SparkPost/ValueMappers/BooleanValueMapper.cs index ed3c49a3..b5e1f6ee 100644 --- a/src/SparkPost/ValueMappers/BooleanValueMapper.cs +++ b/src/SparkPost/ValueMappers/BooleanValueMapper.cs @@ -14,4 +14,4 @@ public object Map(Type propertyType, object value) return value as bool? == true; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/DateTimeOffsetValueMapper.cs b/src/SparkPost/ValueMappers/DateTimeOffsetValueMapper.cs index eff01faa..ef6e3608 100644 --- a/src/SparkPost/ValueMappers/DateTimeOffsetValueMapper.cs +++ b/src/SparkPost/ValueMappers/DateTimeOffsetValueMapper.cs @@ -11,7 +11,7 @@ public bool CanMap(Type propertyType, object value) public object Map(Type propertyType, object value) { - return string.Format("{0:s}{0:zzz}", (DateTimeOffset?) value); + return string.Format("{0:s}{0:zzz}", (DateTimeOffset?)value); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/DateTimeValueMapper.cs b/src/SparkPost/ValueMappers/DateTimeValueMapper.cs index 8f6c4ba5..43114109 100644 --- a/src/SparkPost/ValueMappers/DateTimeValueMapper.cs +++ b/src/SparkPost/ValueMappers/DateTimeValueMapper.cs @@ -11,7 +11,7 @@ public bool CanMap(Type propertyType, object value) public object Map(Type propertyType, object value) { - return ((DateTime) value).ToString("yyyy-MM-ddTHH:mm"); + return ((DateTime)value).ToString("yyyy-MM-ddTHH:mm"); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/EnumValueMapper.cs b/src/SparkPost/ValueMappers/EnumValueMapper.cs index 072d757d..9cc73ab0 100644 --- a/src/SparkPost/ValueMappers/EnumValueMapper.cs +++ b/src/SparkPost/ValueMappers/EnumValueMapper.cs @@ -14,4 +14,4 @@ public object Map(Type propertyType, object value) return value.ToString().ToLowerInvariant(); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/EnumerableValueMapper.cs b/src/SparkPost/ValueMappers/EnumerableValueMapper.cs index 50101044..69c643b0 100644 --- a/src/SparkPost/ValueMappers/EnumerableValueMapper.cs +++ b/src/SparkPost/ValueMappers/EnumerableValueMapper.cs @@ -15,14 +15,13 @@ public EnumerableValueMapper(IDataMapper mapper) public bool CanMap(Type propertyType, object value) { - return value != null && value.GetType() != typeof (string) && value is IEnumerable; + return value != null && value.GetType() != typeof(string) && value is IEnumerable; } public object Map(Type propertyType, object value) { - var things = (from object thing in (IEnumerable) value - select mapper.GetTheValue(thing.GetType(), thing)).ToList(); + var things = (from object thing in (IEnumerable)value select mapper.GetTheValue(thing.GetType(), thing)).ToList(); return things.Count > 0 ? things : null; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/MapASetOfItemsUsingToDictionary.cs b/src/SparkPost/ValueMappers/MapASetOfItemsUsingToDictionary.cs index daab9d03..ae79d387 100644 --- a/src/SparkPost/ValueMappers/MapASetOfItemsUsingToDictionary.cs +++ b/src/SparkPost/ValueMappers/MapASetOfItemsUsingToDictionary.cs @@ -20,9 +20,10 @@ public MapASetOfItemsUsingToDictionary(IDataMapper dataMapper) public bool CanMap(Type propertyType, object value) { - return value != null && propertyType.Name.EndsWith("List`1") && - propertyType.GetGenericArguments().Count() == 1 && - converters.ContainsKey(propertyType.GetGenericArguments().First()); + return value != null + && propertyType.Name.EndsWith("List`1") + && propertyType.GetGenericArguments().Count() == 1 + && converters.ContainsKey(propertyType.GetGenericArguments().First()); } public object Map(Type propertyType, object value) @@ -32,12 +33,11 @@ public object Map(Type propertyType, object value) var list = (value as IEnumerable).ToList(); if (list.Any()) - value = list.Select(x => converter.Invoke(dataMapper, BindingFlags.Default, null, - new[] {x}, CultureInfo.CurrentCulture)).ToList(); + value = list.Select(x => converter.Invoke(dataMapper, BindingFlags.Default, null, new[] { x }, CultureInfo.CurrentCulture)).ToList(); else value = null; return value; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/MapASingleItemUsingToDictionary.cs b/src/SparkPost/ValueMappers/MapASingleItemUsingToDictionary.cs index d5f0a5c1..70df6613 100644 --- a/src/SparkPost/ValueMappers/MapASingleItemUsingToDictionary.cs +++ b/src/SparkPost/ValueMappers/MapASingleItemUsingToDictionary.cs @@ -20,13 +20,12 @@ public MapASingleItemUsingToDictionary(IDataMapper dataMapper) public bool CanMap(Type propertyType, object value) { - return propertyType != typeof (int) && converters.ContainsKey(propertyType); + return propertyType != typeof(int) && converters.ContainsKey(propertyType); } public object Map(Type propertyType, object value) { - return converters[propertyType].Invoke(dataMapper, BindingFlags.Default, null, - new[] {value}, CultureInfo.CurrentCulture); + return converters[propertyType].Invoke(dataMapper, BindingFlags.Default, null, new[] { value }, CultureInfo.CurrentCulture); } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/StringObjectDictionaryValueMapper.cs b/src/SparkPost/ValueMappers/StringObjectDictionaryValueMapper.cs index 137119bd..28101828 100644 --- a/src/SparkPost/ValueMappers/StringObjectDictionaryValueMapper.cs +++ b/src/SparkPost/ValueMappers/StringObjectDictionaryValueMapper.cs @@ -21,7 +21,7 @@ public bool CanMap(Type propertyType, object value) public object Map(Type propertyType, object value) { - var original = (IDictionary) value; + var original = (IDictionary)value; var dictionary = new Dictionary(); foreach (var item in original.Where(i => i.Value != null)) { @@ -32,4 +32,4 @@ public object Map(Type propertyType, object value) return dictionary.Count > 0 ? dictionary : null; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/ValueMappers/StringStringDictionaryValueMapper.cs b/src/SparkPost/ValueMappers/StringStringDictionaryValueMapper.cs index d8bff48e..63b63235 100644 --- a/src/SparkPost/ValueMappers/StringStringDictionaryValueMapper.cs +++ b/src/SparkPost/ValueMappers/StringStringDictionaryValueMapper.cs @@ -12,8 +12,8 @@ public bool CanMap(Type propertyType, object value) public object Map(Type propertyType, object value) { - var dictionary = (IDictionary) value; + var dictionary = (IDictionary)value; return dictionary.Count > 0 ? dictionary : null; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/VerifySendingDomain.cs b/src/SparkPost/VerifySendingDomain.cs index 2071438c..2cef3ea7 100644 --- a/src/SparkPost/VerifySendingDomain.cs +++ b/src/SparkPost/VerifySendingDomain.cs @@ -3,15 +3,15 @@ public class VerifySendingDomain { public string Domain { get; set; } - + public bool SpfVerify { get; set; } - + public bool DkimVerify { get; set; } - + public bool PostmasterAtVerify { get; set; } - + public string PostmasterAtToken { get; set; } - + public string AbuseAtToken { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/VerifySendingDomainResponse.cs b/src/SparkPost/VerifySendingDomainResponse.cs index 91668114..6cf9c418 100644 --- a/src/SparkPost/VerifySendingDomainResponse.cs +++ b/src/SparkPost/VerifySendingDomainResponse.cs @@ -4,4 +4,4 @@ public class VerifySendingDomainResponse : Response { public VerifySendingDomainStatus Status { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/VerifySendingDomainStatus.cs b/src/SparkPost/VerifySendingDomainStatus.cs index 3779feb7..59d7bb88 100644 --- a/src/SparkPost/VerifySendingDomainStatus.cs +++ b/src/SparkPost/VerifySendingDomainStatus.cs @@ -1,4 +1,5 @@ using System; + namespace SparkPost { public class VerifySendingDomainStatus : SendingDomainStatus @@ -12,17 +13,22 @@ public class VerifySendingDomainStatus : SendingDomainStatus /// public static VerifySendingDomainStatus ConvertToVerifySendingDomainStatus(dynamic result) { - return result != null ? new VerifySendingDomainStatus + return result != null + ? new VerifySendingDomainStatus { OwnershipVerified = result.ownership_verified, DkimStatus = Enum.Parse(typeof(DkimStatus), (result.dkim_status ?? DkimStatus.Unknowed).ToString(), true), SpfStatus = Enum.Parse(typeof(SpfStatus), (result.spf_status ?? SpfStatus.Unknowed).ToString(), true), - AbuseAtStatus = Enum.Parse(typeof(AbuseAtStatus), (result.abuse_at_status ?? AbuseAtStatus.Unknowed).ToString(), true) , - PostmasterAtStatus = Enum.Parse(typeof(PostmasterAtStatus), (result.postmaster_at_status ?? PostmasterAtStatus.Unknowed).ToString(), true), + AbuseAtStatus = Enum.Parse(typeof(AbuseAtStatus), (result.abuse_at_status ?? AbuseAtStatus.Unknowed).ToString(), true), + PostmasterAtStatus = Enum.Parse( + typeof(PostmasterAtStatus), + (result.postmaster_at_status ?? PostmasterAtStatus.Unknowed).ToString(), + true + ), ComplianceStatus = Enum.Parse(typeof(ComplianceStatus), (result.compliance_status ?? ComplianceStatus.Unknowed).ToString(), true), - Dns = Dns.ConvertToDns(result.dns) + Dns = SparkPost.Dns.ConvertToDns(result.dns) } : null; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Webhook.cs b/src/SparkPost/Webhook.cs index b026bf57..2dbed710 100644 --- a/src/SparkPost/Webhook.cs +++ b/src/SparkPost/Webhook.cs @@ -23,4 +23,4 @@ public Webhook() public object AuthRequestDetails { get; set; } public object AuthCredentials { get; set; } } -} \ No newline at end of file +} diff --git a/src/SparkPost/Webhooks.cs b/src/SparkPost/Webhooks.cs index c943adf3..e8bcf929 100644 --- a/src/SparkPost/Webhooks.cs +++ b/src/SparkPost/Webhooks.cs @@ -27,7 +27,8 @@ public Webhooks(IClient client, IRequestSender requestSender, IDataMapper dataMa public async Task List(object query = null) { - if (query == null) query = new {}; + if (query == null) + query = new { }; var request = new Request { Url = $"/api/{client.Version}/webhooks", @@ -36,21 +37,19 @@ public async Task List(object query = null) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return ListWebhookResponse.CreateFromResponse(response); } public async Task Retrieve(string id) { - var request = new Request - { - Url = $"/api/{client.Version}/webhooks/{id}", - Method = "GET" - }; + var request = new Request { Url = $"/api/{client.Version}/webhooks/{id}", Method = "GET" }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); return RetrieveWebhookResponse.CreateFromResponse(response); } @@ -65,7 +64,8 @@ public async Task Create(Webhook webhook) }; var response = await requestSender.Send(request); - if (response.StatusCode != HttpStatusCode.OK) throw new ResponseException(response); + if (response.StatusCode != HttpStatusCode.OK) + throw new ResponseException(response); var updateSuppressionResponse = new Response(); LeftRight.SetValuesToMatch(updateSuppressionResponse, response); @@ -74,14 +74,10 @@ public async Task Create(Webhook webhook) public async Task Delete(string id) { - var request = new Request - { - Url = $"/api/{client.Version}/webhooks/{id}", - Method = "DELETE" - }; + var request = new Request { Url = $"/api/{client.Version}/webhooks/{id}", Method = "DELETE" }; var response = await requestSender.Send(request); return response.StatusCode == HttpStatusCode.NoContent; } } -} \ No newline at end of file +}