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 is unauthorized.
+
+