diff --git a/Directory.Build.targets b/Directory.Build.targets index a72569f7af7..fb96e1a1544 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/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/ApplicationEvents.vb b/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/ApplicationEvents.vb index 3445e6db329..68e1e312172 100644 --- a/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/ApplicationEvents.vb +++ b/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/ApplicationEvents.vb @@ -3,15 +3,18 @@ Namespace My ' The following events are available for MyApplication: ' Startup: Raised when the application starts, before the startup form is created. - ' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally. + ' Shutdown: Raised after all application forms are closed. This event is not raised if the + ' application terminates abnormally. ' UnhandledException: Raised if the application encounters an unhandled exception. ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. - ' **NEW** ApplyApplicationDefaults: Raised when the application queries default values to be set for the application. + ' **NEW** ApplyApplicationDefaults: + ' Raised when the application queries default values to be set for the application. ' Example: - ' Private Sub MyApplication_ApplyApplicationDefaults(sender As Object, e As ApplyApplicationDefaultsEventArgs) Handles Me.ApplyApplicationDefaults + ' Private Sub MyApplication_ApplyApplicationDefaults(sender As Object, e As ApplyApplicationDefaultsEventArgs) _ + ' Handles Me.ApplyApplicationDefaults ' ' ' Setting the application-wide default Font: ' e.Font = New Font(FontFamily.GenericSansSerif, 12, FontStyle.Regular) diff --git a/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/Form1.Designer.vb b/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/Form1.Designer.vb index 0a21f031def..357d44f45c7 100644 --- a/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/Form1.Designer.vb +++ b/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/Form1.Designer.vb @@ -2,7 +2,7 @@ Partial Class Form1 Inherits System.Windows.Forms.Form - 'Form overrides dispose to clean up the component list. + ' Form overrides dispose to clean up the component list. Protected Overrides Sub Dispose(disposing As Boolean) Try @@ -14,12 +14,12 @@ Partial Class Form1 End Try End Sub - 'Required by the Windows Form Designer + ' Required by the Windows Form Designer Private components As System.ComponentModel.IContainer - 'NOTE: The following procedure is required by the Windows Form Designer - 'It can be modified using the Windows Form Designer. - 'Do not modify it using the code editor. + ' NOTE: The following procedure is required by the Windows Form Designer + ' It can be modified using the Windows Form Designer. + ' Do not modify it using the code editor. Private Sub InitializeComponent() components = New System.ComponentModel.Container() diff --git a/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/My Project/Application.Designer.vb b/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/My Project/Application.Designer.vb index 86fcf0fab94..666a89fef24 100644 --- a/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/My Project/Application.Designer.vb +++ b/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsApplication-VisualBasic/My Project/Application.Designer.vb @@ -10,10 +10,10 @@ Namespace My - 'NOTE: This file is auto-generated; do not modify it directly. To make changes, - ' or if you encounter build errors in this file, go to the Project Designer - ' (go to Project Properties or double-click the My Project node in - ' Solution Explorer), and make changes on the Application tab. + ' NOTE: This file is auto-generated; do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to Project Properties or double-click the My Project node in Solution Explorer), + ' and make changes on the Application tab. ' Partial Friend Class MyApplication diff --git a/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsControlLibrary-VisualBasic/UserControl1.Designer.vb b/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsControlLibrary-VisualBasic/UserControl1.Designer.vb index 21cd445ae78..93909d765e7 100644 --- a/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsControlLibrary-VisualBasic/UserControl1.Designer.vb +++ b/pkg/Microsoft.Dotnet.WinForms.ProjectTemplates/content/WinFormsControlLibrary-VisualBasic/UserControl1.Designer.vb @@ -2,7 +2,7 @@ Partial Class UserControl1 Inherits System.Windows.Forms.UserControl - 'UserControl1 overrides dispose to clean up the component list. + ' UserControl1 overrides dispose to clean up the component list. Protected Overrides Sub Dispose(disposing As Boolean) Try @@ -14,12 +14,12 @@ Partial Class UserControl1 End Try End Sub - 'Required by the Windows Form Designer + ' Required by the Windows Form Designer Private components As System.ComponentModel.IContainer - 'NOTE: The following procedure is required by the Windows Form Designer - 'It can be modified using the Windows Form Designer. - 'Do not modify it using the code editor. + ' NOTE: The following procedure is required by the Windows Form Designer + ' It can be modified using the Windows Form Designer. + ' Do not modify it using the code editor. Private Sub InitializeComponent() components = New System.ComponentModel.Container() diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft.VisualBasic.Forms.vbproj b/src/Microsoft.VisualBasic.Forms/src/Microsoft.VisualBasic.Forms.vbproj index 095dcd70100..92143067eeb 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft.VisualBasic.Forms.vbproj +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft.VisualBasic.Forms.vbproj @@ -18,6 +18,10 @@ true + + + + diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ApplicationBase.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ApplicationBase.vb index a98c73c81b5..621159e8e8f 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ApplicationBase.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ApplicationBase.vb @@ -16,7 +16,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices ' The executing application (the EntryAssembly) Private _info As AssemblyInfo - 'Lazy-initialized and cached log object. + ' Lazy-initialized and cached log object. Private _log As Logging.Log Public Sub New() @@ -38,7 +38,9 @@ Namespace Microsoft.VisualBasic.ApplicationServices Public ReadOnly Property Info() As AssemblyInfo Get If _info Is Nothing Then - Dim assembly As Reflection.Assembly = If(Reflection.Assembly.GetEntryAssembly(), Reflection.Assembly.GetCallingAssembly()) + Dim assembly As Reflection.Assembly = + If(Reflection.Assembly.GetEntryAssembly(), Reflection.Assembly.GetCallingAssembly()) + _info = New AssemblyInfo(assembly) End If Return _info diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/CantStartSingleInstanceException.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/CantStartSingleInstanceException.vb index d9698267a35..8b1f1de1cbd 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/CantStartSingleInstanceException.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/CantStartSingleInstanceException.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System.ComponentModel +Imports System.Runtime.Serialization Imports VbUtils = Microsoft.VisualBasic.CompilerServices.ExceptionUtils @@ -18,7 +19,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices ' Deserialization constructor must be defined since we are serializable - Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) + Protected Sub New(info As SerializationInfo, context As StreamingContext) MyBase.New(info, context) End Sub diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ConsoleApplicationBase.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ConsoleApplicationBase.vb index 3a69acd3b43..7fc921ea645 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ConsoleApplicationBase.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ConsoleApplicationBase.vb @@ -50,14 +50,28 @@ Namespace Microsoft.VisualBasic.ApplicationServices Public ReadOnly Property CommandLineArgs() As ObjectModel.ReadOnlyCollection(Of String) Get If _commandLineArgs Is Nothing Then - 'Get rid of Arg(0) which is the path of the executing program. Main(args() as string) doesn't report the name of the app and neither will we + ' Get rid of Arg(0) which is the path of the executing program. Main(args() as string) + ' doesn't report the name of the app and neither will we Dim envArgs As String() = Environment.GetCommandLineArgs - If envArgs.GetLength(0) >= 2 Then '1 element means no args, just the executing program. >= 2 means executing program + one or more command line arguments - Dim newArgs(envArgs.GetLength(0) - 2) As String 'dimming z(0) gives a z() of 1 element. - Array.Copy(envArgs, 1, newArgs, 0, envArgs.GetLength(0) - 1) 'copy everything but the 0th element (the path of the executing program) + + ' 1 element means no args, just the executing program. + If envArgs.GetLength(0) >= 2 Then + ' >= 2 means executing program + one or more command line arguments + ' dimming z(0) gives a z() of 1 element. + Dim newArgs(envArgs.GetLength(0) - 2) As String + + ' Copy everything but the 0th element (the path of the executing program) + Dim length As Integer = envArgs.GetLength(0) - 1 + Array.Copy( + sourceArray:=envArgs, + sourceIndex:=1, + destinationArray:=newArgs, + destinationIndex:=0, + length) _commandLineArgs = New ObjectModel.ReadOnlyCollection(Of String)(newArgs) Else - _commandLineArgs = New ObjectModel.ReadOnlyCollection(Of String)(Array.Empty(Of String)()) 'provide the empty set + ' Provide the empty set + _commandLineArgs = New ObjectModel.ReadOnlyCollection(Of String)(Array.Empty(Of String)()) End If End If Return _commandLineArgs diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/NoStartupFormException.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/NoStartupFormException.vb index 7e3531e53cd..705577b4f80 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/NoStartupFormException.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/NoStartupFormException.vb @@ -2,6 +2,7 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System.ComponentModel +Imports System.Runtime.Serialization Imports VbUtils = Microsoft.VisualBasic.CompilerServices.ExceptionUtils @@ -17,7 +18,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices ' De-serialization constructor must be defined since we are serializable - Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) + Protected Sub New(info As SerializationInfo, context As StreamingContext) MyBase.New(info, context) End Sub diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/User.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/User.vb index d390478e991..1f4a36c8c1f 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/User.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/User.vb @@ -71,7 +71,9 @@ Namespace Microsoft.VisualBasic.ApplicationServices ''' Indicates whether or not the current user is a member of the passed in role. ''' ''' The name of the role. - ''' if the user is a member of the role otherwise . + ''' + ''' if the user is a member of the role otherwise . + ''' Public Function IsInRole(role As String) As Boolean Return InternalPrincipal.IsInRole(role) End Function 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 18a97c87960..e52242c2eff 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb @@ -305,10 +305,14 @@ Namespace Microsoft.VisualBasic.ApplicationServices End Get Set(value As Form) If value Is Nothing Then - Throw VbUtils.GetArgumentNullException("MainForm", SR.General_PropertyNothing, "MainForm") + Throw VbUtils.GetArgumentNullException( + argumentName:="MainForm", + resourceKey:=SR.General_PropertyNothing, + "MainForm") End If If value Is _splashScreen Then - Throw New ArgumentException(VbUtils.GetResourceString(SR.AppModel_SplashAndMainFormTheSame)) + Dim message As String = VbUtils.GetResourceString(SR.AppModel_SplashAndMainFormTheSame) + Throw New ArgumentException(message) End If _appContext.MainForm = value End Set @@ -480,7 +484,8 @@ Namespace Microsoft.VisualBasic.ApplicationServices Try If handler IsNot Nothing Then handler.Invoke(sender, e) Catch ex As Exception - If Not OnUnhandledException(New UnhandledExceptionEventArgs(True, ex)) Then + Dim e1 As New UnhandledExceptionEventArgs(exitApplication:=True, exception:=ex) + If Not OnUnhandledException(e1) Then ' The user didn't write a handler so throw the error up the chain. Throw @@ -497,7 +502,8 @@ Namespace Microsoft.VisualBasic.ApplicationServices ''' it doesn't freeze up while the main form is getting it together. ''' Private Sub DisplaySplash() - Debug.Assert(_splashScreen IsNot Nothing, "We should have never get here if there is no splash screen") + Const Message As String = "We should have never get here if there is no splash screen" + Debug.Assert(_splashScreen IsNot Nothing, Message) If _splashTimer IsNot Nothing Then @@ -538,13 +544,15 @@ Namespace Microsoft.VisualBasic.ApplicationServices ' have already seen via our hook of System.Windows.Forms.Application.ThreadException). If _processingUnhandledExceptionEvent Then - ' If the UnhandledException handler threw for some reason, throw that error out to the system. + ' If the UnhandledException handler threw for some reason, + ' throw that error out to the system. Throw Else ' We had an exception, but not during the OnUnhandledException handler so give the user ' a chance to look at what happened in the UnhandledException event handler - If Not OnUnhandledException(New UnhandledExceptionEventArgs(True, ex)) Then + Dim e As New UnhandledExceptionEventArgs(exitApplication:=True, ex) + If Not OnUnhandledException(e) Then ' The user didn't write a handler so throw the error out to the system Throw @@ -668,7 +676,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices ''' event so we do the translation here before raising our event. ''' Private Sub OnUnhandledExceptionEventAdaptor(sender As Object, e As ThreadExceptionEventArgs) - OnUnhandledException(New UnhandledExceptionEventArgs(True, e.Exception)) + OnUnhandledException(New UnhandledExceptionEventArgs(exitApplication:=True, e.Exception)) End Sub ''' @@ -796,7 +804,9 @@ Namespace Microsoft.VisualBasic.ApplicationServices #Enable Warning WFO5001 ' We'll handle "/nosplash" for you. - If Not (commandLineArgs.Contains("/nosplash") OrElse Me.CommandLineArgs.Contains("-nosplash")) Then + If Not (commandLineArgs.Contains("/nosplash") OrElse + Me.CommandLineArgs.Contains("-nosplash")) Then + ShowSplashScreen() End If @@ -1016,7 +1026,10 @@ Namespace Microsoft.VisualBasic.ApplicationServices ''' Friend Shared Sub ValidateAuthenticationModeEnumValue(value As AuthenticationMode, paramName As String) If value < AuthenticationMode.Windows OrElse value > AuthenticationMode.ApplicationDefined Then - Throw New InvalidEnumArgumentException(paramName, value, GetType(AuthenticationMode)) + Throw New InvalidEnumArgumentException( + argumentName:=paramName, + invalidValue:=value, + enumClass:=GetType(AuthenticationMode)) End If End Sub @@ -1026,7 +1039,10 @@ Namespace Microsoft.VisualBasic.ApplicationServices ''' Friend Shared Sub ValidateShutdownModeEnumValue(value As ShutdownMode, paramName As String) If value < ShutdownMode.AfterMainFormCloses OrElse value > ShutdownMode.AfterAllFormsClose Then - Throw New InvalidEnumArgumentException(paramName, value, GetType(ShutdownMode)) + Throw New InvalidEnumArgumentException( + argumentName:=paramName, + invalidValue:=value, + enumClass:=GetType(ShutdownMode)) End If End Sub diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/CompilerServices/ExceptionUtils.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/CompilerServices/ExceptionUtils.vb index 2b9949e4c2d..e5d17481419 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/CompilerServices/ExceptionUtils.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/CompilerServices/ExceptionUtils.vb @@ -10,13 +10,18 @@ Namespace Microsoft.VisualBasic.CompilerServices Friend Module ExceptionUtils ''' - ''' Returns a new instance of with the message from resource file and the Exception.ArgumentName property set. + ''' Returns a new instance of with the message from resource file and + ''' the Exception.ArgumentName property set. ''' ''' The name of the argument (parameter). Not localized. ''' The resource ID. - ''' Strings that will replace place holders in the resource string, if any. + ''' + ''' Strings that will replace place holders in the resource string, if any. + ''' ''' A new instance of . - ''' This is the preferred way to construct an argument exception. + ''' + ''' This is the preferred way to construct an argument exception. + ''' Friend Function GetArgumentExceptionWithArgName( argumentName As String, resourceKey As String, @@ -112,9 +117,9 @@ Namespace Microsoft.VisualBasic.CompilerServices End Function ''' - ''' + ''' Gets a string from resource file based on "ID" appended to value. ''' - ''' A value that will become the ResourceKey + ''' A value that will become the resourceKey ''' A localized version of the resource. Friend Function GetResourceString(resourceId As VbErrors) As String Dim resourceKey As String = $"ID{CStr(resourceId)}" @@ -122,17 +127,27 @@ Namespace Microsoft.VisualBasic.CompilerServices End Function ''' - ''' Returns a new instance of with the message from resource file and the last Win32 error. + ''' Returns a new instance of + ''' with the message from resource file and the last Win32 error. ''' ''' The resource ID. - ''' Strings that will replace place holders in the resource string, if any. - ''' A new instance of . - ''' There is no way to exclude the Win32 error so this function will call Marshal.GetLastWin32Error all the time. + ''' + ''' Strings that will replace place holders in the resource string, if any. + ''' + ''' + ''' A new instance of . + ''' + ''' + ''' There is no way to exclude the Win32 error so this function will + ''' call Marshal.GetLastWin32Error all the time. + ''' Friend Function GetWin32Exception( resourceKey As String, ParamArray placeHolders() As String) As ComponentModel.Win32Exception - Return New ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), GetResourceString(resourceKey, placeHolders)) + Return New ComponentModel.Win32Exception( + [error]:=Marshal.GetLastWin32Error(), + message:=GetResourceString(resourceKey, placeHolders)) End Function Friend Function VbMakeException(resourceId As Integer) As Exception diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Audio.AudioPlayMode.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Audio.AudioPlayMode.vb index 957570edb21..73c66bd2cd7 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Audio.AudioPlayMode.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Audio.AudioPlayMode.vb @@ -8,9 +8,9 @@ Namespace Microsoft.VisualBasic ''' Public Enum AudioPlayMode ' Any changes to this enum must be reflected in ValidateAudioPlayModeEnum() - WaitToComplete = 0 'Synchronous - Background = 1 'Asynchronous - BackgroundLoop = 2 'Asynchronous and looping + WaitToComplete = 0 ' Synchronous + Background = 1 ' Asynchronous + BackgroundLoop = 2 ' Asynchronous and looping End Enum End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Audio.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Audio.vb index bc424bb4466..45e0febf245 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Audio.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Audio.vb @@ -12,7 +12,8 @@ Namespace Microsoft.VisualBasic.Devices ''' Public Class Audio - ' Object that plays the sounds. We use a private member so we can ensure we have a reference for async plays + ' Object that plays the sounds. We use a private member + ' so we can ensure we have a reference for async plays Private _sound As Media.SoundPlayer ''' @@ -27,7 +28,10 @@ Namespace Microsoft.VisualBasic.Devices ''' Private Shared Sub ValidateAudioPlayModeEnum(value As AudioPlayMode, paramName As String) If value < AudioPlayMode.WaitToComplete OrElse value > AudioPlayMode.BackgroundLoop Then - Throw New ComponentModel.InvalidEnumArgumentException(paramName, value, GetType(AudioPlayMode)) + Throw New ComponentModel.InvalidEnumArgumentException( + argumentName:=paramName, + invalidValue:=value, + enumClass:=GetType(AudioPlayMode)) End If End Sub @@ -57,7 +61,8 @@ Namespace Microsoft.VisualBasic.Devices Debug.Assert(sound IsNot Nothing, "There's no SoundPlayer") Debug.Assert([Enum].IsDefined(mode), "Enum value is out of range") - ' Stopping the sound ensures it's safe to dispose it. This could happen when we change the value of _Sound below + ' Stopping the sound ensures it's safe to dispose it. + ' This could happen when we change the value of _sound below _sound?.Stop() _sound = sound @@ -96,8 +101,10 @@ Namespace Microsoft.VisualBasic.Devices ''' ''' The name of the file. ''' - ''' An enum value representing the Background (async), - ''' WaitToComplete (sync) or BackgroundLoop + ''' An enum value representing the + ''' 0 - Background (async), + ''' 1 - WaitToComplete (sync) + ''' 2 - BackgroundLoop ''' Public Sub Play(location As String, playMode As AudioPlayMode) ValidateAudioPlayModeEnum(playMode, NameOf(playMode)) @@ -143,7 +150,9 @@ Namespace Microsoft.VisualBasic.Devices ''' ''' The sound to be played. ''' Plays the sound asynchronously. - ''' if systemSound is . + ''' + ''' If systemSound is . + ''' Public Sub PlaySystemSound(systemSound As Media.SystemSound) If systemSound Is Nothing Then Throw VbUtils.GetArgumentNullException(NameOf(systemSound)) diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Clock.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Clock.vb index 7f741b66c40..44ec81e5366 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Clock.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Clock.vb @@ -9,7 +9,7 @@ Namespace Microsoft.VisualBasic.Devices ''' Public Class Clock -#Disable Warning IDE0049 ' Use language keywords instead of framework type names for type references, Justification:= +#Disable Warning IDE0049 ' Use language keywords instead of framework type names for type references, Justification:= ''' ''' Gets a Date that is the current local date and time on this computer. @@ -25,7 +25,9 @@ Namespace Microsoft.VisualBasic.Devices ''' Gets a DateTime that is the current local date and time on this ''' computer expressed as GMT time. ''' - ''' A Date whose value is the current date and time expressed as GMT time. + ''' + ''' A Date whose value is the current date and time expressed as GMT time. + ''' Public ReadOnly Property GmtTime() As DateTime Get Return DateTime.UtcNow diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Computer.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Computer.vb index 47f7280eba3..ebf50e09d32 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Computer.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Computer.vb @@ -16,26 +16,26 @@ Namespace Microsoft.VisualBasic.Devices ''' Partial Public Class Computer : Inherits ServerComputer - ' NOTE: The .Net design guidelines state that access to Instance members does not - ' have to be thread-safe. Access to Shared members does have to be thread-safe. - ' Since My.Computer creates the instance of Computer in a thread-safe way, - ' access to the Computer will necessarily be thread-safe. There is nothing to - ' prevent a user from passing our computer object across threads or creating - ' their own instance and then getting into trouble. But that is completely - ' consistent with the rest of the FX design. It is MY.* that is thread safe - ' and leads to best practice access to these objects. If you Dim them up yourself, - ' you are responsible for managing the threading. + ' NOTE: The .Net design guidelines state that access to Instance members does not + ' have to be thread-safe. Access to Shared members does have to be thread-safe. + ' Since My.Computer creates the instance of Computer in a thread-safe way, + ' access to the Computer will necessarily be thread-safe. There is nothing to + ' prevent a user from passing our computer object across threads or creating + ' their own instance and then getting into trouble. But that is completely + ' consistent with the rest of the FX design. It is MY.* that is thread safe + ' and leads to best practice access to these objects. If you Dim them up yourself, + ' you are responsible for managing the threading. - 'Lazy initialized cache for the clipboard class. (proxies can be shared - they have no state) + ' Lazy initialized cache for the clipboard class. (proxies can be shared - they have no state) Private Shared s_clipboard As ClipboardProxy - 'Lazy initialized cache for the Keyboard class. SHARED because Keyboard behaves as a ReadOnly singleton class + ' Lazy initialized cache for the Keyboard class. SHARED because Keyboard behaves as a ReadOnly singleton class Private Shared s_keyboardInstance As Keyboard - 'Lazy initialized cache for the Mouse class. SHARED because Mouse behaves as a ReadOnly singleton class + ' Lazy initialized cache for the Mouse class. SHARED because Mouse behaves as a ReadOnly singleton class Private Shared s_mouse As Mouse - 'Lazy initialized cache for the Audio class. + ' Lazy initialized cache for the Audio class. Private _audio As Audio ''' @@ -96,9 +96,9 @@ Namespace Microsoft.VisualBasic.Devices ''' A object as the primary screen. Public ReadOnly Property Screen() As System.Windows.Forms.Screen Get - 'Don't cache this. The Screen class responds to display resolution changes by nulling out AllScreens, which - 'PrimaryScreen relies on to find the primary. So we always need to access the latest PrimaryScreen so we - 'will get the current resolution reported. + ' Don't cache this. The Screen class responds to display resolution changes by nulling out AllScreens, + ' which PrimaryScreen relies on to find the primary. So we always need to access the latest + ' PrimaryScreen so we will get the current resolution reported. Return System.Windows.Forms.Screen.PrimaryScreen End Get End Property 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/Keyboard.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Keyboard.vb index 14773681229..4d907e6deea 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Keyboard.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Keyboard.vb @@ -29,10 +29,10 @@ Namespace Microsoft.VisualBasic.Devices ''' if the key is down otherwise . Public ReadOnly Property CapsLock() As Boolean Get - 'Security Note: Only the state of the Caps Lock is returned + ' Security Note: Only the state of the Caps Lock is returned - 'The low order byte of the return value from - 'GetKeyState is 1 if the key is toggled on. + ' The low order byte of the return value from + ' GetKeyState is 1 if the key is toggled on. Return CType(UnsafeNativeMethods.GetKeyState(Keys.CapsLock) And 1, Boolean) End Get End Property @@ -54,10 +54,10 @@ Namespace Microsoft.VisualBasic.Devices ''' if the key is down otherwise . Public ReadOnly Property NumLock() As Boolean Get - 'Security Note: Only the state of the Num Lock is returned + ' Security Note: Only the state of the Num Lock is returned - 'The low order byte of the return value from - 'GetKeyState is 1 if the key is toggled on. + ' The low order byte of the return value from + ' GetKeyState is 1 if the key is toggled on. Return CType(UnsafeNativeMethods.GetKeyState(Keys.NumLock) And 1, Boolean) End Get End Property @@ -68,10 +68,10 @@ Namespace Microsoft.VisualBasic.Devices ''' if the key is down otherwise . Public ReadOnly Property ScrollLock() As Boolean Get - 'Security Note: Only the state of the Scroll Lock is returned + ' Security Note: Only the state of the Scroll Lock is returned - 'The low order byte of the return value from - 'GetKeyState is 1 if the key is toggled on. + ' The low order byte of the return value from + ' GetKeyState is 1 if the key is toggled on. Return CType(UnsafeNativeMethods.GetKeyState(Keys.Scroll) And 1, Boolean) End Get End Property diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Mouse.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Mouse.vb index 4a4b36d7635..651a6442c27 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Mouse.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Mouse.vb @@ -64,5 +64,5 @@ Namespace Microsoft.VisualBasic.Devices End Get End Property - End Class 'Mouse + End Class End Namespace 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 8bee94db45f..93f0d91c79c 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,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System.Net -Imports Microsoft.VisualBasic.CompilerServices +Imports System.Threading +Imports System.Windows.Forms Imports Microsoft.VisualBasic.FileIO Imports Microsoft.VisualBasic.MyServices.Internal @@ -24,14 +25,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) + 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 ''' @@ -40,14 +48,22 @@ Namespace Microsoft.VisualBasic.Devices ''' 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( + 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 ''' @@ -63,14 +79,21 @@ Namespace Microsoft.VisualBasic.Devices 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 ''' @@ -86,14 +109,21 @@ Namespace Microsoft.VisualBasic.Devices userName As String, password As String) - DownloadFile( - address, - destinationFileName, - userName, - password, - showUI:=False, - connectionTimeout:=DEFAULT_TIMEOUT, - overwrite:=False) + 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 + Throw + End Try End Sub ''' @@ -117,97 +147,176 @@ 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 cancelToken As New CancellationToken + Dim t As Task = DownloadFileAsync( + address, + destinationFileName, + userName, + password, + dialog, + connectionTimeout, + overwrite, + onUserCancel:=UICancelOption.ThrowException, + cancelToken) + + If t.IsFaulted Then + ' This will be true if any parameters are bad + Throw t.Exception + Else + dialog?.ShowProgressDialog() + t.Wait() + If t.IsFaulted OrElse t.IsCanceled 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 + + Try + IO.File.Delete(destinationFileName) + Catch + ' ignore error + End Try + End If + + Throw ex.InnerException + End If + Throw + Finally + CloseProgressDialog(dialog) + End Try End Sub ''' ''' 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. + ''' 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 what to do if user cancels dialog (either or do nothing). + ''' Indicates whether or not the file should be overwritten if local file already exists. ''' Public Sub DownloadFile( - address As String, + address As Uri, destinationFileName As String, userName As String, password As String, showUI As Boolean, connectionTimeout As Integer, - overwrite As Boolean, - onUserCancel As UICancelOption) + overwrite As Boolean) - ' 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 + If address Is Nothing 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) - - DownloadFile( - address:=addressUri, - destinationFileName, - networkCredentials, - showUI, - connectionTimeout, - overwrite, - onUserCancel) + 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:=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, - ''' - ''' Name and path of file where download is saved. - ''' + ''' 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. ''' 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). ''' Public Sub DownloadFile( - address As Uri, + address As String, destinationFileName As String, userName As String, password As String, showUI As Boolean, connectionTimeout As Integer, - overwrite As Boolean) + overwrite As Boolean, + onUserCancel As UICancelOption) + + ' 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)) + End If - DownloadFile( - address, - destinationFileName, - userName, - password, - showUI, - connectionTimeout, - overwrite, - UICancelOption.ThrowException) + Dim addressUri As Uri = GetUri(address.Trim()) + Dim networkCredentials As ICredentials = GetNetworkCredentials(userName, password) + Dim dialog As ProgressDialog = Nothing + Try + dialog = GetProgressDialog(addressUri.AbsolutePath, destinationFileName, showUI) + 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 ''' @@ -240,17 +349,51 @@ Namespace Microsoft.VisualBasic.Devices 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, + userName, + password, + dialog, + connectionTimeout, + overwrite, + onUserCancel) + + If t.IsFaulted Then + ' IsFaulted will be true if any parameters are bad + Throw t.Exception + Else + dialog?.ShowProgressDialog() + Do While Not (t.IsCompleted OrElse t.IsFaulted OrElse t.IsCanceled) + ' prevent UI freeze + Thread.Sleep(10) + Application.DoEvents() + Loop + 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 ''' @@ -278,14 +421,39 @@ Namespace Microsoft.VisualBasic.Devices 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 + 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 ''' @@ -314,66 +482,45 @@ Namespace Microsoft.VisualBasic.Devices 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)) - - ' 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) - 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)) + Dim dialog As ProgressDialog = Nothing + Try + dialog = GetProgressDialog(address:=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 - - ' 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) - End If - - If Not IO.Directory.Exists(targetDirectory) Then - IO.Directory.CreateDirectory(targetDirectory) - End If - - ' Create the copier - Dim copier As New WebClientCopy(client, dialog) - - ' Download the file - copier.DownloadFile(address, fullFilename) - - ' Handle a dialog cancel - If showUI _ - AndAlso Environment.UserInteractive _ - AndAlso onUserCancel = UICancelOption.ThrowException _ - AndAlso dialog.UserCanceledTheDialog Then - Throw New OperationCanceledException() + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException End If - End Using + Throw + Finally + CloseProgressDialog(dialog) + 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..b362394579e --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.DownloadFileAsync.vb @@ -0,0 +1,374 @@ +' 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) + Dim clientHandler As HttpClientHandler = + If(networkCredentials Is Nothing, + New HttpClientHandler, + New HttpClientHandler With {.Credentials = networkCredentials}) + Await DownloadFileAsync( + addressUri, + destinationFileName, + clientHandler, + dialog, + connectionTimeout, + overwrite, + onUserCancel:=UICancelOption.ThrowException, + 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 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, + clientHandler:=If( + networkCredentials Is Nothing, + New HttpClientHandler, + New HttpClientHandler With {.Credentials = networkCredentials}), + dialog, + connectionTimeout, + overwrite, + onUserCancel, + 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. + ''' + ''' + 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 + + 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) + + Dim clientHandler As HttpClientHandler = + If(networkCredentials Is Nothing, + New HttpClientHandler, + New HttpClientHandler With {.Credentials = networkCredentials}) + Await DownloadFileAsync( + addressUri, + destinationFileName, + clientHandler, + dialog, + connectionTimeout, + overwrite, + 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) + + Dim clientHandler As HttpClientHandler = + If(networkCredentials Is Nothing, + New HttpClientHandler, + New HttpClientHandler With {.Credentials = networkCredentials}) + Await DownloadFileAsync( + addressUri, + destinationFileName, + clientHandler, + 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 + + Dim clientHandler As HttpClientHandler = + If(networkCredentials Is Nothing, + New HttpClientHandler, + New HttpClientHandler With {.Credentials = networkCredentials}) + Await DownloadFileAsync( + addressUri, + destinationFileName, + clientHandler, + dialog, + connectionTimeout, + overwrite, + onUserCancel:=UICancelOption.ThrowException, + 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. + ''' 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 + + ' Set credentials if we have any + Dim client As HttpClient + If clientHandler Is Nothing Then + client = New HttpClient() + Else + client = New HttpClient(clientHandler) + End If + + 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 + CloseProgressDialog(dialog) + Throw + End If + End Try + + End Function + + End Class +End Namespace 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 9a2ee54c814..dcf939a4809 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 @@ -2,6 +2,9 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System.Net +Imports System.Net.Http +Imports System.Threading +Imports System.Windows.Forms Imports Microsoft.VisualBasic.CompilerServices Imports Microsoft.VisualBasic.FileIO Imports Microsoft.VisualBasic.MyServices.Internal @@ -262,6 +265,7 @@ Namespace Microsoft.VisualBasic.Devices connectionTimeout As Integer, onUserCancel As UICancelOption) + ' Construct the local file. This will validate the full name and path sourceFileName = FileSystemUtils.NormalizeFilePath(sourceFileName, NameOf(sourceFileName)) ' Make sure the file exists @@ -280,15 +284,13 @@ Namespace Microsoft.VisualBasic.Devices Throw GetArgumentNullException(NameOf(address)) End If - Using client As New WebClientExtended() - client.Timeout = connectionTimeout - - ' Set credentials if we have any - If networkCredentials IsNot Nothing Then - client.Credentials = networkCredentials - End If - - Dim dialog As ProgressDialog = Nothing + Dim dialog As ProgressDialog = Nothing + Try + ' Get network credentials + Dim clientHandler As HttpClientHandler = + If(networkCredentials Is Nothing, + New HttpClientHandler, + New HttpClientHandler With {.Credentials = networkCredentials}) If InteractiveEnvironment(showUI) Then dialog = New ProgressDialog With { .Text = GetResourceString(SR.ProgressDialogUploadingTitle, sourceFileName), @@ -299,19 +301,39 @@ Namespace Microsoft.VisualBasic.Devices } End If - ' Create the copier - Dim copier As New WebClientCopy(client, dialog) - - ' Download the file - copier.UploadFile(sourceFileName, address) - - ' Handle a dialog cancel - If InteractiveEnvironment(showUI) Then - If onUserCancel = UICancelOption.ThrowException And dialog.UserCanceledTheDialog Then - Throw New OperationCanceledException() + Dim t As Task = UploadFileAsync( + sourceFileName, + addressUri:=address, + clientHandler, + dialog, + connectionTimeout, + onUserCancel) + + If t.IsFaulted Then + ' IsFaulted will be true if any parameters are bad + Throw t.Exception + Else + dialog?.ShowProgressDialog() + Do While Not (t.IsCompleted OrElse t.IsFaulted OrElse t.IsCanceled) + ' prevent UI freeze + Thread.Sleep(10) + Application.DoEvents() + Loop + If t.IsFaulted Then + Throw t.Exception End If + If t.IsCanceled Then + Throw New OperationCanceledException + End If + End If + Catch ex As Exception + If ex.InnerException IsNot Nothing Then + Throw ex.InnerException End If - End Using + Throw + Finally + CloseProgressDialog(dialog) + End Try End Sub diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.UploadFileAsync.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.UploadFileAsync.vb new file mode 100644 index 00000000000..b5fc3d91b2e --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/Network.UploadFileAsync.vb @@ -0,0 +1,89 @@ +' 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 + ''' + ''' Uploads a file to the network to the specified path. + ''' + ''' Name and path of file to be uploaded. + ''' Uri to the remote file + ''' An HttpClientHandler of the user performing the download. + ''' Progress Dialog. + ''' Time allotted before giving up on a connection. + ''' 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 UploadFileAsync( + sourceFileName As String, + addressUri As Uri, + clientHandler As HttpClientHandler, + dialog As ProgressDialog, + connectionTimeout As Integer, + onUserCancel As UICancelOption, + Optional cancelToken As CancellationToken = Nothing) As Task + + If cancelToken = Nothing Then + cancelToken = New CancellationTokenSource().Token + End If + + If connectionTimeout <= 0 Then + Throw VbUtils.GetArgumentExceptionWithArgName(NameOf(connectionTimeout), SR.Network_BadConnectionTimeout) + End If + + If addressUri Is Nothing Then + Throw VbUtils.GetArgumentNullException(NameOf(addressUri)) + End If + + Dim normalizedFilePath As String = FileSystemUtils.NormalizeFilePath(sourceFileName, NameOf(sourceFileName)) + + ' Make sure we have a meaningful file. + If String.IsNullOrEmpty(normalizedFilePath) Then + Throw VbUtils.GetInvalidOperationException(SR.Network_DownloadNeedsFilename) + End If + + Dim client As HttpClient = If(clientHandler Is Nothing, + New HttpClient(), + New HttpClient(clientHandler)) + client.Timeout = New TimeSpan(0, 0, 0, 0, connectionTimeout) + + ' Create the copier + Dim copier As New HttpClientCopy(client, dialog) + + ' Upload the file + Try + Await copier.UploadFileWorkerAsync( + filePath:=normalizedFilePath, + requestURI:=addressUri, + externalToken:=cancelToken).ConfigureAwait(continueOnCapturedContext:=False) + Catch ioEx As IO.IOException + Throw + + Catch ex As Exception + If onUserCancel = UICancelOption.ThrowException OrElse (dialog IsNot Nothing AndAlso Not dialog.UserCanceledTheDialog) Then + If ex.Message.Contains("401") Then + Throw New WebException(SR.net_webstatus_Unauthorized, WebExceptionStatus.ProtocolError) + End If + Throw + End If + If ex.Message.Contains("401") Then + Throw New WebException(SR.net_webstatus_Unauthorized) + End If + Finally + CloseProgressDialog(dialog) + End Try + + End Function + + End Class +End Namespace 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 fcfd6afa251..a5b264c37ac 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/NetworkUtilities.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/NetworkUtilities.vb @@ -68,7 +68,7 @@ Namespace Microsoft.VisualBasic.Devices showUI As Boolean) As ProgressDialog If InteractiveEnvironment(showUI) Then - 'Construct the local file. This will validate the full name and path + ' Construct the local file. This will validate the full name and path Dim fullFilename As String = FileSystemUtils.NormalizeFilePath( path:=destinationFileName, paramName:=NameOf(destinationFileName)) @@ -95,7 +95,7 @@ Namespace Microsoft.VisualBasic.Devices Try Return New Uri(address) Catch ex As UriFormatException - 'Throw an exception with an error message more appropriate to our API + ' Throw an exception with an error message more appropriate to our API Throw GetArgumentExceptionWithArgName( argumentName:=NameOf(address), resourceKey:=SR.Network_InvalidUriString, diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/ServerComputer.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/ServerComputer.vb index 1bb249f6e2d..926a2981fb0 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/ServerComputer.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/ServerComputer.vb @@ -12,25 +12,28 @@ Namespace Microsoft.VisualBasic.Devices ''' Public Class ServerComputer - 'NOTE: The .Net design guidelines state that access to Instance members does not have to be thread-safe. Access to Shared members does have to be thread-safe. - 'Since My.Computer creates the instance of Computer in a thread-safe way, access to the Computer will necessarily be thread-safe. - 'There is nothing to prevent a user from passing our computer object across threads or creating their own instance and then getting into trouble. - 'But that is completely consistent with the rest of the FX design. It is MY.* that is thread safe and leads to best practice access to these objects. - 'If you dim them up yourself, you are responsible for managing the threading. - - 'Lazy initialized cache for the Clock class. SHARED because Clock behaves as a readonly singleton class + ' NOTE: The .Net design guidelines state that access to Instance members does not have to be thread-safe. + ' Access to Shared members does have to be thread-safe. Since My.Computer creates the + ' instance of Computer in a thread-safe way, access to the Computer will necessarily be thread-safe. + ' There is nothing to prevent a user from passing our computer object across threads or + ' creating their own instance and then getting into trouble. + ' But that is completely consistent with the rest of the FX design. + ' It is MY.* that is thread safe and leads to best practice access to these objects. + ' If you dim them up yourself, you are responsible for managing the threading. + + ' Lazy initialized cache for the Clock class. SHARED because Clock behaves as a readonly singleton class Private Shared s_clock As Clock - 'Lazy initialized cache for ComputerInfo + ' Lazy initialized cache for ComputerInfo Private _computerInfo As ComputerInfo - 'Lazy initialized cache for the FileSystem. + ' Lazy initialized cache for the FileSystem. Private _fileIO As FileSystemProxy - 'Lazy initialized cache for the Network class. + ' Lazy initialized cache for the Network class. Private _network As Network - 'Lazy initialized cache for the Registry class + ' Lazy initialized cache for the Registry class Private _registryInstance As RegistryProxy ''' diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/WebClientExtended.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/WebClientExtended.vb deleted file mode 100644 index ca95e62b799..00000000000 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Devices/WebClientExtended.vb +++ /dev/null @@ -1,77 +0,0 @@ -' 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 - -Namespace Microsoft.VisualBasic.Devices - - ''' - ''' Temporary class used to provide WebClient with a timeout property. - ''' - ''' This class will be deleted when Timeout is added to WebClient. - Friend NotInheritable Class WebClientExtended - Inherits WebClient - - ' The Timeout value to be used by WebClient's WebRequest for Downloading or Uploading a file - Private _timeout As Integer = 100000 - - ' Flag used to indicate whether or not we should use passive mode when ftp downloading - Private _useNonPassiveFtp As Boolean - -#Disable Warning BC41004 ' First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete - - Friend Sub New() - End Sub - -#Enable Warning BC41004 ' First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete - - ''' - ''' Sets or indicates the timeout used by WebRequest used by WebClient - ''' - Public WriteOnly Property Timeout() As Integer - Set(value As Integer) - Debug.Assert(value > 0, "illegal value for timeout") - _timeout = value - End Set - End Property - - ''' - ''' Enables switching the server to non passive mode. - ''' - ''' We need this in order for the progress UI on a download to work - Public WriteOnly Property UseNonPassiveFtp() As Boolean - Set(value As Boolean) - _useNonPassiveFtp = value - End Set - End Property - - ''' - ''' Makes sure that the timeout value for WebRequests (used for all Download - ''' and Upload methods) is set to the Timeout value. - ''' - ''' - Protected Overrides Function GetWebRequest(address As Uri) As WebRequest - Dim request As WebRequest = MyBase.GetWebRequest(address) - - Debug.Assert(request IsNot Nothing, "Unable to get WebRequest from base class") - If request IsNot Nothing Then - request.Timeout = _timeout - If _useNonPassiveFtp Then - Dim ftpRequest As FtpWebRequest = TryCast(request, FtpWebRequest) - If ftpRequest IsNot Nothing Then - ftpRequest.UsePassive = False - End If - End If - - Dim httpRequest As HttpWebRequest = TryCast(request, HttpWebRequest) - If httpRequest IsNot Nothing Then - httpRequest.AllowAutoRedirect = False - End If - - End If - - Return request - End Function - - End Class -End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/FileSystemUtils.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/FileSystemUtils.vb index 2702dc0b4cd..eb19c7e80e2 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/FileSystemUtils.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/FileSystemUtils.vb @@ -9,7 +9,7 @@ Imports VbUtils = Microsoft.VisualBasic.CompilerServices.ExceptionUtils Namespace Microsoft.VisualBasic.CompilerServices ''' - ''' Internal utilities from Microsoft.VisualBasic.FileIO.FileSystem. + ''' Internal utilities from . ''' Friend NotInheritable Class FileSystemUtils @@ -20,10 +20,12 @@ Namespace Microsoft.VisualBasic.CompilerServices ''' The given path in long format if the path exists. ''' ''' GetLongPathName is a PInvoke call and requires unmanaged code permission. - ''' Use and (which call FindFirstFile) so that we always have permission. + ''' Use and + ''' (which call FindFirstFile) so that we always have permission. ''' Private Shared Function GetLongPath(fullPath As String) As String - Debug.Assert(Not String.IsNullOrEmpty(fullPath) AndAlso IO.Path.IsPathRooted(fullPath), "Must be full path") + Debug.Assert(Not String.IsNullOrEmpty(fullPath) AndAlso + Path.IsPathRooted(fullPath), "Must be full path") Try ' If root path, return itself. UNC path do not recognize 8.3 format in root path, so this is fine. If IsRoot(fullPath) Then @@ -46,8 +48,9 @@ Namespace Microsoft.VisualBasic.CompilerServices Return fullPath End If Catch ex As Exception - ' Ignore these type of exceptions and return FullPath. These type of exceptions should either be caught by calling functions - ' or indicate that caller does not have enough permission and should get back the 8.3 path. + ' Ignore these type of exceptions and return FullPath. These type of exceptions should + ' either be caught by calling functions or indicate that caller does not have enough permission and + ' should get back the 8.3 path. If TypeOf ex Is ArgumentException OrElse TypeOf ex Is ArgumentNullException OrElse TypeOf ex Is PathTooLongException OrElse @@ -72,9 +75,12 @@ Namespace Microsoft.VisualBasic.CompilerServices ''' Checks if the full path is a root path. ''' ''' The path to check. - ''' if FullPath is a root path, otherwise. + ''' + ''' if FullPath is a root path, + ''' otherwise. + ''' ''' - ''' IO.Path.GetPathRoot: C: -> C:, C:\ -> C:\, \\machine\share -> \\machine\share, + ''' : C: -> C:, C:\ -> C:\, \\machine\share -> \\machine\share, ''' BUT \\machine\share\ -> \\machine\share (No separator here). ''' Therefore, remove any separators at the end to have correct result. ''' @@ -94,7 +100,9 @@ Namespace Microsoft.VisualBasic.CompilerServices ''' Removes all directory separators at the end of a path. ''' ''' a full or relative path. - ''' If Path is a root path, the same value. Otherwise, removes any directory separators at the end. + ''' + ''' If Path is a root path, the same value. Otherwise, removes any directory separators at the end. + ''' ''' We decided not to return path with separators at the end. Private Shared Function RemoveEndingSeparator(path As String) As String If IO.Path.IsPathRooted(path) Then diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeMethods.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeMethods.vb index 5929c87b42d..006deeb8b1e 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeMethods.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeMethods.vb @@ -68,7 +68,8 @@ Namespace Microsoft.VisualBasic.CompilerServices fAttach As Integer) As Integer - Friend Declare Function SetForegroundWindow Lib "user32" (hwnd As IntPtr) As Boolean + Friend Declare Function SetForegroundWindow Lib "user32" ( + hwnd As IntPtr) As Boolean Friend Declare Function SetFocus Lib "user32" (hwnd As IntPtr) As IntPtr @@ -86,7 +87,7 @@ Namespace Microsoft.VisualBasic.CompilerServices hHandle As NativeTypes.LateInitSafeHandleZeroOrMinusOneIsInvalid, dwMilliseconds As Integer) As Integer -#Disable Warning IDE0049 ' Use language keywords instead of framework type names for type references, Justification:= +#Disable Warning IDE0049 ' Use language keywords instead of framework type names for type references, Justification:= #Disable Warning IDE1006 ' Naming Styles, Justification:= ''' @@ -99,21 +100,24 @@ Namespace Microsoft.VisualBasic.CompilerServices End Function ''' - ''' Contains information about the current state of both physical and virtual memory, including extended memory. + ''' Contains information about the current state of both physical and virtual memory, + ''' including extended memory. ''' Friend Structure MEMORYSTATUSEX - 'typedef struct _MEMORYSTATUSEX { - ' DWORD dwLength; Size of the structure. Must set before calling GlobalMemoryStatusEx. - ' DWORD dwMemoryLoad; Number between 0 and 100 on current memory utilization. - ' DWORDLONG ullTotalPhys; Total size of physical memory. - ' DWORDLONG ullAvailPhys; Total size of available physical memory. - ' DWORDLONG ullTotalPageFile; Size of committed memory limit. - ' DWORDLONG ullAvailPageFile; Size of available memory to committed (ullTotalPageFile max). - ' DWORDLONG ullTotalVirtual; Total size of user potion of virtual address space of calling process. - ' DWORDLONG ullAvailVirtual; Total size of unreserved and uncommitted memory in virtual address space. - ' DWORDLONG ullAvailExtendedVirtual; Total size of unreserved and uncommitted memory in extended portion of virtual address. - '} MEMORYSTATUSEX, *LPMEMORYSTATUSEX; + ' typedef struct _MEMORYSTATUSEX { + ' DWORD dwLength; Size of the structure. Must set before calling GlobalMemoryStatusEx. + ' DWORD dwMemoryLoad; Number between 0 and 100 on current memory utilization. + ' DWORDLONG ullTotalPhys; Total size of physical memory. + ' DWORDLONG ullAvailPhys; Total size of available physical memory. + ' DWORDLONG ullTotalPageFile; Size of committed memory limit. + ' DWORDLONG ullAvailPageFile; Size of available memory to committed (ullTotalPageFile max). + ' DWORDLONG ullTotalVirtual; Total size of user potion of virtual address space of calling process. + ' DWORDLONG ullAvailVirtual; Total size of unreserved and uncommitted memory in + ' virtual address space. + ' DWORDLONG ullAvailExtendedVirtual; Total size of unreserved and uncommitted memory in + ' extended portion of virtual address. + ' } MEMORYSTATUSEX, *LPMEMORYSTATUSEX; Friend dwLength As UInt32 Friend dwMemoryLoad As UInt32 diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeTypes.PROCESS_INFORMATION.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeTypes.PROCESS_INFORMATION.vb index 885793b7380..e77604aa430 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeTypes.PROCESS_INFORMATION.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeTypes.PROCESS_INFORMATION.vb @@ -8,7 +8,8 @@ Namespace Microsoft.VisualBasic.CompilerServices Partial Friend NotInheritable Class NativeTypes ''' - ''' Represent Win32 PROCESS_INFORMATION structure. IMPORTANT: Copy the handles to a SafeHandle before use them. + ''' Represent Win32 PROCESS_INFORMATION structure. + ''' IMPORTANT: Copy the handles to a SafeHandle before use them. ''' ''' ''' The handles in PROCESS_INFORMATION are initialized in unmanaged function. diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeTypes.STARTUPINFO.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeTypes.STARTUPINFO.vb index 9ca12db3db1..4179920d5d8 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeTypes.STARTUPINFO.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/NativeTypes.STARTUPINFO.vb @@ -10,11 +10,15 @@ Namespace Microsoft.VisualBasic.CompilerServices #Disable Warning CA1812 ' Supress warning as this is a type used in PInvoke and shouldn't be changed. ''' - ''' Important! This class should be used where the API being called has allocated the strings. That is why lpReserved, etc. are declared as IntPtrs instead - ''' of Strings - so that the marshaling layer won't release the memory. This caused us problems in the shell() functions. We would call GetStartupInfo() - ''' which doesn't expect the memory for the strings to be freed. But because the strings were previously defined as type String, the marshaller would + ''' Important! This class should be used where the API being called has allocated the strings. + ''' That is why lpReserved, etc. are declared as IntPtrs instead of Strings + ''' - so that the marshaling layer won't release the memory. + ''' This caused us problems in the shell() functions. We would call GetStartupInfo() + ''' which doesn't expect the memory for the strings to be freed. + ''' But because the strings were previously defined as type String, the marshaller would ''' and we got memory corruption problems detectable while running AppVerifier. - ''' If you use this structure with an API like CreateProcess() then you are supplying the strings so you'll need another version of this class that defines lpReserved, etc. + ''' If you use this structure with an API like CreateProcess() then you are supplying the strings + ''' so you'll need another version of this class that defines lpReserved, etc. ''' as String so that the memory will get cleaned up. ''' @@ -22,9 +26,9 @@ Namespace Microsoft.VisualBasic.CompilerServices Implements IDisposable Public cb As Integer - Public lpReserved As IntPtr = IntPtr.Zero 'not string - see summary - Public lpDesktop As IntPtr = IntPtr.Zero 'not string - see summary - Public lpTitle As IntPtr = IntPtr.Zero 'not string - see summary + Public lpReserved As IntPtr = IntPtr.Zero ' Not string - see summary + Public lpDesktop As IntPtr = IntPtr.Zero ' Not string - see summary + Public lpTitle As IntPtr = IntPtr.Zero ' Not string - see summary Public dwX As Integer Public dwY As Integer Public dwXSize As Integer @@ -73,7 +77,7 @@ Namespace Microsoft.VisualBasic.CompilerServices NativeMethods.CloseHandle(hStdError) hStdError = s_invalidHandle End If - End If 'Me.dwFlags and STARTF_USESTDHANDLES + End If ' Me.dwFlags and STARTF_USESTDHANDLES End If End If diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/UnsafeNativeMethods.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/UnsafeNativeMethods.vb index 2df7838af03..e83ac9a6180 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/UnsafeNativeMethods.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/UnsafeNativeMethods.vb @@ -15,7 +15,10 @@ Namespace Microsoft.VisualBasic.CompilerServices ''' The amount of free space available to the current user. ''' The total amount of space on the disk relative to the current user. ''' The amount of free space on the disk. - ''' if function succeeds in getting info otherwise . + ''' + ''' if function succeeds in getting info. + ''' Otherwise . + ''' Friend Function GetDiskFreeSpaceEx( Directory As String, diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/VBInputBox.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/VBInputBox.vb index 0f91f6a9029..b2911d61b4e 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/VBInputBox.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Helpers/VBInputBox.vb @@ -21,7 +21,7 @@ Namespace Microsoft.VisualBasic.CompilerServices #Enable Warning IDE1006 ' Naming Styles Public Output As String = String.Empty - 'This constructor needed to be able to show the designer at design-time. + ' This constructor needed to be able to show the designer at design-time. Friend Sub New() MyBase.New() InitializeComponent() @@ -41,28 +41,32 @@ Namespace Microsoft.VisualBasic.CompilerServices Label = New Label SuspendLayout() ' - 'OKButton + ' OKButton ' resources.ApplyResources(OKButton, "OKButton", CultureInfo.CurrentUICulture) OKButton.Name = "OKButton" ' - 'MyCancelButton + ' MyCancelButton ' MyCancelButton.DialogResult = DialogResult.Cancel - resources.ApplyResources(MyCancelButton, "MyCancelButton", CultureInfo.CurrentUICulture) + resources.ApplyResources( + value:=MyCancelButton, + objectName:="MyCancelButton", + culture:=CultureInfo.CurrentUICulture) + MyCancelButton.Name = "MyCancelButton" ' - 'TextBox + ' TextBox ' resources.ApplyResources(TextBox, "TextBox", CultureInfo.CurrentUICulture) TextBox.Name = "TextBox" ' - 'Label + ' Label ' resources.ApplyResources(Label, "Label", CultureInfo.CurrentUICulture) Label.Name = "Label" ' - 'VBInputBox + ' VBInputBox ' AcceptButton = OKButton resources.ApplyResources(Me, "$this", CultureInfo.CurrentUICulture) @@ -80,28 +84,34 @@ Namespace Microsoft.VisualBasic.CompilerServices End Sub - 'Initialize labels etc from the args passed in to InputBox() - Private Sub InitializeInputBox(prompt As String, title As String, defaultResponse As String, xPos As Integer, yPos As Integer) + ' Initialize labels etc from the args passed in to InputBox() + Private Sub InitializeInputBox( + prompt As String, + title As String, + defaultResponse As String, + xPos As Integer, + yPos As Integer) + Text = title Label.Text = prompt TextBox.Text = defaultResponse AddHandler OKButton.Click, AddressOf OKButton_Click AddHandler MyCancelButton.Click, AddressOf MyCancelButton_Click - 'Re-size the dialog if the prompt is too large + ' Re-size the dialog if the prompt is too large Dim labelGraphics As Graphics = Label.CreateGraphics Dim labelSizeNeeded As SizeF = labelGraphics.MeasureString(prompt, Label.Font, Label.Width) labelGraphics.Dispose() If labelSizeNeeded.Height > Label.Height Then - 'The current label size is not large enough to accommodate the prompt. We need - ' to expand the label and the dialog, and move the textbox to make room. + ' The current label size is not large enough to accommodate the prompt. We need + ' to expand the label and the dialog, and move the textbox to make room. Dim dialogHeightChange As Integer = CInt(labelSizeNeeded.Height - Label.Height) Label.Height += dialogHeightChange TextBox.Top += dialogHeightChange Height += dialogHeightChange End If - 'Position the form + ' Position the form If (xPos = -1) AndAlso (yPos = -1) Then StartPosition = FormStartPosition.CenterScreen Else diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Interaction.InputBoxHandler.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Interaction.InputBoxHandler.vb index ade7075bddc..db1e41e6aeb 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Interaction.InputBoxHandler.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Interaction.InputBoxHandler.vb @@ -17,7 +17,14 @@ Namespace Microsoft.VisualBasic Private _exception As Exception Private _result As String - Public Sub New(Prompt As String, Title As String, DefaultResponse As String, XPos As Integer, YPos As Integer, ParentWindow As IWin32Window) + Public Sub New( + Prompt As String, + Title As String, + DefaultResponse As String, + XPos As Integer, + YPos As Integer, + ParentWindow As IWin32Window) + _prompt = Prompt _title = Title _defaultResponse = DefaultResponse @@ -40,7 +47,14 @@ Namespace Microsoft.VisualBasic Public Sub StartHere() Try - _result = InternalInputBox(_prompt, _title, _defaultResponse, _xPos, _yPos, _parentWindow) + _result = InternalInputBox( + _prompt, + _title, + _defaultResponse, + _xPos, + _yPos, + _parentWindow) + Catch ex As Exception _exception = ex End Try diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Interaction.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Interaction.vb index 14004e09e8b..87d092e7505 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Interaction.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Interaction.vb @@ -13,20 +13,28 @@ Imports VbUtils = Microsoft.VisualBasic.CompilerServices.ExceptionUtils Namespace Microsoft.VisualBasic - ' Helper methods invoked through reflection from Microsoft.VisualBasic.Interaction in Microsoft.VisualBasic.Core.dll. - ' Do not change this API without also updating that dependent module. + ' Helper methods invoked through reflection from Microsoft.VisualBasic.Interaction + ' in Microsoft.VisualBasic.Core.dll. Do not change this API without also updating + ' that dependent module. Friend Module _Interaction Private Sub AppActivateHelper(hwndApp As IntPtr, processId As String) - ' if no window with name (full or truncated) or task id, return an error - ' if the window is not enabled or not visible, get the first window owned by it that is not enabled or not visible + ' if no window with name (full or truncated) or task id, return an error + ' if the window is not enabled or not visible, get the first window owned + ' by it that is not enabled or not visible Dim hwndOwned As IntPtr - If Not SafeNativeMethods.IsWindowEnabled(hwndApp) OrElse Not SafeNativeMethods.IsWindowVisible(hwndApp) Then - ' scan to the next window until failure + If Not SafeNativeMethods.IsWindowEnabled(hwndApp) _ + OrElse Not SafeNativeMethods.IsWindowVisible(hwndApp) Then + + ' scan to the next window until failure hwndOwned = NativeMethods.GetWindow(hwndApp, NativeTypes.GW_HWNDFIRST) Do While IntPtr.op_Inequality(hwndOwned, IntPtr.Zero) - If IntPtr.op_Equality(NativeMethods.GetWindow(hwndOwned, NativeTypes.GW_OWNER), hwndApp) Then - If Not SafeNativeMethods.IsWindowEnabled(hwndOwned) OrElse Not SafeNativeMethods.IsWindowVisible(hwndOwned) Then + + Dim value1 As IntPtr = NativeMethods.GetWindow(hwndOwned, NativeTypes.GW_OWNER) + If IntPtr.op_Equality(value1, hwndApp) Then + If Not SafeNativeMethods.IsWindowEnabled(hwndOwned) _ + OrElse Not SafeNativeMethods.IsWindowVisible(hwndOwned) Then + hwndApp = hwndOwned hwndOwned = NativeMethods.GetWindow(hwndApp, NativeTypes.GW_HWNDFIRST) Else @@ -36,12 +44,13 @@ Namespace Microsoft.VisualBasic hwndOwned = NativeMethods.GetWindow(hwndOwned, NativeTypes.GW_HWNDNEXT) Loop - ' if scan failed, return an error + ' if scan failed, return an error If IntPtr.op_Equality(hwndOwned, IntPtr.Zero) Then - Throw New ArgumentException(Utils.GetResourceString(SR.ProcessNotFound, processId)) + Dim message As String = Utils.GetResourceString(SR.ProcessNotFound, processId) + Throw New ArgumentException(message) End If - ' set active window to the owned one + ' set active window to the owned one hwndApp = hwndOwned End If @@ -54,35 +63,42 @@ Namespace Microsoft.VisualBasic Dim dwDummy As Integer ' dummy arg for SafeNativeMethods.GetWindowThreadProcessId ' Attach ourselves to the window we want to set focus to - NativeMethods.AttachThreadInput(0, SafeNativeMethods.GetWindowThreadProcessId(hwndApp, dwDummy), 1) + NativeMethods.AttachThreadInput( + idAttach:=0, + idAttachTo:=SafeNativeMethods.GetWindowThreadProcessId(hwndApp, dwDummy), + fAttach:=1) + ' Make it foreground and give it focus, this will occur ' synchronously because we are attached. NativeMethods.SetForegroundWindow(hwndApp) NativeMethods.SetFocus(hwndApp) ' Unattached ourselves from the window - NativeMethods.AttachThreadInput(0, SafeNativeMethods.GetWindowThreadProcessId(hwndApp, dwDummy), 0) + NativeMethods.AttachThreadInput( + idAttach:=0, + idAttachTo:=SafeNativeMethods.GetWindowThreadProcessId(hwndApp, dwDummy), + fAttach:=0) End Sub Private Function GetTitleFromAssembly(callingAssembly As Reflection.Assembly) As String Dim title As String - 'Get the Assembly name of the calling assembly - 'Assembly.GetName requires PathDiscovery permission so we try this first - 'and if it throws we catch the security exception and parse the name - 'from the full assembly name + ' Get the Assembly name of the calling assembly + ' Assembly.GetName requires PathDiscovery permission so we try this first + ' and if it throws we catch the security exception and parse the name + ' from the full assembly name Try title = callingAssembly.GetName().Name Catch ex As SecurityException Dim fullName As String = callingAssembly.FullName - 'Find the text up to the first comma. Note, this fails if the assembly has - 'a comma in its name + ' Find the text up to the first comma. Note, this fails if the assembly has + ' a comma in its name Dim firstCommaLocation As Integer = fullName.IndexOf(","c) If firstCommaLocation >= 0 Then title = fullName.Substring(0, firstCommaLocation) Else - 'The name is not in the format we're expecting so return an empty string + ' The name is not in the format we're expecting so return an empty string title = String.Empty End If End Try @@ -91,7 +107,14 @@ Namespace Microsoft.VisualBasic End Function - Private Function InternalInputBox(prompt As String, title As String, defaultResponse As String, xPos As Integer, yPos As Integer, parentWindow As IWin32Window) As String + Private Function InternalInputBox( + prompt As String, + title As String, + defaultResponse As String, + xPos As Integer, + yPos As Integer, + parentWindow As IWin32Window) As String + Using box As New VBInputBox(prompt, title, defaultResponse, xPos, yPos) box.ShowDialog(parentWindow) Return box.Output @@ -99,25 +122,34 @@ Namespace Microsoft.VisualBasic End Function Public Sub AppActivateByProcessId(ProcessId As Integer) - 'As an optimization, we will only check the UI permission once we actually know we found the app to activate - we'll do that in AppActivateHelper + ' As an optimization, we will only check the UI permission once we actually + ' know we found the app to activate- we'll do that in AppActivateHelper Dim processIdOwningWindow As Integer - 'Note, a process can have multiple windows. What we want to do is dig through to find one - 'that we can actually activate. So first ignore all the ones that are not visible and don't support mouse - 'or keyboard input - Dim windowHandle As IntPtr = NativeMethods.GetWindow(NativeMethods.GetDesktopWindow(), NativeTypes.GW_CHILD) + ' Note, a process can have multiple windows. What we want to do is dig through to find one + ' that we can actually activate. So first ignore all the ones that are not visible and don't support mouse + ' or keyboard input + Dim windowHandle As IntPtr = NativeMethods.GetWindow( + hwnd:=NativeMethods.GetDesktopWindow(), + wFlag:=NativeTypes.GW_CHILD) Do While IntPtr.op_Inequality(windowHandle, IntPtr.Zero) SafeNativeMethods.GetWindowThreadProcessId(windowHandle, processIdOwningWindow) - If (processIdOwningWindow = ProcessId) AndAlso SafeNativeMethods.IsWindowEnabled(windowHandle) AndAlso SafeNativeMethods.IsWindowVisible(windowHandle) Then - Exit Do 'We found a window belonging to the desired process that we can actually activate and will support user input + If (processIdOwningWindow = ProcessId) _ + AndAlso SafeNativeMethods.IsWindowEnabled(windowHandle) _ + AndAlso SafeNativeMethods.IsWindowVisible(windowHandle) Then + + ' We found a window belonging to the desired process that we can actually + ' activate and will support user input + Exit Do End If - 'keep rummaging through windows looking for one that belongs to the process we are after + ' Keep rummaging through windows looking for one that belongs to the process we are after windowHandle = NativeMethods.GetWindow(windowHandle, NativeTypes.GW_HWNDNEXT) Loop - 'If we didn't find a window during the pass above, try the less desirable route of finding any window that belongs to the process + ' If we didn't find a window during the pass above, + ' try the less desirable route of finding any window that belongs to the process If IntPtr.op_Equality(windowHandle, IntPtr.Zero) Then windowHandle = NativeMethods.GetWindow(NativeMethods.GetDesktopWindow(), NativeTypes.GW_CHILD) @@ -127,24 +159,28 @@ Namespace Microsoft.VisualBasic Exit Do End If - 'keep rummaging through windows looking for one that belongs to the process we are after + ' Keep rummaging through windows looking for one that belongs to the process we are after windowHandle = NativeMethods.GetWindow(windowHandle, NativeTypes.GW_HWNDNEXT) Loop End If - If IntPtr.op_Equality(windowHandle, IntPtr.Zero) Then 'we never found a window belonging to the desired process - Throw New ArgumentException(Utils.GetResourceString(SR.ProcessNotFound, CStr(ProcessId))) + If IntPtr.op_Equality(windowHandle, IntPtr.Zero) Then + ' We never found a window belonging to the desired process + Dim message As String = Utils.GetResourceString(SR.ProcessNotFound, CStr(ProcessId)) + Throw New ArgumentException(message) Else AppActivateHelper(windowHandle, CStr(ProcessId)) End If End Sub Public Sub AppActivateByTitle(Title As String) - 'As an optimization, we will only check the UI permission once we actually know we found the app to activate - we'll do that in AppActivateHelper - Dim windowHandle As IntPtr = NativeMethods.FindWindow(Nothing, Title) 'see if we can find the window using an exact match on the title + ' As an optimization, we will only check the UI permission once we actually know + ' we found the app to activate - we'll do that in AppActivateHelper + ' See if we can find the window using an exact match on the title + Dim windowHandle As IntPtr = NativeMethods.FindWindow(lpClassName:=Nothing, lpWindowName:=Title) Const MAX_TITLE_LENGTH As Integer = 511 - ' if no match, search through all parent windows + ' if no match, search through all parent windows If IntPtr.op_Equality(windowHandle, IntPtr.Zero) Then Dim appTitle As String ' Old implementation uses MAX_TITLE_LENGTH characters, INCLUDING NULL character. @@ -153,57 +189,90 @@ Namespace Microsoft.VisualBasic Dim appTitleLength As Integer Dim titleLength As Integer = Len(Title) - 'Loop through all children of the desktop + ' Loop through all children of the desktop windowHandle = NativeMethods.GetWindow(NativeMethods.GetDesktopWindow(), NativeTypes.GW_CHILD) Do While IntPtr.op_Inequality(windowHandle, IntPtr.Zero) - ' get the window caption and test for a left-aligned substring - appTitleLength = NativeMethods.GetWindowText(windowHandle, appTitleBuilder, appTitleBuilder.Capacity) + ' Get the window caption and test for a left-aligned substring + appTitleLength = NativeMethods.GetWindowText( + hWnd:=windowHandle, + lpString:=appTitleBuilder, + nMaxCount:=appTitleBuilder.Capacity) + appTitle = appTitleBuilder.ToString() If appTitleLength >= titleLength Then - If String.Compare(appTitle, 0, Title, 0, titleLength, StringComparison.OrdinalIgnoreCase) = 0 Then - Exit Do 'found one + If String.Compare( + strA:=appTitle, + indexA:=0, + strB:=Title, + indexB:=0, + length:=titleLength, + comparisonType:=StringComparison.OrdinalIgnoreCase) = 0 Then + + Exit Do ' Found one End If End If - 'keep looking + ' Keep looking windowHandle = NativeMethods.GetWindow(windowHandle, NativeTypes.GW_HWNDNEXT) Loop If IntPtr.op_Equality(windowHandle, IntPtr.Zero) Then ' We didn't find it so try right aligned - windowHandle = NativeMethods.GetWindow(NativeMethods.GetDesktopWindow(), NativeTypes.GW_CHILD) + windowHandle = NativeMethods.GetWindow( + hwnd:=NativeMethods.GetDesktopWindow(), + wFlag:=NativeTypes.GW_CHILD) Do While IntPtr.op_Inequality(windowHandle, IntPtr.Zero) - ' get the window caption and test for a right-aligned substring - appTitleLength = NativeMethods.GetWindowText(windowHandle, appTitleBuilder, appTitleBuilder.Capacity) + ' get the window caption and test for a right-aligned substring + appTitleLength = NativeMethods.GetWindowText( + hWnd:=windowHandle, + lpString:=appTitleBuilder, + nMaxCount:=appTitleBuilder.Capacity) + appTitle = appTitleBuilder.ToString() If appTitleLength >= titleLength Then - If String.Compare(Right(appTitle, titleLength), 0, Title, 0, titleLength, StringComparison.OrdinalIgnoreCase) = 0 Then - Exit Do 'found a match + If String.Compare( + strA:=Right(str:=appTitle, Length:=titleLength), + indexA:=0, + strB:=Title, + indexB:=0, + length:=titleLength, + comparisonType:=StringComparison.OrdinalIgnoreCase) = 0 Then + + Exit Do ' Found a match End If End If - 'keep looking + ' Keep looking windowHandle = NativeMethods.GetWindow(windowHandle, NativeTypes.GW_HWNDNEXT) Loop End If End If - If IntPtr.op_Equality(windowHandle, IntPtr.Zero) Then 'no match + If IntPtr.op_Equality(windowHandle, IntPtr.Zero) Then ' No match Throw New ArgumentException(Utils.GetResourceString(SR.ProcessNotFound, Title)) Else AppActivateHelper(windowHandle, Title) End If End Sub - Public Function InputBox(Prompt As String, Title As String, DefaultResponse As String, XPos As Integer, YPos As Integer) As String + Public Function InputBox( + Prompt As String, + Title As String, + DefaultResponse As String, + XPos As Integer, + YPos As Integer) As String + Dim vbHost As IVbHost Dim parentWindow As IWin32Window = Nothing vbHost = HostServices.VBHost - If vbHost IsNot Nothing Then 'If we are hosted then we want to use the host as the parent window. If no parent window that's fine. + + ' If we are hosted then we want to use the host as the parent window. + ' If no parent window that's fine. + If vbHost IsNot Nothing Then parentWindow = vbHost.GetParentWindow() End If @@ -215,9 +284,9 @@ Namespace Microsoft.VisualBasic End If End If - 'Threading state can only be set once, and will most often be already set - 'but set to STA and check if it isn't STA, then we need to start another thread - 'to display the InputBox + ' Threading state can only be set once, and will most often be already set + ' but set to STA and check if it isn't STA, then we need to start another thread + ' to display the InputBox If Thread.CurrentThread.GetApartmentState() <> ApartmentState.STA Then Dim inputHandler As New InputBoxHandler(Prompt, Title, DefaultResponse, XPos, YPos, parentWindow) Dim thread As New Thread(New ThreadStart(AddressOf inputHandler.StartHere)) @@ -245,14 +314,15 @@ Namespace Microsoft.VisualBasic parentWindow = vbHost.GetParentWindow() End If - 'Only allow legal button combinations to be set, one choice from each group - 'These bit constants are defined in System.Windows.Forms.MessageBox - 'Low-order 4 bits (0x000f), legal values: 0, 1, 2, 3, 4, 5 - ' next 4 bits (0x00f0), legal values: 0, &H10, &H20, &H30, &H40 - ' next 4 bits (0x0f00), legal values: 0, &H100, &H200 + ' Only allow legal button combinations to be set, one choice from each group + ' These bit constants are defined in System.Windows.Forms.MessageBox + ' Low-order 4 bits (0x000f), legal values: 0, 1, 2, 3, 4, 5 + ' next 4 bits (0x00f0), legal values: 0, &H10, &H20, &H30, &H40 + ' next 4 bits (0x0f00), legal values: 0, &H100, &H200 If ((Buttons And &HFI) > MsgBoxStyle.RetryCancel) _ - OrElse ((Buttons And &HF0I) > MsgBoxStyle.Information) _ - OrElse ((Buttons And &HF00I) > MsgBoxStyle.DefaultButton3) Then + OrElse ((Buttons And &HF0I) > MsgBoxStyle.Information) _ + OrElse ((Buttons And &HF00I) > MsgBoxStyle.DefaultButton3) Then + Buttons = MsgBoxStyle.OkOnly End If @@ -267,7 +337,8 @@ Namespace Microsoft.VisualBasic Catch ex As ThreadAbortException Throw Catch - Throw New ArgumentException(Utils.GetResourceString(SR.Argument_InvalidValueType2, "Prompt", "String")) + Throw New ArgumentException( + Utils.GetResourceString(SR.Argument_InvalidValueType2, "Prompt", "String")) End Try Try @@ -278,8 +349,10 @@ Namespace Microsoft.VisualBasic sTitle = vbHost.GetWindowTitle() End If Else - sTitle = CStr(Title) 'allows the title to be an expression, e.g. MsgBox(prompt, Title:=1+5) + ' Allows the title to be an expression, e.g. MsgBox(prompt, Title:=1+5) + sTitle = CStr(Title) End If + Catch ex As StackOverflowException Throw Catch ex As OutOfMemoryException @@ -287,15 +360,18 @@ Namespace Microsoft.VisualBasic Catch ex As ThreadAbortException Throw Catch - Throw New ArgumentException(Utils.GetResourceString(SR.Argument_InvalidValueType2, "Title", "String")) + Throw New ArgumentException( + Utils.GetResourceString(SR.Argument_InvalidValueType2, "Title", "String")) End Try - - Return CType(MessageBox.Show(parentWindow, sPrompt, sTitle, - CType(Buttons And &HF, MessageBoxButtons), - CType(Buttons And &HF0, MessageBoxIcon), - CType(Buttons And &HF00, MessageBoxDefaultButton), - CType(Buttons And &HFFFFF000, MessageBoxOptions)), - MsgBoxResult) + Dim result As DialogResult = MessageBox.Show( + owner:=parentWindow, + text:=sPrompt, + caption:=sTitle, + buttons:=CType(Buttons And &HF, MessageBoxButtons), + icon:=CType(Buttons And &HF0, MessageBoxIcon), + defaultButton:=CType(Buttons And &HF00, MessageBoxDefaultButton), + options:=CType(Buttons And &HFFFFF000, MessageBoxOptions)) + Return CType(result, MsgBoxResult) End Function Public Function Shell(PathName As String, Style As AppWinStyle, Wait As Boolean, Timeout As Integer) As Integer @@ -307,25 +383,40 @@ Namespace Microsoft.VisualBasic Dim errorCode As Integer = 0 If PathName Is Nothing Then - Throw New ArgumentNullException(Utils.GetResourceString(SR.Argument_InvalidNullValue1, "Pathname")) + Throw New ArgumentNullException( + paramName:=Utils.GetResourceString(ResourceKey:=SR.Argument_InvalidNullValue1, "Pathname")) End If If Style < 0 OrElse Style > 9 Then - Throw New ArgumentException(Utils.GetResourceString(SR.Argument_InvalidValue1, "Style")) + Throw New ArgumentException( + message:=Utils.GetResourceString(ResourceKey:=SR.Argument_InvalidValue1, "Style")) End If NativeMethods.GetStartupInfo(startupInfo) Try - startupInfo.dwFlags = NativeTypes.STARTF_USESHOWWINDOW ' we want to specify the initial window style (minimized, etc) so set this bit. + ' we want to specify the initial window style (minimized, etc) so set this bit. + startupInfo.dwFlags = NativeTypes.STARTF_USESHOWWINDOW startupInfo.wShowWindow = Style - 'We have to have unmanaged permissions to do this, so asking for path permissions would be redundant - 'Note: We are using the StartupInfo (defined in NativeTypes.StartupInfo) in CreateProcess() even though this version - 'of the StartupInfo type uses IntPtr instead of String because GetStartupInfo() above requires that version so we don't - 'free the string fields since the API manages it instead. But its OK here because we are just passing along the memory - 'that GetStartupInfo() allocated along to CreateProcess() which just reads the string fields. + ' We have to have unmanaged permissions to do this, so asking for path permissions would be redundant + ' Note: We are using the StartupInfo (defined in NativeTypes.StartupInfo) in CreateProcess() + ' even though this version of the StartupInfo type uses IntPtr instead of String because + ' GetStartupInfo() above requires that version so we don't free the string fields since the + ' API manages it instead. But its OK here because we are just passing along the memory + ' that GetStartupInfo() allocated along to CreateProcess() which just reads the string fields. + + ok = NativeMethods.CreateProcess( + lpApplicationName:=Nothing, + lpCommandLine:=PathName, + lpProcessAttributes:=Nothing, + lpThreadAttributes:=Nothing, + bInheritHandles:=False, + dwCreationFlags:=NativeTypes.NORMAL_PRIORITY_CLASS, + lpEnvironment:=Nothing, + lpCurrentDirectory:=Nothing, + lpStartupInfo:=startupInfo, + lpProcessInformation:=processInfo) - ok = NativeMethods.CreateProcess(Nothing, PathName, Nothing, Nothing, False, NativeTypes.NORMAL_PRIORITY_CLASS, Nothing, Nothing, startupInfo, processInfo) If ok = 0 Then errorCode = Marshal.GetLastWin32Error() End If @@ -339,24 +430,26 @@ Namespace Microsoft.VisualBasic Try If ok <> 0 Then If Wait Then - ' Is infinite wait okay here ? - ' This is okay since this is marked as requiring the HostPermission with ExternalProcessMgmt rights + ' Is infinite wait okay here? + ' This is okay since this is marked as requiring the HostPermission + ' with ExternalProcessMgmt rights ok = NativeMethods.WaitForSingleObject(safeProcessHandle, Timeout) - If ok = 0 Then 'succeeded - 'Process ran to completion - Shell = 0 + If ok = 0 Then + ' Succeeded + ' Process ran to completion + Return 0 Else - 'Wait timed out - Shell = processInfo.dwProcessId + ' Wait timed out + Return processInfo.dwProcessId End If Else - NativeMethods.WaitForInputIdle(safeProcessHandle, 10000) - Shell = processInfo.dwProcessId + NativeMethods.WaitForInputIdle(safeProcessHandle, Milliseconds:=10000) + Return processInfo.dwProcessId End If Else - 'Check for a win32 error access denied. If it is, make and throw the exception. - 'If not, throw FileNotFound + ' Check for a win32 error access denied. If it is, make and throw the exception. + ' If not, throw FileNotFound Const ERROR_ACCESS_DENIED As Integer = 5 If errorCode = ERROR_ACCESS_DENIED Then Throw VbUtils.VbMakeException(VbErrors.PermissionDenied) diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/FileLogTraceListener.ReferencedStream.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/FileLogTraceListener.ReferencedStream.vb index 3aca1cf1207..85774dc7f98 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/FileLogTraceListener.ReferencedStream.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/FileLogTraceListener.ReferencedStream.vb @@ -141,6 +141,6 @@ Namespace Microsoft.VisualBasic.Logging GC.SuppressFinalize(Me) End Sub - End Class 'ReferencedStream + End Class ' ReferencedStream End Class End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/FileLogTraceListener.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/FileLogTraceListener.vb index fe06c7aa46a..bcbcf78fba2 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/FileLogTraceListener.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/FileLogTraceListener.vb @@ -218,7 +218,10 @@ Namespace Microsoft.VisualBasic.Logging ''' ''' Indicates whether or not the should be flushed after every write. ''' - ''' if the stream should be flushed after every write, otherwise . + ''' + ''' if the stream should be flushed after every write, + ''' otherwise . + ''' Public Property AutoFlush() As Boolean Get If Not _propertiesSet(AUTOFLUSH_INDEX) Then @@ -293,7 +296,11 @@ Namespace Microsoft.VisualBasic.Logging ' If we're using custom location and the value is changing we need to ' close the stream - If Location = LogFileLocation.Custom And Not String.Equals(tempPath, _customLocation, StringComparison.OrdinalIgnoreCase) Then + If Location = LogFileLocation.Custom AndAlso + Not String.Equals( + tempPath, + _customLocation, + StringComparison.OrdinalIgnoreCase) Then CloseCurrentStream() End If @@ -334,8 +341,12 @@ Namespace Microsoft.VisualBasic.Logging Get If Not _propertiesSet(DISKSPACEEXHAUSTEDBEHAVIOR_INDEX) Then If Attributes.ContainsKey(KEY_DISKSPACEEXHAUSTEDBEHAVIOR) Then - Dim converter As TypeConverter = TypeDescriptor.GetConverter(GetType(DiskSpaceExhaustedOption)) - Me.DiskSpaceExhaustedBehavior = DirectCast(converter.ConvertFromInvariantString(Attributes(KEY_DISKSPACEEXHAUSTEDBEHAVIOR)), DiskSpaceExhaustedOption) + Dim type As Type = GetType(DiskSpaceExhaustedOption) + Dim converter As TypeConverter = TypeDescriptor.GetConverter(type) + Dim text As String = Attributes(KEY_DISKSPACEEXHAUSTEDBEHAVIOR) + Me.DiskSpaceExhaustedBehavior = DirectCast( + converter.ConvertFromInvariantString(text), + DiskSpaceExhaustedOption) End If End If Return _diskSpaceExhaustedBehavior @@ -383,7 +394,8 @@ Namespace Microsoft.VisualBasic.Logging Get If Not _propertiesSet(INCLUDEHOSTNAME_INDEX) Then If Attributes.ContainsKey(KEY_INCLUDEHOSTNAME) Then - Me.IncludeHostName = Convert.ToBoolean(Attributes(KEY_INCLUDEHOSTNAME), CultureInfo.InvariantCulture) + Dim value As String = Attributes(KEY_INCLUDEHOSTNAME) + Me.IncludeHostName = Convert.ToBoolean(value, CultureInfo.InvariantCulture) End If End If Return _includeHostName @@ -404,7 +416,8 @@ Namespace Microsoft.VisualBasic.Logging If Not _propertiesSet(LOCATION_INDEX) Then If Attributes.ContainsKey(KEY_LOCATION) Then Dim converter As TypeConverter = TypeDescriptor.GetConverter(GetType(LogFileLocation)) - Me.Location = DirectCast(converter.ConvertFromInvariantString(Attributes(KEY_LOCATION)), LogFileLocation) + Dim text As String = Attributes(KEY_LOCATION) + Me.Location = DirectCast(converter.ConvertFromInvariantString(text), LogFileLocation) End If End If Return _location @@ -429,8 +442,12 @@ Namespace Microsoft.VisualBasic.Logging Get If Not _propertiesSet(LOGFILECREATIONSCHEDULE_INDEX) Then If Attributes.ContainsKey(KEY_LOGFILECREATIONSCHEDULE) Then - Dim converter As TypeConverter = TypeDescriptor.GetConverter(GetType(LogFileCreationScheduleOption)) - Me.LogFileCreationSchedule = DirectCast(converter.ConvertFromInvariantString(Attributes(KEY_LOGFILECREATIONSCHEDULE)), LogFileCreationScheduleOption) + Dim converter As TypeConverter = TypeDescriptor.GetConverter( + GetType(LogFileCreationScheduleOption)) + Dim text As String = Attributes(KEY_LOGFILECREATIONSCHEDULE) + Me.LogFileCreationSchedule = DirectCast( + converter.ConvertFromInvariantString(text), + LogFileCreationScheduleOption) End If End If Return _logFileDateStamp @@ -463,7 +480,10 @@ Namespace Microsoft.VisualBasic.Logging Set(value As Long) DemandWritePermission() If value < MIN_FILE_SIZE Then - Throw VbUtils.GetArgumentExceptionWithArgName(NameOf(value), SR.ApplicationLogNumberTooSmall, "MaxFileSize") + Throw VbUtils.GetArgumentExceptionWithArgName( + argumentName:=NameOf(value), + resourceKey:=SR.ApplicationLogNumberTooSmall, + "MaxFileSize") End If _maxFileSize = value _propertiesSet(MAXFILESIZE_INDEX) = True @@ -478,7 +498,9 @@ Namespace Microsoft.VisualBasic.Logging Get If Not _propertiesSet(RESERVEDISKSPACE_INDEX) Then If Attributes.ContainsKey(KEY_RESERVEDISKSPACE) Then - Me.ReserveDiskSpace = Convert.ToInt64(Attributes(KEY_RESERVEDISKSPACE), CultureInfo.InvariantCulture) + Me.ReserveDiskSpace = Convert.ToInt64( + value:=Attributes(KEY_RESERVEDISKSPACE), + provider:=CultureInfo.InvariantCulture) End If End If Return _reserveDiskSpace @@ -486,7 +508,10 @@ Namespace Microsoft.VisualBasic.Logging Set(value As Long) DemandWritePermission() If value < 0 Then - Throw VbUtils.GetArgumentExceptionWithArgName(NameOf(value), SR.ApplicationLog_NegativeNumber, "ReserveDiskSpace") + Throw VbUtils.GetArgumentExceptionWithArgName( + NameOf(value), + SR.ApplicationLog_NegativeNumber, + "ReserveDiskSpace") End If _reserveDiskSpace = value _propertiesSet(RESERVEDISKSPACE_INDEX) = True @@ -534,7 +559,10 @@ Namespace Microsoft.VisualBasic.Logging ''' Private Shared Sub ValidateDiskSpaceExhaustedOptionEnumValue(value As DiskSpaceExhaustedOption, paramName As String) If value < DiskSpaceExhaustedOption.ThrowException OrElse value > DiskSpaceExhaustedOption.DiscardMessages Then - Throw New InvalidEnumArgumentException(paramName, value, GetType(DiskSpaceExhaustedOption)) + Throw New InvalidEnumArgumentException( + argumentName:=paramName, + invalidValue:=value, + enumClass:=GetType(DiskSpaceExhaustedOption)) End If End Sub @@ -542,9 +570,15 @@ Namespace Microsoft.VisualBasic.Logging ''' Validates that the value being passed as an LogFileCreationScheduleOption enum is a legal value. ''' ''' - Private Shared Sub ValidateLogFileCreationScheduleOptionEnumValue(value As LogFileCreationScheduleOption, paramName As String) + Private Shared Sub ValidateLogFileCreationScheduleOptionEnumValue( + value As LogFileCreationScheduleOption, + paramName As String) + If value < LogFileCreationScheduleOption.None OrElse value > LogFileCreationScheduleOption.Weekly Then - Throw New InvalidEnumArgumentException(paramName, value, GetType(LogFileCreationScheduleOption)) + Throw New InvalidEnumArgumentException( + argumentName:=paramName, + invalidValue:=value, + enumClass:=GetType(LogFileCreationScheduleOption)) End If End Sub @@ -554,7 +588,10 @@ Namespace Microsoft.VisualBasic.Logging ''' Private Shared Sub ValidateLogFileLocationEnumValue(value As LogFileLocation, paramName As String) If value < LogFileLocation.TempDirectory OrElse value > LogFileLocation.Custom Then - Throw New InvalidEnumArgumentException(paramName, value, GetType(LogFileLocation)) + Throw New InvalidEnumArgumentException( + argumentName:=paramName, + invalidValue:=value, + enumClass:=GetType(LogFileLocation)) End If End Sub @@ -591,7 +628,10 @@ Namespace Microsoft.VisualBasic.Logging ''' This ensures these API cannot be used to circumvent CAS. ''' Private Sub DemandWritePermission() - Debug.Assert(Not String.IsNullOrWhiteSpace(Path.GetDirectoryName(LogFileName)), "The log directory shouldn't be empty.") + Debug.Assert( + condition:=Not String.IsNullOrWhiteSpace(Path.GetDirectoryName(LogFileName)), + message:="The log directory shouldn't be empty.") + Dim fileName As String = Path.GetDirectoryName(LogFileName) End Sub @@ -614,11 +654,11 @@ Namespace Microsoft.VisualBasic.Logging Dim reader As StreamReader = Nothing Try - 'Attempt to determine the encoding of the file. The call to Reader.ReadLine - 'will change the current encoding of Reader to that of the file. + ' Attempt to determine the encoding of the file. The call to Reader.ReadLine + ' will change the current encoding of Reader to that of the file. reader = New StreamReader(fileName, Encoding, True) - 'Ignore 0 length file + ' Ignore 0 length file If reader.BaseStream.Length > 0 Then reader.ReadLine() @@ -640,7 +680,7 @@ Namespace Microsoft.VisualBasic.Logging Private Function GetFreeDiskSpace() As Long Dim pathName As String = Path.GetPathRoot(Path.GetFullPath(FullLogFileName)) - 'Initialize FreeUserSpace so we can determine if its value is changed by the API call + ' Initialize FreeUserSpace so we can determine if its value is changed by the API call Dim freeUserSpace As Long = -1 Dim totalUserSpace As Long Dim totalFreeSpace As Long @@ -668,7 +708,8 @@ Namespace Microsoft.VisualBasic.Logging While refStream Is Nothing AndAlso i < MAX_OPEN_ATTEMPTS ' This should only be true if processes outside our process have - ' MAX_OPEN_ATTEMPTS files open using the naming schema (file-1.log, file-2.log ... file-MAX_OPEN_ATTEMPTS.log) + ' MAX_OPEN_ATTEMPTS files open using the naming schema + ' (file-1.log, file-2.log ... file-MAX_OPEN_ATTEMPTS.log) Dim fileName As String If i = 0 Then @@ -723,8 +764,9 @@ Namespace Microsoft.VisualBasic.Logging i += 1 End SyncLock End While - 'If we fall out the loop, we have failed to obtain a valid stream name. This occurs if there are files on your system - 'ranging from BaseStreamName0..BaseStreamName{integer.MaxValue} which is pretty unlikely but hey. + ' If we fall out the loop, we have failed to obtain a valid stream name. + ' This occurs if there are files on your system ranging from BaseStreamName0.. + ' BaseStreamName{integer.MaxValue} which is pretty unlikely but hey. Throw VbUtils.GetInvalidOperationException(SR.ApplicationLog_ExhaustedPossibleStreamNames, baseStreamName) End Function @@ -752,20 +794,24 @@ Namespace Microsoft.VisualBasic.Logging ''' the free disk space against the user's limits. ''' ''' The size of what's about to be written to the file. - ''' if the limits aren't trespassed, otherwise . + ''' + ''' if the limits aren't trespassed, otherwise . + ''' ''' This method is not 100% accurate if AutoFlush is False. Private Function ResourcesAvailable(newEntrySize As Long) As Boolean If ListenerStream.FileSize + newEntrySize > MaxFileSize Then If DiskSpaceExhaustedBehavior = DiskSpaceExhaustedOption.ThrowException Then - Throw New InvalidOperationException(Utils.GetResourceString(SR.ApplicationLog_FileExceedsMaximumSize)) + Throw New InvalidOperationException( + message:=Utils.GetResourceString(SR.ApplicationLog_FileExceedsMaximumSize)) End If Return False End If If GetFreeDiskSpace() - newEntrySize < ReserveDiskSpace Then If DiskSpaceExhaustedBehavior = DiskSpaceExhaustedOption.ThrowException Then - Throw New InvalidOperationException(Utils.GetResourceString(SR.ApplicationLog_ReservedSpaceEncroached)) + Throw New InvalidOperationException( + message:=Utils.GetResourceString(SR.ApplicationLog_ReservedSpaceEncroached)) End If Return False End If @@ -822,7 +868,12 @@ Namespace Microsoft.VisualBasic.Logging ''' The eventType of the message. ''' The id of the message. ''' An object containing the message to be logged. - Public Overrides Sub TraceData(eventCache As TraceEventCache, source As String, eventType As TraceEventType, id As Integer, data As Object) + Public Overrides Sub TraceData( + eventCache As TraceEventCache, + source As String, + eventType As TraceEventType, + id As Integer, + data As Object) Dim message As String = String.Empty If data IsNot Nothing Then @@ -840,7 +891,12 @@ Namespace Microsoft.VisualBasic.Logging ''' The eventType of the message. ''' The id of the message. ''' A list of objects making up the message to be logged. - Public Overrides Sub TraceData(eventCache As TraceEventCache, source As String, eventType As TraceEventType, id As Integer, ParamArray data As Object()) + Public Overrides Sub TraceData( + eventCache As TraceEventCache, + source As String, + eventType As TraceEventType, + id As Integer, + ParamArray data As Object()) Dim messageBuilder As New StringBuilder() If data IsNot Nothing Then @@ -864,10 +920,23 @@ Namespace Microsoft.VisualBasic.Logging ''' The eventType of the message. ''' The id of the message. ''' The message. - Public Overrides Sub TraceEvent(eventCache As TraceEventCache, source As String, eventType As TraceEventType, id As Integer, message As String) + Public Overrides Sub TraceEvent( + eventCache As TraceEventCache, + source As String, + eventType As TraceEventType, + id As Integer, + message As String) If Filter IsNot Nothing Then - If Not Filter.ShouldTrace(eventCache, source, eventType, id, message, Nothing, Nothing, Nothing) Then + If Not Filter.ShouldTrace( + cache:=eventCache, + source, + eventType, + id, + formatOrMessage:=message, + args:=Nothing, + data1:=Nothing, + data:=Nothing) Then Return End If End If @@ -936,7 +1005,13 @@ Namespace Microsoft.VisualBasic.Logging ''' The id of the message. ''' A string with placeholders that serves as a format for the message. ''' The values for the placeholders in format. - Public Overrides Sub TraceEvent(eventCache As TraceEventCache, source As String, eventType As TraceEventType, id As Integer, format As String, ParamArray args() As Object) + Public Overrides Sub TraceEvent( + eventCache As TraceEventCache, + source As String, + eventType As TraceEventType, + id As Integer, + format As String, + ParamArray args() As Object) ' Create the message Dim message As String @@ -1000,5 +1075,5 @@ Namespace Microsoft.VisualBasic.Logging End Try End Sub - End Class 'FileLogTraceListener + End Class End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/Log.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/Log.vb index 6c00c4cf337..562e6a58cf0 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/Log.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/Log.vb @@ -28,7 +28,9 @@ Namespace Microsoft.VisualBasic.Logging ''' ''' Creates a Log and the underlying TraceSource based on the platform. ''' - ''' Right now we only support WinApp as an application platform. + ''' + ''' Right now we only support WinApp as an application platform. + ''' Public Sub New() ' Set trace source for platform. Right now we only support WinApp _traceSource = New DefaultTraceSource(WINAPP_SOURCE_NAME) @@ -67,7 +69,7 @@ Namespace Microsoft.VisualBasic.Logging Public ReadOnly Property TraceSource() As TraceSource Get - 'Note, this is a downcast from the DefaultTraceSource class we are using + ' Note: This is a downcast from the DefaultTraceSource class we are using Return _traceSource End Get End Property @@ -120,7 +122,7 @@ Namespace Microsoft.VisualBasic.Logging ''' configure the trace source according to the defaults they would have had in a default AppConfig. ''' Protected Friend Overridable Sub InitializeWithDefaultsSinceNoConfigExists() - 'By default, you get a file log listener that picks everything from level Information on up. + ' By default, you get a file log listener that picks everything from level Information on up. _traceSource.Listeners.Add(New FileLogTraceListener(DEFAULT_FILE_LOG_TRACE_LISTENER_NAME)) _traceSource.Switch.Level = SourceLevels.Information End Sub diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/Logging.LogFileCreationScheduleOption.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/Logging.LogFileCreationScheduleOption.vb index e479f066cd1..3fa8a4af2fe 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/Logging.LogFileCreationScheduleOption.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/Logging/Logging.LogFileCreationScheduleOption.vb @@ -7,9 +7,9 @@ Namespace Microsoft.VisualBasic.Logging ''' Options for the date stamp in the name of a log file. ''' Public Enum LogFileCreationScheduleOption As Integer - None '(default) - Daily 'YYYY-MM-DD for today - Weekly 'YYYY-MM-DD for first day of this week + None ' (default) + Daily ' YYYY-MM-DD for today + Weekly ' YYYY-MM-DD for first day of this week End Enum End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ContextValue.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ContextValue.vb index fcadcdd3286..133328a9ae3 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ContextValue.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ContextValue.vb @@ -21,7 +21,7 @@ Namespace Microsoft.VisualBasic.MyServices.Internal Private Shared s_threadLocal As ThreadLocal(Of IDictionary) - 'An item is stored in the dictionary by a GUID which this string maintains + ' An item is stored in the dictionary by a GUID which this string maintains Private ReadOnly _contextKey As String Public Sub New() @@ -39,7 +39,7 @@ Namespace Microsoft.VisualBasic.MyServices.Internal Get Dim dictionary As IDictionary = GetDictionary() - 'Note, IDictionary(key) can return Nothing and that's OK + ' Note: IDictionary(key) can return Nothing and that's OK Return DirectCast(dictionary(_contextKey), T) End Get Set(value As T) @@ -50,7 +50,10 @@ Namespace Microsoft.VisualBasic.MyServices.Internal Private Shared Function GetDictionary() As IDictionary If s_threadLocal Is Nothing Then - Interlocked.CompareExchange(s_threadLocal, New ThreadLocal(Of IDictionary)(Function() New Dictionary(Of String, T)), Nothing) + Interlocked.CompareExchange( + location1:=s_threadLocal, + value:=New ThreadLocal(Of IDictionary)(Function() New Dictionary(Of String, T)), + comparand:=Nothing) End If Return s_threadLocal.Value End Function 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..f2cfe043a11 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/HttpClientCopy.vb @@ -0,0 +1,258 @@ +' 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.Net.Http.Headers +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 + + Private Const BufferSize As Integer = 8192 + + ' The WebClient performs the downloading or uploading operations for us + Private ReadOnly _httpClient As HttpClient + + Private _cancelTokenSourceGet As CancellationTokenSource + Private _cancelTokenSourcePost As CancellationTokenSource + Private _cancelTokenSourceReadStream As CancellationTokenSource + Private _cancelTokenSourceWriteStream 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 + + ''' + ''' 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() + _cancelTokenSourceReadStream?.Cancel() + _cancelTokenSourcePost?.Cancel() + _cancelTokenSourceWriteStream?.Cancel() + 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(method:=New DoIncrement(AddressOf _progressDialog.Increment), increment) + End If + + End If + End If + 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() + _cancelTokenSourceReadStream = New CancellationTokenSource() + _cancelTokenSourceWriteStream = New CancellationTokenSource() + + Dim response As HttpResponseMessage = Nothing + Dim totalBytesRead As Long = 0 + Try + Using linkedCts As CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cancelTokenSourceGet.Token, externalToken) + response = Await _httpClient.GetAsync( + requestUri:=addressUri, + completionOption:=HttpCompletionOption.ResponseHeadersRead, + cancellationToken:=_cancelTokenSourceGet.Token).ConfigureAwait(continueOnCapturedContext:=False) + End Using + 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 + Select Case response.StatusCode + Case HttpStatusCode.OK + _cancelTokenSourceReadStream = CancellationTokenSource.CreateLinkedTokenSource(New CancellationTokenSource().Token, externalToken) + _cancelTokenSourceWriteStream = 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(BufferSize - 1) As Byte + Dim bytesRead As Integer + Try + bytesRead = Await responseStream.ReadAsync( + buffer:=buffer.AsMemory(start:=0, buffer.Length), + cancellationToken:=_cancelTokenSourceReadStream.Token). + ConfigureAwait(continueOnCapturedContext:=False) + + Do While bytesRead > 0 + totalBytesRead += bytesRead + + Await fileStream.WriteAsync( + buffer:=buffer.AsMemory(0, bytesRead), + cancellationToken:=_cancelTokenSourceWriteStream.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:=_cancelTokenSourceReadStream.Token). + ConfigureAwait(continueOnCapturedContext:=False) + Loop + Finally + CloseProgressDialog(_progressDialog) + End Try + End Using + End Using + + 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 + + ''' + ''' Uploads a file + ''' + ''' The name and path of the source file + ''' The address to which the file is uploaded + Public Async Function UploadFileWorkerAsync(filePath As String, requestURI As Uri, externalToken As CancellationToken) As Task + Debug.Assert(_httpClient IsNot Nothing, "No WebClient") + Debug.Assert(requestURI IsNot Nothing, "No address") + + _cancelTokenSourceReadStream = New CancellationTokenSource() + _cancelTokenSourcePost = New CancellationTokenSource() + Dim contentLength As Long = New FileInfo(filePath).Length + Dim totalBytesRead As Long = 0 + Dim progress As Action(Of Long, Long) = + Sub(bytesRead As Long, streamLength As Long) + totalBytesRead += bytesRead + If _progressDialog IsNot Nothing Then + Dim progressPercentage As Integer = CInt(totalBytesRead / streamLength * 100) + InvokeIncrement(progressPercentage) + Thread.Sleep(millisecondsTimeout:=1) + End If + End Sub + Using linkedStreamCts As CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cancelTokenSourceReadStream.Token, _cancelTokenSourcePost.Token, externalToken) + Try + Dim response As HttpResponseMessage + Using multipartContent As New MultipartFormDataContent("----boundary") + Dim fileStream As New FileStream(filePath, FileMode.Open, FileAccess.Read) + Dim fileContent As New StreamContent(fileStream) + fileContent.Headers.ContentType = New MediaTypeHeaderValue("application/octet-stream") + Dim fileName As String = Path.GetFileName(filePath) + multipartContent.Add(fileContent, "file", $"""{fileName}""") + If _progressDialog Is Nothing Then + response = + Await _httpClient.PostAsync(requestURI, multipartContent, cancellationToken:=linkedStreamCts.Token) _ + .ConfigureAwait(continueOnCapturedContext:=False) + Else + Dim progressContent As New ProgressableStreamContent(multipartContent, progress, BufferSize) + response = + Await _httpClient.PostAsync(requestURI, progressContent, cancellationToken:=linkedStreamCts.Token) _ + .ConfigureAwait(continueOnCapturedContext:=False) + End If + response.EnsureSuccessStatusCode() + Select Case response.StatusCode + Case HttpStatusCode.OK + Case HttpStatusCode.Unauthorized + Throw New WebException(SR.net_webstatus_Unauthorized, WebExceptionStatus.ProtocolError) + Case Else + Throw New WebException() + End Select + response?.Dispose() + Await fileStream.DisposeAsync().ConfigureAwait(False) + End Using + Catch ex As HttpRequestException + Throw + Catch ex As TaskCanceledException + If ex.CancellationToken = externalToken Then + externalToken.ThrowIfCancellationRequested() + ElseIf linkedStreamCts.IsCancellationRequested Then + ' a real cancellation, triggered by the caller + Throw + Else + Throw New WebException(SR.net_webstatus_Timeout, WebExceptionStatus.Timeout) + End If + Finally + CloseProgressDialog(_progressDialog) + End Try + End Using + If _progressDialog IsNot Nothing Then + RemoveHandler _progressDialog.UserHitCancel, AddressOf _progressDialog_UserHitCancel + End If + End Function + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ProgressDialog.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ProgressDialog.vb index 80650ca3691..bdfaddfdfa9 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ProgressDialog.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ProgressDialog.vb @@ -28,7 +28,7 @@ Namespace Microsoft.VisualBasic.MyServices.Internal ' Constant used to get re-sizable dialog with border style set to fixed dialog. Private Const WS_THICKFRAME As Integer = &H40000 - 'Required by the Windows Form Designer + ' Required by the Windows Form Designer Private ReadOnly _components As IContainer ' Indicates whether or not the user has canceled the copy @@ -116,9 +116,9 @@ Namespace Microsoft.VisualBasic.MyServices.Internal RaiseEvent UserHitCancel() End Sub - 'NOTE: The following procedure is required by the Windows Form Designer - 'It can be modified using the Windows Form Designer. - 'Do not modify it using the code editor. + ' NOTE: The following procedure is required by the Windows Form Designer + ' It can be modified using the Windows Form Designer. + ' Do not modify it using the code editor. Private Sub InitializeComponent() Dim resources As New ComponentResourceManager(GetType(ProgressDialog)) @@ -127,23 +127,23 @@ Namespace Microsoft.VisualBasic.MyServices.Internal ButtonCloseDialog = New Button SuspendLayout() ' - 'LabelInfo + ' LabelInfo ' resources.ApplyResources(LabelInfo, "LabelInfo", CultureInfo.CurrentUICulture) LabelInfo.MaximumSize = New Size(300, 0) LabelInfo.Name = "LabelInfo" ' - 'ProgressBarWork + ' ProgressBarWork ' resources.ApplyResources(ProgressBarWork, "ProgressBarWork", CultureInfo.CurrentUICulture) ProgressBarWork.Name = "ProgressBarWork" ' - 'ButtonCloseDialog + ' ButtonCloseDialog ' resources.ApplyResources(ButtonCloseDialog, "ButtonCloseDialog", CultureInfo.CurrentUICulture) ButtonCloseDialog.Name = "ButtonCloseDialog" ' - 'ProgressDialog + ' ProgressDialog ' resources.ApplyResources(Me, "$this", CultureInfo.CurrentUICulture) Controls.Add(ButtonCloseDialog) @@ -206,7 +206,7 @@ Namespace Microsoft.VisualBasic.MyServices.Internal LabelInfo.MaximumSize = New Size(ClientSize.Width - BORDER_SIZE, 0) End Sub - 'Form overrides dispose to clean up the component list. + ' Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(disposing As Boolean) If disposing Then _components?.Dispose() @@ -257,7 +257,9 @@ Namespace Microsoft.VisualBasic.MyServices.Internal ''' ''' Displays the progress dialog modally ''' - ''' This method should be called on the main thread after the worker thread has been started. + ''' + ''' This method should be called on the main thread after the worker thread has been started. + ''' Public Sub ShowProgressDialog() Try If Not _closing Then diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ProgressableStreamContent.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ProgressableStreamContent.vb new file mode 100644 index 00000000000..2edd4cd8332 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/ProgressableStreamContent.vb @@ -0,0 +1,57 @@ +' 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 + +Namespace Microsoft.VisualBasic.MyServices.Internal + + Friend Class ProgressableStreamContent + Inherits HttpContent + + Private ReadOnly _bufferSize As Integer + Private ReadOnly _content As HttpContent + Private ReadOnly _progress As Action(Of Long, Long) + Public Sub New(content As HttpContent, progress As Action(Of Long, Long), Optional bufferSize As Integer = 4096) + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize) + ArgumentNullException.ThrowIfNull(content) + _content = content + _progress = progress + _bufferSize = bufferSize + For Each header As KeyValuePair(Of String, IEnumerable(Of String)) In content.Headers + Headers.TryAddWithoutValidation(header.Key, header.Value) + Next + End Sub + + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing Then _content.Dispose() + MyBase.Dispose(disposing) + End Sub + + Protected Overrides Async Function SerializeToStreamAsync(stream As Stream, context As TransportContext) As Task + Dim buffer(_bufferSize - 1) As Byte + Dim size As Long + Dim uploaded As Long = 0 + TryComputeLength(size) + + Using sinput As Stream = Await _content.ReadAsStreamAsync().ConfigureAwait(False) + While True + Dim bytesRead As Long = Await sinput.ReadAsync(buffer).ConfigureAwait(False) + If bytesRead <= 0 Then Exit While + uploaded += bytesRead + _progress?.Invoke(uploaded, size) + Await stream.WriteAsync(buffer.AsMemory(0, CInt(bytesRead))).ConfigureAwait(False) + Await Stream.FlushAsync().ConfigureAwait(False) + End While + End Using + Await Stream.FlushAsync().ConfigureAwait(False) + End Function + + Protected Overrides Function TryComputeLength(ByRef length As Long) As Boolean + length = _content.Headers.ContentLength.GetValueOrDefault() + Return True + End Function + + 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 deleted file mode 100644 index 5ebced7ff68..00000000000 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/MyServices/Internal/WebClientCopy.vb +++ /dev/null @@ -1,211 +0,0 @@ -' 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 Microsoft.VisualBasic.Devices - -Namespace Microsoft.VisualBasic.MyServices.Internal - - ''' - ''' Class that controls the thread that does the actual work of downloading or uploading. - ''' - Friend NotInheritable Class WebClientCopy - - ' 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 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 - Private _exceptionEncounteredDuringFileTransfer As Exception - - ' 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 WebClientCopy, used to download or upload a file. - ''' - ''' The used to do the downloading or uploading. - ''' UI for indicating progress. - Public Sub New(client As WebClient, dialog As ProgressDialog) - Debug.Assert(client IsNot Nothing, $"No {client}") - - _webClient = client - _progressDialog = dialog - 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() Handles _progressDialog.UserHitCancel - ' 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. - ''' - ''' - ''' - 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 - Try - 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 upload changes. - ''' - ''' - ''' - Private Sub _webClient_UploadProgressChanged(sender As Object, e As UploadProgressChangedEventArgs) _ - Handles _webClient.UploadProgressChanged - - Dim increment As Long = (e.BytesSent * 100) \ e.TotalBytesToSend - InvokeIncrement(CInt(increment)) - 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 - - ''' - ''' 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. - ''' - ''' 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(_webClient IsNot Nothing, $"No {NameOf(_webClient)}") - Debug.Assert(address IsNot Nothing, $"No {NameOf(address)}") - Debug.Assert((Not String.IsNullOrWhiteSpace(sourceFileName)) _ - AndAlso IO.File.Exists(sourceFileName), "Invalid file") - - ' 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 - _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. - If _exceptionEncounteredDuringFileTransfer IsNot Nothing Then - If _progressDialog Is Nothing OrElse Not _progressDialog.UserCanceledTheDialog Then - Throw _exceptionEncounteredDuringFileTransfer - End If - End If - End Sub - - End Class -End Namespace 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..1650d2ba6fc 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,9 +13,21 @@ WindowsFormsWithCustomSubMain True Library - + + + + + + + PreserveNewest + + + PreserveNewest + + + diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/AssemblyPublicKeyIsAsExpectedTest.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/AssemblyPublicKeyIsAsExpectedTest.vb index f578e38df4c..7b2df7affe9 100644 --- a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/AssemblyPublicKeyIsAsExpectedTest.vb +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/AssemblyPublicKeyIsAsExpectedTest.vb @@ -8,7 +8,12 @@ Imports Xunit Namespace Microsoft.VisualBasic.Forms.Tests Public Class AssemblyPublicKeyIsAsExpectedTest - Private Const AssemblyPK As String = "002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293" + + Private Const AssemblyPK As String = + "002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0" & + "a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad23613210290" & + "0b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99" & + "285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293" ''' ''' Test to find out a correct PublicKey in InternalsVisibleTo for assembly under test. diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/DownloadFileAsyncTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/DownloadFileAsyncTests.vb new file mode 100644 index 00000000000..088a8ce39f4 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/DownloadFileAsyncTests.vb @@ -0,0 +1,122 @@ +' 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 FluentAssertions +Imports Microsoft.VisualBasic.FileIO +Imports Xunit + +Namespace Microsoft.VisualBasic.Forms.Tests + + Public Class DownloadFileAsyncTests + Inherits VbFileCleanupTestBase + + + Public Sub DownloadFileAsync_AllOptions_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + Dim t As Task = Devices.Network.DownloadFileAsync( + addressUri:=New Uri(uriString:=webListener.Address), + destinationFileName, + clientHandler:=New HttpClientHandler, + dialog:=Nothing, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing, + cancelToken:=CancellationToken.None) + If t.IsFaulted Then + Throw t.Exception + End If + t.Wait() + End Sub + + testCode.Should.NotThrow() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(FileSizes.FileSize1MB) + End Using + End Sub + + + Public Sub DownloadFileAsync_AllOptionsClientHandlerNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + Dim t As Task = Devices.Network.DownloadFileAsync( + addressUri:=Nothing, + destinationFileName, + clientHandler:=Nothing, + dialog:=Nothing, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing, + cancelToken:=CancellationToken.None) + If t.IsFaulted Then + Throw t.Exception + End If + End Sub + + testCode.Should.Throw(Of ArgumentNullException)().WithParameterName("addressUri") + End Using + End Sub + + + Public Sub DownloadFileAsync_AllOptionsInvalidTimeout_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + Dim t As Task = Devices.Network.DownloadFileAsync( + addressUri:=New Uri(uriString:=webListener.Address), + destinationFileName, + clientHandler:=Nothing, + dialog:=Nothing, + connectionTimeout:=-1, + overwrite:=True, + onUserCancel:=UICancelOption.DoNothing, + cancelToken:=CancellationToken.None) + If t.IsFaulted Then + Throw t.Exception + End If + End Sub + + testCode.Should.Throw(Of ArgumentException)().WithParameterName("connectionTimeout") + End Using + End Sub + + + Public Sub DownloadFileAsync_UriWithAllOptions_ExceptOnUserCancelWhereUsernameIsNothing_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + Devices.Network.DownloadFileAsync( + addressUri:=New Uri(uriString:=webListener.Address), + destinationFileName, + userName:=Nothing, + password:=String.Empty, + dialog:=Nothing, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=False, + cancelToken:=CancellationToken.None).Wait() + End Sub + testCode.Should.NotThrow() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(FileSizes.FileSize1MB) + End Using + End Sub + + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/DownloadFileTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/DownloadFileTests.vb new file mode 100644 index 00000000000..8ea990fb30a --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/DownloadFileTests.vb @@ -0,0 +1,1615 @@ +' 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.Devices +Imports Microsoft.VisualBasic.FileIO +Imports Xunit + +Namespace Microsoft.VisualBasic.Forms.Tests + + Public Class DownloadFileTests + Inherits VbFileCleanupTestBase + + + + + Public Sub DownloadFile_UnauthorizedUriWithAllOptions_ExceptOnUserCancel_Throws(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + If webListener.ServerThrowsPasswordErrors Then + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + GetNetworkCredentials(webListener.ServerUserName, password), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End If + End Sub + + + + + Public Sub DownloadFile_UnauthorizedUriWithUserNamePassword_Throw(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=String.Empty) + If webListener.ServerThrowsPasswordErrors Then + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=webListener.ServerUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End If + End Sub + + + + + Public Sub DownloadFile_UnauthorizedUriWithUserNamePassword_Throws(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + If webListener.ServerThrowsPasswordErrors Then + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=webListener.ServerUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End If + End Sub + + + + + Public Sub DownloadFile_UnauthorizedUrlWithUserNamePassword_Throw(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=String.Empty) + If webListener.ServerThrowsPasswordErrors Then + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=webListener.ServerUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End If + End Sub + + + + + Public Sub DownloadFile_UnauthorizedUrlWithUserNamePassword_Throws(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + If webListener.ServerThrowsPasswordErrors Then + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=webListener.ServerUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End If + End Sub + + + Public Sub DownloadFile_UriOnly_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UriOnlyWhereAddressIsEmptyString_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)() + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriOnlyWhereAddressIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)() + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + + Public Sub DownloadFile_UriOnlyWhereDestinationFileNameInvalidAddressOnly_Throws(destinationFileName As String) + Dim testDirectory As String = CreateTempDirectory() + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + 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:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True) + End Sub + + testCode.Should.NotThrow() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereDestinationFileNameInvalidOverwrite_Throws( + destinationFileName As String) + + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereFileExistsNoOverwrite_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1Byte) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should.Be(1) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereOverwriteTrue_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1Byte) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereOverwriteWhereDestinationFileExists_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1Byte) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereTimeOut_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize100MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereTimeoutNegative_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize100MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereUriIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereUrlInvalid_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)() + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptions_ExceptOnUserCancelWhereUsernameIsNothing_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsAndNetworkCredentials_Fail() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=Nothing, + destinationFileName, + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.Throw(Of ArgumentNullException)() + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsAndNetworkCredentials_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.NotThrow() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsAndNetworkCredentialsTimeout0_Fail() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=0, + overwrite:=True, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.Throw(Of ArgumentException)() + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsDoNotShowUI_ExceptOnUserCancelWhereInvalidUrl_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)() + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + + Public Sub DownloadFile_UriWithAllOptionsExceptOnUserCancelWhereDestinationFileNameInvalidOverwriteThrows( + destinationFileName As String) + + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Using + 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(FileSizes.FileSize1MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + + Public Sub DownloadFile_UriWithAllOptionsWhereDestinationFileNameInvalid_Throws(destinationFileName As String) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)() + VerifyFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Using + 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(FileSizes.FileSize1MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + 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(FileSizes.FileSize1MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsWhereOnUserCancelIsDoNothing_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + 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(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + 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(FileSizes.FileSize1MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + 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(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsWhereUriIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsWithAllOptions_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UriWithAllOptionsWithAllOptionsWithAllOptionsWhereDestinationIsDirectory_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UriWithUserNamePassword_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + userName:=webListener.ServerUserName, + password:=webListener.ServerPassword) + End Sub + + testCode.Should.NotThrow() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UrlOnly_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName) + End Sub + + testCode.Should.NotThrow() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + 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(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + + Public Sub DownloadFile_UrlOnlyWhereDestinationFileNameInvalidAddressOnly_Throws(destinationFileName As String) + Dim testDirectory As String = CreateTempDirectory() + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereDestinationFileNameInvalidOverwrite_Throws( + destinationFileName As String) + + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereFileExistsNoOverwrite_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1Byte) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should.Be(1) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereInvalidUrlDoNotShowUI_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereOverwriteTrue_Fail() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1GB) + Dim webListener As New WebListener(FileSizes.FileSize1GB) + Using 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() _ + .Throw(Of Exception)() _ + .Where(Function(ex) TypeOf ex Is OperationCanceledException OrElse TypeOf ex Is WebException) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereOverwriteTrue_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1Byte) + Dim webListener As New WebListener(FileSizes.FileSize100MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereOverwriteWhereDestinationFileExists_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1Byte) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereTimeOut_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize100MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereTimeoutNegative_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize100MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereUrlInvalid_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptions_ExceptOnUserCancelWhereUsernameIsNothing_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsAndNetworkCredentials_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=New Uri(webListener.Address), + destinationFileName, + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + overwrite:=True, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.NotThrow() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsDoNotShowUI_ExceptOnUserCancelWhereInvalidUrl_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + + Public Sub DownloadFile_UrlWithAllOptionsWhereAddressIsNothingOrEmpty_Throws(address As String) + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + 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)) + End Sub + + + + Public Sub DownloadFile_UrlWithAllOptionsWhereDestinationFileNameInvalid_Throws(destinationFileName As String) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory:=Nothing, destinationFileName, listener) + End Using + 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(FileSizes.FileSize1MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + 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(FileSizes.FileSize1MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsWhereOnUserCancelIsDoNothing_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + 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(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + 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(FileSizes.FileSize1MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + 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(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsWhereUriIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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)) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsWithAllOptions_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithAllOptionsWithAllOptionsWithAllOptionsWhereDestinationIsDirectory_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using 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) + VerifyFailedDownload(testDirectory, destinationFileName, listener) + End Using + End Sub + + + Public Sub DownloadFile_UrlWithUserNamePassword_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim destinationFileName As String = GetUniqueFileNameWithPath(testDirectory) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.DownloadFile( + address:=webListener.Address, + destinationFileName, + userName:=webListener.ServerUserName, + password:=webListener.ServerPassword) + End Sub + + testCode.Should.NotThrow() + VerifySuccessfulDownload(testDirectory, destinationFileName, listener).Should() _ + .Be(webListener.FileSize) + End Using + End Sub + + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/FileLogTraceListenerTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/FileLogTraceListenerTests.vb index c1e12773b9d..6c5de737f85 100644 --- a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/FileLogTraceListenerTests.vb +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/FileLogTraceListenerTests.vb @@ -24,7 +24,8 @@ Namespace Microsoft.VisualBasic.Forms.Tests .Location = LogFileLocation.Custom, .CustomLocation = testDirectory} - Dim expectedBaseFileName As String = Path.GetFileNameWithoutExtension(Application.ExecutablePath) + Dim expectedBaseFileName As String = + Path.GetFileNameWithoutExtension(Application.ExecutablePath) listener.BaseFileName.Should.BeEquivalentTo(expectedBaseFileName) listener.Name.Should.NotBeNull() @@ -45,7 +46,8 @@ Namespace Microsoft.VisualBasic.Forms.Tests listener.DiskSpaceExhaustedBehavior = DiskSpaceExhaustedOption.ThrowException listener.DiskSpaceExhaustedBehavior.Should.Be(DiskSpaceExhaustedOption.ThrowException) - listener.FullLogFileName.Should.BeEquivalentTo(Path.Combine(testDirectory, $"{expectedBaseFileName}.log")) + Dim expected As String = Path.Combine(testDirectory, expectedBaseFileName & ".log") + listener.FullLogFileName.Should.BeEquivalentTo(expected) listener.LogFileCreationSchedule.Should.Be(LogFileCreationScheduleOption.None) listener.LogFileCreationSchedule = LogFileCreationScheduleOption.Daily @@ -75,7 +77,8 @@ Namespace Microsoft.VisualBasic.Forms.Tests CStr(listener.TestAccessor().Dynamic.HostName).Should.NotBeEmpty() - Dim listenerStream As FileLogTraceListener.ReferencedStream = CType(listener.TestAccessor().Dynamic.ListenerStream, FileLogTraceListener.ReferencedStream) + Dim listenerStream As FileLogTraceListener.ReferencedStream = + CType(listener.TestAccessor().Dynamic.ListenerStream, FileLogTraceListener.ReferencedStream) listenerStream.Should.NotBeNull() listenerStream.IsInUse.Should.BeTrue() listenerStream.FileSize.Should.Be(0) @@ -108,11 +111,17 @@ Namespace Microsoft.VisualBasic.Forms.Tests Public Sub ListenerSetInvalidMaxFileSizePropertiesThrows(value As Long) Dim testDirectory As String = CreateTempDirectory() Using listener As New FileLogTraceListener(NameOf(FileLogTraceListenerTests)) _ - With {.Location = LogFileLocation.Custom, .CustomLocation = testDirectory} + With { + .Location = LogFileLocation.Custom, + .CustomLocation = testDirectory + } - CType(Sub() - listener.MaxFileSize = value - End Sub, Action).Should.Throw(Of ArgumentException)() + Dim testCode As Action = + Sub() + listener.MaxFileSize = value + End Sub + + testCode.Should.Throw(Of ArgumentException)() End Using End Sub diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/FileSystemProxyTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/FileSystemProxyTests.vb index 523cf1fb5bd..7bd5b3d67ad 100644 --- a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/FileSystemProxyTests.vb +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/FileSystemProxyTests.vb @@ -96,7 +96,7 @@ Namespace Microsoft.VisualBasic.Forms.Tests Public Sub DeleteDirectoryRecycleWithUICancelOptionsProxyTest() Dim sourceDirectoryName As String = CreateTempDirectory() - Dim sourceFileName As String = CreateTempFile(sourceDirectoryName, NameOf(sourceFileName), size:=1) + Dim sourceFileName As String = CreateTempFile(sourceDirectoryName, NameOf(sourceFileName), size:=FileSizes.FileSize1Byte) Dim data As Byte() = {4} _fileSystem.WriteAllBytes(sourceFileName, data, append:=False) File.Exists(sourceFileName).Should.BeTrue() @@ -112,7 +112,7 @@ Namespace Microsoft.VisualBasic.Forms.Tests Public Sub DeleteDirectoryWithUIProxyRecycleTest() Dim sourceDirectoryName As String = CreateTempDirectory() - Dim sourceFileName As String = CreateTempFile(sourceDirectoryName, NameOf(sourceFileName), size:=1) + Dim sourceFileName As String = CreateTempFile(sourceDirectoryName, NameOf(sourceFileName), size:=FileSizes.FileSize1Byte) Dim data As Byte() = {4} _fileSystem.WriteAllBytes(sourceFileName, data, append:=False) File.Exists(sourceFileName).Should.BeTrue() @@ -127,7 +127,7 @@ Namespace Microsoft.VisualBasic.Forms.Tests Public Sub DeleteFileWithRecycleOptionProxyTest() Dim sourceDirectoryName As String = CreateTempDirectory() - Dim sourceFileName As String = CreateTempFile(sourceDirectoryName, NameOf(sourceFileName), size:=1) + Dim sourceFileName As String = CreateTempFile(sourceDirectoryName, NameOf(sourceFileName), size:=FileSizes.FileSize1Byte) Dim byteArray As Byte() = {4} _fileSystem.WriteAllBytes(sourceFileName, byteArray, append:=False) File.Exists(sourceFileName).Should.BeTrue() @@ -146,7 +146,7 @@ Namespace Microsoft.VisualBasic.Forms.Tests Public Sub DeleteFileWithUIProxyTest() Dim sourceDirectoryName As String = CreateTempDirectory() - Dim sourceFileName As String = CreateTempFile(sourceDirectoryName, NameOf(sourceFileName), size:=1) + Dim sourceFileName As String = CreateTempFile(sourceDirectoryName, NameOf(sourceFileName), size:=FileSizes.FileSize1Byte) Dim data As Byte() = {4} _fileSystem.WriteAllBytes(sourceFileName, data, append:=False) File.Exists(sourceFileName).Should.BeTrue() @@ -187,7 +187,7 @@ Namespace Microsoft.VisualBasic.Forms.Tests Dim sourceDirectoryName As String = CreateTempDirectory() Dim fileA As String = CreateTempFile(sourceDirectoryName, NameOf(fileA)) _fileSystem.WriteAllText(fileA, "A", append:=False) - Dim fileB As String = CreateTempFile(sourceDirectoryName, NameOf(fileB), size:=1) + Dim fileB As String = CreateTempFile(sourceDirectoryName, NameOf(fileB), size:=FileSizes.FileSize1Byte) Dim fileC As String = CreateTempFile(sourceDirectoryName, NameOf(fileC)) _fileSystem.WriteAllText(fileC, "C", append:=False) Dim filenames As ReadOnlyCollection(Of String) = _fileSystem.FindInFiles( diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/ServerConfigurationTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/ServerConfigurationTests.vb new file mode 100644 index 00000000000..76bb0361468 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/ServerConfigurationTests.vb @@ -0,0 +1,40 @@ +' 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 FluentAssertions +Imports Xunit + +Namespace Microsoft.VisualBasic.Forms.Tests + + Public Class ServerConfigurationTests + + Private Shared Sub Verify(uploading As Boolean, defaultConfiguration As ServerConfiguration, testConfiguration As ServerConfiguration) + defaultConfiguration.GetAcceptsAnonymousLogin(uploading).Should.Be(testConfiguration.GetAcceptsAnonymousLogin(uploading)) + defaultConfiguration.GetDefaultPassword(uploading).Should.Be(testConfiguration.GetDefaultPassword(uploading)) + defaultConfiguration.GetDefaultUserName(uploading).Should.Be(testConfiguration.GetDefaultUserName(uploading)) + defaultConfiguration.GetFileUrlPrefix(uploading).Should.Be(testConfiguration.GetFileUrlPrefix(uploading)) + defaultConfiguration.GetThrowsPasswordErrors(uploading).Should.Be(testConfiguration.GetThrowsPasswordErrors(uploading)) + End Sub + + + + Public Sub VerifyNew_Success(uploading As Boolean) + Dim defaultConfiguration As New ServerConfiguration + Dim testConfiguration As ServerConfiguration = ServerConfiguration.ServerConfigurationLoad + Verify(uploading, defaultConfiguration, testConfiguration) + End Sub + + + + Public Sub VerifySerialization_Success(uploading As Boolean) + Dim defaultConfiguration As New ServerConfiguration + Dim jsonFilePathBase As String = Path.GetTempPath + Dim jsonFullPath As String = defaultConfiguration.ServerConfigurationSave(jsonFilePathBase) + Dim testConfiguration As ServerConfiguration = ServerConfiguration.ServerConfigurationLoad(jsonFilePathBase) + Verify(uploading, defaultConfiguration, testConfiguration) + File.Delete(jsonFullPath) + End Sub + + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/SingleInstanceHelpersTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/SingleInstanceHelpersTests.vb index 297c174fe58..b93e5c6ef48 100644 --- a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/SingleInstanceHelpersTests.vb +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/SingleInstanceHelpersTests.vb @@ -61,15 +61,14 @@ Namespace Microsoft.VisualBasic.Forms.Tests Dim awaitable As ConfiguredTaskAwaitable = SendSecondInstanceArgsAsync( pipeName, args:=commandLine, - cancellationToken:=tokenSource.Token) _ - .ConfigureAwait(continueOnCapturedContext:=False) + cancellationToken:=tokenSource.Token).ConfigureAwait(continueOnCapturedContext:=False) awaitable.GetAwaiter().GetResult() Dim CancelToken As New CancellationToken Dim buffer As Byte() = New Byte(commandLine.Length) {} - Dim count As Integer = - Await pipeServer.ReadAsync(buffer:=buffer.AsMemory(start:=0, length:=commandLine.Length)) _ - .ConfigureAwait(continueOnCapturedContext:=True) + Dim count As Integer = Await pipeServer.ReadAsync( + buffer:=buffer.AsMemory(start:=0, length:=commandLine.Length)) _ + .ConfigureAwait(continueOnCapturedContext:=True) ' Ensure the result is set Do diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/TimeTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/TimeTests.vb index fcffdd0d7ff..279072741e2 100644 --- a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/TimeTests.vb +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/TimeTests.vb @@ -34,7 +34,8 @@ Namespace Microsoft.VisualBasic.Forms.Tests Public Sub VbTimeCloseToSystemTime(timeData As DualTimeZones) Dim systemTime As Date = timeData.SystemTime Dim vbTime As Date = timeData.ComputerTime - Dim because As String = $"{timeData.TimeName} is wrong, System Time is {systemTime} and Clock Time is {vbTime}" + Dim because As String = + $"{timeData.TimeName} is wrong, System Time is {systemTime} and Clock Time is {vbTime}" TimesEqual( vbTime, systemTime, @@ -46,7 +47,8 @@ Namespace Microsoft.VisualBasic.Forms.Tests Dim timeData As New DualTimeZones(TimeZone.MismatchedTimes) Dim systemTime As Date = timeData.SystemTime Dim vbTime As Date = timeData.ComputerTime - Dim because As String = $"{timeData.ComputerTime} is wrong, System Time is {systemTime} and Clock Time is {vbTime}" + Dim because As String = + $"{timeData.ComputerTime} is wrong, System Time is {systemTime} and Clock Time is {vbTime}" Dim results As Boolean = TimesEqual( vbTime, systemTime, diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/UploadFileTests.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/UploadFileTests.vb new file mode 100644 index 00000000000..2eb0c22020f --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/Forms/UploadFileTests.vb @@ -0,0 +1,1472 @@ +' 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.Devices +Imports Microsoft.VisualBasic.FileIO +Imports Xunit + +Namespace Microsoft.VisualBasic.Forms.Tests + + Public Class UploadFileTests + Inherits VbFileCleanupTestBase + + + + + Public Sub UploadFile_UnauthorizedUriWithAllOptions_ExceptOnUserCancelWherePasswordWrong_Throws(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + If webListener.ServerThrowsPasswordErrors Then + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + New NetworkCredential(webListener.ServerUserName, password), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + webListener.FaultMessage.Should.BeNull() + End Using + End If + End Sub + + + + + Public Sub UploadFile_UnauthorizedUriWithUserNamePasswordWherePasswordWrong_Throws(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + If webListener.ServerThrowsPasswordErrors Then + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=webListener.ServerUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + webListener.FaultMessage.Should.BeNull() + End Using + End If + End Sub + + + + + Public Sub UploadFile_UnauthorizedUrlWithUserNamePasswordWherePasswordWrong_Throw(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=String.Empty) + If webListener.ServerThrowsPasswordErrors Then + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address, + userName:=webListener.ServerUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + webListener.FaultMessage.Should.BeNull() + End Using + End If + + End Sub + + + + + Public Sub UploadFile_UnauthorizedUrlWithUserNamePasswordWherePasswordWrong_Throws(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + If webListener.ServerThrowsPasswordErrors Then + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=webListener.ServerUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + webListener.FaultMessage.Should.BeNull() + End Using + End If + End Sub + + + + Public Sub UploadFile_UriOnly_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address)) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + Public Sub UploadFile_UriOnlyWhereAddressIsEmptyString_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(String.Empty)) + End Sub + + testCode.Should.Throw(Of UriFormatException)() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UriOnlyWhereAddressIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(Nothing)) + End Sub + + testCode.Should.Throw(Of ArgumentNullException)() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriOnlyWhereSourceFileNameInvalidAddressOnly_Throws(sourceFileName As String) + Dim testDirectory As String = CreateTempDirectory() + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address)) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriOnlyWrongFileSize_Throw(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1Byte) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address)) + End Sub + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.StartWith("File size mismatch") + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptions_ExceptOnUserCancel_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptions_ExceptOnUserCancelWhereSourceFileNameInvalid_Throws( + sourceFileName As String) + + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=Nothing, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptions_ExceptOnUserCancelWhereTimeOut_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize100MB) + Dim webListener As New WebListener(fileSize:=FileSizes.FileSize100MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=1) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Timeout) + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptions_ExceptOnUserCancelWhereTimeoutNegative_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize100MB) + Dim webListener As New WebListener(FileSizes.FileSize100MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=-1) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(SR.Network_BadConnectionTimeout)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptions_ExceptOnUserCancelWhereTrue_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionLargeTimeout) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptions_ExceptOnUserCancelWhereUriIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=CType(Nothing, Uri), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptions_ExceptOnUserCancelWhereUrlInvalid_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(InvalidUrlAddress), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + testCode.Should().Throw(Of UriFormatException)() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptions_ExceptOnUserCancelWhereUsernameIsNothing_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=Nothing, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptions_ExceptOnUserCancelWhereWhereDestinationFileExists_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptionsAndNetworkCredentials_Fail() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=Nothing, + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.Throw(Of ArgumentNullException)() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptionsAndNetworkCredentials_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptionsAndNetworkCredentialsTimeout0_Fail() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=0, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.Throw(Of ArgumentException)() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptionsDoNotShowUI_ExceptOnUserCancelWhereInvalidUrl_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(InvalidUrlAddress), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + testCode.Should.Throw(Of UriFormatException)() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptionsExceptOnUserCancelWhereSourceFileNameInvalidThrows( + sourceFileName As String) + + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=Nothing, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptionsWhereCheckFilePathTrailingSeparators_Throw(separator As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=$"{sourceFileName}{separator}", + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + 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(sourceFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + + Public Sub UploadFile_UriWithAllOptionsWhereDestinationIsRootDirectory_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=root, ' This is a Root Directory! + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + 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(sourceFileName)) + testCode.Should.Throw(Of ArgumentException)().Where(exceptionExpression) + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptionsWhereFilePathTrailingSeparatorsAreInvalid_Throw(separator As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=$"{sourceFileName}{separator}", + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + 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(sourceFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptionsWhereOnUserCancelIsDoNothing_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + + + Public Sub UploadFile_UriWithAllOptionsWhereRootDirectoryInvalid_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=root, ' This is a Root Directory! + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should().Throw(Of FileNotFoundException)() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + + Public Sub UploadFile_UriWithAllOptionsWhereRootDirectoryTrailingSeparatorInvalid_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=root, ' This is a Root Directory! + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + 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(sourceFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptionsWhereSourceFileNameInvalid_Throws(sourceFileName As String) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=Nothing, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should.Throw(Of ArgumentNullException)() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UriWithAllOptionsWhereUriIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=CType(Nothing, Uri), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UriWithAllOptionsWithAllOptions_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + Public Sub UploadFile_UriWithUserNamePassword_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=webListener.ServerUserName, + password:=webListener.ServerPassword) + End Sub + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + + Public Sub UploadFile_UriWithUserNamePasswordWherePasswordWrong_Throw(password As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=String.Empty) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=webListener.ServerUserName, + password) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UrlOnly_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + + Public Sub UploadFile_UrlOnlyWhereAddressInvalid_Throws(address As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile(sourceFileName, address) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UrlOnlyWhereSourceFileNameInvalidAddressOnly_Throws(sourceFileName As String) + Dim testDirectory As String = CreateTempDirectory() + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile(sourceFileName, address:=webListener.Address) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UrlWithAllOptions_ExceptOnUserCancelWhereInvalidUrlDoNotShowUI_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=InvalidUrlAddress, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + Dim value As String = SR.Network_InvalidUriString.Replace("{0}", "invalidURL") + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(value)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UrlWithAllOptions_ExceptOnUserCancelWhereSourceFileNameInvalid_Throws( + sourceFileName As String) + + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=Nothing, + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UrlWithAllOptions_ExceptOnUserCancelWhereTimeOut_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize100MB) + Dim webListener As New WebListener(FileSizes.FileSize100MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=1) + End Sub + + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Timeout) + End Using + End Sub + + + Public Sub UploadFile_UrlWithAllOptions_ExceptOnUserCancelWhereTimeoutNegative_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize100MB) + Dim webListener As New WebListener(FileSizes.FileSize100MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=-1) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(SR.Network_BadConnectionTimeout)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UrlWithAllOptions_ExceptOnUserCancelWhereTrue_Fail() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1GB) + Dim webListener As New WebListener(FileSizes.FileSize1GB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + testCode.Should() _ + .Throw(Of Exception)() _ + .Where(Function(ex) TypeOf ex Is OperationCanceledException OrElse TypeOf ex Is WebException) + End Using + End Sub + + + + Public Sub UploadFile_UrlWithAllOptions_ExceptOnUserCancelWhereTrue_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=True, + connectionTimeout:=TestingConnectionTimeout) + End Sub + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + Public Sub UploadFile_UrlWithAllOptions_ExceptOnUserCancelWhereUrlInvalid_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=InvalidUrlAddress, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + Dim value As String = SR.Network_InvalidUriString.Replace("{0}", "invalidURL") + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(value)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UrlWithAllOptions_ExceptOnUserCancelWhereUsernameIsNothing_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address, + userName:=Nothing, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + + Public Sub UploadFile_UrlWithAllOptions_ExceptOnUserCancelWhereWhereUploadFailed_Throws(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1Byte) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.StartWith("File size mismatch") + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + Public Sub UploadFile_UrlWithAllOptionsAndNetworkCredentials_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=New Uri(webListener.Address), + GetNetworkCredentials(webListener.ServerUserName, webListener.ServerPassword), + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.ThrowException) + End Sub + + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UrlWithAllOptionsDoNotShowUI_ExceptOnUserCancelWhereInvalidUrl_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=InvalidUrlAddress, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout) + End Sub + + Dim value As String = SR.Network_InvalidUriString.Replace("{0}", "invalidURL") + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(Function(e) e.Message.StartsWith(value)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UrlWithAllOptionsWhereAddressIsNothingOrEmpty_Throws(address As String) + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=Nothing, + address, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + End Sub + + + + + Public Sub UploadFile_UrlWithAllOptionsWhereDestinationIsRootDirectory_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=root, ' This is a Root Directory! + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + 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(sourceFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UrlWithAllOptionsWhereFilePathTrailingSeparatorsAreInvalid_Throw(separator As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=$"{sourceFileName}{separator}", + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + 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(sourceFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UrlWithAllOptionsWhereOnUserCancelIsDoNothing_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + + + Public Sub UploadFile_UrlWithAllOptionsWhereRootDirectoryTrailingSeparatorInvalid_Throw(root As String) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=root, ' This is a Root Directory! + address:=New Uri(webListener.Address), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + 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(sourceFileName)) + testCode.Should() _ + .Throw(Of ArgumentException)() _ + .Where(exceptionExpression) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UrlWithAllOptionsWhereSourceFileNameInvalid_Throws(sourceFileName As String) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName:=Nothing, + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + Public Sub UploadFile_UrlWithAllOptionsWhereUriIsNothing_Throws() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=CType(Nothing, Uri), + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + testCode.Should() _ + .Throw(Of ArgumentNullException)() _ + .Where(Function(e) e.Message.StartsWith(SR.General_ArgumentNullException)) + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + + + Public Sub UploadFile_UrlWithAllOptionsWithAllOptions_Success(supportAnonymousLogin As Boolean) + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener(FileSizes.FileSize1MB, supportAnonymousLogin) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address, + userName:=String.Empty, + password:=String.Empty, + showUI:=False, + connectionTimeout:=TestingConnectionTimeout, + onUserCancel:=UICancelOption.DoNothing) + End Sub + + If webListener.ServerAcceptsAnonymousLogin Then + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + Else + testCode.Should() _ + .Throw(Of WebException)() _ + .WithMessage(SR.net_webstatus_Unauthorized) + End If + End Using + End Sub + + + Public Sub UploadFile_UrlWithUserNamePassword_Success() + Dim testDirectory As String = CreateTempDirectory() + Dim sourceFileName As String = CreateTempFile(testDirectory, size:=FileSizes.FileSize1MB) + Dim webListener As New WebListener( + fileSize:=FileSizes.FileSize1MB, + serverUserName:=DefaultUserName, + serverPassword:=DefaultPassword) + Using listener As HttpListener = webListener.ProcessRequests() + Dim testCode As Action = + Sub() + My.Computer.Network.UploadFile( + sourceFileName, + address:=webListener.Address, + userName:=webListener.ServerUserName, + password:=webListener.ServerPassword) + End Sub + + testCode.Should.NotThrow() + webListener.FaultMessage.Should.BeNull() + End Using + End Sub + + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/DownloadFileTestConstants.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/DownloadFileTestConstants.vb new file mode 100644 index 00000000000..0399b51d3a6 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/DownloadFileTestConstants.vb @@ -0,0 +1,12 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. + +Namespace Microsoft.VisualBasic.Forms.Tests + Public Module DownloadFileTestConstants + Friend Const DefaultPassword As String = NameOf(DefaultPassword) + Friend Const DefaultUserName As String = NameOf(DefaultUserName) + Friend Const InvalidUrlAddress As String = "invalidURL" + Friend Const TestingConnectionLargeTimeout As Integer = 100_000_000 + Friend Const TestingConnectionTimeout As Integer = 100_000 + End Module +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/DownloadFileVerifiers.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/DownloadFileVerifiers.vb new file mode 100644 index 00000000000..14f7044d9f2 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/DownloadFileVerifiers.vb @@ -0,0 +1,59 @@ +' 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 + +Namespace Microsoft.VisualBasic.Forms.Tests + + Public Module DownloadFileVerifiers + ''' + ''' 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. + ''' + Friend Sub VerifyFailedDownload( + 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 + File.Exists(destinationFileName).Should.BeFalse() + End If + 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 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. + ''' + Friend Function VerifySuccessfulDownload( + 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) + listener.Stop() + listener.Close() + Return fileInfo.Length + End Function + + End Module +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/EnumFileSizes.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/EnumFileSizes.vb new file mode 100644 index 00000000000..0d864d545a0 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/EnumFileSizes.vb @@ -0,0 +1,14 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. + +Namespace Microsoft.VisualBasic.Forms.Tests + Friend Module EnumFileSizes + Friend Enum FileSizes As Integer + Unknown = -1 + FileSize1Byte = 1 + FileSize1MB = 1_048_576 + FileSize100MB = 104_857_600 + FileSize1GB = 1_048_576_000 + End Enum + End Module +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/PrivateSetterContractResolver.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/PrivateSetterContractResolver.vb new file mode 100644 index 00000000000..f3156fda23c --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/PrivateSetterContractResolver.vb @@ -0,0 +1,33 @@ +' Licensed to the .NET Foundation under one or more agreements. +' The .NET Foundation licenses this file to you under the MIT license. + +Imports System.Reflection +Imports System.Text.Json +Imports System.Text.Json.Serialization.Metadata + +Namespace Microsoft.VisualBasic.Forms.Tests + Public Class PrivateSetterContractResolver + Inherits DefaultJsonTypeInfoResolver + + Public Overrides Function GetTypeInfo(type As Type, options As JsonSerializerOptions) As JsonTypeInfo + Dim jsonTypeInfo As JsonTypeInfo = MyBase.GetTypeInfo(type, options) + + If jsonTypeInfo.Kind = JsonTypeInfoKind.Object Then + For Each [property] As JsonPropertyInfo In jsonTypeInfo.Properties + [property].Set = Function(obj, value) + Dim prop As PropertyInfo = type.GetProperty( + [property].Name, + BindingFlags.Public _ + Or BindingFlags.NonPublic _ + Or BindingFlags.Instance _ + Or BindingFlags.IgnoreCase) + prop.SetValue(obj, value, Nothing) + Return True + End Function + Next + End If + + Return jsonTypeInfo + End Function + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/ServerConfiguration.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/ServerConfiguration.vb new file mode 100644 index 00000000000..38ad15b17d3 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/ServerConfiguration.vb @@ -0,0 +1,233 @@ +' 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.Text.Json +Imports System.Text.Json.Serialization + +Namespace Microsoft.VisualBasic.Forms.Tests + + Public Class ServerConfiguration + Private Const JsonDefaultFileName As String = "ServerConfiguration.JSON" + + Private Shared ReadOnly s_deserializerOptions As New JsonSerializerOptions() With { + .TypeInfoResolver = New PrivateSetterContractResolver()} + + Private Shared ReadOnly s_jsonFilePathBase As String = Path.Combine( + My.Application.Info.DirectoryPath, + "System\Windows\TestUtilities\TestData") + + Private ReadOnly _serializerOptions As New JsonSerializerOptions With { + .WriteIndented = True} + + Private _fileDownloadUrlPrefix As String = "http://127.0.0.1:8080/" + Private _fileUploadUrlPrefix As String = "http://127.0.0.1:8080/" + Private _serverDownloadAllowsAnonymousUser As Boolean = True + Private _serverDownloadIgnoresPasswordErrors As Boolean + Private _serverDownloadPassword As String = "" + Private _serverDownloadUserName As String = "" + Private _serverUploadAllowsAnonymousUser As Boolean = True + Private _serverUploadIgnoresPasswordErrors As Boolean + Private _serverUploadPassword As String = "" + Private _serverUploadUserName As String = "" + + Public Sub New() + + End Sub + + + Public Sub New( + fileDownloadUrlPrefix As String, + fileUploadUrlPrefix As String, + serverDownloadAllowsAnonymousUser As Boolean, + serverDownloadIgnoresPasswordErrors As Boolean, + serverDownloadPassword As String, + serverDownloadUserName As String, + serverUploadAllowsAnonymousUser As Boolean, + serverUploadIgnoresPasswordErrors As Boolean, + serverUploadPassword As String, + serverUploadUserName As String) + + Me.FileDownloadUrlPrefix = fileDownloadUrlPrefix + Me.FileUploadUrlPrefix = fileUploadUrlPrefix + Me.ServerDownloadAllowsAnonymousUser = serverDownloadAllowsAnonymousUser + Me.ServerDownloadIgnoresPasswordErrors = serverDownloadIgnoresPasswordErrors + Me.ServerDownloadPassword = serverDownloadPassword + Me.ServerDownloadUserName = serverDownloadUserName + Me.ServerUploadAllowsAnonymousUser = serverUploadAllowsAnonymousUser + Me.ServerUploadIgnoresPasswordErrors = serverUploadIgnoresPasswordErrors + Me.ServerUploadPassword = serverUploadPassword + Me.ServerUploadUserName = serverUploadUserName + End Sub + + + Public Property FileDownloadUrlPrefix As String + Private Get + Return _fileDownloadUrlPrefix + End Get + Set + _fileDownloadUrlPrefix = Value + End Set + End Property + + + Public Property FileUploadUrlPrefix As String + Private Get + Return _fileUploadUrlPrefix + End Get + Set + _fileUploadUrlPrefix = Value + End Set + End Property + + + Public Property ServerDownloadAllowsAnonymousUser As Boolean + Private Get + Return _serverDownloadAllowsAnonymousUser + End Get + Set + _serverDownloadAllowsAnonymousUser = Value + End Set + End Property + + + Public Property ServerDownloadIgnoresPasswordErrors As Boolean + Private Get + Return _serverDownloadIgnoresPasswordErrors + End Get + Set + _serverDownloadIgnoresPasswordErrors = Value + End Set + End Property + + + Public Property ServerDownloadPassword As String + Private Get + Return _serverDownloadPassword + End Get + Set + _serverDownloadPassword = Value + End Set + End Property + + + Public Property ServerDownloadUserName As String + Private Get + Return _serverDownloadUserName + End Get + Set + _serverDownloadUserName = Value + End Set + End Property + + + Public Property ServerUploadAllowsAnonymousUser As Boolean + Private Get + Return _serverUploadAllowsAnonymousUser + End Get + Set + _serverUploadAllowsAnonymousUser = Value + End Set + End Property + + + Public Property ServerUploadIgnoresPasswordErrors As Boolean + Private Get + Return _serverUploadIgnoresPasswordErrors + End Get + Set + _serverUploadIgnoresPasswordErrors = Value + End Set + End Property + + + Public Property ServerUploadPassword As String + Private Get + Return _serverUploadPassword + End Get + Set + _serverUploadPassword = Value + End Set + End Property + + + Public Property ServerUploadUserName As String + Private Get + Return _serverUploadUserName + End Get + Set + _serverUploadUserName = Value + End Set + End Property + + Private Shared Function GetJsonFilePath(jsonFilePathBase As String, jsonFileName As String) As String + If String.IsNullOrWhiteSpace(jsonFilePathBase) Then + jsonFilePathBase = s_jsonFilePathBase + End If + Return Path.Combine(jsonFilePathBase, jsonFileName) + End Function + + Friend Function GetAcceptsAnonymousLogin(uploading As Boolean) As Boolean + If uploading Then + Return ServerUploadAllowsAnonymousUser + Else + Return ServerDownloadAllowsAnonymousUser + End If + End Function + + Friend Function GetDefaultPassword(uploading As Boolean) As String + If uploading Then + Return ServerUploadPassword + Else + Return ServerDownloadPassword + End If + End Function + + Friend Function GetDefaultUserName(uploading As Boolean) As String + If uploading Then + Return ServerUploadUserName + Else + Return ServerDownloadUserName + End If + End Function + + Friend Function GetFileUrlPrefix(uploading As Boolean) As String + If uploading Then + Return FileUploadUrlPrefix + Else + Return FileDownloadUrlPrefix + End If + End Function + + Friend Function GetThrowsPasswordErrors(uploading As Boolean) As Boolean + If uploading Then + Return Not ServerUploadIgnoresPasswordErrors + Else + Return Not ServerDownloadIgnoresPasswordErrors + End If + End Function + + Public Shared Function ServerConfigurationLoad( + Optional jsonFilePathBase As String = "", + Optional jsonFileName As String = JsonDefaultFileName) As ServerConfiguration + + Dim jsonFileNameWithPath As String = GetJsonFilePath(jsonFilePathBase, jsonFileName) + If File.Exists(jsonFileNameWithPath) Then + Dim jsonString As String = File.ReadAllText(jsonFileNameWithPath) + Return JsonSerializer.Deserialize(Of ServerConfiguration)(jsonString, s_deserializerOptions) + End If + Return New ServerConfiguration + End Function + + Public Function ServerConfigurationSave( + Optional jsonFilePathBase As String = "", + Optional jsonFileName As String = JsonDefaultFileName) As String + + Dim jsonFileNameWithPath As String = GetJsonFilePath(jsonFilePathBase, jsonFileName) + Dim jsonString As String = JsonSerializer.Serialize(Me, _serializerOptions) + File.WriteAllText(jsonFileNameWithPath, jsonString) + Return jsonFileNameWithPath + End Function + + End Class +End Namespace diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/ServerConfiguration.json b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/ServerConfiguration.json new file mode 100644 index 00000000000..03191e63526 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/ServerConfiguration.json @@ -0,0 +1,12 @@ +{ + "FileDownloadUrlPrefix": "http://127.0.0.1:8080/", + "FileUploadUrlPrefix": "http://127.0.0.1:8080/", + "ServerDownloadAllowsAnonymousUser": true, + "ServerDownloadIgnoresPasswordErrors": false, + "ServerDownloadPassword": "", + "ServerDownloadUserName": "", + "ServerUploadAllowsAnonymousUser": true, + "ServerUploadIgnoresPasswordErrors": false, + "ServerUploadPassword": "", + "ServerUploadUserName": "" +} \ No newline at end of file diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/ServerConfigurationSample.JSON b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/ServerConfigurationSample.JSON new file mode 100644 index 00000000000..3e36d5eef58 --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/ServerConfigurationSample.JSON @@ -0,0 +1,12 @@ +{ + "FileDownloadUrlPrefix": "http://someServer.net/", + "FileUploadUrlPrefix": "ftp://ftp.someServer.com/", + "ServerDownloadAllowsAnonymousUser": false, + "ServerDownloadIgnoresPasswordErrors": true, + "ServerDownloadPassword": "Anything", + "ServerDownloadUserName": "Anonymous", + "ServerUploadAllowsAnonymousUser": false, + "ServerUploadIgnoresPasswordErrors": true, + "ServerUploadPassword": "rNrKYTX9g7z3RgJRmxWuGHbeu", + "ServerUploadUserName": "defaultuser" +} diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/TimeTestData.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/TimeTestData.vb index c7c4995579c..505db22711d 100644 --- a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/TimeTestData.vb +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/TestData/TimeTestData.vb @@ -6,7 +6,9 @@ Namespace Microsoft.VisualBasic.Forms.Tests Public Class TimeTestData Implements IEnumerable(Of Object()) - Public Iterator Function GetEnumerator() As IEnumerator(Of Object()) Implements IEnumerable(Of Object()).GetEnumerator + Public Iterator Function GetEnumerator() As IEnumerator(Of Object()) _ + Implements IEnumerable(Of Object()).GetEnumerator + Yield {New DualTimeZones(TimeZone.GMT)} Yield {New DualTimeZones(TimeZone.Local)} End Function diff --git a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/VbFileCleanupTestBase.vb b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/VbFileCleanupTestBase.vb index 18bc3f06182..68dabaf0c53 100644 --- a/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/VbFileCleanupTestBase.vb +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/VbFileCleanupTestBase.vb @@ -9,7 +9,9 @@ Namespace Microsoft.VisualBasic.Forms.Tests Public MustInherit Class VbFileCleanupTestBase Implements IDisposable - Private Shared ReadOnly s_baseTempPath As String = Path.Combine(Path.GetTempPath, "DownLoadTest9d9e3a8-7a46-4333-a0eb-4faf76994801") + Private Shared ReadOnly s_baseTempPath As String = Path.Combine( + Path.GetTempPath, + "DownLoadTest9d9e3a8-7a46-4333-a0eb-4faf76994801") Friend Const DefaultFileName As String = "Testing.Txt" Friend ReadOnly _testDirectories As New HashSet(Of String) @@ -17,7 +19,9 @@ Namespace Microsoft.VisualBasic.Forms.Tests Dispose(disposing:=False) End Sub - ' The base path is system temp directory / a guaranteed unique directory based on a GUID / a temp directory based on TestName + ' The base path is the system temp directory / + ' a guaranteed unique directory based on a GUID / + ' a temp directory based on TestName Friend Shared ReadOnly Property BaseTempPath As String Get Return s_baseTempPath @@ -36,16 +40,23 @@ Namespace Microsoft.VisualBasic.Forms.Tests End Sub ''' - ''' If size >= 0 then create the file with size length. + ''' If size is not FileSize.Unknown then create the file with size length. ''' ''' Full path to working directory. ''' - ''' Size in bytes of the file to be created. + ''' FileSize of the file to be created. ''' ''' The full path and file name of the created file. - ''' If size = -1 no file is create but the full path is returned. + ''' If size = FileSize.Unknown no file is create but the full path is returned. ''' - Friend Shared Function CreateTempFile(sourceDirectoryName As String, Optional filename As String = DefaultFileName, Optional size As Integer = -1) As String + Friend Shared Function CreateTempFile( + sourceDirectoryName As String, + Optional filename As String = DefaultFileName, + Optional size As FileSizes = FileSizes.Unknown) As String + + If filename = DefaultFileName AndAlso size <> FileSizes.Unknown Then + filename = $"{[Enum].GetName(size).Replace("FileSize", "")}.zip" + End If Dim filenameWithPath As String = Path.Combine(sourceDirectoryName, filename) If size >= 0 Then @@ -93,7 +104,10 @@ Namespace Microsoft.VisualBasic.Forms.Tests ''' ''' If >0 use line number as part of name. ''' The name of a directory that is safe to write to and is verified to exist. - Friend Function CreateTempDirectory( Optional memberName As String = Nothing, Optional lineNumber As Integer = -1) As String + Friend Function CreateTempDirectory( + Optional memberName As String = Nothing, + Optional lineNumber As Integer = -1) As String + Dim folder As String If lineNumber > 0 Then folder = Path.Combine(BaseTempPath, $"{memberName}{lineNumber}") 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..0ac369608fd --- /dev/null +++ b/src/Microsoft.VisualBasic.Forms/tests/UnitTests/System/Windows/TestUtilities/WebListener.vb @@ -0,0 +1,304 @@ +' 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 + Inherits ServerConfiguration + Private Const BufferSize As Integer = 4096 + Private ReadOnly _address As String + Private ReadOnly _fileName As String + Private ReadOnly _fileSize As Integer + Private ReadOnly _fileUrlPrefix As String + Private ReadOnly _localServer As Boolean + Private ReadOnly _serverConfigurationInstance As ServerConfiguration + Private ReadOnly _serverPassword As String + Private ReadOnly _serverUserName As String + Private ReadOnly _upload As Boolean + + ''' + ''' The name of the function that creates the server is used 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 supportAnonymousLogin As Boolean = True, Optional memberName As String = Nothing) + Debug.Assert(fileSize > 0) + _fileName = $"{[Enum].GetName(GetType(FileSizes), fileSize)}.zip".Replace("FileSize", "") + _fileSize = fileSize + _serverConfigurationInstance = ServerConfigurationLoad() + _fileUrlPrefix = _serverConfigurationInstance.GetFileUrlPrefix(_upload) + _localServer = _fileUrlPrefix.Contains("8080") + _upload = memberName.Contains("Upload", StringComparison.InvariantCultureIgnoreCase) + If _localServer Then + ServerAcceptsAnonymousLogin = supportAnonymousLogin + Else + ServerAcceptsAnonymousLogin = _serverConfigurationInstance.GetAcceptsAnonymousLogin(_upload) + End If + ServerThrowsPasswordErrors = _serverConfigurationInstance.GetThrowsPasswordErrors(_upload) + _address = $"{_serverConfigurationInstance.GetFileUrlPrefix(_upload)}{_fileName}" + 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, + serverUserName As String, + serverPassword As String, + Optional supportAnonymousLogin As Boolean = True, + Optional memberName As String = Nothing) + + Me.New(fileSize, supportAnonymousLogin, memberName) + + If _localServer Then + _serverPassword = serverPassword + _serverUserName = serverUserName + Else + If serverPassword = DefaultPassword Then + _serverPassword = _serverConfigurationInstance.GetDefaultPassword(_upload) + Else + _serverPassword = serverPassword + End If + If serverUserName = DefaultUserName Then + _serverUserName = _serverConfigurationInstance.GetDefaultUserName(_upload) + Else + _serverUserName = serverUserName + End If + End If + End Sub + + Public ReadOnly Property Address As String + Get + Return _address + End Get + End Property + + ''' + ''' This server will save a when something in the stream doesn't + ''' match what is expected. These will never be visible to the user. + ''' + ''' A with a description of the issue or + Public Property FaultMessage As String + + Public ReadOnly Property FileSize As Long + Get + Return _fileSize + End Get + End Property + + Public Property ServerAcceptsAnonymousLogin As Boolean = True + + Public ReadOnly Property ServerPassword As String + Get + Return _serverPassword + End Get + End Property + + ''' + ''' Some File servers do not return errors on mismatched passwords so we need to + ''' ignore tests that expect errors. + ''' + ''' + Public Property ServerThrowsPasswordErrors As Boolean = True + + Public ReadOnly Property ServerUserName As String + Get + Return _serverUserName + End Get + End Property + + Private Shared Function GetBoundary(contentType As String) As String + Dim elements As String() = contentType.Split(New Char() {";"c}, StringSplitOptions.RemoveEmptyEntries) + Dim element As String = elements.FirstOrDefault(Function(e) e.Trim().StartsWith("boundary=", StringComparison.OrdinalIgnoreCase)) + Return If(element IsNot Nothing, element.Substring(startIndex:=element.IndexOf("="c) + 1).Trim().Trim(""""c), String.Empty) + End Function + + Private Shared Function GetContentDispositionHeader( + lines As List(Of String), + ByRef headerParts() As String) As Integer + For dispositionIndex As Integer = 0 To lines.Count - 1 + Dim line As String = lines(dispositionIndex) + If line.Contains("Content-Disposition", StringComparison.InvariantCultureIgnoreCase) Then + headerParts = line.Split({":"c}, count:=2) + Dim result As Boolean = headerParts.Length = 2 _ + AndAlso headerParts(0).Trim().Equals(value:="Content-Disposition", + comparisonType:=StringComparison.OrdinalIgnoreCase) + Return dispositionIndex + End If + Next + Return -1 + End Function + + Private Shared Function GetDataLength(lines As List(Of String), dispositionIndex As Integer) As Integer + For Each line As String In lines + If line.Substring(0, 1) = vbNullChar Then + Return line.Length + End If + Next + Return 0 + End Function + + Private Shared Function GetFilename(headerParts() As String) As String + Dim value As String = "" + Dim line As String = headerParts(1) + Dim startIndex As Integer = line.IndexOf("filename=""", StringComparison.InvariantCultureIgnoreCase) + If startIndex > -1 Then + line = line.Substring(startIndex + 10) + Dim length As Integer = line.IndexOf(""""c) + value = line.Substring(0, length) + End If + + Return value + End Function + + Friend Function ProcessRequests() As HttpListener + ' Create a listener and add the prefixes. + Dim listener As New HttpListener() + + If _fileUrlPrefix.Contains("8080") Then + + listener.Prefixes.Add(_fileUrlPrefix) + If Not ServerAcceptsAnonymousLogin _ + OrElse _serverUserName IsNot Nothing _ + OrElse _serverPassword 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 <> _serverUserName _ + OrElse String.IsNullOrWhiteSpace(identity.Password) _ + OrElse identity.Password <> _serverPassword Then + + response.StatusCode = HttpStatusCode.Unauthorized + Exit Try + End If + End If + ' Simulate network traffic + Thread.Sleep(millisecondsTimeout:=20) + If _upload Then + Dim request As HttpListenerRequest = context.Request + If request.HttpMethod.Equals("Post", StringComparison.OrdinalIgnoreCase) _ + AndAlso request.HasEntityBody Then + + Dim formData As Dictionary(Of String, String) = GetMultipartFormData(request) + + Using bodyStream As Stream = request.InputStream + Using reader As New StreamReader( + stream:=bodyStream, + encoding:=request.ContentEncoding, + detectEncodingFromByteOrderMarks:=True, + BufferSize) + End Using + End Using + Try + Dim dataLength As String = formData(NameOf(dataLength)) + If _fileSize.ToString <> dataLength Then + FaultMessage = $"File size mismatch, expected {_fileSize} actual {dataLength}" + Else + Dim fileName As String = formData("filename") + If Not fileName.Equals(_fileName, StringComparison.OrdinalIgnoreCase) Then + FaultMessage = $"Filename incorrect, expected '{_fileName}', actual {fileName}" + End If + End If + Catch ex As Exception + ' Ignore is case upload is cancelled + End Try + End If + response.StatusCode = 200 + Else + 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 + Try + output.Write(buffer, offset:=0, count:=buffer.Length) + Catch ex As Exception + ' ignore it will be handled elsewhere + End Try + End Using + End If + Finally + Try + response?.Close() + Catch ex As Exception + + End Try + response = Nothing + End Try + End Sub + + Task.Run(action) + End If + Return listener + End Function + + ''' + ''' Parses a and gets the fileName of the uploaded file + ''' and the lenght of the data file in bytes + ''' + ''' + ''' + ''' A that contains the filename and lenght of the data file. + ''' + Public Function GetMultipartFormData(request As HttpListenerRequest) As Dictionary(Of String, String) + Dim result As New Dictionary(Of String, String) + + If request.ContentType.StartsWith("multipart/form-data", StringComparison.OrdinalIgnoreCase) Then + Dim boundary As String = GetBoundary(request.ContentType) + Using reader As New StreamReader(request.InputStream, request.ContentEncoding) + Try + Dim content As String = reader.ReadToEnd() + Dim parts As String() = content.Split(boundary, StringSplitOptions.RemoveEmptyEntries) + + For Each part As String In parts + If part.Trim() <> "--" Then + Dim separator As String() = New String() {Environment.NewLine} + Dim lines As List(Of String) = part.Split(separator, StringSplitOptions.RemoveEmptyEntries).ToList + If lines.Count > 2 Then + Dim headerParts As String() = Nothing + Dim dispositionIndex As Integer = GetContentDispositionHeader(lines, headerParts) + + If dispositionIndex > -1 Then + result.Add("filename", GetFilename(headerParts)) + If lines.Count > dispositionIndex + 1 Then + result.Add("dataLength", GetDataLength(lines, dispositionIndex).ToString) + End If + Exit For + End If + End If + End If + Next + Catch ex As Exception + FaultMessage = "MultipartFormData format Error" + End Try + End Using + End If + + Return result + 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 ae2854277ae..a7141e712c2 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.Drawing.Common/src/System/Drawing/Imaging/ColorMatrix.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/ColorMatrix.cs index 599d3ff0d16..aa5a4e1cb49 100644 --- a/src/System.Drawing.Common/src/System/Drawing/Imaging/ColorMatrix.cs +++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/ColorMatrix.cs @@ -299,7 +299,6 @@ public float Matrix44 /// /// Initializes a new instance of the class with the elements in the specified matrix. /// - [CLSCompliant(false)] public ColorMatrix(float[][] newColorMatrix) { _matrix00 = newColorMatrix[0][0]; diff --git a/src/System.Drawing.Common/src/System/Drawing/Imaging/ImageCodecInfo.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/ImageCodecInfo.cs index 9fbeea3d0d0..6d68eb6b623 100644 --- a/src/System.Drawing.Common/src/System/Drawing/Imaging/ImageCodecInfo.cs +++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/ImageCodecInfo.cs @@ -28,10 +28,8 @@ internal ImageCodecInfo() public int Version { get; set; } - [CLSCompliant(false)] public byte[][]? SignaturePatterns { get; set; } - [CLSCompliant(false)] public byte[][]? SignatureMasks { get; set; } // Encoder/Decoder selection APIs diff --git a/src/System.Windows.Forms.Analyzers.VisualBasic/src/Analyzers/AvoidPassingTaskWithoutCancellationToken/AvoidPassingTaskWithoutCancellationTokenAnalyzer.vb b/src/System.Windows.Forms.Analyzers.VisualBasic/src/Analyzers/AvoidPassingTaskWithoutCancellationToken/AvoidPassingTaskWithoutCancellationTokenAnalyzer.vb index ff6a30f001e..6a498c4ab87 100644 --- a/src/System.Windows.Forms.Analyzers.VisualBasic/src/Analyzers/AvoidPassingTaskWithoutCancellationToken/AvoidPassingTaskWithoutCancellationTokenAnalyzer.vb +++ b/src/System.Windows.Forms.Analyzers.VisualBasic/src/Analyzers/AvoidPassingTaskWithoutCancellationToken/AvoidPassingTaskWithoutCancellationTokenAnalyzer.vb @@ -39,7 +39,9 @@ Namespace Global.System.Windows.Forms.VisualBasic.Analyzers.AvoidPassingTaskWith Dim memberAccessExpr = DirectCast(invocationExpr.Expression, MemberAccessExpressionSyntax) Dim methodSymbol = TryCast(context.SemanticModel.GetSymbolInfo(memberAccessExpr).Symbol, IMethodSymbol) - If methodSymbol Is Nothing OrElse methodSymbol.Name <> InvokeAsyncString OrElse methodSymbol.Parameters.Length <> 2 Then + If methodSymbol Is Nothing OrElse methodSymbol.Name <> InvokeAsyncString OrElse + methodSymbol.Parameters.Length <> 2 Then + Return End If @@ -78,7 +80,9 @@ Namespace Global.System.Windows.Forms.VisualBasic.Analyzers.AvoidPassingTaskWith If funcType.DelegateInvokeMethod?.ReturnType IsNot Nothing Then Dim returnType = TryCast(funcType.DelegateInvokeMethod.ReturnType, INamedTypeSymbol) - If returnType IsNot Nothing AndAlso (returnType.Name = TaskString OrElse returnType.Name = ValueTaskString) Then + If returnType IsNot Nothing AndAlso (returnType.Name = TaskString OrElse + returnType.Name = ValueTaskString) Then + Dim diagnostic As Diagnostic = Diagnostic.Create( s_avoidFuncReturningTaskWithoutCancellationToken, invocationExpr.GetLocation()) 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.Analyzers.VisualBasic/tests/UnitTests/System.Windows.Forms.Analyzers.VisualBasic.Tests/AvoidPassingTaskWithoutCancellationTokenTest.vb b/src/System.Windows.Forms.Analyzers.VisualBasic/tests/UnitTests/System.Windows.Forms.Analyzers.VisualBasic.Tests/AvoidPassingTaskWithoutCancellationTokenTest.vb index e9cb92e94bc..04ba6bec6c0 100644 --- a/src/System.Windows.Forms.Analyzers.VisualBasic/tests/UnitTests/System.Windows.Forms.Analyzers.VisualBasic.Tests/AvoidPassingTaskWithoutCancellationTokenTest.vb +++ b/src/System.Windows.Forms.Analyzers.VisualBasic/tests/UnitTests/System.Windows.Forms.Analyzers.VisualBasic.Tests/AvoidPassingTaskWithoutCancellationTokenTest.vb @@ -93,13 +93,13 @@ Namespace VisualBasicControls Dim okFunc As New Func(Of Integer)(Function() 42) ' Just a Task we will get in trouble since it's handled as a fire and forget. - Dim notOkAsyncFunc As New Func(Of Task)(Function() + Dim notOkAsyncFunc As New Func(Of Task)(Function() control.Text = ""Hello, World!"" Return Task.CompletedTask End Function) ' A Task returning a value will also get us in trouble since it's handled as a fire and forget. - Dim notOkAsyncFunc2 As New Func(Of Task(Of Integer))(Function() + Dim notOkAsyncFunc2 As New Func(Of Task(Of Integer))(Function() control.Text = ""Hello, World!"" Return Task.FromResult(42) End Function) @@ -120,13 +120,13 @@ Namespace VisualBasicControls Dim task5 = control.InvokeAsync(notOkAsyncFunc2, System.Threading.CancellationToken.None) ' This is OK, since we're passing a cancellation token. - Dim okAsyncFunc = New Func(Of CancellationToken, ValueTask)(Function(cancellation) + Dim okAsyncFunc = New Func(Of CancellationToken, ValueTask)(Function(cancellation) control.Text = ""Hello, World!"" Return ValueTask.CompletedTask End Function) ' This is also OK, again, because we're passing a cancellation token. - Dim okAsyncFunc2 = New Func(Of CancellationToken, ValueTask(Of Integer))(Function(cancellation) + Dim okAsyncFunc2 = New Func(Of CancellationToken, ValueTask(Of Integer))(Function(cancellation) control.Text = ""Hello, World!"" Return ValueTask.FromResult(42) End Function) @@ -151,25 +151,39 @@ End Namespace - Public Async Function VB_AvoidPassingFuncReturningTaskWithoutCancellationAnalyzer(referenceAssemblies As ReferenceAssemblies) As Task + Public Async Function VB_AvoidPassingFuncReturningTaskWithoutCancellationAnalyzer( + referenceAssemblies As ReferenceAssemblies) As Task ' If the API does not exist, we need to add it to the test. Dim customControlSource As String = AsyncControl Dim diagnosticId As String = DiagnosticIDs.AvoidPassingFuncReturningTaskWithoutCancellationToken - Dim context As New VisualBasicAnalyzerTest(Of AvoidPassingTaskWithoutCancellationTokenAnalyzer, DefaultVerifier) With - { - .TestCode = TestCode, - .ReferenceAssemblies = referenceAssemblies - } + Dim context As New VisualBasicAnalyzerTest(Of AvoidPassingTaskWithoutCancellationTokenAnalyzer, DefaultVerifier) _ + With + { + .TestCode = TestCode, + .ReferenceAssemblies = referenceAssemblies + } context.TestState.OutputKind = OutputKind.WindowsApplication context.TestState.Sources.Add(customControlSource) context.TestState.ExpectedDiagnostics.AddRange( - { - DiagnosticResult.CompilerWarning(diagnosticId).WithSpan(40, 25, 40, 101), - DiagnosticResult.CompilerWarning(diagnosticId).WithSpan(43, 25, 43, 101), - DiagnosticResult.CompilerWarning(diagnosticId).WithSpan(46, 25, 46, 102) - }) + collection:={ + DiagnosticResult.CompilerWarning(diagnosticId).WithSpan( + startLine:=40, + startColumn:=25, + endLine:=40, + endColumn:=101), + DiagnosticResult.CompilerWarning(diagnosticId).WithSpan( + startLine:=43, + startColumn:=25, + endLine:=43, + endColumn:=101), + DiagnosticResult.CompilerWarning(diagnosticId).WithSpan( + startLine:=46, + startColumn:=25, + endLine:=46, + endColumn:=102) + }) Await context.RunAsync().ConfigureAwait(continueOnCapturedContext:=True) End Function diff --git a/src/System.Windows.Forms.Analyzers.VisualBasic/tests/UnitTests/System.Windows.Forms.Analyzers.VisualBasic.Tests/MissingPropertySerializationConfigurationAnalyzerTest.vb b/src/System.Windows.Forms.Analyzers.VisualBasic/tests/UnitTests/System.Windows.Forms.Analyzers.VisualBasic.Tests/MissingPropertySerializationConfigurationAnalyzerTest.vb index 8085ff56bff..fcbde236943 100644 --- a/src/System.Windows.Forms.Analyzers.VisualBasic/tests/UnitTests/System.Windows.Forms.Analyzers.VisualBasic.Tests/MissingPropertySerializationConfigurationAnalyzerTest.vb +++ b/src/System.Windows.Forms.Analyzers.VisualBasic/tests/UnitTests/System.Windows.Forms.Analyzers.VisualBasic.Tests/MissingPropertySerializationConfigurationAnalyzerTest.vb @@ -162,7 +162,9 @@ End Namespace - Public Async Function VB_MissingControlPropertySerializationConfigurationAnalyzer(referenceAssemblies As ReferenceAssemblies) As Task + Public Async Function VB_MissingControlPropertySerializationConfigurationAnalyzer( + referenceAssemblies As ReferenceAssemblies) As Task + Dim context = New VisualBasicAnalyzerTest(Of MissingPropertySerializationConfigurationAnalyzer, DefaultVerifier) With @@ -178,7 +180,9 @@ End Namespace - Public Async Function VB_ControlPropertySerializationConfigurationAnalyzer(referenceAssemblies As ReferenceAssemblies) As Task + Public Async Function VB_ControlPropertySerializationConfigurationAnalyzer( + referenceAssemblies As ReferenceAssemblies) As Task + Dim context = New VisualBasicAnalyzerTest(Of MissingPropertySerializationConfigurationAnalyzer, DefaultVerifier) With 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/Drawing/Design/BitmapEditor.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/BitmapEditor.cs index bc635b861a8..49458c97ef4 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/BitmapEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/BitmapEditor.cs @@ -7,7 +7,6 @@ namespace System.Drawing.Design; /// Provides an editor that can perform default file searching for bitmap (.bmp) /// files. /// -[CLSCompliant(false)] public class BitmapEditor : ImageEditor { protected static List BitmapExtensions = ["bmp", "gif", "jpg", "jpeg", "png", "ico"]; diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ColorEditor.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ColorEditor.cs index a6de6e142a2..6741c91e659 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ColorEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ColorEditor.cs @@ -10,7 +10,6 @@ namespace System.Drawing.Design; /// /// Provides an editor for visually picking a color. /// -[CLSCompliant(false)] public partial class ColorEditor : UITypeEditor { /// diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/CursorEditor.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/CursorEditor.cs index b3a5937aba9..a531476cd0f 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/CursorEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/CursorEditor.cs @@ -9,7 +9,6 @@ namespace System.Drawing.Design; /// /// Provides an editor that can perform default file searching for cursor (.cur) files. /// -[CLSCompliant(false)] public partial class CursorEditor : UITypeEditor { private CursorUI? _cursorUI; diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/FontEditor.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/FontEditor.cs index 9f9ba551aef..4bd3e80f730 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/FontEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/FontEditor.cs @@ -10,7 +10,6 @@ namespace System.Drawing.Design; /// /// Provides a font editor that is used to visually select and configure a Font object. /// -[CLSCompliant(false)] public class FontEditor : UITypeEditor { private FontDialog? _fontDialog; diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ImageEditor.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ImageEditor.cs index 43e59295904..8cae46caa92 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ImageEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ImageEditor.cs @@ -12,7 +12,6 @@ namespace System.Drawing.Design; /// /// Provides an editor for visually picking an image. /// -[CLSCompliant(false)] public class ImageEditor : UITypeEditor { private static readonly Type[] s_imageExtenders = [typeof(BitmapEditor), typeof(MetafileEditor)]; diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/MetafileEditor.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/MetafileEditor.cs index a789af8f4fa..a28e719e723 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/MetafileEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/MetafileEditor.cs @@ -8,7 +8,6 @@ namespace System.Drawing.Design; /// /// Extends Image's editor class to provide default file searching for metafile (.emf) files. /// -[CLSCompliant(false)] public class MetafileEditor : ImageEditor { protected override string GetFileDialogDescription() => SR.metafileFileDescription; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/AnchorEditor.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/AnchorEditor.cs index 566452fcc52..204c3bf3f98 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/AnchorEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/AnchorEditor.cs @@ -9,7 +9,6 @@ namespace System.Windows.Forms.Design; /// /// Provides a design-time editor for specifying the property. /// -[CLSCompliant(false)] public sealed partial class AnchorEditor : UITypeEditor { private AnchorUI? _anchorUI; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BorderSidesEditor.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BorderSidesEditor.cs index 86601d714f9..803bcbe564c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BorderSidesEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BorderSidesEditor.cs @@ -9,7 +9,6 @@ namespace System.Windows.Forms.Design; /// /// Provides an editor for setting the ToolStripStatusLabel BorderSides property.. /// -[CLSCompliant(false)] public partial class BorderSidesEditor : UITypeEditor { private BorderSidesEditorUI? _borderSidesEditorUI; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentDocumentDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentDocumentDesigner.cs index 0631fe61f41..0d2d86e5411 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentDocumentDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentDocumentDesigner.cs @@ -123,7 +123,6 @@ protected override void Dispose(bool disposing) /// Gets a value indicating whether the specified tool is supported by this /// designer. /// - [CLSCompliant(false)] protected virtual bool GetToolSupported(ToolboxItem tool) { throw new NotImplementedException(SR.NotImplementedByDesign); 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..f709f3b7139 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 @@ -745,7 +745,6 @@ public virtual void AddComponent(IComponent component) } } - [CLSCompliant(false)] protected virtual bool CanCreateComponentFromTool(ToolboxItem tool) { IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); @@ -813,7 +812,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.Design/src/System/Windows/Forms/Design/DockEditor.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DockEditor.cs index d2556254817..d8222031614 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DockEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DockEditor.cs @@ -9,7 +9,6 @@ namespace System.Windows.Forms.Design; /// /// Implements the design time editor for specifying the property. /// -[CLSCompliant(false)] public sealed partial class DockEditor : UITypeEditor { private DockUI? _dockUI; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FileNameEditor.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FileNameEditor.cs index f22eaec150c..7ed6ecfd513 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FileNameEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FileNameEditor.cs @@ -9,7 +9,6 @@ namespace System.Windows.Forms.Design; /// /// Provides an editor for filenames. /// -[CLSCompliant(false)] public class FileNameEditor : UITypeEditor { private OpenFileDialog? _openFileDialog; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FolderNameEditor.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FolderNameEditor.cs index 49c1d937950..77dc10325a5 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FolderNameEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FolderNameEditor.cs @@ -9,7 +9,6 @@ namespace System.Windows.Forms.Design; /// /// Provides an editor for choosing a folder from the filesystem. /// -[CLSCompliant(false)] public partial class FolderNameEditor : UITypeEditor { private FolderBrowser? _folderBrowser; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageListImageEditor.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageListImageEditor.cs index 26abab9a586..23e21ebbcfc 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageListImageEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageListImageEditor.cs @@ -11,7 +11,6 @@ namespace System.Windows.Forms.Design; /// /// Provides an editor that can perform default file searching for bitmap (.bmp) files. /// -[CLSCompliant(false)] public class ImageListImageEditor : ImageEditor { // Metafile types are not supported in the ImageListImageEditor and should not be displayed as an option. diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs index 1e168abf271..d9e18359aeb 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs @@ -280,7 +280,6 @@ protected Size GridSize /// This property is used by deriving classes to determine if the designer is /// in a state where it has a valid MouseDragTool. /// - [CLSCompliant(false)] protected ToolboxItem MouseDragTool => _mouseDragTool; /// @@ -796,7 +795,6 @@ protected void CreateTool(ToolboxItem tool) /// Creates the given tool in the currently selected control at the /// given position. The default size for the tool is used. /// - [CLSCompliant(false)] protected void CreateTool(ToolboxItem tool, Point location) { CreateToolCore(tool, location.X, location.Y, 0, 0, true, false); @@ -806,7 +804,6 @@ protected void CreateTool(ToolboxItem tool, Point location) /// Creates the given tool in the currently selected control. The /// tool is created with the provided shape. /// - [CLSCompliant(false)] protected void CreateTool(ToolboxItem tool, Rectangle bounds) { CreateToolCore(tool, bounds.X, bounds.Y, bounds.Width, bounds.Height, true, true); @@ -816,7 +813,6 @@ protected void CreateTool(ToolboxItem tool, Rectangle bounds) /// This is the worker method of all CreateTool methods. It is the only one /// that can be overridden. /// - [CLSCompliant(false)] protected virtual IComponent[] CreateToolCore(ToolboxItem tool, int x, int y, int width, int height, bool hasLocation, bool hasSize) { IComponent[] comp = null; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs index c8651883043..83dc2d5072f 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs @@ -10,7 +10,6 @@ namespace System.Windows.Forms.Design; /// /// Provides an editor for picking shortcut keys. /// -[CLSCompliant(false)] public partial class ShortcutKeysEditor : UITypeEditor { private ShortcutKeysUI? _shortcutKeysUI; 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 027b42e8757..014ad11710e 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