diff --git a/Directory.Build.targets b/Directory.Build.targets index dc33b70b526..f5b1b4272f6 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -3,9 +3,12 @@ - + + $(AssemblyName) + + diff --git a/eng/versioning.targets b/eng/versioning.targets deleted file mode 100644 index 321b0599d4f..00000000000 --- a/eng/versioning.targets +++ /dev/null @@ -1,35 +0,0 @@ - - - true - - - - $(IntermediateOutputPath)_AssemblyInfo.g.cs - - - - $(AssemblyName) - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb index f5ac6664952..d2bc36d4ffd 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb @@ -154,7 +154,8 @@ Namespace Microsoft.VisualBasic.ApplicationServices ' have our principal on the thread before that happens. If authenticationMode = AuthenticationMode.Windows Then Try - ' Consider: Sadly, a call to: System.Security.SecurityManager.IsGranted(New SecurityPermission(SecurityPermissionFlag.ControlPrincipal)) + ' Consider: Sadly, a call to: + ' Security.SecurityManager.IsGranted(New SecurityPermission(SecurityPermissionFlag.ControlPrincipal)) ' Will only check the THIS caller so you'll always get TRUE. ' What we need is a way to get to the value of this on a demand basis. ' So I try/catch instead for now but would rather be able to IF my way around this block. @@ -382,7 +383,8 @@ Namespace Microsoft.VisualBasic.ApplicationServices _unhandledExceptionHandlers.Add(value) - ' Only add the listener once so we don't fire the UnHandledException event over and over for the same exception + ' Only add the listener once so we don't fire the + ' UnHandledException event over and over for the same exception If _unhandledExceptionHandlers.Count = 1 Then AddHandler Application.ThreadException, AddressOf OnUnhandledExceptionEventAdaptor End If @@ -631,7 +633,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices _formLoadWaiter = New AutoResetEvent(False) Task.Run(Async Function() As Task - Await _splashScreenCompletionSource.Task.ConfigureAwait(False) + Await _splashScreenCompletionSource.Task.ConfigureAwait(continueOnCapturedContext:=False) _formLoadWaiter.Set() End Function) @@ -653,7 +655,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices If _splashTimer IsNot Nothing Then - 'We only have a timer if there was a minimum timeout on the splash screen. + ' We only have a timer if there was a minimum timeout on the splash screen. _splashTimer.Dispose() _splashTimer = Nothing End If @@ -725,7 +727,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices Protected Sub HideSplashScreen() - 'This ultimately wasn't necessary. I suppose we better keep it for backwards compatibility. + ' This ultimately wasn't necessary. I suppose we better keep it for backwards compatibility. SyncLock _splashLock ' .NET Framework 4.0 (Dev10 #590587) - we now activate the main form before calling @@ -766,7 +768,11 @@ Namespace Microsoft.VisualBasic.ApplicationServices ''' variants was passed in. ''' ''' - ''' Returning True indicates that we should continue on with the application Startup sequence. + ''' + ''' Returning + ''' Indicates that we should continue on with the application Startup sequence. + ''' + ''' ''' ''' This extensibility point is exposed for people who want to override ''' the Startup sequence at the earliest possible point to @@ -867,26 +873,29 @@ Namespace Microsoft.VisualBasic.ApplicationServices End If ' When we have a splash screen that hasn't timed out before the main form is ready to paint, we want to - ' block the main form from painting. To do that I let the form get past the Load() event and hold it until - ' the splash screen goes down. Then I let the main form continue it's startup sequence. The ordering of - ' Form startup events for reference is: Ctor(), Load Event, Layout event, Shown event, Activated event, Paint event. + ' block the main form from painting. To do that I let the form get past the Load() event and + ' hold it until the splash screen goes down. Then I let the main form continue it's startup sequence. + ' The ordering of Form startup events for reference is: + ' Ctor(), Load Event, Layout event, Shown event, Activated event, Paint event. AddHandler MainForm.Load, AddressOf MainFormLoadingDone End If ' Run() eats all exceptions (unless running under the debugger). If the user wrote an ' UnhandledException handler we will hook the System.Windows.Forms.Application.ThreadException event ' (see Public Custom Event UnhandledException) which will raise our UnhandledException Event. - ' If our user didn't write an UnhandledException event, then we land in the try/catch handler for Forms.Application.Run(). + ' If our user didn't write an UnhandledException event, then we land in the try/catch handler + ' for Forms.Application.Run(). Try Application.Run(_appContext) Finally - ' When Run() returns, the context we pushed in our ctor (which was a WindowsFormsSynchronizationContext) - ' is restored. But we are going to dispose it so we need to disconnect the network listener so that it + ' When Run() returns, the context we pushed in our ctor + ' (which was a WindowsFormsSynchronizationContext) is restored. + ' But we are going to dispose it so we need to disconnect the network listener so that it ' can't fire any events in response to changing network availability conditions through a dead context. If _networkObject IsNot Nothing Then _networkObject.DisconnectListener() - 'Restore the prior sync context. + ' Restore the prior sync context. AsyncOperationManager.SynchronizationContext = _appSynchronizationContext _appSynchronizationContext = Nothing End Try @@ -914,11 +923,12 @@ Namespace Microsoft.VisualBasic.ApplicationServices ' The timing is important because the network object has an AsyncOperationsManager in it that marshals ' the network changed event to the main thread. The asyncOperationsManager does a CreateOperation() ' which makes a copy of the executionContext. That execution context shows up on your thread during - ' the callback so I delay creating the network object (and consequently the capturing of the execution context) - ' until the principal has been set on the thread. This avoids the problem where My.User isn't set - ' during the NetworkAvailabilityChanged event. This problem would just extend itself to any future - ' callback that involved the asyncOperationsManager so this is where we need to create objects that - ' have a asyncOperationsContext in them. + ' the callback so I delay creating the network object + ' (and consequently the capturing of the execution context) until the principal has been set on the thread. + ' This avoids the problem where My.User isn't set during the NetworkAvailabilityChanged event. + ' This problem would just extend itself to any future callback that involved + ' the asyncOperationsManager so this is where we need to create objects that have + ' a asyncOperationsContext in them. If _turnOnNetworkListener And _networkObject Is Nothing Then ' The is-nothing-check is to avoid hooking the object more than once. @@ -956,7 +966,10 @@ Namespace Microsoft.VisualBasic.ApplicationServices ''' that execution shouldn't continue. ''' ''' - ''' indicates the exception event was raised / it was not. + ''' + ''' indicates the exception event was raised + ''' it was not. + ''' Protected Overridable Function OnUnhandledException(e As UnhandledExceptionEventArgs) As Boolean @@ -1050,7 +1063,10 @@ Namespace Microsoft.VisualBasic.ApplicationServices Using pipeServer Dim tokenSource As New CancellationTokenSource() #Disable Warning BC42358 ' Call is not awaited. - WaitForClientConnectionsAsync(pipeServer, AddressOf OnStartupNextInstanceMarshallingAdaptor, cancellationToken:=tokenSource.Token) + WaitForClientConnectionsAsync( + pipeServer, + AddressOf OnStartupNextInstanceMarshallingAdaptor, + cancellationToken:=tokenSource.Token) #Enable Warning BC42358 DoApplicationModel() tokenSource.Cancel() @@ -1072,7 +1088,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices Throw New CantStartSingleInstanceException() End Try End If - End If 'Single-Instance application + End If ' Single-Instance application End Sub End Class diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/ComputerInfo.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/ComputerInfo.vb index d3552a0efab..6dfcf883681 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/ComputerInfo.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/ComputerInfo.vb @@ -47,7 +47,6 @@ Namespace Microsoft.VisualBasic.Devices ''' ''' Throw if we are unable to obtain the memory status. ''' - Public ReadOnly Property AvailablePhysicalMemory() As UInt64 Get Return MemoryStatus.AvailablePhysicalMemory @@ -64,7 +63,6 @@ Namespace Microsoft.VisualBasic.Devices ''' ''' Throw if we are unable to obtain the memory status. ''' - Public ReadOnly Property AvailableVirtualMemory() As UInt64 Get Return MemoryStatus.AvailableVirtualMemory @@ -131,7 +129,6 @@ Namespace Microsoft.VisualBasic.Devices ''' ''' Throw if we are unable to obtain the memory status. ''' - Public ReadOnly Property TotalPhysicalMemory() As UInt64 Get Return MemoryStatus.TotalPhysicalMemory @@ -148,7 +145,6 @@ Namespace Microsoft.VisualBasic.Devices ''' ''' Throw if we are unable to obtain the memory status. ''' - Public ReadOnly Property TotalVirtualMemory() As UInt64 Get Return MemoryStatus.TotalVirtualMemory diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.DownloadFile.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.DownloadFile.vb index 37b4776aa91..8da1972b718 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.DownloadFile.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.DownloadFile.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System.Net -Imports Microsoft.VisualBasic.CompilerServices Imports Microsoft.VisualBasic.FileIO Imports Microsoft.VisualBasic.MyServices.Internal @@ -24,30 +23,21 @@ Namespace Microsoft.VisualBasic.Devices ''' Address to the remote file, http, ftp etc... ''' Name and path of file where download is saved. Public Sub DownloadFile(address As String, destinationFileName As String) - DownloadFile( - address, - destinationFileName, - userName:=DEFAULT_USERNAME, - password:=DEFAULT_PASSWORD, - showUI:=False, - connectionTimeout:=DEFAULT_TIMEOUT, - overwrite:=False) - End Sub - - ''' - ''' Downloads a file from the network to the specified path. - ''' - ''' to the remote file. - ''' Name and path of file where download is saved. - Public Sub DownloadFile(address As Uri, destinationFileName As String) - DownloadFile( - address, - destinationFileName, - userName:=DEFAULT_USERNAME, - password:=DEFAULT_PASSWORD, - showUI:=False, - connectionTimeout:=DEFAULT_TIMEOUT, - overwrite:=False) + Try + DownloadFileAsync( + address, + destinationFileName, + userName:=DEFAULT_USERNAME, + password:=DEFAULT_PASSWORD, + dialog:=Nothing, + connectionTimeout:=DEFAULT_TIMEOUT, + overwrite:=False).Wait() + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException + End If + Throw + End Try End Sub ''' @@ -63,37 +53,21 @@ Namespace Microsoft.VisualBasic.Devices userName As String, password As String) - DownloadFile( - address, - destinationFileName, - userName, - password, - showUI:=False, - connectionTimeout:=DEFAULT_TIMEOUT, - overwrite:=False) - End Sub - - ''' - ''' Downloads a file from the network to the specified path. - ''' - ''' to the remote file. - ''' Name and path of file where download is saved. - ''' The name of the user performing the download. - ''' The user's password. - Public Sub DownloadFile( - address As Uri, - destinationFileName As String, - userName As String, - password As String) - - DownloadFile( - address, - destinationFileName, - userName, - password, - showUI:=False, - connectionTimeout:=DEFAULT_TIMEOUT, - overwrite:=False) + Try + DownloadFileAsync( + address, + destinationFileName, + userName, + password, + dialog:=Nothing, + connectionTimeout:=DEFAULT_TIMEOUT, + overwrite:=False).Wait() + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException + End If + Throw + End Try End Sub ''' @@ -117,15 +91,51 @@ Namespace Microsoft.VisualBasic.Devices connectionTimeout As Integer, overwrite As Boolean) - DownloadFile( - address, - destinationFileName, - userName, - password, - showUI, - connectionTimeout, - overwrite, - UICancelOption.ThrowException) + Dim dialog As ProgressDialog = Nothing + Try + dialog = GetProgressDialog(address, destinationFileName, showUI) + + Dim t As Task = DownloadFileAsync( + address, + destinationFileName, + userName, + password, + dialog, + connectionTimeout, + overwrite, + onUserCancel:=UICancelOption.ThrowException) + + If t.IsFaulted Then + ' This will be true if any parameters are bad + Throw t.Exception + Else + dialog?.ShowProgressDialog() + t.Wait() + If t.IsFaulted Then + Throw t.Exception + End If + End If + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + If TryCast(ex.InnerException, OperationCanceledException) IsNot Nothing AndAlso + Environment.UserInteractive Then + + If showUI AndAlso Environment.UserInteractive Then + Try + IO.File.Delete(destinationFileName) + Catch + ' ignore error + End Try + Throw New OperationCanceledException() + End If + End If + + Throw ex.InnerException + End If + Throw + Finally + CloseProgressDialog(dialog) + End Try End Sub ''' @@ -137,12 +147,11 @@ Namespace Microsoft.VisualBasic.Devices ''' The user's password. ''' Indicates whether or not to show a progress bar. ''' Time allotted before giving up on a connection. - ''' - ''' Indicates whether or not the file should be overwritten - ''' if local file already exists. + ''' Indicates whether or not the file should be + ''' overwritten if local file already exists. ''' ''' - ''' Indicates what to do if user cancels dialog (either or do nothing). + ''' Indicates what to do if user cancels dialog (either throw or do nothing). ''' Public Sub DownloadFile( address As String, @@ -154,8 +163,8 @@ Namespace Microsoft.VisualBasic.Devices overwrite As Boolean, onUserCancel As UICancelOption) - ' We're safe from DownloadFile(Nothing, ...) due to overload failure (DownloadFile(String,...) - ' vs. DownloadFile(Uri,...)). + ' We're safe from DownloadFile(Nothing, ...) due to overload failure (DownloadFile(String,...) vs. + ' DownloadFile(Uri,...)). ' However, it is good practice to verify address before calling Trim. If String.IsNullOrWhiteSpace(address) Then Throw VbUtils.GetArgumentNullException(NameOf(address)) @@ -166,216 +175,348 @@ Namespace Microsoft.VisualBasic.Devices ' Get network credentials Dim networkCredentials As ICredentials = GetNetworkCredentials(userName, password) - DownloadFile( - address:=addressUri, - destinationFileName, - networkCredentials, - showUI, - connectionTimeout, - overwrite, - onUserCancel) + Dim dialog As ProgressDialog = Nothing + Try + If showUI AndAlso Environment.UserInteractive Then + ' Construct the local file. This will validate the full name and path + Dim fullFilename As String = CompilerServices.FileSystemUtils.NormalizeFilePath( + path:=destinationFileName, + paramName:=NameOf(destinationFileName)) + + dialog = GetProgressDialog(address, destinationFileName, showUI) + End If + + Dim t As Task = DownloadFileAsync( + addressUri, + destinationFileName, + networkCredentials, + dialog, + connectionTimeout, + overwrite, + onUserCancel) + + If t.IsFaulted Then + ' IsFaulted will be true if any parameters are bad + Throw t.Exception + Else + dialog?.ShowProgressDialog() + t.Wait() + If t.IsFaulted Then + Throw t.Exception + End If + End If + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException + End If + Throw + Finally + CloseProgressDialog(dialog) + End Try End Sub ''' ''' Downloads a file from the network to the specified path. ''' - ''' to the remote file, - ''' - ''' Name and path of file where download is saved. - ''' - ''' The name of the user performing the download. - ''' The user's password. + ''' Uri to the remote file. + ''' Name and path of file where download is saved. + ''' The credentials of the user performing the download. ''' Indicates whether or not to show a progress bar. ''' Time allotted before giving up on a connection. ''' ''' Indicates whether or not the file should be overwritten if local file already exists. ''' + ''' Calls to all the other overloads will come through here. Public Sub DownloadFile( address As Uri, destinationFileName As String, - userName As String, - password As String, + networkCredentials As ICredentials, showUI As Boolean, connectionTimeout As Integer, overwrite As Boolean) - DownloadFile( - address, - destinationFileName, - userName, - password, - showUI, - connectionTimeout, - overwrite, - UICancelOption.ThrowException) + If address Is Nothing Then + Throw VbUtils.GetArgumentNullException(NameOf(address)) + End If + + Dim dialog As ProgressDialog = Nothing + Try + dialog = GetProgressDialog(address.AbsolutePath, destinationFileName, showUI) + Dim t As Task = DownloadFileAsync( + addressUri:=address, + destinationFileName, + networkCredentials, + dialog, + connectionTimeout, + overwrite) + + If t.IsFaulted Then + ' IsFaulted will be true if any parameters are bad + Throw t.Exception + Else + dialog?.ShowProgressDialog() + t.Wait() + If t.IsFaulted Then + Throw t.Exception + End If + End If + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException + End If + Throw + Finally + CloseProgressDialog(dialog) + End Try End Sub ''' ''' Downloads a file from the network to the specified path. ''' - ''' to the remote file. - ''' - ''' Name and path of file where download is saved. - ''' - ''' The name of the user performing the download. - ''' The user's password. + ''' Uri to the remote file. + ''' Name and path of file where download is saved. + ''' The credentials of the user performing the download. ''' Indicates whether or not to show a progress bar. - ''' - ''' Time allotted before giving up on a connection. - ''' + ''' Time allotted before giving up on a connection. ''' - ''' Indicates whether or not the file should be overwritten - ''' if local file already exists. + ''' Indicates whether or not the file should be overwritten if local file already exists. ''' ''' - ''' Indicates what to do if user cancels dialog (either or do nothing). + ''' Indicates what to do if user cancels dialog (either throw or do nothing). ''' + ''' Calls to all the other overloads will come through here. Public Sub DownloadFile( address As Uri, destinationFileName As String, - userName As String, - password As String, + networkCredentials As ICredentials, showUI As Boolean, connectionTimeout As Integer, overwrite As Boolean, onUserCancel As UICancelOption) - ' Get network credentials - Dim networkCredentials As ICredentials = GetNetworkCredentials(userName, password) + If connectionTimeout <= 0 Then + Throw VbUtils.GetArgumentExceptionWithArgName( + argumentName:=NameOf(connectionTimeout), + resourceKey:=SR.Network_BadConnectionTimeout) + End If - DownloadFile( - address, - destinationFileName, - networkCredentials, - showUI, - connectionTimeout, - overwrite, - onUserCancel) + If address Is Nothing Then + Throw VbUtils.GetArgumentNullException(NameOf(address)) + End If + + Dim dialog As ProgressDialog = Nothing + Try + dialog = GetProgressDialog(address.AbsolutePath, destinationFileName, showUI) + Dim t As Task = DownloadFileAsync( + addressUri:=address, + destinationFileName, + networkCredentials, + dialog, + connectionTimeout, + overwrite, + onUserCancel) + + If t.IsFaulted Then + ' IsFaulted will be true if any parameters are bad + Throw t.Exception + Else + dialog?.ShowProgressDialog() + t.Wait() + If t.IsFaulted Then + Throw t.Exception + End If + End If + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException + End If + Throw + Finally + CloseProgressDialog(dialog) + End Try End Sub ''' ''' Downloads a file from the network to the specified path. ''' - ''' to the remote file. - ''' - ''' Name and path of file where download is saved. - ''' - ''' - ''' The credentials of the user performing the download. - ''' + ''' Uri to the remote file. + ''' Name and path of file where download is saved. + ''' The name of the user performing the download. + ''' The user's password. ''' Indicates whether or not to show a progress bar. ''' Time allotted before giving up on a connection. ''' - ''' Indicates whether or not the file should be overwritten - ''' if local file already exists. + ''' Indicates whether or not the file should be overwritten if local file already exists. ''' - ''' Calls to all the other overloads will come through here. Public Sub DownloadFile( address As Uri, destinationFileName As String, - networkCredentials As ICredentials, + userName As String, + password As String, showUI As Boolean, connectionTimeout As Integer, overwrite As Boolean) - DownloadFile( - address, - destinationFileName, - networkCredentials, - showUI, - connectionTimeout, - overwrite, - UICancelOption.ThrowException) + If address Is Nothing Then + Throw VbUtils.GetArgumentNullException(NameOf(address)) + End If + + Dim dialog As ProgressDialog = Nothing + Dim networkCredentials As ICredentials = GetNetworkCredentials(userName, password) + Try + dialog = GetProgressDialog(address.AbsolutePath, destinationFileName, showUI) + Dim t As Task = DownloadFileAsync( + addressUri:=address, + destinationFileName, + networkCredentials, + dialog, + connectionTimeout, + overwrite, + onUserCancel:=UICancelOption.ThrowException) + + If t.IsFaulted Then + ' IsFaulted will be true if any parameters are bad + Throw t.Exception + Else + dialog?.ShowProgressDialog() + t.Wait() + If t.IsFaulted Then + Throw t.Exception + End If + End If + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException + End If + Throw + Finally + CloseProgressDialog(dialog) + End Try End Sub ''' ''' Downloads a file from the network to the specified path. ''' - ''' to the remote file. + ''' Uri to the remote file. ''' Name and path of file where download is saved. - ''' The of the user performing the download. + ''' The name of the user performing the download. + ''' The user's password. ''' Indicates whether or not to show a progress bar. ''' Time allotted before giving up on a connection. ''' - ''' Indicates whether or not the file should be overwritten - ''' if local file already exists. + ''' Indicates whether or not the file should be overwritten if local file already exists. ''' ''' - ''' Indicates what to do if user cancels dialog (either or do nothing). + ''' Indicates what to do if user cancels dialog (either throw or do nothing). ''' - ''' Calls to all the other overloads will come through here. Public Sub DownloadFile( address As Uri, destinationFileName As String, - networkCredentials As ICredentials, + userName As String, + password As String, showUI As Boolean, connectionTimeout As Integer, overwrite As Boolean, onUserCancel As UICancelOption) If connectionTimeout <= 0 Then - Throw VbUtils.GetArgumentExceptionWithArgName(NameOf(connectionTimeout), SR.Network_BadConnectionTimeout) + Throw VbUtils.GetArgumentExceptionWithArgName( + argumentName:=NameOf(connectionTimeout), + resourceKey:=SR.Network_BadConnectionTimeout) End If If address Is Nothing Then Throw VbUtils.GetArgumentNullException(NameOf(address)) End If - Using client As New WebClientExtended - client.Timeout = connectionTimeout - - ' Don't use passive mode if we're showing UI - client.UseNonPassiveFtp = showUI - - 'Construct the local file. This will validate the full name and path - Dim fullFilename As String = FileSystemUtils.NormalizeFilePath(destinationFileName, NameOf(destinationFileName)) + ' Get network credentials + Dim networkCredentials As ICredentials = GetNetworkCredentials(userName, password) - ' Sometime a path that can't be parsed is normalized to the current directory. This makes sure we really - ' have a file and path - If IO.Directory.Exists(fullFilename) Then - Throw VbUtils.GetInvalidOperationException(SR.Network_DownloadNeedsFilename) + Dim dialog As ProgressDialog = Nothing + Try + dialog = GetProgressDialog(address.AbsolutePath, destinationFileName, showUI) + Dim t As Task = DownloadFileAsync( + addressUri:=address, + destinationFileName, + networkCredentials, + dialog, + connectionTimeout, + overwrite, + onUserCancel) + + If t.IsFaulted Then + ' IsFaulted will be true if any parameters are bad + Throw t.Exception + Else + dialog?.ShowProgressDialog() + t.Wait() + If t.IsFaulted Then + Throw t.Exception + End If End If - - 'Throw if the file exists and the user doesn't want to overwrite - If IO.File.Exists(fullFilename) And Not overwrite Then - Throw New IO.IOException(VbUtils.GetResourceString(SR.IO_FileExists_Path, destinationFileName)) - End If - - ' Set credentials if we have any - If networkCredentials IsNot Nothing Then - client.Credentials = networkCredentials - End If - - Dim dialog As ProgressDialog = GetProgressDialog(address.AbsolutePath, fullFilename, showUI) - - 'Check to see if the target directory exists. If it doesn't, create it - Dim targetDirectory As String = IO.Path.GetDirectoryName(fullFilename) - - ' Make sure we have a meaningful directory. If we don't, the destinationFileName is suspect - If String.IsNullOrEmpty(targetDirectory) Then - Throw VbUtils.GetInvalidOperationException(SR.Network_DownloadNeedsFilename) + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException End If + Throw + Finally + CloseProgressDialog(dialog) + End Try + End Sub - If Not IO.Directory.Exists(targetDirectory) Then - IO.Directory.CreateDirectory(targetDirectory) + ''' + ''' Downloads a file from the network to the specified path. + ''' + ''' Uri to the remote file. + ''' Name and path of file where download is saved. + Public Sub DownloadFile(address As Uri, destinationFileName As String) + Try + + DownloadFileAsync( + addressUri:=address, + destinationFileName, + userName:=DEFAULT_USERNAME, + password:=DEFAULT_PASSWORD, + dialog:=Nothing, + connectionTimeout:=DEFAULT_TIMEOUT, + overwrite:=False).Wait() + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException End If + Throw + End Try + End Sub - 'Create the copier - Dim copier As New WebClientCopy(client, dialog) - - 'Download the file - copier.DownloadFile(address, fullFilename) + ''' + ''' Downloads a file from the network to the specified path. + ''' + ''' Uri to the remote file. + ''' Name and path of file where download is saved. + ''' The name of the user performing the download. + ''' The user's password. + Public Sub DownloadFile( + address As Uri, + destinationFileName As String, + userName As String, + password As String) - 'Handle a dialog cancel - If showUI AndAlso Environment.UserInteractive Then - If onUserCancel = UICancelOption.ThrowException And dialog.UserCanceledTheDialog Then - Throw New OperationCanceledException() - End If + Try + DownloadFileAsync( + addressUri:=address, + destinationFileName, + userName, + password, + dialog:=Nothing, + connectionTimeout:=DEFAULT_TIMEOUT, + overwrite:=False).Wait() + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException End If - - End Using - + Throw + End Try End Sub End Class diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.DownloadFileAsync.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.DownloadFileAsync.vb new file mode 100644 index 00000000000..7f054586ad8 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.DownloadFileAsync.vb @@ -0,0 +1,347 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. + +Imports System.Net +Imports System.Net.Http +Imports System.Threading +Imports Microsoft.VisualBasic.CompilerServices +Imports Microsoft.VisualBasic.FileIO +Imports Microsoft.VisualBasic.MyServices.Internal + +Imports VbUtils = Microsoft.VisualBasic.CompilerServices.ExceptionUtils + +Namespace Microsoft.VisualBasic.Devices + + Partial Public Class Network + + ''' + ''' Sends and receives a packet to and from the passed in Uri. + ''' Maps older networkCredentials to HttpClientHandler. + ''' + ''' Uri to the remote file. + ''' Name and path of file where download is saved. + ''' The credentials of the user performing the download. + ''' A ProgressDialog or Nothing. + ''' Time allotted before giving up on a connection. + ''' + ''' Indicates whether or not the file should be overwritten if local file already exists. + ''' + ''' + ''' + Friend Shared Function DownloadFileAsync( + addressUri As Uri, + destinationFileName As String, + networkCredentials As ICredentials, + dialog As ProgressDialog, + connectionTimeout As Integer, + overwrite As Boolean, + onUserCancel As UICancelOption, + Optional cancelToken As CancellationToken = Nothing) As Task + + Dim clientHandler As HttpClientHandler = If(networkCredentials Is Nothing, + New HttpClientHandler, + New HttpClientHandler With {.Credentials = networkCredentials} + ) + Return DownloadFileAsync(addressUri, + destinationFileName, + clientHandler, + dialog, + connectionTimeout, + overwrite, + onUserCancel, + cancelToken) + End Function + + ''' + ''' Downloads a file from the network to the specified path. + ''' + ''' Uri to the remote file + ''' Name and path of file where download is saved. + ''' The name of the user performing the download. + ''' The user's password. + ''' A ProgressDialog or Nothing. + ''' Time allotted before giving up on a connection. + ''' + ''' Indicates whether or not the file should be overwritten if local file already exists. + ''' + ''' + Friend Shared Async Function DownloadFileAsync( + addressUri As Uri, + destinationFileName As String, + userName As String, + password As String, + dialog As ProgressDialog, + connectionTimeout As Integer, + overwrite As Boolean, + Optional cancelToken As CancellationToken = Nothing) As Task + + Dim networkCredentials As ICredentials = GetNetworkCredentials(userName, password) + + Await DownloadFileAsync( + addressUri, + destinationFileName, + networkCredentials, + dialog, + connectionTimeout, + overwrite, + onUserCancel:=UICancelOption.ThrowException, + cancelToken).ConfigureAwait(continueOnCapturedContext:=False) + End Function + +#If False Then ' This is here of API review determains its needed + + ''' + ''' Downloads a file from the network to the specified path. + ''' + ''' Uri to the remote file + ''' Name and path of file where download is saved. + ''' The name of the user performing the download. + ''' The user's password. + ''' ProgressDialog or Nothing. + ''' Time allotted before giving up on a connection. + ''' + ''' Indicates whether or not the file should be overwritten if local file already exists. + ''' + ''' + ''' Indicates what to do if user cancels dialog (either throw or do nothing). + ''' + ''' + Friend Shared Async Function DownloadFileAsync( + addressUri As Uri, + destinationFileName As String, + userName As String, + password As String, + dialog As ProgressDialog, + connectionTimeout As Integer, + overwrite As Boolean, + onUserCancel As UICancelOption, + Optional cancelToken As CancellationToken = Nothing) As Task + + ' Get network credentials + Dim networkCredentials As ICredentials = GetNetworkCredentials(userName, password) + + Await DownloadFileAsync( + addressUri, + destinationFileName, + networkCredentials, + dialog, + connectionTimeout, + overwrite, + onUserCancel + cancelToken).ConfigureAwait(continueOnCapturedContext:=False) + End Function +#End If + + ''' + ''' Downloads a file from the network to the specified path. + ''' + ''' Uri to the remote file + ''' Name and path of file where download is saved. + ''' An HttpClientHandler of the user performing the download. + ''' Progress Dialog. + ''' Time allotted before giving up on a connection. + ''' + ''' Indicates whether or not the file should be overwritten if local file already exists. + ''' + ''' + ''' Indicates what to do if user cancels dialog (either throw or do nothing). + ''' + ''' + ''' Calls to all the other overloads will come through here. + Friend Shared Async Function DownloadFileAsync( + addressUri As Uri, + destinationFileName As String, + clientHandler As HttpClientHandler, + dialog As ProgressDialog, + connectionTimeout As Integer, + overwrite As Boolean, + onUserCancel As UICancelOption, + cancelToken As CancellationToken) As Task + + If cancelToken = Nothing Then + cancelToken = New CancellationTokenSource().Token + End If + + If connectionTimeout <= 0 Then + Throw VbUtils.GetArgumentExceptionWithArgName( + argumentName:=NameOf(connectionTimeout), + resourceKey:=SR.Network_BadConnectionTimeout) + End If + + If addressUri Is Nothing Then + Throw VbUtils.GetArgumentNullException(NameOf(addressUri)) + End If + + Dim client As HttpClient = If(clientHandler Is Nothing, + New HttpClient(), + New HttpClient(clientHandler) + ) + + ' Set credentials if we have any + client.Timeout = New TimeSpan(0, 0, 0, 0, connectionTimeout) + + ' Construct the local file. This will validate the full name and path + Dim normalizedFilePath As String = FileSystemUtils.NormalizeFilePath( + path:=destinationFileName, + paramName:=NameOf(destinationFileName)) + + ' Sometime a path that can't be parsed is normalized to the current directory. + ' This makes sure we really have a file and path + If IO.Directory.Exists(normalizedFilePath) Then + Throw VbUtils.GetInvalidOperationException(SR.Network_DownloadNeedsFilename) + End If + + ' Throw if the file exists and the user doesn't want to overwrite + If Not overwrite AndAlso IO.File.Exists(normalizedFilePath) Then + Throw New IO.IOException( + message:=VbUtils.GetResourceString(SR.IO_FileExists_Path, destinationFileName)) + End If + + ' Check to see if the target directory exists. If it doesn't, create it + Dim targetDirectory As String = IO.Path.GetDirectoryName(normalizedFilePath) + + ' Make sure we have a meaningful directory. If we don't, the destinationFileName is suspect + If String.IsNullOrEmpty(targetDirectory) Then + Throw VbUtils.GetInvalidOperationException(SR.Network_DownloadNeedsFilename) + End If + + If Not IO.Directory.Exists(targetDirectory) Then + IO.Directory.CreateDirectory(targetDirectory) + End If + + ' Create the copier + Dim copier As New HttpClientCopy(client, dialog) + + ' Download the file + Try + Await copier.DownloadFileWorkerAsync( + addressUri, + normalizedFilePath, + externalToken:=cancelToken).ConfigureAwait(continueOnCapturedContext:=False) + Catch ex As Exception + If onUserCancel = UICancelOption.ThrowException OrElse Not dialog.UserCanceledTheDialog Then + Throw + End If + End Try + + End Function + + ''' + ''' Downloads a file from the network to the specified path. + ''' + ''' Address to the remote file, http, ftp etc... + ''' Name and path of file where download is saved. + ''' The name of the user performing the download. + ''' The user's password. + ''' A ProgressDialog or Nothing. + ''' Time allotted before giving up on a connection. + ''' + ''' Indicates whether or not the file should be overwritten if local file already exists. + ''' + ''' + Friend Shared Async Function DownloadFileAsync( + address As String, + destinationFileName As String, + userName As String, + password As String, + dialog As ProgressDialog, + connectionTimeout As Integer, + overwrite As Boolean, + Optional cancelToken As CancellationToken = Nothing) As Task + + Await DownloadFileAsync( + address, + destinationFileName, + userName, + password, + dialog, + connectionTimeout, + overwrite, + onUserCancel:=UICancelOption.ThrowException, + cancelToken).ConfigureAwait(continueOnCapturedContext:=False) + End Function + + ''' + ''' Downloads a file from the network to the specified path. + ''' + ''' Address to the remote file, http, ftp etc... + ''' Name and path of file where download is saved. + ''' The name of the user performing the download. + ''' The user's password. + ''' A ProgressDialog or Nothing. + ''' Time allotted before giving up on a connection. + ''' + ''' Indicates whether or not the file should be overwritten if local file already exists. + ''' + ''' + ''' Indicates what to do if user cancels dialog (either throw or do nothing). + ''' + ''' + Friend Shared Async Function DownloadFileAsync( + address As String, + destinationFileName As String, + userName As String, + password As String, + dialog As ProgressDialog, + connectionTimeout As Integer, + overwrite As Boolean, + onUserCancel As UICancelOption, + Optional cancelToken As CancellationToken = Nothing) As Task + + If String.IsNullOrWhiteSpace(address) Then + Throw VbUtils.GetArgumentNullException(NameOf(address)) + End If + + Dim addressUri As Uri = GetUri(address.Trim()) + + ' Get network credentials + Dim networkCredentials As ICredentials = GetNetworkCredentials(userName, password) + + Await DownloadFileAsync( + addressUri, + destinationFileName, + networkCredentials, + dialog, + connectionTimeout, + overwrite, + onUserCancel, + cancelToken).ConfigureAwait(continueOnCapturedContext:=False) + End Function + + ''' + ''' Downloads a file from the network to the specified path. + ''' + ''' Uri to the remote file + ''' Name and path of file where download is saved. + ''' The credentials of the user performing the download. + ''' A ProgressDialog or Nothing. + ''' Time allotted before giving up on a connection. + ''' + ''' Indicates whether or not the file should be overwritten if local file already exists. + ''' + ''' + ''' + ''' Function will Throw on unhandled exceptions. + ''' + Friend Shared Async Function DownloadFileAsync( + addressUri As Uri, + destinationFileName As String, + networkCredentials As ICredentials, + dialog As ProgressDialog, + connectionTimeout As Integer, + overwrite As Boolean, + Optional cancelToken As CancellationToken = Nothing) As Task + + Await DownloadFileAsync( + addressUri, + destinationFileName, + networkCredentials, + dialog, + connectionTimeout, + overwrite, + onUserCancel:=UICancelOption.ThrowException, + cancelToken).ConfigureAwait(continueOnCapturedContext:=False) + End Function + + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.Ping.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.Ping.vb index 2d149593d59..108fd13ee4e 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.Ping.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.Ping.vb @@ -8,13 +8,13 @@ Namespace Microsoft.VisualBasic.Devices Partial Public Class Network - 'Size of Ping.exe buffer + ' Size of Ping.exe buffer Private Const BUFFER_SIZE As Integer = 32 ' Default timeout for Ping Private Const DEFAULT_PING_TIMEOUT As Integer = 1000 - 'Holds the buffer for pinging. We lazy initialize on first use + ' Holds the buffer for pinging. We lazy initialize on first use Private _pingBuffer() As Byte ''' @@ -26,9 +26,10 @@ Namespace Microsoft.VisualBasic.Devices If _pingBuffer Is Nothing Then ReDim _pingBuffer(BUFFER_SIZE - 1) For i As Integer = 0 To BUFFER_SIZE - 1 - 'This is the same logic Ping.exe uses to fill it's buffer - Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture - _pingBuffer(i) = Convert.ToByte(Asc("a"c) + (i Mod 23), provider) + ' This is the same logic Ping.exe uses to fill it's buffer + _pingBuffer(i) = Convert.ToByte( + value:=Asc("a"c) + (i Mod 23), + provider:=Globalization.CultureInfo.InvariantCulture) Next End If diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.UploadFile.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.UploadFile.vb index f012efecd59..2770839678d 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.UploadFile.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.UploadFile.vb @@ -264,7 +264,7 @@ Namespace Microsoft.VisualBasic.Devices sourceFileName = FileSystemUtils.NormalizeFilePath(sourceFileName, NameOf(sourceFileName)) - 'Make sure the file exists + ' Make sure the file exists If Not IO.File.Exists(sourceFileName) Then Dim message As String = GetResourceString(SR.IO_FileNotFound_Path, sourceFileName) Throw New IO.FileNotFoundException(message) @@ -288,24 +288,15 @@ Namespace Microsoft.VisualBasic.Devices client.Credentials = networkCredentials End If - Dim dialog As ProgressDialog = Nothing - If showUI AndAlso Environment.UserInteractive Then - dialog = New ProgressDialog With { - .Text = GetResourceString(SR.ProgressDialogUploadingTitle, sourceFileName), - .LabelText = GetResourceString( - resourceKey:=SR.ProgressDialogUploadingLabel, - sourceFileName, - address.AbsolutePath) - } - End If + Dim dialog As ProgressDialog = GetProgressDialog(address.AbsolutePath, sourceFileName, showUI) - 'Create the copier + ' Create the copier Dim copier As New WebClientCopy(client, dialog) - 'Download the file + ' Download the file copier.UploadFile(sourceFileName, address) - 'Handle a dialog cancel + ' Handle a dialog cancel If showUI AndAlso Environment.UserInteractive Then If onUserCancel = UICancelOption.ThrowException And dialog.UserCanceledTheDialog Then Throw New OperationCanceledException() diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/NetworkUtilities.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/NetworkUtilities.vb index fec0451ee24..1458e5fcefe 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/NetworkUtilities.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/NetworkUtilities.vb @@ -83,7 +83,9 @@ Namespace Microsoft.VisualBasic.Devices ''' We also use this function to validate the UriString (remote file address). ''' ''' The remote file address. - ''' A if successful, otherwise it throws an . + ''' + ''' A if successful, otherwise it throws an . + ''' Friend Function GetUri(address As String) As Uri Try Return New Uri(address) diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/ClipboardProxy.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/ClipboardProxy.vb index 2a747f9d266..0b1c5913ace 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/ClipboardProxy.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/ClipboardProxy.vb @@ -10,7 +10,7 @@ Imports System.Windows.Forms Namespace Microsoft.VisualBasic.MyServices ''' - ''' A class that wraps System.Windows.Forms.Clipboard so that + ''' A class that wraps so that ''' a clipboard can be instanced. ''' @@ -23,22 +23,23 @@ Namespace Microsoft.VisualBasic.MyServices End Sub ''' - ''' Removes everything from the clipboard. + ''' Removes all data from the . ''' Public Sub Clear() Clipboard.Clear() End Sub ''' - ''' Indicates whether or not there's an audio stream saved to the clipboard. + ''' Indicates whether there is data on the in the format./>. ''' - ''' if an audio stream is available, otherwise . + ''' if an audio is available, otherwise . Public Function ContainsAudio() As Boolean Return Clipboard.ContainsAudio() End Function ''' - ''' Indicates whether or not there is data on the clipboard in the passed in format. + ''' Indicates whether or not there is data on the in the passed in format + ''' or can be converted to that format. ''' ''' ''' if there's data in the passed in format, otherwise . @@ -47,7 +48,8 @@ Namespace Microsoft.VisualBasic.MyServices End Function ''' - ''' Indicates whether or not a file drop list has been saved to the clipboard. + ''' Indicates whether there is data on the that is in the + ''' format or can be converted to that format. ''' ''' if a file drop list is available, otherwise . Public Function ContainsFileDropList() As Boolean @@ -55,7 +57,8 @@ Namespace Microsoft.VisualBasic.MyServices End Function ''' - ''' Indicate whether or not an image has been saved to the clipboard. + ''' Indicates whether there Is data on the that Is in the + ''' format or can be converted to that format. ''' ''' if an image is available, otherwise . Public Function ContainsImage() As Boolean @@ -63,7 +66,7 @@ Namespace Microsoft.VisualBasic.MyServices End Function ''' - ''' Indicates whether or not text is available on the clipboard. + ''' Indicates whether there is text data on the in format. ''' ''' if text is available, otherwise . Public Function ContainsText() As Boolean @@ -71,8 +74,8 @@ Namespace Microsoft.VisualBasic.MyServices End Function ''' - ''' Indicates whether or not text is available on the clipboard in - ''' the passed in format. + ''' Indicates whether there is text data on the in the format indicated by the + ''' specified value. ''' ''' The type of text being checked for. ''' if text is available, otherwise . @@ -81,15 +84,15 @@ Namespace Microsoft.VisualBasic.MyServices End Function ''' - ''' Gets an audio stream from the clipboard. + ''' Retrieves an audio stream from the . ''' - ''' The audio stream as a Stream. + ''' The audio stream as a . Public Function GetAudioStream() As Stream Return Clipboard.GetAudioStream() End Function ''' - ''' Gets data from the clipboard that's been saved in the passed in format. + ''' Gets data from the that's been saved in the passed in format. ''' ''' The type of data being sought. ''' The data. @@ -98,9 +101,9 @@ Namespace Microsoft.VisualBasic.MyServices End Function ''' - ''' Gets a from the clipboard. + ''' Retrieves the data that is currently on the system . ''' - ''' The data object. + ''' The . ''' This gives the ability to save an object in multiple formats. Public Function GetDataObject() As IDataObject @@ -108,7 +111,7 @@ Namespace Microsoft.VisualBasic.MyServices End Function ''' - ''' Gets a file drop list from the clipboard. + ''' Retrieves a collection of file names from the . ''' ''' The list of file paths as a . Public Function GetFileDropList() As StringCollection @@ -116,32 +119,33 @@ Namespace Microsoft.VisualBasic.MyServices End Function ''' - ''' Gets an Image from the clipboard. + ''' Retrieves an from the . ''' - ''' The image. + ''' Public Function GetImage() As Image Return Clipboard.GetImage() End Function ''' - ''' Gets text from the clipboard. + ''' Retrieves text data from the in the format. ''' - ''' The text as a String. + ''' The text as a . Public Function GetText() As String Return Clipboard.GetText() End Function ''' - ''' Gets text from the clipboard saved in the passed in format. + ''' Retrieves text data from the in the format indicated by the specified + ''' value. ''' ''' The type of text to get. - ''' The text as a String. + ''' The text as a . Public Function GetText(format As TextDataFormat) As String Return Clipboard.GetText(format) End Function ''' - ''' Saves the passed in audio byte array to the clipboard. + ''' Clears the and then adds data in the format. ''' ''' The byte array to be saved. Public Sub SetAudio(audioBytes As Byte()) @@ -149,15 +153,15 @@ Namespace Microsoft.VisualBasic.MyServices End Sub ''' - ''' Saves the passed in audio stream to the clipboard. + ''' Clears the and then adds data in the format. ''' - ''' The stream to be saved. + ''' The to be saved. Public Sub SetAudio(audioStream As Stream) Clipboard.SetAudio(audioStream) End Sub ''' - ''' Saves the passed in data to the clipboard in the passed in format. + ''' Clears the and then adds data in the specified format. ''' ''' The format in which to save the data. ''' The data to be saved. @@ -166,9 +170,9 @@ Namespace Microsoft.VisualBasic.MyServices End Sub ''' - ''' Saves a to the clipboard. + ''' Places nonpersistent on the . ''' - ''' The data object to be saved. + ''' The to be saved. ''' This gives the ability to save an object in multiple formats. Public Sub SetDataObject(data As DataObject) @@ -176,7 +180,8 @@ Namespace Microsoft.VisualBasic.MyServices End Sub ''' - ''' Saves the passed in file drop list to the clipboard. + ''' Clears the > and then adds a collection of file names + ''' in the format. ''' ''' The file drop list as a . Public Sub SetFileDropList(filePaths As StringCollection) @@ -192,7 +197,7 @@ Namespace Microsoft.VisualBasic.MyServices End Sub ''' - ''' Saves the passed in String to the clipboard. + ''' Clears the Clipboard and then adds text data in the format. ''' ''' The to save. Public Sub SetText(text As String) diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/HttpClientCopy.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/HttpClientCopy.vb new file mode 100644 index 00000000000..8a38aba6efe --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/HttpClientCopy.vb @@ -0,0 +1,221 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. + +Imports System.IO +Imports System.Net +Imports System.Net.Http +Imports System.Threading +Imports Microsoft.VisualBasic.Devices.NetworkUtilities + +Namespace Microsoft.VisualBasic.MyServices.Internal + + ''' + ''' Class that controls the thread that does the actual work of downloading or uploading. + ''' + Friend NotInheritable Class HttpClientCopy + + ' Dialog shown if user wants to see progress UI. Allows the user to cancel the file transfer. + Private WithEvents _progressDialog As ProgressDialog + + ' The WebClient performs the downloading or uploading operations for us + Private ReadOnly _httpClient As HttpClient + + Private _cancelTokenSourceGet As CancellationTokenSource + Private _cancelTokenSourceRead As CancellationTokenSource + Private _cancelTokenSourceReadStream As CancellationTokenSource + Private _cancelTokenSourceWrite As CancellationTokenSource + + ' The percentage of the operation completed + Private _percentage As Integer + + ' Used for invoking ProgressDialog.Increment + Private Delegate Sub DoIncrement(Increment As Integer) + + ''' + ''' Creates an instance of a HttpClientCopy, used to download or upload a file. + ''' + ''' The HttpClient used to do the downloading or uploading. + ''' UI for indicating progress. + Public Sub New(client As HttpClient, dialog As ProgressDialog) + + Debug.Assert(client IsNot Nothing, "No HttpClient") + + _httpClient = client + _progressDialog = dialog + If _progressDialog IsNot Nothing Then + AddHandler _progressDialog.UserHitCancel, AddressOf _progressDialog_UserHitCancel + End If + + End Sub + + ''' + ''' Notifies the progress dialog to increment the progress bar. + ''' + ''' The percentage of bytes read. + Private Sub InvokeIncrement(progressPercentage As Integer) + ' Don't invoke unless dialog is up and running + If _progressDialog IsNot Nothing Then + If _progressDialog.IsHandleCreated Then + + ' For performance, don't invoke if increment is 0 + Dim increment As Integer = progressPercentage - _percentage + _percentage = progressPercentage + If increment > 0 Then + _progressDialog.BeginInvoke(New DoIncrement(AddressOf _progressDialog.Increment), increment) + End If + + End If + End If + End Sub + + ''' + ''' If the user clicks cancel on the Progress dialog, we need to cancel + ''' the current async file transfer operation. + ''' + ''' + ''' Note that we don't want to close the progress dialog here. Wait until + ''' the actual file transfer cancel event comes through and do it there. + ''' + Private Sub _progressDialog_UserHitCancel() + ' Cancel the upload/download transfer. We'll close the ProgressDialog + ' as soon as the HttpClient cancels the xfer. + _cancelTokenSourceGet.Cancel() + _cancelTokenSourceRead.Cancel() + _cancelTokenSourceReadStream.Cancel() + _cancelTokenSourceWrite.Cancel() + End Sub + + ''' + ''' Downloads a file. + ''' + ''' The source for the file. + ''' The path and name where the file is to be saved. + Friend Async Function DownloadFileWorkerAsync(addressUri As Uri, normalizedFilePath As String, externalToken As CancellationToken) As Task + Debug.Assert(_httpClient IsNot Nothing, "No HttpClient") + Debug.Assert(addressUri IsNot Nothing, "No address") + Dim directoryPath As String = Path.GetDirectoryName(Path.GetFullPath(normalizedFilePath)) + Debug.Assert((Not String.IsNullOrWhiteSpace(normalizedFilePath)) AndAlso + Directory.Exists(directoryPath), "Invalid path") + + _cancelTokenSourceGet = New CancellationTokenSource() + _cancelTokenSourceRead = New CancellationTokenSource() + _cancelTokenSourceReadStream = New CancellationTokenSource() + _cancelTokenSourceWrite = New CancellationTokenSource() + + Dim response As HttpResponseMessage = Nothing + + _cancelTokenSourceGet = New CancellationTokenSource() + Using linkedCts As CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cancelTokenSourceGet.Token, externalToken) + Try + response = Await _httpClient.GetAsync( + requestUri:=addressUri, + completionOption:=HttpCompletionOption.ResponseHeadersRead, + cancellationToken:=_cancelTokenSourceGet.Token).ConfigureAwait(continueOnCapturedContext:=False) + + Catch ex As TaskCanceledException + If ex.CancellationToken = externalToken Then + externalToken.ThrowIfCancellationRequested() + ElseIf ex.CancellationToken = _cancelTokenSourceGet.Token Then + ' a real cancellation, triggered by the caller + Throw + Else + Throw New WebException(SR.net_webstatus_Timeout, WebExceptionStatus.Timeout) + End If + End Try + End Using + Select Case response.StatusCode + Case HttpStatusCode.OK + _cancelTokenSourceRead = CancellationTokenSource.CreateLinkedTokenSource(New CancellationTokenSource().Token, externalToken) + _cancelTokenSourceReadStream = CancellationTokenSource.CreateLinkedTokenSource(New CancellationTokenSource().Token, externalToken) + _cancelTokenSourceWrite = CancellationTokenSource.CreateLinkedTokenSource(New CancellationTokenSource().Token, externalToken) + Dim contentLength? As Long = response?.Content.Headers.ContentLength + If contentLength.HasValue Then + Using responseStream As Stream = Await response.Content.ReadAsStreamAsync( + cancellationToken:=_cancelTokenSourceReadStream.Token). + ConfigureAwait(continueOnCapturedContext:=False) + + Using fileStream As New FileStream( + path:=normalizedFilePath, + mode:=FileMode.Create, + access:=FileAccess.Write, + share:=FileShare.None) + + Dim buffer(8191) As Byte + Dim totalBytesRead As Long = 0 + Dim bytesRead As Integer + Try + bytesRead = Await responseStream.ReadAsync( + buffer:=buffer.AsMemory(start:=0, buffer.Length), + cancellationToken:=_cancelTokenSourceRead.Token). + ConfigureAwait(continueOnCapturedContext:=False) + + Do While bytesRead > 0 + totalBytesRead += bytesRead + + Await fileStream.WriteAsync( + buffer:=buffer.AsMemory(0, bytesRead), + cancellationToken:=_cancelTokenSourceWrite.Token). + ConfigureAwait(continueOnCapturedContext:=False) + + If _progressDialog IsNot Nothing Then + Dim percentage As Integer = CInt(totalBytesRead / contentLength.Value * 100) + InvokeIncrement(percentage) + End If + bytesRead = Await responseStream.ReadAsync( + buffer:=buffer.AsMemory(start:=0, buffer.Length), + cancellationToken:=_cancelTokenSourceRead.Token). + ConfigureAwait(continueOnCapturedContext:=False) + Loop + Finally + CloseProgressDialog(_progressDialog) + End Try + End Using + End Using + If response.StatusCode = HttpStatusCode.OK Then + End If + + If _progressDialog IsNot Nothing Then + RemoveHandler _progressDialog.UserHitCancel, AddressOf _progressDialog_UserHitCancel + End If + End If + + Case HttpStatusCode.Unauthorized + Throw New WebException(SR.net_webstatus_Unauthorized, WebExceptionStatus.ProtocolError) + Case Else + Throw New WebException() + End Select + response?.Dispose() + End Function + +#If False Then ' Future code to implement upload using Http + ''' + ''' Uploads a file + ''' + ''' The name and path of the source file + ''' The address to which the file is uploaded + Public Sub UploadFile(sourceFileName As String, address As Uri) + Debug.Assert(_httpClient IsNot Nothing, "No WebClient") + Debug.Assert(address IsNot Nothing, "No address") + Debug.Assert((Not String.IsNullOrWhiteSpace(sourceFileName)) AndAlso + File.Exists(sourceFileName), "Invalid file") + + ' If we have a dialog we need to set up an async download + If _progressDialog IsNot Nothing Then + _httpClient.UploadFileAsync(address, sourceFileName) + ' returns when the download sequence is over, whether due to success, error, or being canceled + _progressDialog.ShowProgressDialog() + Else + _httpClient.UploadFile(address, sourceFileName) + End If + + ' Now that we are back on the main thread, throw the exception we encountered if the user didn't cancel. + If _exceptionEncounteredDuringFileTransfer IsNot Nothing Then + If _progressDialog Is Nothing OrElse Not _progressDialog.UserCanceledTheDialog Then + Throw _exceptionEncounteredDuringFileTransfer + End If + End If + End Sub +#End If + + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/WebClientCopy.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/WebClientCopy.vb index 203d72a44d2..54a9396cb18 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/WebClientCopy.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/WebClientCopy.vb @@ -17,7 +17,8 @@ Namespace Microsoft.VisualBasic.MyServices.Internal ' The WebClient performs the downloading or uploading operations for us Private WithEvents _webClient As WebClient - 'Keeps track of the error that happened during upload/download so we can throw it once we can guarantee we are back on the main thread + ' Keeps track of the error that happened during upload/download so we can throw it + ' once we can guarantee we are back on the main thread Private _exceptionEncounteredDuringFileTransfer As Exception ' The percentage of the operation completed @@ -47,46 +48,11 @@ Namespace Microsoft.VisualBasic.MyServices.Internal ''' the actual file transfer cancel event comes through and do it there. ''' Private Sub _progressDialog_UserHitCancel() Handles _progressDialog.UserHitCancel - 'cancel the upload/download transfer. We'll close the ProgressDialog - 'as soon as the WebClient cancels the xfer. + ' Cancel the upload/download transfer. We'll close the ProgressDialog + ' as soon as the WebClient cancels the xfer. _webClient.CancelAsync() End Sub - ''' - ''' Handles the WebClient's DownloadFileCompleted event. - ''' - ''' - ''' - Private Sub _webClient_DownloadFileCompleted(sender As Object, e As ComponentModel.AsyncCompletedEventArgs) _ - Handles _webClient.DownloadFileCompleted - - Try - ' If the download was interrupted by an exception, keep track of the exception, - ' which we'll throw from the main thread - If e.Error IsNot Nothing Then - _exceptionEncounteredDuringFileTransfer = e.Error - End If - - If Not e.Cancelled AndAlso e.Error Is Nothing Then - InvokeIncrement(100) - End If - Finally - 'We don't close the dialog until we receive the WebClient.DownloadFileCompleted event - CloseProgressDialog(_progressDialog) - End Try - End Sub - - ''' - ''' Handles event WebClient fires whenever progress of download changes. - ''' - ''' - ''' - Private Sub _webClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) _ - Handles _webClient.DownloadProgressChanged - - InvokeIncrement(e.ProgressPercentage) - End Sub - ''' ''' Handles the WebClient's UploadFileCompleted event. ''' @@ -95,8 +61,8 @@ Namespace Microsoft.VisualBasic.MyServices.Internal Private Sub _webClient_UploadFileCompleted(sender As Object, e As UploadFileCompletedEventArgs) _ Handles _webClient.UploadFileCompleted - ' If the upload was interrupted by an exception, keep track of the - ' exception, which we'll throw from the main thread + ' If the upload was interrupted by an exception, keep track of the exception, + ' which we'll throw from the main thread Try If e.Error IsNot Nothing Then _exceptionEncounteredDuringFileTransfer = e.Error @@ -105,8 +71,8 @@ Namespace Microsoft.VisualBasic.MyServices.Internal InvokeIncrement(100) End If Finally - 'We don't close the dialog until we receive the - 'WebClient.DownloadFileCompleted event + ' We don't close the dialog until we receive the + ' WebClient.DownloadFileCompleted event CloseProgressDialog(_progressDialog) End Try End Sub @@ -145,36 +111,6 @@ Namespace Microsoft.VisualBasic.MyServices.Internal End If End Sub - ''' - ''' Downloads a file. - ''' - ''' The source for the file. - ''' The path and name where the file is saved. - Public Sub DownloadFile(address As Uri, destinationFileName As String) - Debug.Assert(_webClient IsNot Nothing, $"No {NameOf(_webClient)}") - Debug.Assert(address IsNot Nothing, $"No {NameOf(address)}") - Dim path As String = IO.Path.GetDirectoryName(IO.Path.GetFullPath(destinationFileName)) - Debug.Assert((Not String.IsNullOrWhiteSpace(destinationFileName)) _ - AndAlso IO.Directory.Exists(path), $"Invalid {NameOf(path)}") - - ' If we have a dialog we need to set up an async download - If _progressDialog IsNot Nothing Then - _webClient.DownloadFileAsync(address, destinationFileName) - 'returns when the download sequence is over, whether due to success, error, or being canceled - _progressDialog.ShowProgressDialog() - Else - _webClient.DownloadFile(address, destinationFileName) - End If - - 'Now that we are back on the main thread, throw the exception we encountered if the user didn't cancel. - If _exceptionEncounteredDuringFileTransfer IsNot Nothing Then - If _progressDialog Is Nothing OrElse Not _progressDialog.UserCanceledTheDialog Then - Throw _exceptionEncounteredDuringFileTransfer - End If - End If - - End Sub - ''' ''' Uploads a file. ''' @@ -189,14 +125,16 @@ Namespace Microsoft.VisualBasic.MyServices.Internal ' If we have a dialog we need to set up an async download If _progressDialog IsNot Nothing Then _webClient.UploadFileAsync(address, sourceFileName) - 'returns when the download sequence is over, whether due to success, error, or being canceled + + ' Returns when the download sequence is over, + ' whether due to success, error, or being canceled _progressDialog.ShowProgressDialog() Else _webClient.UploadFile(address, sourceFileName) End If - 'Now that we are back on the main thread, throw the exception we - 'encountered if the user didn't cancel. + ' Now that we are back on the main thread, throw the exception we + ' encountered if the user didn't cancel. If _exceptionEncounteredDuringFileTransfer IsNot Nothing Then If _progressDialog Is Nothing OrElse Not _progressDialog.UserCanceledTheDialog Then Throw _exceptionEncounteredDuringFileTransfer diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/SR.resx b/src/Microsoft.VisualBasic.Forms/src/Resources/SR.resx index ff406c3aee6..47f58111e22 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/SR.resx +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/SR.resx @@ -1,16 +1,16 @@  - @@ -221,4 +221,10 @@ Environment variable is not defined: '{0}'. + + The network operation has timed out. + + + The network operation is unauthorized. + diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.cs.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.cs.xlf index f737611c412..9b04fd1c94c 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.cs.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.cs.xlf @@ -177,6 +177,16 @@ Ukládání {0} + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.de.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.de.xlf index e4e2a7e5e3e..4241a9c79fc 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.de.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.de.xlf @@ -177,6 +177,16 @@ {0} wird hochgeladen + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.es.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.es.xlf index 006fe62ea7d..b928124e52c 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.es.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.es.xlf @@ -177,6 +177,16 @@ Cargando {0} + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.fr.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.fr.xlf index 3e06f665f6a..cfa6763c203 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.fr.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.fr.xlf @@ -177,6 +177,16 @@ Chargement de {0} + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.it.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.it.xlf index cc73272c979..a040a2d48e4 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.it.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.it.xlf @@ -177,6 +177,16 @@ Caricamento di {0} + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ja.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ja.xlf index d9c1b872741..95057a734e3 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ja.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ja.xlf @@ -177,6 +177,16 @@ {0} のアップロード中 + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ko.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ko.xlf index 5546130053f..90a42911b9a 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ko.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ko.xlf @@ -177,6 +177,16 @@ {0} 업로드 중 + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.pl.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.pl.xlf index 35284bb512e..96ece95f46b 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.pl.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.pl.xlf @@ -177,6 +177,16 @@ Przekazywanie: {0} + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.pt-BR.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.pt-BR.xlf index 1e1b8f1416f..4f87094e257 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.pt-BR.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.pt-BR.xlf @@ -177,6 +177,16 @@ Carregando {0} + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ru.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ru.xlf index e400e684656..bfa18e769da 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ru.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.ru.xlf @@ -177,6 +177,16 @@ Идет отправка {0} + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.tr.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.tr.xlf index 751c15e6832..42b54249b7b 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.tr.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.tr.xlf @@ -177,6 +177,16 @@ {0} karşıya yükleniyor + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.zh-Hans.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.zh-Hans.xlf index af55164f9e7..27bbc168d6f 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.zh-Hans.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.zh-Hans.xlf @@ -177,6 +177,16 @@ 正在上传 {0} + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.zh-Hant.xlf b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.zh-Hant.xlf index c3df5ab1fb7..b9e74cf4c97 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.zh-Hant.xlf +++ b/src/Microsoft.VisualBasic.Forms/src/Resources/xlf/SR.zh-Hant.xlf @@ -177,6 +177,16 @@ 正在上傳 {0} + + The network operation has timed out. + The network operation has timed out. + + + + The network operation is unauthorized. + The network operation is unauthorized. + + \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/Microsoft.VisualBasic.Forms.Tests.vbproj b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/Microsoft.VisualBasic.Forms.Tests.vbproj index 48eca2f60d4..4b31b66fd0d 100644 --- a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/Microsoft.VisualBasic.Forms.Tests.vbproj +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/Microsoft.VisualBasic.Forms.Tests.vbproj @@ -1,6 +1,6 @@  - + $(TargetFramework) $(TargetFramework)-windows7.0 true @@ -13,7 +13,6 @@ WindowsFormsWithCustomSubMain True Library - diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/NetworkDownloadTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/NetworkDownloadTests.vb new file mode 100644 index 00000000000..801d484af23 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/NetworkDownloadTests.vb @@ -0,0 +1,1568 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. + +Imports System.IO +Imports System.Net +Imports FluentAssertions +Imports Microsoft.VisualBasic.FileIO +Imports Xunit + +Namespace Microsoft.VisualBasic.Forms.Tests + + Public Class NetworkTests + Inherits VbFileCleanupTestBase + + Private Const DefaultPassword As String = NameOf(DefaultPassword) + Private Const DefaultUserName As String = NameOf(DefaultUserName) + Private Const DownloadLargeFileSize As Integer = 104_857_600 + Private Const DownloadSmallFileSize As Integer = 18_135 + Private Const InvalidUrlAddress As String = "invalidURL" + Private Const TestingConnectionTimeout As Integer = 100_000 + + Private Shared Sub CleanUpListener(listener As HttpListener) + listener.Stop() + listener.Close() + End Sub + + ''' + ''' Verify that testDirectory exists, that destinationFileName exist and what its length is. + ''' + ''' A Unique directory under the systems Temp directory. + ''' The full path and filename of the new file. + ''' + Private Shared Sub VerifyAndCleanupFailedDownload( + testDirectory As String, + destinationFileName As String, + listener As HttpListener) + + If Not String.IsNullOrWhiteSpace(testDirectory) Then + Directory.Exists(testDirectory).Should.BeTrue() + End If + If Not String.IsNullOrWhiteSpace(destinationFileName) Then + Call New FileInfo(destinationFileName).Exists.Should.BeFalse() + End If + CleanUpListener(listener) + End Sub + + ''' + ''' Verify that testDirectory exists, that destinationFileName exist and what its length is. + ''' + ''' A Unique directory under the systems Temp directory. + ''' + ''' The size in bytes of the destination file, this saves the caller from having to + ''' do another FileInfo call. + ''' + ''' The full path and filename of the new file. + ''' + Private Shared Function VerifyAndCleanupSuccessfulDownload( + testDirectory As String, + destinationFileName As String, + listener As HttpListener) As Long + + Directory.Exists(testDirectory).Should.BeTrue() + Dim fileInfo As New FileInfo(destinationFileName) + fileInfo.Exists.Should.BeTrue() + Directory.Exists(fileInfo.DirectoryName).Should.BeTrue() + ' This directory should not be systems Temp Directory because it must be created + Path.GetTempPath.Should.NotBe(fileInfo.DirectoryName) + CleanUpListener(listener) + Return fileInfo.Length + End Function + + + Public Sub DownloadFile_UriOnly_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UriOnlyWhereAddressIsEmptyString_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(String.Empty), + destinationFileName) + End Sub + + testCode.Should.Throw(Of UriFormatException)() + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriOnlyWhereAddressIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(Nothing), + destinationFileName) + End Sub + + testCode.Should.Throw(Of ArgumentNullException)() + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + Public Sub DownloadFile_UriOnlyWhereDestinationFileNameInvalidAddressOnly_Throws(destinationFileName As String) + Dim testDirectory As String = CreateTempDirectory() + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancel_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim networkCredentials As New NetworkCredential(DefaultUserName, DefaultPassword) + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + networkCredentials, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereDestinationFileNameInvalidOverwrite_Throws( + destinationFileName As String) + + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=Nothing, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereFileExistsNoOverwrite_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=1) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + Dim value As String = SR.IO_FileExists_Path.Replace("{0}", destinationFileName) + testCode.Should() _ + .Throw(Of IOException)() _ + .Where(Function(e) e.Message.Equals(value)) + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should.Be(1) + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereOverwriteTrue_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=1) + Dim webListener As New WebListener(DownloadLargeFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadLargeFileSize) + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereOverwriteWhereDestinationFileExists_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=1) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWherePasswordWrong_Throws(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + Dim networkCredentials As New NetworkCredential(DefaultUserName, password) + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + networkCredentials, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereTimeOut_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadLargeFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=1, + overwrite:=True) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Timeout) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereTimeoutNegative_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadLargeFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=-1, + overwrite:=False) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(SR.Network_BadConnectionTimeout)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereUriIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=CType(Nothing, Uri), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereUrlInvalid_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(InvalidUrlAddress), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + testCode.Should().Throw(Of UriFormatException)() + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereUsernameIsNothing_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=Nothing, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsAndNetworkCredentials_Fail() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim networkCredentials As New NetworkCredential(DefaultUserName, DefaultPassword) + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=Nothing, + destinationFileName, + networkCredentials, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.Throw(Of ArgumentNullException)() + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsAndNetworkCredentials_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim networkCredentials As New NetworkCredential(DefaultUserName, DefaultPassword) + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + networkCredentials, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsAndNetworkCredentialsTimeout0_Fail() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim networkCredentials As New NetworkCredential(DefaultUserName, DefaultPassword) + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + networkCredentials, + showUI:=False, + connectionTimeout:=0, + overwrite:=True, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.Throw(Of ArgumentException)() + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsDoNotShowUI_ExceptOnUserCancelWhereInvalidUrl_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(InvalidUrlAddress), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + testCode.Should.Throw(Of UriFormatException)() + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + Public Sub DownloadFile_UriWithAllOptionsExceptOnUserCancelWhereDestinationFileNameInvalidOverwriteThrows( + destinationFileName As String) + + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=Nothing, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Sub + + + + + Public Sub DownloadFile_UriWithAllOptionsWhereCheckFilePathTrailingSeparators_Throw(separator As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=$"{destinationFileName}{separator}", + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + Dim exceptionExpression As Expressions.Expression(Of Func(Of ArgumentException, Boolean)) = + Function(e) e.Message.StartsWith(SR.IO_FilePathException) _ + AndAlso e.Message.Contains(NameOf(destinationFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + Public Sub DownloadFile_UriWithAllOptionsWhereDestinationFileNameInvalid_Throws(destinationFileName As String) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=Nothing, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should.Throw(Of ArgumentNullException)() + VerifyAndCleanupFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Sub + + + + + Public Sub DownloadFile_UriWithAllOptionsWhereDestinationIsRootDirectory_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=root, ' This is a Root Directory! + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + Dim exceptionExpression As Expressions.Expression(Of Func(Of ArgumentException, Boolean)) = + Function(e) e.Message.StartsWith(SR.IO_FilePathException) _ + AndAlso e.Message.Contains(NameOf(destinationFileName)) + testCode.Should.Throw(Of ArgumentException)().Where(exceptionExpression) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + + Public Sub DownloadFile_UriWithAllOptionsWhereFilePathTrailingSeparatorsAreInvalid_Throw(separator As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=$"{destinationFileName}{separator}", + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + Dim exceptionExpression As Expressions.Expression(Of Func(Of ArgumentException, Boolean)) = + Function(e) e.Message.StartsWith(SR.IO_FilePathException) _ + AndAlso e.Message.Contains(NameOf(destinationFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsWhereOnUserCancelIsDoNothing_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + + + Public Sub DownloadFile_UriWithAllOptionsWhereRootDirectoryInvalid_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=root, ' This is a Root Directory! + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of InvalidOperationException)() _ + .Where(Function(e) e.Message.StartsWith(SR.Network_DownloadNeedsFilename)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + + Public Sub DownloadFile_UriWithAllOptionsWhereRootDirectoryTrailingSeparatorInvalid_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=root, ' This is a Root Directory! + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + Dim exceptionExpression As Expressions.Expression(Of Func(Of ArgumentException, Boolean)) = + Function(e) e.Message.StartsWith(SR.IO_FilePathException) _ + AndAlso e.Message.Contains(NameOf(destinationFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsWhereTargetDirectoryNonexistent_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Directory.Delete(testDirectory, recursive:=True) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsWhereUriIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=CType(Nothing, Uri), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsWithAllOptions_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsWithAllOptionsWithAllOptionsWhereDestinationIsDirectory_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=testDirectory, ' This is a Directory! + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of InvalidOperationException)() _ + .WithMessage(SR.Network_DownloadNeedsFilename) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UriWithUserNamePassword_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=DefaultUserName, + password:=DefaultPassword) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + + + Public Sub DownloadFile_UriWithUserNamePasswordWherePasswordWrong_Throw(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=String.Empty) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=DefaultUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + + Public Sub DownloadFile_UriWithUserNamePasswordWherePasswordWrong_Throws(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=DefaultUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlOnly_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + + Public Sub DownloadFile_UrlOnlyWhereAddressInvalid_Throws(address As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address, + destinationFileName) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + Public Sub DownloadFile_UrlOnlyWhereDestinationFileNameInvalidAddressOnly_Throws(destinationFileName As String) + Dim testDirectory As String = CreateTempDirectory() + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereDestinationFileNameInvalidOverwrite_Throws( + destinationFileName As String) + + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName:=Nothing, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereFileExistsNoOverwrite_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=1) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + Dim value As String = SR.IO_FileExists_Path.Replace("{0}", destinationFileName) + testCode.Should() _ + .Throw(Of IOException)() _ + .Where(Function(e) e.Message.Equals(value)) + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should.Be(1) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereInvalidUrlDoNotShowUI_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=InvalidUrlAddress, + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + Dim value As String = SR.Network_InvalidUriString.Replace("{0}", "invalidURL") + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(value)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereOverwriteTrue_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=1) + Dim webListener As New WebListener(DownloadLargeFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadLargeFileSize) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereOverwriteWhereDestinationFileExists_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=1) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereTimeOut_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadLargeFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=1, + overwrite:=True) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Timeout) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereTimeoutNegative_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadLargeFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=-1, + overwrite:=False) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(SR.Network_BadConnectionTimeout)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereUrlInvalid_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=InvalidUrlAddress, + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + Dim value As String = SR.Network_InvalidUriString.Replace("{0}", "invalidURL") + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(value)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereUsernameIsNothing_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=Nothing, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsAndNetworkCredentials_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim networkCredentials As New NetworkCredential(DefaultUserName, DefaultPassword) + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + networkCredentials, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsDoNotShowUI_ExceptOnUserCancelWhereInvalidUrl_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=InvalidUrlAddress, + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False) + End Sub + + Dim value As String = SR.Network_InvalidUriString.Replace("{0}", "invalidURL") + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(value)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + Public Sub DownloadFile_UrlWithAllOptionsWhereDestinationFileNameInvalid_Throws(destinationFileName As String) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName:=Nothing, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Sub + + + + + Public Sub DownloadFile_UrlWithAllOptionsWhereDestinationIsRootDirectory_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName:=root, ' This is a Root Directory! + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + Dim exceptionExpression As Expressions.Expression(Of Func(Of ArgumentException, Boolean)) = + Function(e) e.Message.StartsWith(SR.IO_FilePathException) _ + AndAlso e.Message.Contains(NameOf(destinationFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + + Public Sub DownloadFile_UrlWithAllOptionsWhereFilePathTrailingSeparatorsAreInvalid_Throw(separator As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName:=$"{destinationFileName}{separator}", + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + Dim exceptionExpression As Expressions.Expression(Of Func(Of ArgumentException, Boolean)) = + Function(e) e.Message.StartsWith(SR.IO_FilePathException) _ + AndAlso e.Message.Contains(NameOf(destinationFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsWhereOnUserCancelIsDoNothing_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + + + Public Sub DownloadFile_UrlWithAllOptionsWhereRootDirectoryInvalid_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName:=root, ' This is a Root Directory! + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of InvalidOperationException)() _ + .Where(Function(e) e.Message.StartsWith(SR.Network_DownloadNeedsFilename)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + + Public Sub DownloadFile_UrlWithAllOptionsWhereRootDirectoryTrailingSeparatorInvalid_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName:=root, ' This is a Root Directory! + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + Dim exceptionExpression As Expressions.Expression(Of Func(Of ArgumentException, Boolean)) = + Function(e) e.Message.StartsWith(SR.IO_FilePathException) _ + AndAlso e.Message.Contains(NameOf(destinationFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsWhereTargetDirectoryNonexistent_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Directory.Delete(testDirectory, recursive:=True) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsWhereUriIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=CType(Nothing, Uri), + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsWithAllOptions_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsWithAllOptionsWithAllOptionsWhereDestinationIsDirectory_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(DownloadSmallFileSize) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName:=testDirectory, ' This is a Directory! + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of InvalidOperationException)() _ + .WithMessage(SR.Network_DownloadNeedsFilename) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + Public Sub DownloadFile_UrlWithUserNamePassword_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=DefaultUserName, + password:=DefaultPassword) + End Sub + + testCode.Should.NotThrow() + VerifyAndCleanupSuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(DownloadSmallFileSize) + End Sub + + + + + Public Sub DownloadFile_UrlWithUserNamePasswordWherePasswordWrong_Throw(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=String.Empty) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=DefaultUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + + + + Public Sub DownloadFile_UrlWithUserNamePasswordWherePasswordWrong_Throws(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=DownloadSmallFileSize, + userName:=DefaultUserName, + password:=DefaultPassword) + Dim listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=DefaultUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyAndCleanupFailedDownload(testDirectory, destinationFileName, listener) + End Sub + + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/WebListener.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/WebListener.vb new file mode 100644 index 00000000000..f8cd3aef554 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/WebListener.vb @@ -0,0 +1,98 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. + +Imports System.IO +Imports System.Net +Imports System.Runtime.CompilerServices +Imports System.Threading + +Namespace Microsoft.VisualBasic.Forms.Tests + + Public Class WebListener + Private ReadOnly _downloadFileUrlPrefix As String + Private ReadOnly _fileSize As Integer + Private ReadOnly _password As String + Private ReadOnly _userName As String + + ''' + ''' The name of the function that creates the server is uses to establish the file to be downloaded. + ''' + ''' Is used to create the file name and the size of download. + ''' Used to establish the file path to be downloaded. + Public Sub New(fileSize As Integer, Optional memberName As String = Nothing) + _fileSize = fileSize + _downloadFileUrlPrefix = $"http://127.0.0.1:8080/{memberName}/" + Address = $"{_downloadFileUrlPrefix}T{fileSize}" + End Sub + + ''' + ''' Used for authenticated download. + ''' + ''' Passed to Me.New. + ''' Name to match for authorization. + ''' Password to match for authorization. + ''' Passed to Me.New. + Public Sub New( + fileSize As Integer, + userName As String, + password As String, + Optional memberName As String = Nothing) + + Me.New(fileSize, memberName) + _userName = userName + _password = password + End Sub + + Public ReadOnly Property Address As String + + Friend Function ProcessRequests() As HttpListener + ' Create a listener and add the prefixes. + Dim listener As New HttpListener() + + listener.Prefixes.Add(_downloadFileUrlPrefix) + If _userName IsNot Nothing OrElse _password IsNot Nothing Then + listener.AuthenticationSchemes = AuthenticationSchemes.Basic + End If + listener.Start() + Dim action As Action = + Sub() + ' Start the listener to begin listening for requests. + Dim response As HttpListenerResponse = Nothing + Try + ' Note: GetContext blocks while waiting for a request. + Dim context As HttpListenerContext = listener.GetContext() + ' Create the response. + response = context.Response + + If context.User?.Identity.IsAuthenticated Then + Dim identity As HttpListenerBasicIdentity = + CType(context.User?.Identity, HttpListenerBasicIdentity) + If String.IsNullOrWhiteSpace(identity.Name) _ + OrElse identity.Name <> _userName _ + OrElse String.IsNullOrWhiteSpace(identity.Password) _ + OrElse identity.Password <> _password Then + + response.StatusCode = HttpStatusCode.Unauthorized + Exit Try + End If + End If + ' Simulate network traffic + Thread.Sleep(millisecondsTimeout:=20) + Dim responseString As String = Strings.StrDup(_fileSize, "A") + Dim buffer() As Byte = Text.Encoding.UTF8.GetBytes(responseString) + response.ContentLength64 = buffer.Length + Using output As Stream = response.OutputStream + output.Write(buffer, offset:=0, count:=buffer.Length) + End Using + Finally + response?.Close() + response = Nothing + End Try + End Sub + + Task.Run(action) + Return listener + End Function + + End Class +End Namespace diff --git a/src/System.Drawing.Common/src/CompatibilitySuppressions.xml b/src/System.Drawing.Common/src/CompatibilitySuppressions.xml index ef75f17f963..521f4adba7b 100644 --- a/src/System.Drawing.Common/src/CompatibilitySuppressions.xml +++ b/src/System.Drawing.Common/src/CompatibilitySuppressions.xml @@ -1,5 +1,5 @@  - + CP0002 @@ -25,6 +25,13 @@ lib/netstandard2.0/System.Drawing.Common.dll lib/net462/System.Drawing.Common.dll + + CP0014 + M:System.Drawing.Imaging.ColorMatrix.#ctor(System.Single[][]):[T:System.CLSCompliantAttribute] + lib/net8.0/System.Drawing.Common.dll + lib/net8.0/System.Drawing.Common.dll + true + CP0014 M:System.Drawing.Printing.PrintPageEventArgs.get_Graphics:[T:System.Runtime.CompilerServices.NullableContextAttribute] @@ -32,6 +39,20 @@ lib/net8.0/System.Drawing.Common.dll true + + CP0014 + P:System.Drawing.Imaging.ImageCodecInfo.SignatureMasks:[T:System.CLSCompliantAttribute] + lib/net8.0/System.Drawing.Common.dll + lib/net8.0/System.Drawing.Common.dll + true + + + CP0014 + P:System.Drawing.Imaging.ImageCodecInfo.SignaturePatterns:[T:System.CLSCompliantAttribute] + lib/net8.0/System.Drawing.Common.dll + lib/net8.0/System.Drawing.Common.dll + true + CP0014 P:System.Drawing.Printing.PrintPageEventArgs.Graphics:[T:System.Runtime.CompilerServices.NullableAttribute] @@ -123,6 +144,27 @@ lib/net8.0/System.Drawing.Common.dll true + + CP0014 + M:System.Drawing.Imaging.ColorMatrix.#ctor(System.Single[][]):[T:System.CLSCompliantAttribute] + lib/netstandard2.0/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true + + + CP0014 + P:System.Drawing.Imaging.ImageCodecInfo.SignatureMasks:[T:System.CLSCompliantAttribute] + lib/netstandard2.0/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true + + + CP0014 + P:System.Drawing.Imaging.ImageCodecInfo.SignaturePatterns:[T:System.CLSCompliantAttribute] + lib/netstandard2.0/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true + CP0015 T:System.Drawing.Printing.PrintPageEventArgs:[T:System.Runtime.CompilerServices.NullableContextAttribute] diff --git a/src/System.Drawing.Common/src/Special/NotSupported.cs b/src/System.Drawing.Common/src/Special/NotSupported.cs index 4a8321c0b36..b3fbf98babd 100644 --- a/src/System.Drawing.Common/src/Special/NotSupported.cs +++ b/src/System.Drawing.Common/src/Special/NotSupported.cs @@ -1976,7 +1976,6 @@ public enum ColorMapType public sealed partial class ColorMatrix { public ColorMatrix() { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } - [System.CLSCompliantAttribute(false)] public ColorMatrix(float[][] newColorMatrix) { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } public float this[int row, int column] { get { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } set { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } } public float Matrix00 { get { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } set { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } } @@ -2473,9 +2472,7 @@ public sealed partial class ImageCodecInfo public string? FormatDescription { get { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } set { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } } public System.Guid FormatID { get { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } set { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } } public string? MimeType { get { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } set { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } } - [System.CLSCompliantAttribute(false)] public byte[][]? SignatureMasks { get { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } set { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } } - [System.CLSCompliantAttribute(false)] public byte[][]? SignaturePatterns { get { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } set { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } } public int Version { get { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } set { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } } public static System.Drawing.Imaging.ImageCodecInfo[] GetImageDecoders() { throw new System.PlatformNotSupportedException(System.SR.SystemDrawingCommon_PlatformNotSupported); } diff --git a/src/System.Drawing.Common/src/System.Drawing.Common.csproj b/src/System.Drawing.Common/src/System.Drawing.Common.csproj index 25aea9c4d95..4d1825db612 100644 --- a/src/System.Drawing.Common/src/System.Drawing.Common.csproj +++ b/src/System.Drawing.Common/src/System.Drawing.Common.csproj @@ -9,7 +9,6 @@ false enable disable - true true true true diff --git a/src/System.Windows.Forms.Analyzers.VisualBasic/src/Diagnostic/VisualBasicDiagnosticDescriptors.vb b/src/System.Windows.Forms.Analyzers.VisualBasic/src/Diagnostic/VisualBasicDiagnosticDescriptors.vb index 05f4f816cf3..708b5e78f71 100644 --- a/src/System.Windows.Forms.Analyzers.VisualBasic/src/Diagnostic/VisualBasicDiagnosticDescriptors.vb +++ b/src/System.Windows.Forms.Analyzers.VisualBasic/src/Diagnostic/VisualBasicDiagnosticDescriptors.vb @@ -8,21 +8,39 @@ Imports System.Windows.Forms.Analyzers.VisualBasic.Resources Friend Module VisualBasicDiagnosticDescriptors Public ReadOnly s_missingPropertySerializationConfiguration As New DiagnosticDescriptor( - id:=DiagnosticIDs.MissingPropertySerializationConfiguration, - title:=New LocalizableResourceString(NameOf(SR.WFO1000AnalyzerTitle), SR.ResourceManager, GetType(SR)), - messageFormat:=New LocalizableResourceString(NameOf(SR.WFO1000AnalyzerMessageFormat), SR.ResourceManager, GetType(SR)), - category:=DiagnosticCategories.WinFormsSecurity, - defaultSeverity:=DiagnosticSeverity.Error, - isEnabledByDefault:=True, - description:=New LocalizableResourceString(NameOf(SR.WFO1000AnalyzerDescription), SR.ResourceManager, GetType(SR))) + id:=DiagnosticIDs.MissingPropertySerializationConfiguration, + title:=New LocalizableResourceString( + nameOfLocalizableResource:=NameOf(SR.WFO1000AnalyzerTitle), + resourceManager:=SR.ResourceManager, + resourceSource:=GetType(SR)), + messageFormat:=New LocalizableResourceString( + nameOfLocalizableResource:=NameOf(SR.WFO1000AnalyzerMessageFormat), + resourceManager:=SR.ResourceManager, + resourceSource:=GetType(SR)), + category:=DiagnosticCategories.WinFormsSecurity, + defaultSeverity:=DiagnosticSeverity.Error, + isEnabledByDefault:=True, + description:=New LocalizableResourceString( + nameOfLocalizableResource:=NameOf(SR.WFO1000AnalyzerDescription), + resourceManager:=SR.ResourceManager, + resourceSource:=GetType(SR))) Public ReadOnly s_avoidFuncReturningTaskWithoutCancellationToken As New DiagnosticDescriptor( - id:=DiagnosticIDs.AvoidPassingFuncReturningTaskWithoutCancellationToken, - title:=New LocalizableResourceString(NameOf(SR.WFO2001AnalyzerTitle), SR.ResourceManager, GetType(SR)), - messageFormat:=New LocalizableResourceString(NameOf(SR.WFO2001AnalyzerMessageFormat), SR.ResourceManager, GetType(SR)), - category:=DiagnosticCategories.WinFormsSecurity, - defaultSeverity:=DiagnosticSeverity.Warning, - isEnabledByDefault:=True, - description:=New LocalizableResourceString(NameOf(SR.WFO2001AnalyzerDescription), SR.ResourceManager, GetType(SR))) + id:=DiagnosticIDs.AvoidPassingFuncReturningTaskWithoutCancellationToken, + title:=New LocalizableResourceString( + nameOfLocalizableResource:=NameOf(SR.WFO2001AnalyzerTitle), + resourceManager:=SR.ResourceManager, + resourceSource:=GetType(SR)), + messageFormat:=New LocalizableResourceString( + nameOfLocalizableResource:=NameOf(SR.WFO2001AnalyzerMessageFormat), + resourceManager:=SR.ResourceManager, + resourceSource:=GetType(SR)), + category:=DiagnosticCategories.WinFormsSecurity, + defaultSeverity:=DiagnosticSeverity.Warning, + isEnabledByDefault:=True, + description:=New LocalizableResourceString( + nameOfLocalizableResource:=NameOf(SR.WFO2001AnalyzerDescription), + resourceManager:=SR.ResourceManager, + resourceSource:=GetType(SR))) End Module diff --git a/src/System.Windows.Forms.Design/src/System.Windows.Forms.Design.csproj b/src/System.Windows.Forms.Design/src/System.Windows.Forms.Design.csproj index 74ac5d4b609..d9ace26472a 100644 --- a/src/System.Windows.Forms.Design/src/System.Windows.Forms.Design.csproj +++ b/src/System.Windows.Forms.Design/src/System.Windows.Forms.Design.csproj @@ -2,7 +2,6 @@ System.Windows.Forms.Design - true true true enable diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs index 067f443f996..be18ebb880e 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs @@ -813,7 +813,6 @@ protected virtual bool CanDisplayComponent(IComponent component) return TypeDescriptor.GetAttributes(component).Contains(DesignTimeVisibleAttribute.Yes); } - [CLSCompliant(false)] public void CreateComponentFromTool(ToolboxItem tool) { if (!CanCreateComponentFromTool(tool)) diff --git a/src/System.Windows.Forms.Primitives/src/System.Windows.Forms.Primitives.csproj b/src/System.Windows.Forms.Primitives/src/System.Windows.Forms.Primitives.csproj index c05a1eb50a1..58876a64667 100644 --- a/src/System.Windows.Forms.Primitives/src/System.Windows.Forms.Primitives.csproj +++ b/src/System.Windows.Forms.Primitives/src/System.Windows.Forms.Primitives.csproj @@ -3,7 +3,6 @@ System.Windows.Forms.Primitives true - true enable