From: Stephen Toub Date: Tue, 17 Mar 2020 19:45:17 +0000 (-0400) Subject: Annotate System.Net.Requests for nullable reference types (#33630) X-Git-Tag: submit/tizen/20210909.063632~9117 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=c5070bd300751add48d63255e6c9e302fe4208cc;p=platform%2Fupstream%2Fdotnet%2Fruntime.git Annotate System.Net.Requests for nullable reference types (#33630) --- diff --git a/src/libraries/Common/src/Interop/Windows/WinInet/Interop.wininet_errors.cs b/src/libraries/Common/src/Interop/Windows/WinInet/Interop.wininet_errors.cs index 5bb5373..193a03f 100644 --- a/src/libraries/Common/src/Interop/Windows/WinInet/Interop.wininet_errors.cs +++ b/src/libraries/Common/src/Interop/Windows/WinInet/Interop.wininet_errors.cs @@ -2,8 +2,6 @@ // 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; - namespace System.Net { internal static partial class Interop diff --git a/src/libraries/Common/src/System/Net/LazyAsyncResult.cs b/src/libraries/Common/src/System/Net/LazyAsyncResult.cs index 20d9557..95c7325 100644 --- a/src/libraries/Common/src/System/Net/LazyAsyncResult.cs +++ b/src/libraries/Common/src/System/Net/LazyAsyncResult.cs @@ -45,7 +45,7 @@ namespace System.Net private bool _protectState; // Used by ContextAwareResult to prevent some calls. #endif - private readonly object _asyncObject; // Caller's async object. + private readonly object? _asyncObject; // Caller's async object. private readonly object? _asyncState; // Caller's state object. private AsyncCallback? _asyncCallback; // Caller's callback method. private object? _result; // Final IO result to be returned byt the End*() method. @@ -58,7 +58,7 @@ namespace System.Net private object? _event; // Lazy allocated event to be returned in the IAsyncResult for the client to wait on. - internal LazyAsyncResult(object myObject, object? myState, AsyncCallback? myCallBack) + internal LazyAsyncResult(object? myObject, object? myState, AsyncCallback? myCallBack) { _asyncObject = myObject; _asyncState = myState; @@ -68,7 +68,7 @@ namespace System.Net } // Interface method to return the original async object. - internal object AsyncObject + internal object? AsyncObject { get { diff --git a/src/libraries/Common/src/System/Net/TlsStream.cs b/src/libraries/Common/src/System/Net/TlsStream.cs index 6076b43..9be73c9 100644 --- a/src/libraries/Common/src/System/Net/TlsStream.cs +++ b/src/libraries/Common/src/System/Net/TlsStream.cs @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; namespace System.Net { @@ -32,7 +32,7 @@ namespace System.Net ServicePointManager.CheckCertificateRevocationList); } - public IAsyncResult BeginAuthenticateAsClient(AsyncCallback asyncCallback, object state) + public IAsyncResult BeginAuthenticateAsClient(AsyncCallback? asyncCallback, object? state) { return _sslStream.BeginAuthenticateAsClient( _host, @@ -48,7 +48,7 @@ namespace System.Net _sslStream.EndAuthenticateAsClient(asyncResult); } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { return _sslStream.BeginWrite(buffer, offset, size, callback, state); } @@ -68,7 +68,7 @@ namespace System.Net return _sslStream.Read(buffer, offset, size); } - 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) { return _sslStream.BeginRead(buffer, offset, count, callback, state); } diff --git a/src/libraries/System.Net.Requests/ref/System.Net.Requests.cs b/src/libraries/System.Net.Requests/ref/System.Net.Requests.cs index 9b30667..d105fb5 100644 --- a/src/libraries/System.Net.Requests/ref/System.Net.Requests.cs +++ b/src/libraries/System.Net.Requests/ref/System.Net.Requests.cs @@ -10,44 +10,44 @@ namespace System.Net public partial class AuthenticationManager { internal AuthenticationManager() { } - public static System.Net.ICredentialPolicy CredentialPolicy { get { throw null; } set { } } + public static System.Net.ICredentialPolicy? CredentialPolicy { get { throw null; } set { } } public static System.Collections.Specialized.StringDictionary CustomTargetNameDictionary { get { throw null; } } public static System.Collections.IEnumerator RegisteredModules { get { throw null; } } - public static System.Net.Authorization Authenticate(string challenge, System.Net.WebRequest request, System.Net.ICredentials credentials) { throw null; } - public static System.Net.Authorization PreAuthenticate(System.Net.WebRequest request, System.Net.ICredentials credentials) { throw null; } + public static System.Net.Authorization? Authenticate(string challenge, System.Net.WebRequest request, System.Net.ICredentials credentials) { throw null; } + public static System.Net.Authorization? PreAuthenticate(System.Net.WebRequest request, System.Net.ICredentials credentials) { throw null; } public static void Register(System.Net.IAuthenticationModule authenticationModule) { } public static void Unregister(System.Net.IAuthenticationModule authenticationModule) { } public static void Unregister(string authenticationScheme) { } } public partial class Authorization { - public Authorization(string token) { } - public Authorization(string token, bool finished) { } - public Authorization(string token, bool finished, string connectionGroupId) { } + public Authorization(string? token) { } + public Authorization(string? token, bool finished) { } + public Authorization(string? token, bool finished, string? connectionGroupId) { } public bool Complete { get { throw null; } } - public string ConnectionGroupId { get { throw null; } } - public string Message { get { throw null; } } + public string? ConnectionGroupId { get { throw null; } } + public string? Message { get { throw null; } } public bool MutuallyAuthenticated { get { throw null; } set { } } - public string[] ProtectionRealm { get { throw null; } set { } } + public string[]? ProtectionRealm { get { throw null; } set { } } } public partial class FileWebRequest : System.Net.WebRequest, System.Runtime.Serialization.ISerializable { [System.ObsoleteAttribute("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?linkid=14202")] protected FileWebRequest(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public override string ConnectionGroupName { get { throw null; } set { } } + public override string? ConnectionGroupName { get { throw null; } set { } } public override long ContentLength { get { throw null; } set { } } - public override string ContentType { get { throw null; } set { } } - public override System.Net.ICredentials Credentials { get { throw null; } set { } } + public override string? ContentType { get { throw null; } set { } } + public override System.Net.ICredentials? Credentials { get { throw null; } set { } } public override System.Net.WebHeaderCollection Headers { get { throw null; } } public override string Method { get { throw null; } set { } } public override bool PreAuthenticate { get { throw null; } set { } } - public override System.Net.IWebProxy Proxy { get { throw null; } set { } } + public override System.Net.IWebProxy? Proxy { get { throw null; } set { } } public override System.Uri RequestUri { get { throw null; } } public override int Timeout { get { throw null; } set { } } public override bool UseDefaultCredentials { get { throw null; } set { } } public override void Abort() { } - public override System.IAsyncResult BeginGetRequestStream(System.AsyncCallback callback, object state) { throw null; } - public override System.IAsyncResult BeginGetResponse(System.AsyncCallback callback, object state) { throw null; } + public override System.IAsyncResult BeginGetRequestStream(System.AsyncCallback? callback, object? state) { throw null; } + public override System.IAsyncResult BeginGetResponse(System.AsyncCallback? callback, object? state) { throw null; } public override System.IO.Stream EndGetRequestStream(System.IAsyncResult asyncResult) { throw null; } public override System.Net.WebResponse EndGetResponse(System.IAsyncResult asyncResult) { throw null; } protected override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } @@ -115,20 +115,20 @@ namespace System.Net { internal FtpWebRequest() { } public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } set { } } - public override string ConnectionGroupName { get { throw null; } set { } } + public override string? ConnectionGroupName { get { throw null; } set { } } public override long ContentLength { get { throw null; } set { } } public long ContentOffset { get { throw null; } set { } } - public override string ContentType { get { throw null; } set { } } - public override System.Net.ICredentials Credentials { get { throw null; } set { } } - public static new System.Net.Cache.RequestCachePolicy DefaultCachePolicy { get { throw null; } set { } } + public override string? ContentType { get { throw null; } set { } } + public override System.Net.ICredentials? Credentials { get { throw null; } set { } } + public static new System.Net.Cache.RequestCachePolicy? DefaultCachePolicy { get { throw null; } set { } } public bool EnableSsl { get { throw null; } set { } } public override System.Net.WebHeaderCollection Headers { get { throw null; } set { } } public bool KeepAlive { get { throw null; } set { } } public override string Method { get { throw null; } set { } } public override bool PreAuthenticate { get { throw null; } set { } } - public override System.Net.IWebProxy Proxy { get { throw null; } set { } } + public override System.Net.IWebProxy? Proxy { get { throw null; } set { } } public int ReadWriteTimeout { get { throw null; } set { } } - public string RenameTo { get { throw null; } set { } } + public string? RenameTo { get { throw null; } set { } } public override System.Uri RequestUri { get { throw null; } } public System.Net.ServicePoint ServicePoint { get { throw null; } } public override int Timeout { get { throw null; } set { } } @@ -136,8 +136,8 @@ namespace System.Net public override bool UseDefaultCredentials { get { throw null; } set { } } public bool UsePassive { get { throw null; } set { } } public override void Abort() { } - public override System.IAsyncResult BeginGetRequestStream(System.AsyncCallback callback, object state) { throw null; } - public override System.IAsyncResult BeginGetResponse(System.AsyncCallback callback, object state) { throw null; } + public override System.IAsyncResult BeginGetRequestStream(System.AsyncCallback? callback, object? state) { throw null; } + public override System.IAsyncResult BeginGetResponse(System.AsyncCallback? callback, object? state) { throw null; } public override System.IO.Stream EndGetRequestStream(System.IAsyncResult asyncResult) { throw null; } public override System.Net.WebResponse EndGetResponse(System.IAsyncResult asyncResult) { throw null; } public override System.IO.Stream GetRequestStream() { throw null; } @@ -146,17 +146,16 @@ namespace System.Net public partial class FtpWebResponse : System.Net.WebResponse, System.IDisposable { internal FtpWebResponse() { } - public string BannerMessage { get { throw null; } } + public string? BannerMessage { get { throw null; } } public override long ContentLength { get { throw null; } } - public override string ContentType { get { throw null; } } - public string ExitMessage { get { throw null; } } + public string? ExitMessage { get { throw null; } } public override System.Net.WebHeaderCollection Headers { get { throw null; } } public System.DateTime LastModified { get { throw null; } } public override System.Uri ResponseUri { get { throw null; } } public System.Net.FtpStatusCode StatusCode { get { throw null; } } - public string StatusDescription { get { throw null; } } + public string? StatusDescription { get { throw null; } } public override bool SupportsHeaders { get { throw null; } } - public string WelcomeMessage { get { throw null; } } + public string? WelcomeMessage { get { throw null; } } public override void Close() { } public override System.IO.Stream GetResponseStream() { throw null; } } @@ -164,6 +163,7 @@ namespace System.Net public partial class GlobalProxySelection { public GlobalProxySelection() { } + [System.Diagnostics.CodeAnalysis.AllowNull] public static System.Net.IWebProxy Select { get { throw null; } set { } } public static System.Net.IWebProxy GetEmptyWebProxy() { throw null; } } @@ -172,26 +172,26 @@ namespace System.Net { [System.ObsoleteAttribute("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?linkid=14202")] protected HttpWebRequest(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public string Accept { get { throw null; } set { } } + public string? Accept { get { throw null; } set { } } public System.Uri Address { get { throw null; } } public virtual bool AllowAutoRedirect { get { throw null; } set { } } public virtual bool AllowReadStreamBuffering { get { throw null; } set { } } public virtual bool AllowWriteStreamBuffering { get { throw null; } set { } } public System.Net.DecompressionMethods AutomaticDecompression { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } set { } } - public string Connection { get { throw null; } set { } } - public override string ConnectionGroupName { get { throw null; } set { } } + public string? Connection { get { throw null; } set { } } + public override string? ConnectionGroupName { get { throw null; } set { } } public override long ContentLength { get { throw null; } set { } } - public override string ContentType { get { throw null; } set { } } - public System.Net.HttpContinueDelegate ContinueDelegate { get { throw null; } set { } } + public override string? ContentType { get { throw null; } set { } } + public System.Net.HttpContinueDelegate? ContinueDelegate { get { throw null; } set { } } public int ContinueTimeout { get { throw null; } set { } } - public virtual System.Net.CookieContainer CookieContainer { get { throw null; } set { } } - public override System.Net.ICredentials Credentials { get { throw null; } set { } } + public virtual System.Net.CookieContainer? CookieContainer { get { throw null; } set { } } + public override System.Net.ICredentials? Credentials { get { throw null; } set { } } public System.DateTime Date { get { throw null; } set { } } - public static new System.Net.Cache.RequestCachePolicy DefaultCachePolicy { get { throw null; } set { } } + public static new System.Net.Cache.RequestCachePolicy? DefaultCachePolicy { get { throw null; } set { } } public static int DefaultMaximumErrorResponseLength { get { throw null; } set { } } public static int DefaultMaximumResponseHeadersLength { get { throw null; } set { } } - public string Expect { get { throw null; } set { } } + public string? Expect { get { throw null; } set { } } public virtual bool HaveResponse { get { throw null; } } public override System.Net.WebHeaderCollection Headers { get { throw null; } set { } } public string Host { get { throw null; } set { } } @@ -199,24 +199,24 @@ namespace System.Net public bool KeepAlive { get { throw null; } set { } } public int MaximumAutomaticRedirections { get { throw null; } set { } } public int MaximumResponseHeadersLength { get { throw null; } set { } } - public string MediaType { get { throw null; } set { } } + public string? MediaType { get { throw null; } set { } } public override string Method { get { throw null; } set { } } public bool Pipelined { get { throw null; } set { } } public override bool PreAuthenticate { get { throw null; } set { } } public System.Version ProtocolVersion { get { throw null; } set { } } - public override System.Net.IWebProxy Proxy { get { throw null; } set { } } + public override System.Net.IWebProxy? Proxy { get { throw null; } set { } } public int ReadWriteTimeout { get { throw null; } set { } } - public string Referer { get { throw null; } set { } } + public string? Referer { get { throw null; } set { } } public override System.Uri RequestUri { get { throw null; } } public bool SendChunked { get { throw null; } set { } } - public System.Net.Security.RemoteCertificateValidationCallback ServerCertificateValidationCallback { get { throw null; } set { } } + public System.Net.Security.RemoteCertificateValidationCallback? ServerCertificateValidationCallback { get { throw null; } set { } } public System.Net.ServicePoint ServicePoint { get { throw null; } } public virtual bool SupportsCookieContainer { get { throw null; } } public override int Timeout { get { throw null; } set { } } - public string TransferEncoding { get { throw null; } set { } } + public string? TransferEncoding { get { throw null; } set { } } public bool UnsafeAuthenticatedConnectionSharing { get { throw null; } set { } } public override bool UseDefaultCredentials { get { throw null; } set { } } - public string UserAgent { get { throw null; } set { } } + public string? UserAgent { get { throw null; } set { } } public override void Abort() { } public void AddRange(int range) { } public void AddRange(int from, int to) { } @@ -226,27 +226,29 @@ namespace System.Net public void AddRange(string rangeSpecifier, int from, int to) { } public void AddRange(string rangeSpecifier, long range) { } public void AddRange(string rangeSpecifier, long from, long to) { } - public override System.IAsyncResult BeginGetRequestStream(System.AsyncCallback callback, object state) { throw null; } - public override System.IAsyncResult BeginGetResponse(System.AsyncCallback callback, object state) { throw null; } + public override System.IAsyncResult BeginGetRequestStream(System.AsyncCallback? callback, object? state) { throw null; } + public override System.IAsyncResult BeginGetResponse(System.AsyncCallback? callback, object? state) { throw null; } public override System.IO.Stream EndGetRequestStream(System.IAsyncResult asyncResult) { throw null; } - public System.IO.Stream EndGetRequestStream(System.IAsyncResult asyncResult, out System.Net.TransportContext context) { throw null; } + public System.IO.Stream EndGetRequestStream(System.IAsyncResult asyncResult, out System.Net.TransportContext? context) { throw null; } public override System.Net.WebResponse EndGetResponse(System.IAsyncResult asyncResult) { throw null; } #pragma warning disable 0809 // Obsolete member overrides non-obsolete member [System.ObsoleteAttribute("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?linkid=14202")] protected override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } #pragma warning restore 0809 public override System.IO.Stream GetRequestStream() { throw null; } - public System.IO.Stream GetRequestStream(out System.Net.TransportContext context) { throw null; } + public System.IO.Stream GetRequestStream(out System.Net.TransportContext? context) { throw null; } public override System.Net.WebResponse GetResponse() { throw null; } [System.ObsoleteAttribute("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?linkid=14202")] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public partial class HttpWebResponse : System.Net.WebResponse, System.Runtime.Serialization.ISerializable { + [System.Obsolete("This API supports the .NET infrastructure and is not intended to be used directly from your code.", true)] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public HttpWebResponse() { } [System.ObsoleteAttribute("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?linkid=14202")] protected HttpWebResponse(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public string CharacterSet { get { throw null; } } + public string? CharacterSet { get { throw null; } } public string ContentEncoding { get { throw null; } } public override long ContentLength { get { throw null; } } public override string ContentType { get { throw null; } } @@ -291,7 +293,7 @@ namespace System.Net { public ProtocolViolationException() { } protected ProtocolViolationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public ProtocolViolationException(string message) { } + public ProtocolViolationException(string? message) { } 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) { } } @@ -299,11 +301,11 @@ namespace System.Net { public WebException() { } protected WebException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public WebException(string message) { } - public WebException(string message, System.Exception innerException) { } - public WebException(string message, System.Exception innerException, System.Net.WebExceptionStatus status, System.Net.WebResponse response) { } - public WebException(string message, System.Net.WebExceptionStatus status) { } - public System.Net.WebResponse Response { get { throw null; } } + public WebException(string? message) { } + public WebException(string? message, System.Exception? innerException) { } + public WebException(string? message, System.Exception? innerException, System.Net.WebExceptionStatus status, System.Net.WebResponse? response) { } + public WebException(string? message, System.Net.WebExceptionStatus status) { } + public System.Net.WebResponse? Response { get { throw null; } } public System.Net.WebExceptionStatus Status { 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) { } @@ -337,24 +339,24 @@ namespace System.Net protected WebRequest() { } protected WebRequest(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public System.Net.Security.AuthenticationLevel AuthenticationLevel { get { throw null; } set { } } - public virtual System.Net.Cache.RequestCachePolicy CachePolicy { get { throw null; } set { } } - public virtual string ConnectionGroupName { get { throw null; } set { } } + public virtual System.Net.Cache.RequestCachePolicy? CachePolicy { get { throw null; } set { } } + public virtual string? ConnectionGroupName { get { throw null; } set { } } public virtual long ContentLength { get { throw null; } set { } } - public virtual string ContentType { get { throw null; } set { } } - public virtual System.Net.ICredentials Credentials { get { throw null; } set { } } - public static System.Net.Cache.RequestCachePolicy DefaultCachePolicy { get { throw null; } set { } } - public static System.Net.IWebProxy DefaultWebProxy { get { throw null; } set { } } + public virtual string? ContentType { get { throw null; } set { } } + public virtual System.Net.ICredentials? Credentials { get { throw null; } set { } } + public static System.Net.Cache.RequestCachePolicy? DefaultCachePolicy { get { throw null; } set { } } + public static System.Net.IWebProxy? DefaultWebProxy { get { throw null; } set { } } public virtual System.Net.WebHeaderCollection Headers { get { throw null; } set { } } public System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get { throw null; } set { } } public virtual string Method { get { throw null; } set { } } public virtual bool PreAuthenticate { get { throw null; } set { } } - public virtual System.Net.IWebProxy Proxy { get { throw null; } set { } } + public virtual System.Net.IWebProxy? Proxy { get { throw null; } set { } } public virtual System.Uri RequestUri { get { throw null; } } public virtual int Timeout { get { throw null; } set { } } public virtual bool UseDefaultCredentials { get { throw null; } set { } } public virtual void Abort() { } - public virtual System.IAsyncResult BeginGetRequestStream(System.AsyncCallback callback, object state) { throw null; } - public virtual System.IAsyncResult BeginGetResponse(System.AsyncCallback callback, object state) { throw null; } + public virtual System.IAsyncResult BeginGetRequestStream(System.AsyncCallback? callback, object? state) { throw null; } + public virtual System.IAsyncResult BeginGetResponse(System.AsyncCallback? callback, object? state) { throw null; } public static System.Net.WebRequest Create(string requestUriString) { throw null; } public static System.Net.WebRequest Create(System.Uri requestUri) { throw null; } public static System.Net.WebRequest CreateDefault(System.Uri requestUri) { throw null; } diff --git a/src/libraries/System.Net.Requests/ref/System.Net.Requests.csproj b/src/libraries/System.Net.Requests/ref/System.Net.Requests.csproj index 8ac18e9..a351366 100644 --- a/src/libraries/System.Net.Requests/ref/System.Net.Requests.csproj +++ b/src/libraries/System.Net.Requests/ref/System.Net.Requests.csproj @@ -1,6 +1,7 @@ $(NetCoreAppCurrent) + enable diff --git a/src/libraries/System.Net.Requests/src/System.Net.Requests.csproj b/src/libraries/System.Net.Requests/src/System.Net.Requests.csproj index fe4a6b1..63f1a99 100644 --- a/src/libraries/System.Net.Requests/src/System.Net.Requests.csproj +++ b/src/libraries/System.Net.Requests/src/System.Net.Requests.csproj @@ -4,6 +4,7 @@ System.Net.Requests true $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix + enable diff --git a/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs b/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs index e23459e..9ba0857 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs @@ -11,23 +11,19 @@ namespace System.Net { private AuthenticationManager() { } - public static ICredentialPolicy CredentialPolicy { get; set; } + public static ICredentialPolicy? CredentialPolicy { get; set; } public static StringDictionary CustomTargetNameDictionary { get; } = new StringDictionary(); - public static Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials) - { + public static Authorization? Authenticate(string challenge, WebRequest request, ICredentials credentials) => throw new PlatformNotSupportedException(); - } - public static Authorization PreAuthenticate(WebRequest request, ICredentials credentials) - { + public static Authorization? PreAuthenticate(WebRequest request, ICredentials credentials) => throw new PlatformNotSupportedException(); - } public static void Register(IAuthenticationModule authenticationModule) { - if (authenticationModule == null) + if (authenticationModule is null) { throw new ArgumentNullException(nameof(authenticationModule)); } @@ -35,10 +31,18 @@ namespace System.Net public static void Unregister(IAuthenticationModule authenticationModule) { + if (authenticationModule is null) + { + throw new ArgumentNullException(nameof(authenticationModule)); + } } public static void Unregister(string authenticationScheme) { + if (authenticationScheme is null) + { + throw new ArgumentNullException(nameof(authenticationScheme)); + } } public static IEnumerator RegisteredModules => Array.Empty().GetEnumerator(); diff --git a/src/libraries/System.Net.Requests/src/System/Net/Authorization.cs b/src/libraries/System.Net.Requests/src/System/Net/Authorization.cs index 90e62cf..e02541e 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/Authorization.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/Authorization.cs @@ -6,19 +6,19 @@ namespace System.Net { public class Authorization { - private string[] _protectionRealm; + private string[]? _protectionRealm; private bool _mutualAuth; - public Authorization(string token) : + public Authorization(string? token) : this(token, true) { } - public Authorization(string token, bool finished) : + public Authorization(string? token, bool finished) : this(token, finished, null) { } - public Authorization(string token, bool finished, string connectionGroupId) : + public Authorization(string? token, bool finished, string? connectionGroupId) : this(token, finished, connectionGroupId, false) { } - internal Authorization(string token, bool finished, string connectionGroupId, bool mutualAuth) + internal Authorization(string? token, bool finished, string? connectionGroupId, bool mutualAuth) { Message = string.IsNullOrEmpty(token) ? null : token; ConnectionGroupId = string.IsNullOrEmpty(connectionGroupId) ? null : connectionGroupId; @@ -26,13 +26,13 @@ namespace System.Net _mutualAuth = mutualAuth; } - public string Message { get; } + public string? Message { get; } - public string ConnectionGroupId { get; } + public string? ConnectionGroupId { get; } public bool Complete { get; internal set; } - public string[] ProtectionRealm + public string[]? ProtectionRealm { get { return _protectionRealm; } set { _protectionRealm = value != null && value.Length != 0 ? value : null; } diff --git a/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs b/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs index dfcc727..e013d8d 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs @@ -26,16 +26,16 @@ namespace System.Net // Active variables used for the command state machine // - protected WebRequest _request; + protected WebRequest? _request; protected bool _isAsync; private bool _aborted; - protected PipelineEntry[] _commands; + protected PipelineEntry[]? _commands; protected int _index; private bool _doRead; private bool _doSend; - private ResponseDescription _currentResponseDescription; - protected string _abortReason; + private ResponseDescription? _currentResponseDescription; + protected string? _abortReason; internal CommandStream(TcpClient client) : base(client) @@ -82,9 +82,9 @@ namespace System.Net // request that does not own the web request. } - protected void InvokeRequestCallback(object obj) + protected void InvokeRequestCallback(object? obj) { - WebRequest webRequest = _request; + WebRequest? webRequest = _request; if (webRequest != null) { FtpWebRequest ftpWebRequest = (FtpWebRequest)webRequest; @@ -108,10 +108,10 @@ namespace System.Net } } - internal Stream SubmitRequest(WebRequest request, bool isAsync, bool readInitalResponseOnConnect) + internal Stream? SubmitRequest(WebRequest request, bool isAsync, bool readInitalResponseOnConnect) { ClearState(); - PipelineEntry[] commands = BuildCommandsList(request); + PipelineEntry[]? commands = BuildCommandsList(request); InitCommandPipeline(request, commands, isAsync); if (readInitalResponseOnConnect) { @@ -126,12 +126,12 @@ namespace System.Net InitCommandPipeline(null, null, false); } - protected virtual PipelineEntry[] BuildCommandsList(WebRequest request) + protected virtual PipelineEntry[]? BuildCommandsList(WebRequest request) { return null; } - protected Exception GenerateException(string message, WebExceptionStatus status, Exception innerException) + protected Exception GenerateException(string message, WebExceptionStatus status, Exception? innerException) { return new WebException( message, @@ -140,13 +140,13 @@ namespace System.Net null /* no response */ ); } - protected Exception GenerateException(FtpStatusCode code, string statusDescription, Exception innerException) + protected Exception GenerateException(FtpStatusCode code, string? statusDescription, Exception? innerException) { return new WebException(SR.Format(SR.net_ftp_servererror, NetRes.GetWebStatusCodeString(code, statusDescription)), innerException, WebExceptionStatus.ProtocolError, null); } - protected void InitCommandPipeline(WebRequest request, PipelineEntry[] commands, bool isAsync) + protected void InitCommandPipeline(WebRequest? request, PipelineEntry[]? commands, bool isAsync) { _commands = commands; _index = 0; @@ -180,7 +180,7 @@ namespace System.Net /// each command such STOR, PORT, etc, is sent to the server, then the response is parsed into a string, /// with the response, the delegate is called, which returns an instruction (either continue, stop, or read additional /// responses from server). - protected Stream ContinueCommandPipeline() + protected Stream? ContinueCommandPipeline() { // In async case, The BeginWrite can actually result in a // series of synchronous completions that eventually close @@ -188,7 +188,7 @@ namespace System.Net // we need to access, since they may not be valid after // BeginWrite returns bool isAsync = _isAsync; - while (_index < _commands.Length) + while (_index < _commands!.Length) { if (_doSend) { @@ -236,7 +236,7 @@ namespace System.Net } } - Stream stream = null; + Stream? stream = null; bool isReturn = PostSendCommandProcessing(ref stream); if (isReturn) { @@ -252,7 +252,7 @@ namespace System.Net return null; } - private bool PostSendCommandProcessing(ref Stream stream) + private bool PostSendCommandProcessing(ref Stream? stream) { if (_doRead) { @@ -263,11 +263,11 @@ namespace System.Net // next call returns bool isAsync = _isAsync; int index = _index; - PipelineEntry[] commands = _commands; + PipelineEntry[] commands = _commands!; try { - ResponseDescription response = ReceiveCommandResponse(); + ResponseDescription? response = ReceiveCommandResponse(); if (isAsync) { return true; @@ -279,7 +279,7 @@ namespace System.Net // If we get an exception on the QUIT command (which is // always the last command), ignore the final exception // and continue with the pipeline regardlss of sync/async - if (index < 0 || index >= commands.Length || + if (index < 0 || index >= commands!.Length || commands[index].Command != "QUIT\r\n") throw; } @@ -287,9 +287,9 @@ namespace System.Net return PostReadCommandProcessing(ref stream); } - private bool PostReadCommandProcessing(ref Stream stream) + private bool PostReadCommandProcessing(ref Stream? stream) { - if (_index >= _commands.Length) + if (_index >= _commands!.Length) return false; // Set up front to prevent a race condition on result == PipelineInstruction.Pause @@ -297,7 +297,7 @@ namespace System.Net _doRead = false; PipelineInstruction result; - PipelineEntry entry; + PipelineEntry? entry; if (_index == -1) entry = null; else @@ -306,7 +306,7 @@ namespace System.Net // Final QUIT command may get exceptions since the connection // may be already closed by the server. So there is no response // to process, just advance the pipeline to continue. - if (_currentResponseDescription == null && entry.Command == "QUIT\r\n") + if (_currentResponseDescription == null && entry!.Command == "QUIT\r\n") result = PipelineInstruction.Advance; else result = PipelineCallback(entry, _currentResponseDescription, false, ref stream); @@ -393,7 +393,7 @@ namespace System.Net internal PipelineEntryFlags Flags; } - protected virtual PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream) + protected virtual PipelineInstruction PipelineCallback(PipelineEntry? entry, ResponseDescription? response, bool timeout, ref Stream? stream) { return PipelineInstruction.Abort; } @@ -404,7 +404,7 @@ namespace System.Net private static void ReadCallback(IAsyncResult asyncResult) { - ReceiveState state = (ReceiveState)asyncResult.AsyncState; + ReceiveState state = (ReceiveState)asyncResult.AsyncState!; try { Stream stream = (Stream)state.Connection; @@ -435,7 +435,7 @@ namespace System.Net private static void WriteCallback(IAsyncResult asyncResult) { - CommandStream connection = (CommandStream)asyncResult.AsyncState; + CommandStream connection = (CommandStream)asyncResult.AsyncState!; try { try @@ -451,7 +451,7 @@ namespace System.Net { throw; } - Stream stream = null; + Stream? stream = null; if (connection.PostSendCommandProcessing(ref stream)) return; connection.ContinueCommandPipeline(); @@ -496,7 +496,7 @@ namespace System.Net /// Uses the Encoding encoding to transform the bytes received into a string to be /// returned in the GeneralResponseDescription's StatusDescription field. /// - private ResponseDescription ReceiveCommandResponse() + private ResponseDescription? ReceiveCommandResponse() { // These are the things that will be needed to maintain state. ReceiveState state = new ReceiveState(this); @@ -668,7 +668,7 @@ namespace System.Net { _currentResponseDescription = state.Resp; } - Stream stream = null; + Stream? stream = null; if (PostReadCommandProcessing(ref stream)) return; ContinueCommandPipeline(); @@ -685,10 +685,10 @@ namespace System.Net internal bool Multiline = false; internal int Status = NoStatus; - internal string StatusDescription; + internal string? StatusDescription; internal StringBuilder StatusBuffer = new StringBuilder(); - internal string StatusCodeString; + internal string? StatusCodeString; internal bool PositiveIntermediate { get { return (Status >= 100 && Status <= 199); } } internal bool PositiveCompletion { get { return (Status >= 200 && Status <= 299); } } diff --git a/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs index c314cde..a7b4af8 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs @@ -14,9 +14,9 @@ namespace System.Net private readonly WebHeaderCollection _headers = new WebHeaderCollection(); private string _method = WebRequestMethods.File.DownloadFile; private FileAccess _fileAccess = FileAccess.Read; - private ManualResetEventSlim _blockReaderUntilRequestStreamDisposed; - private WebResponse _response; - private WebFileStream _stream; + private ManualResetEventSlim? _blockReaderUntilRequestStreamDisposed; + private WebResponse? _response; + private WebFileStream? _stream; private readonly Uri _uri; private long _contentLength; private int _timeout = DefaultTimeoutMilliseconds; @@ -52,7 +52,7 @@ namespace System.Net internal bool Aborted => _aborted != 0; - public override string ConnectionGroupName { get; set; } + public override string? ConnectionGroupName { get; set; } public override long ContentLength { @@ -67,13 +67,13 @@ namespace System.Net } } - public override string ContentType + public override string? ContentType { get { return _headers["Content-Type"]; } set { _headers["Content-Type"] = value; } } - public override ICredentials Credentials { get; set; } + public override ICredentials? Credentials { get; set; } public override WebHeaderCollection Headers => _headers; @@ -92,7 +92,7 @@ namespace System.Net public override bool PreAuthenticate { get; set; } - public override IWebProxy Proxy { get; set; } + public override IWebProxy? Proxy { get; set; } public override int Timeout { @@ -155,10 +155,10 @@ namespace System.Net catch (Exception e) { throw new WebException(e.Message, e); } } - public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) + public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state) { CheckAndMarkAsyncGetRequestStreamPending(); - Task t = Task.Factory.StartNew(s => ((FileWebRequest)s).CreateWriteStream(), + Task t = Task.Factory.StartNew(s => ((FileWebRequest)s!).CreateWriteStream(), this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return TaskToApm.Begin(t, callback, state); } @@ -168,7 +168,7 @@ namespace System.Net CheckAndMarkAsyncGetRequestStreamPending(); return Task.Factory.StartNew(s => { - FileWebRequest thisRef = (FileWebRequest)s; + FileWebRequest thisRef = (FileWebRequest)s!; Stream writeStream = thisRef.CreateWriteStream(); thisRef._writePending = false; return writeStream; @@ -216,10 +216,10 @@ namespace System.Net } } - public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) + public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state) { CheckAndMarkAsyncGetResponsePending(); - Task t = Task.Factory.StartNew(s => ((FileWebRequest)s).CreateResponse(), + Task t = Task.Factory.StartNew(s => ((FileWebRequest)s!).CreateResponse(), this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return TaskToApm.Begin(t, callback, state); } @@ -229,7 +229,7 @@ namespace System.Net CheckAndMarkAsyncGetResponsePending(); return Task.Factory.StartNew(s => { - var thisRef = (FileWebRequest)s; + var thisRef = (FileWebRequest)s!; WebResponse response = thisRef.CreateResponse(); _readPending = false; return response; @@ -366,7 +366,7 @@ namespace System.Net } } - public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { CheckAborted(); try @@ -393,7 +393,7 @@ namespace System.Net } } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { CheckAborted(); try diff --git a/src/libraries/System.Net.Requests/src/System/Net/FileWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/FileWebResponse.cs index 0e7f0ce..24f331d 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FileWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FileWebResponse.cs @@ -114,11 +114,11 @@ namespace System.Net { _closed = true; - Stream chkStream = _stream; + Stream? chkStream = _stream; if (chkStream != null) { chkStream.Close(); - _stream = null; + _stream = null!; } } } diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs index d2fdb5f2..f36b484 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Collections; -using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Sockets; @@ -27,36 +26,36 @@ namespace System.Net /// internal class FtpControlStream : CommandStream { - private Socket _dataSocket; - private IPEndPoint _passiveEndPoint; - private TlsStream _tlsStream; - - private StringBuilder _bannerMessage; - private StringBuilder _welcomeMessage; - private StringBuilder _exitMessage; - private WeakReference _credentials; + private Socket? _dataSocket; + private IPEndPoint? _passiveEndPoint; + private TlsStream? _tlsStream; + + private StringBuilder? _bannerMessage; + private StringBuilder? _welcomeMessage; + private StringBuilder? _exitMessage; + private WeakReference? _credentials; private string _currentTypeSetting = string.Empty; private long _contentLength = -1; private DateTime _lastModified; private bool _dataHandshakeStarted = false; - private string _loginDirectory = null; - private string _establishedServerDirectory = null; - private string _requestedServerDirectory = null; - private Uri _responseUri; + private string? _loginDirectory; + private string? _establishedServerDirectory; + private string? _requestedServerDirectory; + private Uri? _responseUri; private FtpLoginState _loginState = FtpLoginState.NotLoggedIn; internal FtpStatusCode StatusCode; - internal string StatusLine; + internal string? StatusLine; - internal NetworkCredential Credentials + internal NetworkCredential? Credentials { get { if (_credentials != null && _credentials.IsAlive) { - return (NetworkCredential)_credentials.Target; + return (NetworkCredential?)_credentials.Target; } else { @@ -87,7 +86,7 @@ namespace System.Net /// internal void AbortConnect() { - Socket socket = _dataSocket; + Socket? socket = _dataSocket; if (socket != null) { try @@ -105,12 +104,12 @@ namespace System.Net /// private static void AcceptCallback(IAsyncResult asyncResult) { - FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState; - Socket listenSocket = connection._dataSocket; + FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState!; + Socket listenSocket = connection._dataSocket!; try { connection._dataSocket = listenSocket.EndAccept(asyncResult); - if (!connection.ServerAddress.Equals(((IPEndPoint)connection._dataSocket.RemoteEndPoint).Address)) + if (!connection.ServerAddress.Equals(((IPEndPoint)connection._dataSocket.RemoteEndPoint!).Address)) { connection._dataSocket.Close(); throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError); @@ -133,10 +132,10 @@ namespace System.Net /// private static void ConnectCallback(IAsyncResult asyncResult) { - FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState; + FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState!; try { - connection._dataSocket.EndConnect(asyncResult); + connection._dataSocket!.EndConnect(asyncResult); connection.ContinueCommandPipeline(); } catch (Exception e) @@ -148,10 +147,10 @@ namespace System.Net private static void SSLHandshakeCallback(IAsyncResult asyncResult) { - FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState; + FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState!; try { - connection._tlsStream.EndAuthenticateAsClient(asyncResult); + connection._tlsStream!.EndAuthenticateAsClient(asyncResult); connection.ContinueCommandPipeline(); } catch (Exception e) @@ -163,7 +162,7 @@ namespace System.Net // Creates a FtpDataStream object, constructs a TLS stream if needed. // In case SSL and ASYNC we delay sigaling the user stream until the handshake is done. - private PipelineInstruction QueueOrCreateFtpDataStream(ref Stream stream) + private PipelineInstruction QueueOrCreateFtpDataStream(ref Stream? stream) { if (_dataSocket == null) throw new InternalException(); @@ -173,7 +172,7 @@ namespace System.Net // if (_tlsStream != null) { - stream = new FtpDataStream(_tlsStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable()); + stream = new FtpDataStream(_tlsStream, (FtpWebRequest)_request!, IsFtpDataStreamWriteable()); _tlsStream = null; return PipelineInstruction.GiveStream; } @@ -182,7 +181,7 @@ namespace System.Net if (UsingSecureStream) { - FtpWebRequest request = (FtpWebRequest)_request; + FtpWebRequest request = (FtpWebRequest)_request!; TlsStream tlsStream = new TlsStream(networkStream, _dataSocket, request.RequestUri.Host, request.ClientCertificates); networkStream = tlsStream; @@ -200,7 +199,7 @@ namespace System.Net } } - stream = new FtpDataStream(networkStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable()); + stream = new FtpDataStream(networkStream, (FtpWebRequest)_request!, IsFtpDataStreamWriteable()); return PipelineInstruction.GiveStream; } @@ -222,7 +221,7 @@ namespace System.Net // This is called by underlying base class code, each time a new response is received from the wire or a protocol stage is resumed. // This function controls the setting up of a data socket/connection, and of saving off the server responses. - protected override PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream) + protected override PipelineInstruction PipelineCallback(PipelineEntry? entry, ResponseDescription? response, bool timeout, ref Stream? stream) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Command:{entry?.Command} Description:{response?.StatusDescription}"); @@ -267,7 +266,7 @@ namespace System.Net // // Check for the result of our attempt to use UTF8 // - if (entry.Command == "OPTS utf8 on\r\n") + if (entry!.Command == "OPTS utf8 on\r\n") { if (response.PositiveCompletion) { @@ -342,13 +341,13 @@ namespace System.Net } // Parse out the Content length, if we can - TryUpdateContentLength(response.StatusDescription); + TryUpdateContentLength(response.StatusDescription!); // Parse out the file name, when it is returned and use it for our ResponseUri - FtpWebRequest request = (FtpWebRequest)_request; + FtpWebRequest request = (FtpWebRequest)_request!; if (request.MethodInfo.ShouldParseForResponseUri) { - TryUpdateResponseUri(response.StatusDescription, request); + TryUpdateResponseUri(response.StatusDescription!, request); } return QueueOrCreateFtpDataStream(ref stream); @@ -362,12 +361,12 @@ namespace System.Net // Update welcome message if (status == FtpStatusCode.LoggedInProceed) { - _welcomeMessage.Append(StatusLine); + _welcomeMessage!.Append(StatusLine); } // OR set the user response ExitMessage else if (status == FtpStatusCode.ClosingControl) { - _exitMessage.Append(response.StatusDescription); + _exitMessage!.Append(response.StatusDescription); // And close the control stream socket on "QUIT" CloseSocket(); } @@ -379,7 +378,7 @@ namespace System.Net // So just let the pipeline continue. if (!(NetworkStream is TlsStream)) { - FtpWebRequest request = (FtpWebRequest)_request; + FtpWebRequest request = (FtpWebRequest)_request!; TlsStream tlsStream = new TlsStream(NetworkStream, Socket, request.RequestUri.Host, request.ClientCertificates); if (_isAsync) @@ -413,11 +412,11 @@ namespace System.Net { if (entry.Command.StartsWith("SIZE ", StringComparison.Ordinal)) { - _contentLength = GetContentLengthFrom213Response(response.StatusDescription); + _contentLength = GetContentLengthFrom213Response(response.StatusDescription!); } else if (entry.Command.StartsWith("MDTM ", StringComparison.Ordinal)) { - _lastModified = GetLastModifiedFrom213Response(response.StatusDescription); + _lastModified = GetLastModifiedFrom213Response(response.StatusDescription!); } } // OR parse out our login directory @@ -425,7 +424,7 @@ namespace System.Net { if (entry.Command == "PWD\r\n" && !entry.HasFlag(PipelineEntryFlags.UserCommand)) { - _loginDirectory = GetLoginDirectory(response.StatusDescription); + _loginDirectory = GetLoginDirectory(response.StatusDescription!); } } // Asserting we have some positive response @@ -479,7 +478,7 @@ namespace System.Net if (_loginState != FtpLoginState.LoggedIn) { - Credentials = request.Credentials.GetCredential(request.RequestUri, "basic"); + Credentials = request.Credentials!.GetCredential(request.RequestUri, "basic"); _welcomeMessage = new StringBuilder(); _exitMessage = new StringBuilder(); @@ -630,7 +629,7 @@ namespace System.Net return (PipelineEntry[])commandList.ToArray(typeof(PipelineEntry)); } - private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream, out bool isSocketReady) + private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream? stream, out bool isSocketReady) { isSocketReady = false; if (_dataHandshakeStarted) @@ -654,11 +653,11 @@ namespace System.Net } if (entry.Command == "PASV\r\n") { - port = GetPortV4(response.StatusDescription); + port = GetPortV4(response.StatusDescription!); } else { - port = GetPortV6(response.StatusDescription); + port = GetPortV6(response.StatusDescription!); } isPassive = true; @@ -673,14 +672,14 @@ namespace System.Net try { - _dataSocket = CreateFtpDataSocket((FtpWebRequest)_request, Socket); + _dataSocket = CreateFtpDataSocket((FtpWebRequest)_request!, Socket); } catch (ObjectDisposedException) { throw ExceptionHelper.RequestAbortedException; } - IPEndPoint localEndPoint = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint).Address, 0); + IPEndPoint localEndPoint = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint!).Address, 0); _dataSocket.Bind(localEndPoint); _passiveEndPoint = new IPEndPoint(ServerAddress, port); @@ -695,12 +694,12 @@ namespace System.Net if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting Connect()"); if (_isAsync) { - _dataSocket.BeginConnect(passiveEndPoint, s_connectCallbackDelegate, this); + _dataSocket!.BeginConnect(passiveEndPoint, s_connectCallbackDelegate, this); result = PipelineInstruction.Pause; } else { - _dataSocket.Connect(passiveEndPoint); + _dataSocket!.Connect(passiveEndPoint); result = PipelineInstruction.Advance; // for passive mode we end up going to the next command } } @@ -710,16 +709,16 @@ namespace System.Net if (_isAsync) { - _dataSocket.BeginAccept(s_acceptCallbackDelegate, this); + _dataSocket!.BeginAccept(s_acceptCallbackDelegate, this); result = PipelineInstruction.Pause; } else { - Socket listenSocket = _dataSocket; + Socket listenSocket = _dataSocket!; try { - _dataSocket = _dataSocket.Accept(); - if (!ServerAddress.Equals(((IPEndPoint)_dataSocket.RemoteEndPoint).Address)) + _dataSocket = _dataSocket!.Accept(); + if (!ServerAddress.Equals(((IPEndPoint)_dataSocket.RemoteEndPoint!).Address)) { _dataSocket.Close(); throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError); @@ -839,14 +838,14 @@ namespace System.Net { get { - return _responseUri; + return _responseUri!; } } /// /// Returns the server message sent before user credentials are sent /// - internal string BannerMessage + internal string? BannerMessage { get { @@ -857,7 +856,7 @@ namespace System.Net /// /// Returns the server message sent after user credentials are sent /// - internal string WelcomeMessage + internal string? WelcomeMessage { get { @@ -868,7 +867,7 @@ namespace System.Net /// /// Returns the exit sent message on shutdown /// - internal string ExitMessage + internal string? ExitMessage { get { @@ -966,7 +965,7 @@ namespace System.Net baseUri = uriBuilder.Uri; } - Uri newUri; + Uri? newUri; if (!Uri.TryCreate(baseUri, escapedFilename, out newUri)) { throw new FormatException(SR.Format(SR.net_ftp_invalid_response_filename, filename)); @@ -1076,7 +1075,7 @@ namespace System.Net private void CreateFtpListenerSocket(FtpWebRequest request) { // Gets an IPEndPoint for the local host for the data socket to bind to. - IPEndPoint epListener = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint).Address, 0); + IPEndPoint epListener = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint!).Address, 0); try { _dataSocket = CreateFtpDataSocket(request, Socket); @@ -1099,7 +1098,7 @@ namespace System.Net try { // retrieves the IP address of the local endpoint - IPEndPoint localEP = (IPEndPoint)_dataSocket.LocalEndPoint; + IPEndPoint localEP = (IPEndPoint)_dataSocket!.LocalEndPoint!; if (ServerAddress.AddressFamily == AddressFamily.InterNetwork || ServerAddress.IsIPv4MappedToIPv6) { return FormatAddress(localEP.Address, localEP.Port); @@ -1122,7 +1121,7 @@ namespace System.Net /// /// Formats a simple FTP command + parameter in correct pre-wire format /// - private string FormatFtpCommand(string command, string parameter) + private string FormatFtpCommand(string command, string? parameter) { StringBuilder stringBuilder = new StringBuilder(command.Length + ((parameter != null) ? parameter.Length : 0) + 3 /*size of ' ' \r\n*/); stringBuilder.Append(command); @@ -1228,7 +1227,7 @@ namespace System.Net /// private TriState IsFtpDataStreamWriteable() { - FtpWebRequest request = _request as FtpWebRequest; + FtpWebRequest? request = _request as FtpWebRequest; if (request != null) { if (request.MethodInfo.IsUpload) diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpDataStream.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpDataStream.cs index 40c0486..b404570 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpDataStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpDataStream.cs @@ -88,10 +88,10 @@ namespace System.Net catch (Exception exception) { bool doThrow = true; - WebException webException = exception as WebException; + WebException? webException = exception as WebException; if (webException != null) { - FtpWebResponse response = webException.Response as FtpWebResponse; + FtpWebResponse? response = webException.Response as FtpWebResponse; if (response != null) { if (!_isFullyRead @@ -210,7 +210,7 @@ namespace System.Net private void AsyncReadCallback(IAsyncResult ar) { - LazyAsyncResult userResult = (LazyAsyncResult)ar.AsyncState; + LazyAsyncResult userResult = (LazyAsyncResult)ar.AsyncState!; try { try @@ -233,7 +233,7 @@ namespace System.Net catch { } } - public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { CheckError(); LazyAsyncResult userResult = new LazyAsyncResult(this, state, callback); @@ -253,7 +253,7 @@ namespace System.Net { try { - object result = ((LazyAsyncResult)ar).InternalWaitForCompletion(); + object result = ((LazyAsyncResult)ar).InternalWaitForCompletion()!; if (result is Exception e) { @@ -268,7 +268,7 @@ namespace System.Net } } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { CheckError(); try diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs index 65aebf7..2b09105 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -2,8 +2,6 @@ // 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; -using System.Globalization; using System.IO; using System.Net.Cache; using System.Net.Sockets; @@ -12,7 +10,7 @@ using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; -using System.Threading.Tasks; +using System.Diagnostics.CodeAnalysis; namespace System.Net { @@ -54,12 +52,12 @@ namespace System.Net internal string Method; internal FtpOperation Operation; internal FtpMethodFlags Flags; - internal string HttpCommand; + internal string? HttpCommand; internal FtpMethodInfo(string method, FtpOperation operation, FtpMethodFlags flags, - string httpCommand) + string? httpCommand) { Method = method; Operation = operation; @@ -187,7 +185,7 @@ namespace System.Net private ICredentials _authInfo; private readonly Uri _uri; private FtpMethodInfo _methodInfo; - private string _renameTo = null; + private string? _renameTo; private bool _getRequestStreamStarted; private bool _getResponseStarted; private DateTime _startTime; @@ -195,33 +193,33 @@ namespace System.Net private int _remainingTimeout; private long _contentLength = 0; private long _contentOffset = 0; - private X509CertificateCollection _clientCertificates; + private X509CertificateCollection? _clientCertificates; private bool _passive = true; private bool _binary = true; - private string _connectionGroupName; - private ServicePoint _servicePoint; + private string? _connectionGroupName; + private ServicePoint? _servicePoint; private bool _async; private bool _aborted; private bool _timedOut; - private Exception _exception; + private Exception? _exception; - private TimerThread.Queue _timerQueue = s_DefaultTimerQueue; + private TimerThread.Queue? _timerQueue = s_DefaultTimerQueue; private readonly TimerThread.Callback _timerCallback; private bool _enableSsl; - private FtpControlStream _connection; - private Stream _stream; + private FtpControlStream? _connection; + private Stream? _stream; private RequestStage _requestStage; private bool _onceFailed; - private WebHeaderCollection _ftpRequestHeaders; - private FtpWebResponse _ftpWebResponse; + private WebHeaderCollection? _ftpRequestHeaders; + private FtpWebResponse? _ftpWebResponse; private int _readWriteTimeout = 5 * 60 * 1000; // 5 minutes. - private ContextAwareResult _writeAsyncResult; - private LazyAsyncResult _readAsyncResult; - private LazyAsyncResult _requestCompleteAsyncResult; + private ContextAwareResult? _writeAsyncResult; + private LazyAsyncResult? _readAsyncResult; + private LazyAsyncResult? _requestCompleteAsyncResult; private static readonly NetworkCredential s_defaultFtpNetworkCredential = new NetworkCredential("anonymous", "anonymous@", string.Empty); private const int s_DefaultTimeout = 100000; // 100 seconds @@ -236,7 +234,7 @@ namespace System.Net } } - public static new RequestCachePolicy DefaultCachePolicy + public static new RequestCachePolicy? DefaultCachePolicy { get { @@ -287,7 +285,8 @@ namespace System.Net /// Not allowed to be changed once request is started. /// /// - public string RenameTo + [DisallowNull] + public string? RenameTo { get { @@ -312,7 +311,8 @@ namespace System.Net /// /// Used for clear text authentication with FTP server /// - public override ICredentials Credentials + [DisallowNull] + public override ICredentials? Credentials { get { @@ -446,7 +446,7 @@ namespace System.Net } } - public override IWebProxy Proxy + public override IWebProxy? Proxy { get { @@ -463,7 +463,7 @@ namespace System.Net } } - public override string ConnectionGroupName + public override string? ConnectionGroupName { get { @@ -479,17 +479,7 @@ namespace System.Net } } - public ServicePoint ServicePoint - { - get - { - if (_servicePoint == null) - { - _servicePoint = ServicePointManager.FindServicePoint(_uri); - } - return _servicePoint; - } - } + public ServicePoint ServicePoint => _servicePoint ??= ServicePointManager.FindServicePoint(_uri); internal bool Aborted { @@ -509,7 +499,7 @@ namespace System.Net _timerCallback = new TimerThread.Callback(TimerCallback); _syncObject = new object(); - NetworkCredential networkCredential = null; + NetworkCredential? networkCredential = null; _uri = uri; _methodInfo = FtpMethodInfo.GetMethodInfo(WebRequestMethods.Ftp.DownloadFile); if (_uri.UserInfo != null && _uri.UserInfo.Length != 0) @@ -622,13 +612,13 @@ namespace System.Net { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _ftpWebResponse); } - return _ftpWebResponse; + return _ftpWebResponse!; } /// /// Used to query for the Response of an FTP request [async version] /// - public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) + public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state) { if (NetEventSource.IsEnabled) { @@ -636,7 +626,7 @@ namespace System.Net NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } - ContextAwareResult asyncResult; + ContextAwareResult? asyncResult; try { @@ -721,7 +711,7 @@ namespace System.Net { throw new ArgumentNullException(nameof(asyncResult)); } - LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult; + LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -745,7 +735,7 @@ namespace System.Net if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } - return _ftpWebResponse; + return _ftpWebResponse!; } /// @@ -790,7 +780,7 @@ namespace System.Net FinishRequestStage(RequestStage.WriteReady); CheckError(); - if (_stream.CanTimeout) + if (_stream!.CanTimeout) { _stream.WriteTimeout = ReadWriteTimeout; _stream.ReadTimeout = ReadWriteTimeout; @@ -811,7 +801,7 @@ namespace System.Net /// /// Used to query for the Request stream of an FTP Request [async version] /// - public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) + public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state) { if (NetEventSource.IsEnabled) { @@ -819,7 +809,7 @@ namespace System.Net NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } - ContextAwareResult asyncResult = null; + ContextAwareResult? asyncResult = null; try { if (_getRequestStreamStarted) @@ -859,7 +849,7 @@ namespace System.Net public override Stream EndGetRequestStream(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); - Stream requestStream = null; + Stream? requestStream = null; try { if (asyncResult == null) @@ -867,7 +857,7 @@ namespace System.Net throw new ArgumentNullException(nameof(asyncResult)); } - LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult; + LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null) { @@ -885,7 +875,7 @@ namespace System.Net requestStream = _stream; castedAsyncResult.EndCalled = true; - if (requestStream.CanTimeout) + if (requestStream!.CanTimeout) { requestStream.WriteTimeout = ReadWriteTimeout; requestStream.ReadTimeout = ReadWriteTimeout; @@ -920,7 +910,7 @@ namespace System.Net while (true) { - FtpControlStream connection = _connection; + FtpControlStream? connection = _connection; if (connection == null) { @@ -981,10 +971,10 @@ namespace System.Net catch (WebException webException) { // If this was a timeout, throw a timeout exception - IOException ioEx = webException.InnerException as IOException; + IOException? ioEx = webException.InnerException as IOException; if (ioEx != null) { - SocketException sEx = ioEx.InnerException as SocketException; + SocketException? sEx = ioEx.InnerException as SocketException; if (sEx != null) { if (sEx.SocketErrorCode == SocketError.TimedOut) @@ -1004,7 +994,7 @@ namespace System.Net private Exception TranslateConnectException(Exception e) { - SocketException se = e as SocketException; + SocketException? se = e as SocketException; if (se != null) { if (se.SocketErrorCode == SocketError.HostNotFound) @@ -1068,15 +1058,15 @@ namespace System.Net // non-null in the case of re-submit (recovery) if (_requestCompleteAsyncResult == null) _requestCompleteAsyncResult = new LazyAsyncResult(null, null, null); - return _connection.SubmitRequest(this, true, true); + return _connection!.SubmitRequest(this, true, true)!; } - Stream stream = null; + Stream? stream = null; bool timedOut = false; TimerThread.Timer timer = TimerQueue.CreateTimer(_timerCallback, null); try { - stream = _connection.SubmitRequest(this, false, true); + stream = _connection!.SubmitRequest(this, false, true); } catch (Exception exception) { @@ -1109,17 +1099,17 @@ namespace System.Net } } - return stream; + return stream!; } /// /// Because this is called from the timer thread, neither it nor any methods it calls can call user code. /// - private void TimerCallback(TimerThread.Timer timer, int timeNoticed, object context) + private void TimerCallback(TimerThread.Timer timer, int timeNoticed, object? context) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); - FtpControlStream connection = _connection; + FtpControlStream? connection = _connection; if (connection != null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "aborting connection"); @@ -1185,7 +1175,7 @@ namespace System.Net throw exception; } - FtpControlStream connection = _connection; + FtpControlStream? connection = _connection; if (_exception == null) { if (exception is WebException) @@ -1223,7 +1213,7 @@ namespace System.Net } } - internal void RequestCallback(object obj) + internal void RequestCallback(object? obj) { if (_async) AsyncRequestCallback(obj); @@ -1234,7 +1224,7 @@ namespace System.Net // // Only executed for Sync requests when the pipline is completed // - private void SyncRequestCallback(object obj) + private void SyncRequestCallback(object? obj) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, obj); @@ -1242,7 +1232,7 @@ namespace System.Net try { bool completedRequest = obj == null; - Exception exception = obj as Exception; + Exception? exception = obj as Exception; if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"exp:{exception} completedRequest:{completedRequest}"); @@ -1256,7 +1246,7 @@ namespace System.Net } else { - FtpControlStream connection = _connection; + FtpControlStream? connection = _connection; if (connection != null) { @@ -1264,7 +1254,7 @@ namespace System.Net // This to update response status and exit message if any. // Note that status 221 "Service closing control connection" is always suppressed. - _ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); + _ftpWebResponse!.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); } stageMode = RequestStage.ReleaseConnection; @@ -1285,17 +1275,16 @@ namespace System.Net // // Only executed for Async requests // - private void AsyncRequestCallback(object obj) + private void AsyncRequestCallback(object? obj) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, obj); RequestStage stageMode = RequestStage.CheckForError; try { - FtpControlStream connection; - connection = obj as FtpControlStream; - FtpDataStream stream = obj as FtpDataStream; - Exception exception = obj as Exception; + FtpControlStream? connection = obj as FtpControlStream; + FtpDataStream? stream = obj as FtpDataStream; + Exception? exception = obj as Exception; bool completedRequest = (obj == null); @@ -1371,7 +1360,7 @@ namespace System.Net // This to update response status and exit message if any. // Note that the status 221 "Service closing control connection" is always suppressed. - _ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); + _ftpWebResponse!.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); } stageMode = RequestStage.ReleaseConnection; @@ -1414,9 +1403,9 @@ namespace System.Net stage = RequestStage.ReleaseConnection; RequestStage prev; - LazyAsyncResult writeResult; - LazyAsyncResult readResult; - FtpControlStream connection; + LazyAsyncResult? writeResult; + LazyAsyncResult? readResult; + FtpControlStream? connection; lock (_syncObject) { @@ -1447,7 +1436,7 @@ namespace System.Net !_aborted && prev != RequestStage.ReadReady && _methodInfo.IsDownload && - !_ftpWebResponse.IsFromCache) + !_ftpWebResponse!.IsFromCache) { return prev; } @@ -1523,8 +1512,8 @@ namespace System.Net try { - Stream stream; - FtpControlStream connection; + Stream? stream; + FtpControlStream? connection; lock (_syncObject) { if (_requestStage >= RequestStage.ReleaseConnection) @@ -1575,7 +1564,7 @@ namespace System.Net } } - public override RequestCachePolicy CachePolicy + public override RequestCachePolicy? CachePolicy { get { @@ -1679,7 +1668,7 @@ namespace System.Net } // NOT SUPPORTED method - public override string ContentType + public override string? ContentType { get { @@ -1738,7 +1727,7 @@ namespace System.Net /// /// Creates an FTP WebResponse based off the responseStream and our active Connection /// - private void EnsureFtpWebResponse(Exception exception) + private void EnsureFtpWebResponse(Exception? exception) { if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null)) { @@ -1746,7 +1735,7 @@ namespace System.Net { if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null)) { - Stream responseStream = _stream; + Stream? responseStream = _stream; if (_methodInfo.IsUpload) { @@ -1759,7 +1748,7 @@ namespace System.Net _stream.WriteTimeout = ReadWriteTimeout; } - FtpControlStream connection = _connection; + FtpControlStream? connection = _connection; long contentLength = connection != null ? connection.ContentLength : -1; if (responseStream == null) @@ -1804,13 +1793,13 @@ namespace System.Net } else { - _requestCompleteAsyncResult.InternalWaitForCompletion(); + _requestCompleteAsyncResult!.InternalWaitForCompletion(); CheckError(); } } else { - FtpControlStream connection = _connection; + FtpControlStream? connection = _connection; if (connection != null) connection.Abort(ExceptionHelper.RequestAbortedException); } diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs index 2706cf2..de1c522 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs @@ -11,18 +11,18 @@ namespace System.Net /// public class FtpWebResponse : WebResponse, IDisposable { - internal Stream _responseStream; + internal Stream? _responseStream; private readonly long _contentLength; private readonly Uri _responseUri; private FtpStatusCode _statusCode; - private string _statusLine; - private WebHeaderCollection _ftpRequestHeaders; + private string? _statusLine; + private WebHeaderCollection? _ftpRequestHeaders; private readonly DateTime _lastModified; - private readonly string _bannerMessage; - private readonly string _welcomeMessage; - private string _exitMessage; + private readonly string? _bannerMessage; + private readonly string? _welcomeMessage; + private string? _exitMessage; - internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage) + internal FtpWebResponse(Stream? responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string? statusLine, DateTime lastModified, string? bannerMessage, string? welcomeMessage, string? exitMessage) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, contentLength, statusLine); @@ -41,7 +41,7 @@ namespace System.Net _exitMessage = exitMessage; } - internal void UpdateStatus(FtpStatusCode statusCode, string statusLine, string exitMessage) + internal void UpdateStatus(FtpStatusCode statusCode, string? statusLine, string? exitMessage) { _statusCode = statusCode; _statusLine = statusLine; @@ -50,7 +50,7 @@ namespace System.Net public override Stream GetResponseStream() { - Stream responseStream = null; + Stream? responseStream = null; if (_responseStream != null) { @@ -70,7 +70,7 @@ namespace System.Net } } - internal void SetResponseStream(Stream stream) + internal void SetResponseStream(Stream? stream) { if (stream == null || stream == Stream.Null || stream is EmptyStream) return; @@ -149,7 +149,7 @@ namespace System.Net /// /// Last status line retrieved /// - public string StatusDescription + public string? StatusDescription { get { @@ -171,7 +171,7 @@ namespace System.Net /// /// Returns the server message sent before user credentials are sent /// - public string BannerMessage + public string? BannerMessage { get { @@ -182,7 +182,7 @@ namespace System.Net /// /// Returns the server message sent after user credentials are sent /// - public string WelcomeMessage + public string? WelcomeMessage { get { @@ -193,7 +193,7 @@ namespace System.Net /// /// Returns the exit sent message on shutdown /// - public string ExitMessage + public string? ExitMessage { get { diff --git a/src/libraries/System.Net.Requests/src/System/Net/GlobalProxySelection.cs b/src/libraries/System.Net.Requests/src/System/Net/GlobalProxySelection.cs index 0117813..e6ac71f 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/GlobalProxySelection.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/GlobalProxySelection.cs @@ -2,63 +2,37 @@ // 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; + namespace System.Net { [Obsolete("This class has been deprecated. Please use WebRequest.DefaultWebProxy instead to access and set the global default proxy. Use 'null' instead of GetEmptyWebProxy. https://go.microsoft.com/fwlink/?linkid=14202")] public class GlobalProxySelection { // This defers to WebRequest.DefaultWebProxy, but returns EmptyWebProxy instead of null. + [AllowNull] public static IWebProxy Select { - get - { - IWebProxy proxy = WebRequest.DefaultWebProxy; - if (proxy == null) - { - proxy = GetEmptyWebProxy(); - } - return proxy; - } - - set - { - WebRequest.DefaultWebProxy = value; - } + get => WebRequest.DefaultWebProxy ?? GetEmptyWebProxy(); + set => WebRequest.DefaultWebProxy = value; } - public static IWebProxy GetEmptyWebProxy() - { - return new EmptyWebProxy(); - } + public static IWebProxy GetEmptyWebProxy() => new EmptyWebProxy(); private sealed class EmptyWebProxy : IWebProxy { - private ICredentials _credentials; + private ICredentials? _credentials; - public EmptyWebProxy() - { - } + public EmptyWebProxy() { } - public Uri GetProxy(Uri uri) - { - return uri; - } + public Uri GetProxy(Uri uri) => uri; - public bool IsBypassed(Uri uri) - { - return true; // no proxy, always bypasses - } + public bool IsBypassed(Uri uri) => true; // no proxy, always bypasses - public ICredentials Credentials + public ICredentials? Credentials { - get - { - return _credentials; - } - set - { - _credentials = value; // doesn't do anything, but doesn't break contract either - } + get => _credentials; + set => _credentials = value; // doesn't do anything, but doesn't break contract either } } } diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs index 6bfd49f..cf9b579 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Net.Cache; @@ -11,7 +12,6 @@ using System.Net.Security; using System.Runtime.Serialization; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; -using System.Text; using System.Threading; using System.Threading.Tasks; @@ -26,7 +26,7 @@ namespace System.Net private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection(); - private readonly Uri _requestUri; + private readonly Uri _requestUri = null!; private string _originVerb = HttpMethod.Get.Method; // We allow getting and setting this (to preserve app-compat). But we don't do anything with it @@ -34,11 +34,11 @@ namespace System.Net private int _continueTimeout = DefaultContinueTimeout; private bool _allowReadStreamBuffering = false; - private CookieContainer _cookieContainer = null; - private ICredentials _credentials = null; - private IWebProxy _proxy = WebRequest.DefaultWebProxy; + private CookieContainer? _cookieContainer; + private ICredentials? _credentials; + private IWebProxy? _proxy = WebRequest.DefaultWebProxy; - private Task _sendRequestTask; + private Task? _sendRequestTask; private static int _defaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; @@ -49,33 +49,33 @@ namespace System.Net private int _maximumAllowedRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maximumResponseHeadersLen = _defaultMaxResponseHeadersLength; - private ServicePoint _servicePoint; + private ServicePoint? _servicePoint; private int _timeout = WebRequest.DefaultTimeoutMilliseconds; private int _readWriteTimeout = DefaultReadWriteTimeout; - private HttpContinueDelegate _continueDelegate; + private HttpContinueDelegate? _continueDelegate; // stores the user provided Host header as Uri. If the user specified a default port explicitly we'll lose // that information when converting the host string to a Uri. _HostHasPort will store that information. private bool _hostHasPort; - private Uri _hostUri; + private Uri? _hostUri; - private RequestStream _requestStream; - private TaskCompletionSource _requestStreamOperation = null; - private TaskCompletionSource _responseOperation = null; - private AsyncCallback _requestStreamCallback = null; - private AsyncCallback _responseCallback = null; + private RequestStream? _requestStream; + private TaskCompletionSource? _requestStreamOperation; + private TaskCompletionSource? _responseOperation; + private AsyncCallback? _requestStreamCallback; + private AsyncCallback? _responseCallback; private int _abortCalled = 0; - private CancellationTokenSource _sendRequestCts; - private X509CertificateCollection _clientCertificates; + private CancellationTokenSource? _sendRequestCts; + private X509CertificateCollection? _clientCertificates; private Booleans _booleans = Booleans.Default; private bool _pipelined = true; private bool _preAuthenticate; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private static readonly object s_syncRoot = new object(); - private static volatile HttpClient s_cachedHttpClient; - private static HttpClientParameters s_cachedHttpClientParameters; + private static volatile HttpClient? s_cachedHttpClient; + private static HttpClientParameters? s_cachedHttpClientParameters; //these should be safe. [Flags] @@ -106,11 +106,11 @@ namespace System.Net public readonly TimeSpan Timeout; public readonly SecurityProtocolType SslProtocols; public readonly bool CheckCertificateRevocationList; - public readonly ICredentials Credentials; - public readonly IWebProxy Proxy; - public readonly RemoteCertificateValidationCallback ServerCertificateValidationCallback; - public readonly X509CertificateCollection ClientCertificates; - public readonly CookieContainer CookieContainer; + public readonly ICredentials? Credentials; + public readonly IWebProxy? Proxy; + public readonly RemoteCertificateValidationCallback? ServerCertificateValidationCallback; + public readonly X509CertificateCollection? ClientCertificates; + public readonly CookieContainer? CookieContainer; public HttpClientParameters(HttpWebRequest webRequest) { @@ -186,7 +186,7 @@ namespace System.Net _requestUri = uri; } - private void SetSpecialHeaders(string HeaderName, string value) + private void SetSpecialHeaders(string HeaderName, string? value) { _webHeaderCollection.Remove(HeaderName); if (!string.IsNullOrEmpty(value)) @@ -195,7 +195,7 @@ namespace System.Net } } - public string Accept + public string? Accept { get { @@ -252,7 +252,7 @@ namespace System.Net } } - public override string ContentType + public override string? ContentType { get { @@ -331,7 +331,7 @@ namespace System.Net } } - public string UserAgent + public string? UserAgent { get { @@ -363,7 +363,7 @@ namespace System.Net throw new ArgumentNullException(nameof(value)); } - Uri hostUri; + Uri? hostUri; if ((value.Contains('/')) || (!TryGetHostUri(value, out hostUri))) { throw new ArgumentException(SR.net_invalid_host, nameof(value)); @@ -405,7 +405,7 @@ namespace System.Net /// Gets or sets the value of the Referer header. /// /// - public string Referer + public string? Referer { get { @@ -420,7 +420,7 @@ namespace System.Net /// /// Sets the media type header /// - public string MediaType + public string? MediaType { get; set; @@ -431,7 +431,7 @@ namespace System.Net /// Gets or sets the value of the Transfer-Encoding header. Setting null clears it out. /// /// - public string TransferEncoding + public string? TransferEncoding { get { @@ -565,7 +565,7 @@ namespace System.Net } } - public override string ConnectionGroupName { get; set; } + public override string? ConnectionGroupName { get; set; } public override bool PreAuthenticate { @@ -579,7 +579,7 @@ namespace System.Net } } - public string Connection + public string? Connection { get { @@ -636,7 +636,7 @@ namespace System.Net Returns: The value of the Expect on get. */ - public string Expect + public string? Expect { get { @@ -708,7 +708,7 @@ namespace System.Net get; set; } - public static new RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache); + public static new RequestCachePolicy? DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache); public DateTime IfModifiedSince { @@ -762,7 +762,7 @@ namespace System.Net } } - public HttpContinueDelegate ContinueDelegate + public HttpContinueDelegate? ContinueDelegate { // Nop since the underlying API do not expose 100 continue. get @@ -775,19 +775,9 @@ namespace System.Net } } - public ServicePoint ServicePoint - { - get - { - if (_servicePoint == null) - { - _servicePoint = ServicePointManager.FindServicePoint(Address, Proxy); - } - return _servicePoint; - } - } + public ServicePoint ServicePoint => _servicePoint ??= ServicePointManager.FindServicePoint(Address, Proxy); - public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; } + public RemoteCertificateValidationCallback? ServerCertificateValidationCallback { get; set; } // // ClientCertificates - sets our certs for our reqest, @@ -797,20 +787,8 @@ namespace System.Net // public X509CertificateCollection ClientCertificates { - get - { - if (_clientCertificates == null) - _clientCertificates = new X509CertificateCollection(); - return _clientCertificates; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - _clientCertificates = value; - } + get => _clientCertificates ??= new X509CertificateCollection(); + set => _clientCertificates = value ?? throw new ArgumentNullException(nameof(value)); } // HTTP Version @@ -865,7 +843,7 @@ namespace System.Net } } - public virtual CookieContainer CookieContainer + public virtual CookieContainer? CookieContainer { get { @@ -877,7 +855,7 @@ namespace System.Net } } - public override ICredentials Credentials + public override ICredentials? Credentials { get { @@ -983,7 +961,7 @@ namespace System.Net } } - public override IWebProxy Proxy + public override IWebProxy? Proxy { get { @@ -1099,19 +1077,19 @@ namespace System.Net return Task.FromResult((Stream)_requestStream); } - public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context) + public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext? context) { context = null; return EndGetRequestStream(asyncResult); } - public Stream GetRequestStream(out TransportContext context) + public Stream GetRequestStream(out TransportContext? context) { context = null; return GetRequestStream(); } - public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) + public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state) { CheckAbort(); @@ -1163,14 +1141,14 @@ namespace System.Net var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri); bool disposeRequired = false; - HttpClient client = null; + HttpClient? client = null; try { client = GetCachedOrCreateHttpClient(out disposeRequired); if (_requestStream != null) { ArraySegment bytes = _requestStream.GetBuffer(); - request.Content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count); + request.Content = new ByteArrayContent(bytes.Array!, bytes.Offset, bytes.Count); } if (_hostUri != null) @@ -1180,12 +1158,12 @@ namespace System.Net // Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and // HttpRequestMessage.Content.Headers. - foreach (string headerName in _webHeaderCollection) + foreach (string? headerName in _webHeaderCollection) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214 { // The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers // collection and the request content headers collection for all well-known header names. And custom headers // are only allowed in the request headers collection and not in the request content headers collection. - if (IsWellKnownContentHeader(headerName)) + if (IsWellKnownContentHeader(headerName!)) { if (request.Content == null) { @@ -1193,11 +1171,11 @@ namespace System.Net request.Content = new ByteArrayContent(Array.Empty()); } - request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]); + request.Content.Headers.TryAddWithoutValidation(headerName!, _webHeaderCollection[headerName!]); } else { - request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]); + request.Headers.TryAddWithoutValidation(headerName!, _webHeaderCollection[headerName!]); } } @@ -1217,7 +1195,7 @@ namespace System.Net _sendRequestTask = client.SendAsync( request, _allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead, - _sendRequestCts.Token); + _sendRequestCts!.Token); HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false); HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer); @@ -1242,7 +1220,7 @@ namespace System.Net } } - public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) + public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state) { CheckAbort(); @@ -1387,9 +1365,9 @@ namespace System.Net } } - private bool AddRange(string rangeSpecifier, string from, string to) + private bool AddRange(string rangeSpecifier, string from, string? to) { - string curRange = _webHeaderCollection[HttpKnownHeaderNames.Range]; + string? curRange = _webHeaderCollection[HttpKnownHeaderNames.Range]; if ((curRange == null) || (curRange.Length == 0)) { @@ -1460,7 +1438,7 @@ namespace System.Net using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif - string headerValue = _webHeaderCollection[headerName]; + string? headerValue = _webHeaderCollection[headerName]; if (headerValue == null) { @@ -1494,7 +1472,7 @@ namespace System.Net #endif } - private bool TryGetHostUri(string hostName, out Uri hostUri) + private bool TryGetHostUri(string hostName, [NotNullWhen(true)] out Uri? hostUri) { string s = Address.Scheme + "://" + hostName + Address.PathAndQuery; return Uri.TryCreate(s, UriKind.Absolute, out hostUri); @@ -1519,7 +1497,7 @@ namespace System.Net } } - if (s_cachedHttpClientParameters.Matches(parameters)) + if (s_cachedHttpClientParameters!.Matches(parameters)) { return s_cachedHttpClient; } @@ -1529,9 +1507,9 @@ namespace System.Net return CreateHttpClient(parameters, this); } - private static HttpClient CreateHttpClient(HttpClientParameters parameters, HttpWebRequest request) + private static HttpClient CreateHttpClient(HttpClientParameters parameters, HttpWebRequest? request) { - HttpClient client = null; + HttpClient? client = null; try { var handler = new HttpClientHandler(); @@ -1591,11 +1569,11 @@ namespace System.Net // Set relevant properties from ServicePointManager handler.SslProtocols = (SslProtocols)parameters.SslProtocols; handler.CheckCertificateRevocationList = parameters.CheckCertificateRevocationList; - RemoteCertificateValidationCallback rcvc = parameters.ServerCertificateValidationCallback; + RemoteCertificateValidationCallback? rcvc = parameters.ServerCertificateValidationCallback; if (rcvc != null) { RemoteCertificateValidationCallback localRcvc = rcvc; - HttpWebRequest localRequest = request; + HttpWebRequest localRequest = request!; handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => localRcvc(localRequest, cert, chain, errors); } diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs index 7307c18..e7addde 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs @@ -3,11 +3,10 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; -using System.Globalization; using System.IO; using System.Net.Http; -using System.Net.Http.Headers; using System.Runtime.Serialization; using System.Text; @@ -21,14 +20,20 @@ namespace System.Net /// public class HttpWebResponse : WebResponse, ISerializable { - private HttpResponseMessage _httpResponseMessage; + private HttpResponseMessage _httpResponseMessage = null!; private readonly Uri _requestUri; private CookieCollection _cookies; - private WebHeaderCollection _webHeaderCollection = null; - private string _characterSet = null; + private WebHeaderCollection? _webHeaderCollection; + private string? _characterSet; private readonly bool _isVersionHttp11 = true; - public HttpWebResponse() { } + [Obsolete("This API supports the .NET infrastructure and is not intended to be used directly from your code.", true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public HttpWebResponse() + { + _requestUri = null!; + _cookies = null!; + } [ObsoleteAttribute("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?linkid=14202")] protected HttpWebResponse(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) @@ -46,7 +51,7 @@ namespace System.Net throw new PlatformNotSupportedException(); } - internal HttpWebResponse(HttpResponseMessage _message, Uri requestUri, CookieContainer cookieContainer) + internal HttpWebResponse(HttpResponseMessage _message, Uri requestUri, CookieContainer? cookieContainer) { _httpResponseMessage = _message; _requestUri = requestUri; @@ -74,7 +79,7 @@ namespace System.Net get { CheckDisposed(); - long? length = _httpResponseMessage.Content.Headers.ContentLength; + long? length = _httpResponseMessage.Content?.Headers.ContentLength; return length.HasValue ? length.Value : -1; } } @@ -88,8 +93,7 @@ namespace System.Net // We use TryGetValues() instead of the strongly type Headers.ContentType property so that // we return a string regardless of it being fully RFC conformant. This matches current // .NET Framework behavior. - IEnumerable values; - if (_httpResponseMessage.Content.Headers.TryGetValues("Content-Type", out values)) + if (_httpResponseMessage.Content != null && _httpResponseMessage.Content.Headers.TryGetValues("Content-Type", out IEnumerable? values)) { // In most cases, there is only one media type value as per RFC. But for completeness, we // return all values in cases of overly malformed strings. @@ -120,7 +124,12 @@ namespace System.Net get { CheckDisposed(); - return GetHeaderValueAsString(_httpResponseMessage.Content.Headers.ContentEncoding); + if (_httpResponseMessage.Content != null) + { + return GetHeaderValueAsString(_httpResponseMessage.Content.Headers.ContentEncoding); + } + + return string.Empty; } } @@ -144,7 +153,7 @@ namespace System.Net get { CheckDisposed(); - string lastmodHeaderValue = Headers["Last-Modified"]; + string? lastmodHeaderValue = Headers["Last-Modified"]; if (string.IsNullOrEmpty(lastmodHeaderValue)) { return DateTime.Now; @@ -171,7 +180,8 @@ namespace System.Net get { CheckDisposed(); - return string.IsNullOrEmpty(Headers["Server"]) ? string.Empty : Headers["Server"]; + string? server = Headers["Server"]; + return string.IsNullOrEmpty(server) ? string.Empty : server; } } @@ -222,7 +232,7 @@ namespace System.Net get { CheckDisposed(); - return _httpResponseMessage.RequestMessage.Method.Method; + return _httpResponseMessage.RequestMessage!.Method.Method; } } @@ -234,7 +244,7 @@ namespace System.Net // The underlying System.Net.Http API will automatically update // the .RequestUri property to be the final URI of the response. - return _httpResponseMessage.RequestMessage.RequestUri; + return _httpResponseMessage.RequestMessage!.RequestUri!; } } @@ -252,19 +262,19 @@ namespace System.Net get { CheckDisposed(); - return _httpResponseMessage.ReasonPhrase; + return _httpResponseMessage.ReasonPhrase ?? string.Empty; } } /// /// [To be supplied.] /// - public string CharacterSet + public string? CharacterSet { get { CheckDisposed(); - string contentType = Headers["Content-Type"]; + string? contentType = Headers["Content-Type"]; if (_characterSet == null && !string.IsNullOrWhiteSpace(contentType)) { @@ -337,14 +347,19 @@ namespace System.Net public override Stream GetResponseStream() { CheckDisposed(); - return _httpResponseMessage.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); + if (_httpResponseMessage.Content != null) + { + return _httpResponseMessage.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); + } + + return Stream.Null; } public string GetResponseHeader(string headerName) { CheckDisposed(); - string headerValue = Headers[headerName]; - return ((headerValue == null) ? string.Empty : headerValue); + string? headerValue = Headers[headerName]; + return (headerValue == null) ? string.Empty : headerValue; } public override void Close() @@ -358,7 +373,7 @@ namespace System.Net if (httpResponseMessage != null) { httpResponseMessage.Dispose(); - _httpResponseMessage = null; + _httpResponseMessage = null!; } } diff --git a/src/libraries/System.Net.Requests/src/System/Net/IWebRequestCreate.cs b/src/libraries/System.Net.Requests/src/System/Net/IWebRequestCreate.cs index d13f4d7..0f5c44d 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/IWebRequestCreate.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/IWebRequestCreate.cs @@ -2,8 +2,6 @@ // 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; - namespace System.Net { /// diff --git a/src/libraries/System.Net.Requests/src/System/Net/NetRes.cs b/src/libraries/System.Net.Requests/src/System/Net/NetRes.cs index 5be6fd5..193eb1b 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/NetRes.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/NetRes.cs @@ -8,10 +8,10 @@ namespace System.Net { internal static class NetRes { - public static string GetWebStatusCodeString(FtpStatusCode statusCode, string statusDescription) + public static string GetWebStatusCodeString(FtpStatusCode statusCode, string? statusDescription) { string webStatusCode = "(" + ((int)statusCode).ToString(NumberFormatInfo.InvariantInfo) + ")"; - string statusMessage = null; + string? statusMessage = null; switch (statusCode) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/NetworkStreamWrapper.cs b/src/libraries/System.Net.Requests/src/System/Net/NetworkStreamWrapper.cs index c339817..d881bd7 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/NetworkStreamWrapper.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/NetworkStreamWrapper.cs @@ -32,7 +32,7 @@ namespace System.Net { get { - return ((IPEndPoint)Socket.RemoteEndPoint).Address; + return ((IPEndPoint)Socket.RemoteEndPoint!).Address; } } @@ -175,7 +175,7 @@ namespace System.Net _client.Dispose(); } - public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { return _networkStream.BeginRead(buffer, offset, size, callback, state); } @@ -190,7 +190,7 @@ namespace System.Net return _networkStream.ReadAsync(buffer, offset, count, cancellationToken); } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { return _networkStream.BeginWrite(buffer, offset, size, callback, state); } diff --git a/src/libraries/System.Net.Requests/src/System/Net/ProtocolViolationException.cs b/src/libraries/System.Net.Requests/src/System/Net/ProtocolViolationException.cs index 6773fef..3451590 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/ProtocolViolationException.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/ProtocolViolationException.cs @@ -31,7 +31,7 @@ namespace System.Net /// class with the specified message. /// /// - public ProtocolViolationException(string message) : base(message) + public ProtocolViolationException(string? message) : base(message) { } diff --git a/src/libraries/System.Net.Requests/src/System/Net/RequestStream.cs b/src/libraries/System.Net.Requests/src/System/Net/RequestStream.cs index 278d85e..4717f3f 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/RequestStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/RequestStream.cs @@ -2,11 +2,8 @@ // 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.Generic; using System.Diagnostics; using System.IO; -using System.Text; using System.Threading; using System.Threading.Tasks; @@ -131,7 +128,7 @@ namespace System.Net return _buffer.WriteAsync(buffer, offset, count, cancellationToken); } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { if (buffer == null) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/TaskExtensions.cs b/src/libraries/System.Net.Requests/src/System/Net/TaskExtensions.cs index 3600c4f..b191aec 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/TaskExtensions.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/TaskExtensions.cs @@ -12,8 +12,8 @@ namespace System.Net { public static TaskCompletionSource ToApm( this Task task, - AsyncCallback callback, - object state) + AsyncCallback? callback, + object? state) { TaskCompletionSource tcs = new TaskCompletionSource(state); @@ -23,7 +23,7 @@ namespace System.Net if (completedTask.IsFaulted) { - shouldInvokeCallback = tcs.TrySetException(completedTask.Exception.InnerExceptions); + shouldInvokeCallback = tcs.TrySetException(completedTask.Exception!.InnerExceptions); } else if (completedTask.IsCanceled) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs b/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs index 7cfcaa9..a64a6ca 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs @@ -34,7 +34,7 @@ namespace System.Net /// /// Creates and returns a handle to a new timer with attached context. /// - internal abstract Timer CreateTimer(Callback callback, object context); + internal abstract Timer CreateTimer(Callback callback, object? context); } /// @@ -77,7 +77,7 @@ namespace System.Net /// /// Prototype for the callback that is called when a timer expires. /// - internal delegate void Callback(Timer timer, int timeNoticed, object context); + internal delegate void Callback(Timer timer, int timeNoticed, object? context); private const int ThreadIdleTimeoutMilliseconds = 30 * 1000; private const int CacheScanPerIterations = 32; @@ -117,15 +117,15 @@ namespace System.Net throw new ArgumentOutOfRangeException(nameof(durationMilliseconds)); } - TimerQueue queue; + TimerQueue? queue; object key = durationMilliseconds; // Box once. - WeakReference weakQueue = (WeakReference)s_queuesCache[key]; - if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null) + WeakReference? weakQueue = (WeakReference?)s_queuesCache[key]; + if (weakQueue == null || (queue = (TimerQueue?)weakQueue.Target) == null) { lock (s_newQueues) { - weakQueue = (WeakReference)s_queuesCache[key]; - if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null) + weakQueue = (WeakReference?)s_queuesCache[key]; + if (weakQueue == null || (queue = (TimerQueue?)weakQueue.Target) == null) { queue = new TimerQueue(durationMilliseconds); weakQueue = new WeakReference(queue); @@ -141,7 +141,7 @@ namespace System.Net while (e.MoveNext()) { DictionaryEntry pair = e.Entry; - if (((WeakReference)pair.Value).Target == null) + if (((WeakReference)pair.Value!).Target == null) { garbage.Add(pair.Key); } @@ -192,7 +192,7 @@ namespace System.Net /// /// Creates new timers. This method is thread-safe. /// - internal override Timer CreateTimer(Callback callback, object context) + internal override Timer CreateTimer(Callback callback, object? context) { TimerNode timer = new TimerNode(callback, context, Duration, _timers); @@ -200,7 +200,7 @@ namespace System.Net bool needProd = false; lock (_timers) { - if (!(_timers.Prev.Next == _timers)) + if (!(_timers.Prev!.Next == _timers)) { NetEventSource.Fail(this, $"Tail corruption."); } @@ -240,12 +240,12 @@ namespace System.Net while (true) { // Check if we got to the end. If so, free the handle. - TimerNode timer = _timers.Next; + TimerNode timer = _timers.Next!; if (timer == _timers) { lock (_timers) { - timer = _timers.Next; + timer = _timers.Next!; if (timer == _timers) { if (_thisHandle != IntPtr.Zero) @@ -279,7 +279,7 @@ namespace System.Net /// /// Always returns a dummy infinite timer. /// - internal override Timer CreateTimer(Callback callback, object context) => new InfiniteTimer(); + internal override Timer CreateTimer(Callback callback, object? context) => new InfiniteTimer(); } /// @@ -288,11 +288,11 @@ namespace System.Net private class TimerNode : Timer { private TimerState _timerState; - private Callback _callback; - private object _context; - private readonly object _queueLock; - private TimerNode _next; - private TimerNode _prev; + private Callback? _callback; + private object? _context; + private readonly object _queueLock = null!; + private TimerNode? _next; + private TimerNode? _prev; /// /// Status of the timer. @@ -305,7 +305,7 @@ namespace System.Net Sentinel } - internal TimerNode(Callback callback, object context, int durationMilliseconds, object queueLock) : base(durationMilliseconds) + internal TimerNode(Callback callback, object? context, int durationMilliseconds, object queueLock) : base(durationMilliseconds) { if (callback != null) { @@ -325,13 +325,13 @@ namespace System.Net internal override bool HasExpired => _timerState == TimerState.Fired; - internal TimerNode Next + internal TimerNode? Next { get { return _next; } set { _next = value; } } - internal TimerNode Prev + internal TimerNode? Prev { get { return _prev; } set { _prev = value; } @@ -351,8 +351,8 @@ namespace System.Net // Remove it from the list. This keeps the list from getting too big when there are a lot of rapid creations // and cancellations. This is done before setting it to Cancelled to try to prevent the Fire() loop from // seeing it, or if it does, of having to take a lock to synchronize with the state of the list. - Next.Prev = Prev; - Prev.Next = Next; + Next!.Prev = Prev; + Prev!.Next = Next; // Just cleanup. Doesn't need to be in the lock but is easier to have here. Next = null; @@ -406,8 +406,8 @@ namespace System.Net _timerState = TimerState.Fired; // Remove it from the list. - Next.Prev = Prev; - Prev.Next = Next; + Next!.Prev = Prev; + Prev!.Next = Next; Next = null; Prev = null; @@ -419,8 +419,8 @@ namespace System.Net { try { - Callback callback = _callback; - object context = _context; + Callback callback = _callback!; + object? context = _context; _callback = null; _context = null; callback(this, nowMilliseconds, context); @@ -517,7 +517,7 @@ namespace System.Net { lock (s_newQueues) { - for (LinkedListNode node = s_newQueues.First; node != null; node = s_newQueues.First) + for (LinkedListNode? node = s_newQueues.First; node != null; node = s_newQueues.First) { s_newQueues.Remove(node); s_queues.AddLast(node); @@ -528,12 +528,12 @@ namespace System.Net int now = Environment.TickCount; int nextTick = 0; bool haveNextTick = false; - for (LinkedListNode node = s_queues.First; node != null; /* node = node.Next must be done in the body */) + for (LinkedListNode? node = s_queues.First; node != null; /* node = node.Next must be done in the body */) { - TimerQueue queue = (TimerQueue)node.Value.Target; + TimerQueue? queue = (TimerQueue?)node.Value.Target; if (queue == null) { - LinkedListNode next = node.Next; + LinkedListNode? next = node.Next; s_queues.Remove(node); node = next; continue; diff --git a/src/libraries/System.Net.Requests/src/System/Net/WebException.cs b/src/libraries/System.Net.Requests/src/System/Net/WebException.cs index 5218965..88fa586 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/WebException.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/WebException.cs @@ -17,31 +17,31 @@ namespace System.Net private const WebExceptionStatus DefaultStatus = WebExceptionStatus.UnknownError; private readonly WebExceptionStatus _status = DefaultStatus; - private readonly WebResponse _response = null; + private readonly WebResponse? _response; public WebException() { } - public WebException(string message) : + public WebException(string? message) : base(message) { } - public WebException(string message, Exception innerException) : + public WebException(string? message, Exception? innerException) : this(message, innerException, DefaultStatus, null) { } - public WebException(string message, WebExceptionStatus status) : + public WebException(string? message, WebExceptionStatus status) : this(message, null, status, null) { } - public WebException(string message, - Exception innerException, + public WebException(string? message, + Exception? innerException, WebExceptionStatus status, - WebResponse response) : + WebResponse? response) : base(message, innerException) { _status = status; @@ -58,21 +58,9 @@ namespace System.Net { } - public WebExceptionStatus Status - { - get - { - return _status; - } - } + public WebExceptionStatus Status => _status; - public WebResponse Response - { - get - { - return _response; - } - } + public WebResponse? Response => _response; void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { @@ -109,7 +97,7 @@ namespace System.Net private static WebExceptionStatus GetStatusFromExceptionHelper(HttpRequestException ex) { - SocketException socketEx = ex.InnerException as SocketException; + SocketException? socketEx = ex.InnerException as SocketException; if (socketEx is null) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/WebExceptionPal.Unix.cs b/src/libraries/System.Net.Requests/src/System/Net/WebExceptionPal.Unix.cs index 875ac72..2059f41 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/WebExceptionPal.Unix.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/WebExceptionPal.Unix.cs @@ -2,7 +2,6 @@ // 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.Net.Http; namespace System.Net diff --git a/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs index 976b6ef..3b1d805 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net.Cache; using System.Net.Http; @@ -28,7 +29,7 @@ namespace System.Net } } - private static List s_prefixList; + private static List? s_prefixList; private static object s_internalSyncObject = new object(); internal const int DefaultTimeoutMilliseconds = 100 * 1000; @@ -69,7 +70,7 @@ namespace System.Net if (NetEventSource.IsEnabled) NetEventSource.Enter(null, requestUri); string LookupUri; - WebRequestPrefixElement Current = null; + WebRequestPrefixElement? Current = null; bool Found = false; if (!useUriBase) @@ -121,12 +122,10 @@ namespace System.Net } } - WebRequest webRequest = null; - if (Found) { // We found a match, so just call the creator and return what it does. - webRequest = Current.Creator.Create(requestUri); + WebRequest webRequest = Current!.Creator.Create(requestUri); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, webRequest); return webRequest; } @@ -261,8 +260,7 @@ namespace System.Net // As AbsoluteUri is used later for Create, account for formating changes // like Unicode escaping, default ports, etc. - Uri tempUri; - if (Uri.TryCreate(prefix, UriKind.Absolute, out tempUri)) + if (Uri.TryCreate(prefix, UriKind.Absolute, out Uri? tempUri)) { string cookedUri = tempUri.AbsoluteUri; @@ -385,15 +383,15 @@ namespace System.Net } } - public static RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache); + public static RequestCachePolicy? DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache); - public virtual RequestCachePolicy CachePolicy { get; set; } + public virtual RequestCachePolicy? CachePolicy { get; set; } public AuthenticationLevel AuthenticationLevel { get; set; } = AuthenticationLevel.MutualAuthRequested; public TokenImpersonationLevel ImpersonationLevel { get; set; } = TokenImpersonationLevel.Delegation; - public virtual string ConnectionGroupName + public virtual string? ConnectionGroupName { get { @@ -449,7 +447,7 @@ namespace System.Net } } - public virtual string ContentType + public virtual string? ContentType { get { @@ -461,7 +459,8 @@ namespace System.Net } } - public virtual ICredentials Credentials + [DisallowNull] + public virtual ICredentials? Credentials { get { @@ -507,7 +506,7 @@ namespace System.Net throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } - public virtual IAsyncResult BeginGetResponse(AsyncCallback callback, object state) + public virtual IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state) { throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } @@ -517,7 +516,7 @@ namespace System.Net throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } - public virtual IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) + public virtual IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state) { throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } @@ -537,8 +536,8 @@ namespace System.Net // Unwrap() that it's worth it to just rely on Task.Run and accept the closure/delegate. return Task.Run(() => Task.Factory.FromAsync( - (callback, state) => ((WebRequest)state).BeginGetRequestStream(callback, state), - iar => ((WebRequest)iar.AsyncState).EndGetRequestStream(iar), + (callback, state) => ((WebRequest)state!).BeginGetRequestStream(callback, state), + iar => ((WebRequest)iar.AsyncState!).EndGetRequestStream(iar), this)); } @@ -547,8 +546,8 @@ namespace System.Net // See comment in GetRequestStreamAsync(). Same logic applies here. return Task.Run(() => Task.Factory.FromAsync( - (callback, state) => ((WebRequest)state).BeginGetResponse(callback, state), - iar => ((WebRequest)iar.AsyncState).EndGetResponse(iar), + (callback, state) => ((WebRequest)state!).BeginGetResponse(callback, state), + iar => ((WebRequest)iar.AsyncState!).EndGetResponse(iar), this)); } @@ -557,17 +556,14 @@ namespace System.Net throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } - private static IWebProxy s_DefaultWebProxy; + private static IWebProxy? s_DefaultWebProxy; private static bool s_DefaultWebProxyInitialized; public static IWebProxy GetSystemWebProxy() => HttpClient.DefaultProxy; - public static IWebProxy DefaultWebProxy + public static IWebProxy? DefaultWebProxy { - get - { - return LazyInitializer.EnsureInitialized(ref s_DefaultWebProxy, ref s_DefaultWebProxyInitialized, ref s_internalSyncObject, () => GetSystemWebProxy()); - } + get => LazyInitializer.EnsureInitialized(ref s_DefaultWebProxy, ref s_DefaultWebProxyInitialized, ref s_internalSyncObject, () => GetSystemWebProxy()); set { lock (s_internalSyncObject) @@ -590,7 +586,7 @@ namespace System.Net } } - public virtual IWebProxy Proxy + public virtual IWebProxy? Proxy { get { diff --git a/src/libraries/System.Net.Requests/tests/AuthenticationManagerTest.cs b/src/libraries/System.Net.Requests/tests/AuthenticationManagerTest.cs index a54598b..2aacd2b 100644 --- a/src/libraries/System.Net.Requests/tests/AuthenticationManagerTest.cs +++ b/src/libraries/System.Net.Requests/tests/AuthenticationManagerTest.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Collections; -using System.Diagnostics; using Microsoft.DotNet.RemoteExecutor; using Xunit; @@ -27,6 +26,13 @@ namespace System.Net.Tests } [Fact] + public void Unregister_Null_Throws() + { + Assert.Throws(() => AuthenticationManager.Unregister((IAuthenticationModule)null)); + Assert.Throws(() => AuthenticationManager.Unregister((string)null)); + } + + [Fact] public void Register_Unregister_ModuleCountUnchanged() { RemoteExecutor.Invoke(() => diff --git a/src/libraries/System.Net.Requests/tests/FileWebRequestTest.cs b/src/libraries/System.Net.Requests/tests/FileWebRequestTest.cs index d55182f..0d70373 100644 --- a/src/libraries/System.Net.Requests/tests/FileWebRequestTest.cs +++ b/src/libraries/System.Net.Requests/tests/FileWebRequestTest.cs @@ -2,11 +2,7 @@ // 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.Http; -using System.Net.Test.Common; -using System.Text; using System.Threading.Tasks; using Xunit; diff --git a/src/libraries/System.Net.Requests/tests/GlobalProxySelectionTest.cs b/src/libraries/System.Net.Requests/tests/GlobalProxySelectionTest.cs index 4e13405..01613fb 100644 --- a/src/libraries/System.Net.Requests/tests/GlobalProxySelectionTest.cs +++ b/src/libraries/System.Net.Requests/tests/GlobalProxySelectionTest.cs @@ -2,7 +2,6 @@ // 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; using Microsoft.DotNet.RemoteExecutor; using Xunit; diff --git a/src/libraries/System.Net.Requests/tests/HttpRequestCachePolicyTest.cs b/src/libraries/System.Net.Requests/tests/HttpRequestCachePolicyTest.cs index d8c2553..a224053 100644 --- a/src/libraries/System.Net.Requests/tests/HttpRequestCachePolicyTest.cs +++ b/src/libraries/System.Net.Requests/tests/HttpRequestCachePolicyTest.cs @@ -2,7 +2,6 @@ // 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.Generic; using System.Net.Cache; diff --git a/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs b/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs index b69c855..69eb963 100644 --- a/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs +++ b/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs @@ -9,11 +9,9 @@ using System.IO; using System.Linq; using System.Net.Cache; using System.Net.Http; -using System.Net.Security; using System.Net.Sockets; using System.Net.Test.Common; using System.Runtime.Serialization.Formatters.Binary; -using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json; diff --git a/src/libraries/System.Net.Requests/tests/HttpWebResponseHeaderTest.cs b/src/libraries/System.Net.Requests/tests/HttpWebResponseHeaderTest.cs index 2d48cf8..ae72865 100644 --- a/src/libraries/System.Net.Requests/tests/HttpWebResponseHeaderTest.cs +++ b/src/libraries/System.Net.Requests/tests/HttpWebResponseHeaderTest.cs @@ -9,7 +9,6 @@ using System.Threading.Tasks; using System.Runtime.Serialization.Formatters.Binary; using Xunit; -using Xunit.Abstractions; using System.Runtime.Serialization; namespace System.Net.Tests diff --git a/src/libraries/System.Net.Requests/tests/WebRequestTest.cs b/src/libraries/System.Net.Requests/tests/WebRequestTest.cs index c8fe869..e558dbd 100644 --- a/src/libraries/System.Net.Requests/tests/WebRequestTest.cs +++ b/src/libraries/System.Net.Requests/tests/WebRequestTest.cs @@ -2,7 +2,6 @@ // 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; using Microsoft.DotNet.RemoteExecutor; using Xunit; diff --git a/src/libraries/System.Net.Security/src/System/Net/HelperAsyncResults.cs b/src/libraries/System.Net.Security/src/System/Net/HelperAsyncResults.cs index 3350245..5501d65 100644 --- a/src/libraries/System.Net.Security/src/System/Net/HelperAsyncResults.cs +++ b/src/libraries/System.Net.Security/src/System/Net/HelperAsyncResults.cs @@ -62,7 +62,7 @@ namespace System.Net _callback = callback; } - internal object AsyncObject => UserAsyncResult.AsyncObject; + internal object? AsyncObject => UserAsyncResult.AsyncObject; // // Notify protocol so a next stage could be started. diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs index 7bc1fe8..4c748bd 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs @@ -387,7 +387,7 @@ namespace System.Net.Security try { - NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject; + NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject!; TaskToApm.End(transportResult); if (asyncRequest.Count == 0) { @@ -414,7 +414,7 @@ namespace System.Net.Security // Async ONLY completion. try { - NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject; + NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject!; BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult; // This is an optimization to avoid an additional callback. diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegoState.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegoState.cs index abc42df..b59ffb9 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegoState.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegoState.cs @@ -708,7 +708,7 @@ namespace System.Net.Security // Async completion. try { - NegoState authState = (NegoState)lazyResult.AsyncObject; + NegoState authState = (NegoState)lazyResult.AsyncObject!; authState._framer!.EndWriteMessage(transportResult); // Special case for an error notification. @@ -749,7 +749,7 @@ namespace System.Net.Security // Async completion. try { - NegoState authState = (NegoState)lazyResult.AsyncObject; + NegoState authState = (NegoState)lazyResult.AsyncObject!; byte[]? message = authState._framer!.EndReadMessage(transportResult); authState.ProcessReceivedBlob(message, lazyResult); } diff --git a/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj b/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj index f1941c2..89b1058 100644 --- a/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj +++ b/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj @@ -2,7 +2,7 @@ System.Net.Sockets true - $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix + $(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Windows_NT enable diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs index 65cab78..004c059 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs @@ -36,7 +36,7 @@ namespace System.Net.Sockets // since the overlapped calls may complete asynchronously. internal void SetUnmanagedStructures(object? objectsToPin) { - Socket s = (Socket)AsyncObject; + Socket s = (Socket)AsyncObject!; // Bind the Win32 Socket Handle to the ThreadPool Debug.Assert(s != null, "m_CurrentSocket is null"); @@ -149,7 +149,7 @@ namespace System.Net.Sockets if (success) { // Synchronous success. - Socket socket = (Socket)AsyncObject; + Socket socket = (Socket)AsyncObject!; if (socket.SafeHandle.SkipCompletionPortOnSuccess) { // The socket handle is configured to skip completion on success, diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Unix.cs index af40673..da31c75 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Unix.cs @@ -24,7 +24,7 @@ namespace System.Net.Sockets var errorCode = (SocketError)ErrorCode; if (errorCode == SocketError.Success) { - var socket = (Socket)AsyncObject; + var socket = (Socket)AsyncObject!; socket.SetToConnected(); return socket; } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Windows.cs index f848973..2aad89d 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Windows.cs @@ -11,7 +11,7 @@ namespace System.Net.Sockets internal override unsafe object? PostCompletion(int numBytes) { SocketError errorCode = (SocketError)ErrorCode; - Socket socket = (Socket)AsyncObject; + Socket socket = (Socket)AsyncObject!; if (errorCode == SocketError.Success) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/DisconnectOverlappedAsyncResult.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/DisconnectOverlappedAsyncResult.cs index 0ad746c..8576902 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/DisconnectOverlappedAsyncResult.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/DisconnectOverlappedAsyncResult.cs @@ -18,7 +18,7 @@ namespace System.Net.Sockets { if (ErrorCode == (int)SocketError.Success) { - Socket socket = (Socket)AsyncObject; + Socket socket = (Socket)AsyncObject!; socket.SetToDisconnected(); socket._remoteEndPoint = null; } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs index f9da58f..4311037 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs @@ -37,7 +37,7 @@ namespace System.Net.Sockets _wsaBufferArray = new byte[sizeof(WSABuffer)]; bool ipv4, ipv6; - Socket.GetIPProtocolInformation(((Socket)AsyncObject).AddressFamily, socketAddress, out ipv4, out ipv6); + Socket.GetIPProtocolInformation(((Socket)AsyncObject!).AddressFamily, socketAddress, out ipv4, out ipv6); // Prepare control buffer. if (ipv4) diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs index 8c116cd..b012817 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs @@ -1846,7 +1846,7 @@ namespace System.Net.Sockets asyncResult.SocketAddress = socketAddress; bool isIPv4, isIPv6; - Socket.GetIPProtocolInformation(((Socket)asyncResult.AsyncObject).AddressFamily, socketAddress, out isIPv4, out isIPv6); + Socket.GetIPProtocolInformation(((Socket)asyncResult.AsyncObject!).AddressFamily, socketAddress, out isIPv4, out isIPv6); int socketAddressSize = socketAddress.InternalSize; int bytesReceived;