Skip to content

Commit

Permalink
use HttpClient to replace WebClient
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperk81 committed Jun 17, 2024
1 parent 8cbf7ea commit 40eed0d
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ internal static partial class LocalAppContextSwitches
private const string ScaleTopLevelFormMinMaxSizeForDpiSwitchName = "System.Windows.Forms.ScaleTopLevelFormMinMaxSizeForDpi";
internal const string AnchorLayoutV2SwitchName = "System.Windows.Forms.AnchorLayoutV2";
internal const string ApplyParentFontToMenusSwitchName = "System.Windows.Forms.ApplyParentFontToMenus";
internal const string ServicePointManagerCheckCrlSwitchName = "System.Windows.Forms.ServicePointManagerCheckCrl";
internal const string TrackBarModernRenderingSwitchName = "System.Windows.Forms.TrackBarModernRendering";
private const string DoNotCatchUnhandledExceptionsSwitchName = "System.Windows.Forms.DoNotCatchUnhandledExceptions";
internal const string DataGridViewUIAStartRowCountAtZeroSwitchName = "System.Windows.Forms.DataGridViewUIAStartRowCountAtZero";
Expand All @@ -29,7 +28,6 @@ internal static partial class LocalAppContextSwitches
private static int s_scaleTopLevelFormMinMaxSizeForDpi;
private static int s_anchorLayoutV2;
private static int s_applyParentFontToMenus;
private static int s_servicePointManagerCheckCrl;
private static int s_trackBarModernRendering;
private static int s_doNotCatchUnhandledExceptions;
private static int s_dataGridViewUIAStartRowCountAtZero;
Expand Down Expand Up @@ -124,11 +122,6 @@ static bool GetSwitchDefaultValue(string switchName)
{
return true;
}

if (switchName == ServicePointManagerCheckCrlSwitchName)
{
return true;
}
}

return false;
Expand Down Expand Up @@ -171,17 +164,6 @@ public static bool TrackBarModernRendering
get => GetCachedSwitchValue(TrackBarModernRenderingSwitchName, ref s_trackBarModernRendering);
}

/// <summary>
/// Indicates whether certificates are checked against the certificate authority revocation list.
/// If true, revoked certificates will not be accepted by WebRequests and WebClients as valid.
/// Otherwise, revoked certificates will be accepted as valid.
/// </summary>
public static bool ServicePointManagerCheckCrl
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => GetCachedSwitchValue(ServicePointManagerCheckCrlSwitchName, ref s_servicePointManagerCheckCrl);
}

public static bool DataGridViewUIAStartRowCountAtZero
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ private void ResetLocalSwitches(dynamic testAccessor)
testAccessor.s_anchorLayoutV2 = 0;
testAccessor.s_scaleTopLevelFormMinMaxSizeForDpi = 0;
testAccessor.s_trackBarModernRendering = 0;
testAccessor.s_servicePointManagerCheckCrl = 0;
}

[WinFormsTheory]
Expand All @@ -32,7 +31,6 @@ public void Validate_Default_Switch_Values(string targetFrameworkName, bool expe

Assert.Equal(expected, LocalAppContextSwitches.TrackBarModernRendering);
Assert.Equal(expected, LocalAppContextSwitches.ScaleTopLevelFormMinMaxSizeForDpi);
Assert.Equal(expected, LocalAppContextSwitches.ServicePointManagerCheckCrl);
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms.Layout;
using System.Windows.Forms.Primitives;

namespace System.Windows.Forms;

Expand Down Expand Up @@ -62,6 +61,7 @@ public partial class PictureBox : Control, ISupportInitialize
private SendOrPostCallback? _loadProgressDelegate;
private bool _handleValid;
private readonly object _internalSyncObject = new();
private readonly HttpClient _httpClient = new();

// These default images will be demand loaded.
private Image? _defaultInitialImage;
Expand Down Expand Up @@ -464,23 +464,29 @@ public void Load()
try
{
DisposeImageStream();
if (UseWebRequest())
Uri uri = CalculateUri(_imageLocation);
if (uri.IsFile)
{
LoadImageViaWebClient();
_localImageStreamReader = new StreamReader(uri.LocalPath);
Image img = Image.FromStream(_localImageStreamReader.BaseStream);
InstallNewImage(img, ImageInstallationType.FromUrl);
}
else
else if (UseWebRequest())
{
Uri uri = CalculateUri(_imageLocation);
if (uri.IsFile)
Task.Run(async () =>
{
_localImageStreamReader = new StreamReader(uri.LocalPath);
Image img = Image.FromStream(_localImageStreamReader.BaseStream);
HttpResponseMessage response = await _httpClient.GetAsync(uri).ConfigureAwait(false);
response.EnsureSuccessStatusCode();

using Stream stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
_uriImageStream = stream;
Image img = Image.FromStream(_uriImageStream);
InstallNewImage(img, ImageInstallationType.FromUrl);
}
else
{
throw new NotSupportedException(SR.PictureBoxRemoteLocationNotSupported);
}
}).GetAwaiter().GetResult();
}
else
{
throw new NotSupportedException(SR.PictureBoxRemoteLocationNotSupported);
}
}
catch
Expand All @@ -497,32 +503,6 @@ public void Load()
}
}

