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

Enable culture analyzer and fix issues #3678

Merged
merged 23 commits into from
Jul 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
6 changes: 6 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,12 @@ dotnet_diagnostic.RS0041.severity = none # not default, decreased severity becau
# CA1824: Mark assemblies with NeutralResourcesLanguageAttribute
dotnet_diagnostic.CA1824.severity = warning # not default, increased severity to ensure it is applied

# CA1304: Specify CultureInfo
dotnet_diagnostic.CA1304.severity = warning # not default, increased severity to ensure it is applied

# CA1305: Specify IFormatProvider
dotnet_diagnostic.CA1305.severity = warning # not default, increased severity to ensure it is applied

#### C# Coding Conventions ####

# var preferences
Expand Down
5 changes: 3 additions & 2 deletions playground/TestPlatform.Playground/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
Expand Down Expand Up @@ -169,7 +170,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete

public void HandleLogMessage(TestMessageLevel level, string? message)
{
Console.WriteLine($"[DISCOVERY.{level.ToString().ToUpper()}] {message}");
Console.WriteLine($"[DISCOVERY.{level.ToString().ToUpper(CultureInfo.InvariantCulture)}] {message}");
}

public void HandleRawMessage(string rawMessage)
Expand Down Expand Up @@ -197,7 +198,7 @@ public TestRunHandler()

public void HandleLogMessage(TestMessageLevel level, string? message)
{
Console.WriteLine($"[{level.ToString().ToUpper()}]: {message}");
Console.WriteLine($"[{level.ToString().ToUpper(CultureInfo.InvariantCulture)}]: {message}");
}

public void HandleRawMessage(string rawMessage)
Expand Down
11 changes: 6 additions & 5 deletions src/AttachVS/AttachVs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
Expand Down Expand Up @@ -132,17 +133,17 @@ private static bool AttachVs(Process vs, int pid)
{
try
{
dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null);
lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null);
var lpn = (System.Collections.IEnumerator)lps.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, lps, null);
dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null, CultureInfo.InvariantCulture);
lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null, CultureInfo.InvariantCulture);
var lpn = (System.Collections.IEnumerator)lps.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, lps, null, CultureInfo.InvariantCulture);

