Skip to content

Commit

Permalink
Use string interpolation in more places
Browse files Browse the repository at this point in the history
Mostly tests, but a few src fixes as well.
  • Loading branch information
stephentoub committed Nov 29, 2022
1 parent 0fc047c commit 1a818ef
Show file tree
Hide file tree
Showing 29 changed files with 53 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,9 @@ public virtual string CreateStackTraceString(IntPtr ip, bool includeFileInfo)
return "<unknown>";
}

StringBuilder sb = new StringBuilder();
ReadOnlySpan<char> fileNameWithoutExtension = Path.GetFileNameWithoutExtension(moduleFullFileName.AsSpan());
int rva = (int)(ip - moduleBase);
sb.Append(fileNameWithoutExtension);
sb.Append("!<BaseAddress>+0x");
sb.Append(rva.ToString("x"));
return sb.ToString();
return $"{fileNameWithoutExtension}!<BaseAddress>+0x{rva:x}";
}

public virtual void TryGetSourceLineInfo(IntPtr ip, out string fileName, out int lineNumber, out int columnNumber)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,19 +240,21 @@ internal static SafeKeychainHandle CreateOrOpenKeychain(string keychainPath, boo

internal static unsafe SafeTemporaryKeychainHandle CreateTemporaryKeychain()
{
const int randomSize = 256;
string tmpKeychainPath = Path.Combine(
Path.GetTempPath(),
Guid.NewGuid().ToString("N") + ".keychain");
const int RandomSize = 256;

string tempPath = Path.GetTempPath();
string tmpKeychainPath = Path.EndsInDirectorySeparator(tempPath) ?
$"{tempPath}{Guid.NewGuid():N}.keychain" :
$"{tempPath}{Path.DirectorySeparatorChar}{Guid.NewGuid():N}.keychain";

// Use a random password so that if a keychain is abandoned it isn't recoverable.
// We use stack to minimize lingering
Span<byte> random = stackalloc byte[randomSize];
Span<byte> random = stackalloc byte[RandomSize];
RandomNumberGenerator.Fill(random);

// Create hex-like UTF8 string.
Span<byte> utf8Passphrase = stackalloc byte[randomSize * 2 +1];
utf8Passphrase[randomSize * 2] = 0; // null termination for C string.
Span<byte> utf8Passphrase = stackalloc byte[RandomSize * 2 +1];
utf8Passphrase[RandomSize * 2] = 0; // null termination for C string.

for (int i = 0; i < random.Length; i++)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,7 @@ internal void SetToInvalid()
dwUpper = IntPtr.Zero;
}

public override string ToString()
{
{ return dwLower.ToString("x") + ":" + dwUpper.ToString("x"); }
}
public override string ToString() => $"{dwLower:x}:{dwUpper:x}";
}

internal enum ContextAttribute
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,11 +311,11 @@ public async Task Proxy_SslProxyUnsupported_Throws()
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.Proxy = new WebProxy("https://" + Guid.NewGuid().ToString("N"));
handler.Proxy = new WebProxy($"https://{Guid.NewGuid():N}");

Type expectedType = IsWinHttpHandler ? typeof(HttpRequestException) : typeof(NotSupportedException);

await Assert.ThrowsAsync(expectedType, () => client.GetAsync("http://" + Guid.NewGuid().ToString("N")));
await Assert.ThrowsAsync(expectedType, () => client.GetAsync($"http://{Guid.NewGuid():N}"));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public void Log<TState>(
// Buffer the message into a single string in order to avoid shearing the message when running across multiple threads.
var messageBuilder = new StringBuilder();

var timestamp = _logStart.HasValue ? $"{(DateTimeOffset.UtcNow - _logStart.Value).TotalSeconds.ToString("N3")}s" : DateTimeOffset.UtcNow.ToString("s");
var timestamp = _logStart.HasValue ? $"{(DateTimeOffset.UtcNow - _logStart.Value).TotalSeconds:N3}s" : DateTimeOffset.UtcNow.ToString("s");

var firstLinePrefix = $"| [{timestamp}] {_category} {logLevel}: ";
var lines = formatter(state, exception).Split(NewLineChars, StringSplitOptions.RemoveEmptyEntries);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public static SortedList CreateStringSortedList(int count, int start = 0)

for (int i = start; i < start + count; i++)
{
sortedList.Add("Key_" + i.ToString("D2"), "Value_" + i);
sortedList.Add($"Key_{i:D2}", $"Value_{i}");
}

return sortedList;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,15 +109,15 @@ public void Ctor_IDictionary(int count, bool sorted)
// Create a hashtable in the correctly sorted order
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
hashtable.Add($"Key_{i:D2}", $"Value_{i:D2}");
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
hashtable.Add($"Key_{i:D2}", $"Value_{i:D2}");
}
}

