From 7bf2afd04ad530fb9d7eef952fd330d8babc6aa9 Mon Sep 17 00:00:00 2001 From: Julian Verdurmen <304NotModified@users.noreply.github.com> Date: Sat, 6 Nov 2021 22:44:16 +0100 Subject: [PATCH] Release 4: .NET standard 2.0 only, CSL complaint, Cleanup (#131) * 4.0 release:.NET Standard 2.0 only * Update dependencies * cleanup * update smtpserver package * [assembly:CLSCompliant(true)] * public helper method to internal * cleanup * version 4.0 * cleanup * changelog * ignore ref folder * [CLSCompliant(false)] for SecureSocketOption * changelog * cleanup * 2021 * cleanup * update docs --- azure-pipelines.yml | 3 +- src/NLog.MailKit/MailTarget.cs | 110 ++++++++---------- src/NLog.MailKit/NLog.MailKit.csproj | 26 ++--- src/NLog.MailKit/Properties/AssemblyInfo.cs | 6 + src/NLog.MailKit/SmtpAuthenticationMode.cs | 2 - src/NLog.MailKit/Util/ArrayHelper.cs | 49 -------- src/NLog.MailKit/Util/ExceptionHelper.cs | 24 +--- src/NLog.MailKit/Util/SortHelpers.cs | 108 ++++++----------- .../MailTargetIntegrationTests.cs | 24 ++-- .../Util/MessageStore.cs | 3 +- .../Util/UserAuthenticator.cs | 3 +- .../Util/UserAuthenticatorFactory.cs | 2 +- .../NLog.MailKit.Tests.csproj | 16 ++- test/NLog.MailKit.Tests/NLog.snk | Bin 0 -> 596 bytes .../UnitTests/MailTargetTests.cs | 3 +- 15 files changed, 126 insertions(+), 253 deletions(-) create mode 100644 src/NLog.MailKit/Properties/AssemblyInfo.cs delete mode 100644 src/NLog.MailKit/Util/ArrayHelper.cs rename test/NLog.MailKit.Tests/{ => IntegrationTests}/Util/MessageStore.cs (95%) rename test/NLog.MailKit.Tests/{ => IntegrationTests}/Util/UserAuthenticator.cs (94%) rename test/NLog.MailKit.Tests/{ => IntegrationTests}/Util/UserAuthenticatorFactory.cs (91%) create mode 100644 test/NLog.MailKit.Tests/NLog.snk diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 1646ff9..f0098a9 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -13,7 +13,7 @@ variables: Solution: 'src/NLog.MailKit.sln' BuildPlatform: 'Any CPU' BuildConfiguration: 'Release' - Version: '3.4.0' + Version: '4.0.0' FullVersion: '$(Version).$(Build.BuildId)' steps: @@ -54,6 +54,7 @@ steps: testAssemblyVer2: | **\*.tests.dll !**\obj\** + !**\ref\** codeCoverageEnabled: true platform: '$(BuildPlatform)' configuration: '$(BuildConfiguration)' diff --git a/src/NLog.MailKit/MailTarget.cs b/src/NLog.MailKit/MailTarget.cs index 6e4126c..2c032f5 100644 --- a/src/NLog.MailKit/MailTarget.cs +++ b/src/NLog.MailKit/MailTarget.cs @@ -1,5 +1,5 @@ // -// Copyright (c) 2004-2016 Jaroslaw Kowalski , Kim Christensen, Julian Verdurmen +// Copyright (c) 2004-2021 Jaroslaw Kowalski , Kim Christensen, Julian Verdurmen // // All rights reserved. // @@ -31,7 +31,6 @@ // THE POSSIBILITY OF SUCH DAMAGE. // - using System; using System.Collections.Generic; using System.ComponentModel; @@ -42,8 +41,8 @@ using MimeKit.Text; using NLog.Common; using NLog.Config; -using NLog.Internal; using NLog.Layouts; +using NLog.MailKit.Util; using NLog.Targets; namespace NLog.MailKit @@ -54,7 +53,7 @@ namespace NLog.MailKit /// Documentation on NLog Wiki /// ///

- /// To set up the target in the configuration file, + /// To set up the target in the configuration file, /// use the following syntax: ///

/// @@ -71,7 +70,7 @@ namespace NLog.MailKit /// which lets you send multiple log messages in single mail ///

///

- /// To set up the buffered mail target in the configuration file, + /// To set up the buffered mail target in the configuration file, /// use the following syntax: ///

/// @@ -91,7 +90,6 @@ public class MailTarget : TargetWithLayoutHeaderAndFooter /// /// The default value of the layout is: ${longdate}|${level:uppercase=true}|${logger}|${message} /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This one is safe.")] public MailTarget() { Body = "${message}${newline}"; @@ -209,18 +207,20 @@ public Layout Body /// /// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server. /// - /// See also + /// See also /// - /// . + /// + /// . [DefaultValue(false)] public bool EnableSsl { get; set; } /// - /// Provides a way of specifying the SSL and/or TLS encryption + /// Provides a way of specifying the SSL and/or TLS encryption /// - /// If is true, then will be used. + /// If is true, then will be used. /// [DefaultValue(SecureSocketOptions.StartTlsWhenAvailable)] + [CLSCompliant(false)] public SecureSocketOptions SecureSocketOption { get; set; } /// @@ -233,7 +233,8 @@ public Layout Body /// /// Gets or sets a value indicating whether SmtpClient should ignore invalid certificate. /// - /// . + /// + /// . [DefaultValue(false)] public bool SkipCertificateValidation { get; set; } @@ -243,9 +244,9 @@ public Layout Body public Layout Priority { get; set; } /// - /// Gets or sets a value indicating whether NewLine characters in the body should be replaced with
tags. + /// Gets or sets a value indicating whether NewLine characters in the body should be replaced with
tags. ///
- /// Only happens when is set to true. + /// Only happens when is set to true. [DefaultValue(false)] public bool ReplaceNewlineWithBrTagInHtml { get; set; } @@ -265,24 +266,6 @@ protected override void Write(AsyncLogEventInfo logEvent) Write((IList)new[] { logEvent }); } -#if !NETSTANDARD2_0 - - /// - /// NOTE! Will soon be marked obsolete. Instead override Write(IList{AsyncLogEventInfo} logEvents) - /// - /// Writes an array of logging events to the log target. By default it iterates on all - /// events and passes them to "Write" method. Inheriting classes can use this method to - /// optimize batch writes. - /// - /// Logging events to be written out. - [Obsolete("Write(AsyncLogEventInfo[]) is obsolete. Override Write(IList{AsyncLogEventInfo} logEvents) instead.", true)] - protected override void Write(AsyncLogEventInfo[] logEvents) - { - Write((IList)logEvents); - } - -#endif - /// /// Renders an array logging events. /// @@ -306,7 +289,7 @@ protected override void InitializeTarget() InternalLogger.Debug("Init mailtarget with mailkit"); CheckRequiredParameters(); - if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm) + if (SmtpAuthentication == SmtpAuthenticationMode.Ntlm) { throw new NLogConfigurationException("Ntlm not yet supported"); } @@ -314,8 +297,6 @@ protected override void InitializeTarget() base.InitializeTarget(); } - - /// /// Create mail and send with SMTP /// @@ -329,8 +310,8 @@ private void ProcessSingleMailMessage(IList events) throw new NLogRuntimeException("We need at least one event."); } - LogEventInfo firstEvent = events[0].LogEvent; - LogEventInfo lastEvent = events[events.Count - 1].LogEvent; + var firstEvent = events[0].LogEvent; + var lastEvent = events[events.Count - 1].LogEvent; // unbuffered case, create a local buffer, append header, body and footer var bodyBuffer = CreateBodyBuffer(events, firstEvent, lastEvent); @@ -351,10 +332,12 @@ private void ProcessSingleMailMessage(IList events) var secureSocketOptions = EnableSsl ? SecureSocketOptions.SslOnConnect : SecureSocketOption; InternalLogger.Debug("Sending mail to {0} using {1}:{2} (socket option={3})", message.To, renderedHost, SmtpPort, secureSocketOptions); InternalLogger.Trace(" Subject: '{0}'", message.Subject); - InternalLogger.Trace(" From: '{0}'", message.From.ToString()); + InternalLogger.Trace(" From: '{0}'", message.From); if (SkipCertificateValidation) + { client.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true; + } client.Connect(renderedHost, SmtpPort, secureSocketOptions); @@ -366,7 +349,7 @@ private void ProcessSingleMailMessage(IList events) // Note: only needed if the SMTP server requires authentication - if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic) + if (SmtpAuthentication == SmtpAuthenticationMode.Basic) { var userName = SmtpUserName?.Render(lastEvent); var password = SmtpPassword?.Render(lastEvent); @@ -423,7 +406,7 @@ private StringBuilder CreateBodyBuffer(IEnumerable events, Lo } } - foreach (AsyncLogEventInfo eventInfo in events) + foreach (var eventInfo in events) { bodyBuffer.Append(Layout.Render(eventInfo.LogEvent)); if (AddNewLines) @@ -440,6 +423,7 @@ private StringBuilder CreateBodyBuffer(IEnumerable events, Lo bodyBuffer.Append("\n"); } } + return bodyBuffer; } @@ -459,8 +443,8 @@ private void CheckRequiredParameters() /// /// Create key for grouping. Needed for multiple events in one mailmessage /// - /// event for rendering layouts - ///string to group on + /// event for rendering layouts + /// string to group on private string GetSmtpSettingsKey(LogEventInfo logEvent) { var sb = new StringBuilder(); @@ -472,8 +456,7 @@ private string GetSmtpSettingsKey(LogEventInfo logEvent) AppendLayout(sb, logEvent, SmtpServer); AppendLayout(sb, logEvent, SmtpPassword); AppendLayout(sb, logEvent, SmtpUserName); - - + return sb.ToString(); } @@ -481,17 +464,17 @@ private string GetSmtpSettingsKey(LogEventInfo logEvent) /// Append rendered layout to the stringbuilder ///
/// append to this - /// event for rendering + /// event for rendering /// append if not null private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout) { sb.Append("|"); if (layout != null) + { sb.Append(layout.Render(logEvent)); + } } - - /// /// Create the mailmessage with the addresses, properties and body. /// @@ -505,6 +488,7 @@ private MimeMessage CreateMailMessage(LogEventInfo lastEvent, string body) { throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From"); } + msg.From.Add(MailboxAddress.Parse(renderedFrom)); var addedTo = AddAddresses(msg.To, To, lastEvent); @@ -523,22 +507,21 @@ private MimeMessage CreateMailMessage(LogEventInfo lastEvent, string body) if (Priority != null) { var renderedPriority = Priority.Render(lastEvent); - MessagePriority messagePriority; - messagePriority = ParseMessagePriority(renderedPriority); - msg.Priority = messagePriority; + msg.Priority = ParseMessagePriority(renderedPriority); } TextPart CreateBodyPart() { var newBody = body; if (Html && ReplaceNewlineWithBrTagInHtml) + { newBody = newBody?.Replace(Environment.NewLine, "
"); + } + return new TextPart(Html ? TextFormat.Html : TextFormat.Plain) { Text = newBody, ContentType = { Charset = Encoding?.WebName } - - }; } @@ -547,7 +530,7 @@ TextPart CreateBodyPart() return msg; } - public static MessagePriority ParseMessagePriority(string priority) + internal static MessagePriority ParseMessagePriority(string priority) { if (string.IsNullOrWhiteSpace(priority)) { @@ -559,10 +542,12 @@ public static MessagePriority ParseMessagePriority(string priority) { return MessagePriority.Urgent; } + if (priority.Equals("Low", StringComparison.OrdinalIgnoreCase)) { return MessagePriority.NonUrgent; } + MessagePriority messagePriority; try { @@ -580,26 +565,27 @@ public static MessagePriority ParseMessagePriority(string priority) } /// - /// Render and add the addresses to + /// Render and add the addresses to /// /// Addresses appended to this list /// layout with addresses, ; separated - /// event for rendering the + /// event for rendering the /// added a address? private static bool AddAddresses(InternetAddressList mailAddressCollection, Layout layout, LogEventInfo logEvent) { + if (layout == null) + { + return false; + } + var added = false; - if (layout != null) + foreach (var mail in layout.Render(logEvent).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { - foreach (string mail in layout.Render(logEvent).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) - { - mailAddressCollection.Add(MailboxAddress.Parse(mail)); - added = true; - } + mailAddressCollection.Add(MailboxAddress.Parse(mail)); + added = true; } return added; } } -} - +} \ No newline at end of file diff --git a/src/NLog.MailKit/NLog.MailKit.csproj b/src/NLog.MailKit/NLog.MailKit.csproj index 2d76ca7..c519492 100644 --- a/src/NLog.MailKit/NLog.MailKit.csproj +++ b/src/NLog.MailKit/NLog.MailKit.csproj @@ -1,14 +1,13 @@  - netstandard1.3;netstandard1.5;net45;netstandard2.0 + netstandard2.0 Julian Verdurmen NLog - NLog Mail Target for .NET Core & .NET Standard, and .NET 4.5+ using MailKit. + NLog Mail Target for .NET Core & .NET Standard 2.0+ using MailKit. This package add the mail target to NLog and has the same options* as the original Mail Target. -If the mail target was already available on your platform (.NET Standard 2+, .NET 4.5), -this package will overwrite the original Mail Target. +If the mail target was already available on your platform, this package will overwrite the original Mail Target. * Compared to the original MailTarget, the following options aren't implemented: @@ -27,22 +26,17 @@ this package will overwrite the original Mail Target. True True NLog.snk - False + false -# 🍩 Package improvements -- Enable deterministic build @304NotModified (#124) -- Enabled SourceLink @304NotModified (#127) -- Create and publish snupkg @304NotModified (#123) - -# ↜ Dependencies -- Bump MailKit to 2.9.0 @304NotModified (#128) -- Bump NLog from 4.7.4 to 4.7.12 @304NotModified @dependabot-preview (#96, #112, #125) +- .NET Standard 2.0 only +- Updated MailKit dependency +- CLSCompliant (expect SecureSocketOption) See https://github.com/NLog/NLog.MailKit/releases - 2.0.0.0 - + 4.0.0.0 + bin\Release\$(TargetFramework)\NLog.MailKit.xml @@ -50,7 +44,7 @@ See https://github.com/NLog/NLog.MailKit/releases RELEASE - + diff --git a/src/NLog.MailKit/Properties/AssemblyInfo.cs b/src/NLog.MailKit/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c6f0eb6 --- /dev/null +++ b/src/NLog.MailKit/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System; +using System.Runtime.CompilerServices; + +[assembly: CLSCompliant(true)] +[assembly: InternalsVisibleTo("NLog.MailKit.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100772391E63C104728ADCF18E2390474262559FA7F34A4215848F43288CDE875DCC92A06222E9BE0592B211FF74ADBB5D21A7AAB5522B540B1735F2F03279221056FEDBE7E534073DABEE9DB48F8ECEBCF1DC98A95576E45CBEFF5FE7C4842859451AB2DAE7A8370F1B2F7A529D2CA210E3E844D973523D73D193DF6C17F1314A6")] + diff --git a/src/NLog.MailKit/SmtpAuthenticationMode.cs b/src/NLog.MailKit/SmtpAuthenticationMode.cs index c2e6a36..fd3b457 100644 --- a/src/NLog.MailKit/SmtpAuthenticationMode.cs +++ b/src/NLog.MailKit/SmtpAuthenticationMode.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace NLog.MailKit { diff --git a/src/NLog.MailKit/Util/ArrayHelper.cs b/src/NLog.MailKit/Util/ArrayHelper.cs deleted file mode 100644 index 35d4bab..0000000 --- a/src/NLog.MailKit/Util/ArrayHelper.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright (c) 2004-2016 Jaroslaw Kowalski , Kim Christensen, Julian Verdurmen -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Jaroslaw Kowalski nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -// - -namespace NLog.Internal -{ - internal static class ArrayHelper - { - private static class EmptyArray - { - public static readonly T[] Instance = new T[0]; - } - - public static T[] Empty() - { - // TODO Use Array.Empty in NET 4.6 when we are ready - return EmptyArray.Instance; - } - } -} diff --git a/src/NLog.MailKit/Util/ExceptionHelper.cs b/src/NLog.MailKit/Util/ExceptionHelper.cs index 8e7e718..031070b 100644 --- a/src/NLog.MailKit/Util/ExceptionHelper.cs +++ b/src/NLog.MailKit/Util/ExceptionHelper.cs @@ -1,5 +1,5 @@ // -// Copyright (c) 2004-2016 Jaroslaw Kowalski , Kim Christensen, Julian Verdurmen +// Copyright (c) 2004-2021 Jaroslaw Kowalski , Kim Christensen, Julian Verdurmen // // All rights reserved. // @@ -31,12 +31,11 @@ // THE POSSIBILITY OF SUCH DAMAGE. // -namespace NLog.Internal -{ - using System; - using Common; - using System.Threading; +using System; +using NLog.Common; +namespace NLog.MailKit.Util +{ /// /// Helper class for dealing with exceptions. /// @@ -44,19 +43,6 @@ internal static class ExceptionHelper { private const string LoggedKey = "NLog.ExceptionLoggedToInternalLogger"; - /// - /// Mark this exception as logged to the . - /// - /// - /// - public static void MarkAsLoggedToInternalLogger(this Exception exception) - { - if (exception != null) - { - exception.Data[LoggedKey] = true; - } - } - /// /// Is this exception logged to the ? /// diff --git a/src/NLog.MailKit/Util/SortHelpers.cs b/src/NLog.MailKit/Util/SortHelpers.cs index cce95f7..4dd9fd6 100644 --- a/src/NLog.MailKit/Util/SortHelpers.cs +++ b/src/NLog.MailKit/Util/SortHelpers.cs @@ -1,5 +1,5 @@ // -// Copyright (c) 2004-2016 Jaroslaw Kowalski , Kim Christensen, Julian Verdurmen +// Copyright (c) 2004-2021 Jaroslaw Kowalski , Kim Christensen, Julian Verdurmen // // All rights reserved. // @@ -31,13 +31,13 @@ // THE POSSIBILITY OF SUCH DAMAGE. // -namespace NLog.Internal -{ - using System; - using System.Collections; - using System.Collections.Generic; - using NLog.Common; +using System; +using System.Collections; +using System.Collections.Generic; +using NLog.Common; +namespace NLog.MailKit.Util +{ /// /// Provides helpers to sort log events and associated continuations. /// @@ -50,37 +50,7 @@ internal static class SortHelpers /// The type of the key. /// Value to extract key information from. /// Key selected from log event. - internal delegate TKey KeySelector(TValue value); - - /// - /// Performs bucket sort (group by) on an array of items and returns a dictionary for easy traversal of the result set. - /// - /// The type of the value. - /// The type of the key. - /// The inputs. - /// The key selector function. - /// - /// Dictionary where keys are unique input keys, and values are lists of . - /// - public static Dictionary> BucketSort(this IEnumerable inputs, KeySelector keySelector) - { - var buckets = new Dictionary>(); - - foreach (var input in inputs) - { - var keyValue = keySelector(input); - List eventsInBucket; - if (!buckets.TryGetValue(keyValue, out eventsInBucket)) - { - eventsInBucket = new List(); - buckets.Add(keyValue, eventsInBucket); - } - - eventsInBucket.Add(input); - } - - return buckets; - } + internal delegate TKey KeySelector(TValue value); /// /// Performs bucket sort (group by) on an array of items and returns a dictionary for easy traversal of the result set. @@ -96,7 +66,7 @@ public static ReadOnlySingleBucketDictionary> BucketSort> buckets = null; bool singleBucketFirstKey = false; - TKey singleBucketKey = default(TKey); + TKey singleBucketKey = default; EqualityComparer c = EqualityComparer.Default; for (int i = 0; i < inputs.Count; i++) { @@ -118,15 +88,13 @@ public static ReadOnlySingleBucketDictionary> BucketSort(); - bucket.Add(inputs[i]); + bucket = new List { inputs[i] }; buckets[keyValue] = bucket; } } else { - IList eventsInBucket; - if (!buckets.TryGetValue(keyValue, out eventsInBucket)) + if (!buckets.TryGetValue(keyValue, out var eventsInBucket)) { eventsInBucket = new List(); buckets.Add(keyValue, eventsInBucket); @@ -157,7 +125,6 @@ public struct ReadOnlySingleBucketDictionary : IDictionary? _singleBucket; readonly Dictionary _multiBucket; readonly IEqualityComparer _comparer; - public IEqualityComparer Comparer { get { return _comparer; } } public ReadOnlySingleBucketDictionary(KeyValuePair singleBucket) : this(singleBucket, EqualityComparer.Default) @@ -180,7 +147,7 @@ public ReadOnlySingleBucketDictionary(Dictionary multiBucket, IEqu { _comparer = comparer; _multiBucket = multiBucket; - _singleBucket = default(KeyValuePair); + _singleBucket = default; } /// @@ -193,10 +160,9 @@ public ICollection Keys { if (_multiBucket != null) return _multiBucket.Keys; - else if (_singleBucket.HasValue) + if (_singleBucket.HasValue) return new[] { _singleBucket.Value.Key }; - else - return ArrayHelper.Empty(); + return Array.Empty(); } } @@ -207,15 +173,14 @@ public ICollection Values { if (_multiBucket != null) return _multiBucket.Values; - else if (_singleBucket.HasValue) - return new TValue[] { _singleBucket.Value.Value }; - else - return ArrayHelper.Empty(); + if (_singleBucket.HasValue) + return new[] { _singleBucket.Value.Value }; + return Array.Empty(); } } /// - public bool IsReadOnly { get { return true; } } + public bool IsReadOnly => true; /// /// Allows direct lookup of existing keys. If trying to access non-existing key exception is thrown. @@ -229,10 +194,9 @@ public TValue this[TKey key] { if (_multiBucket != null) return _multiBucket[key]; - else if (_singleBucket.HasValue && _comparer.Equals(_singleBucket.Value.Key, key)) + if (_singleBucket.HasValue && _comparer.Equals(_singleBucket.Value.Key, key)) return _singleBucket.Value.Value; - else - throw new System.Collections.Generic.KeyNotFoundException(); + throw new KeyNotFoundException(); } set { @@ -252,7 +216,7 @@ public struct Enumerator : IEnumerator> internal Enumerator(Dictionary multiBucket) { _singleBucketFirstRead = false; - _singleBucket = default(KeyValuePair); + _singleBucket = default; _multiBuckets = multiBucket.GetEnumerator(); } @@ -274,12 +238,11 @@ public KeyValuePair Current } } - object IEnumerator.Current { get { return Current; } } + object IEnumerator.Current => Current; public void Dispose() { - if (_multiBuckets != null) - _multiBuckets.Dispose(); + _multiBuckets?.Dispose(); } public bool MoveNext() @@ -306,10 +269,9 @@ public Enumerator GetEnumerator() { if (_multiBucket != null) return new Enumerator(_multiBucket); - else if (_singleBucket.HasValue) + if (_singleBucket.HasValue) return new Enumerator(_singleBucket.Value); - else - return new Enumerator(new Dictionary()); + return new Enumerator(new Dictionary()); } /// @@ -329,10 +291,9 @@ public bool ContainsKey(TKey key) { if (_multiBucket != null) return _multiBucket.ContainsKey(key); - else if (_singleBucket.HasValue) + if (_singleBucket.HasValue) return _comparer.Equals(_singleBucket.Value.Key, key); - else - return false; + return false; } /// Will always throw, as dictionary is readonly @@ -354,16 +315,14 @@ public bool TryGetValue(TKey key, out TValue value) { return _multiBucket.TryGetValue(key, out value); } - else if (_singleBucket.HasValue && _comparer.Equals(_singleBucket.Value.Key, key)) + if (_singleBucket.HasValue && _comparer.Equals(_singleBucket.Value.Key, key)) { value = _singleBucket.Value.Value; return true; } - else - { - value = default(TValue); - return false; - } + + value = default; + return false; } /// Will always throw, as dictionary is readonly @@ -383,10 +342,9 @@ public bool Contains(KeyValuePair item) { if (_multiBucket != null) return ((IDictionary)_multiBucket).Contains(item); - else if (_singleBucket.HasValue) + if (_singleBucket.HasValue) return _comparer.Equals(_singleBucket.Value.Key, item.Key) && EqualityComparer.Default.Equals(_singleBucket.Value.Value, item.Value); - else - return false; + return false; } /// diff --git a/test/NLog.MailKit.Tests/IntegrationTests/MailTargetIntegrationTests.cs b/test/NLog.MailKit.Tests/IntegrationTests/MailTargetIntegrationTests.cs index 7515797..1f18c77 100644 --- a/test/NLog.MailKit.Tests/IntegrationTests/MailTargetIntegrationTests.cs +++ b/test/NLog.MailKit.Tests/IntegrationTests/MailTargetIntegrationTests.cs @@ -4,12 +4,12 @@ using System.Threading; using System.Threading.Tasks; using NLog.Config; -using NLog.MailKit.Tests.Util; +using NLog.MailKit.Tests.IntegrationTests.Util; using SmtpServer; using SmtpServer.Authentication; using SmtpServer.Mail; using Xunit; -using UserAuthenticator = NLog.MailKit.Tests.Util.UserAuthenticator; +using UserAuthenticator = NLog.MailKit.Tests.IntegrationTests.Util.UserAuthenticator; namespace NLog.MailKit.Tests.IntegrationTests { @@ -18,19 +18,19 @@ public class MailTargetIntegrationTests [Fact] public void SendUnauthenticationMail() { - SendTest(() => - { - CreateNLogConfig(); - }, 1); + SendTest(() => + { + CreateNLogConfig(); + }, 1); } [Fact] public void SendAuthenticationMail() { - SendTest(() => - { - CreateNLogConfig("user1", "myPassw0rd"); - }, 1); + SendTest(() => + { + CreateNLogConfig("user1", "myPassw0rd"); + }, 1); } [Fact] @@ -42,7 +42,7 @@ public void SendAuthenticationMail_cc_with_name() mailTarget.Cc = "no reply "; }, 2); - //2nd is cc + // 2nd is cc AssertMailBox("do_not_reply@domain.com", transactions[0].To[1]); } @@ -79,7 +79,6 @@ private static IList SendTest(Action createConfig, int toCo Assert.Equal(toCount, recievedMesssage.To.Count); return recievedTransactions; - } private static void AssertMailBox(string expected, IMailbox mailbox) @@ -107,7 +106,6 @@ private static SmtpServer.SmtpServer CreateSmtpServer(MessageStore store) .Port(25, 587) .MessageStore(store) .UserAuthenticator(userAuthenticatorFactory) - .Build(); var smtpServer = new SmtpServer.SmtpServer(options); diff --git a/test/NLog.MailKit.Tests/Util/MessageStore.cs b/test/NLog.MailKit.Tests/IntegrationTests/Util/MessageStore.cs similarity index 95% rename from test/NLog.MailKit.Tests/Util/MessageStore.cs rename to test/NLog.MailKit.Tests/IntegrationTests/Util/MessageStore.cs index 1d54b5e..c6128fe 100644 --- a/test/NLog.MailKit.Tests/Util/MessageStore.cs +++ b/test/NLog.MailKit.Tests/IntegrationTests/Util/MessageStore.cs @@ -6,7 +6,7 @@ using SmtpServer.Protocol; using SmtpServer.Storage; -namespace NLog.MailKit.Tests.Util +namespace NLog.MailKit.Tests.IntegrationTests.Util { public class MessageStore : IMessageStore, IMessageStoreFactory { @@ -24,7 +24,6 @@ public IMessageStore CreateInstance(ISessionContext context) return this; } - #region Implementation of IMessageStore /// diff --git a/test/NLog.MailKit.Tests/Util/UserAuthenticator.cs b/test/NLog.MailKit.Tests/IntegrationTests/Util/UserAuthenticator.cs similarity index 94% rename from test/NLog.MailKit.Tests/Util/UserAuthenticator.cs rename to test/NLog.MailKit.Tests/IntegrationTests/Util/UserAuthenticator.cs index 6b0f59c..65375af 100644 --- a/test/NLog.MailKit.Tests/Util/UserAuthenticator.cs +++ b/test/NLog.MailKit.Tests/IntegrationTests/Util/UserAuthenticator.cs @@ -4,7 +4,7 @@ using SmtpServer; using SmtpServer.Authentication; -namespace NLog.MailKit.Tests.Util +namespace NLog.MailKit.Tests.IntegrationTests.Util { public class UserAuthenticator : IUserAuthenticator { @@ -17,7 +17,6 @@ public UserAuthenticator(string username, string pasword) _username = username; _pasword = pasword; } - #region Implementation of IUserAuthenticator diff --git a/test/NLog.MailKit.Tests/Util/UserAuthenticatorFactory.cs b/test/NLog.MailKit.Tests/IntegrationTests/Util/UserAuthenticatorFactory.cs similarity index 91% rename from test/NLog.MailKit.Tests/Util/UserAuthenticatorFactory.cs rename to test/NLog.MailKit.Tests/IntegrationTests/Util/UserAuthenticatorFactory.cs index 9b81293..55d357f 100644 --- a/test/NLog.MailKit.Tests/Util/UserAuthenticatorFactory.cs +++ b/test/NLog.MailKit.Tests/IntegrationTests/Util/UserAuthenticatorFactory.cs @@ -1,7 +1,7 @@ using SmtpServer; using SmtpServer.Authentication; -namespace NLog.MailKit.Tests.Util +namespace NLog.MailKit.Tests.IntegrationTests.Util { internal class UserAuthenticatorFactory : IUserAuthenticatorFactory { diff --git a/test/NLog.MailKit.Tests/NLog.MailKit.Tests.csproj b/test/NLog.MailKit.Tests/NLog.MailKit.Tests.csproj index 4f09f71..53ccb04 100644 --- a/test/NLog.MailKit.Tests/NLog.MailKit.Tests.csproj +++ b/test/NLog.MailKit.Tests/NLog.MailKit.Tests.csproj @@ -1,15 +1,18 @@  - netcoreapp1.1;net461;netcoreapp2.0 + net5.0 true + true + NLog.snk + false - - + + - + all runtime; build; native; contentfiles; analyzers @@ -18,9 +21,4 @@ - - - - - diff --git a/test/NLog.MailKit.Tests/NLog.snk b/test/NLog.MailKit.Tests/NLog.snk new file mode 100644 index 0000000000000000000000000000000000000000..ae6cb7d01d85b831ba2f6ab0e2fbaa692164a5fc GIT binary patch literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa50097ZBa!Aj5JxDj&luu41au}PS^9r8q#;;H z^fHLe=ylx5Dh47ho8Vb1As_cj+qKdfdaG3;wLr0RUoQhEk|70e?Y@3fKy%u@>Dx&7 z?CZ}R$%>U%Zbi%Q_5OTFLWPu3t1Yg2gK+V(_oXS)${`LugiV(}AuGmSC}o2FHuW ziCY@EH!IfqVZP8U`xovV7tY}iFPjVc%BcX+KT&`M&tB{Q4)M{u;O{%OsSWFw90{=| z^^>k)FPYE14$#0|>VBiwZ<(m84Xw+En?Vc$ofR)3T(s>jr$t}+KWYW)-sB;?{43JI z?A+b5suA~4Ck2dF-*aWA2b7^f-lHV{v*5wH_a;Ciquf{ti(A+M@@qn)uw^PnCf)oo zAS#avpi$bcdYRIt?q-ohP`$mf5LG*YmS4%^gV->^gxlldvuI)>Rj$VTI`VhY0Z&kGPcpCxQznHRpCjb zq8Nuam>O!4&&u&Q!v6y7whD@{;mkY1X{Dr*)nV09UnI8?g7PniJqHapba+|?`*o0o znisZpG@k%Fhl^da--1sYBw(>Vf1ZdUY4AmXwY?N?9HWAWT7?*<2vGYzc$F&^b>>7` iI$@2}JhNx++NQVawRlUo^AY`{4X0Ub!o*$|r!jusyCb~- literal 0 HcmV?d00001 diff --git a/test/NLog.MailKit.Tests/UnitTests/MailTargetTests.cs b/test/NLog.MailKit.Tests/UnitTests/MailTargetTests.cs index 179e598..094fb17 100644 --- a/test/NLog.MailKit.Tests/UnitTests/MailTargetTests.cs +++ b/test/NLog.MailKit.Tests/UnitTests/MailTargetTests.cs @@ -1,9 +1,8 @@ -using NLog.MailKit; using System; using MimeKit; using Xunit; -namespace NLog.MailKit.Tests +namespace NLog.MailKit.Tests.UnitTests { public class MailTargetTests {