while (lpn.MoveNext())
{
var pn = Convert.ToInt32(lpn.Current.GetType().InvokeMember("ProcessID", BindingFlags.GetProperty, null, lpn.Current, null));
var pn = Convert.ToInt32(lpn.Current.GetType().InvokeMember("ProcessID", BindingFlags.GetProperty, null, lpn.Current, null, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);

if (pn == pid)
{
lpn.Current.GetType().InvokeMember("Attach", BindingFlags.InvokeMethod, null, lpn.Current, null);
lpn.Current.GetType().InvokeMember("Attach", BindingFlags.InvokeMethod, null, lpn.Current, null, CultureInfo.InvariantCulture);
return true;
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/DataCollectors/DumpMinitool.x86/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;

using Microsoft.TestPlatform.Extensions.BlameDataCollector;
Expand All @@ -22,7 +23,7 @@ static int Main(string[] args)
}

var outputFile = args[1];
var processId = int.Parse(args[3]);
var processId = int.Parse(args[3], CultureInfo.InvariantCulture);
var dumpType = (MiniDumpTypeOption)Enum.Parse(typeof(MiniDumpTypeOption), args[5]);

Console.WriteLine($"Output file: '{outputFile}'");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public void OnEventLogEntryWritten(object? source, EntryWrittenEventArgs? e)
_dataCollectionLogger.LogWarning(
_dataCollectionContext,
string.Format(
CultureInfo.InvariantCulture,
CultureInfo.CurrentCulture,
Resource.EventsLostWarning,
EventLog.Log));

Expand Down Expand Up @@ -203,7 +203,7 @@ public void OnEventLogEntryWritten(object? source, EntryWrittenEventArgs? e)
_dataCollectionLogger.LogError(
_dataCollectionContext,
string.Format(
CultureInfo.InvariantCulture,
CultureInfo.CurrentCulture,
Resource.EventsLostError,
EventLog.Log,
exception), exception);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ private static void AssertSupport<T>(T obj, string methodName, string className)
{
if (obj == null)
{
throw new NotImplementedException(string.Format(Resources.Resources.MethodNotImplementedOnPlatform, className, methodName));
throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.MethodNotImplementedOnPlatform, className, methodName));
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.TestPlatform.Build/Tasks/VSTestTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public override bool Execute()
Console.WriteLine("Waiting for debugger attach...");

var currentProcess = Process.GetCurrentProcess();
Console.WriteLine(string.Format("Process Id: {0}, Name: {1}", currentProcess.Id, currentProcess.ProcessName));
Console.WriteLine($"Process Id: {currentProcess.Id}, Name: {currentProcess.ProcessName}");

while (!Debugger.IsAttached)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public void ConnectToClientAndProcessRequests(int port, ITestRequestManager test
Dispose();
throw new TimeoutException(
string.Format(
CultureInfo.CurrentUICulture,
CultureInfo.CurrentCulture,
CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage,
CoreUtilities.Constants.VstestConsoleProcessName,
"translation layer",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;

Expand Down Expand Up @@ -169,7 +170,7 @@ internal void OnTestSessionTimeout(object? obj)
{
EqtTrace.Verbose("TestRunRequest.OnTestSessionTimeout: calling cancellation as test run exceeded testSessionTimeout {0} milliseconds", _testSessionTimeout);

string message = string.Format(ClientResources.TestSessionTimeoutMessage, _testSessionTimeout);
string message = string.Format(CultureInfo.CurrentCulture, ClientResources.TestSessionTimeoutMessage, _testSessionTimeout);
var testMessagePayload = new TestMessagePayload { MessageLevel = TestMessageLevel.Error, Message = message };
var rawMessage = _dataSerializer.SerializePayload(MessageType.TestMessage, testMessagePayload);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ private static void Validate(FileTransferInformation fileTransferInfo, string lo
{
throw new FileNotFoundException(
string.Format(
CultureInfo.CurrentCulture,
CultureInfo.InvariantCulture,
"Could not find source file '{0}'.",
fileTransferInfo.FileName));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri

if (!IsUriValid(dataCollectorUri) && !TryGetUriFromFriendlyName(dataCollectorSettings.FriendlyName, out dataCollectorUri))
{
LogWarning(string.Format(CultureInfo.CurrentUICulture, Resources.Resources.UnableToFetchUriString, dataCollectorSettings.FriendlyName));
LogWarning(string.Format(CultureInfo.CurrentCulture, Resources.Resources.UnableToFetchUriString, dataCollectorSettings.FriendlyName));
Copy link
Member

Choose a reason for hiding this comment

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

What is the reason for changing this from ui culture to current culture?

Copy link
Member Author

Choose a reason for hiding this comment

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

The analyzer is complaining about it :)

Rule documentation says:

CultureInfo.CurrentUICulture is used only to retrieve localized resources by using an instance of the System.Resources.ResourceManager class.

}

ObjectModel.DataCollection.DataCollector? dataCollector = null;
Expand All @@ -497,7 +497,7 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri

if (dataCollector == null)
{
LogWarning(string.Format(CultureInfo.CurrentUICulture, Resources.Resources.DataCollectorNotFound, dataCollectorSettings.FriendlyName));
LogWarning(string.Format(CultureInfo.CurrentCulture, Resources.Resources.DataCollectorNotFound, dataCollectorSettings.FriendlyName));
return;
}

Expand Down Expand Up @@ -527,7 +527,7 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri
EqtTrace.Error("DataCollectionManager.LoadAndInitialize: exception while creating data collector {0} : {1}", dataCollectorSettings.FriendlyName, ex);

// No data collector info, so send the error with no direct association to the collector.
LogWarning(string.Format(CultureInfo.CurrentUICulture, Resources.Resources.DataCollectorInitializationError, dataCollectorSettings.FriendlyName, ex));
LogWarning(string.Format(CultureInfo.CurrentCulture, Resources.Resources.DataCollectorInitializationError, dataCollectorSettings.FriendlyName, ex));
return;
}

Expand Down Expand Up @@ -570,7 +570,7 @@ private List<DataCollectorSettings> GetDataCollectorsEnabledForRun(DataCollectio
if (runEnabledDataCollectors.Any(dcSettings => string.Equals(dcSettings.FriendlyName, settings.FriendlyName, StringComparison.OrdinalIgnoreCase)))
{
// If Uri or assembly qualified type name is repeated, consider data collector as duplicate and ignore it.
LogWarning(string.Format(CultureInfo.CurrentUICulture, Resources.Resources.IgnoredDuplicateConfiguration, settings.FriendlyName));
LogWarning(string.Format(CultureInfo.CurrentCulture, Resources.Resources.IgnoredDuplicateConfiguration, settings.FriendlyName));
continue;
}

Expand Down Expand Up @@ -689,7 +689,7 @@ private void AddCollectorEnvironmentVariables(
{
// Data collector is overriding an already requested variable, possibly an error.
var message = string.Format(
CultureInfo.CurrentUICulture,
CultureInfo.CurrentCulture,
Resources.Resources.DataCollectorRequestedDuplicateEnvironmentVariable,
collectorFriendlyName,
namevaluepair.Key,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,6 @@ private static Guid GetProfilerGuid(string profilerGuid)

private static string GetTelemetryKey(string telemetryPrefix, DataCollectorInformation dataCollectorInformation)
{
return string.Format("{0}.{1}", telemetryPrefix, dataCollectorInformation.DataCollectorConfig?.TypeUri?.ToString());
return $"{telemetryPrefix}.{dataCollectorInformation.DataCollectorConfig?.TypeUri}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ private void PopulateMap()
{
_logger.SendMessage(
TestMessageLevel.Warning,
string.Format(CultureInfo.CurrentUICulture, CommonResources.InvalidExtensionUriFormat, extension.Metadata.ExtensionUri, e));
string.Format(CultureInfo.CurrentCulture, CommonResources.InvalidExtensionUriFormat, extension.Metadata.ExtensionUri, e));
}
}

Expand All @@ -170,7 +170,7 @@ private void PopulateMap()
{
_logger.SendMessage(
TestMessageLevel.Warning,
string.Format(CultureInfo.CurrentUICulture, CommonResources.DuplicateExtensionUri, extension.Metadata.ExtensionUri));
string.Format(CultureInfo.CurrentCulture, CommonResources.DuplicateExtensionUri, extension.Metadata.ExtensionUri));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ private void GetTestExtensionsFromFiles<TPluginInfo, TExtension>(
catch (FileLoadException e)
{
EqtTrace.Warning("TestPluginDiscoverer-FileLoadException: Failed to load extensions from file '{0}'. Skipping test extension scan for this file. Error: {1}", file, e);
string fileLoadErrorMessage = string.Format(CultureInfo.CurrentUICulture, CommonResources.FailedToLoadAdapaterFile, file);
string fileLoadErrorMessage = string.Format(CultureInfo.CurrentCulture, CommonResources.FailedToLoadAdapaterFile, file);
TestSessionMessageLogger.Instance.SendMessage(TestMessageLevel.Warning, fileLoadErrorMessage);
UnloadableFiles.Add(file);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ protected SettingsProviderExtensionManager(
_logger.SendMessage(
TestMessageLevel.Error,
string.Format(
CultureInfo.CurrentUICulture,
CultureInfo.CurrentCulture,
CommonResources.DuplicateSettingsName,
settingsName));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public static void UpdateRunSettingsNodeInnerXml(this IRunSettingsProvider runSe
internal static XmlNode? GetXmlNode(XmlDocument xmlDocument, string key)
{
var xPath = key.Replace('.', '/');
var node = xmlDocument.SelectSingleNode(string.Format("//RunSettings/{0}", xPath));
var node = xmlDocument.SelectSingleNode($"//RunSettings/{xPath}");
return node;
}

Expand Down
25 changes: 15 additions & 10 deletions src/Microsoft.TestPlatform.Common/Utilities/SimpleJSON.cs
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ public virtual long AsLong
}
set
{
Value = value.ToString();
Value = value.ToString(CultureInfo.InvariantCulture);
}
}

Expand All @@ -340,7 +340,7 @@ public virtual ulong AsULong
}
set
{
Value = value.ToString();
Value = value.ToString(CultureInfo.InvariantCulture);
}
}

Expand Down Expand Up @@ -403,7 +403,7 @@ public static implicit operator int(JSONNode d)

public static implicit operator JSONNode(long n)
{
return LongAsString ? new JSONString(n.ToString()) : new JSONNumber(n);
return LongAsString ? new JSONString(n.ToString(CultureInfo.InvariantCulture)) : new JSONNumber(n);
}
public static implicit operator long(JSONNode d)
{
Expand All @@ -412,7 +412,7 @@ public static implicit operator long(JSONNode d)

public static implicit operator JSONNode(ulong n)
{
return LongAsString ? new JSONString(n.ToString()) : new JSONNumber(n);
return LongAsString ? new JSONString(n.ToString(CultureInfo.InvariantCulture)) : new JSONNumber(n);
}
public static implicit operator ulong(JSONNode d)
{
Expand Down Expand Up @@ -505,7 +505,7 @@ internal static string Escape(string aText)
if (c < ' ' || (ForceASCII && c > 127))
{
ushort val = c;
sb.Append("\\u").Append(val.ToString("X4"));
sb.Append("\\u").Append(val.ToString("X4", CultureInfo.InvariantCulture));
}
else
sb.Append(c);
Expand All @@ -523,7 +523,11 @@ private static JSONNode ParseElement(string token, bool quoted)
return token;
if (token.Length <= 5)
{
string tmp = token.ToLower();
string tmp = token.ToLower(
#if !NETSTANDARD1_3
CultureInfo.InvariantCulture
#endif
);
if (tmp is "false" or "true")
return tmp == "true";
if (tmp == "null")
Expand Down Expand Up @@ -674,7 +678,8 @@ public static JSONNode Parse(string aJSON)
string s = aJSON.Substring(i + 1, 4);
token.Append((char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier));
System.Globalization.NumberStyles.AllowHexSpecifier,
CultureInfo.InvariantCulture));
i += 4;
break;
}
Expand Down Expand Up @@ -1124,7 +1129,7 @@ public override bool Equals(object obj)
if (base.Equals(obj))
return true;
JSONNumber s2 = obj as JSONNumber;
return s2 != null ? _data == s2._data : IsNumeric(obj) && Convert.ToDouble(obj) == _data;
return s2 != null ? _data == s2._data : IsNumeric(obj) && Convert.ToDouble(obj, CultureInfo.InvariantCulture) == _data;
}
public override int GetHashCode()
{
Expand Down Expand Up @@ -1342,7 +1347,7 @@ public override long AsLong
set
{
if (LongAsString)
Set(new JSONString(value.ToString()));
Set(new JSONString(value.ToString(CultureInfo.InvariantCulture)));
else
Set(new JSONNumber(value));
}
Expand All @@ -1361,7 +1366,7 @@ public override ulong AsULong
set
{
if (LongAsString)
Set(new JSONString(value.ToString()));
Set(new JSONString(value.ToString(CultureInfo.InvariantCulture)));
else
Set(new JSONNumber(value));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ private void HandleBeforeTestRunStart(Message message)
_dataCollectionTestCaseEventHandler.Close();
throw new TestPlatformException(
string.Format(
CultureInfo.CurrentUICulture,
CultureInfo.CurrentCulture,
CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage,
CoreUtilitiesConstants.DatacollectorProcessName,
CoreUtilitiesConstants.TesthostProcessName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;

using Microsoft.VisualStudio.TestPlatform.ObjectModel;

Expand Down Expand Up @@ -84,7 +85,7 @@ public override bool CanConvert(Type objectType)
case "TestCase.CodeFilePath":
testCase.CodeFilePath = propertyData; break;
case "TestCase.LineNumber":
testCase.LineNumber = int.Parse(propertyData!); break;
testCase.LineNumber = int.Parse(propertyData!, CultureInfo.CurrentCulture); break;
default:
// No need to register member properties as they get registered as part of TestCaseProperties class.
testProperty = TestProperty.Register(testProperty.Id, testProperty.Label, testProperty.GetValueType(), testProperty.Attributes, typeof(TestObject));
Expand Down
Loading