Expand Down Expand Up @@ -163,15 +163,15 @@ public void Ctor_IDictionary_IComparer(int count, bool sorted)
// Create a hashtable in the correctly sorted order
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
hashtable.Add($"Key_{i:D2}", $"Value_{i:D2}");
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
hashtable.Add($"Key_{i:D2}", $"Value_{i:D2}");
}
}

Expand All @@ -182,9 +182,9 @@ public void Ctor_IDictionary_IComparer(int count, bool sorted)

for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
string expectedValue = "Value_" + (count - i - 1).ToString("D2");
string key = $"Key_{i:D2}";
string value = $"Value_{i:D2}";
string expectedValue = $"Value_{count - i - 1:D2}";

Assert.Equal(sortList.GetByIndex(i), expectedValue);
Assert.Equal(hashtable[key], sortList[key]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ private static string GenerateRootId()
// It is important that the part that changes frequently be first, because
// some sampling functions don't sample from the high entropy part of their hash function.
// This makes sampling based on this produce poor samples.
return '|' + Interlocked.Increment(ref s_currentRootId).ToString("x") + s_uniqSuffix;
return $"|{Interlocked.Increment(ref s_currentRootId):x}{s_uniqSuffix}";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public partial class Activity : IDisposable
private const int RequestIdMaxLength = 1024;

// Used to generate an ID it represents the machine and process we are in.
private static readonly string s_uniqSuffix = "-" + GetRandomNumber().ToString("x") + ".";
private static readonly string s_uniqSuffix = $"-{GetRandomNumber():x}.";

// A unique number inside the appdomain, randomized between appdomains.
// Int gives enough randomization and keeps hex-encoded s_currentRootId 8 chars long for most applications
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public void Fail_LogFileDirectoryNotFound()
{
// Exception should be handled by DefaultTraceListener.WriteLine so no need to assert.
var listener = new TestDefaultTraceListener();
listener.LogFileName = $"{Guid.NewGuid().ToString("N")}\\LogFile.txt";
listener.LogFileName = $"{Guid.NewGuid:N}\\LogFile.txt";

listener.ShouldOverrideWriteLine = false;
listener.Fail("FAIL");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,7 @@ public class FilteringOptions
public EventLevel Level;
public IDictionary<string, string> Args;

public override string ToString()
{
return string.Format("<Options Keywords='{0}' Level'{1}' ArgsCount='{2}'",
((ulong)Keywords).ToString("x"), Level, Args.Count);
}
public override string ToString() => $"<Options Keywords='{(ulong)Keywords:x}' Level'{Level}' ArgsCount='{Args.Count}'";
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ public void TimesIncludeMillisecondPart()
// If it's the OS/Filesystem often returns 0 for the millisecond part, this may
// help prove it. This should only be written 1/1000 runs, unless the test is going to
// fail.
Console.WriteLine($"## TimesIncludeMillisecondPart got a file time of {time.ToString("o")} on {driveFormat}");
Console.WriteLine($"## TimesIncludeMillisecondPart got a file time of {time:o} on {driveFormat}");
item = GetExistingItem(); // try a new file/directory
}
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ protected void ReadOnly_FileSystemHelper(Action<string> testAction, string subDi
/// </remarks>
protected static bool GetIsCaseSensitiveByProbing(string probingDirectory)
{
string pathWithUpperCase = Path.Combine(probingDirectory, "CASESENSITIVETEST" + Guid.NewGuid().ToString("N"));
string pathWithUpperCase = Path.Combine(probingDirectory, $"CASESENSITIVETEST{Guid.NewGuid():N}");
using (new FileStream(pathWithUpperCase, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 0x1000, FileOptions.DeleteOnClose))
{
string lowerCased = pathWithUpperCase.ToLowerInvariant();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1388,7 +1388,7 @@ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage reques
}
}

private static string CreateFakeUri() => $"http://{Guid.NewGuid().ToString("N")}";
private static string CreateFakeUri() => $"http://{Guid.NewGuid():N}";

private static async Task<T> WhenCanceled<T>(CancellationToken cancellationToken)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ public void MaxResponseDrainSize_SetAfterUse_Throws()
using (HttpClient client = CreateHttpClient(handler))
{
handler.MaxResponseDrainSize = 1;
client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure
_ = client.GetAsync($"http://{Guid.NewGuid():N}"); // ignoring failure
Assert.Equal(1, handler.MaxResponseDrainSize);
Assert.Throws<InvalidOperationException>(() => handler.MaxResponseDrainSize = 1);
}
Expand Down Expand Up @@ -365,7 +365,7 @@ public void ResponseDrainTimeout_SetAfterUse_Throws()
using (HttpClient client = CreateHttpClient(handler))
{
handler.ResponseDrainTimeout = TimeSpan.FromSeconds(42);
client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure
_ = client.GetAsync($"http://{Guid.NewGuid():N}"); // ignoring failure
Assert.Equal(TimeSpan.FromSeconds(42), handler.ResponseDrainTimeout);
Assert.Throws<InvalidOperationException>(() => handler.ResponseDrainTimeout = TimeSpan.FromSeconds(42));
}
Expand Down Expand Up @@ -1175,7 +1175,7 @@ public void ConnectTimeout_SetAfterUse_Throws()
using (HttpClient client = CreateHttpClient(handler))
{
handler.ConnectTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure
_ = client.GetAsync($"http://{Guid.NewGuid():N}"); // ignoring failure
Assert.Equal(TimeSpan.FromMilliseconds(int.MaxValue), handler.ConnectTimeout);
Assert.Throws<InvalidOperationException>(() => handler.ConnectTimeout = TimeSpan.FromMilliseconds(1));
}
Expand Down Expand Up @@ -1222,7 +1222,7 @@ public void Expect100ContinueTimeout_SetAfterUse_Throws()
using (HttpClient client = CreateHttpClient(handler))
{
handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure
_ = client.GetAsync($"http://{Guid.NewGuid():N}"); // ignoring failure
Assert.Equal(TimeSpan.FromMilliseconds(int.MaxValue), handler.Expect100ContinueTimeout);
Assert.Throws<InvalidOperationException>(() => handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(1));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult)

internal HttpListenerContext? HandleAuthentication(HttpListenerSession session, RequestContextBase memoryBlob, out bool stoleBlob)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "HandleAuthentication() memoryBlob:0x" + ((IntPtr)memoryBlob.RequestBlob).ToString("x"));
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"HandleAuthentication() memoryBlob:0x{(IntPtr)memoryBlob.RequestBlob:x}");

