Skip to content
Closed
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 @@ -951,7 +951,7 @@ internal void AddSessionToCache(CimSession cimSession, XOperationContextBase con
CimTestCimSessionContext testCimSessionContext = context as CimTestCimSessionContext;
uint sessionId = this.sessionState.GenerateSessionId();
string originalSessionName = testCimSessionContext.CimSessionWrapper.Name;
string sessionName = originalSessionName ?? string.Format(CultureInfo.CurrentUICulture, @"{0}{1}", CimSessionState.CimSessionClassName, sessionId);
Copy link
Collaborator

@iSazonov iSazonov Jan 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Really we should replace all string.Format with string.Create

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow up PR?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, current changes haven't value. Idea is to use new API to reduce allocations. There is no string.Format with interpalated string handler. I guess I misled you. Please use string.Create.
(You can find all new APIs with interpolated handlers starting with https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/InterpolatedStringHandlerAttribute.cs,382762ca0bf5bcac,references)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also please don't change our trace.WriteLine() and other such callsites - this requires changes in the APIs themselves, which is not always easy. See example #18246.

string sessionName = originalSessionName ?? string.Create(CultureInfo.CurrentUICulture, $"{CimSessionState.CimSessionClassName}{sessionId}");

// detach CimSession from the proxy object
CimSession createdCimSession = testCimSessionContext.Proxy.Detach();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -875,7 +875,7 @@ internal void WriteOperationStartMessage(string operation, Hashtable parameterLi
parameters.Append(',');
}

parameters.Append(string.Format(CultureInfo.CurrentUICulture, @"'{0}' = {1}", key, parameterList[key]));
parameters.AppendFormat(CultureInfo.CurrentUICulture, $@"'{key}' = {parameterList[key]}");
}
}

Expand Down Expand Up @@ -1232,7 +1232,7 @@ public void EnumerateInstancesAsync(string namespaceName, string className)
this.operationParameters.Add(@"className", className);
this.WriteOperationStartMessage(this.operationName, this.operationParameters);
CimAsyncMultipleResults<CimInstance> asyncResult = this.CimSession.EnumerateInstancesAsync(namespaceName, className, this.OperationOptions);
string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className);
string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}");
ConsumeCimInstanceAsync(asyncResult, new CimResultContext(errorSource));
}

Expand Down Expand Up @@ -1314,7 +1314,7 @@ public void EnumerateClassesAsync(string namespaceName, string className)
this.operationParameters.Add(@"className", className);
this.WriteOperationStartMessage(this.operationName, this.operationParameters);
CimAsyncMultipleResults<CimClass> asyncResult = this.CimSession.EnumerateClassesAsync(namespaceName, className, this.OperationOptions);
string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className);
string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}");
ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource));
}

Expand All @@ -1334,7 +1334,7 @@ public void GetClassAsync(string namespaceName, string className)
this.operationParameters.Add(@"className", className);
this.WriteOperationStartMessage(this.operationName, this.operationParameters);
CimAsyncResult<CimClass> asyncResult = this.CimSession.GetClassAsync(namespaceName, className, this.OperationOptions);
string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className);
string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}");
ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource));
}

Expand Down Expand Up @@ -1388,7 +1388,7 @@ public void InvokeMethodAsync(
this.operationParameters.Add(@"methodName", methodName);
this.WriteOperationStartMessage(this.operationName, this.operationParameters);
CimAsyncMultipleResults<CimMethodResultBase> asyncResult = this.CimSession.InvokeMethodAsync(namespaceName, className, methodName, methodParameters, this.OperationOptions);
string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className);
string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}");
ConsumeCimInvokeMethodResultAsync(asyncResult, className, methodName, new CimResultContext(errorSource));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ protected override object GetSourceObject()
case CimBaseCommand.ClassNameComputerSet:
// validate the classname
this.CheckArgument();
tempQueryExpression = string.Format(CultureInfo.CurrentCulture, "Select * from {0}", this.ClassName);
tempQueryExpression = string.Create(CultureInfo.CurrentCulture, $"Select * from {this.ClassName}");
break;
}

