Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introducing Trace helper methods in PresentationCore #8702

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
using System.Windows.Navigation;
using System.Security;
using MS.Internal.PresentationCore;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;

namespace MS.Internal.AppModel
{
Expand Down Expand Up @@ -55,13 +59,8 @@ internal static Uri SiteOfOrigin
// Calling FixFileUri because BaseDirectory will be a c:\\ style path
siteOfOrigin = BaseUriHelper.FixFileUri(new Uri(System.AppDomain.CurrentDomain.BaseDirectory));
}
#if DEBUG
if (_traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": SiteOfOriginContainer: returning site of origin " + siteOfOrigin);
#endif

Trace($"SiteOfOriginContainer: returning site of origin {siteOfOrigin}");

return siteOfOrigin;
}
Expand Down Expand Up @@ -194,7 +193,120 @@ internal static bool TraceSwitchEnabled
// Internal Methods
//
//------------------------------------------------------
// None

[Conditional("DEBUG")]
internal static void Trace(string message)
{
if (_traceSwitch.Enabled)
{
System.Diagnostics.Trace.TraceInformation(
$"{DateTime.Now:T} {DateTime.Now.Millisecond} {Environment.CurrentManagedThreadId}: {message}");
}

}

[Conditional("DEBUG")]
internal static void Trace(ref TraceInterpolatedStringHandler message)
{
if (_traceSwitch.Enabled)
{
System.Diagnostics.Trace.TraceInformation(message.ToStringAndClear());
}

}

/// <summary>
/// Provides an interpolated string handler for <see
/// cref="TraceSwitchExtensions.TraceVerbose(TraceSwitch?, ref TraceSwitchExtensions.TraceVerboseInterpolatedStringHandler)"
/// /> that only performs formatting if the condition applies.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[InterpolatedStringHandler]
public struct TraceInterpolatedStringHandler
{
/// <summary>
/// The handler we use to perform the formatting.
/// </summary>
private StringBuilder.AppendInterpolatedStringHandler _stringBuilderHandler;

/// <summary>
/// The underlying <see cref="StringBuilder"/> instance used by <see cref="_stringBuilderHandler"/>,
/// if any.
/// </summary>
private StringBuilder _builder;

/// <summary>
/// Creates an instance of the handler.
/// </summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <param name="traceSwitch">The TraceSwitch passed to the <see cref="TraceSwitchExtensions"/> method.</param>
/// <param name="shouldAppend">A value indicating whether formatting should proceed.</param>
/// <remarks>
/// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd
/// otherwise be for members intended to be used directly.
/// </remarks>
internal TraceInterpolatedStringHandler(int literalLength, int formattedCount, out bool shouldAppend)
{
if (_traceSwitch.Enabled)
{
_builder = new StringBuilder();
_builder.Append($"{DateTime.Now:T} {DateTime.Now.Millisecond} {Environment.CurrentManagedThreadId}: ");
_stringBuilderHandler = new StringBuilder.AppendInterpolatedStringHandler(literalLength, formattedCount,
_builder);
shouldAppend = true;
}
else
{
_stringBuilderHandler = default;
shouldAppend = false;
}
}

/// <summary>
/// Extracts the built string from the handler.
/// </summary>
internal string ToStringAndClear()
{
string s = _builder?.ToString() ?? string.Empty;
_stringBuilderHandler = default;
_builder = null;
return s;
}

/// <summary>
/// Writes the specified string to the handler.
/// </summary>
/// <param name="value">The string to write.</param>
public void AppendLiteral(string value) => _stringBuilderHandler.AppendLiteral(value);

/// <summary>
/// Writes the specified value to the handler.
/// </summary>
/// <param name="value">The value to write.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value) => _stringBuilderHandler.AppendFormatted(value);

/// <summary>
/// Writes the specified value to the handler.
/// </summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value, string? format) => _stringBuilderHandler.AppendFormatted(value, format);

/// <summary>
/// Writes the specified character span to the handler.
/// </summary>
/// <param name="value">The span to write.</param>
public void AppendFormatted(ReadOnlySpan<char> value) => _stringBuilderHandler.AppendFormatted(value);

/// <summary>
/// Writes the specified character span to the handler.
/// </summary>
/// <param name="value">The value to write.</param>
public void AppendFormatted(string value) => _stringBuilderHandler.AppendFormatted(value);
}