string? challenge = null;
stoleBlob = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ internal HttpResponseStreamAsyncResult(object asyncObject, object? userState, As
{
_dataChunks = new Interop.HttpApi.HTTP_DATA_CHUNK[chunked ? 3 : 1];

if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "m_pOverlapped:0x" + ((IntPtr)_pOverlapped).ToString("x8"));
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"m_pOverlapped:0x{(IntPtr)_pOverlapped:x8}");

object[] objectsToPin = new object[1 + _dataChunks.Length];
objectsToPin[_dataChunks.Length] = _dataChunks;
Expand Down Expand Up @@ -227,7 +227,7 @@ private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlap
{
object state = ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!;
HttpResponseStreamAsyncResult asyncResult = (state as HttpResponseStreamAsyncResult)!;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "errorCode:0x" + errorCode.ToString("x8") + " numBytes:" + numBytes + " nativeOverlapped:0x" + ((IntPtr)nativeOverlapped).ToString("x8"));
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:0x{errorCode:x8} numBytes:{numBytes} nativeOverlapped:0x{(IntPtr)nativeOverlapped:x8}");

IOCompleted(asyncResult, errorCode, numBytes);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public void PrintCurrentResults(TimeSpan elapsed, bool showAggregatesOnly)
for (int i = 0; i < _currentCounters.Length; i++)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($"\tWorker #{i.ToString("N0")}:");
Console.Write($"\tWorker #{i:N0}:");
Console.ResetColor();

