// 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
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.
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;
}
// Interface method to return the original async object.
- internal object AsyncObject
+ internal object? AsyncObject
{
get
{
// 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
{
ServicePointManager.CheckCertificateRevocationList);
}
- public IAsyncResult BeginAuthenticateAsClient(AsyncCallback asyncCallback, object state)
+ public IAsyncResult BeginAuthenticateAsClient(AsyncCallback? asyncCallback, object? state)
{
return _sslStream.BeginAuthenticateAsClient(
_host,
_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);
}
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);
}
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) { }
{
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 { } }
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; }
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; }
}
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; }
}
{
[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 { } }
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) { }
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; } }
{
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) { }
}
{
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) { }
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; }
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Net.Requests.cs" />
<AssemblyName>System.Net.Requests</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System\Net\AuthenticationManager.cs" />
{
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));
}
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<IAuthenticationModule>().GetEnumerator();
{
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;
_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; }
// 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)
// 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;
}
}
- 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)
{
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,
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;
/// 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
// 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)
{
}
}
- Stream stream = null;
+ Stream? stream = null;
bool isReturn = PostSendCommandProcessing(ref stream);
if (isReturn)
{
return null;
}
- private bool PostSendCommandProcessing(ref Stream stream)
+ private bool PostSendCommandProcessing(ref Stream? stream)
{
if (_doRead)
{
// 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;
// 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;
}
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
_doRead = false;
PipelineInstruction result;
- PipelineEntry entry;
+ PipelineEntry? entry;
if (_index == -1)
entry = null;
else
// 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);
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;
}
private static void ReadCallback(IAsyncResult asyncResult)
{
- ReceiveState state = (ReceiveState)asyncResult.AsyncState;
+ ReceiveState state = (ReceiveState)asyncResult.AsyncState!;
try
{
Stream stream = (Stream)state.Connection;
private static void WriteCallback(IAsyncResult asyncResult)
{
- CommandStream connection = (CommandStream)asyncResult.AsyncState;
+ CommandStream connection = (CommandStream)asyncResult.AsyncState!;
try
{
try
{
throw;
}
- Stream stream = null;
+ Stream? stream = null;
if (connection.PostSendCommandProcessing(ref stream))
return;
connection.ContinueCommandPipeline();
/// Uses the Encoding <code>encoding</code> to transform the bytes received into a string to be
/// returned in the GeneralResponseDescription's StatusDescription field.
/// </summary>
- private ResponseDescription ReceiveCommandResponse()
+ private ResponseDescription? ReceiveCommandResponse()
{
// These are the things that will be needed to maintain state.
ReceiveState state = new ReceiveState(this);
{
_currentResponseDescription = state.Resp;
}
- Stream stream = null;
+ Stream? stream = null;
if (PostReadCommandProcessing(ref stream))
return;
ContinueCommandPipeline();
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); } }
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;
internal bool Aborted => _aborted != 0;
- public override string ConnectionGroupName { get; set; }
+ public override string? ConnectionGroupName { get; set; }
public override long ContentLength
{
}
}
- 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;
public override bool PreAuthenticate { get; set; }
- public override IWebProxy Proxy { get; set; }
+ public override IWebProxy? Proxy { get; set; }
public override int Timeout
{
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<Stream> t = Task.Factory.StartNew(s => ((FileWebRequest)s).CreateWriteStream(),
+ Task<Stream> t = Task.Factory.StartNew(s => ((FileWebRequest)s!).CreateWriteStream(),
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
return TaskToApm.Begin(t, callback, state);
}
CheckAndMarkAsyncGetRequestStreamPending();
return Task.Factory.StartNew(s =>
{
- FileWebRequest thisRef = (FileWebRequest)s;
+ FileWebRequest thisRef = (FileWebRequest)s!;
Stream writeStream = thisRef.CreateWriteStream();
thisRef._writePending = false;
return writeStream;
}
}
- public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
+ public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state)
{
CheckAndMarkAsyncGetResponsePending();
- Task<WebResponse> t = Task.Factory.StartNew(s => ((FileWebRequest)s).CreateResponse(),
+ Task<WebResponse> t = Task.Factory.StartNew(s => ((FileWebRequest)s!).CreateResponse(),
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
return TaskToApm.Begin(t, callback, state);
}
CheckAndMarkAsyncGetResponsePending();
return Task.Factory.StartNew(s =>
{
- var thisRef = (FileWebRequest)s;
+ var thisRef = (FileWebRequest)s!;
WebResponse response = thisRef.CreateResponse();
_readPending = false;
return response;
}
}
- 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
}
}
- 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
{
_closed = true;
- Stream chkStream = _stream;
+ Stream? chkStream = _stream;
if (chkStream != null)
{
chkStream.Close();
- _stream = null;
+ _stream = null!;
}
}
}
// 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;
/// </summary>
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
{
/// </summary>
internal void AbortConnect()
{
- Socket socket = _dataSocket;
+ Socket? socket = _dataSocket;
if (socket != null)
{
try
/// </summary>
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);
/// </summary>
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)
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)
// 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();
//
if (_tlsStream != null)
{
- stream = new FtpDataStream(_tlsStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable());
+ stream = new FtpDataStream(_tlsStream, (FtpWebRequest)_request!, IsFtpDataStreamWriteable());
_tlsStream = null;
return PipelineInstruction.GiveStream;
}
if (UsingSecureStream)
{
- FtpWebRequest request = (FtpWebRequest)_request;
+ FtpWebRequest request = (FtpWebRequest)_request!;
TlsStream tlsStream = new TlsStream(networkStream, _dataSocket, request.RequestUri.Host, request.ClientCertificates);
networkStream = tlsStream;
}
}
- stream = new FtpDataStream(networkStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable());
+ stream = new FtpDataStream(networkStream, (FtpWebRequest)_request!, IsFtpDataStreamWriteable());
return PipelineInstruction.GiveStream;
}
// 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}");
//
// 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)
{
}
// 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);
// 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();
}
// 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)
{
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
{
if (entry.Command == "PWD\r\n" && !entry.HasFlag(PipelineEntryFlags.UserCommand))
{
- _loginDirectory = GetLoginDirectory(response.StatusDescription);
+ _loginDirectory = GetLoginDirectory(response.StatusDescription!);
}
}
// Asserting we have some positive response
if (_loginState != FtpLoginState.LoggedIn)
{
- Credentials = request.Credentials.GetCredential(request.RequestUri, "basic");
+ Credentials = request.Credentials!.GetCredential(request.RequestUri, "basic");
_welcomeMessage = new StringBuilder();
_exitMessage = new StringBuilder();
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)
}
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;
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);
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
}
}
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);
{
get
{
- return _responseUri;
+ return _responseUri!;
}
}
/// <summary>
/// <para>Returns the server message sent before user credentials are sent</para>
/// </summary>
- internal string BannerMessage
+ internal string? BannerMessage
{
get
{
/// <summary>
/// <para>Returns the server message sent after user credentials are sent</para>
/// </summary>
- internal string WelcomeMessage
+ internal string? WelcomeMessage
{
get
{
/// <summary>
/// <para>Returns the exit sent message on shutdown</para>
/// </summary>
- internal string ExitMessage
+ internal string? ExitMessage
{
get
{
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));
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);
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);
/// <summary>
/// <para>Formats a simple FTP command + parameter in correct pre-wire format</para>
/// </summary>
- 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);
/// </summary>
private TriState IsFtpDataStreamWriteable()
{
- FtpWebRequest request = _request as FtpWebRequest;
+ FtpWebRequest? request = _request as FtpWebRequest;
if (request != null)
{
if (request.MethodInfo.IsUpload)
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
private void AsyncReadCallback(IAsyncResult ar)
{
- LazyAsyncResult userResult = (LazyAsyncResult)ar.AsyncState;
+ LazyAsyncResult userResult = (LazyAsyncResult)ar.AsyncState!;
try
{
try
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);
{
try
{
- object result = ((LazyAsyncResult)ar).InternalWaitForCompletion();
+ object result = ((LazyAsyncResult)ar).InternalWaitForCompletion()!;
if (result is Exception e)
{
}
}
- 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
// 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;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
-using System.Threading.Tasks;
+using System.Diagnostics.CodeAnalysis;
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;
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;
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
}
}
- public static new RequestCachePolicy DefaultCachePolicy
+ public static new RequestCachePolicy? DefaultCachePolicy
{
get
{
/// Not allowed to be changed once request is started.
/// </para>
/// </summary>
- public string RenameTo
+ [DisallowNull]
+ public string? RenameTo
{
get
{
/// <summary>
/// <para>Used for clear text authentication with FTP server</para>
/// </summary>
- public override ICredentials Credentials
+ [DisallowNull]
+ public override ICredentials? Credentials
{
get
{
}
}
- public override IWebProxy Proxy
+ public override IWebProxy? Proxy
{
get
{
}
}
- public override string ConnectionGroupName
+ public override string? ConnectionGroupName
{
get
{
}
}
- public ServicePoint ServicePoint
- {
- get
- {
- if (_servicePoint == null)
- {
- _servicePoint = ServicePointManager.FindServicePoint(_uri);
- }
- return _servicePoint;
- }
- }
+ public ServicePoint ServicePoint => _servicePoint ??= ServicePointManager.FindServicePoint(_uri);
internal bool Aborted
{
_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)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _ftpWebResponse);
}
- return _ftpWebResponse;
+ return _ftpWebResponse!;
}
/// <summary>
/// <para>Used to query for the Response of an FTP request [async version]</para>
/// </summary>
- public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
+ public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
- ContextAwareResult asyncResult;
+ ContextAwareResult? asyncResult;
try
{
{
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));
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
- return _ftpWebResponse;
+ return _ftpWebResponse!;
}
/// <summary>
FinishRequestStage(RequestStage.WriteReady);
CheckError();
- if (_stream.CanTimeout)
+ if (_stream!.CanTimeout)
{
_stream.WriteTimeout = ReadWriteTimeout;
_stream.ReadTimeout = ReadWriteTimeout;
/// <summary>
/// <para>Used to query for the Request stream of an FTP Request [async version]</para>
/// </summary>
- public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
+ public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
- ContextAwareResult asyncResult = null;
+ ContextAwareResult? asyncResult = null;
try
{
if (_getRequestStreamStarted)
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
- Stream requestStream = null;
+ Stream? requestStream = null;
try
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
}
- LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
+ LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult;
if (castedAsyncResult == null)
{
requestStream = _stream;
castedAsyncResult.EndCalled = true;
- if (requestStream.CanTimeout)
+ if (requestStream!.CanTimeout)
{
requestStream.WriteTimeout = ReadWriteTimeout;
requestStream.ReadTimeout = ReadWriteTimeout;
while (true)
{
- FtpControlStream connection = _connection;
+ FtpControlStream? connection = _connection;
if (connection == null)
{
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)
private Exception TranslateConnectException(Exception e)
{
- SocketException se = e as SocketException;
+ SocketException? se = e as SocketException;
if (se != null)
{
if (se.SocketErrorCode == SocketError.HostNotFound)
// 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)
{
}
}
- return stream;
+ return stream!;
}
/// <summary>
/// <para>Because this is called from the timer thread, neither it nor any methods it calls can call user code.</para>
/// </summary>
- 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");
throw exception;
}
- FtpControlStream connection = _connection;
+ FtpControlStream? connection = _connection;
if (_exception == null)
{
if (exception is WebException)
}
}
- internal void RequestCallback(object obj)
+ internal void RequestCallback(object? obj)
{
if (_async)
AsyncRequestCallback(obj);
//
// 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);
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}");
}
else
{
- FtpControlStream connection = _connection;
+ FtpControlStream? connection = _connection;
if (connection != null)
{
// 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;
//
// 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);
// 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;
stage = RequestStage.ReleaseConnection;
RequestStage prev;
- LazyAsyncResult writeResult;
- LazyAsyncResult readResult;
- FtpControlStream connection;
+ LazyAsyncResult? writeResult;
+ LazyAsyncResult? readResult;
+ FtpControlStream? connection;
lock (_syncObject)
{
!_aborted &&
prev != RequestStage.ReadReady &&
_methodInfo.IsDownload &&
- !_ftpWebResponse.IsFromCache)
+ !_ftpWebResponse!.IsFromCache)
{
return prev;
}
try
{
- Stream stream;
- FtpControlStream connection;
+ Stream? stream;
+ FtpControlStream? connection;
lock (_syncObject)
{
if (_requestStage >= RequestStage.ReleaseConnection)
}
}
- public override RequestCachePolicy CachePolicy
+ public override RequestCachePolicy? CachePolicy
{
get
{
}
// NOT SUPPORTED method
- public override string ContentType
+ public override string? ContentType
{
get
{
/// <summary>
/// <para>Creates an FTP WebResponse based off the responseStream and our active Connection</para>
/// </summary>
- private void EnsureFtpWebResponse(Exception exception)
+ private void EnsureFtpWebResponse(Exception? exception)
{
if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null))
{
{
if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null))
{
- Stream responseStream = _stream;
+ Stream? responseStream = _stream;
if (_methodInfo.IsUpload)
{
_stream.WriteTimeout = ReadWriteTimeout;
}
- FtpControlStream connection = _connection;
+ FtpControlStream? connection = _connection;
long contentLength = connection != null ? connection.ContentLength : -1;
if (responseStream == null)
}
else
{
- _requestCompleteAsyncResult.InternalWaitForCompletion();
+ _requestCompleteAsyncResult!.InternalWaitForCompletion();
CheckError();
}
}
else
{
- FtpControlStream connection = _connection;
+ FtpControlStream? connection = _connection;
if (connection != null)
connection.Abort(ExceptionHelper.RequestAbortedException);
}
/// </summary>
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);
_exitMessage = exitMessage;
}
- internal void UpdateStatus(FtpStatusCode statusCode, string statusLine, string exitMessage)
+ internal void UpdateStatus(FtpStatusCode statusCode, string? statusLine, string? exitMessage)
{
_statusCode = statusCode;
_statusLine = statusLine;
public override Stream GetResponseStream()
{
- Stream responseStream = null;
+ Stream? responseStream = null;
if (_responseStream != null)
{
}
}
- internal void SetResponseStream(Stream stream)
+ internal void SetResponseStream(Stream? stream)
{
if (stream == null || stream == Stream.Null || stream is EmptyStream)
return;
/// <summary>
/// <para>Last status line retrieved</para>
/// </summary>
- public string StatusDescription
+ public string? StatusDescription
{
get
{
/// <summary>
/// <para>Returns the server message sent before user credentials are sent</para>
/// </summary>
- public string BannerMessage
+ public string? BannerMessage
{
get
{
/// <summary>
/// <para>Returns the server message sent after user credentials are sent</para>
/// </summary>
- public string WelcomeMessage
+ public string? WelcomeMessage
{
get
{
/// <summary>
/// <para>Returns the exit sent message on shutdown</para>
/// </summary>
- public string ExitMessage
+ public string? ExitMessage
{
get
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.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
}
}
}
// 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;
using System.Runtime.Serialization;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
-using System.Text;
using System.Threading;
using System.Threading.Tasks;
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
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<HttpResponseMessage> _sendRequestTask;
+ private Task<HttpResponseMessage>? _sendRequestTask;
private static int _defaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
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<Stream> _requestStreamOperation = null;
- private TaskCompletionSource<WebResponse> _responseOperation = null;
- private AsyncCallback _requestStreamCallback = null;
- private AsyncCallback _responseCallback = null;
+ private RequestStream? _requestStream;
+ private TaskCompletionSource<Stream>? _requestStreamOperation;
+ private TaskCompletionSource<WebResponse>? _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]
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)
{
_requestUri = uri;
}
- private void SetSpecialHeaders(string HeaderName, string value)
+ private void SetSpecialHeaders(string HeaderName, string? value)
{
_webHeaderCollection.Remove(HeaderName);
if (!string.IsNullOrEmpty(value))
}
}
- public string Accept
+ public string? Accept
{
get
{
}
}
- public override string ContentType
+ public override string? ContentType
{
get
{
}
}
- public string UserAgent
+ public string? UserAgent
{
get
{
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));
/// Gets or sets the value of the Referer header.
/// </para>
/// </devdoc>
- public string Referer
+ public string? Referer
{
get
{
/// <devdoc>
/// <para>Sets the media type header</para>
/// </devdoc>
- public string MediaType
+ public string? MediaType
{
get;
set;
/// Gets or sets the value of the Transfer-Encoding header. Setting null clears it out.
/// </para>
/// </devdoc>
- public string TransferEncoding
+ public string? TransferEncoding
{
get
{
}
}
- public override string ConnectionGroupName { get; set; }
+ public override string? ConnectionGroupName { get; set; }
public override bool PreAuthenticate
{
}
}
- public string Connection
+ public string? Connection
{
get
{
Returns: The value of the Expect on get.
*/
- public string Expect
+ public string? Expect
{
get
{
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
{
}
}
- public HttpContinueDelegate ContinueDelegate
+ public HttpContinueDelegate? ContinueDelegate
{
// Nop since the underlying API do not expose 100 continue.
get
}
}
- 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,
//
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
}
}
- public virtual CookieContainer CookieContainer
+ public virtual CookieContainer? CookieContainer
{
get
{
}
}
- public override ICredentials Credentials
+ public override ICredentials? Credentials
{
get
{
}
}
- public override IWebProxy Proxy
+ public override IWebProxy? Proxy
{
get
{
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();
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<byte> 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)
// 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)
{
request.Content = new ByteArrayContent(Array.Empty<byte>());
}
- 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!]);
}
}
_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);
}
}
- public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
+ public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state)
{
CheckAbort();
}
}
- 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))
{
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
- string headerValue = _webHeaderCollection[headerName];
+ string? headerValue = _webHeaderCollection[headerName];
if (headerValue == null)
{
#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);
}
}
- if (s_cachedHttpClientParameters.Matches(parameters))
+ if (s_cachedHttpClientParameters!.Matches(parameters))
{
return s_cachedHttpClient;
}
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();
// 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);
}
// 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;
/// </devdoc>
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)
throw new PlatformNotSupportedException();
}
- internal HttpWebResponse(HttpResponseMessage _message, Uri requestUri, CookieContainer cookieContainer)
+ internal HttpWebResponse(HttpResponseMessage _message, Uri requestUri, CookieContainer? cookieContainer)
{
_httpResponseMessage = _message;
_requestUri = requestUri;
get
{
CheckDisposed();
- long? length = _httpResponseMessage.Content.Headers.ContentLength;
+ long? length = _httpResponseMessage.Content?.Headers.ContentLength;
return length.HasValue ? length.Value : -1;
}
}
// 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<string> values;
- if (_httpResponseMessage.Content.Headers.TryGetValues("Content-Type", out values))
+ if (_httpResponseMessage.Content != null && _httpResponseMessage.Content.Headers.TryGetValues("Content-Type", out IEnumerable<string>? 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.
get
{
CheckDisposed();
- return GetHeaderValueAsString(_httpResponseMessage.Content.Headers.ContentEncoding);
+ if (_httpResponseMessage.Content != null)
+ {
+ return GetHeaderValueAsString(_httpResponseMessage.Content.Headers.ContentEncoding);
+ }
+
+ return string.Empty;
}
}
get
{
CheckDisposed();
- string lastmodHeaderValue = Headers["Last-Modified"];
+ string? lastmodHeaderValue = Headers["Last-Modified"];
if (string.IsNullOrEmpty(lastmodHeaderValue))
{
return DateTime.Now;
get
{
CheckDisposed();
- return string.IsNullOrEmpty(Headers["Server"]) ? string.Empty : Headers["Server"];
+ string? server = Headers["Server"];
+ return string.IsNullOrEmpty(server) ? string.Empty : server;
}
}
get
{
CheckDisposed();
- return _httpResponseMessage.RequestMessage.Method.Method;
+ return _httpResponseMessage.RequestMessage!.Method.Method;
}
}
// 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!;
}
}
get
{
CheckDisposed();
- return _httpResponseMessage.ReasonPhrase;
+ return _httpResponseMessage.ReasonPhrase ?? string.Empty;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
- public string CharacterSet
+ public string? CharacterSet
{
get
{
CheckDisposed();
- string contentType = Headers["Content-Type"];
+ string? contentType = Headers["Content-Type"];
if (_characterSet == null && !string.IsNullOrWhiteSpace(contentType))
{
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()
if (httpResponseMessage != null)
{
httpResponseMessage.Dispose();
- _httpResponseMessage = null;
+ _httpResponseMessage = null!;
}
}
// 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
{
/// <devdoc>
{
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)
{
{
get
{
- return ((IPEndPoint)Socket.RemoteEndPoint).Address;
+ return ((IPEndPoint)Socket.RemoteEndPoint!).Address;
}
}
_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);
}
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);
}
/// class with the specified message.
/// </para>
/// </devdoc>
- public ProtocolViolationException(string message) : base(message)
+ public ProtocolViolationException(string? message) : base(message)
{
}
// 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;
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)
{
{
public static TaskCompletionSource<TResult> ToApm<TResult>(
this Task<TResult> task,
- AsyncCallback callback,
- object state)
+ AsyncCallback? callback,
+ object? state)
{
TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(state);
if (completedTask.IsFaulted)
{
- shouldInvokeCallback = tcs.TrySetException(completedTask.Exception.InnerExceptions);
+ shouldInvokeCallback = tcs.TrySetException(completedTask.Exception!.InnerExceptions);
}
else if (completedTask.IsCanceled)
{
/// <summary>
/// <para>Creates and returns a handle to a new timer with attached context.</para>
/// </summary>
- internal abstract Timer CreateTimer(Callback callback, object context);
+ internal abstract Timer CreateTimer(Callback callback, object? context);
}
/// <summary>
/// <summary>
/// <para>Prototype for the callback that is called when a timer expires.</para>
/// </summary>
- 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;
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);
while (e.MoveNext())
{
DictionaryEntry pair = e.Entry;
- if (((WeakReference)pair.Value).Target == null)
+ if (((WeakReference)pair.Value!).Target == null)
{
garbage.Add(pair.Key);
}
/// <summary>
/// <para>Creates new timers. This method is thread-safe.</para>
/// </summary>
- internal override Timer CreateTimer(Callback callback, object context)
+ internal override Timer CreateTimer(Callback callback, object? context)
{
TimerNode timer = new TimerNode(callback, context, Duration, _timers);
bool needProd = false;
lock (_timers)
{
- if (!(_timers.Prev.Next == _timers))
+ if (!(_timers.Prev!.Next == _timers))
{
NetEventSource.Fail(this, $"Tail corruption.");
}
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)
/// <summary>
/// <para>Always returns a dummy infinite timer.</para>
/// </summary>
- internal override Timer CreateTimer(Callback callback, object context) => new InfiniteTimer();
+ internal override Timer CreateTimer(Callback callback, object? context) => new InfiniteTimer();
}
/// <summary>
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;
/// <summary>
/// <para>Status of the timer.</para>
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)
{
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; }
// 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;
_timerState = TimerState.Fired;
// Remove it from the list.
- Next.Prev = Prev;
- Prev.Next = Next;
+ Next!.Prev = Prev;
+ Prev!.Next = Next;
Next = null;
Prev = null;
{
try
{
- Callback callback = _callback;
- object context = _context;
+ Callback callback = _callback!;
+ object? context = _context;
_callback = null;
_context = null;
callback(this, nowMilliseconds, context);
{
lock (s_newQueues)
{
- for (LinkedListNode<WeakReference> node = s_newQueues.First; node != null; node = s_newQueues.First)
+ for (LinkedListNode<WeakReference>? node = s_newQueues.First; node != null; node = s_newQueues.First)
{
s_newQueues.Remove(node);
s_queues.AddLast(node);
int now = Environment.TickCount;
int nextTick = 0;
bool haveNextTick = false;
- for (LinkedListNode<WeakReference> node = s_queues.First; node != null; /* node = node.Next must be done in the body */)
+ for (LinkedListNode<WeakReference>? 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<WeakReference> next = node.Next;
+ LinkedListNode<WeakReference>? next = node.Next;
s_queues.Remove(node);
node = next;
continue;
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;
{
}
- 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)
{
private static WebExceptionStatus GetStatusFromExceptionHelper(HttpRequestException ex)
{
- SocketException socketEx = ex.InnerException as SocketException;
+ SocketException? socketEx = ex.InnerException as SocketException;
if (socketEx is null)
{
// 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
using System.Collections.Generic;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Cache;
using System.Net.Http;
}
}
- private static List<WebRequestPrefixElement> s_prefixList;
+ private static List<WebRequestPrefixElement>? s_prefixList;
private static object s_internalSyncObject = new object();
internal const int DefaultTimeoutMilliseconds = 100 * 1000;
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, requestUri);
string LookupUri;
- WebRequestPrefixElement Current = null;
+ WebRequestPrefixElement? Current = null;
bool Found = false;
if (!useUriBase)
}
}
- 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;
}
// 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;
}
}
- 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
{
}
}
- public virtual string ContentType
+ public virtual string? ContentType
{
get
{
}
}
- public virtual ICredentials Credentials
+ [DisallowNull]
+ public virtual ICredentials? Credentials
{
get
{
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);
}
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);
}
// Unwrap() that it's worth it to just rely on Task.Run and accept the closure/delegate.
return Task.Run(() =>
Task<Stream>.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));
}
// See comment in GetRequestStreamAsync(). Same logic applies here.
return Task.Run(() =>
Task<WebResponse>.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));
}
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<IWebProxy>(ref s_DefaultWebProxy, ref s_DefaultWebProxyInitialized, ref s_internalSyncObject, () => GetSystemWebProxy());
set
{
lock (s_internalSyncObject)
}
}
- public virtual IWebProxy Proxy
+ public virtual IWebProxy? Proxy
{
get
{
// See the LICENSE file in the project root for more information.
using System.Collections;
-using System.Diagnostics;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
}
[Fact]
+ public void Unregister_Null_Throws()
+ {
+ Assert.Throws<ArgumentNullException>(() => AuthenticationManager.Unregister((IAuthenticationModule)null));
+ Assert.Throws<ArgumentNullException>(() => AuthenticationManager.Unregister((string)null));
+ }
+
+ [Fact]
public void Register_Unregister_ModuleCountUnchanged()
{
RemoteExecutor.Invoke(() =>
// 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;
// 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;
// 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;
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;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;
-using Xunit.Abstractions;
using System.Runtime.Serialization;
namespace System.Net.Tests
// 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;
_callback = callback;
}
- internal object AsyncObject => UserAsyncResult.AsyncObject;
+ internal object? AsyncObject => UserAsyncResult.AsyncObject;
//
// Notify protocol so a next stage could be started.
try
{
- NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject;
+ NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject!;
TaskToApm.End(transportResult);
if (asyncRequest.Count == 0)
{
// 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.
// Async completion.
try
{
- NegoState authState = (NegoState)lazyResult.AsyncObject;
+ NegoState authState = (NegoState)lazyResult.AsyncObject!;
authState._framer!.EndWriteMessage(transportResult);
// Special case for an error notification.
// Async completion.
try
{
- NegoState authState = (NegoState)lazyResult.AsyncObject;
+ NegoState authState = (NegoState)lazyResult.AsyncObject!;
byte[]? message = authState._framer!.EndReadMessage(transportResult);
authState.ProcessReceivedBlob(message, lazyResult);
}
<PropertyGroup>
<AssemblyName>System.Net.Sockets</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix</TargetFrameworks>
+ <TargetFrameworks>$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Windows_NT</TargetFrameworks>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
// 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");
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,
var errorCode = (SocketError)ErrorCode;
if (errorCode == SocketError.Success)
{
- var socket = (Socket)AsyncObject;
+ var socket = (Socket)AsyncObject!;
socket.SetToConnected();
return socket;
}
internal override unsafe object? PostCompletion(int numBytes)
{
SocketError errorCode = (SocketError)ErrorCode;
- Socket socket = (Socket)AsyncObject;
+ Socket socket = (Socket)AsyncObject!;
if (errorCode == SocketError.Success)
{
{
if (ErrorCode == (int)SocketError.Success)
{
- Socket socket = (Socket)AsyncObject;
+ Socket socket = (Socket)AsyncObject!;
socket.SetToDisconnected();
socket._remoteEndPoint = null;
}
_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)
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;