//------------------------------------------------------
//
Expand Down Expand Up @@ -226,13 +338,7 @@ internal static bool TraceSwitchEnabled
/// <returns></returns>
protected override PackagePart GetPartCore(Uri uri)
{
#if DEBUG
if (_traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": SiteOfOriginContainer: Creating SiteOfOriginPart for Uri " + uri);
#endif
Trace($"SiteOfOriginContainer: Creating SiteOfOriginPart for Uri {uri}");
return new SiteOfOriginPart(this, uri);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,25 +52,13 @@ internal SiteOfOriginPart(Package container, Uri uri) :

protected override Stream GetStreamCore(FileMode mode, FileAccess access)
{
#if DEBUG
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Getting stream.");
#endif
SiteOfOriginContainer.Trace("SiteOfOriginPart: Getting stream.");
return GetStreamAndSetContentType(false);
}

protected override string GetContentTypeCore()
{
#if DEBUG
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Getting content type.");
#endif
SiteOfOriginContainer.Trace("SiteOfOriginPart: Getting content type.");

GetStreamAndSetContentType(true);
return _contentType.ToString();
Expand All @@ -92,13 +80,7 @@ private Stream GetStreamAndSetContentType(bool onlyNeedContentType)
{
if (onlyNeedContentType && _contentType != MS.Internal.ContentType.Empty)
{
#if DEBUG
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Getting content type and using previously determined value");
#endif
SiteOfOriginContainer.Trace("SiteOfOriginPart: Getting content type and using previously determined value");
return null;
}

Expand All @@ -108,40 +90,22 @@ private Stream GetStreamAndSetContentType(bool onlyNeedContentType)
// the next time GetStreamCore() is called.
if (_cacheStream != null)
{
#if DEBUG
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
"SiteOfOriginPart: Using Cached stream");
#endif
SiteOfOriginContainer.Trace("SiteOfOriginPart: Using Cached stream");
Stream temp = _cacheStream;
_cacheStream = null;
return temp;
}

if (_absoluteLocation == null)
{
#if DEBUG
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Determining absolute uri for this resource");
#endif
SiteOfOriginContainer.Trace("SiteOfOriginPart: Determining absolute uri for this resource");
string original = Uri.ToString();
Invariant.Assert(original[0] == '/');
string uriMinusInitialSlash = original.Substring(1); // trim leading '/'
_absoluteLocation = new Uri(SiteOfOriginContainer.SiteOfOrigin, uriMinusInitialSlash);
}

#if DEBUG
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Making web request to " + _absoluteLocation);
#endif
SiteOfOriginContainer.Trace($"SiteOfOriginPart: Making web request to {_absoluteLocation}");

// For performance reasons it is better to open local files directly
// rather than make a FileWebRequest.
Expand All @@ -161,13 +125,7 @@ private Stream GetStreamAndSetContentType(bool onlyNeedContentType)

private Stream HandleFileSource(bool onlyNeedContentType)
{
#if DEBUG
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": Opening local file " + _absoluteLocation);
#endif
SiteOfOriginContainer.Trace($"SiteOfOriginPart: Opening local file {_absoluteLocation}");
if (_contentType == MS.Internal.ContentType.Empty)
{
_contentType = MS.Internal.MimeTypeMapper.GetMimeTypeFromUri(Uri);
Expand All @@ -185,23 +143,11 @@ private Stream HandleWebSource(bool onlyNeedContentType)
WebResponse response = WpfWebRequestHelper.CreateRequestAndGetResponse(_absoluteLocation);
Stream responseStream = response.GetResponseStream();

#if DEBUG
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": Successfully retrieved stream from " + _absoluteLocation);
#endif
SiteOfOriginContainer.Trace($"SiteOfOriginPart: Successfully retrieved stream from {_absoluteLocation}");

if (_contentType == MS.Internal.ContentType.Empty)
{
#if DEBUG
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Setting _contentType");
#endif
SiteOfOriginContainer.Trace($"SiteOfOriginPart: Setting {nameof(_contentType)}");

_contentType = WpfWebRequestHelper.GetContentType(response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ internal static string CompositeFontExtension

static Util()
{
string s = Environment.GetEnvironmentVariable(WinDir) + @"\Fonts\";
string s = $@"{Environment.GetEnvironmentVariable(WinDir)}\Fonts\";

_windowsFontsLocalPath = s.ToUpperInvariant();

Expand Down Expand Up @@ -538,7 +538,7 @@ internal static Uri CombineUriWithFaceIndex(string fontUri, int faceIndex)
// so that they don't conflict with the fragment part.
string canonicalPathUri = new Uri(fontUri).GetComponents(UriComponents.AbsoluteUri, UriFormat.SafeUnescaped);
string faceIndexString = faceIndex.ToString(CultureInfo.InvariantCulture);
return new Uri(canonicalPathUri + '#' + faceIndexString);
return new Uri($"{canonicalPathUri}#{faceIndexString}");
}

internal static bool IsSupportedFontExtension(string extension, out bool isComposite)
Expand Down Expand Up @@ -662,7 +662,7 @@ private static string NormalizeFontFamilyReference(string fontFamilyReference, i
{
// No fragment separator. The entire string is a family name so convert to uppercase
// and add a fragment separator at the beginning.
return string.Concat("#", fontFamilyReference.AsSpan(startIndex, length)).ToUpperInvariant();
return $"#{fontFamilyReference.AsSpan(startIndex, length)}".ToUpperInvariant();
}
else if (fragmentIndex + 1 == startIndex + length)
{
Expand Down Expand Up @@ -702,11 +702,7 @@ internal static string ConvertFamilyNameAndLocationToFontFamilyReference(string
if (!string.IsNullOrEmpty(location))
{
// We just escaped the family name and the location part should already be a valid URI reference.
fontFamilyReference = string.Concat(
location,
"#",
fontFamilyReference
);
fontFamilyReference = $"{location}#{fontFamilyReference}";
}

return fontFamilyReference;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ private void SetFontSources()
{
if (_tryGetCompositeFontsOnly)
{
files = Directory.GetFiles(_uri.LocalPath, "*" + Util.CompositeFontExtension);
files = Directory.GetFiles(_uri.LocalPath, $"*{Util.CompositeFontExtension}");
isOnlyCompositeFontFiles = true;
}
else
Expand Down Expand Up @@ -168,7 +168,7 @@ private void SetFontSources()
{
if (_tryGetCompositeFontsOnly)
{
files = Directory.GetFiles(_uri.LocalPath, "*" + Util.CompositeFontExtension);
files = Directory.GetFiles(_uri.LocalPath, $"*{Util.CompositeFontExtension}");
isOnlyCompositeFontFiles = true;
}
else
Expand Down Expand Up @@ -269,7 +269,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
private bool _tryGetCompositeFontsOnly;

private const string InstalledWindowsFontsRegistryKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts";
private const string InstalledWindowsFontsRegistryKeyFullPath = @"HKEY_LOCAL_MACHINE\" + InstalledWindowsFontsRegistryKey;
private const string InstalledWindowsFontsRegistryKeyFullPath = $@"HKEY_LOCAL_MACHINE\{InstalledWindowsFontsRegistryKey}";
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ private void ParseFontFamilyCollectionElement()

if (!foundOsSection)
{
Fail(string.Format("No FontFamily element found in FontFamilyCollection that matches current OS or greater: {0}", OSVersionHelper.GetOsVersion().ToString()));
Fail($"No FontFamily element found in FontFamilyCollection that matches current OS or greater: {OSVersionHelper.GetOsVersion()}");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ internal void MoveTo(IEnumerable<Point> path)
}
#if POINTS_FILTER_TRACE
_totalPointsAdded += path.Length;
System.Diagnostics.Debug.WriteLine(String.Format("Total Points added: {0} screened: {1} collinear screened: {2}", _totalPointsAdded, _totalPointsScreened, _collinearPointsScreened));
System.Diagnostics.Debug.WriteLine($"Total Points added: {_totalPointsAdded} screened: {_totalPointsScreened} collinear screened: {_collinearPointsScreened}");
#endif

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,13 @@ public override string ToString()
}
else if (Value is string)
{
val = "\"" + Value.ToString() + "\"";
val = $"\"{Value}\"";
}
else
{
val = Value.ToString();
}
return KnownIds.ConvertToString(Id) + "," + val;
return $"{KnownIds.ConvertToString(Id)},{val}";
}

/// <summary>
Expand Down
Loading
Loading