Expand Down
8 changes: 3 additions & 5 deletions src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -201,16 +201,14 @@ internal static string GetSourceCodeInformation(bool withFileName, int depth)
StackFrame frame = trace.GetFrame(depth);
// if (withFileName)
// {
// return string.Format(CultureInfo.CurrentUICulture, "{0}#{1}:{2}:", frame.GetFileName()., frame.GetFileLineNumber(), frame.GetMethod().Name);
// return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetFileName().}#{frame.GetFileLineNumber()}:{frame.GetMethod().Name}:");
// }
// else
// {
// return string.Format(CultureInfo.CurrentUICulture, "{0}:", frame.GetMethod());
// return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetMethod()}:");
// }

return string.Format(CultureInfo.CurrentUICulture, "{0}::{1} ",
frame.GetMethod().DeclaringType.Name,
frame.GetMethod().Name);
return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetMethod().DeclaringType.Name}::{frame.GetMethod().Name} ");
}
#endregion

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ private static string AddIndent(string str, string indentString)
foreach (string line in lines)
{
// Indentation is not localized
returnValue.AppendFormat("{0}{1}\r\n", indentString, line);
returnValue.AppendFormat($"{indentString}{line}\r\n");
}

if (returnValue.Length > 2)
Expand Down Expand Up @@ -369,7 +369,7 @@ private void AddSyntax(bool setting, string sectionTitle)
continue;
}

string commandStart = string.Format(CultureInfo.CurrentCulture, "{0} ", commandName);
string commandStart = string.Create(CultureInfo.CurrentCulture, $"{commandName} ");
this.AddText(HelpParagraphBuilder.AddIndent(commandStart), false);

foreach (object parameterObj in parameterObjs)
Expand All @@ -389,7 +389,7 @@ private void AddSyntax(bool setting, string sectionTitle)
continue;
}

string parameterType = parameterValue == null ? string.Empty : string.Format(CultureInfo.CurrentCulture, "<{0}>", parameterValue);
string parameterType = parameterValue == null ? string.Empty : string.Create(CultureInfo.CurrentCulture, $"<{parameterValue}>");

string parameterOptionalOpenBrace, parameterOptionalCloseBrace;

Expand Down Expand Up @@ -607,7 +607,7 @@ private void AddMembers(bool setting, string sectionTitle)
description = GetPropertyString(propertyTypeObject, "description");
}

memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}\r\n", propertyType, name);
memberText = string.Create(CultureInfo.CurrentCulture, $" [{propertyType}] {name}\r\n");
}
}
else if (string.Equals("method", type, StringComparison.OrdinalIgnoreCase))
Expand Down Expand Up @@ -697,7 +697,7 @@ private static void FormatMethodData(PSObject member, string name, out string me
}
}

string paramString = string.Format(CultureInfo.CurrentCulture, "[{0}] ${1},", parameterType, parameterName);
string paramString = string.Create(CultureInfo.CurrentCulture, $"[{parameterType}] ${parameterName},");

parameterText.Append(paramString);
}
Expand All @@ -709,7 +709,7 @@ private static void FormatMethodData(PSObject member, string name, out string me
}
}

memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}({2})\r\n", returnType, name, parameterText);
memberText = string.Create(CultureInfo.CurrentCulture, $" [{returnType}] {name}({parameterText})\r\n");
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ protected override DataErrorInfoValidationResult Validate(string columnName)
{
if (!columnName.Equals(SelectedIndexPropertyName, StringComparison.CurrentCulture))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not a valid column name.", columnName), "columnName");
throw new ArgumentException(string.Create(CultureInfo.CurrentCulture, $"{columnName} is not a valid column name."), "columnName");
}

if (!this.IsIndexWithinBounds(this.SelectedIndex))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ internal DataErrorInfoValidationResult EvaluateValidationRules(object value, Sys
DataErrorInfoValidationResult result = rule.Validate(value, cultureInfo);
if (result == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "DataErrorInfoValidationResult not returned by ValidationRule: {0}", rule.ToString()));
throw new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"DataErrorInfoValidationResult not returned by ValidationRule: {rule}"));
}

