From e143921e4b2f7a7fc682f3f2777b0569913c5687 Mon Sep 17 00:00:00 2001 From: onkrot Date: Fri, 23 Feb 2024 15:58:50 +0500 Subject: [PATCH] Update `MS.Internal.IO.Packaging` classes --- .../IO/Packaging/ByteRangeDownloader.cs | 97 ++++++++----------- .../IO/Packaging/DeobfuscatingStream.cs | 13 +-- .../MS/internal/IO/Packaging/NetStream.cs | 90 ++++++++--------- .../IO/Packaging/PreloadedPackages.cs | 42 ++------ .../internal/IO/Packaging/PseudoWebRequest.cs | 23 ++--- .../internal/IO/Packaging/ResponseStream.cs | 10 +- 6 files changed, 106 insertions(+), 169 deletions(-) diff --git a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/ByteRangeDownloader.cs b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/ByteRangeDownloader.cs index 84c29a0af85..6ef8954e85d 100644 --- a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/ByteRangeDownloader.cs +++ b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/ByteRangeDownloader.cs @@ -13,16 +13,14 @@ // web requests other than through WININET using System; -using System.Collections; +using System.Collections.Generic; using System.ComponentModel; // For Win32Exception using System.Diagnostics; using System.Globalization; using System.IO; -using System.IO.IsolatedStorage; // For IsolatedStorage temp file using System.Net; -using System.Net.Cache; // For RequestCachePolicy -using System.Runtime.InteropServices; // For Marshal -using System.Security; // SecurityCritical, SecurityTreatAsSafe +using System.Net.Cache; // For RequestCachePolicy +using System.Runtime.InteropServices; // For Marshal using System.Threading; // For Mutex using Microsoft.Win32.SafeHandles; using MS.Internal.PresentationCore; @@ -39,7 +37,7 @@ namespace MS.Internal.IO.Packaging [FriendAccessAllowed] internal class ByteRangeDownloader : IDisposable { - //------------------------------------------------------ + //------------------------------------------------------ // // Constructors // @@ -60,7 +58,7 @@ internal ByteRangeDownloader(Uri requestedUri, string tempFileName, SafeWaitHand if (tempFileName.Length <= 0) { - throw new ArgumentException(SR.InvalidTempFileName, "tempFileName"); + throw new ArgumentException(SR.InvalidTempFileName, nameof(tempFileName)); } _tempFileStream = File.Open(tempFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); @@ -164,8 +162,8 @@ protected virtual void Dispose(bool disposing) byteRanges = new int[rangeCount, 2]; for (int i = 0; i < rangeCount; ++i) { - byteRanges[i, Offset_Index] = (int)_byteRangesAvailable[(i * 2) + Offset_Index]; - byteRanges[i, Length_Index] = (int)_byteRangesAvailable[(i * 2) + Length_Index]; + byteRanges[i, Offset_Index] = _byteRangesAvailable[(i * 2) + Offset_Index]; + byteRanges[i, Length_Index] = _byteRangesAvailable[(i * 2) + Length_Index]; } _byteRangesAvailable.Clear(); } @@ -213,18 +211,15 @@ internal void RequestByteRanges(int[,] byteRanges) else // cannot make request yet, put the request in the wait queue { // Lazy Init - if (_requestsOnWait == null) - { - // there are currently only ever two of these (one pair) - // so optimize - _requestsOnWait = new ArrayList(2); - } + // there are currently only ever two of these (one pair) + // so optimize + _requestsOnWait ??= new List(2); for (int i = 0; i < byteRanges.GetLength(0); ++i) { // Add requests to the wait queue - _requestsOnWait.Add((int) byteRanges[i, Offset_Index]); - _requestsOnWait.Add((int) byteRanges[i, Length_Index]); + _requestsOnWait.Add(byteRanges[i, Offset_Index]); + _requestsOnWait.Add(byteRanges[i, Length_Index]); } } } @@ -240,12 +235,12 @@ internal void RequestByteRanges(int[,] byteRanges) { CheckOneDimensionalByteRanges(inByteRanges); - int[,] outByteRanges = new int[(inByteRanges.Length / 2),2]; + int[,] outByteRanges = new int[(inByteRanges.Length / 2), 2]; - for (int i=0, j=0; i < inByteRanges.Length; ++i, ++j) + for (int i = 0, j = 0; i < inByteRanges.Length; ++i, ++j) { - outByteRanges[j,Offset_Index] = inByteRanges[i]; - outByteRanges[j,Length_Index] = inByteRanges[i+1]; + outByteRanges[j, Offset_Index] = inByteRanges[i]; + outByteRanges[j, Length_Index] = inByteRanges[i + 1]; ++i; } @@ -270,7 +265,7 @@ static internal int[] ConvertByteRanges(int[,] inByteRanges) int[] outByteRanges = new int[inByteRanges.Length]; - for (int i=0, j=0; i < inByteRanges.GetLength(0); ++i, ++j) + for (int i = 0, j = 0; i < inByteRanges.GetLength(0); ++i, ++j) { outByteRanges[j] = inByteRanges[i, Offset_Index]; outByteRanges[++j] = inByteRanges[i, Length_Index]; @@ -407,14 +402,14 @@ private ByteRangeDownloader(Uri requestedUri, SafeWaitHandle eventHandle) // Ensure uri is correct scheme (http or https) Do case-sensitive comparison since Uri.Scheme contract is to return in lower case only. if (!string.Equals(requestedUri.Scheme, Uri.UriSchemeHttp, StringComparison.Ordinal) && !string.Equals(requestedUri.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal)) { - throw new ArgumentException(SR.InvalidScheme, "requestedUri"); + throw new ArgumentException(SR.InvalidScheme, nameof(requestedUri)); } ArgumentNullException.ThrowIfNull(eventHandle); if (eventHandle.IsInvalid || eventHandle.IsClosed) { - throw new ArgumentException(SR.InvalidEventHandle, "eventHandle"); + throw new ArgumentException(SR.InvalidEventHandle, nameof(eventHandle)); } _requestedUri = requestedUri; @@ -461,8 +456,8 @@ private HttpWebRequest CreateHttpWebRequest(int[,] byteRanges) // Add byte ranges (to header) for (int i = 0; i < byteRanges.GetLength(0); ++i) { - request.AddRange(byteRanges[i,Offset_Index], - byteRanges[i,Offset_Index] + byteRanges[i,Length_Index] - 1); + request.AddRange(byteRanges[i, Offset_Index], + byteRanges[i, Offset_Index] + byteRanges[i, Length_Index] - 1); } return request; @@ -519,7 +514,7 @@ private void ResponseCallback(IAsyncResult ar) // Get the header and make sure that it was indeed the byte range response int beginOffset = _byteRangesInProgress[0, Offset_Index]; - int endOffset = beginOffset+ _byteRangesInProgress[0,Length_Index] - 1; + int endOffset = beginOffset + _byteRangesInProgress[0, Length_Index] - 1; // HttpWebRequest in the current CLR does not allow multiple byte range requests. // At this point, none of the callers of this class will make more than one range at a time @@ -565,17 +560,14 @@ private void ResponseCallback(IAsyncResult ar) catch // catch (and re-throw) all kinds of exceptions so we can inform the other thread { // inform other thread of error condition - _erroredOut= true; + _erroredOut = true; _erroredOutException = null; throw; } finally { - if (webResponse != null) - { - webResponse.Close(); - } + webResponse?.Close(); // bytes requested are downloaded or errored out // inform the caller that these ranges are available @@ -587,7 +579,7 @@ private void ResponseCallback(IAsyncResult ar) { ProcessWaitQueue(); } - } + } } /// @@ -632,10 +624,7 @@ private bool WriteByteRange(HttpWebResponse response, int offset, int length) // Get the downloaded stream using (Stream s = response.GetResponseStream()) { - if (_buffer == null) - { - _buffer = new byte[WriteBufferSize]; - } + _buffer ??= new byte[WriteBufferSize]; // mutex available? if (_fileMutex != null) @@ -672,8 +661,8 @@ private void ProcessWaitQueue() if (_requestsOnWait != null && _requestsOnWait.Count > 0) { // _byteRangesInProgress is already allocated and can be reused - _byteRangesInProgress[0,Offset_Index] = (int) _requestsOnWait[Offset_Index]; - _byteRangesInProgress[0,Length_Index] = (int) _requestsOnWait[Length_Index]; + _byteRangesInProgress[0, Offset_Index] = _requestsOnWait[Offset_Index]; + _byteRangesInProgress[0, Length_Index] = _requestsOnWait[Length_Index]; _requestsOnWait.RemoveRange(0, 2); _webRequest = CreateHttpWebRequest(_byteRangesInProgress); @@ -706,7 +695,7 @@ static private void CheckOneDimensionalByteRanges(int[] byteRanges) for (int i = 0; i < byteRanges.Length; i++) { - if (byteRanges[i] < 0 || byteRanges[i+1] <= 0) + if (byteRanges[i] < 0 || byteRanges[i + 1] <= 0) { throw new ArgumentException(SR.Format(SR.InvalidByteRanges, "byteRanges")); } @@ -731,7 +720,7 @@ static private void CheckTwoDimensionalByteRanges(int[,] byteRanges) for (int i = 0; i < byteRanges.GetLength(0); ++i) { - if (byteRanges[i,Offset_Index] < 0 || byteRanges[i,Length_Index] <= 0) + if (byteRanges[i, Offset_Index] < 0 || byteRanges[i, Length_Index] <= 0) { throw new ArgumentException(SR.Format(SR.InvalidByteRanges, "byteRanges")); } @@ -756,7 +745,7 @@ static private void CheckTwoDimensionalByteRanges(int[,] byteRanges) /// True if the some bytes of the requested bytes are included in the response. static private bool CheckContentRange(WebHeaderCollection responseHeaders, int beginOffset, ref int endOffset) { - String contentRange = responseHeaders[ContentRangeHeader]; + string contentRange = responseHeaders[ContentRangeHeader]; // No Content-Range (condition #1) if (contentRange == null) @@ -782,7 +771,7 @@ static private bool CheckContentRange(WebHeaderCollection responseHeaders, int b } // Get the first byte offset of the range (XXX) - int firstByteOffset = Int32.Parse(contentRange.AsSpan(ByteRangeUnit.Length, + int firstByteOffset = int.Parse(contentRange.AsSpan(ByteRangeUnit.Length, index - ByteRangeUnit.Length), NumberStyles.None, NumberFormatInfo.InvariantInfo); @@ -796,7 +785,7 @@ static private bool CheckContentRange(WebHeaderCollection responseHeaders, int b } // Get the last byte offset of the range (YYY) - int lastByteOffset = Int32.Parse(contentRangeSpan.Slice(0, index), NumberStyles.None, NumberFormatInfo.InvariantInfo); + int lastByteOffset = int.Parse(contentRangeSpan.Slice(0, index), NumberStyles.None, NumberFormatInfo.InvariantInfo); // Get the instance length // ContentRange: ZZZ @@ -807,7 +796,7 @@ static private bool CheckContentRange(WebHeaderCollection responseHeaders, int b // if it is not an integer or the integer is bigger than Int32 since HttpWebRequest.AddRange // only supports Int32 // Once HttpWebRequest.AddRange start supporting Int64 we should change it to Int64 and long - Int32.Parse(contentRangeSpan, NumberStyles.None, NumberFormatInfo.InvariantInfo); + int.Parse(contentRangeSpan, NumberStyles.None, NumberFormatInfo.InvariantInfo); } // The response is considered to be successful if @@ -845,7 +834,7 @@ static private bool CheckContentRange(WebHeaderCollection responseHeaders, int b private bool _firstRequestMade; private bool _disposed; - private Object _syncObject = new Object(); + private readonly object _syncObject = new object(); private bool _erroredOut; private Exception _erroredOutException; @@ -854,15 +843,15 @@ static private bool CheckContentRange(WebHeaderCollection responseHeaders, int b private IWebProxy _proxy; private ICredentials _credentials; - private CookieContainer _cookieContainer = new CookieContainer(1); + private readonly CookieContainer _cookieContainer = new CookieContainer(1); private SafeWaitHandle _eventHandle; // event handle which needs to be raised to inform the caller that - // the requested bytes are available - private Mutex _fileMutex; // object controlling synchronization on the temp file - if this is null, we own the stream - private System.IO.Stream _tempFileStream; // stream to write to + // the requested bytes are available + private readonly Mutex _fileMutex; // object controlling synchronization on the temp file - if this is null, we own the stream + private Stream _tempFileStream; // stream to write to - private ArrayList _byteRangesAvailable = new ArrayList(2); // byte ranges that are downloaded - private ArrayList _requestsOnWait; // List of byte ranges requested need to be processed + private List _byteRangesAvailable = new List(2); // byte ranges that are downloaded + private List _requestsOnWait; // List of byte ranges requested need to be processed private int[,] _byteRangesInProgress; private HttpWebRequest _webRequest; @@ -874,8 +863,8 @@ static private bool CheckContentRange(WebHeaderCollection responseHeaders, int b private const int Offset_Index = 0; private const int Length_Index = 1; - private const String ByteRangeUnit = "BYTES "; - private const String ContentRangeHeader = "Content-Range"; + private const string ByteRangeUnit = "BYTES "; + private const string ContentRangeHeader = "Content-Range"; #endregion Private Fields } diff --git a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/DeobfuscatingStream.cs b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/DeobfuscatingStream.cs index b6928c2600e..67bc16a1fe6 100644 --- a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/DeobfuscatingStream.cs +++ b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/DeobfuscatingStream.cs @@ -20,7 +20,6 @@ using System; using System.IO; -using System.IO.Packaging; using MS.Internal.PresentationCore; // for ExceptionStringTable @@ -200,17 +199,13 @@ internal DeobfuscatingStream(Stream obfuscatedStream, Uri streamUri, bool leaveO // Make sure streamUri is in the correct form; getting partUri from it will do all necessary checks for error // conditions; We also have to make sure that it has a part name - Uri partUri = System.IO.Packaging.PackUriHelper.GetPartUri(streamUri); - if (partUri == null) - { - throw new InvalidOperationException(SR.InvalidPartName); - } + Uri _ = System.IO.Packaging.PackUriHelper.GetPartUri(streamUri) ?? throw new InvalidOperationException(SR.InvalidPartName); // Normally we should use PackUriHelper.GetStringForPartUri to get the string representation of part Uri // however, since we already made sure that streamUris is in the correct form (such as to check if it is an absolute Uri // and there is a correct authority (package)), it doesn't have to be fully validated again. // Get the escaped string for the part name as part names should have only ascii characters - String guid = Path.GetFileNameWithoutExtension( + string guid = Path.GetFileNameWithoutExtension( streamUri.GetComponents(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.UriEscaped)); _guid = GetGuidByteArray(guid); @@ -353,8 +348,8 @@ private static byte[] GetGuidByteArray(string guidString) //------------------------------------------------------ private Stream _obfuscatedStream; // stream we ultimately decompress from and to in the container - private byte[] _guid; - private bool _ownObfuscatedStream; // Does this class own the underlying stream? + private readonly byte[] _guid; + private readonly bool _ownObfuscatedStream; // Does this class own the underlying stream? // if it does, it should dispose the underlying stream when this class is disposed private const long ObfuscatedLength = 32; #endregion diff --git a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/NetStream.cs b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/NetStream.cs index bf6074820ac..719b41f59a6 100644 --- a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/NetStream.cs +++ b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/NetStream.cs @@ -38,15 +38,11 @@ #endif using System; +using System.Collections.Generic; +using System.Diagnostics; // for Debug.Assert using System.IO; using System.Net; -using System.Runtime.InteropServices; using System.Threading; -using System.Collections; // for IComparer -using System.Diagnostics; // for Debug.Assert -using System.Security; // SecurityCritical, SecurityTreatAsSafe -using System.IO.IsolatedStorage; // for IsolatedStorageFileStream -using MS.Internal.IO.Packaging; // ByteRangeDownloader using MS.Internal.PresentationCore; // for ExceptionStringTable namespace MS.Internal.IO.Packaging @@ -79,7 +75,7 @@ internal NetStream( { #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.NetStream()"); + Trace.TraceInformation("NetStream.NetStream()"); #endif // check parms @@ -131,7 +127,7 @@ public override int Read(byte[] buffer, int offset, int count) CheckDisposed(); #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.Read() offset:{0} length:{1}", _position, count ); + Trace.TraceInformation("NetStream.Read() offset:{0} length:{1}", _position, count ); #endif PackagingUtilities.VerifyStreamReadArgs(this, buffer, offset, count); @@ -145,7 +141,7 @@ public override int Read(byte[] buffer, int offset, int count) checked { if (offset + count > buffer.Length) - throw new ArgumentException(SR.IOBufferOverflow, "buffer"); + throw new ArgumentException(SR.IOBufferOverflow, nameof(buffer)); // make sure some data is in the stream - block until it is int bytesAvailable = GetData(new Block(_position, count)); @@ -254,7 +250,7 @@ public override long Seek(long offset, SeekOrigin origin) default: { - throw new ArgumentOutOfRangeException("origin", SR.SeekOriginInvalid); + throw new ArgumentOutOfRangeException(nameof(origin), SR.SeekOriginInvalid); } } } @@ -265,7 +261,7 @@ public override long Seek(long offset, SeekOrigin origin) #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.Seek() pos:{0}", temp); + Trace.TraceInformation("NetStream.Seek() pos:{0}", temp); #endif _position = temp; return _position; @@ -291,7 +287,7 @@ public override long Position #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.set_Position() pos:{0}", value); + Trace.TraceInformation("NetStream.set_Position() pos:{0}", value); #endif _position = value; @@ -382,7 +378,7 @@ protected override void Dispose(bool disposing) { #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.Close()"); + Trace.TraceInformation("NetStream.Close()"); #endif lock (_syncObject) { @@ -394,7 +390,7 @@ protected override void Dispose(bool disposing) { #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.Dispose(bool) - mark as closed"); + Trace.TraceInformation("NetStream.Dispose(bool) - mark as closed"); #endif // No matter what, mark ourselves as disposed. @@ -402,10 +398,8 @@ protected override void Dispose(bool disposing) _disposed = true; // release any blocked threads - Set() does not throw any exceptions - if (_readEventHandles[(int)ReadEvent.FullDownloadReadEvent] != null) - _readEventHandles[(int)ReadEvent.FullDownloadReadEvent].Set(); - if (_readEventHandles[(int)ReadEvent.ByteRangeReadEvent] != null) - _readEventHandles[(int)ReadEvent.ByteRangeReadEvent].Set(); + _readEventHandles[(int)ReadEvent.FullDownloadReadEvent]?.Set(); + _readEventHandles[(int)ReadEvent.ByteRangeReadEvent]?.Set(); // Free ByteRangeDownloader FreeByteRangeDownloader(); @@ -423,15 +417,12 @@ protected override void Dispose(bool disposing) } // Free Full Download - if (_responseStream != null) - { - _responseStream.Close(); - } + _responseStream?.Close(); FreeTempFile(); #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.Dispose(bool) - exiting"); + Trace.TraceInformation("NetStream.Dispose(bool) - exiting"); #endif } finally @@ -520,7 +511,7 @@ private void ReadCallBack(IAsyncResult ar) { #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.ReadCallBack() - exiting early because we are closed"); + Trace.TraceInformation("NetStream.ReadCallBack() - exiting early because we are closed"); #endif return; } @@ -537,7 +528,7 @@ private void ReadCallBack(IAsyncResult ar) #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.ReadCallBack (offset,length):({0},{1})", _highWaterMark, read); + Trace.TraceInformation("NetStream.ReadCallBack (offset,length):({0},{1})", _highWaterMark, read); #endif lock(PackagingUtilities.IsolatedStorageFileLock) { @@ -560,7 +551,7 @@ private void ReadCallBack(IAsyncResult ar) { #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.ReadCallBack() - read complete - EndRead() returned zero"); + Trace.TraceInformation("NetStream.ReadCallBack() - read complete - EndRead() returned zero"); #endif // set Length if not already done so if (_fullStreamLength < 0) @@ -604,7 +595,7 @@ private void EnsureDownloader() _byteRangeDownloader.Credentials = _originalRequest.Credentials; _byteRangeDownloader.CachePolicy = _originalRequest.CachePolicy; - _byteRangesAvailable = new ArrayList(); // byte ranges that are downloaded + _byteRangesAvailable = new List(); // byte ranges that are downloaded } } @@ -620,7 +611,7 @@ private void MakeByteRangeRequest(Block block) // block.Offset > Int32.MaxValue // block.Offset + block.Length - 1 > Int32.MaxValue // No need to do "checked" since block.Length > 0 && block.Length <= Int32.MaxValue - if (block.Offset > (Int32.MaxValue - block.Length + 1)) + if (block.Offset > (int.MaxValue - block.Length + 1)) return; // spawn a request @@ -631,7 +622,7 @@ private void MakeByteRangeRequest(Block block) { #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.MakeByteRangeRequest() offset:{0} length:{1} (padded to {2})", + Trace.TraceInformation("NetStream.MakeByteRangeRequest() offset:{0} length:{1} (padded to {2})", block.Offset, block.Length, _additionalRequestMinSize); #endif block.Length = _additionalRequestMinSize; @@ -640,7 +631,7 @@ private void MakeByteRangeRequest(Block block) else { if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.MakeByteRangeRequest() offset:{0} length:{1}", block.Offset, block.Length); + Trace.TraceInformation("NetStream.MakeByteRangeRequest() offset:{0} length:{1}", block.Offset, block.Length); } #endif @@ -706,7 +697,7 @@ private void GetByteRangeData() #if DEBUG // Note that this includes the "fullDownload" range if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.GetData() total byteranges:{0} after merging:{1}", _unmergedBlocks, _byteRangesAvailable.Count); + Trace.TraceInformation("NetStream.GetData() total byteranges:{0} after merging:{1}", _unmergedBlocks, _byteRangesAvailable.Count); #endif _inAdditionalRequest = false; // allow more byte-range requests } @@ -913,19 +904,19 @@ internal void Merge(Block b) // Merge all overlapping and adjacent ranges // This function assumes the list of ranges are already sorted // Function is destructive (in-place) - private void MergeByteRanges(ArrayList ranges) + private static void MergeByteRanges(List ranges) { checked { // For each byte range for (int i = 0; i + 1 < ranges.Count; i++) { - Block b = (Block)ranges[i]; + Block b = ranges[i]; // handle possible multiple-overlap (or adjacency) - while (b.Mergeable((Block)ranges[i + 1])) + while (b.Mergeable(ranges[i + 1])) { - b.Merge((Block)ranges[i + 1]); + b.Merge(ranges[i + 1]); ranges.RemoveAt(i + 1); // don't index off the end of the list @@ -947,7 +938,7 @@ private int HandleByteRangeReadEvent(Block block) { #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.GetData() - byteRange data Event signaled"); + Trace.TraceInformation("NetStream.GetData() - byteRange data Event signaled"); #endif Debug.Assert(block.Length > 0); @@ -968,7 +959,7 @@ private int HandleByteRangeReadEvent(Block block) _additionalRequestThreshold *= 2; #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.GetData() - byteRange request satisfied by full download - increasing threshold"); + Trace.TraceInformation("NetStream.GetData() - byteRange request satisfied by full download - increasing threshold"); #endif } else @@ -1014,7 +1005,7 @@ private int HandleFullDownloadReadEvent(Block block) { #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.GetData() - Request Data (BeginRead)"); + Trace.TraceInformation("NetStream.GetData() - Request Data (BeginRead)"); #endif // Continue reading data until @@ -1072,8 +1063,8 @@ private int GetData(Block block) // 5. The block we were asked to retrieve was not satisfied by existing data if (_allowByteRangeRequests && !_inAdditionalRequest - && (_highWaterMark <= Int64.MaxValue - (long) _additionalRequestThreshold) // Ensure that we don't get overflow from the next line - && (block.Offset > _highWaterMark + (long) _additionalRequestThreshold) + && (_highWaterMark <= long.MaxValue - _additionalRequestThreshold) // Ensure that we don't get overflow from the next line + && (block.Offset > _highWaterMark + _additionalRequestThreshold) && ((_byteRangeDownloader == null) || !_byteRangeDownloader.ErroredOut) && (block.Length > 0)) { MakeByteRangeRequest(block); // request data @@ -1087,7 +1078,7 @@ private int GetData(Block block) { #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.GetData() - wait start"); // for debugging deadlock + Trace.TraceInformation("NetStream.GetData() - wait start"); // for debugging deadlock #endif // WaitAny if both events are in use - or just ReadEvent eventFired; @@ -1108,7 +1099,7 @@ private int GetData(Block block) } #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.GetData() - wait end [{0}]", eventFired); + Trace.TraceInformation("NetStream.GetData() - wait end [{0}]", eventFired); #endif lock (_syncObject) { @@ -1134,7 +1125,7 @@ private int GetData(Block block) #if DEBUG if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("NetStream.GetData() satisfied with {0} bytes", dataAvailable); + Trace.TraceInformation("NetStream.GetData() satisfied with {0} bytes", dataAvailable); #endif // could exit with dataAvailable == 0 if we didn't know the full stream length coming in and the request // was beyond the actual stream length @@ -1187,10 +1178,7 @@ private void ReleaseFullDownloadResources() finally { // FreeFullDownload - if (_responseStream != null) - { - _responseStream.Close(); - } + _responseStream?.Close(); } } finally @@ -1274,9 +1262,9 @@ private void FreeTempFile() //------------------------------------------------------ private enum ReadEvent { FullDownloadReadEvent = 0, ByteRangeReadEvent = 1, MaxReadEventEnum }; - Uri _uri; // uri we are resolving + readonly Uri _uri; // uri we are resolving - WebRequest _originalRequest; // Proxy member is Critical + readonly WebRequest _originalRequest; // Proxy member is Critical Stream _tempFileStream; // local temp stream we are writing to and reading from - protected by _tempFileMutex long _position; // our "logical stream position" @@ -1290,7 +1278,7 @@ private enum ReadEvent { FullDownloadReadEvent = 0, ByteRangeReadEvent = 1, MaxR // 3. _readEventHandles - cannot be as these are synchronization objects which must be freely accessible // 4. _byteRangeDownloader - yes except this object can be disposed while it is still "active" - it is expected to behave correctly in this // scenario. - private Object _syncObject = new Object(); + private readonly object _syncObject = new object(); private volatile bool _disposed; // full-file download @@ -1319,7 +1307,7 @@ private enum ReadEvent { FullDownloadReadEvent = 0, ByteRangeReadEvent = 1, MaxR private bool _allowByteRangeRequests; // toggle private ByteRangeDownloader _byteRangeDownloader; // handles byte-range downloads for us private bool _inAdditionalRequest; // only spawn one byte-range request at a time - private ArrayList _byteRangesAvailable; // byte ranges that are downloaded + private List _byteRangesAvailable; // byte ranges that are downloaded #if DEBUG private int _unmergedBlocks; // for trace only #endif diff --git a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/PreloadedPackages.cs b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/PreloadedPackages.cs index be91d945ef5..57917770ec2 100644 --- a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/PreloadedPackages.cs +++ b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/PreloadedPackages.cs @@ -10,16 +10,10 @@ // using System; -using System.Security; -using System.Collections; -using System.Collections.Specialized; -using System.Diagnostics; -using System.Globalization; -using System.IO; +using System.Collections.Generic; using System.IO.Packaging; -using MS.Internal; -using MS.Internal.PresentationCore; // for ExceptionStringTable +using MS.Internal.PresentationCore; // for ExceptionStringTable namespace MS.Internal.IO.Packaging { @@ -33,16 +27,6 @@ namespace MS.Internal.IO.Packaging [FriendAccessAllowed] internal static class PreloadedPackages { - //------------------------------------------------------ - // - // Static Constructors - // - //------------------------------------------------------ - static PreloadedPackages() - { - _globalLock = new Object(); - } - //------------------------------------------------------ // // Internal Methods @@ -58,8 +42,7 @@ static PreloadedPackages() /// uri must be absolute internal static Package GetPackage(Uri uri) { - bool ignored; - return GetPackage(uri, out ignored); + return GetPackage(uri, out bool _); } /// @@ -80,8 +63,7 @@ internal static Package GetPackage(Uri uri, out bool threadSafe) if (_packagePairs != null) { - PackageThreadSafePair packagePair = _packagePairs[uri] as PackageThreadSafePair; - if (packagePair != null) + if (_packagePairs.TryGetValue(uri, out PackageThreadSafePair packagePair)) { package = packagePair.Package; threadSafe = packagePair.ThreadSafe; @@ -120,10 +102,7 @@ internal static void AddPackage(Uri uri, Package package, bool threadSafe) lock (_globalLock) { - if (_packagePairs == null) - { - _packagePairs = new HybridDictionary(3); - } + _packagePairs ??= new Dictionary(3); _packagePairs.Add(uri, new PackageThreadSafePair(package, threadSafe)); } @@ -142,10 +121,7 @@ internal static void RemovePackage(Uri uri) lock (_globalLock) { - if (_packagePairs != null) - { - _packagePairs.Remove(uri); - } + _packagePairs?.Remove(uri); } } @@ -164,7 +140,7 @@ private static void ValidateUriKey(Uri uri) if (!uri.IsAbsoluteUri) { - throw new ArgumentException(SR.UriMustBeAbsolute, "uri"); + throw new ArgumentException(SR.UriMustBeAbsolute, nameof(uri)); } } @@ -237,8 +213,8 @@ internal bool ThreadSafe // ListDictionary is the best fit for this scenarios; otherwise we should be using // Hashtable. HybridDictionary already has functionality of switching between // ListDictionary and Hashtable depending on the size of the collection - static private HybridDictionary _packagePairs; - static private readonly Object _globalLock; + static private Dictionary _packagePairs; + static private readonly object _globalLock = new object(); #endregion Private Fields } diff --git a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/PseudoWebRequest.cs b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/PseudoWebRequest.cs index 769993d11ae..6abf673dbca 100644 --- a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/PseudoWebRequest.cs +++ b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/PseudoWebRequest.cs @@ -19,12 +19,7 @@ using System.IO.Packaging; using System.Net; using System.Net.Cache; // for RequestCachePolicy -using System.Runtime.Serialization; using System.Diagnostics; // For Assert -using MS.Utility; // for EventTrace -using MS.Internal.IO.Packaging; // for PackageCacheEntry -using MS.Internal.PresentationCore; // for SR exception strings -using MS.Internal; namespace MS.Internal.IO.Packaging { @@ -194,8 +189,7 @@ public override WebHeaderCollection Headers get { // lazy init - if (_headers == null) - _headers = new WebHeaderCollection(); + _headers ??= []; return _headers; } @@ -253,8 +247,7 @@ public override IWebProxy Proxy get { // lazy init - if (_proxy == null) - _proxy = WebRequest.DefaultWebProxy; + _proxy ??= DefaultWebProxy; return _proxy; } @@ -329,7 +322,7 @@ public override bool UseDefaultCredentials // Private Methods // //------------------------------------------------------ - private bool IsScheme(String schemeName) + private bool IsScheme(string schemeName) { return (string.Equals(_innerUri.Scheme, schemeName, StringComparison.Ordinal)); } @@ -340,7 +333,7 @@ private bool IsScheme(String schemeName) private void SetDefaults() { // set defaults - _connectionGroupName = String.Empty; // http default + _connectionGroupName = string.Empty; // http default _contentType = null; // default _credentials = null; // actual default _headers = null; // lazy init @@ -367,10 +360,10 @@ private void SetDefaults() // Private Fields // //------------------------------------------------------ - private Uri _uri; // pack uri - private Uri _innerUri; // inner uri extracted from the pack uri - private Uri _partName; // name of PackagePart (if any) - null for full-container references - private Package _cacheEntry; // cached package + private readonly Uri _uri; // pack uri + private readonly Uri _innerUri; // inner uri extracted from the pack uri + private readonly Uri _partName; // name of PackagePart (if any) - null for full-container references + private readonly Package _cacheEntry; // cached package // local copies of public members private string _connectionGroupName; diff --git a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/ResponseStream.cs b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/ResponseStream.cs index c09994eceed..1895983b8c6 100644 --- a/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/ResponseStream.cs +++ b/src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/ResponseStream.cs @@ -24,7 +24,6 @@ using System.IO; using System.IO.Packaging; // for PackWebResponse using MS.Utility; -using System.Windows; namespace MS.Internal.IO.Packaging { @@ -235,18 +234,15 @@ protected override void Dispose(bool disposing) { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) - System.Diagnostics.Trace.TraceInformation("ContainerResponseStream.Dispose(bool)"); + Trace.TraceInformation("ContainerResponseStream.Dispose(bool)"); #endif _container = null; // close the Part or NetStream _innerStream.Close(); - if (_owningStream != null) - { - // in this case, the innerStream was the part so this is the NetStream - _owningStream.Close(); - } + // in this case, the innerStream was the part so this is the NetStream + _owningStream?.Close(); } } finally