Skip to content

Commit

Permalink
[StyleCleanUp] Addressing CA warnings Part 1 (#10144)
Browse files Browse the repository at this point in the history
* Resolving CA2249, CA2251, CA1847 CA1845 and CA1846

* Adding String Comparison to Contains Check

* Adding the NET check

* Removing NET check

* Revert "Removing NET check"

This reverts commit 753cd86.

* using StringBuilderbuilder.Append(String,int,int)

* Changing NET check to NETFX check
  • Loading branch information
himgoyalmicro authored Feb 3, 2025
1 parent 444cf2f commit d411234
Show file tree
Hide file tree
Showing 26 changed files with 53 additions and 57 deletions.
15 changes: 0 additions & 15 deletions src/Microsoft.DotNet.Wpf/src/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,6 @@ dotnet_diagnostic.CA1834.severity = suggestion
# CA1838: Avoid StringBuilder parameters for P/Invokes
dotnet_diagnostic.CA1838.severity = suggestion

# CA1845: Use span-based 'string.Concat'
dotnet_diagnostic.CA1845.severity = suggestion

# CA1846: Prefer AsSpan over Substring
dotnet_diagnostic.CA1846.severity = suggestion

# CA1847: Use string.Contains(char) instead of string.Contains(string) with single characters
dotnet_diagnostic.CA1847.severity = suggestion

# CA1851: Possible multiple enumerations of IEnumerable collection
dotnet_diagnostic.CA1851.severity = suggestion

Expand Down Expand Up @@ -158,12 +149,6 @@ dotnet_diagnostic.CA2219.severity = suggestion
# CA2242: Test for NaN correctly
dotnet_diagnostic.CA2242.severity = suggestion

# CA2249: Consider using 'string.Contains' instead of 'string.IndexOf'
dotnet_diagnostic.CA2249.severity = suggestion

# CA2251: Use String.Equals over String.Compare
dotnet_diagnostic.CA2251.severity = suggestion

# CA2300: Do not use insecure deserializer BinaryFormatter
dotnet_diagnostic.CA2300.severity = suggestion

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ private void Initialize(FileUnit sourceFile)
}

int pathEndIndex = SourceFileInfo.RelativeSourceFilePath.LastIndexOf(Path.DirectorySeparatorChar);
string targetPath = TargetPath + SourceFileInfo.RelativeSourceFilePath.Substring(0, pathEndIndex + 1);
string targetPath = string.Concat(TargetPath, SourceFileInfo.RelativeSourceFilePath.Substring(0, pathEndIndex + 1));