if (!result.IsValid)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ protected virtual string GetPattern()
patterns.Add(rule.Pattern);
}

patterns.Add(string.Format(CultureInfo.InvariantCulture, "(?<{0}>){1}", FullTextRuleGroupName, ValuePattern));
patterns.Add(string.Create(CultureInfo.InvariantCulture, $"(?<{FullTextRuleGroupName}>){ValuePattern}"));

return string.Join("|", patterns.ToArray());
}
Expand Down Expand Up @@ -199,7 +199,7 @@ public SearchableRule(string uniqueId, SelectorFilterRule selectorFilterRule, Te
this.UniqueId = uniqueId;
this.selectorFilterRule = selectorFilterRule;
this.childRule = childRule;
this.Pattern = string.Format(CultureInfo.InvariantCulture, "(?<{0}>){1}\\s*:\\s*{2}", uniqueId, Regex.Escape(selectorFilterRule.DisplayName), SearchTextParser.ValuePattern);
this.Pattern = string.Create(CultureInfo.InvariantCulture, $"(?<{uniqueId}>){Regex.Escape(selectorFilterRule.DisplayName)}\\s*:\\s*{SearchTextParser.ValuePattern}");
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,7 @@ private string GetClipboardTextLineForSelectedItem(object value)
propertyValue = string.Empty;
}

entryText.AppendFormat(CultureInfo.CurrentCulture, "{0}\t", propertyValue);
entryText.AppendFormat(CultureInfo.CurrentCulture, $"{propertyValue}\t");
}

return entryText.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public object Convert(object value, Type targetType, object parameter, System.Gl
}

string name = (!string.IsNullOrEmpty(cvg.Name.ToString())) ? cvg.Name.ToString() : UICultureResources.GroupTitleNone;
string display = string.Format(CultureInfo.CurrentCulture, "{0} ({1})", name, cvg.ItemCount);
string display = string.Create(CultureInfo.CurrentCulture, $"{name} ({cvg.ItemCount})");

return display;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private void ButtonBrowse_Click(object sender, RoutedEventArgs e)

foreach (object selectedItem in multipleSelectionDialog.listboxParameter.SelectedItems)
{
newComboText.AppendFormat(CultureInfo.InvariantCulture, "{0},", selectedItem.ToString());
newComboText.AppendFormat(CultureInfo.InvariantCulture, $"{selectedItem.},");
}

