Fix analyzer warning (#16442)

This commit is contained in:
CleanCodeDeveloper
2022-02-22 20:52:34 +01:00
committed by GitHub
parent 230c199ee5
commit 6a722e2961
15 changed files with 60 additions and 61 deletions

View File

@@ -31,6 +31,8 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "We need to have the names of these keys in lowercase to be able to compare with the keys becoming form the template json. ContainsKey does not allow StringComparer specification to IgnoreCase", Scope = "member", Target = "Microsoft.Templates.Core.ITemplateInfoExtensions.#GetQueryableProperties(Microsoft.TemplateEngine.Abstractions.ITemplateInfo)")]
[assembly: SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "We need to have the names of these keys in lowercase to be able to compare with the keys becoming form the template json. ContainsKey does not allow StringComparer specification to IgnoreCase", Scope = "member", Target = "Microsoft.Templates.Core.Composition.CompositionQuery.#Match(System.Collections.Generic.IEnumerable`1<Microsoft.Templates.Core.Composition.QueryNode>,Microsoft.Templates.Core.Composition.QueryablePropertyDictionary)")]
[assembly: SuppressMessage("Usage", "VSTHRD103:Call async methods when in an async method", Justification = "Resource DictionaryWriter does not implement flush async", Scope = "member", Target = "~M:Microsoft.Templates.Core.PostActions.Catalog.Merge.MergeResourceDictionaryPostAction.ExecuteInternalAsync~System.Threading.Tasks.Task")]
[assembly: SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Used in a lot of places for meaningful method names")]
[assembly: SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Static methods may improve performance but decrease maintainability")]
// Threading suppressions
[assembly: SuppressMessage("Microsoft.VisualStudio.Threading.Analyzers", "VSTHRD100:Avoid async void methods", Justification = "Event handlers needs async void", Scope = "member", Target = "~M:Microsoft.Templates.UI.Controls.Notification.OnClose")]

View File

@@ -33,10 +33,7 @@ namespace FancyZonesEditor
{
if (AutomationPeer.ListenerExists(AutomationEvents.PropertyChanged))
{
ClickAutomationEventButtonAutomationPeer peer =
UIElementAutomationPeer.FromElement(this) as ClickAutomationEventButtonAutomationPeer;
if (peer != null)
if (UIElementAutomationPeer.FromElement(this) is ClickAutomationEventButtonAutomationPeer peer)
{
peer.RaisePropertyChangedEvent(
ValuePatternIdentifiers.ValueProperty,

View File

@@ -11,9 +11,9 @@ namespace FancyZonesEditor.Converters
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
if (value is bool valueBool)
{
return (bool)value == true ? 1 : 0;
return valueBool == true ? 1 : 0;
}
return 0;
@@ -21,9 +21,9 @@ namespace FancyZonesEditor.Converters
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is int)
if (value is int valueInt)
{
return (int)value == 1;
return valueInt == 1;
}
return false;

View File

@@ -18,6 +18,8 @@
<UseWindowsForms>true</UseWindowsForms>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisMode>Recommended</AnalysisMode>
</PropertyGroup>
<PropertyGroup>

View File

@@ -355,17 +355,17 @@ namespace FancyZonesEditor
});
}
Action<Zone> extend = (zone) =>
void Extend(Zone zone)
{
left = Math.Min(left, zone.Left);
right = Math.Max(right, zone.Right);
top = Math.Min(top, zone.Top);
bottom = Math.Max(bottom, zone.Bottom);
};
}
foreach (Index index in indices)
{
extend(_zones[index]);
Extend(_zones[index]);
}
bool possiblyBroken = true;
@@ -386,7 +386,7 @@ namespace FancyZonesEditor
if (newArea != 0 && newArea != area)
{
// bad intersection found, extend
extend(zone);
Extend(zone);
possiblyBroken = true;
}
}
@@ -494,17 +494,17 @@ namespace FancyZonesEditor
{
var resizer = _resizers[resizerIndex];
Func<int, int> getSize = (zoneIndex) =>
int GetSize(int zoneIndex)
{
Zone zone = _zones[zoneIndex];
return resizer.Orientation == Orientation.Vertical ? zone.Right - zone.Left : zone.Bottom - zone.Top;
};
}
int minZoneSize = resizer.Orientation == Orientation.Vertical ? MinZoneWidth : MinZoneHeight;
foreach (int zoneIndex in resizer.PositiveSideIndices)
{
if (getSize(zoneIndex) - delta < minZoneSize)
if (GetSize(zoneIndex) - delta < minZoneSize)
{
return false;
}
@@ -512,7 +512,7 @@ namespace FancyZonesEditor
foreach (int zoneIndex in resizer.NegativeSideIndices)
{
if (getSize(zoneIndex) + delta < minZoneSize)
if (GetSize(zoneIndex) + delta < minZoneSize)
{
return false;
}

View File

@@ -146,12 +146,10 @@ namespace FancyZonesEditor
}
Orientation orient = Orientation.Horizontal;
int offset = 0;
int zoneIndex = Preview.Children.IndexOf(gridZone);
var zone = _data.Zones[zoneIndex];
Debug.Assert(Preview.Children.Count > zoneIndex, "Zone index out of range");
Debug.Assert(Preview.Children.Count > Preview.Children.IndexOf(gridZone), "Zone index out of range");
int offset;
if (((App)Application.Current).MainWindowSettings.IsShiftKeyPressed)
{
orient = Orientation.Vertical;
@@ -174,8 +172,7 @@ namespace FancyZonesEditor
}
else
{
var resizer = Keyboard.FocusedElement as GridResizer;
if (resizer != null)
if (Keyboard.FocusedElement is GridResizer resizer)
{
HandleResizerKeyDown(resizer, e);
return;
@@ -185,15 +182,13 @@ namespace FancyZonesEditor
private void GridEditor_KeyUp(object sender, KeyEventArgs e)
{
var resizer = Keyboard.FocusedElement as GridResizer;
if (resizer != null)
if (Keyboard.FocusedElement is GridResizer resizer)
{
HandleResizerKeyUp(resizer, e);
return;
}
var gridZone = Keyboard.FocusedElement as GridZone;
if (gridZone != null)
if (Keyboard.FocusedElement is GridZone gridZone)
{
HandleGridZoneKeyUp(gridZone, e);
return;

View File

@@ -23,8 +23,6 @@ namespace FancyZonesEditor
private const string GridZoneBackgroundBrushID = "GridZoneBackgroundBrush";
private const string SecondaryForegroundBrushID = "SecondaryForegroundBrush";
private const string AccentColorBrushID = "SystemControlBackgroundAccentBrush";
private const string CanvasCanvasZoneBorderBrushID = "CanvasCanvasZoneBorderBrush";
public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register(ObjectDependencyID, typeof(bool), typeof(GridZone), new PropertyMetadata(false, OnSelectionChanged));
public event SplitEventHandler Split;

View File

@@ -21,8 +21,6 @@ namespace FancyZonesEditor
private const string PropertyZoneCountID = "ZoneCount";
private const string PropertyShowSpacingID = "ShowSpacing";
private const string PropertySpacingID = "Spacing";
private const string PropertyZoneBackgroundID = "ZoneBackground";
private const string PropertyZoneBorderID = "ZoneBorder";
private const string ObjectDependencyID = "IsActualSize";
public static readonly DependencyProperty IsActualSizeProperty = DependencyProperty.Register(ObjectDependencyID, typeof(bool), typeof(LayoutPreview), new PropertyMetadata(false));

View File

@@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
@@ -76,8 +77,7 @@ namespace FancyZonesEditor
{
if (e.Key == Key.Enter && _openedDialog != null && _openedDialog.IsVisible)
{
var source = e.OriginalSource as RadioButton;
if (source != null && source.IsChecked != true)
if (e.OriginalSource is RadioButton source && source.IsChecked != true)
{
source.IsChecked = true;
e.Handled = true;
@@ -105,7 +105,7 @@ namespace FancyZonesEditor
private void DecrementZones_Click(object sender, RoutedEventArgs e)
{
var mainEditor = App.Overlay;
if (!(mainEditor.CurrentDataContext is LayoutModel model))
if (mainEditor.CurrentDataContext is not LayoutModel model)
{
return;
}
@@ -119,7 +119,7 @@ namespace FancyZonesEditor
private void IncrementZones_Click(object sender, RoutedEventArgs e)
{
var mainEditor = App.Overlay;
if (!(mainEditor.CurrentDataContext is LayoutModel model))
if (mainEditor.CurrentDataContext is not LayoutModel model)
{
return;
}
@@ -177,9 +177,9 @@ namespace FancyZonesEditor
foreach (LayoutModel customModel in MainWindowSettingsModel.CustomModels)
{
string name = customModel.Name;
if (name.StartsWith(defaultNamePrefix))
if (name.StartsWith(defaultNamePrefix, StringComparison.CurrentCulture))
{
if (int.TryParse(name.Substring(defaultNamePrefix.Length), out int i))
if (int.TryParse(name.AsSpan(defaultNamePrefix.Length), out int i))
{
if (maxCustomIndex < i)
{
@@ -202,7 +202,7 @@ namespace FancyZonesEditor
EditLayoutDialog.Hide();
var mainEditor = App.Overlay;
if (!(mainEditor.CurrentDataContext is LayoutModel model))
if (mainEditor.CurrentDataContext is not LayoutModel model)
{
return;
}
@@ -226,7 +226,7 @@ namespace FancyZonesEditor
foreach (LayoutModel customModel in MainWindowSettingsModel.CustomModels)
{
string customModelName = customModel.Name;
if (customModelName.StartsWith(name))
if (customModelName.StartsWith(name, StringComparison.CurrentCulture))
{
int openBraceIndex = customModelName.LastIndexOf('(');
int closeBraceIndex = customModelName.LastIndexOf(')');
@@ -320,7 +320,7 @@ namespace FancyZonesEditor
}
Keyboard.ClearFocus();
EditLayoutDialogTitle.Text = string.Format(Properties.Resources.Edit_Template, ((LayoutModel)dataContext).Name);
EditLayoutDialogTitle.Text = string.Format(CultureInfo.CurrentCulture, Properties.Resources.Edit_Template, ((LayoutModel)dataContext).Name);
await EditLayoutDialog.ShowAsync();
}
@@ -331,7 +331,7 @@ namespace FancyZonesEditor
Select((LayoutModel)dataContext);
EditLayoutDialog.Hide();
var mainEditor = App.Overlay;
if (!(mainEditor.CurrentDataContext is LayoutModel model))
if (mainEditor.CurrentDataContext is not LayoutModel model)
{
return;
}
@@ -415,7 +415,7 @@ namespace FancyZonesEditor
Logger.LogTrace();
var mainEditor = App.Overlay;
if (!(mainEditor.CurrentDataContext is LayoutModel model))
if (mainEditor.CurrentDataContext is not LayoutModel model)
{
return;
}
@@ -527,8 +527,7 @@ namespace FancyZonesEditor
private void TextBox_GotKeyboardFocus(object sender, RoutedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
if (sender is TextBox tb)
{
tb.SelectionStart = tb.Text.Length;
}

View File

@@ -5,6 +5,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace FancyZonesEditor.Models
@@ -74,7 +75,9 @@ namespace FancyZonesEditor.Models
public LayoutType Type { get; set; }
#pragma warning disable CA1720 // Identifier contains type name (Not worth the effort to change this now.)
public Guid Guid
#pragma warning restore CA1720 // Identifier contains type name
{
get
{
@@ -181,16 +184,22 @@ namespace FancyZonesEditor.Models
{
get
{
return _quickKey == -1 ? Properties.Resources.Quick_Key_None : _quickKey.ToString();
return _quickKey == -1 ? Properties.Resources.Quick_Key_None : _quickKey.ToString(CultureInfo.CurrentCulture);
}
set
{
var intValue = -1;
string none = Properties.Resources.Quick_Key_None;
var intValue = value == none ? -1 : int.Parse(value);
if (value != none && int.TryParse(value, out var parsedInt))
{
intValue = parsedInt;
}
if (intValue != _quickKey)
{
string prev = _quickKey == -1 ? none : _quickKey.ToString();
string prev = _quickKey == -1 ? none : _quickKey.ToString(CultureInfo.CurrentCulture);
_quickKey = intValue;
if (intValue != -1)

View File

@@ -11,9 +11,9 @@ namespace FancyZonesEditor
internal static class NativeMethods
{
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName);
public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPWStr)] string lpFileName);
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
[DllImport("kernel32", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
}
}

View File

@@ -24,5 +24,7 @@ namespace FancyZonesEditor
public int Offset { get; }
}
#pragma warning disable CA1711 // Identifiers should not have incorrect suffix (Causes warning in another class if fixed)
public delegate void SplitEventHandler(object sender, SplitEventArgs args);
#pragma warning restore CA1711 // Identifiers should not have incorrect suffix
}

View File

@@ -35,9 +35,6 @@ namespace FancyZonesEditor.Utils
private const string CustomLayoutsFile = "\\Microsoft\\PowerToys\\FancyZones\\custom-layouts.json";
private const string ParamsFile = "\\Microsoft\\PowerToys\\FancyZones\\editor-parameters.json";
// Non-localizable string: Multi-monitor id
private const string MultiMonitorId = "FancyZones#MultiMonitorDevice";
// Non-localizable string: default virtual desktop id
private const string DefaultVirtualDesktopGuid = "{00000000-0000-0000-0000-000000000000}";
@@ -317,7 +314,7 @@ namespace FancyZonesEditor.Utils
if (!App.Overlay.SpanZonesAcrossMonitors)
{
// Test launch with custom monitors configuration
bool isCustomMonitorConfigurationMode = targetMonitorName.StartsWith("Monitor#");
bool isCustomMonitorConfigurationMode = targetMonitorName.StartsWith("Monitor#", StringComparison.Ordinal);
if (isCustomMonitorConfigurationMode)
{
App.Overlay.Monitors.Clear();
@@ -735,7 +732,7 @@ namespace FancyZonesEditor.Utils
{
LayoutHotkeyWrapper wrapper = new LayoutHotkeyWrapper
{
Key = int.Parse(pair.Key),
Key = int.Parse(pair.Key, CultureInfo.CurrentCulture),
LayoutId = pair.Value,
};
@@ -906,7 +903,7 @@ namespace FancyZonesEditor.Utils
{
try
{
Stream inputStream = _fileSystem.File.Open(fileName, FileMode.Open);
using (Stream inputStream = _fileSystem.File.Open(fileName, FileMode.Open))
using (StreamReader reader = new StreamReader(inputStream))
{
string data = reader.ReadToEnd();
@@ -948,11 +945,11 @@ namespace FancyZonesEditor.Utils
bool unused = true;
foreach (Monitor monitor in monitors)
{
string deviceIdSaved = monitor.Device.Id.Substring(0, monitor.Device.Id.LastIndexOf("_"));
string deviceIdReadFromSettings = layout.DeviceId.Substring(0, layout.DeviceId.LastIndexOf("_"));
string deviceIdSaved = monitor.Device.Id.Substring(0, monitor.Device.Id.LastIndexOf("_", StringComparison.Ordinal));
string deviceIdReadFromSettings = layout.DeviceId.Substring(0, layout.DeviceId.LastIndexOf("_", StringComparison.Ordinal));
string virtualDesktopIdSaved = monitor.Device.Id.Substring(monitor.Device.Id.LastIndexOf("_") + 1);
string virtualDesktopIdReadFromSettings = layout.DeviceId.Substring(layout.DeviceId.LastIndexOf("_") + 1);
string virtualDesktopIdSaved = monitor.Device.Id.Substring(monitor.Device.Id.LastIndexOf("_", StringComparison.Ordinal) + 1);
string virtualDesktopIdReadFromSettings = layout.DeviceId.Substring(layout.DeviceId.LastIndexOf("_", StringComparison.Ordinal) + 1);
if (deviceIdSaved == deviceIdReadFromSettings && (virtualDesktopIdSaved == virtualDesktopIdReadFromSettings || virtualDesktopIdReadFromSettings == DefaultVirtualDesktopGuid))
{
@@ -1070,7 +1067,7 @@ namespace FancyZonesEditor.Utils
MainWindowSettingsModel.LayoutHotkeys.CleanUp();
foreach (var wrapper in layoutHotkeys.LayoutHotkeys)
{
MainWindowSettingsModel.LayoutHotkeys.SelectKey(wrapper.Key.ToString(), wrapper.LayoutId);
MainWindowSettingsModel.LayoutHotkeys.SelectKey(wrapper.Key.ToString(CultureInfo.CurrentCulture), wrapper.LayoutId);
}
return true;

View File

@@ -26,7 +26,7 @@ namespace FancyZonesEditor.Utils
public static void SetWindowStyleToolWindow(Window hwnd)
{
var helper = new WindowInteropHelper(hwnd).Handle;
SetWindowLong(helper, GWL_EX_STYLE, (GetWindowLong(helper, GWL_EX_STYLE) | WS_EX_TOOLWINDOW) & ~WS_EX_APPWINDOW);
_ = SetWindowLong(helper, GWL_EX_STYLE, (GetWindowLong(helper, GWL_EX_STYLE) | WS_EX_TOOLWINDOW) & ~WS_EX_APPWINDOW);
}
}
}

View File

@@ -15,7 +15,7 @@ namespace FancyZonesEditor.ViewModels
public event PropertyChangedEventHandler PropertyChanged;
public delegate void MonitorChangedEventHandler(MonitorChangedEventArgs args);
public delegate void MonitorChangedEvent(MonitorChangedEventArgs args);
public ObservableCollection<MonitorInfoModel> MonitorInfoForViewModel { get; set; }