// Create if not already exists
if (targetPath.Length > 0 && !Directory.Exists(targetPath))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,11 @@ internal static string GetWholeExceptionMessage(Exception exception)
while (e.InnerException != null)
{
Exception eInner = e.InnerException;
#if !NETFX
if (!e.Message.Contains(eInner.Message, StringComparison.Ordinal))
#else
if (e.Message.IndexOf(eInner.Message, StringComparison.Ordinal) == -1)
#endif
{
message += ", ";
message += eInner.Message;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,11 @@ private UidCollector ParseFile(string fileName)
collector.RootElementLinePosition = reader.LinePosition;
}

if (reader.Name.IndexOf('.') >= 0)
#if !NETFX
if (reader.Name.Contains('.'))
#else
if (reader.Name.Contains("."))
#endif
{
// the name has a dot, which suggests it is a property tag.
// we will ignore adding uid
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -818,21 +818,21 @@ protected RBNode<T> LoadTree(ref string s)
s = s.Substring(1);

index = s.IndexOf(','); // read LeftSize
node.LeftSize = Int32.Parse(s.Substring(0, index), TypeConverterHelper.InvariantEnglishUS);
node.LeftSize = Int32.Parse(s.AsSpan(0, index), TypeConverterHelper.InvariantEnglishUS);
s = s.Substring(index + 1);

index = s.IndexOf(','); // read Size
node.Size = Int32.Parse(s.Substring(0, index), TypeConverterHelper.InvariantEnglishUS);
node.Size = Int32.Parse(s.AsSpan(0, index), TypeConverterHelper.InvariantEnglishUS);
s = s.Substring(index+1);

for (int k = 0; k < node.Size-1; ++k) // read data
{
index = s.IndexOf(',');
node.SetItemAt(k, AsT(Int32.Parse(s.Substring(0, index), TypeConverterHelper.InvariantEnglishUS)));
node.SetItemAt(k, AsT(Int32.Parse(s.AsSpan(0, index), TypeConverterHelper.InvariantEnglishUS)));
s = s.Substring(index+1);
}
index = s.IndexOf('(');
node.SetItemAt(node.Size - 1, AsT(Int32.Parse(s.Substring(0, index), TypeConverterHelper.InvariantEnglishUS)));
node.SetItemAt(node.Size - 1, AsT(Int32.Parse(s.AsSpan(0, index), TypeConverterHelper.InvariantEnglishUS)));
s = s.Substring(index);

node.LeftChild = LoadTree(ref s); // read subtrees
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,7 @@ public void LoadTree(string s)
{
if (s.StartsWith("\"", StringComparison.Ordinal)) s = s.Substring(1);
int index = s.IndexOf('(');
LeftSize = Int32.Parse(s.Substring(0, index), TypeConverterHelper.InvariantEnglishUS);
LeftSize = Int32.Parse(s.AsSpan(0, index), TypeConverterHelper.InvariantEnglishUS);
s = s.Substring(index);
this.LeftChild = LoadTree(ref s);
this.LeftChild.Parent = this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder
// We never expect to get a real method name here--see the explanation in GetMethods().
if (name.StartsWith("[DISPID=", StringComparison.OrdinalIgnoreCase))
{
int dispid = int.Parse(name.Substring(8, name.Length-9), CultureInfo.InvariantCulture);
int dispid = int.Parse(name.AsSpan(8, name.Length-9), CultureInfo.InvariantCulture);
MethodInfo method;
if (_dispId2MethodMap.TryGetValue(dispid, out method))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3671,11 +3671,11 @@ ref StrikeState strikeState
{
ulState = ULState.ULNone;
strikeState = StrikeState.StrikeNone;
if (decoration.IndexOf("Underline", StringComparison.OrdinalIgnoreCase) != -1)
if (decoration.Contains("Underline", StringComparison.OrdinalIgnoreCase))
{
ulState = ULState.ULNormal;
}
if (decoration.IndexOf("Strikethrough", StringComparison.OrdinalIgnoreCase) != -1)
if (decoration.Contains("Strikethrough", StringComparison.OrdinalIgnoreCase))
{
strikeState = StrikeState.StrikeNormal;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ internal static DependencyProperty ResolveProperty(IServiceProvider serviceProvi
{
value = value.Trim();
// If it contains a . it means that it is a full name with type and property.
if (value.Contains("."))
if (value.Contains('.'))
{
// Prefixes could have .'s so we take the last one and do a type resolve against that
int lastIndex = value.LastIndexOf('.');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1458,8 +1458,11 @@ private string ResolveAttributeNamespaceURI(string prefix, string name, string p
// if the prefix was "" then
// 1) normal properties resolve to the parent Tag namespace.
// 2) Attached properties resolve to the "" default namespace.
int dotIndex = name.IndexOf('.');
if (-1 == dotIndex)
#if !NETFX
if (!name.Contains('.'))
#else
if (!name.Contains("."))
#endif
attribNamespaceURI = parentURI;
else
attribNamespaceURI = _parserHelper.LookupNamespace("");
Expand Down Expand Up @@ -1618,7 +1621,7 @@ internal static void RemoveEscapes(ref string value)
if (builder == null)
{
builder = new StringBuilder(value.Length);
builder.Append(value.Substring(0,i));
builder.Append(value, 0, i);
}
noEscape = false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2731,8 +2731,11 @@ private string ResolveAttributeNamespaceURI(string prefix, string name, string p
// if the prefix was "" then
// 1) normal properties resolve to the parent Tag namespace.
// 2) Attached properties resolve to the "" default namespace.
int dotIndex = name.IndexOf('.');
if (-1 == dotIndex)
#if !NETFX
if (!name.Contains('.'))
#else
if (!name.Contains("."))
#endif
attribNamespaceURI = parentURI;
else
attribNamespaceURI = XmlReader.LookupNamespace("");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ Type destinationType
{
colorString = color.ToString(culture);

if (colorString.StartsWith("sc#", StringComparison.Ordinal) && colorString.Contains("E"))
if (colorString.StartsWith("sc#", StringComparison.Ordinal) && colorString.Contains('E'))
{
//
// Fix bug 1588888: Serialization produces non-compliant scRGB color string.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ Type destinationType
index = m_mainFile.Length;
}

string uri = m_mainFile.Substring(0, index) + "_" + bitmapName;
string uri = string.Concat(m_mainFile.Substring(0, index), "_", bitmapName);

Stream bitmapStreamDest = new System.IO.FileStream(uri, FileMode.Create, FileAccess.ReadWrite, FileShare.None);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ public static void Sync(ISyncKeyTipAndContent syncElement, DependencyProperty co
{
if (accessKeyIndex == -1)
{
int accessorIndex = stringContent.IndexOf(keyTip[0]);
if (accessorIndex != -1)
if (stringContent.Contains(keyTip[0]))
{
syncElement.KeepKeyTipAndContentInSync = true;
syncElement.IsKeyTipSyncSource = true;
Expand Down Expand Up @@ -154,7 +153,7 @@ public static object CoerceContentProperty(ISyncKeyTipAndContent syncElement,
if (accessorIndex >= 0)
{
syncElement.KeepKeyTipAndContentInSync = true;
return stringContent.Substring(0, accessorIndex) + '_' + stringContent.Substring(accessorIndex);
return string.Concat(stringContent.Substring(0, accessorIndex), '_', stringContent.Substring(accessorIndex));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@ public GenericTypeNameParser(Func<string, string> prefixResolver)

public static XamlTypeName ParseIfTrivalName(string text, Func<string, string> prefixResolver, out string error)
{
int parenIdx = text.IndexOf('(');
int bracketIdx = text.IndexOf('[');
if (parenIdx != -1 || bracketIdx != -1)
if (text.Contains('(') || text.Contains('['))
{
error = string.Empty;
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -664,14 +664,14 @@ static private IRawElementProviderSimple GetProxyFromEntry(ProxyScoping findType
break;

case ProxyScoping.PartialMatchApparentClassName:
if (classNameForPartialMatch.IndexOf(pi.ClassName, StringComparison.Ordinal) >= 0)
if (classNameForPartialMatch.Contains(pi.ClassName, StringComparison.Ordinal))
{
factoryCallback = pi.ClientSideProviderFactoryCallback;
}
break;

case ProxyScoping.PartialMatchRealClassName:
if (classNameForPartialMatch.IndexOf(pi.ClassName, StringComparison.Ordinal) >= 0
if (classNameForPartialMatch.Contains(pi.ClassName, StringComparison.Ordinal)
&& ((pi.Flags & ClientSideProviderMatchIndicator.DisallowBaseClassNameMatch) == 0))
{
factoryCallback = pi.ClientSideProviderFactoryCallback;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,15 @@ internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild)
IntPtr hwndSpin;

// Find the Edit control. Typically the UpDown is first so we'll start with the other window.
if (Misc.ProxyGetClassName(hwndLastChild).IndexOf("Edit", StringComparison.OrdinalIgnoreCase) != -1)
if (Misc.ProxyGetClassName(hwndLastChild).Contains("Edit", StringComparison.OrdinalIgnoreCase))
{
hwndEdit = hwndLastChild;
hwndSpin = hwndFirstChild;
}
else
{
// Haven't seen this but suppose it's possible. Subsequent test will confirm.
if (Misc.ProxyGetClassName(hwndFirstChild).IndexOf("Edit", StringComparison.OrdinalIgnoreCase) != -1)
if (Misc.ProxyGetClassName(hwndFirstChild).Contains("Edit", StringComparison.OrdinalIgnoreCase))
{
hwndEdit = hwndFirstChild;
hwndSpin = hwndLastChild;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public WindowsContainer (IntPtr hwnd, ProxyHwnd parent, int item)
{
_sType = SR.LocalizedControlTypeDialog;
}
else if (className.IndexOf("AfxControlBar", StringComparison.Ordinal) != -1)
else if (className.Contains("AfxControlBar", StringComparison.Ordinal))
{
_sType = SR.LocalizedControlTypeContainer;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2453,7 +2453,7 @@ private static string AccelatorKeyCtrl(string sKeyword, string sCanonicalsKeywor
{
// Take the remaining string from the Keyword
// Case Alt+Enter
return sCanonicalsKeyword + menuRawText.Substring(pos + cKeyChars + 1, cMenuChars - (pos + cKeyChars + 1));
return string.Concat(sCanonicalsKeyword, menuRawText.Substring(pos + cKeyChars + 1, cMenuChars - (pos + cKeyChars + 1)));
}
}
}
Expand All @@ -2475,7 +2475,7 @@ private static string AccelatorFxx (string menuText)
// Check that it is the form Fxx
if (pos < cChars - 1 && pos > 0 && menuText [pos] == 'f')
{
int iKey = int.Parse(menuText.Substring(pos + 1, cChars - (pos + 1)), CultureInfo.InvariantCulture);
int iKey = int.Parse(menuText.AsSpan(pos + 1, cChars - (pos + 1)), CultureInfo.InvariantCulture);
if (iKey > 0 && iKey <= 12)
{
return "F" + iKey.ToString(CultureInfo.CurrentCulture);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ private string GetValue()
object embeddedObject;
while (start < end && embeddedObjectOffset != -1)
{
sbText.Append(text.Substring(start, embeddedObjectOffset - start));
sbText.Append(text.AsSpan(start, embeddedObjectOffset - start));
range.SetRange(embeddedObjectOffset, end);
if (range.GetEmbeddedObject(out embeddedObject) == NativeMethods.S_OK && embeddedObject != null)
{
Expand All @@ -548,7 +548,7 @@ private string GetValue()

if (start < end)
{
sbText.Append(text.Substring(start, end - start));
sbText.Append(text.AsSpan(start, end - start));
}

text = sbText.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild)
return null;
}

if (Misc.ProxyGetClassName(hwndBuddy).IndexOf("EDIT", StringComparison.OrdinalIgnoreCase) == -1)
if (!Misc.ProxyGetClassName(hwndBuddy).Contains("EDIT", StringComparison.OrdinalIgnoreCase))
{
return null;
}
Expand Down Expand Up @@ -278,7 +278,7 @@ internal static IntPtr GetUpDownFromEdit(IntPtr hwnd)
while (hwndChild != IntPtr.Zero)
{
string className = Misc.ProxyGetClassName(hwndChild);
if (className.IndexOf("msctls_updown32", StringComparison.OrdinalIgnoreCase) != -1)
if (className.Contains("msctls_updown32", StringComparison.OrdinalIgnoreCase))
{
IntPtr hwndBuddy = Misc.ProxySendMessage(hwndChild, NativeMethods.UDM_GETBUDDY, IntPtr.Zero, IntPtr.Zero);
if (hwnd == hwndBuddy)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ internal static void RaiseEvents (IntPtr hwnd, int eventId, object idProp, int i
IntPtr hwndParent = NativeMethodsSetLastError.GetAncestor (hwnd, NativeMethods.GA_PARENT);
if (hwndParent != IntPtr.Zero)
{
if (Misc.GetClassName(hwndParent).IndexOf("SysListView32", StringComparison.Ordinal) >= 0)
if (Misc.GetClassName(hwndParent).Contains("SysListView32", StringComparison.Ordinal))
{
// Notify the Listview that the header Change
WindowsListView wlv = (WindowsListView) WindowsListView.Create (hwndParent, 0);
Expand Down Expand Up @@ -245,7 +245,7 @@ internal void ScrollIntoView(HeaderItem headerItem)
IntPtr hwndParent = NativeMethodsSetLastError.GetAncestor (_hwnd, NativeMethods.GA_PARENT);
if (hwndParent != IntPtr.Zero)
{
if (Misc.GetClassName(hwndParent).IndexOf("SysListView32", StringComparison.Ordinal) >= 0)
if (Misc.GetClassName(hwndParent).Contains("SysListView32", StringComparison.Ordinal))
{
// Determine the number of pixels or columns to scroll horizontally.
int pixels = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ private bool IsSpinnerElement()
// If this is a Spinner UpDown Control, the buddy window should be a control with
// the class of EDIT.
IntPtr hwndBuddy = HwndBuddy(_hwnd);
return hwndBuddy != IntPtr.Zero && Misc.ProxyGetClassName(hwndBuddy).IndexOf("EDIT", StringComparison.OrdinalIgnoreCase) != -1;
return hwndBuddy != IntPtr.Zero && Misc.ProxyGetClassName(hwndBuddy).Contains("EDIT", StringComparison.OrdinalIgnoreCase);
}

private double Max
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ static public string AntiFormat(string s)
else
{
// duplicate the formatting character
sb.Append(s.Substring(index, formatIndex - index + 1));
sb.Append(s.AsSpan(index, formatIndex - index + 1));
sb.Append(s[formatIndex]);

index = formatIndex + 1;
Expand All @@ -405,7 +405,7 @@ static public string AntiFormat(string s)

if (index <= lengthMinus1)
{
sb.Append(s.Substring(index));
sb.Append(s.AsSpan(index));
}

return sb.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ static internal void CheckStringForEmbeddedPathSeparator(string testString,
{
CheckStringAgainstNullAndEmpty(testString, testStringIdentifier);

if (testString.IndexOf(PathSeparator) != -1)
if (testString.Contains(PathSeparator))
throw new ArgumentException(
SR.Format(SR.NameCanNotHaveDelimiter,
testStringIdentifier,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ internal static Uri PackageRootUri
internal static bool IsPackUri(Uri uri)
{
return uri != null &&
string.Compare(uri.Scheme, System.IO.Packaging.PackUriHelper.UriSchemePack, StringComparison.OrdinalIgnoreCase) == 0;
string.Equals(uri.Scheme, System.IO.Packaging.PackUriHelper.UriSchemePack, StringComparison.OrdinalIgnoreCase);
}

/// <summary>
Expand Down

0 comments on commit d411234

Please sign in to comment.