//
// Setting forceCaptureContext enables the ContextCopy property even when a null callback is specified. (The context is
// always captured if a callback is given.)
- internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object myObject, object? myState, AsyncCallback? myCallBack) :
+ internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object? myObject, object? myState, AsyncCallback? myCallBack) :
this(captureIdentity, forceCaptureContext, false, myObject, myState, myCallBack)
{ }
- internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object? myState, AsyncCallback? myCallBack) :
+ internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object? myObject, object? myState, AsyncCallback? myCallBack) :
base(myObject, myState, myCallBack)
{
if (forceCaptureContext)
throw new FormatException(SR.InvalidHeaderName);
}
- internal static string? ReadQuotedString(string data, ref int offset, StringBuilder builder)
+ internal static string? ReadQuotedString(string data, ref int offset, StringBuilder? builder)
{
return ReadQuotedString(data, ref offset, builder, false, false);
}
throw new FormatException(SR.MailHeaderFieldMalformedHeader);
}
- internal static string? ReadParameterAttribute(string data, ref int offset, StringBuilder builder)
+ internal static string? ReadParameterAttribute(string data, ref int offset, StringBuilder? builder)
{
if (!SkipCFWS(data, ref offset))
return null; //
#nullable enable
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
private SafeFreeCredentials? _credentialsHandle;
private SafeDeleteContext? _securityContext;
- private string _spn = null!;
+ private string? _spn;
private int _tokenSize;
private ContextFlagsPal _requestedContextFlags;
//
// This overload does not attempt to impersonate because the caller either did it already or the original thread context is still preserved.
//
- internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
+ internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string? spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
{
Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
}
- private void Initialize(bool isServer, string package, NetworkCredential credential, string spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
+ private void Initialize(bool isServer, string package, NetworkCredential credential, string? spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, package, spn, requestedContextFlags);
return NegotiateStreamPal.VerifySignature(_securityContext!, buffer, offset, count);
}
- internal int MakeSignature(byte[] buffer, int offset, int count, ref byte[] output)
+ internal int MakeSignature(byte[] buffer, int offset, int count, [AllowNull] ref byte[] output)
{
return NegotiateStreamPal.MakeSignature(_securityContext!, buffer, offset, count, ref output);
}
return outgoingBlob;
}
- internal byte[]? GetOutgoingBlob(byte[] incomingBlob, bool thrownOnError)
+ internal byte[]? GetOutgoingBlob(byte[]? incomingBlob, bool thrownOnError)
{
SecurityStatusPal statusCode;
return GetOutgoingBlob(incomingBlob, thrownOnError, out statusCode);
using System.IO;
using System.ComponentModel;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication;
SafeFreeNegoCredentials credential,
ref SafeDeleteContext? context,
ChannelBinding? channelBinding,
- string targetName,
+ string? targetName,
ContextFlagsPal inFlags,
byte[]? incomingBlob,
ref byte[]? resultBuffer,
NetEventSource.Info(context, $"requested protocol = {protocol}, target = {targetName}");
}
- context = new SafeDeleteNegoContext(credential, targetName);
+ context = new SafeDeleteNegoContext(credential, targetName!);
}
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)context;
internal static SecurityStatusPal InitializeSecurityContext(
ref SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext? securityContext,
- string spn,
+ string? spn,
ContextFlagsPal requestedContextFlags,
byte[]? incomingBlob,
ChannelBinding? channelBinding,
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer!, offset, count);
}
- internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output)
+ internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, [AllowNull] ref byte[] output)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext)securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, false, buffer, offset, count);
#nullable enable
using System.ComponentModel;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
internal static SecurityStatusPal InitializeSecurityContext(
ref SafeFreeCredentials? credentialsHandle,
ref SafeDeleteContext? securityContext,
- string spn,
+ string? spn,
ContextFlagsPal requestedContextFlags,
byte[]? incomingBlob,
ChannelBinding? channelBinding,
return securityBuffer[1].size;
}
- internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output)
+ internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, [AllowNull] ref byte[] output)
{
SecPkgContext_Sizes sizes = default;
bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_SIZES, ref sizes);
{
private readonly SslStream _sslStream;
private readonly string _host;
- private readonly X509CertificateCollection _clientCertificates;
+ private readonly X509CertificateCollection? _clientCertificates;
- public TlsStream(NetworkStream stream, Socket socket, string host, X509CertificateCollection clientCertificates) : base(socket)
+ public TlsStream(NetworkStream stream, Socket socket, string host, X509CertificateCollection? clientCertificates) : base(socket)
{
_sslStream = new SslStream(stream, false, ServicePointManager.ServerCertificateValidationCallback);
_host = host;
public partial class AlternateView : System.Net.Mail.AttachmentBase
{
public AlternateView(System.IO.Stream contentStream) : base (default(System.IO.Stream)) { }
- public AlternateView(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
- public AlternateView(System.IO.Stream contentStream, string mediaType) : base (default(System.IO.Stream)) { }
+ public AlternateView(System.IO.Stream contentStream, System.Net.Mime.ContentType? contentType) : base (default(System.IO.Stream)) { }
+ public AlternateView(System.IO.Stream contentStream, string? mediaType) : base (default(System.IO.Stream)) { }
public AlternateView(string fileName) : base (default(System.IO.Stream)) { }
- public AlternateView(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
- public AlternateView(string fileName, string mediaType) : base (default(System.IO.Stream)) { }
- public System.Uri BaseUri { get { throw null; } set { } }
+ public AlternateView(string fileName, System.Net.Mime.ContentType? contentType) : base (default(System.IO.Stream)) { }
+ public AlternateView(string fileName, string? mediaType) : base (default(System.IO.Stream)) { }
+ public System.Uri? BaseUri { get { throw null; } set { } }
public System.Net.Mail.LinkedResourceCollection LinkedResources { get { throw null; } }
public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content) { throw null; }
- public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Net.Mime.ContentType contentType) { throw null; }
- public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Text.Encoding contentEncoding, string mediaType) { throw null; }
+ public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Net.Mime.ContentType? contentType) { throw null; }
+ public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Text.Encoding? contentEncoding, string? mediaType) { throw null; }
protected override void Dispose(bool disposing) { }
}
public sealed partial class AlternateViewCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.AlternateView>, System.IDisposable
public partial class Attachment : System.Net.Mail.AttachmentBase
{
public Attachment(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
- public Attachment(System.IO.Stream contentStream, string name) : base (default(System.IO.Stream)) { }
- public Attachment(System.IO.Stream contentStream, string name, string mediaType) : base (default(System.IO.Stream)) { }
+ public Attachment(System.IO.Stream contentStream, string? name) : base (default(System.IO.Stream)) { }
+ public Attachment(System.IO.Stream contentStream, string? name, string? mediaType) : base (default(System.IO.Stream)) { }
public Attachment(string fileName) : base (default(System.IO.Stream)) { }
public Attachment(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
- public Attachment(string fileName, string mediaType) : base (default(System.IO.Stream)) { }
- public System.Net.Mime.ContentDisposition ContentDisposition { get { throw null; } }
- public string Name { get { throw null; } set { } }
- public System.Text.Encoding NameEncoding { get { throw null; } set { } }
+ public Attachment(string fileName, string? mediaType) : base (default(System.IO.Stream)) { }
+ public System.Net.Mime.ContentDisposition? ContentDisposition { get { throw null; } }
+ public string? Name { get { throw null; } set { } }
+ public System.Text.Encoding? NameEncoding { get { throw null; } set { } }
public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, System.Net.Mime.ContentType contentType) { throw null; }
- public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string name) { throw null; }
- public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string name, System.Text.Encoding contentEncoding, string mediaType) { throw null; }
+ public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string? name) { throw null; }
+ public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string? name, System.Text.Encoding? contentEncoding, string mediaType) { throw null; }
}
public abstract partial class AttachmentBase : System.IDisposable
{
protected AttachmentBase(System.IO.Stream contentStream) { }
- protected AttachmentBase(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) { }
- protected AttachmentBase(System.IO.Stream contentStream, string mediaType) { }
+ protected AttachmentBase(System.IO.Stream contentStream, System.Net.Mime.ContentType? contentType) { }
+ protected AttachmentBase(System.IO.Stream contentStream, string? mediaType) { }
protected AttachmentBase(string fileName) { }
- protected AttachmentBase(string fileName, System.Net.Mime.ContentType contentType) { }
- protected AttachmentBase(string fileName, string mediaType) { }
+ protected AttachmentBase(string fileName, System.Net.Mime.ContentType? contentType) { }
+ protected AttachmentBase(string fileName, string? mediaType) { }
+ [System.Diagnostics.CodeAnalysis.AllowNull]
public string ContentId { get { throw null; } set { } }
public System.IO.Stream ContentStream { get { throw null; } }
public System.Net.Mime.ContentType ContentType { get { throw null; } set { } }
public partial class LinkedResource : System.Net.Mail.AttachmentBase
{
public LinkedResource(System.IO.Stream contentStream) : base (default(System.IO.Stream)) { }
- public LinkedResource(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
- public LinkedResource(System.IO.Stream contentStream, string mediaType) : base (default(System.IO.Stream)) { }
+ public LinkedResource(System.IO.Stream contentStream, System.Net.Mime.ContentType? contentType) : base (default(System.IO.Stream)) { }
+ public LinkedResource(System.IO.Stream contentStream, string? mediaType) : base (default(System.IO.Stream)) { }
public LinkedResource(string fileName) : base (default(System.IO.Stream)) { }
- public LinkedResource(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
- public LinkedResource(string fileName, string mediaType) : base (default(System.IO.Stream)) { }
- public System.Uri ContentLink { get { throw null; } set { } }
+ public LinkedResource(string fileName, System.Net.Mime.ContentType? contentType) : base (default(System.IO.Stream)) { }
+ public LinkedResource(string fileName, string? mediaType) : base (default(System.IO.Stream)) { }
+ public System.Uri? ContentLink { get { throw null; } set { } }
public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content) { throw null; }
- public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType contentType) { throw null; }
- public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Text.Encoding contentEncoding, string mediaType) { throw null; }
+ public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType? contentType) { throw null; }
+ public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Text.Encoding? contentEncoding, string? mediaType) { throw null; }
}
public sealed partial class LinkedResourceCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.LinkedResource>, System.IDisposable
{
public partial class MailAddress
{
public MailAddress(string address) { }
- public MailAddress(string address, string displayName) { }
- public MailAddress(string address, string displayName, System.Text.Encoding displayNameEncoding) { }
+ public MailAddress(string address, string? displayName) { }
+ public MailAddress(string address, string? displayName, System.Text.Encoding? displayNameEncoding) { }
public string Address { get { throw null; } }
public string DisplayName { get { throw null; } }
public string Host { get { throw null; } }
public string User { get { throw null; } }
- public override bool Equals(object value) { throw null; }
+ public override bool Equals(object? value) { throw null; }
public override int GetHashCode() { throw null; }
- public static bool TryCreate(string address, out MailAddress result) { throw null; }
- public static bool TryCreate(string address, string displayName, out MailAddress result) { throw null; }
- public static bool TryCreate(string address, string displayName, System.Text.Encoding displayNameEncoding, out MailAddress result) { throw null; }
+ public static bool TryCreate(string address, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out MailAddress? result) { throw null; }
+ public static bool TryCreate(string address, string? displayName, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out MailAddress? result) { throw null; }
+ public static bool TryCreate(string address, string? displayName, System.Text.Encoding displayNameEncoding, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out MailAddress? result) { throw null; }
public override string ToString() { throw null; }
}
public partial class MailAddressCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.MailAddress>
public MailMessage() { }
public MailMessage(System.Net.Mail.MailAddress from, System.Net.Mail.MailAddress to) { }
public MailMessage(string from, string to) { }
- public MailMessage(string from, string to, string subject, string body) { }
+ public MailMessage(string from, string to, string? subject, string? body) { }
public System.Net.Mail.AlternateViewCollection AlternateViews { get { throw null; } }
public System.Net.Mail.AttachmentCollection Attachments { get { throw null; } }
public System.Net.Mail.MailAddressCollection Bcc { get { throw null; } }
+ [System.Diagnostics.CodeAnalysis.AllowNull]
public string Body { get { throw null; } set { } }
- public System.Text.Encoding BodyEncoding { get { throw null; } set { } }
+ public System.Text.Encoding? BodyEncoding { get { throw null; } set { } }
public System.Net.Mime.TransferEncoding BodyTransferEncoding { get { throw null; } set { } }
public System.Net.Mail.MailAddressCollection CC { get { throw null; } }
public System.Net.Mail.DeliveryNotificationOptions DeliveryNotificationOptions { get { throw null; } set { } }
- public System.Net.Mail.MailAddress From { get { throw null; } set { } }
+ [System.Diagnostics.CodeAnalysis.DisallowNull]
+ public System.Net.Mail.MailAddress? From { get { throw null; } set { } }
public System.Collections.Specialized.NameValueCollection Headers { get { throw null; } }
- public System.Text.Encoding HeadersEncoding { get { throw null; } set { } }
+ public System.Text.Encoding? HeadersEncoding { get { throw null; } set { } }
public bool IsBodyHtml { get { throw null; } set { } }
public System.Net.Mail.MailPriority Priority { get { throw null; } set { } }
[System.ObsoleteAttribute("ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. https://go.microsoft.com/fwlink/?linkid=14202")]
- public System.Net.Mail.MailAddress ReplyTo { get { throw null; } set { } }
+ public System.Net.Mail.MailAddress? ReplyTo { get { throw null; } set { } }
public System.Net.Mail.MailAddressCollection ReplyToList { get { throw null; } }
- public System.Net.Mail.MailAddress Sender { get { throw null; } set { } }
+ [System.Diagnostics.CodeAnalysis.DisallowNull]
+ public System.Net.Mail.MailAddress? Sender { get { throw null; } set { } }
+ [System.Diagnostics.CodeAnalysis.AllowNull]
public string Subject { get { throw null; } set { } }
- public System.Text.Encoding SubjectEncoding { get { throw null; } set { } }
+ public System.Text.Encoding? SubjectEncoding { get { throw null; } set { } }
public System.Net.Mail.MailAddressCollection To { get { throw null; } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public partial class SmtpClient : System.IDisposable
{
public SmtpClient() { }
- public SmtpClient(string host) { }
- public SmtpClient(string host, int port) { }
+ public SmtpClient(string? host) { }
+ public SmtpClient(string? host, int port) { }
public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } }
- public System.Net.ICredentialsByHost Credentials { get { throw null; } set { } }
+ public System.Net.ICredentialsByHost? Credentials { get { throw null; } set { } }
public System.Net.Mail.SmtpDeliveryFormat DeliveryFormat { get { throw null; } set { } }
public System.Net.Mail.SmtpDeliveryMethod DeliveryMethod { get { throw null; } set { } }
public bool EnableSsl { get { throw null; } set { } }
- public string Host { get { throw null; } set { } }
- public string PickupDirectoryLocation { get { throw null; } set { } }
+ [System.Diagnostics.CodeAnalysis.DisallowNull]
+ public string? Host { get { throw null; } set { } }
+ public string? PickupDirectoryLocation { get { throw null; } set { } }
public int Port { get { throw null; } set { } }
public System.Net.ServicePoint ServicePoint { get { throw null; } }
- public string TargetName { get { throw null; } set { } }
+ public string? TargetName { get { throw null; } set { } }
public int Timeout { get { throw null; } set { } }
public bool UseDefaultCredentials { get { throw null; } set { } }
- public event System.Net.Mail.SendCompletedEventHandler SendCompleted { add { } remove { } }
+ public event System.Net.Mail.SendCompletedEventHandler? SendCompleted { add { } remove { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected void OnSendCompleted(System.ComponentModel.AsyncCompletedEventArgs e) { }
public void Send(System.Net.Mail.MailMessage message) { }
- public void Send(string from, string recipients, string subject, string body) { }
- public void SendAsync(System.Net.Mail.MailMessage message, object userToken) { }
- public void SendAsync(string from, string recipients, string subject, string body, object userToken) { }
+ public void Send(string from, string recipients, string? subject, string? body) { }
+ public void SendAsync(System.Net.Mail.MailMessage message, object? userToken) { }
+ public void SendAsync(string from, string recipients, string? subject, string? body, object? userToken) { }
public void SendAsyncCancel() { }
public System.Threading.Tasks.Task SendMailAsync(System.Net.Mail.MailMessage message) { throw null; }
- public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string subject, string body) { throw null; }
+ public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string? subject, string? body) { throw null; }
public System.Threading.Tasks.Task SendMailAsync(System.Net.Mail.MailMessage message, System.Threading.CancellationToken cancellationToken) { throw null; }
- public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string subject, string body, System.Threading.CancellationToken cancellationToken) { throw null; }
+ public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string? subject, string? body, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public enum SmtpDeliveryFormat
{
{
public SmtpException() { }
public SmtpException(System.Net.Mail.SmtpStatusCode statusCode) { }
- public SmtpException(System.Net.Mail.SmtpStatusCode statusCode, string message) { }
+ public SmtpException(System.Net.Mail.SmtpStatusCode statusCode, string? message) { }
protected SmtpException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
- public SmtpException(string message) { }
- public SmtpException(string message, System.Exception innerException) { }
+ public SmtpException(string? message) { }
+ public SmtpException(string? message, System.Exception? innerException) { }
public System.Net.Mail.SmtpStatusCode StatusCode { get { throw null; } set { } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
public partial class SmtpFailedRecipientException : System.Net.Mail.SmtpException, System.Runtime.Serialization.ISerializable
{
public SmtpFailedRecipientException() { }
- public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string failedRecipient) { }
- public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string failedRecipient, string serverResponse) { }
+ public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string? failedRecipient) { }
+ public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string? failedRecipient, string? serverResponse) { }
protected SmtpFailedRecipientException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
- public SmtpFailedRecipientException(string message) { }
- public SmtpFailedRecipientException(string message, System.Exception innerException) { }
- public SmtpFailedRecipientException(string message, string failedRecipient, System.Exception innerException) { }
- public string FailedRecipient { get { throw null; } }
+ public SmtpFailedRecipientException(string? message) { }
+ public SmtpFailedRecipientException(string? message, System.Exception? innerException) { }
+ public SmtpFailedRecipientException(string? message, string? failedRecipient, System.Exception? innerException) { }
+ public string? FailedRecipient { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
}
{
public SmtpFailedRecipientsException() { }
protected SmtpFailedRecipientsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
- public SmtpFailedRecipientsException(string message) { }
- public SmtpFailedRecipientsException(string message, System.Exception innerException) { }
- public SmtpFailedRecipientsException(string message, System.Net.Mail.SmtpFailedRecipientException[] innerExceptions) { }
+ public SmtpFailedRecipientsException(string? message) { }
+ public SmtpFailedRecipientsException(string? message, System.Exception? innerException) { }
+ public SmtpFailedRecipientsException(string? message, System.Net.Mail.SmtpFailedRecipientException[] innerExceptions) { }
public System.Net.Mail.SmtpFailedRecipientException[] InnerExceptions { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
public ContentDisposition(string disposition) { }
public System.DateTime CreationDate { get { throw null; } set { } }
public string DispositionType { get { throw null; } set { } }
- public string FileName { get { throw null; } set { } }
+ public string? FileName { get { throw null; } set { } }
public bool Inline { get { throw null; } set { } }
public System.DateTime ModificationDate { get { throw null; } set { } }
public System.Collections.Specialized.StringDictionary Parameters { get { throw null; } }
public System.DateTime ReadDate { get { throw null; } set { } }
public long Size { get { throw null; } set { } }
- public override bool Equals(object rparam) { throw null; }
+ public override bool Equals(object? rparam) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
}
{
public ContentType() { }
public ContentType(string contentType) { }
- public string Boundary { get { throw null; } set { } }
- public string CharSet { get { throw null; } set { } }
+ public string? Boundary { get { throw null; } set { } }
+ public string? CharSet { get { throw null; } set { } }
public string MediaType { get { throw null; } set { } }
+ [System.Diagnostics.CodeAnalysis.AllowNull]
public string Name { get { throw null; } set { } }
public System.Collections.Specialized.StringDictionary Parameters { get { throw null; } }
- public override bool Equals(object rparam) { throw null; }
+ public override bool Equals(object? rparam) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Net.Mail.cs" />
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System\Net\Base64Stream.cs" />
private readonly int _lineLength;
private readonly Base64WriteStateInfo _writeState;
- private ReadStateInfo _readState;
+ private ReadStateInfo? _readState;
//the number of bytes needed to encode three bytes (see algorithm description in Encode method below)
private const int SizeOfBase64EncodedChar = 4;
}
}
- public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
{
if (buffer == null)
{
return result;
}
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
{
if (buffer == null)
{
private static readonly AsyncCallback s_onRead = OnRead;
- internal ReadAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
+ internal ReadAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) : base(null, state, callback)
{
_parent = parent;
_buffer = buffer;
{
if (!result.CompletedSynchronously)
{
- ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState;
+ ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState!;
try
{
if (!thisPtr.CompleteRead(result))
private readonly int _count;
private int _written;
- internal WriteAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
+ internal WriteAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) : base(null, state, callback)
{
_parent = parent;
_buffer = buffer;
{
if (!result.CompletedSynchronously)
{
- WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
+ WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState!;
try
{
thisPtr.CompleteWrite(result);
_offset += count;
}
- internal void Append(string value)
+ internal void Append(string? value)
{
Append(value, false);
}
- internal void Append(string value, bool allowUnicode)
+ internal void Append(string? value, bool allowUnicode)
{
if (string.IsNullOrEmpty(value))
{
{
internal class BufferedReadStream : DelegatedStream
{
- private byte[] _storedBuffer;
+ private byte[]? _storedBuffer;
private int _storedLength;
private int _storedOffset;
private readonly bool _readMore;
}
}
- public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
{
ReadAsyncResult result = new ReadAsyncResult(this, callback, state);
result.Read(buffer, offset, count);
if (_storedOffset < _storedLength)
{
read = Math.Min(count, _storedLength - _storedOffset);
- Buffer.BlockCopy(_storedBuffer, _storedOffset, buffer, offset, read);
+ Buffer.BlockCopy(_storedBuffer!, _storedOffset, buffer, offset, read);
_storedOffset += read;
if (read == count || !_readMore)
{
}
read = Math.Min(count, _storedLength - _storedOffset);
- Buffer.BlockCopy(_storedBuffer, _storedOffset, buffer, offset, read);
+ Buffer.BlockCopy(_storedBuffer!, _storedOffset, buffer, offset, read);
_storedOffset += read;
if (read == count || !_readMore)
{
{
if (_storedOffset < _storedLength)
{
- return (int)_storedBuffer[_storedOffset++];
+ return _storedBuffer![_storedOffset++];
}
else
{
_storedOffset -= count;
}
// if there's room in the buffer but need to shift things over
- else if (count <= _storedBuffer.Length - _storedLength + _storedOffset)
+ else if (count <= _storedBuffer!.Length - _storedLength + _storedOffset)
{
Buffer.BlockCopy(_storedBuffer, _storedOffset, _storedBuffer, count, _storedLength - _storedOffset);
_storedLength += count - _storedOffset;
}
}
- Buffer.BlockCopy(buffer, offset, _storedBuffer, _storedOffset, count);
+ Buffer.BlockCopy(buffer, offset, _storedBuffer!, _storedOffset, count);
}
private class ReadAsyncResult : LazyAsyncResult
private int _read;
private static readonly AsyncCallback s_onRead = new AsyncCallback(OnRead);
- internal ReadAsyncResult(BufferedReadStream parent, AsyncCallback callback, object state) : base(null, state, callback)
+ internal ReadAsyncResult(BufferedReadStream parent, AsyncCallback? callback, object? state) : base(null, state, callback)
{
_parent = parent;
}
if (_parent._storedOffset < _parent._storedLength)
{
_read = Math.Min(count, _parent._storedLength - _parent._storedOffset);
- Buffer.BlockCopy(_parent._storedBuffer, _parent._storedOffset, buffer, offset, _read);
+ Buffer.BlockCopy(_parent._storedBuffer!, _parent._storedOffset, buffer, offset, _read);
_parent._storedOffset += _read;
if (_read == count || !_parent._readMore)
{
{
if (!result.CompletedSynchronously)
{
- ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState;
+ ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState!;
try
{
thisPtr._read += thisPtr._parent.BaseStream.EndRead(result);
/// <summary>Provides a stream that notifies an event when the Close method is called.</summary>
internal class ClosableStream : DelegatedStream
{
- private readonly EventHandler _onClose;
+ private readonly EventHandler? _onClose;
private int _closed;
- internal ClosableStream(Stream stream, EventHandler onClose) : base(stream)
+ internal ClosableStream(Stream stream, EventHandler? onClose) : base(stream)
{
_onClose = onClose;
}
internal class DelegatedStream : Stream
{
private readonly Stream _stream;
- private readonly NetworkStream _netStream;
protected DelegatedStream(Stream stream)
{
throw new ArgumentNullException(nameof(stream));
_stream = stream;
- _netStream = stream as NetworkStream;
}
protected Stream BaseStream
}
}
- public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
{
if (!CanRead)
throw new NotSupportedException(SR.ReadNotSupported);
- IAsyncResult result = null;
-
- if (_netStream != null)
- {
- result = _netStream.BeginRead(buffer, offset, count, callback, state);
- }
- else
- {
- result = _stream.BeginRead(buffer, offset, count, callback, state);
- }
- return result;
+ return _stream.BeginRead(buffer, offset, count, callback, state);
}
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
{
if (!CanWrite)
throw new NotSupportedException(SR.WriteNotSupported);
- IAsyncResult result = null;
-
- if (_netStream != null)
- {
- result = _netStream.BeginWrite(buffer, offset, count, callback, state);
- }
- else
- {
- result = _stream.BeginWrite(buffer, offset, count, callback, state);
- }
- return result;
+ return _stream.BeginWrite(buffer, offset, count, callback, state);
}
//This calls close on the inner stream
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.IO;
using System.Net.Mime;
using System.Text;
{
public class AlternateView : AttachmentBase
{
- private LinkedResourceCollection _linkedResources;
+ private LinkedResourceCollection? _linkedResources;
internal AlternateView()
{ }
-
public AlternateView(string fileName) :
base(fileName)
{ }
- public AlternateView(string fileName, string mediaType) :
+ public AlternateView(string fileName, string? mediaType) :
base(fileName, mediaType)
{ }
- public AlternateView(string fileName, ContentType contentType) :
+ public AlternateView(string fileName, ContentType? contentType) :
base(fileName, contentType)
{ }
base(contentStream)
{ }
- public AlternateView(Stream contentStream, string mediaType) :
+ public AlternateView(Stream contentStream, string? mediaType) :
base(contentStream, mediaType)
{ }
- public AlternateView(Stream contentStream, ContentType contentType) :
+ public AlternateView(Stream contentStream, ContentType? contentType) :
base(contentStream, contentType)
{ }
throw new ObjectDisposedException(GetType().FullName);
}
-
- if (_linkedResources == null)
- {
- _linkedResources = new LinkedResourceCollection();
- }
- return _linkedResources;
+ return _linkedResources ??= new LinkedResourceCollection();
}
}
- public Uri BaseUri
+ public Uri? BaseUri
{
get
{
return a;
}
- public static AlternateView CreateAlternateViewFromString(string content, Encoding contentEncoding, string mediaType)
+ public static AlternateView CreateAlternateViewFromString(string content, Encoding? contentEncoding, string? mediaType)
{
AlternateView a = new AlternateView();
a.SetContentFromString(content, contentEncoding, mediaType);
return a;
}
- public static AlternateView CreateAlternateViewFromString(string content, ContentType contentType)
+ public static AlternateView CreateAlternateViewFromString(string content, ContentType? contentType)
{
AlternateView a = new AlternateView();
a.SetContentFromString(content, contentType);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.ObjectModel;
namespace System.Net.Mail
throw new ObjectDisposedException(GetType().FullName);
}
-
if (item == null)
{
throw new ArgumentNullException(nameof(item));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Mime;
using System.Text;
SetContentFromFile(fileName, string.Empty);
}
- protected AttachmentBase(string fileName, string mediaType)
+ protected AttachmentBase(string fileName, string? mediaType)
{
SetContentFromFile(fileName, mediaType);
}
- protected AttachmentBase(string fileName, ContentType contentType)
+ protected AttachmentBase(string fileName, ContentType? contentType)
{
SetContentFromFile(fileName, contentType);
}
_part.SetContent(contentStream);
}
- protected AttachmentBase(Stream contentStream, string mediaType)
+ protected AttachmentBase(Stream contentStream, string? mediaType)
{
_part.SetContent(contentStream, null, mediaType);
}
- internal AttachmentBase(Stream contentStream, string name, string mediaType)
+ internal AttachmentBase(Stream contentStream, string? name, string? mediaType)
{
_part.SetContent(contentStream, name, mediaType);
}
- protected AttachmentBase(Stream contentStream, ContentType contentType)
+ protected AttachmentBase(Stream contentStream, ContentType? contentType)
{
_part.SetContent(contentStream, contentType);
}
}
}
- internal void SetContentFromFile(string fileName, ContentType contentType)
+ internal void SetContentFromFile(string fileName, ContentType? contentType)
{
if (fileName == null)
{
_part.SetContent(stream, contentType);
}
- internal void SetContentFromFile(string fileName, string mediaType)
+ internal void SetContentFromFile(string fileName, string? mediaType)
{
if (fileName == null)
{
_part.SetContent(stream, null, mediaType);
}
- internal void SetContentFromString(string content, ContentType contentType)
+ internal void SetContentFromString(string content, ContentType? contentType)
{
if (content == null)
{
}
}
- internal void SetContentFromString(string content, Encoding encoding, string mediaType)
+ internal void SetContentFromString(string content, Encoding? encoding, string? mediaType)
{
if (content == null)
{
throw new ObjectDisposedException(GetType().FullName);
}
- return _part.Stream;
+ return _part.Stream!;
}
}
+ [AllowNull]
public string ContentId
{
get
{
- string cid = _part.ContentID;
+ string? cid = _part.ContentID;
if (string.IsNullOrEmpty(cid))
{
cid = Guid.NewGuid().ToString();
}
}
- internal Uri ContentLocation
+ internal Uri? ContentLocation
{
get
{
- Uri uri;
+ Uri? uri;
if (!Uri.TryCreate(_part.ContentLocation, UriKind.RelativeOrAbsolute, out uri))
{
return null;
public class Attachment : AttachmentBase
{
- private string _name;
- private Encoding _nameEncoding;
+ private string? _name;
+ private Encoding? _nameEncoding;
internal Attachment()
{
MimePart.ContentDisposition = new ContentDisposition();
}
- public Attachment(string fileName, string mediaType) :
+ public Attachment(string fileName, string? mediaType) :
base(fileName, mediaType)
{
Name = Path.GetFileName(fileName);
MimePart.ContentDisposition = new ContentDisposition();
}
- public Attachment(Stream contentStream, string name) :
+ public Attachment(Stream contentStream, string? name) :
base(contentStream, null, null)
{
Name = name;
MimePart.ContentDisposition = new ContentDisposition();
}
- public Attachment(Stream contentStream, string name, string mediaType) :
+ public Attachment(Stream contentStream, string? name, string? mediaType) :
base(contentStream, null, mediaType)
{
Name = name;
{
if (!allowUnicode && _name != null && _name.Length != 0 && !MimeBasePart.IsAscii(_name, false))
{
- Encoding encoding = NameEncoding;
- if (encoding == null)
- {
- encoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
- }
+ Encoding encoding = NameEncoding ?? Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
MimePart.ContentType.Name = MimeBasePart.EncodeHeaderValue(_name, encoding, MimeBasePart.ShouldUseBase64Encoding(encoding));
}
else
}
}
- public string Name
+ public string? Name
{
get
{
}
set
{
- Encoding nameEncoding = MimeBasePart.DecodeEncoding(value);
+ Encoding? nameEncoding = MimeBasePart.DecodeEncoding(value);
if (nameEncoding != null)
{
_nameEncoding = nameEncoding;
}
}
-
- public Encoding NameEncoding
+ public Encoding? NameEncoding
{
get
{
}
}
- public ContentDisposition ContentDisposition
+ public ContentDisposition? ContentDisposition
{
get
{
base.PrepareForSending(allowUnicode);
}
- public static Attachment CreateAttachmentFromString(string content, string name)
+ public static Attachment CreateAttachmentFromString(string content, string? name)
{
Attachment a = new Attachment();
a.SetContentFromString(content, null, string.Empty);
return a;
}
- public static Attachment CreateAttachmentFromString(string content, string name, Encoding contentEncoding, string mediaType)
+ public static Attachment CreateAttachmentFromString(string content, string? name, Encoding? contentEncoding, string? mediaType)
{
Attachment a = new Attachment();
a.SetContentFromString(content, contentEncoding, mediaType);
{
internal interface ISmtpAuthenticationModule
{
- Authorization Authenticate(string challenge, NetworkCredential credentials, object sessionCookie, string spn, ChannelBinding channelBindingToken);
+ Authorization? Authenticate(string? challenge, NetworkCredential? credentials, object sessionCookie, string? spn, ChannelBinding? channelBindingToken);
string AuthenticationType { get; }
//
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.IO;
using System.Net.Mime;
using System.Text;
base(fileName)
{ }
- public LinkedResource(string fileName, string mediaType) :
+ public LinkedResource(string fileName, string? mediaType) :
base(fileName, mediaType)
{ }
- public LinkedResource(string fileName, ContentType contentType) :
+ public LinkedResource(string fileName, ContentType? contentType) :
base(fileName, contentType)
{ }
base(contentStream)
{ }
- public LinkedResource(Stream contentStream, string mediaType) :
+ public LinkedResource(Stream contentStream, string? mediaType) :
base(contentStream, mediaType)
{ }
- public LinkedResource(Stream contentStream, ContentType contentType) :
+ public LinkedResource(Stream contentStream, ContentType? contentType) :
base(contentStream, contentType)
{ }
- public Uri ContentLink
+ public Uri? ContentLink
{
get
{
return a;
}
- public static LinkedResource CreateLinkedResourceFromString(string content, Encoding contentEncoding, string mediaType)
+ public static LinkedResource CreateLinkedResourceFromString(string content, Encoding? contentEncoding, string? mediaType)
{
LinkedResource a = new LinkedResource();
a.SetContentFromString(content, contentEncoding, mediaType);
return a;
}
- public static LinkedResource CreateLinkedResourceFromString(string content, ContentType contentType)
+ public static LinkedResource CreateLinkedResourceFromString(string content, ContentType? contentType)
{
LinkedResource a = new LinkedResource();
a.SetContentFromString(content, contentType);
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net.Mime;
using System.Text;
// For internal use only by MailAddressParser.
// The components were already validated before this is called.
- internal MailAddress(string displayName, string userName, string domain, Encoding displayNameEncoding)
+ internal MailAddress(string displayName, string userName, string domain, Encoding? displayNameEncoding)
{
_host = domain;
_userName = userName;
"displayName was null in internal constructor");
}
- public MailAddress(string address) : this(address, null, (Encoding)null)
+ public MailAddress(string address) : this(address, null, (Encoding?)null)
{
}
- public MailAddress(string address, string displayName) : this(address, displayName, (Encoding)null)
+ public MailAddress(string address, string? displayName) : this(address, displayName, (Encoding?)null)
{
}
// field. The display name does not need to be pre-encoded if a 'displayNameEncoding' is provided.
//
// A FormatException will be thrown if any of the components in 'address' are invalid.
- public MailAddress(string address, string displayName, Encoding displayNameEncoding)
+ public MailAddress(string address, string? displayName, Encoding? displayNameEncoding)
{
bool parseSuccess = TryParse(address, displayName, displayNameEncoding,
out (string displayName, string user, string host, Encoding displayNameEncoding) parsedData,
/// <param name="address">A <see cref="string"/> that contains an email address.</param>
/// <param name="result">When this method returns, contains the <see cref="MailAddress"/> instance if address parsing succeed</param>
/// <returns>A <see cref="bool"/> value that is true if the <see cref="MailAddress"/> was successfully created; otherwise, false.</returns>
- public static bool TryCreate(string address, out MailAddress result) => TryCreate(address, displayName: null, out result);
+ public static bool TryCreate(string address, [NotNullWhen(true)] out MailAddress? result) => TryCreate(address, displayName: null, out result);
/// <summary>
/// Create a new <see cref="MailAddress"/>. Does not throw an exception if the MailAddress cannot be created.
/// <param name="displayName">A <see cref="string"/> that contains the display name associated with address. This parameter can be null.</param>
/// <param name="result">When this method returns, contains the <see cref="MailAddress"/> instance if address parsing succeed</param>
/// <returns>A <see cref="bool"/> value that is true if the <see cref="MailAddress"/> was successfully created; otherwise, false.</returns>
- public static bool TryCreate(string address, string displayName, out MailAddress result) => TryCreate(address, displayName, displayNameEncoding: null, out result);
+ public static bool TryCreate(string address, string? displayName, [NotNullWhen(true)] out MailAddress? result) => TryCreate(address, displayName, displayNameEncoding: null, out result);
/// <summary>
/// Create a new <see cref="MailAddress"/>. Does not throw an exception if the MailAddress cannot be created.
/// <param name="displayNameEncoding">The <see cref="Encoding"/> that defines the character set used for displayName</param>
/// <param name="result">When this method returns, contains the <see cref="MailAddress"/> instance if address parsing succeed</param>
/// <returns>A <see cref="bool"/> value that is true if the <see cref="MailAddress"/> was successfully created; otherwise, false.</returns>
- public static bool TryCreate(string address, string displayName, Encoding displayNameEncoding, out MailAddress result)
+ public static bool TryCreate(string address, string? displayName, Encoding? displayNameEncoding, [NotNullWhen(true)] out MailAddress? result)
{
if (TryParse(address, displayName, displayNameEncoding,
out (string displayName, string user, string host, Encoding displayNameEncoding) parsed,
}
}
- private static bool TryParse(string address, string displayName, Encoding displayNameEncoding, out (string displayName, string user, string host, Encoding displayNameEncoding) parsedData, bool throwExceptionIfFail)
+ private static bool TryParse(string address, string? displayName, Encoding? displayNameEncoding, out (string displayName, string user, string host, Encoding displayNameEncoding) parsedData, bool throwExceptionIfFail)
{
if (address == null)
{
}
}
- public override bool Equals(object value)
+ public override bool Equals(object? value)
{
if (value == null)
{
return headers;
}
- internal static string GetString(MailHeaderID id)
+ internal static string? GetString(MailHeaderID id)
{
switch (id)
{
using System;
using System.Collections.Specialized;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Mime;
using System.Text;
public class MailMessage : IDisposable
{
- private AlternateViewCollection _views;
- private AttachmentCollection _attachments;
- private AlternateView _bodyView = null;
- private string _body = string.Empty;
- private Encoding _bodyEncoding;
+ private AlternateViewCollection? _views;
+ private AttachmentCollection? _attachments;
+ private AlternateView? _bodyView;
+ private string? _body = string.Empty;
+ private Encoding? _bodyEncoding;
private TransferEncoding _bodyTransferEncoding = TransferEncoding.Unknown;
private bool _isBodyHtml = false;
private bool _disposed = false;
}
- public MailMessage(string from, string to, string subject, string body) : this(from, to)
+ public MailMessage(string from, string to, string? subject, string? body) : this(from, to)
{
Subject = subject;
Body = body;
_message = new Message(from, to);
}
-
- public MailAddress From
+ [DisallowNull]
+ public MailAddress? From
{
get
{
}
}
- public MailAddress Sender
+ [DisallowNull]
+ public MailAddress? Sender
{
get
{
}
[Obsolete("ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. https://go.microsoft.com/fwlink/?linkid=14202")]
- public MailAddress ReplyTo
+ public MailAddress? ReplyTo
{
get
{
}
}
+ [AllowNull]
public string Subject
{
get
}
}
- public Encoding SubjectEncoding
+ public Encoding? SubjectEncoding
{
get
{
}
}
- public Encoding HeadersEncoding
+ public Encoding? HeadersEncoding
{
get
{
}
}
+ [AllowNull]
public string Body
{
get
}
}
- public Encoding BodyEncoding
+ public Encoding? BodyEncoding
{
get
{
throw new ObjectDisposedException(GetType().FullName);
}
- if (_attachments == null)
- {
- _attachments = new AttachmentCollection();
- }
- return _attachments;
+ return _attachments ??= new AttachmentCollection();
}
}
public AlternateViewCollection AlternateViews
throw new ObjectDisposedException(GetType().FullName);
}
- if (_views == null)
- {
- _views = new AlternateViewCollection();
- }
-
- return _views;
+ return _views ??= new AlternateViewCollection();
}
}
{
// we should not unnecessarily use Multipart/Mixed
// When there is no attachement and all the alternative views are of "Alternative" types.
- MimeMultiPart part = null;
+ MimeMultiPart? part = null;
MimeMultiPart viewsPart = new MimeMultiPart(MimeMultiPartType.Alternative);
if (!string.IsNullOrEmpty(_body))
}
internal IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode,
- AsyncCallback callback, object state)
+ AsyncCallback? callback, object? state)
{
SetContent(allowUnicode);
return _message.BeginSend(writer, sendEnvelope, allowUnicode, callback, state);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics.CodeAnalysis;
using System.Net.Mime;
using System.Runtime.ExceptionServices;
using System.Text;
{
#region Fields
- private MailAddress _from;
- private MailAddress _sender;
- private MailAddressCollection _replyToList;
- private MailAddress _replyTo;
- private MailAddressCollection _to;
- private MailAddressCollection _cc;
- private MailAddressCollection _bcc;
- private MimeBasePart _content;
- private HeaderCollection _headers;
- private HeaderCollection _envelopeHeaders;
- private string _subject;
- private Encoding _subjectEncoding;
- private Encoding _headersEncoding;
+ private MailAddress? _from;
+ private MailAddress? _sender;
+ private MailAddressCollection? _replyToList;
+ private MailAddress? _replyTo;
+ private MailAddressCollection? _to;
+ private MailAddressCollection? _cc;
+ private MailAddressCollection? _bcc;
+ private MimeBasePart? _content;
+ private HeaderCollection? _headers;
+ private HeaderCollection? _envelopeHeaders;
+ private string? _subject;
+ private Encoding? _subjectEncoding;
+ private Encoding? _headersEncoding;
private MailPriority _priority = (MailPriority)(-1);
#endregion Fields
}
}
- internal MailAddress From
+ [DisallowNull]
+ internal MailAddress? From
{
get
{
}
- internal MailAddress Sender
+ internal MailAddress? Sender
{
get
{
}
- internal MailAddress ReplyTo
+ internal MailAddress? ReplyTo
{
get
{
}
}
- internal MailAddressCollection ReplyToList
- {
- get
- {
- if (_replyToList == null)
- _replyToList = new MailAddressCollection();
+ internal MailAddressCollection ReplyToList => _replyToList ??= new MailAddressCollection();
- return _replyToList;
- }
- }
+ internal MailAddressCollection To => _to ??= new MailAddressCollection();
- internal MailAddressCollection To
- {
- get
- {
- if (_to == null)
- _to = new MailAddressCollection();
+ internal MailAddressCollection Bcc => _bcc ??= new MailAddressCollection();
- return _to;
- }
- }
+ internal MailAddressCollection CC => _cc ??= new MailAddressCollection();
- internal MailAddressCollection Bcc
- {
- get
- {
- if (_bcc == null)
- _bcc = new MailAddressCollection();
- return _bcc;
- }
- }
-
- internal MailAddressCollection CC
- {
- get
- {
- if (_cc == null)
- _cc = new MailAddressCollection();
-
- return _cc;
- }
- }
-
-
- internal string Subject
+ internal string? Subject
{
get
{
}
set
{
- Encoding inputEncoding = null;
+ Encoding? inputEncoding = null;
try
{
// extract the encoding from =?encoding?BorQ?blablalba?=
}
}
- internal Encoding SubjectEncoding
+ internal Encoding? SubjectEncoding
{
get
{
}
}
- internal Encoding HeadersEncoding
+ internal Encoding? HeadersEncoding
{
get
{
}
}
-
- internal virtual MimeBasePart Content
+ [DisallowNull]
+ internal virtual MimeBasePart? Content
{
get
{
internal void EmptySendCallback(IAsyncResult result)
{
- Exception e = null;
+ Exception? e = null;
if (result.CompletedSynchronously)
{
return;
}
- EmptySendContext context = (EmptySendContext)result.AsyncState;
+ EmptySendContext context = (EmptySendContext)result.AsyncState!;
try
{
context._writer.EndGetContentStream(result).Close();
}
internal virtual IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode,
- AsyncCallback callback, object state)
+ AsyncCallback? callback, object? state)
{
PrepareHeaders(sendEnvelope, allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
}
else
{
- LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
+ LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
EncodeHeaders(EnvelopeHeaders, allowUnicode);
// Only add X-Sender header if it wasn't already set by the user
- string xSenderHeader = MailHeaderInfo.GetString(MailHeaderID.XSender);
+ string xSenderHeader = MailHeaderInfo.GetString(MailHeaderID.XSender)!;
if (!IsHeaderSet(xSenderHeader))
{
- MailAddress sender = Sender ?? From;
+ MailAddress sender = Sender ?? From!;
EnvelopeHeaders.InternalSet(xSenderHeader, sender.Encode(xSenderHeader.Length, allowUnicode));
}
- string headerName = MailHeaderInfo.GetString(MailHeaderID.XReceiver);
+ string headerName = MailHeaderInfo.GetString(MailHeaderID.XReceiver)!;
EnvelopeHeaders.Remove(headerName);
foreach (MailAddress address in To)
}
//ContentType is written directly to the stream so remove potential user duplicate
- Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType));
+ Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType)!);
Headers[MailHeaderInfo.GetString(MailHeaderID.MimeVersion)] = "1.0";
// add sender to headers first so that it is written first to allow the IIS smtp svc to
// send MAIL FROM with the sender if both sender and from are present
- headerName = MailHeaderInfo.GetString(MailHeaderID.Sender);
+ headerName = MailHeaderInfo.GetString(MailHeaderID.Sender)!;
if (Sender != null)
{
Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode));
Headers.Remove(headerName);
}
- headerName = MailHeaderInfo.GetString(MailHeaderID.From);
- Headers.InternalAdd(headerName, From.Encode(headerName.Length, allowUnicode));
+ headerName = MailHeaderInfo.GetString(MailHeaderID.From)!;
+ Headers.InternalAdd(headerName, From!.Encode(headerName.Length, allowUnicode));
- headerName = MailHeaderInfo.GetString(MailHeaderID.To);
+ headerName = MailHeaderInfo.GetString(MailHeaderID.To)!;
if (To.Count > 0)
{
Headers.InternalAdd(headerName, To.Encode(headerName.Length, allowUnicode));
Headers.Remove(headerName);
}
- headerName = MailHeaderInfo.GetString(MailHeaderID.Cc);
+ headerName = MailHeaderInfo.GetString(MailHeaderID.Cc)!;
if (CC.Count > 0)
{
Headers.InternalAdd(headerName, CC.Encode(headerName.Length, allowUnicode));
Headers.Remove(headerName);
}
- headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo);
+ headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo)!;
if (ReplyTo != null)
{
Headers.InternalAdd(headerName, ReplyTo.Encode(headerName.Length, allowUnicode));
Headers.Remove(headerName);
}
- Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc));
+ Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc)!);
if (_priority == MailPriority.High)
{
//if the priority was never set, allow the app to set the headers directly.
else if (((int)_priority) != -1)
{
- Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority));
- Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority));
- Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance));
+ Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority)!);
+ Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority)!);
+ Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance)!);
}
- Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date),
- MailBnfHelper.GetDateTimeString(DateTime.Now, null));
+ Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date)!,
+ MailBnfHelper.GetDateTimeString(DateTime.Now, null)!);
- headerName = MailHeaderInfo.GetString(MailHeaderID.Subject);
+ headerName = MailHeaderInfo.GetString(MailHeaderID.Subject)!;
if (!string.IsNullOrEmpty(_subject))
{
if (allowUnicode)
Headers.Remove(headerName);
}
- EncodeHeaders(_headers, allowUnicode);
+ EncodeHeaders(_headers!, allowUnicode);
}
internal void EncodeHeaders(HeaderCollection headers, bool allowUnicode)
{
- if (_headersEncoding == null)
- {
- _headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
- }
+ _headersEncoding ??= Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
System.Diagnostics.Debug.Assert(_headersEncoding != null);
for (int i = 0; i < headers.Count; i++)
{
- string headerName = headers.GetKey(i);
+ string headerName = headers.GetKey(i)!;
//certain well-known values are encoded by PrepareHeaders and PrepareEnvelopeHeaders
//so we can ignore them because either we encoded them already or there is no
continue;
}
- string[] values = headers.GetValues(headerName);
+ string[] values = headers.GetValues(headerName)!;
string encodedValue = string.Empty;
for (int j = 0; j < values.Length; j++)
{
}
}
- private bool IsHeaderSet(string headerName)
+ private bool IsHeaderSet(string? headerName)
{
for (int i = 0; i < Headers.Count; i++)
{
if (headers == null)
throw new ArgumentNullException(nameof(headers));
- foreach (string key in headers)
+ foreach (string? key in headers) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
{
- string[] values = headers.GetValues(key);
+ string[] values = headers!.GetValues(key)!;
foreach (string value in values)
- WriteHeader(key, value, allowUnicode);
+ WriteHeader(key!, value, allowUnicode);
}
}
/// </summary>
/// <param name="sender">Sender of the close event</param>
/// <param name="args">Event args (not used)</param>
- protected override void OnClose(object sender, EventArgs args)
+ protected override void OnClose(object? sender, EventArgs args)
{
Diagnostics.Debug.Assert(_contentStream == sender);
_contentStream.Flush();
- _contentStream = null;
+ _contentStream = null!;
}
}
}
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net.NetworkInformation;
public class SmtpClient : IDisposable
{
- private string _host;
+ private string? _host;
private int _port;
private int _timeout = 100000;
private bool _inCall;
private bool _cancelled;
private bool _timedOut;
- private string _targetName = null;
+ private string? _targetName;
private SmtpDeliveryMethod _deliveryMethod = SmtpDeliveryMethod.Network;
private SmtpDeliveryFormat _deliveryFormat = SmtpDeliveryFormat.SevenBit; // Non-EAI default
- private string _pickupDirectoryLocation = null;
- private SmtpTransport _transport;
- private MailMessage _message; //required to prevent premature finalization
- private MailWriter _writer;
- private MailAddressCollection _recipients;
- private SendOrPostCallback _onSendCompletedDelegate;
- private Timer _timer;
- private ContextAwareResult _operationCompletedResult = null;
- private AsyncOperation _asyncOp = null;
+ private string? _pickupDirectoryLocation;
+ private SmtpTransport _transport = null!; // initialized by helper called from ctor
+ private MailMessage? _message; //required to prevent premature finalization
+ private MailWriter? _writer;
+ private MailAddressCollection? _recipients;
+ private SendOrPostCallback _onSendCompletedDelegate = null!; // initialized by helper called from ctor
+ private Timer? _timer;
+ private ContextAwareResult? _operationCompletedResult;
+ private AsyncOperation? _asyncOp;
private static readonly AsyncCallback s_contextSafeCompleteCallback = new AsyncCallback(ContextSafeCompleteCallback);
private const int DefaultPort = 25;
- internal string clientDomain = null;
- private bool _disposed = false;
- private ServicePoint _servicePoint;
+ internal string _clientDomain = null!; // initialized by helper called from ctor
+ private bool _disposed;
+ private ServicePoint? _servicePoint;
// (async only) For when only some recipients fail. We still send the e-mail to the others.
- private SmtpFailedRecipientException _failedRecipientException;
+ private SmtpFailedRecipientException? _failedRecipientException;
// ports above this limit are invalid
private const int MaxPortValue = 65535;
- public event SendCompletedEventHandler SendCompleted;
+ public event SendCompletedEventHandler? SendCompleted;
private bool _useDefaultCredentials;
- private ICredentialsByHost _customCredentials;
+ private ICredentialsByHost? _customCredentials;
public SmtpClient()
{
}
}
- public SmtpClient(string host)
+ public SmtpClient(string? host)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host);
try
}
}
- public SmtpClient(string host, int port)
+ public SmtpClient(string? host, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host, port);
try
if (_targetName == null)
_targetName = "SMTPSVC/" + _host;
- if (clientDomain == null)
+ if (_clientDomain == null)
{
// We use the local host name as the default client domain
// for the client's EHLO or HELO message. This limits the
sb.Append(ch);
}
if (sb.Length > 0)
- clientDomain = sb.ToString();
+ _clientDomain = sb.ToString();
else
- clientDomain = "LocalHost";
+ _clientDomain = "LocalHost";
}
}
-
- public string Host
+ [DisallowNull]
+ public string? Host
{
get
{
}
}
- public ICredentialsByHost Credentials
+ public ICredentialsByHost? Credentials
{
get
{
get
{
CheckHostAndPort();
- if (_servicePoint == null)
- {
- // This differs from desktop, where it uses an internal overload of FindServicePoint that just
- // takes a string host and an int port, bypassing the need for a Uri. We workaround that here by
- // creating an http Uri, simply for the purposes of getting an appropriate ServicePoint instance.
- // This has some subtle impact on behavior, e.g. the returned ServicePoint's Address property will
- // be usable, whereas in .NET Framework it throws an exception that "This property is not supported for
- // protocols that do not use URI."
- _servicePoint = ServicePointManager.FindServicePoint(new Uri("mailto:" + _host + ":" + _port));
- }
- return _servicePoint;
+
+ // This differs from desktop, where it uses an internal overload of FindServicePoint that just
+ // takes a string host and an int port, bypassing the need for a Uri. We workaround that here by
+ // creating an http Uri, simply for the purposes of getting an appropriate ServicePoint instance.
+ // This has some subtle impact on behavior, e.g. the returned ServicePoint's Address property will
+ // be usable, whereas in .NET Framework it throws an exception that "This property is not supported for
+ // protocols that do not use URI."
+ return _servicePoint ??= ServicePointManager.FindServicePoint(new Uri("mailto:" + _host + ":" + _port));
}
}
}
}
- public string PickupDirectoryLocation
+ public string? PickupDirectoryLocation
{
get
{
}
}
- public string TargetName
+ public string? TargetName
{
get { return _targetName; }
set { _targetName = value; }
}
}
- internal MailWriter GetFileMailWriter(string pickupDirectory)
+ internal MailWriter GetFileMailWriter(string? pickupDirectory)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"{nameof(pickupDirectory)}={pickupDirectory}");
SendCompleted?.Invoke(this, e);
}
- private void SendCompletedWaitCallback(object operationState)
+ private void SendCompletedWaitCallback(object? operationState)
{
- OnSendCompleted((AsyncCompletedEventArgs)operationState);
+ OnSendCompleted((AsyncCompletedEventArgs)operationState!);
}
- public void Send(string from, string recipients, string subject, string body)
+ public void Send(string from, string recipients, string? subject, string? body)
{
if (_disposed)
{
NetEventSource.Associate(this, message);
}
- SmtpFailedRecipientException recipientException = null;
+ SmtpFailedRecipientException? recipientException = null;
if (InCall)
{
_timedOut = false;
_timer = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
bool allowUnicode = false;
- string pickupDirectory = PickupDirectoryLocation;
+ string? pickupDirectory = PickupDirectoryLocation;
MailWriter writer;
switch (DeliveryMethod)
}
}
- public void SendAsync(string from, string recipients, string subject, string body, object userToken)
+ public void SendAsync(string from, string recipients, string? subject, string? body, object? userToken)
{
if (_disposed)
{
SendAsync(new MailMessage(from, recipients, subject, body), userToken);
}
- public void SendAsync(MailMessage message, object userToken)
+ public void SendAsync(MailMessage message, object? userToken)
{
if (_disposed)
{
InCall = true;
_cancelled = false;
_message = message;
- string pickupDirectory = PickupDirectoryLocation;
+ string? pickupDirectory = PickupDirectoryLocation;
- CredentialCache cache;
+ CredentialCache? cache;
// Skip token capturing if no credentials are used or they don't include a default one.
// Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
_transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));
lock (_operationCompletedResult.StartPostingAsyncOp())
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
- _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host, Port);
+ _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host!, Port);
_operationCompletedResult.FinishPostingAsyncOp();
}
break;
private bool IsSystemNetworkCredentialInCache(CredentialCache cache)
{
// Check if SystemNetworkCredential is in given cache.
- foreach (NetworkCredential credential in cache)
+ foreach (NetworkCredential? credential in cache) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
{
if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
{
//************* Task-based async public methods *************************
- public Task SendMailAsync(string from, string recipients, string subject, string body)
+ public Task SendMailAsync(string from, string recipients, string? subject, string? body)
{
var message = new MailMessage(from, recipients, subject, body);
return SendMailAsync(message, cancellationToken: default);
return SendMailAsync(message, cancellationToken: default);
}
- public Task SendMailAsync(string from, string recipients, string subject, string body, CancellationToken cancellationToken)
+ public Task SendMailAsync(string from, string recipients, string? subject, string? body, CancellationToken cancellationToken)
{
var message = new MailMessage(from, recipients, subject, body);
return SendMailAsync(message, cancellationToken);
}
// Create a TaskCompletionSource to represent the operation
- var tcs = new TaskCompletionSource<object>();
+ var tcs = new TaskCompletionSource<object?>();
CancellationTokenRegistration ctr = default;
int state = 0;
// Register a handler that will transfer completion results to the TCS Task
- SendCompletedEventHandler handler = null;
+ SendCompletedEventHandler? handler = null;
handler = (sender, e) =>
{
if (e.UserState == tcs)
ctr = cancellationToken.Register(s =>
{
- ((SmtpClient)s).SendAsyncCancel();
+ ((SmtpClient)s!).SendAsyncCancel();
}, this);
if (Interlocked.Exchange(ref state, 1) != 0)
}
}
- private void TimeOutCallback(object state)
+ private void TimeOutCallback(object? state)
{
if (!_timedOut)
{
}
}
- private void Complete(Exception exception, IAsyncResult result)
+ private void Complete(Exception? exception, IAsyncResult result)
{
- ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState;
+ ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState!;
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
private static void ContextSafeCompleteCallback(IAsyncResult ar)
{
ContextAwareResult result = (ContextAwareResult)ar;
- SmtpClient client = (SmtpClient)ar.AsyncState;
- Exception exception = result.Result as Exception;
- AsyncOperation asyncOp = client._asyncOp;
+ SmtpClient client = (SmtpClient)ar.AsyncState!;
+ Exception? exception = result.Result as Exception;
+ AsyncOperation asyncOp = client._asyncOp!;
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(exception, client._cancelled, asyncOp.UserSuppliedState);
client.InCall = false;
client._failedRecipientException = null; // Reset before the next send.
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
- _message.EndSend(result);
+ _message!.EndSend(result);
// If some recipients failed but not others, throw AFTER sending the message.
Complete(_failedRecipientException, result);
}
}
else
{
- _message.BeginSend(_writer, DeliveryMethod != SmtpDeliveryMethod.Network,
- IsUnicodeSupported(), new AsyncCallback(SendMessageCallback), result.AsyncState);
+ _message!.BeginSend(_writer, DeliveryMethod != SmtpDeliveryMethod.Network,
+ IsUnicodeSupported(), new AsyncCallback(SendMessageCallback), result.AsyncState!);
}
}
catch (Exception e)
{
// Detected durring Begin/EndGetConnection, restrictable using DeliveryFormat
bool allowUnicode = IsUnicodeSupported();
- ValidateUnicodeRequirement(_message, _recipients, allowUnicode);
- _transport.BeginSendMail(_message.Sender ?? _message.From, _recipients,
+ ValidateUnicodeRequirement(_message!, _recipients!, allowUnicode);
+ _transport.BeginSendMail(_message!.Sender ?? _message.From!, _recipients!,
_message.BuildDeliveryStatusNotificationString(), allowUnicode,
- new AsyncCallback(SendMailCallback), result.AsyncState);
+ new AsyncCallback(SendMailCallback), result.AsyncState!);
}
}
catch (Exception e)
{
address.GetSmtpAddress(allowUnicode);
}
- if (message.Sender != null)
- {
- message.Sender.GetSmtpAddress(allowUnicode);
- }
- message.From.GetSmtpAddress(allowUnicode);
+
+ message.Sender?.GetSmtpAddress(allowUnicode);
+ message.From!.GetSmtpAddress(allowUnicode);
}
private void GetConnection()
{
if (!_transport.IsConnected)
{
- _transport.GetConnection(_host, _port);
+ _transport.GetConnection(_host!, _port);
}
}
private static readonly AsyncCallback s_onReadLine = new AsyncCallback(OnReadLine);
private static readonly AsyncCallback s_onWrite = new AsyncCallback(OnWrite);
- internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
+ internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callback, object? state)
{
MultiAsyncResult multiResult = new MultiAsyncResult(conn, callback, state);
multiResult.Enter();
conn.EndFlush(writeResult);
multiResult.Leave();
}
- SmtpReplyReader reader = conn.Reader.GetNextReplyReader();
+ SmtpReplyReader reader = conn.Reader!.GetNextReplyReader();
multiResult.Enter();
//this actually does a read on the stream.
internal static object EndSend(IAsyncResult result, out string response)
{
- object commandResult = MultiAsyncResult.End(result);
+ object commandResult = MultiAsyncResult.End(result)!;
if (commandResult is Exception e)
{
ExceptionDispatchInfo.Throw(e);
{
if (!result.CompletedSynchronously)
{
- MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+ MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
try
{
SmtpConnection conn = (SmtpConnection)multiResult.Context;
- LineInfo info = conn.Reader.CurrentReader.EndReadLine(result);
+ LineInfo info = conn.Reader!.CurrentReader!.EndReadLine(result);
if (!(multiResult.Result is Exception))
multiResult.Result = info;
multiResult.Leave();
{
if (!result.CompletedSynchronously)
{
- MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+ MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
try
{
SmtpConnection conn = (SmtpConnection)multiResult.Context;
internal static SmtpStatusCode Send(SmtpConnection conn, out string response)
{
conn.Flush();
- SmtpReplyReader reader = conn.Reader.GetNextReplyReader();
+ SmtpReplyReader reader = conn.Reader!.GetNextReplyReader();
LineInfo info = reader.ReadLine();
response = info.Line;
reader.Close();
private static readonly AsyncCallback s_onReadLines = new AsyncCallback(OnReadLines);
private static readonly AsyncCallback s_onWrite = new AsyncCallback(OnWrite);
- internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
+ internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callback, object? state)
{
MultiAsyncResult multiResult = new MultiAsyncResult(conn, callback, state);
multiResult.Enter();
conn.EndFlush(writeResult);
multiResult.Leave();
}
- SmtpReplyReader reader = conn.Reader.GetNextReplyReader();
+ SmtpReplyReader reader = conn.Reader!.GetNextReplyReader();
multiResult.Enter();
IAsyncResult readLinesResult = reader.BeginReadLines(s_onReadLines, multiResult);
if (readLinesResult.CompletedSynchronously)
{
- LineInfo[] lines = conn.Reader.CurrentReader.EndReadLines(readLinesResult);
+ LineInfo[] lines = conn.Reader.CurrentReader!.EndReadLines(readLinesResult);
if (!(multiResult.Result is Exception))
multiResult.Result = lines;
multiResult.Leave();
internal static LineInfo[] EndSend(IAsyncResult result)
{
- object commandResult = MultiAsyncResult.End(result);
+ object commandResult = MultiAsyncResult.End(result)!;
if (commandResult is Exception e)
{
ExceptionDispatchInfo.Throw(e);
{
if (!result.CompletedSynchronously)
{
- MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+ MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
try
{
SmtpConnection conn = (SmtpConnection)multiResult.Context;
- LineInfo[] lines = conn.Reader.CurrentReader.EndReadLines(result);
+ LineInfo[] lines = conn.Reader!.CurrentReader!.EndReadLines(result);
if (!(multiResult.Result is Exception))
multiResult.Result = lines;
multiResult.Leave();
{
if (!result.CompletedSynchronously)
{
- MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+ MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
try
{
SmtpConnection conn = (SmtpConnection)multiResult.Context;
internal static LineInfo[] Send(SmtpConnection conn)
{
conn.Flush();
- return conn.Reader.GetNextReplyReader().ReadLines();
+ return conn.Reader!.GetNextReplyReader().ReadLines();
}
}
internal static class AuthCommand
{
- internal static IAsyncResult BeginSend(SmtpConnection conn, string type, string message, AsyncCallback callback, object state)
+ internal static IAsyncResult BeginSend(SmtpConnection conn, string type, string message, AsyncCallback? callback, object? state)
{
PrepareCommand(conn, type, message);
return ReadLinesCommand.BeginSend(conn, callback, state);
}
- internal static IAsyncResult BeginSend(SmtpConnection conn, string message, AsyncCallback callback, object state)
+ internal static IAsyncResult BeginSend(SmtpConnection conn, string? message, AsyncCallback? callback, object? state)
{
PrepareCommand(conn, message);
return ReadLinesCommand.BeginSend(conn, callback, state);
conn.BufferBuilder.Append(SmtpCommands.CRLF);
}
- private static void PrepareCommand(SmtpConnection conn, string message)
+ private static void PrepareCommand(SmtpConnection conn, string? message)
{
conn.BufferBuilder.Append(message);
conn.BufferBuilder.Append(SmtpCommands.CRLF);
return CheckResponse(ReadLinesCommand.Send(conn));
}
- internal static LineInfo Send(SmtpConnection conn, string message)
+ internal static LineInfo Send(SmtpConnection conn, string? message)
{
PrepareCommand(conn, message);
return CheckResponse(ReadLinesCommand.Send(conn));
internal static class DataCommand
{
- internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
+ internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callback, object? state)
{
PrepareCommand(conn);
return CheckCommand.BeginSend(conn, callback, state);
internal static class EHelloCommand
{
- internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback callback, object state)
+ internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback? callback, object? state)
{
PrepareCommand(conn, domain);
return ReadLinesCommand.BeginSend(conn, callback, state);
internal static class HelloCommand
{
- internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback callback, object state)
+ internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback? callback, object? state)
{
PrepareCommand(conn, domain);
return CheckCommand.BeginSend(conn, callback, state);
internal static class StartTlsCommand
{
- internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
+ internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callback, object? state)
{
PrepareCommand(conn);
return CheckCommand.BeginSend(conn, callback, state);
internal static class MailCommand
{
internal static IAsyncResult BeginSend(SmtpConnection conn, byte[] command, MailAddress from,
- bool allowUnicode, AsyncCallback callback, object state)
+ bool allowUnicode, AsyncCallback? callback, object? state)
{
PrepareCommand(conn, command, from, allowUnicode);
return CheckCommand.BeginSend(conn, callback, state);
internal static class RecipientCommand
{
- internal static IAsyncResult BeginSend(SmtpConnection conn, string to, AsyncCallback callback, object state)
+ internal static IAsyncResult BeginSend(SmtpConnection conn, string to, AsyncCallback? callback, object? state)
{
PrepareCommand(conn, to);
return CheckCommand.BeginSend(conn, callback, state);
private bool _isConnected;
private bool _isClosed;
private bool _isStreamOpen;
- private readonly EventHandler _onCloseHandler;
- internal SmtpTransport _parent;
- private readonly SmtpClient _client;
- private NetworkStream _networkStream;
- internal TcpClient _tcpClient;
- internal string _host = null;
+ private readonly EventHandler? _onCloseHandler;
+ internal SmtpTransport? _parent;
+ private readonly SmtpClient? _client;
+ private NetworkStream? _networkStream;
+ internal TcpClient? _tcpClient;
internal int _port = 0;
- private SmtpReplyReaderFactory _responseReader;
+ private SmtpReplyReaderFactory? _responseReader;
- private readonly ICredentialsByHost _credentials;
- private string[] _extensions;
- private readonly ChannelBinding _channelBindingToken = null;
+ private readonly ICredentialsByHost? _credentials;
+ private string[]? _extensions;
private bool _enableSsl;
- private X509CertificateCollection _clientCertificates;
+ private X509CertificateCollection? _clientCertificates;
- internal SmtpConnection(SmtpTransport parent, SmtpClient client, ICredentialsByHost credentials, ISmtpAuthenticationModule[] authenticationModules)
+ internal SmtpConnection(SmtpTransport parent, SmtpClient client, ICredentialsByHost? credentials, ISmtpAuthenticationModule[] authenticationModules)
{
_client = client;
_credentials = credentials;
internal bool IsStreamOpen => _isStreamOpen;
- internal SmtpReplyReaderFactory Reader => _responseReader;
+ internal SmtpReplyReaderFactory? Reader => _responseReader;
internal bool EnableSsl
{
}
}
- internal X509CertificateCollection ClientCertificates
+ internal X509CertificateCollection? ClientCertificates
{
get
{
internal void InitializeConnection(string host, int port)
{
- _tcpClient.Connect(host, port);
+ _tcpClient!.Connect(host, port);
_networkStream = _tcpClient.GetStream();
}
- internal IAsyncResult BeginInitializeConnection(string host, int port, AsyncCallback callback, object state)
+ internal IAsyncResult BeginInitializeConnection(string host, int port, AsyncCallback? callback, object? state)
{
- return _tcpClient.BeginConnect(host, port, callback, state);
+ return _tcpClient!.BeginConnect(host, port, callback, state);
}
internal void EndInitializeConnection(IAsyncResult result)
{
- _tcpClient.EndConnect(result);
+ _tcpClient!.EndConnect(result);
_networkStream = _tcpClient.GetStream();
}
- internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
+ internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback? callback, object? state, string host, int port)
{
ConnectAndHandshakeAsyncResult result = new ConnectAndHandshakeAsyncResult(this, host, port, outerResult, callback, state);
result.GetConnection();
return result;
}
- internal IAsyncResult BeginFlush(AsyncCallback callback, object state)
+ internal IAsyncResult BeginFlush(AsyncCallback? callback, object? state)
{
- return _networkStream.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, callback, state);
+ return _networkStream!.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, callback, state);
}
internal void EndFlush(IAsyncResult result)
{
- _networkStream.EndWrite(result);
+ _networkStream!.EndWrite(result);
_bufferBuilder.Reset();
}
internal void Flush()
{
- _networkStream.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length);
+ _networkStream!.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length);
_bufferBuilder.Reset();
}
finally
{
//free cbt buffer
- _channelBindingToken?.Close();
_networkStream?.Close();
_tcpClient.Dispose();
}
}
InitializeConnection(host, port);
- _responseReader = new SmtpReplyReaderFactory(_networkStream);
+ _responseReader = new SmtpReplyReaderFactory(_networkStream!);
LineInfo info = _responseReader.GetNextReplyReader().ReadLine();
try
{
- _extensions = EHelloCommand.Send(this, _client.clientDomain);
+ _extensions = EHelloCommand.Send(this, _client!._clientDomain);
ParseExtensions(_extensions);
}
catch (SmtpException e)
throw;
}
- HelloCommand.Send(this, _client.clientDomain);
+ HelloCommand.Send(this, _client!._clientDomain);
//if ehello isn't supported, assume basic login
_supportedAuth = SupportedAuth.Login;
}
}
StartTlsCommand.Send(this);
- TlsStream tlsStream = new TlsStream(_networkStream, _tcpClient.Client, host, _clientCertificates);
+ TlsStream tlsStream = new TlsStream(_networkStream!, _tcpClient!.Client, host, _clientCertificates);
tlsStream.AuthenticateAsClient();
_networkStream = tlsStream;
_responseReader = new SmtpReplyReaderFactory(_networkStream);
// According to RFC 3207: The client SHOULD send an EHLO command
// as the first command after a successful TLS negotiation.
- _extensions = EHelloCommand.Send(this, _client.clientDomain);
+ _extensions = EHelloCommand.Send(this, _client._clientDomain);
ParseExtensions(_extensions);
}
continue;
}
- NetworkCredential credential = _credentials.GetCredential(host, port, _authenticationModules[i].AuthenticationType);
+ NetworkCredential? credential = _credentials.GetCredential(host, port, _authenticationModules[i].AuthenticationType);
if (credential == null)
continue;
- Authorization auth = SetContextAndTryAuthenticate(_authenticationModules[i], credential, null);
+ Authorization? auth = SetContextAndTryAuthenticate(_authenticationModules[i], credential, null);
if (auth != null && auth.Message != null)
{
while ((int)info.StatusCode == 334)
{
- auth = _authenticationModules[i].Authenticate(info.Line, null, this, _client.TargetName, _channelBindingToken);
+ auth = _authenticationModules[i].Authenticate(info.Line, null, this, _client.TargetName, null);
if (auth == null)
{
throw new SmtpException(SR.SmtpAuthenticationFailed);
_isConnected = true;
}
- private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context)
+ private Authorization? SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential? credential, ContextAwareResult? context)
{
// We may need to restore user thread token here
if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
try
{
- ExecutionContext x = context == null ? null : context.ContextCopy;
+ ExecutionContext? x = context == null ? null : context.ContextCopy;
if (x != null)
{
AuthenticateCallbackContext authenticationContext =
- new AuthenticateCallbackContext(this, module, credential, _client.TargetName, _channelBindingToken);
+ new AuthenticateCallbackContext(this, module, credential, _client!.TargetName, null);
ExecutionContext.Run(x, s_AuthenticateCallback, authenticationContext);
return authenticationContext._result;
}
else
{
- return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken);
+ return module.Authenticate(null, credential, this, _client!.TargetName, null);
}
}
catch
}
}
- return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken);
+ return module.Authenticate(null, credential, this, _client!.TargetName, null);
}
- private static void AuthenticateCallback(object state)
+ private static void AuthenticateCallback(object? state)
{
- AuthenticateCallbackContext context = (AuthenticateCallbackContext)state;
+ AuthenticateCallbackContext context = (AuthenticateCallbackContext)state!;
context._result = context._module.Authenticate(null, context._credential, context._thisPtr, context._spn, context._token);
}
private class AuthenticateCallbackContext
{
- internal AuthenticateCallbackContext(SmtpConnection thisPtr, ISmtpAuthenticationModule module, NetworkCredential credential, string spn, ChannelBinding Token)
+ internal AuthenticateCallbackContext(SmtpConnection thisPtr, ISmtpAuthenticationModule module, NetworkCredential credential, string? spn, ChannelBinding? Token)
{
_thisPtr = thisPtr;
_module = module;
internal readonly SmtpConnection _thisPtr;
internal readonly ISmtpAuthenticationModule _module;
internal readonly NetworkCredential _credential;
- internal readonly string _spn;
- internal readonly ChannelBinding _token;
+ internal readonly string? _spn;
+ internal readonly ChannelBinding? _token;
- internal Authorization _result;
+ internal Authorization? _result;
}
internal void EndGetConnection(IAsyncResult result)
internal Stream GetClosableStream()
{
- ClosableStream cs = new ClosableStream(_networkStream, _onCloseHandler);
+ ClosableStream cs = new ClosableStream(_networkStream!, _onCloseHandler);
_isStreamOpen = true;
return cs;
}
- private void OnClose(object sender, EventArgs args)
+ private void OnClose(object? sender, EventArgs args)
{
_isStreamOpen = false;
private class ConnectAndHandshakeAsyncResult : LazyAsyncResult
{
- private string _authResponse;
+ private string? _authResponse;
private readonly SmtpConnection _connection;
private int _currentModule = -1;
private readonly int _port;
private readonly ContextAwareResult _outerResult;
- internal ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback callback, object state) :
+ internal ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback? callback, object? state) :
base(null, state, callback)
{
_connection = connection;
internal static void End(IAsyncResult result)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result;
- object connectResult = thisPtr.InternalWaitForCompletion();
+ object? connectResult = thisPtr.InternalWaitForCompletion();
if (connectResult is Exception e)
{
ExceptionDispatchInfo.Throw(e);
{
if (!result.CompletedSynchronously)
{
- ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+ ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
try
{
thisPtr._connection.EndInitializeConnection(result);
private void Handshake()
{
- _connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream);
+ _connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream!);
- SmtpReplyReader reader = _connection.Reader.GetNextReplyReader();
+ SmtpReplyReader reader = _connection.Reader!.GetNextReplyReader();
IAsyncResult result = reader.BeginReadLine(s_handshakeCallback, this);
if (!result.CompletedSynchronously)
{
{
if (!result.CompletedSynchronously)
{
- ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+ ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
try
{
try
{
- LineInfo info = thisPtr._connection.Reader.CurrentReader.EndReadLine(result);
+ LineInfo info = thisPtr._connection.Reader!.CurrentReader!.EndReadLine(result);
if (info.StatusCode != SmtpStatusCode.ServiceReady)
{
thisPtr.InvokeCallback(new SmtpException(info.StatusCode, info.Line, true));
private bool SendEHello()
{
- IAsyncResult result = EHelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendEHelloCallback, this);
+ IAsyncResult result = EHelloCommand.BeginSend(_connection, _connection._client!._clientDomain, s_sendEHelloCallback, this);
if (result.CompletedSynchronously)
{
_connection._extensions = EHelloCommand.EndSend(result);
{
if (!result.CompletedSynchronously)
{
- ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+ ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
try
{
try
private bool SendHello()
{
- IAsyncResult result = HelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendHelloCallback, this);
+ IAsyncResult result = HelloCommand.BeginSend(_connection, _connection._client!._clientDomain, s_sendHelloCallback, this);
//if ehello isn't supported, assume basic auth
if (result.CompletedSynchronously)
{
{
if (!result.CompletedSynchronously)
{
- ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+ ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
try
{
HelloCommand.EndSend(result);
{
if (!result.CompletedSynchronously)
{
- ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+ ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
try
{
StartTlsCommand.EndSend(result);
private bool TlsStreamAuthenticate()
{
- _connection._networkStream = new TlsStream(_connection._networkStream, _connection._tcpClient.Client, _host, _connection._clientCertificates);
- IAsyncResult result = (_connection._networkStream as TlsStream).BeginAuthenticateAsClient(TlsStreamAuthenticateCallback, this);
+ _connection._networkStream = new TlsStream(_connection._networkStream!, _connection._tcpClient!.Client, _host, _connection._clientCertificates);
+ IAsyncResult result = ((TlsStream)_connection._networkStream).BeginAuthenticateAsClient(TlsStreamAuthenticateCallback, this);
if (result.CompletedSynchronously)
{
- (_connection._networkStream as TlsStream).EndAuthenticateAsClient(result);
+ ((TlsStream)_connection._networkStream).EndAuthenticateAsClient(result);
_connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream);
SendEHello();
return true;
{
if (!result.CompletedSynchronously)
{
- ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+ ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
try
{
- (thisPtr._connection._networkStream as TlsStream).EndAuthenticateAsClient(result);
+ (thisPtr._connection._networkStream as TlsStream)!.EndAuthenticateAsClient(result);
thisPtr._connection._responseReader = new SmtpReplyReaderFactory(thisPtr._connection._networkStream);
thisPtr.SendEHello();
}
continue;
}
- NetworkCredential credential = _connection._credentials.GetCredential(_host, _port, module.AuthenticationType);
+ NetworkCredential? credential = _connection._credentials.GetCredential(_host, _port, module.AuthenticationType);
if (credential == null)
continue;
- Authorization auth = _connection.SetContextAndTryAuthenticate(module, credential, _outerResult);
+ Authorization? auth = _connection.SetContextAndTryAuthenticate(module, credential, _outerResult);
if (auth != null && auth.Message != null)
{
{
if (!result.CompletedSynchronously)
{
- ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+ ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
try
{
LineInfo info = AuthCommand.EndSend(result);
{
// We don't need credential on the continued auth assuming they were captured on the first call.
// That should always work, otherwise what if a new credential has been returned?
- Authorization auth = _connection._authenticationModules[_currentModule].Authenticate(_authResponse, null, _connection, _connection._client.TargetName, _connection._channelBindingToken);
+ Authorization? auth = _connection._authenticationModules[_currentModule].Authenticate(_authResponse, null, _connection, _connection._client!.TargetName, null);
if (auth == null)
{
throw new SmtpException(SR.SmtpAuthenticationFailed);
{
if (!result.CompletedSynchronously)
{
- ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+ ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
try
{
LineInfo info = AuthCommand.EndSend(result);
{
private SmtpStatusCode _statusCode = SmtpStatusCode.GeneralFailure;
- private static string GetMessageForStatus(SmtpStatusCode statusCode, string serverResponse)
+ private static string GetMessageForStatus(SmtpStatusCode statusCode, string? serverResponse)
{
return GetMessageForStatus(statusCode) + " " + SR.Format(SR.MailServerResponse, serverResponse);
}
_statusCode = statusCode;
}
- public SmtpException(SmtpStatusCode statusCode, string message) : base(message)
+ public SmtpException(SmtpStatusCode statusCode, string? message) : base(message)
{
_statusCode = statusCode;
}
{
}
- public SmtpException(string message) : base(message)
+ public SmtpException(string? message) : base(message)
{
}
- public SmtpException(string message, Exception innerException) : base(message, innerException)
+ public SmtpException(string? message, Exception? innerException) : base(message, innerException)
{
}
_statusCode = (SmtpStatusCode)serializationInfo.GetInt32("Status");
}
- internal SmtpException(SmtpStatusCode statusCode, string serverMessage, bool serverResponse) : base(GetMessageForStatus(statusCode, serverMessage))
+ internal SmtpException(SmtpStatusCode statusCode, string? serverMessage, bool serverResponse) : base(GetMessageForStatus(statusCode, serverMessage))
{
_statusCode = statusCode;
}
- internal SmtpException(string message, string serverResponse) : base(message + " " + SR.Format(SR.MailServerResponse, serverResponse))
+ internal SmtpException(string message, string? serverResponse) : base(message + " " + SR.Format(SR.MailServerResponse, serverResponse))
{
}
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class SmtpFailedRecipientException : SmtpException, ISerializable
{
- private readonly string _failedRecipient;
+ private readonly string? _failedRecipient;
internal bool fatal;
public SmtpFailedRecipientException() : base() { }
- public SmtpFailedRecipientException(string message) : base(message) { }
+ public SmtpFailedRecipientException(string? message) : base(message) { }
- public SmtpFailedRecipientException(string message, Exception innerException) : base(message, innerException) { }
+ public SmtpFailedRecipientException(string? message, Exception? innerException) : base(message, innerException) { }
protected SmtpFailedRecipientException(SerializationInfo info, StreamingContext context) : base(info, context)
{
_failedRecipient = info.GetString("failedRecipient");
}
- public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient) : base(statusCode)
+ public SmtpFailedRecipientException(SmtpStatusCode statusCode, string? failedRecipient) : base(statusCode)
{
_failedRecipient = failedRecipient;
}
- public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient, string serverResponse) : base(statusCode, serverResponse, true)
+ public SmtpFailedRecipientException(SmtpStatusCode statusCode, string? failedRecipient, string? serverResponse) : base(statusCode, serverResponse, true)
{
_failedRecipient = failedRecipient;
}
- public SmtpFailedRecipientException(string message, string failedRecipient, Exception innerException) : base(message, innerException)
+ public SmtpFailedRecipientException(string? message, string? failedRecipient, Exception? innerException) : base(message, innerException)
{
_failedRecipient = failedRecipient;
}
- public string FailedRecipient
+ public string? FailedRecipient
{
get
{
_innerExceptions = Array.Empty<SmtpFailedRecipientException>();
}
- public SmtpFailedRecipientsException(string message) : base(message)
+ public SmtpFailedRecipientsException(string? message) : base(message)
{
_innerExceptions = Array.Empty<SmtpFailedRecipientException>();
}
- public SmtpFailedRecipientsException(string message, Exception innerException) : base(message, innerException)
+ public SmtpFailedRecipientsException(string? message, Exception? innerException) : base(message, innerException)
{
- SmtpFailedRecipientException smtpException = innerException as SmtpFailedRecipientException;
+ SmtpFailedRecipientException? smtpException = innerException as SmtpFailedRecipientException;
_innerExceptions = smtpException == null ? Array.Empty<SmtpFailedRecipientException>() : new SmtpFailedRecipientException[] { smtpException };
}
protected SmtpFailedRecipientsException(SerializationInfo info, StreamingContext context) : base(info, context)
{
- _innerExceptions = (SmtpFailedRecipientException[])info.GetValue("innerExceptions", typeof(SmtpFailedRecipientException[]));
+ _innerExceptions = (SmtpFailedRecipientException[])info.GetValue("innerExceptions", typeof(SmtpFailedRecipientException[]))!;
}
- public SmtpFailedRecipientsException(string message, SmtpFailedRecipientException[] innerExceptions) :
+ public SmtpFailedRecipientsException(string? message, SmtpFailedRecipientException[] innerExceptions) :
base(message, innerExceptions != null && innerExceptions.Length > 0 ? innerExceptions[0].FailedRecipient : null,
innerExceptions != null && innerExceptions.Length > 0 ? innerExceptions[0] : null)
{
{
}
- public Authorization Authenticate(string challenge, NetworkCredential credential, object sessionCookie, string spn, ChannelBinding channelBindingToken)
+ public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
lock (_sessions)
{
- NetworkCredential cachedCredential;
+ NetworkCredential? cachedCredential;
if (!_sessions.TryGetValue(sessionCookie, out cachedCredential))
{
if (credential == null || ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
{
}
- public Authorization Authenticate(string challenge, NetworkCredential credential, object sessionCookie, string spn, ChannelBinding channelBindingToken)
+ public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, "Authenticate");
try
{
lock (_sessions)
{
- NTAuthentication clientContext;
+ NTAuthentication? clientContext;
if (!_sessions.TryGetValue(sessionCookie, out clientContext))
{
if (credential == null)
ContextFlagsPal.Connection | ContextFlagsPal.InitIntegrity, channelBindingToken);
}
- byte[] byteResp;
- string resp = null;
+ byte[]? byteResp;
+ string? resp = null;
if (!clientContext.IsCompleted)
{
// If auth is not yet completed keep producing
// challenge responses with GetOutgoingBlob
- byte[] decodedChallenge = null;
+ byte[]? decodedChallenge = null;
if (challenge != null)
{
decodedChallenge =
public void CloseContext(object sessionCookie)
{
- NTAuthentication clientContext = null;
+ NTAuthentication? clientContext = null;
lock (_sessions)
{
if (_sessions.TryGetValue(sessionCookie, out clientContext))
//
// Returns null for failure, Base64 encoded string on
// success.
- private string GetSecurityLayerOutgoingBlob(string challenge, NTAuthentication clientContext)
+ private string? GetSecurityLayerOutgoingBlob(string? challenge, NTAuthentication clientContext)
{
// must have a security layer challenge
// "authorization identity" is not supplied as it is unnecessary.
// let MakeSignature figure out length of output
- byte[] output = null;
+ byte[]? output = null;
try
{
len = clientContext.MakeSignature(input, 0, 4, ref output);
{
}
- public Authorization Authenticate(string challenge, NetworkCredential credential, object sessionCookie, string spn, ChannelBinding channelBindingToken)
+ public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, "Authenticate");
try
{
lock (_sessions)
{
- NTAuthentication clientContext;
+ NTAuthentication? clientContext;
if (!_sessions.TryGetValue(sessionCookie, out clientContext))
{
if (credential == null)
}
- string resp = clientContext.GetOutgoingBlob(challenge);
+ string? resp = clientContext.GetOutgoingBlob(challenge);
if (!clientContext.IsCompleted)
{
_reader = reader;
}
- internal IAsyncResult BeginReadLines(AsyncCallback callback, object state)
+ internal IAsyncResult BeginReadLines(AsyncCallback? callback, object? state)
{
return _reader.BeginReadLines(this, callback, state);
}
- internal IAsyncResult BeginReadLine(AsyncCallback callback, object state)
+ internal IAsyncResult BeginReadLine(AsyncCallback? callback, object? state)
{
return _reader.BeginReadLine(this, callback, state);
}
}
private readonly BufferedReadStream _bufferedStream;
- private byte[] _byteBuffer;
- private SmtpReplyReader _currentReader;
+ private byte[]? _byteBuffer;
+ private SmtpReplyReader? _currentReader;
private const int DefaultBufferSize = 256;
private ReadState _readState = ReadState.Status0;
private SmtpStatusCode _statusCode;
_bufferedStream = new BufferedReadStream(stream);
}
- internal SmtpReplyReader CurrentReader
+ internal SmtpReplyReader? CurrentReader
{
get
{
}
}
- internal IAsyncResult BeginReadLines(SmtpReplyReader caller, AsyncCallback callback, object state)
+ internal IAsyncResult BeginReadLines(SmtpReplyReader caller, AsyncCallback? callback, object? state)
{
ReadLinesAsyncResult result = new ReadLinesAsyncResult(this, callback, state);
result.Read(caller);
return result;
}
- internal IAsyncResult BeginReadLine(SmtpReplyReader caller, AsyncCallback callback, object state)
+ internal IAsyncResult BeginReadLine(SmtpReplyReader caller, AsyncCallback? callback, object? state)
{
ReadLinesAsyncResult result = new ReadLinesAsyncResult(this, callback, state, true);
result.Read(caller);
private class ReadLinesAsyncResult : LazyAsyncResult
{
- private StringBuilder _builder;
- private ArrayList _lines;
+ private StringBuilder? _builder;
+ private ArrayList? _lines;
private readonly SmtpReplyReaderFactory _parent;
private static readonly AsyncCallback s_readCallback = new AsyncCallback(ReadCallback);
private int _read;
private int _statusRead;
private readonly bool _oneLine;
- internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback callback, object state) : base(null, state, callback)
+ internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback? callback, object? state) : base(null, state, callback)
{
_parent = parent;
}
- internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback callback, object state, bool oneLine) : base(null, state, callback)
+ internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback? callback, object? state, bool oneLine) : base(null, state, callback)
{
_oneLine = oneLine;
_parent = parent;
{
ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result;
thisPtr.InternalWaitForCompletion();
- return (LineInfo[])thisPtr._lines.ToArray(typeof(LineInfo));
+ return (LineInfo[])thisPtr._lines!.ToArray(typeof(LineInfo));
}
private void Read()
{
do
{
- IAsyncResult result = _parent._bufferedStream.BeginRead(_parent._byteBuffer, 0, _parent._byteBuffer.Length, s_readCallback, this);
+ IAsyncResult result = _parent._bufferedStream.BeginRead(_parent._byteBuffer!, 0, _parent._byteBuffer!.Length, s_readCallback, this);
if (!result.CompletedSynchronously)
{
return;
{
if (!result.CompletedSynchronously)
{
- Exception exception = null;
- ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result.AsyncState;
+ Exception? exception = null;
+ ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result.AsyncState!;
try
{
thisPtr._read = thisPtr._parent._bufferedStream.EndRead(result);
for (int start = 0; start != _read;)
{
- int actual = _parent.ProcessRead(_parent._byteBuffer, start, _read - start, true);
+ int actual = _parent.ProcessRead(_parent._byteBuffer!, start, _read - start, true);
if (_statusRead < 4)
{
}
}
- _builder.Append(Encoding.UTF8.GetString(_parent._byteBuffer, start, actual));
+ _builder!.Append(Encoding.UTF8.GetString(_parent._byteBuffer!, start, actual));
start += actual;
if (_parent._readState == ReadState.Status0)
{
- _lines.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
+ _lines!.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
_builder = new StringBuilder();
_statusRead = 0;
if (_oneLine)
{
- _parent._bufferedStream.Push(_parent._byteBuffer, start, _read - start);
+ _parent._bufferedStream.Push(_parent._byteBuffer!, start, _read - start);
InvokeCallback();
return false;
}
}
else if (_parent._readState == ReadState.Done)
{
- _lines.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
- _parent._bufferedStream.Push(_parent._byteBuffer, start, _read - start);
+ _lines!.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
+ _parent._bufferedStream.Push(_parent._byteBuffer!, start, _read - start);
InvokeCallback();
return false;
}
internal const int DefaultPort = 25;
private readonly ISmtpAuthenticationModule[] _authenticationModules;
- private SmtpConnection _connection;
+ private SmtpConnection? _connection;
private readonly SmtpClient _client;
- private ICredentialsByHost _credentials;
+ private ICredentialsByHost? _credentials;
private readonly List<SmtpFailedRecipientException> _failedRecipientExceptions = new List<SmtpFailedRecipientException>();
private bool _identityRequired;
private bool _shouldAbort;
private bool _enableSsl = false;
- private X509CertificateCollection _clientCertificates = null;
+ private X509CertificateCollection? _clientCertificates;
internal SmtpTransport(SmtpClient client) : this(client, SmtpAuthenticationManager.GetModules())
{
_authenticationModules = authenticationModules;
}
- internal ICredentialsByHost Credentials
+ internal ICredentialsByHost? Credentials
{
get
{
}
}
- internal X509CertificateCollection ClientCertificates
- {
- get
- {
- if (_clientCertificates == null)
- {
- _clientCertificates = new X509CertificateCollection();
- }
- return _clientCertificates;
- }
- }
+ internal X509CertificateCollection ClientCertificates => _clientCertificates ??= new X509CertificateCollection();
internal bool ServerSupportsEai
{
finally { }
}
- internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
+ internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback? callback, object? state, string host, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
- IAsyncResult result = null;
+ IAsyncResult? result = null;
try
{
_connection = new SmtpConnection(this, _client, _credentials, _authenticationModules);
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
- _connection.EndGetConnection(result);
+ _connection!.EndGetConnection(result);
}
finally
{
}
internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients,
- string deliveryNotify, bool allowUnicode, AsyncCallback callback, object state)
+ string deliveryNotify, bool allowUnicode, AsyncCallback? callback, object? state)
{
if (sender == null)
{
throw new ArgumentNullException(nameof(recipients));
}
- SendMailAsyncResult result = new SendMailAsyncResult(_connection, sender, recipients,
- allowUnicode, _connection.DSNEnabled ? deliveryNotify : null,
+ SendMailAsyncResult result = new SendMailAsyncResult(_connection!, sender, recipients,
+ allowUnicode, _connection!.DSNEnabled ? deliveryNotify : null,
callback, state);
result.Send();
return result;
}
internal MailWriter SendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify,
- bool allowUnicode, out SmtpFailedRecipientException exception)
+ bool allowUnicode, out SmtpFailedRecipientException? exception)
{
if (sender == null)
{
throw new ArgumentNullException(nameof(recipients));
}
- MailCommand.Send(_connection, SmtpCommands.Mail, sender, allowUnicode);
+ MailCommand.Send(_connection!, SmtpCommands.Mail, sender, allowUnicode);
_failedRecipientExceptions.Clear();
exception = null;
foreach (MailAddress address in recipients)
{
string smtpAddress = address.GetSmtpAddress(allowUnicode);
- string to = smtpAddress + (_connection.DSNEnabled ? deliveryNotify : string.Empty);
+ string to = smtpAddress + (_connection!.DSNEnabled ? deliveryNotify : string.Empty);
if (!RecipientCommand.Send(_connection, to, out response))
{
_failedRecipientExceptions.Add(
- new SmtpFailedRecipientException(_connection.Reader.StatusCode, smtpAddress, response));
+ new SmtpFailedRecipientException(_connection.Reader!.StatusCode, smtpAddress, response));
}
}
}
}
- DataCommand.Send(_connection);
- return new MailWriter(_connection.GetClosableStream(), encodeForTransport: true);
+ DataCommand.Send(_connection!);
+ return new MailWriter(_connection!.GetClosableStream(), encodeForTransport: true);
}
}
{
private readonly SmtpConnection _connection;
private readonly MailAddress _from;
- private readonly string _deliveryNotify;
+ private readonly string? _deliveryNotify;
private static readonly AsyncCallback s_sendMailFromCompleted = new AsyncCallback(SendMailFromCompleted);
private static readonly AsyncCallback s_sendToCollectionCompleted = new AsyncCallback(SendToCollectionCompleted);
private static readonly AsyncCallback s_sendDataCompleted = new AsyncCallback(SendDataCompleted);
private readonly List<SmtpFailedRecipientException> _failedRecipientExceptions = new List<SmtpFailedRecipientException>();
- private Stream _stream;
+ private Stream? _stream;
private readonly MailAddressCollection _toCollection;
private int _toIndex;
private readonly bool _allowUnicode;
internal SendMailAsyncResult(SmtpConnection connection, MailAddress from, MailAddressCollection toCollection,
- bool allowUnicode, string deliveryNotify, AsyncCallback callback, object state)
+ bool allowUnicode, string? deliveryNotify, AsyncCallback? callback, object? state)
: base(null, state, callback)
{
_toCollection = toCollection;
internal static MailWriter End(IAsyncResult result)
{
SendMailAsyncResult thisPtr = (SendMailAsyncResult)result;
- object sendMailResult = thisPtr.InternalWaitForCompletion();
+ object? sendMailResult = thisPtr.InternalWaitForCompletion();
// Note the difference between the singular and plural FailedRecipient exceptions.
// Only fail immediately if we couldn't send to any recipients.
ExceptionDispatchInfo.Throw(e);
}
- return new MailWriter(thisPtr._stream, encodeForTransport: true);
+ return new MailWriter(thisPtr._stream!, encodeForTransport: true);
}
private void SendMailFrom()
{
{
if (!result.CompletedSynchronously)
{
- SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState;
+ SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState!;
try
{
MailCommand.EndSend(result);
string response;
if (!RecipientCommand.EndSend(result, out response))
{
- _failedRecipientExceptions.Add(new SmtpFailedRecipientException(_connection.Reader.StatusCode,
+ _failedRecipientExceptions.Add(new SmtpFailedRecipientException(_connection.Reader!.StatusCode,
_toCollection[_toIndex - 1].GetSmtpAddress(_allowUnicode), response));
}
}
{
if (!result.CompletedSynchronously)
{
- SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState;
+ SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState!;
try
{
string response;
if (!RecipientCommand.EndSend(result, out response))
{
thisPtr._failedRecipientExceptions.Add(
- new SmtpFailedRecipientException(thisPtr._connection.Reader.StatusCode,
+ new SmtpFailedRecipientException(thisPtr._connection.Reader!.StatusCode,
thisPtr._toCollection[thisPtr._toIndex - 1].GetSmtpAddress(thisPtr._allowUnicode),
response));
if (thisPtr._failedRecipientExceptions.Count == thisPtr._toCollection.Count)
{
- SmtpFailedRecipientException exception = null;
- if (thisPtr._toCollection.Count == 1)
- {
- exception = (SmtpFailedRecipientException)thisPtr._failedRecipientExceptions[0];
- }
- else
- {
- exception = new SmtpFailedRecipientsException(thisPtr._failedRecipientExceptions, true);
- }
+ SmtpFailedRecipientException exception = thisPtr._toCollection.Count == 1 ?
+ (SmtpFailedRecipientException)thisPtr._failedRecipientExceptions[0] :
+ new SmtpFailedRecipientsException(thisPtr._failedRecipientExceptions, true);
exception.fatal = true;
thisPtr.InvokeCallback(exception);
return;
{
if (!result.CompletedSynchronously)
{
- SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState;
+ SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState!;
try
{
DataCommand.EndSend(result);
}
// Return the list of non-terminal failures (some recipients failed but not others).
- internal SmtpFailedRecipientException GetFailedRecipientException()
+ internal SmtpFailedRecipientException? GetFailedRecipientException()
{
if (_failedRecipientExceptions.Count == 1)
{
private readonly EventHandler _onCloseHandler;
private readonly bool _shouldEncodeLeadingDots;
private readonly int _lineLength;
- protected Stream _contentStream;
+ protected Stream _contentStream = null!; // set to null on dispose
protected bool _isInContent;
protected BaseWriter(Stream stream, bool shouldEncodeLeadingDots)
internal Stream GetContentStream() => GetContentStream(null);
- private Stream GetContentStream(MultiAsyncResult multiResult)
+ private Stream GetContentStream(MultiAsyncResult? multiResult)
{
if (_isInContent)
{
return cs;
}
- internal IAsyncResult BeginGetContentStream(AsyncCallback callback, object state)
+ internal IAsyncResult BeginGetContentStream(AsyncCallback? callback, object? state)
{
MultiAsyncResult multiResult = new MultiAsyncResult(this, callback, state);
internal Stream EndGetContentStream(IAsyncResult result)
{
- object o = MultiAsyncResult.End(result);
+ object o = MultiAsyncResult.End(result)!;
if (o is Exception e)
{
ExceptionDispatchInfo.Throw(e);
#region Cleanup
- protected void Flush(MultiAsyncResult multiResult)
+ protected void Flush(MultiAsyncResult? multiResult)
{
if (_bufferBuilder.Length > 0)
{
{
if (!result.CompletedSynchronously)
{
- MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+ MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
BaseWriter thisPtr = (BaseWriter)multiResult.Context;
try
{
internal abstract void Close();
- protected abstract void OnClose(object sender, EventArgs args);
+ protected abstract void OnClose(object? sender, EventArgs args);
#endregion Cleanup
private const string FileNameKey = "filename";
private const string SizeKey = "size";
- private TrackingValidationObjectDictionary _parameters;
+ private TrackingValidationObjectDictionary? _parameters;
private string _disposition;
- private string _dispositionType;
+ private string _dispositionType = null!; // set by ctor or by helper called from ctor
private bool _isChanged;
private bool _isPersisted;
private static readonly TrackingValidationObjectDictionary.ValidateAndParseValue s_dateParser =
- new TrackingValidationObjectDictionary.ValidateAndParseValue(v => new SmtpDateTime(v.ToString()));
+ new TrackingValidationObjectDictionary.ValidateAndParseValue(v => new SmtpDateTime(v.ToString()!));
// this will throw a FormatException if the value supplied is not a valid SmtpDateTime
private static readonly TrackingValidationObjectDictionary.ValidateAndParseValue s_longParser =
internal DateTime GetDateParameter(string parameterName)
{
- SmtpDateTime dateValue = ((TrackingValidationObjectDictionary)Parameters).InternalGet(parameterName) as SmtpDateTime;
+ SmtpDateTime? dateValue = ((TrackingValidationObjectDictionary)Parameters).InternalGet(parameterName) as SmtpDateTime;
return dateValue == null ? DateTime.MinValue : dateValue.Date;
}
}
}
- public StringDictionary Parameters => _parameters ?? (_parameters = new TrackingValidationObjectDictionary(s_validators));
+ public StringDictionary Parameters => _parameters ??= new TrackingValidationObjectDictionary(s_validators);
/// <summary>
/// Gets the value of the Filename parameter.
/// </summary>
- public string FileName
+ public string? FileName
{
get { return Parameters[FileNameKey]; }
set
{
get
{
- object sizeValue = ((TrackingValidationObjectDictionary)Parameters).InternalGet(SizeKey);
+ object? sizeValue = ((TrackingValidationObjectDictionary)Parameters).InternalGet(SizeKey);
return sizeValue == null ? -1 : (long)sizeValue;
}
set
// via the headers.
_disposition = contentDisposition;
ParseValue();
- headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), ToString());
+ headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition)!, ToString());
_isPersisted = true;
}
{
if (IsChanged || !_isPersisted || forcePersist)
{
- headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), ToString());
+ headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition)!, ToString());
_isPersisted = true;
}
}
{
_disposition = Encode(false); // Legacy wire-safe format
_isChanged = false;
- _parameters.IsChanged = false;
+ _parameters!.IsChanged = false;
_isPersisted = false;
}
return _disposition;
builder.Append(_dispositionType); // Must not have unicode, already validated
// Validate and encode unicode where required
- foreach (string key in Parameters.Keys)
+ foreach (string? key in Parameters.Keys) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
{
builder.Append("; ");
- EncodeToBuffer(key, builder, allowUnicode);
+ EncodeToBuffer(key!, builder, allowUnicode);
builder.Append('=');
- EncodeToBuffer(_parameters[key], builder, allowUnicode);
+ EncodeToBuffer(_parameters![key!]!, builder, allowUnicode);
}
return builder.ToString();
private static void EncodeToBuffer(string value, StringBuilder builder, bool allowUnicode)
{
- Encoding encoding = MimeBasePart.DecodeEncoding(value);
+ Encoding? encoding = MimeBasePart.DecodeEncoding(value);
if (encoding != null) // Manually encoded elsewhere, pass through
{
builder.Append('"').Append(value).Append('"');
}
}
- public override bool Equals(object rparam)
+ public override bool Equals(object? rparam)
{
return rparam == null ?
false :
break;
}
- string paramAttribute = MailBnfHelper.ReadParameterAttribute(_disposition, ref offset, null);
- string paramValue;
+ string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_disposition, ref offset, null);
+ string? paramValue;
// verify the next character after the parameter is correct
if (_disposition[offset++] != '=')
// See the LICENSE file in the project root for more information.
using System.Collections.Specialized;
+using System.Diagnostics.CodeAnalysis;
using System.Net.Mail;
using System.Text;
{
private readonly TrackingStringDictionary _parameters = new TrackingStringDictionary();
- private string _mediaType;
- private string _subType;
+ private string _mediaType = null!; // initialized by helper called from ctor
+ private string _subType = null!; // initialized by helper called from ctor
private bool _isChanged;
private string _type;
private bool _isPersisted;
ParseValue();
}
- public string Boundary
+ public string? Boundary
{
get { return Parameters["boundary"]; }
set
}
}
- public string CharSet
+ public string? CharSet
{
get { return Parameters["charset"]; }
set
}
}
-
+ [AllowNull]
public string Name
{
get
{
- string value = Parameters["name"];
- Encoding nameEncoding = MimeBasePart.DecodeEncoding(value);
+ string? value = Parameters["name"];
+ Encoding? nameEncoding = MimeBasePart.DecodeEncoding(value);
if (nameEncoding != null)
{
value = MimeBasePart.DecodeHeaderValue(value);
}
- return value;
+ return value!;
}
set
{
}
}
-
public StringDictionary Parameters => _parameters;
internal void Set(string contentType, HeaderCollection headers)
{
_type = contentType;
ParseValue();
- headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), ToString());
+ headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType)!, ToString());
_isPersisted = true;
}
{
if (IsChanged || !_isPersisted || forcePersist)
{
- headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), ToString());
+ headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType)!, ToString());
_isPersisted = true;
}
}
builder.Append(_subType); // Must not have unicode, already validated
// Validate and encode unicode where required
- foreach (string key in Parameters.Keys)
+ foreach (string? key in Parameters.Keys) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
{
builder.Append("; ");
- EncodeToBuffer(key, builder, allowUnicode);
+ EncodeToBuffer(key!, builder, allowUnicode);
builder.Append('=');
- EncodeToBuffer(_parameters[key], builder, allowUnicode);
+ EncodeToBuffer(_parameters[key!]!, builder, allowUnicode);
}
return builder.ToString();
private static void EncodeToBuffer(string value, StringBuilder builder, bool allowUnicode)
{
- Encoding encoding = MimeBasePart.DecodeEncoding(value);
+ Encoding? encoding = MimeBasePart.DecodeEncoding(value);
if (encoding != null) // Manually encoded elsewhere, pass through
{
builder.Append('\"').Append(value).Append('"');
}
}
- public override bool Equals(object rparam) =>
+ public override bool Equals(object? rparam) =>
rparam == null ? false : string.Equals(ToString(), rparam.ToString(), StringComparison.OrdinalIgnoreCase);
public override int GetHashCode() => ToString().ToLowerInvariant().GetHashCode();
private void ParseValue()
{
int offset = 0;
- Exception exception = null;
+ Exception? exception = null;
try
{
break;
}
- string paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset, null);
+ string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset, null);
if (paramAttribute == null || paramAttribute.Length == 0)
{
break;
}
- string paramValue;
+ string? paramValue;
if (offset >= _type.Length || _type[offset++] != '=')
{
exception = new FormatException(SR.ContentTypeInvalid);
/// </summary>
internal class EightBitStream : DelegatedStream, IEncodableStream
{
- private WriteStateInfoBase _writeState;
+ private WriteStateInfoBase? _writeState;
// Should we do RFC 2821 Section 4.5.2 encoding of leading dots on a line?
// We make this optional because this stream may be used recursively and
/// <param name="count">Count of bytes to write</param>
/// <param name="callback">Callback to call when write completes</param>
/// <param name="state">State to pass to callback</param>
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
{
if (buffer == null)
{
/// </summary>
internal class HeaderCollection : NameValueCollection
{
- private readonly MimeBasePart _part = null;
+ private readonly MimeBasePart? _part = null;
// default constructor
// intentionally override the default comparer in the derived base class
{
}
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
public override void Remove(string name)
+#pragma warning restore CS8610
{
if (name == null)
{
if (id == MailHeaderID.ContentType && _part != null)
{
- _part.ContentType = null;
+ _part.ContentType = null!; // this throws ArgumentNullException
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
}
- public override string Get(string name)
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
+ public override string? Get(string name)
+#pragma warning restore CS8610
{
if (name == null)
{
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
- ((MimePart)_part).ContentDisposition.PersistIfNeeded(this, false);
+ ((MimePart)_part!).ContentDisposition!.PersistIfNeeded(this, false);
}
return base.Get(name);
}
- public override string[] GetValues(string name)
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
+ public override string[]? GetValues(string name)
+#pragma warning restore CS8610
{
if (name == null)
{
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
- ((MimePart)_part).ContentDisposition.PersistIfNeeded(this, false);
+ ((MimePart)_part).ContentDisposition!.PersistIfNeeded(this, false);
}
return base.GetValues(name);
}
}
}
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
public override void Set(string name, string value)
+#pragma warning restore CS8610
{
if (name == null)
{
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
- ((MimePart)_part).ContentDisposition.Set(value.ToLowerInvariant(), this);
+ ((MimePart)_part).ContentDisposition!.Set(value.ToLowerInvariant(), this);
}
else
{
}
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
public override void Add(string name, string value)
+#pragma warning restore CS8610
{
if (name == null)
{
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
- ((MimePart)_part).ContentDisposition.Set(value.ToLowerInvariant(), this);
+ ((MimePart)_part).ContentDisposition!.Set(value.ToLowerInvariant(), this);
}
else
{
internal const string DefaultCharSet = "utf-8";
private static readonly char[] s_decodeEncodingSplitChars = new char[] { '?', '\r', '\n' };
- protected ContentType _contentType;
- protected ContentDisposition _contentDisposition;
- private HeaderCollection _headers;
+ protected ContentType? _contentType;
+ protected ContentDisposition? _contentDisposition;
+ private HeaderCollection? _headers;
internal MimeBasePart() { }
- internal static bool ShouldUseBase64Encoding(Encoding encoding) =>
+ internal static bool ShouldUseBase64Encoding(Encoding? encoding) =>
encoding == Encoding.Unicode || encoding == Encoding.UTF8 || encoding == Encoding.UTF32 || encoding == Encoding.BigEndianUnicode;
//use when the length of the header is not known or if there is no header
EncodeHeaderValue(value, encoding, base64Encoding, 0);
//used when the length of the header name itself is known (i.e. Subject : )
- internal static string EncodeHeaderValue(string value, Encoding encoding, bool base64Encoding, int headerLength)
+ internal static string EncodeHeaderValue(string value, Encoding? encoding, bool base64Encoding, int headerLength)
{
//no need to encode if it's pure ascii
if (IsAscii(value, false))
return value;
}
- if (encoding == null)
- {
- encoding = Encoding.GetEncoding(DefaultCharSet);
- }
+ encoding ??= Encoding.GetEncoding(DefaultCharSet);
EncodedStreamFactory factory = new EncodedStreamFactory();
IEncodableStream stream = factory.GetEncoderForHeader(encoding, base64Encoding, headerLength);
private static readonly char[] s_headerValueSplitChars = new char[] { '\r', '\n', ' ' };
private static readonly char[] s_questionMarkSplitChars = new char[] { '?' };
- internal static string DecodeHeaderValue(string value)
+ internal static string DecodeHeaderValue(string? value)
{
if (string.IsNullOrEmpty(value))
{
// "=?utf-8?B?RmlsZU5hbWVf55CG0Y3Qq9C60I5jw4TRicKq0YIM0Y1hSsSeTNCy0Klh?="; // 3.5
// With the addition of folding in 4.0, there may be multiple lines with encoding, only detect the first:
// "=?utf-8?B?RmlsZU5hbWVf55CG0Y3Qq9C60I5jw4TRicKq0YIM0Y1hSsSeTNCy0Klh?=\r\n =?utf-8?B??=";
- internal static Encoding DecodeEncoding(string value)
+ internal static Encoding? DecodeEncoding(string? value)
{
if (string.IsNullOrEmpty(value))
{
return true;
}
- internal string ContentID
+ internal string? ContentID
{
- get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentID)]; }
+ get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentID)!]; }
set
{
if (string.IsNullOrEmpty(value))
}
}
- internal string ContentLocation
+ internal string? ContentLocation
{
- get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentLocation)]; }
+ get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentLocation)!]; }
set
{
if (string.IsNullOrEmpty(value))
internal ContentType ContentType
{
- get { return _contentType ?? (_contentType = new ContentType()); }
+ get { return _contentType ??= new ContentType(); }
set
{
if (value == null)
internal void PrepareHeaders(bool allowUnicode)
{
- _contentType.PersistIfNeeded((HeaderCollection)Headers, false);
- _headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), _contentType.Encode(allowUnicode));
+ _contentType!.PersistIfNeeded((HeaderCollection)Headers, false);
+ _headers!.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType)!, _contentType.Encode(allowUnicode));
if (_contentDisposition != null)
{
_contentDisposition.PersistIfNeeded((HeaderCollection)Headers, false);
- _headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), _contentDisposition.Encode(allowUnicode));
+ _headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition)!, _contentDisposition.Encode(allowUnicode));
}
}
throw new NotImplementedException();
}
- internal virtual IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback,
- bool allowUnicode, object state)
+ internal virtual IAsyncResult BeginSend(BaseWriter writer, AsyncCallback? callback,
+ bool allowUnicode, object? state)
{
throw new NotImplementedException();
}
throw new ArgumentNullException(nameof(asyncResult));
}
- LazyAsyncResult castedAsyncResult = asyncResult as MimePartAsyncResult;
+ LazyAsyncResult? castedAsyncResult = asyncResult as MimePartAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
internal class MimePartAsyncResult : LazyAsyncResult
{
- internal MimePartAsyncResult(MimeBasePart part, object state, AsyncCallback callback) : base(part, state, callback)
+ internal MimePartAsyncResult(MimeBasePart part, object? state, AsyncCallback? callback) : base(part, state, callback)
{
}
}
{
internal class MimeMultiPart : MimeBasePart
{
- private Collection<MimeBasePart> _parts;
+ private Collection<MimeBasePart>? _parts;
private static int s_boundary;
- private AsyncCallback _mimePartSentCallback;
+ private AsyncCallback? _mimePartSentCallback;
private bool _allowUnicode;
internal MimeMultiPart(MimeMultiPartType type)
}
}
- internal void Complete(IAsyncResult result, Exception e)
+ internal void Complete(IAsyncResult result, Exception? e)
{
//if we already completed and we got called again,
//it mean's that there was an exception in the callback and we
//should just rethrow it.
- MimePartContext context = (MimePartContext)result.AsyncState;
+ MimePartContext context = (MimePartContext)result.AsyncState!;
if (context._completed)
{
- ExceptionDispatchInfo.Throw(e);
+ ExceptionDispatchInfo.Throw(e!);
}
try
{
- context._outputStream.Close();
+ context._outputStream!.Close();
}
catch (Exception ex)
{
return;
}
- ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+ ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
try
{
private void MimeWriterCloseCallbackHandler(IAsyncResult result)
{
- MimePartContext context = (MimePartContext)result.AsyncState;
+ MimePartContext context = (MimePartContext)result.AsyncState!;
((MimeWriter)context._writer).EndClose(result);
Complete(result, null);
}
return;
}
- ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+ ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
try
{
private void MimePartSentCallbackHandler(IAsyncResult result)
{
- MimePartContext context = (MimePartContext)result.AsyncState;
+ MimePartContext context = (MimePartContext)result.AsyncState!;
MimeBasePart part = (MimeBasePart)context._partsEnumerator.Current;
part.EndSend(result);
if (context._partsEnumerator.MoveNext())
{
part = (MimeBasePart)context._partsEnumerator.Current;
- IAsyncResult sendResult = part.BeginSend(context._writer, _mimePartSentCallback, _allowUnicode, context);
+ IAsyncResult sendResult = part.BeginSend(context._writer, _mimePartSentCallback!, _allowUnicode, context);
if (sendResult.CompletedSynchronously)
{
MimePartSentCallbackHandler(sendResult);
return;
}
- ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+ ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
try
{
private void ContentStreamCallbackHandler(IAsyncResult result)
{
- MimePartContext context = (MimePartContext)result.AsyncState;
+ MimePartContext context = (MimePartContext)result.AsyncState!;
context._outputStream = context._writer.EndGetContentStream(result);
- context._writer = new MimeWriter(context._outputStream, ContentType.Boundary);
+ context._writer = new MimeWriter(context._outputStream!, ContentType.Boundary!);
if (context._partsEnumerator.MoveNext())
{
MimeBasePart part = (MimeBasePart)context._partsEnumerator.Current;
}
}
- internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback, bool allowUnicode,
- object state)
+ internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback? callback, bool allowUnicode,
+ object? state)
{
_allowUnicode = allowUnicode;
PrepareHeaders(allowUnicode);
}
internal IEnumerator<MimeBasePart> _partsEnumerator;
- internal Stream _outputStream;
+ internal Stream? _outputStream;
internal LazyAsyncResult _result;
internal BaseWriter _writer;
internal bool _completed;
PrepareHeaders(allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
Stream outputStream = writer.GetContentStream();
- MimeWriter mimeWriter = new MimeWriter(outputStream, ContentType.Boundary);
+ MimeWriter mimeWriter = new MimeWriter(outputStream, ContentType.Boundary!);
foreach (MimeBasePart part in Parts)
{
/// </summary>
internal class MimePart : MimeBasePart, IDisposable
{
- private Stream _stream = null;
+ private Stream? _stream;
private bool _streamSet = false;
private bool _streamUsedOnce = false;
- private AsyncCallback _readCallback;
- private AsyncCallback _writeCallback;
+ private AsyncCallback? _readCallback;
+ private AsyncCallback? _writeCallback;
private const int maxBufferSize = 0x4400; //seems optimal for send based on perf analysis
internal MimePart() { }
public void Dispose()
{
- if (_stream != null)
- {
- _stream.Close();
- }
+ _stream?.Close();
}
- internal Stream Stream => _stream;
+ internal Stream? Stream => _stream;
- internal ContentDisposition ContentDisposition
+ internal ContentDisposition? ContentDisposition
{
get { return _contentDisposition; }
set
_contentDisposition = value;
if (value == null)
{
- ((HeaderCollection)Headers).InternalRemove(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition));
+ ((HeaderCollection)Headers).InternalRemove(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition)!);
}
else
{
- _contentDisposition.PersistIfNeeded((HeaderCollection)Headers, true);
+ _contentDisposition!.PersistIfNeeded((HeaderCollection)Headers, true);
}
}
}
{
get
{
- string value = Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)];
+ string value = Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)!]!;
if (value.Equals("base64", StringComparison.OrdinalIgnoreCase))
{
return TransferEncoding.Base64;
if (_streamSet)
{
- _stream.Close();
+ _stream!.Close();
_stream = null;
_streamSet = false;
}
TransferEncoding = TransferEncoding.Base64;
}
- internal void SetContent(Stream stream, string name, string mimeType)
+ internal void SetContent(Stream stream, string? name, string? mimeType)
{
if (stream == null)
{
SetContent(stream);
}
- internal void SetContent(Stream stream, ContentType contentType)
+ internal void SetContent(Stream stream, ContentType? contentType)
{
if (stream == null)
{
SetContent(stream);
}
- internal void Complete(IAsyncResult result, Exception e)
+ internal void Complete(IAsyncResult result, Exception? e)
{
//if we already completed and we got called again,
//it mean's that there was an exception in the callback and we
//should just rethrow it.
- MimePartContext context = (MimePartContext)result.AsyncState;
+ MimePartContext context = (MimePartContext)result.AsyncState!;
if (context._completed)
{
- ExceptionDispatchInfo.Throw(e);
+ ExceptionDispatchInfo.Throw(e!);
}
try
return;
}
- ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+ ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
try
{
internal void ReadCallbackHandler(IAsyncResult result)
{
- MimePartContext context = (MimePartContext)result.AsyncState;
- context._bytesLeft = Stream.EndRead(result);
+ MimePartContext context = (MimePartContext)result.AsyncState!;
+ context._bytesLeft = Stream!.EndRead(result);
if (context._bytesLeft > 0)
{
- IAsyncResult writeResult = context._outputStream.BeginWrite(context._buffer, 0, context._bytesLeft, _writeCallback, context);
+ IAsyncResult writeResult = context._outputStream!.BeginWrite(context._buffer, 0, context._bytesLeft, _writeCallback, context);
if (writeResult.CompletedSynchronously)
{
WriteCallbackHandler(writeResult);
return;
}
- ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+ ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
try
{
internal void WriteCallbackHandler(IAsyncResult result)
{
- MimePartContext context = (MimePartContext)result.AsyncState;
- context._outputStream.EndWrite(result);
- IAsyncResult readResult = Stream.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
+ MimePartContext context = (MimePartContext)result.AsyncState!;
+ context._outputStream!.EndWrite(result);
+ IAsyncResult readResult = Stream!.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
if (readResult.CompletedSynchronously)
{
ReadCallbackHandler(readResult);
internal void ContentStreamCallbackHandler(IAsyncResult result)
{
- MimePartContext context = (MimePartContext)result.AsyncState;
+ MimePartContext context = (MimePartContext)result.AsyncState!;
Stream outputStream = context._writer.EndGetContentStream(result);
context._outputStream = GetEncodedStream(outputStream);
_readCallback = new AsyncCallback(ReadCallback);
_writeCallback = new AsyncCallback(WriteCallback);
- IAsyncResult readResult = Stream.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
+ IAsyncResult readResult = Stream!.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
if (readResult.CompletedSynchronously)
{
ReadCallbackHandler(readResult);
return;
}
- ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+ ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
try
{
_buffer = new byte[maxBufferSize];
}
- internal Stream _outputStream;
+ internal Stream? _outputStream;
internal LazyAsyncResult _result;
internal int _bytesLeft;
internal BaseWriter _writer;
internal bool _completedSynchronously = true;
}
- internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback, bool allowUnicode, object state)
+ internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback? callback, bool allowUnicode, object? state)
{
PrepareHeaders(allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
{
if (_streamUsedOnce)
{
- if (Stream.CanSeek)
+ if (Stream!.CanSeek)
{
Stream.Seek(0, SeekOrigin.Begin);
_streamUsedOnce = false;
if (headers == null)
throw new ArgumentNullException(nameof(headers));
- foreach (string key in headers)
- WriteHeader(key, headers[key], allowUnicode);
+ foreach (string? key in headers) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
+ WriteHeader(key!, headers[key]!, allowUnicode);
}
#region Cleanup
- internal IAsyncResult BeginClose(AsyncCallback callback, object state)
+ internal IAsyncResult BeginClose(AsyncCallback? callback, object? state)
{
MultiAsyncResult multiResult = new MultiAsyncResult(this, callback, state);
_stream.Close();
}
- private void Close(MultiAsyncResult multiResult)
+ private void Close(MultiAsyncResult? multiResult)
{
_bufferBuilder.Append(s_crlf);
_bufferBuilder.Append(s_DASHDASH);
/// </summary>
/// <param name="sender">Sender of the close event</param>
/// <param name="args">Event args (not used)</param>
- protected override void OnClose(object sender, EventArgs args)
+ protected override void OnClose(object? sender, EventArgs args)
{
if (_contentStream != sender)
return; // may have called WriteHeader
_contentStream.Flush();
- _contentStream = null;
+ _contentStream = null!;
_writeBoundary = true;
_isInContent = false;
private readonly object _context;
private int _outstanding;
- internal MultiAsyncResult(object context, AsyncCallback callback, object state) : base(context, state, callback)
+ internal MultiAsyncResult(object context, AsyncCallback? callback, object? state) : base(context, state, callback)
{
_context = context;
}
internal void CompleteSequence() => Decrement();
- internal static object End(IAsyncResult result)
+ internal static object? End(IAsyncResult result)
{
MultiAsyncResult thisPtr = (MultiAsyncResult)result;
thisPtr.InternalWaitForCompletion();
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // F
};
- private ReadStateInfo _readState;
+ private ReadStateInfo? _readState;
private readonly WriteStateInfoBase _writeState;
internal QEncodedStream(WriteStateInfoBase wsi) : base(new MemoryStream())
internal WriteStateInfoBase WriteState => _writeState;
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
{
if (buffer == null)
{
private int _written;
- internal WriteAsyncResult(QEncodedStream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ internal WriteAsyncResult(QEncodedStream parent, byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
: base(null, state, callback)
{
_parent = parent;
{
if (!result.CompletedSynchronously)
{
- WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
+ WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState!;
try
{
thisPtr.CompleteWrite(result);
private static ReadOnlySpan<byte> HexEncodeMap => new byte[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70 };
private readonly int _lineLength;
- private ReadStateInfo _readState;
- private WriteStateInfoBase _writeState;
+ private ReadStateInfo? _readState;
+ private WriteStateInfoBase? _writeState;
/// <summary>
/// ctor.
private ReadStateInfo ReadState => _readState ?? (_readState = new ReadStateInfo());
- internal WriteStateInfoBase WriteState => _writeState ?? (_writeState = new WriteStateInfoBase(1024, null, null, _lineLength));
+ internal WriteStateInfoBase WriteState => _writeState ??= new WriteStateInfoBase(1024, null, null, _lineLength);
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
{
if (buffer == null)
{
//add two to the encoded Byte Length to be conservative so that we guarantee that the line length is acceptable
if ((_lineLength != -1 && WriteState.CurrentLineLength + SizeOfEncodedChar + 2 >= _lineLength && (buffer[cur] == ' ' ||
buffer[cur] == '\t' || buffer[cur] == '\r' || buffer[cur] == '\n')) ||
- _writeState.CurrentLineLength + SizeOfEncodedChar + 2 >= EncodedStreamFactory.DefaultMaxLineLength)
+ _writeState!.CurrentLineLength + SizeOfEncodedChar + 2 >= EncodedStreamFactory.DefaultMaxLineLength)
{
if (WriteState.Buffer.Length - WriteState.Length < SizeOfSoftCRLF)
{
private static readonly AsyncCallback s_onWrite = new AsyncCallback(OnWrite);
private int _written;
- internal WriteAsyncResult(QuotedPrintableStream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
+ internal WriteAsyncResult(QuotedPrintableStream parent, byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) : base(null, state, callback)
{
_parent = parent;
_buffer = buffer;
{
if (!result.CompletedSynchronously)
{
- WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
+ WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState!;
try
{
thisPtr.CompleteWrite(result);
{
internal class WriteStateInfoBase
{
- protected readonly byte[] _header;
- protected readonly byte[] _footer;
+ protected readonly byte[]? _header;
+ protected readonly byte[]? _footer;
protected readonly int _maxLineLength;
protected byte[] _buffer;
_currentBufferUsed = 0;
}
- internal WriteStateInfoBase(int bufferSize, byte[] header, byte[] footer, int maxLineLength)
+ internal WriteStateInfoBase(int bufferSize, byte[]? header, byte[]? footer, int maxLineLength)
: this(bufferSize, header, footer, maxLineLength, 0)
{
}
- internal WriteStateInfoBase(int bufferSize, byte[] header, byte[] footer, int maxLineLength, int mimeHeaderLength)
+ internal WriteStateInfoBase(int bufferSize, byte[]? header, byte[]? footer, int maxLineLength, int mimeHeaderLength)
{
_buffer = new byte[bufferSize];
_header = header;
_currentBufferUsed = 0;
}
- internal int FooterLength => _footer.Length;
- internal byte[] Footer => _footer;
- internal byte[] Header => _header;
+ internal int FooterLength => _footer!.Length;
+ internal byte[]? Footer => _footer;
+ internal byte[]? Header => _header;
internal byte[] Buffer => _buffer;
internal int Length => _currentBufferUsed;
internal int CurrentLineLength => _currentLineLength;
internal bool IsChanged { get { return _isChanged; } set { _isChanged = value; } }
- public override void Add(string key, string value)
+ public override void Add(string key, string? value)
{
if (_isReadOnly)
{
_isChanged = true;
}
- public override string this[string key]
+ public override string? this[string key]
{
get { return base[key]; }
set
// even though validators may exist, we should not initialize this initially since by default it is empty
// and it may never be populated with values if the user does not set them
private readonly Dictionary<string, ValidateAndParseValue> _validators;
- private Dictionary<string, object> _internalObjects = null;
+ private Dictionary<string, object>? _internalObjects = null;
#endregion
// precondition: key must not be null
// addValue determines if we are doing a set (false) or an add (true)
- private void PersistValue(string key, string value, bool addValue)
+ private void PersistValue(string key, string? value, bool addValue)
{
Debug.Assert(key != null, "key was null");
// in addition, a key with an empty value is not valid so we do not persist those either
if (!string.IsNullOrEmpty(value))
{
- ValidateAndParseValue foundEntry;
+ ValidateAndParseValue? foundEntry;
if (_validators != null && _validators.TryGetValue(key, out foundEntry))
{
// run the validator for this key; it will throw if the value is invalid
// public interface only allows strings so this provides a means
// to get the objects when they are not strings
- internal object InternalGet(string key)
+ internal object? InternalGet(string key)
{
// internalObjects will throw if the key is not found so we must check it
- object foundObject;
+ object? foundObject;
if (_internalObjects != null && _internalObjects.TryGetValue(key, out foundObject))
{
return foundObject;
#region Public Fields
- public override string this[string key]
+ public override string? this[string key]
{
get
{
#region Public Methods
- public override void Add(string key, string value)
+ public override void Add(string key, string? value)
{
PersistValue(key, value, true);
}
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath>
<TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix</TargetFrameworks>
+ <Nullable>annotations</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="Base64EncodingTest.cs" />
}
}
- internal string Spn
+ internal string? Spn
{
get
{
{
internal static IIdentity GetIdentity(NTAuthentication context)
{
- string name = context.Spn;
+ string name = context.Spn!;
string protocol = context.ProtocolName;
if (context.IsServer)
internal static IIdentity GetIdentity(NTAuthentication context)
{
IIdentity? result = null;
- string name = context.IsServer ? context.AssociatedName! : context.Spn;
+ string name = context.IsServer ? context.AssociatedName! : context.Spn!;
string protocol = context.ProtocolName;
if (context.IsServer)