if (newComboText.Length > 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private static CheckBox CreateCheckBox(ParameterViewModel parameterViewModel, in
//// Add AutomationProperties.AutomationId for Ui Automation test.
checkBox.SetValue(
System.Windows.Automation.AutomationProperties.AutomationIdProperty,
string.Format(CultureInfo.CurrentCulture, "chk{0}", parameterViewModel.Name));
string.Create(CultureInfo.CurrentCulture, $"chk{parameterViewModel.Name}"));

checkBox.SetValue(
System.Windows.Automation.AutomationProperties.NameProperty,
Expand Down Expand Up @@ -164,7 +164,7 @@ private static MultipleSelectionControl CreateMultiSelectComboControl(ParameterV
multiControls.comboxParameter.SetBinding(ComboBox.TextProperty, valueBinding);

// Add AutomationProperties.AutomationId for Ui Automation test.
multiControls.SetValue(System.Windows.Automation.AutomationProperties.AutomationIdProperty, string.Format("combox{0}", parameterViewModel.Name));
multiControls.SetValue(System.Windows.Automation.AutomationProperties.AutomationIdProperty, string.Create($"combox{parameterViewModel.Name}"));

multiControls.comboxParameter.SetValue(
System.Windows.Automation.AutomationProperties.NameProperty,
Expand Down Expand Up @@ -206,7 +206,7 @@ private static TextBox CreateTextBoxControl(ParameterViewModel parameterViewMode
//// Add AutomationProperties.AutomationId for UI Automation test.
textBox.SetValue(
System.Windows.Automation.AutomationProperties.AutomationIdProperty,
string.Format(CultureInfo.CurrentCulture, "txt{0}", parameterViewModel.Name));
string.Create(CultureInfo.CurrentCulture, $"txt{parameterViewModel.Name}"));

textBox.SetValue(
System.Windows.Automation.AutomationProperties.NameProperty,
Expand Down Expand Up @@ -397,7 +397,7 @@ private Label CreateLabel(ParameterViewModel parameterViewModel, int rowNumber)
//// Add AutomationProperties.AutomationId for Ui Automation test.
label.SetValue(
System.Windows.Automation.AutomationProperties.AutomationIdProperty,
string.Format(CultureInfo.CurrentCulture, "lbl{0}", parameterViewModel.Name));
string.Create(CultureInfo.CurrentCulture, $"lbl{parameterViewModel.Name}"));

return label;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ public string GetScript()

if (commandName.Contains(' '))
{
builder.AppendFormat("& \"{0}\"", commandName);
builder.AppendFormat($"& \"{commandName}\"");
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public string GetScript()
{
if (((bool?)parameter.Value) == true)
{
builder.AppendFormat("-{0} ", parameter.Name);
builder.AppendFormat($"-{parameter.Name} ");
}

continue;
Expand Down Expand Up @@ -166,7 +166,7 @@ public string GetScript()
parameterValueString = ParameterSetViewModel.GetDelimitedParameter(parameterValueString, "(", ")");
}

builder.AppendFormat("-{0} {1} ", parameter.Name, parameterValueString);
builder.AppendFormat($"-{parameter.Name} {parameterValueString} ");
}

return builder.ToString().Trim();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public string NameCheckLabel
string returnValue = this.Parameter.Name;
if (this.Parameter.IsMandatory)
{
returnValue = string.Format(CultureInfo.CurrentUICulture, "{0}{1}", returnValue, ShowCommandResources.MandatoryLabelSegment);
returnValue = string.Create(CultureInfo.CurrentUICulture, $"{returnValue}{ShowCommandResources.MandatoryLabelSegment}");
}

return returnValue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ protected override void ProcessRecord()
break;

default:
Debug.Fail(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName));
Debug.Fail(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}"));
break;
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ protected override void ProcessRecord()
break;

default:
WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName));
WriteDebug(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}"));
break;
}
}
Expand Down Expand Up @@ -492,7 +492,7 @@ private void ProcessGetProvider()
foreach (string log in _providersByLogMap.Keys)
{
logQuery = new EventLogQuery(log, PathType.LogName, AddProviderPredicatesToFilter(_providersByLogMap[log]));
WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Log {0} will be queried", log));
WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Log {log} will be queried"));
}
}

Expand Down Expand Up @@ -680,7 +680,7 @@ private void ProcessFile()
foreach (string resolvedPath in resolvedPaths)
{
_resolvedPaths.Add(resolvedPath);
WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found file {0}", resolvedPath));
WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Found file {resolvedPath}"));
}
}

Expand Down Expand Up @@ -908,7 +908,7 @@ private string BuildStructuredQuery(EventLogSession eventLogSession)
break;

default:
WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName));
WriteDebug(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}"));
break;
}

Expand Down Expand Up @@ -2047,7 +2047,7 @@ private void FindProvidersByLogForWildcardPatterns(EventLogSession eventLogSessi
||
(wildProvPattern.IsMatch(provName)))
{
WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found matching provider: {0}", provName));
WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Found matching provider: {provName}"));
AddLogsForProviderToInternalMap(eventLogSession, provName);
bMatched = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ protected override void EndProcessing()
break;

default:
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName));
Debug.Assert(false, $"Invalid parameter set name: {ParameterSetName}");
break;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ private static string GetHalVersion(CimSession session, string systemDirectory)
try
{
var halPath = CIMHelper.EscapePath(System.IO.Path.Combine(systemDirectory, "hal.dll"));
var query = string.Format("SELECT * FROM CIM_DataFile Where Name='{0}'", halPath);
var query = string.Format($"SELECT * FROM CIM_DataFile Where Name='{halPath}'");
var instance = session.QueryFirstInstance(query);

if (instance != null)
Expand Down
Loading