Skip to content

Commit

Permalink
.NET 8 Upgrade Silenced Errors Fix (#30469)
Browse files Browse the repository at this point in the history
* [Dev][Build] .NET 8 Upgrade Silenced errors first fix.

* [Dev][Build] .NET 8 Upgrade Silenced errors. CA1859

* [Dev][Build] .NET 8 Upgrade Silenced errors. CA1854.

* [Dev][Build] .NET 8 Upgrade Silenced errors. CA1860

* [Dev][Build] .NET 8 Upgrade Silenced errors. CA1861

* [Dev][Build] .NET 8 Upgrade Silenced errors. CA1862

* [Dev][Build] .NET 8 Upgrade Silenced errors. CA1863

* [Dev][Build] .NET 8 Upgrade Silenced errors. CA1864

* [Dev][Build] .NET 8 Upgrade Silenced errors. CA1865

* [Dev][Build] .NET 8 Upgrade Silenced errors. CA2208

* [Dev][Build] .NET 8 Upgrade Silenced errors. CS9191

* [Dev][Build] .NET 8 Upgrade Silenced errors. Spell check

* [Dev][Build] .NET 8 Upgrade Silenced errors. Spell check

* [Dev][Build] .NET 8 Upgrade Silenced errors.
- CompositeFormat variables used more than once in the same file were assigned to a single variable.
- GetProcessesByName logic fix.
- String comparion fix.
- ArgumentOutOfRangeException message change.

* [Dev][Build] .NET 8 Upgrade Silenced errors.
- Null check added.
- static readonly CompositeFormat added for all fields.
  • Loading branch information
gokcekantarci authored Dec 28, 2023
1 parent cd57659 commit a94b3ee
Show file tree
Hide file tree
Showing 112 changed files with 429 additions and 291 deletions.
47 changes: 1 addition & 46 deletions src/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -96,49 +96,4 @@ end_of_line = crlf
dotnet_diagnostic.IDE0065.severity = none

# IDE0009: Add this or Me qualification
dotnet_diagnostic.IDE0009.severity = none

# CA1859: Change type for improved performance
dotnet_diagnostic.CA1859.severity = none

# CA1716: Identifiers should not match keywords
dotnet_diagnostic.CA1716.severity = none

# SYSLIB1096: Convert to 'GeneratedComInterface'
dotnet_diagnostic.SYSLIB1096.severity = silent

# CA1309: Use ordinal StringComparison
dotnet_diagnostic.CA1309.severity = suggestion

# CS1615: Argument may not be passed with the ref keyword
dotnet_diagnostic.CS1615.severity = none

# CA1854: Prefer a 'TryGetValue' call over a Dictionary indexer access guarded by a 'ContainsKey' check to avoid double lookup
dotnet_diagnostic.CA1854.severity = suggestion

# CA1860: Avoid using 'Enumerable.Any()' extension method
dotnet_diagnostic.CA1860.severity = suggestion

# CA1861: Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array
dotnet_diagnostic.CA1861.severity = suggestion

# CA1862: Prefer using 'StringComparer'/'StringComparison' to perform case-insensitive string comparisons
dotnet_diagnostic.CA1862.severity = suggestion

# CA1863: Cache a CompositeFormat for repeated use in this formatting operation
dotnet_diagnostic.CA1863.severity = none

# CA1864: Prefer the 'IDictionary.TryAdd(TKey, TValue)' method
dotnet_diagnostic.CA1864.severity = suggestion

# CA1865: Use 'string.Method(char)' instead of 'string.Method(string)' for string with single char
dotnet_diagnostic.CA1865.severity = suggestion

# CA1869: Cache and reuse 'JsonSerializerOptions' instances
dotnet_diagnostic.CA1869.severity = none

# CA2208: Instantiate argument exceptions correctly
dotnet_diagnostic.CA2208.severity = none

# CS9191: The 'ref' modifier for argument corresponding to 'in' is equivalent to 'in'. Consider using 'in' instead.
dotnet_diagnostic.CS9191.severity = none
dotnet_diagnostic.IDE0009.severity = none
2 changes: 1 addition & 1 deletion src/common/AllExperiments/Experiments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ private async Task VariantAssignmentProvider_Initialize()

private string? AssignmentUnit { get; set; }

private IVariantAssignmentRequest GetVariantAssignmentRequest()
private VariantAssignmentRequest GetVariantAssignmentRequest()
{
var jsonFilePath = CreateFilePath();
try
Expand Down
12 changes: 7 additions & 5 deletions src/common/FilePreviewCommon/Formatters/JsonFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ public class JsonFormatter : IFormatter
/// <inheritdoc/>
public string LangSet => "json";

private static readonly JsonSerializerOptions _serializerOptions = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};

/// <inheritdoc/>
public string Format(string value)
{
Expand All @@ -22,11 +28,7 @@ public string Format(string value)

using (var jDocument = JsonDocument.Parse(value, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }))
{
return JsonSerializer.Serialize(jDocument, new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
});
return JsonSerializer.Serialize(jDocument, _serializerOptions);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/modules/Hosts/Hosts/Settings/UserSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class UserSettings : IUserSettings
private const string HostsModuleName = "Hosts";
private const int MaxNumberOfRetry = 5;

private readonly ISettingsUtils _settingsUtils;
private readonly SettingsUtils _settingsUtils;
private readonly IFileSystemWatcher _watcher;
private readonly object _loadingSettingsLock = new object();

Expand Down
10 changes: 7 additions & 3 deletions src/modules/MouseWithoutBorders/App/Class/Common.Clipboard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ internal partial class Common
private static string lastDragDropFile;
private static long clipboardCopiedTime;

internal static readonly char[] Comma = new char[] { ',' };
internal static readonly char[] Star = new char[] { '*' };
internal static readonly char[] NullSeparator = new char[] { '\0' };

internal static ID LastIDWithClipboardData { get; set; }

internal static string LastDragDropFile
Expand Down Expand Up @@ -406,7 +410,7 @@ private static void ConnectAndGetData(object postAction)

try
{
remoteMachine = postAct.Contains("mspaint,") ? postAct.Split(new char[] { ',' })[1] : Common.LastMachineWithClipboardData;
remoteMachine = postAct.Contains("mspaint,") ? postAct.Split(Comma)[1] : Common.LastMachineWithClipboardData;

remoteMachine = remoteMachine.Trim();

Expand Down Expand Up @@ -518,7 +522,7 @@ internal static void ReceiveAndProcessClipboardData(string remoteMachine, Socket

fileName = Common.GetStringU(header).Replace("\0", string.Empty);
Common.LogDebug("Header: " + fileName);
string[] headers = fileName.Split(new char[] { '*' });
string[] headers = fileName.Split(Star);

if (headers.Length < 2 || !long.TryParse(headers[0], out long dataSize))
{
Expand Down Expand Up @@ -973,7 +977,7 @@ internal static void SetClipboardData(byte[] data)

foreach (string txt in texts)
{
if (string.IsNullOrEmpty(txt.Trim(new char[] { '\0' })))
if (string.IsNullOrEmpty(txt.Trim(NullSeparator)))
{
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ namespace MouseWithoutBorders
{
internal partial class Common
{
private static SymmetricAlgorithm symAl;
#pragma warning disable SYSLIB0021
private static AesCryptoServiceProvider symAl;
#pragma warning restore SYSLIB0021
private static string myKey;
private static uint magicNumber;
private static Random ran = new(); // Used for non encryption related functionality.
Expand Down
8 changes: 5 additions & 3 deletions src/modules/MouseWithoutBorders/App/Class/Common.Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,8 @@ internal static void RunDDHelper(bool cleanUp = false)
HasSwitchedMachineSinceLastCopy = true;

// Common.CreateLowIntegrityProcess("\"" + Path.GetDirectoryName(Application.ExecutablePath) + "\\MouseWithoutBordersHelper.exe\"", string.Empty, 0, false, 0);
if (Process.GetProcessesByName(HelperProcessName)?.Any() != true)
var processes = Process.GetProcessesByName(HelperProcessName);
if (processes?.Length == 0)
{
Log("Unable to start helper process.");
Common.ShowToolTip("Error starting Mouse Without Borders Helper, clipboard sharing will not work!", 5000, ToolTipIcon.Error);
Expand All @@ -325,7 +326,8 @@ internal static void RunDDHelper(bool cleanUp = false)
}
else
{
if (Process.GetProcessesByName(HelperProcessName)?.Any() == true)
var processes = Process.GetProcessesByName(HelperProcessName);
if (processes?.Length > 0)
{
Log("Helper process found running.");
}
Expand Down Expand Up @@ -432,7 +434,7 @@ internal static bool GetUserName()
{
if (string.IsNullOrEmpty(Setting.Values.Username) && !Common.RunOnLogonDesktop)
{
if (Program.User.ToLower(CultureInfo.CurrentCulture).Contains("system"))
if (Program.User.Contains("system", StringComparison.CurrentCultureIgnoreCase))
{
_ = Common.ImpersonateLoggedOnUserAndDoSomething(() =>
{
Expand Down
3 changes: 1 addition & 2 deletions src/modules/MouseWithoutBorders/App/Class/Common.Launch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,11 @@ internal static bool ImpersonateLoggedOnUserAndDoSomething(Action targetFunc)
}
}

[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "Dotnet port with style preservation")]
internal static int CreateProcessInInputDesktopSession(string commandLine, string arg, string desktop, short wShowWindow, bool lowIntegrity = false)

// As user who runs explorer.exe
{
if (!Program.User.ToLower(CultureInfo.InvariantCulture).Contains("system"))
if (!Program.User.Contains("system", StringComparison.InvariantCultureIgnoreCase))
{
ProcessStartInfo s = new(commandLine, arg);
s.WindowStyle = wShowWindow != 0 ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ internal static void StartMouseWithoutBordersService(string desktopToRunMouseWit
{
Process[] ps = Process.GetProcessesByName("MouseWithoutBordersSvc");

if (ps.Any())
if (ps.Length != 0)
{
if (DateTime.UtcNow - lastStartServiceTime < TimeSpan.FromSeconds(5))
{
Expand Down
3 changes: 2 additions & 1 deletion src/modules/MouseWithoutBorders/App/Class/InputSimulation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ internal static void MouseClickDotForm(int x, int y)
private static bool ctrlDown;
private static bool altDown;
private static bool shiftDown;
internal static readonly string[] Args = new string[] { "CAD" };

private static void ResetModifiersState(HotkeySettings matchingHotkey)
{
Expand Down Expand Up @@ -456,7 +457,7 @@ private static void InputProcessKeyEx(int vkCode, int flags, out bool eatKey)
if (ctrlDown && altDown)
{
ctrlDown = altDown = false;
new ServiceController("MouseWithoutBordersSvc").Start(new string[] { "CAD" });
new ServiceController("MouseWithoutBordersSvc").Start(Args);
}

break;
Expand Down
4 changes: 2 additions & 2 deletions src/modules/MouseWithoutBorders/App/Class/MachinePool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ public void Initialize(IEnumerable<string> machineNames)
}
else if (list.Count >= 4)
{
throw new ArgumentException("machineNames.Length > Common.MAX_MACHINE");
throw new ArgumentException($"The number of machines exceeded the maximum allowed limit of {Common.MAX_MACHINE}. Actual count: {list.Count}.");
}

_ = LearnMachine(name);
Expand All @@ -178,7 +178,7 @@ public void Initialize(IEnumerable<MachineInf> infos)
}
else if (list.Count >= 4)
{
throw new ArgumentException("infos.Length > Common.MAX_MACHINE");
throw new ArgumentException($"The number of machines exceeded the maximum allowed limit of {Common.MAX_MACHINE}. Actual count: {list.Count}.");
}

_ = LearnMachine(inf.Name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@ namespace MouseWithoutBorders.Class
{
internal static class MachinePoolHelpers
{
internal static readonly char[] Comma = new char[] { ',' };
internal static readonly char[] Colon = new char[] { ':' };

internal static MachineInf[] LoadMachineInfoFromMachinePoolStringSetting(string s)
{
if (s == null)
{
throw new ArgumentNullException(s);
}

string[] st = s.Split(new char[] { ',' });
string[] st = s.Split(Comma);

if (st.Length < Common.MAX_MACHINE)
{
Expand All @@ -25,7 +28,7 @@ internal static MachineInf[] LoadMachineInfoFromMachinePoolStringSetting(string
MachineInf[] rv = new MachineInf[Common.MAX_MACHINE];
for (int i = 0; i < Common.MAX_MACHINE; i++)
{
string[] mc = st[i].Split(new char[] { ':' });
string[] mc = st[i].Split(Colon);
if (mc.Length == 2)
{
rv[i].Name = mc[0];
Expand Down
2 changes: 1 addition & 1 deletion src/modules/MouseWithoutBorders/App/Class/Setting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ internal class Settings
{
internal bool Changed;

private readonly ISettingsUtils _settingsUtils;
private readonly SettingsUtils _settingsUtils;
private readonly object _loadingSettingsLock = new object();
private readonly IFileSystemWatcher _watcher;

Expand Down
8 changes: 5 additions & 3 deletions src/modules/MouseWithoutBorders/App/Class/SocketStuff.cs
Original file line number Diff line number Diff line change
Expand Up @@ -887,14 +887,14 @@ void ClientThread(object obj)

if (!string.IsNullOrEmpty(Setting.Values.Name2IP))
{
string[] name2ip = Setting.Values.Name2IP.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
string[] name2ip = Setting.Values.Name2IP.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
string[] nameNip;

if (name2ip != null)
{
foreach (string st in name2ip)
{
nameNip = st.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
nameNip = st.Split(BlankSeparator, StringSplitOptions.RemoveEmptyEntries);

if (nameNip != null && nameNip.Length >= 2 && nameNip[0].Trim().Equals(machineName, StringComparison.OrdinalIgnoreCase)
&& IPAddress.TryParse(nameNip[1].Trim(), out IPAddress ip) && !validAddressesSt.Contains("[" + ip.ToString() + "]")
Expand Down Expand Up @@ -1063,7 +1063,7 @@ private bool CheckForSameSubNet(List<IPAddress> validatedAddresses, string machi

List<IPAddress> localIPv4Addresses = GetMyIPv4Addresses().ToList();

if (!localIPv4Addresses.Any())
if (localIPv4Addresses.Count == 0)
{
Common.Log($"No IPv4 resolved from the local machine: {Common.MachineName}");
return true;
Expand Down Expand Up @@ -1234,6 +1234,8 @@ private void FlagReopenSocketIfNeeded(Exception e)
}

private long lastRemoteMachineID;
internal static readonly string[] Separator = new string[] { "\r\n" };
internal static readonly char[] BlankSeparator = new char[] { ' ' };

private void MainTCPRoutine(TcpSk tcp, string machineName, bool isClient)
{
Expand Down
3 changes: 2 additions & 1 deletion src/modules/MouseWithoutBorders/App/Class/TcpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ internal void Close()
}

private static bool logged;
internal static readonly string[] Separator = new[] { " " };

private void LogError(string log)
{
Expand Down Expand Up @@ -146,7 +147,7 @@ private void LogError(string log)
try
{
// Assuming the format of netstat's output is fixed.
pid = int.Parse(portLogLine.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).Last(), CultureInfo.CurrentCulture);
pid = int.Parse(portLogLine.Split(Separator, StringSplitOptions.RemoveEmptyEntries).Last(), CultureInfo.CurrentCulture);
process = Process.GetProcessById(pid);
}
catch (Exception)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,14 @@ private void CloseWindowButtonClick(object sender, EventArgs e)
}

private string lastMessage = string.Empty;
private static readonly string[] Separator = new string[] { "\r\n" };

internal void ShowTip(ToolTipIcon icon, string msg, int durationInMilliseconds)
{
int x = 0;
string text = msg + $"\r\n {(lastMessage.Equals(msg, StringComparison.OrdinalIgnoreCase) ? string.Empty : $"\r\nPrevious message/error: {lastMessage}")} ";
lastMessage = msg;
int y = (-text.Split(new string[] { "\r\n" }, StringSplitOptions.None).Length * 15) - 30;
int y = (-text.Split(Separator, StringSplitOptions.None).Length * 15) - 30;

toolTipManual.Hide(this);

Expand Down
4 changes: 3 additions & 1 deletion src/modules/MouseWithoutBorders/App/Form/frmMatrix.cs
Original file line number Diff line number Diff line change
Expand Up @@ -742,11 +742,13 @@ private void LoadSettingsToUI()
LoadMachines();
}

internal static readonly string[] Separator = new string[] { "\r\n" };

internal void ShowTip(ToolTipIcon icon, string text, int duration)
{
int x = 0;
text += "\r\n ";
int y = (-text.Split(new string[] { "\r\n" }, StringSplitOptions.None).Length * 15) - 30;
int y = (-text.Split(Separator, StringSplitOptions.None).Length * 15) - 30;

toolTipManual.Hide(this);

Expand Down
4 changes: 3 additions & 1 deletion src/modules/PowerOCR/PowerOCR/Helpers/ImageMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,8 @@ internal static async Task<string> GetClickedWord(Window passedWindow, System.Wi
return resultText.Trim();
}

internal static readonly char[] Separator = new char[] { '\n', '\r' };

public static async Task<string> ExtractText(Bitmap bmp, Language? preferredLanguage, System.Windows.Point? singlePoint = null)
{
Language? selectedLanguage = preferredLanguage ?? GetOCRLanguage();
Expand Down Expand Up @@ -211,7 +213,7 @@ public static async Task<string> ExtractText(Bitmap bmp, Language? preferredLang

if (culture.TextInfo.IsRightToLeft)
{
string[] textListLines = text.ToString().Split(new char[] { '\n', '\r' });
string[] textListLines = text.ToString().Split(Separator);

_ = text.Clear();
foreach (string textLine in textListLines)
Expand Down
2 changes: 1 addition & 1 deletion src/modules/PowerOCR/PowerOCR/Models/ResultTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ private static List<int> CalculateRowAreas(Rectangle rectCanvasSize, int hitGrid
return rowAreas;
}

private static void CheckIntersectionsWithWordBorders(int hitGridSpacing, ICollection<WordBorder> wordBorders, ICollection<int> rowAreas, int i, Rect horizontalLineRect)
private static void CheckIntersectionsWithWordBorders(int hitGridSpacing, ICollection<WordBorder> wordBorders, List<int> rowAreas, int i, Rect horizontalLineRect)
{
foreach (WordBorder wb in wordBorders)
{
Expand Down
2 changes: 1 addition & 1 deletion src/modules/PowerOCR/PowerOCR/Settings/UserSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace PowerOCR.Settings
[Export(typeof(IUserSettings))]
public class UserSettings : IUserSettings
{
private readonly ISettingsUtils _settingsUtils;
private readonly SettingsUtils _settingsUtils;
private const string PowerOcrModuleName = "TextExtractor";
private const string DefaultActivationShortcut = "Win + Shift + O";
private const int MaxNumberOfRetry = 5;
Expand Down
Loading

0 comments on commit a94b3ee

Please sign in to comment.