Console.ForegroundColor = ConsoleColor.Green;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ public static void InvalidArguments_Throw()
AssertExtensions.Throws<ArgumentNullException>("address", () => ServicePointManager.FindServicePoint((Uri)null, null));
Assert.Throws<NotSupportedException>(() => ServicePointManager.FindServicePoint("http://anything", new FixedWebProxy("https://anything")));
ServicePoint sp = ServicePointManager.FindServicePoint("http://" + Guid.NewGuid().ToString("N"), null);
ServicePoint sp = ServicePointManager.FindServicePoint($"http://{Guid.NewGuid():N}", null);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLeaseTimeout = -2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLimit = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.MaxIdleTime = -2);
Expand Down
6 changes: 3 additions & 3 deletions src/libraries/System.Net.WebProxy/tests/WebProxyTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public static IEnumerable<object[]> BypassOnLocal_MemberData()
// Local

yield return new object[] { new Uri($"http://nodotinhostname"), true };
yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}"), true };
yield return new object[] { new Uri($"http://{Guid.NewGuid():N}"), true };
foreach (IPAddress address in Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
Expand All @@ -209,7 +209,7 @@ public static IEnumerable<object[]> BypassOnLocal_MemberData()
if (!string.IsNullOrWhiteSpace(domain))
{
Uri uri = null;
try { uri = new Uri($"http://{Guid.NewGuid().ToString("N")}.{domain}"); }
try { uri = new Uri($"http://{Guid.NewGuid():N}.{domain}"); }
catch (UriFormatException) { }

if (uri != null)
Expand All @@ -220,7 +220,7 @@ public static IEnumerable<object[]> BypassOnLocal_MemberData()

// Non-local

yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}.com"), false };
yield return new object[] { new Uri($"http://{Guid.NewGuid():N}.com"), false };
yield return new object[] { new Uri($"http://{IPAddress.None}"), false };
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ public async Task ConnectAsync_CancellationRequestedBeforeConnect_ThrowsOperatio
{
var cts = new CancellationTokenSource();
cts.Cancel();
Task t = ConnectAsync(clientSocket, new Uri("ws://" + Guid.NewGuid().ToString("N")), cts.Token);
Task t = ConnectAsync(clientSocket, new Uri($"ws://{Guid.NewGuid():N}"), cts.Token);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t);
}
}
Expand All @@ -363,7 +363,7 @@ public async Task ConnectAsync_CancellationRequestedInflightConnect_ThrowsOperat
using (var clientSocket = new ClientWebSocket())
{
var cts = new CancellationTokenSource();
Task t = ConnectAsync(clientSocket, new Uri("ws://" + Guid.NewGuid().ToString("N")), cts.Token);
Task t = ConnectAsync(clientSocket, new Uri($"ws://{Guid.NewGuid():N}"), cts.Token);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ internal static void SetError(QilNode n, string message)
message = SR.Format(SR.Qil_Validation, message);

#if QIL_TRACE_NODE_CREATION
message += " ["+ n.NodeId + " (" + n.NodeType.ToString("G") + ")]";
message = "{message} [{n.NodeId} ({n.NodeType:G})]";
#endif
if (n.Annotation is string s)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -923,7 +923,7 @@ public static void Xml_DeserializeTypeWithEmptyDateTimeOffsetProperties()
public static void Xml_DeserializeDateTimeOffsetType()
{
var now = new DateTimeOffset(DateTime.Now);
string xml = @"<?xml version=""1.0""?><dateTimeOffset>" + now.ToString("o") + "</dateTimeOffset>";
string xml = $@"<?xml version=""1.0""?><dateTimeOffset>{now:o}</dateTimeOffset>";
XmlSerializer serializer = new XmlSerializer(typeof(DateTimeOffset));

using (StringReader reader = new StringReader(xml))
Expand Down
Loading

0 comments on commit 1a818ef

Please sign in to comment.