private void LoadImageViaWebClient()
{
Image img;
Uri uri = CalculateUri(_imageLocation!);
if (uri.IsFile)
{
_localImageStreamReader = new StreamReader(uri.LocalPath);
img = Image.FromStream(_localImageStreamReader.BaseStream);
}
else
{
if (LocalAppContextSwitches.ServicePointManagerCheckCrl)
{
ServicePointManager.CheckCertificateRevocationList = true;
}

#pragma warning disable SYSLIB0014 // Type or member is obsolete
using WebClient webClient = new(); // lgtm[cs/webrequest-checkcertrevlist-disabled] - Having ServicePointManager.CheckCertificateRevocationList set to true has a slim chance of resulting in failure. We have an opt-out for this rare event.
#pragma warning restore SYSLIB0014 // Type or member is obsolete
_uriImageStream = webClient.OpenRead(uri.ToString());
img = Image.FromStream(_uriImageStream);
}

InstallNewImage(img, ImageInstallationType.FromUrl);
}

[SRCategory(nameof(SR.CatAsynchronous))]
[SRDescription(nameof(SR.PictureBoxLoad1Descr))]
public void Load(string url)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -732,17 +732,13 @@ public void PictureBox_ImageLocation_SetValidWithWaitOnLoadTrueLocal_GetReturnsE
Assert.Equal(PathImageLocation, pictureBox.ImageLocation);
}

[WinFormsTheory]
[BoolData]
public void PictureBox_ImageLocation_SetValidWithWaitOnLoadTrueUri_ConfigSwitch_CheckCRL_GetReturnsExpected(bool switchValue)
[WinFormsFact]
public void PictureBox_ImageLocation_SetValidWithWaitOnLoadTrueUri_ConfigSwitch_CheckCRL_GetReturnsExpected()
{
dynamic testAccessor = typeof(LocalAppContextSwitches).TestAccessor().Dynamic;

try
{
AppContext.SetSwitch(LocalAppContextSwitches.ServicePointManagerCheckCrlSwitchName, switchValue);
Assert.Equal(switchValue, LocalAppContextSwitches.ServicePointManagerCheckCrl);

using PictureBox pictureBox = new()
{
WaitOnLoad = true
Expand All @@ -763,10 +759,6 @@ public void PictureBox_ImageLocation_SetValidWithWaitOnLoadTrueUri_ConfigSwitch_
{
// Swallow network errors.
}
finally
{
testAccessor.s_servicePointManagerCheckCrl = 0;
}
}

[WinFormsTheory]
Expand Down Expand Up @@ -2002,17 +1994,13 @@ public void PictureBox_Load_UrlValidWithWaitOnLoadTrueLocal_GetReturnsExpected()
Assert.Equal(new Size(110, 100), pictureBox.Image.Size);
}

[WinFormsTheory]
[BoolData]
public void PictureBox_Load_UrlValidWithWaitOnLoadTrueUri_ConfigSwitch_CheckCRL_GetReturnsExpected(bool switchValue)
[WinFormsFact]
public void PictureBox_Load_UrlValidWithWaitOnLoadTrueUri_ConfigSwitch_CheckCRL_GetReturnsExpected()
{
dynamic testAccessor = typeof(LocalAppContextSwitches).TestAccessor().Dynamic;

try
{
AppContext.SetSwitch(LocalAppContextSwitches.ServicePointManagerCheckCrlSwitchName, switchValue);
Assert.Equal(switchValue, LocalAppContextSwitches.ServicePointManagerCheckCrl);

using PictureBox pictureBox = new()
{
WaitOnLoad = true
Expand All @@ -2033,10 +2021,6 @@ public void PictureBox_Load_UrlValidWithWaitOnLoadTrueUri_ConfigSwitch_CheckCRL_
{
// Swallow network errors.
}
finally
{
testAccessor.s_servicePointManagerCheckCrl = 0;
}
}

[WinFormsTheory]
Expand Down

0 comments on commit 40eed0d

Please sign in to comment.