From 2798042dbbe99d44ec82ea0567381e70a95d260e Mon Sep 17 00:00:00 2001 From: Rose <83477269+AtariDreams@users.noreply.github.com> Date: Tue, 30 Aug 2022 18:50:33 -0400 Subject: [PATCH] Fix C# warnings A continuation of my last PR --- src/Calculator/App.xaml.cs | 18 ++--- .../Common/AlwaysSelectedCollectionView.cs | 10 +-- .../Common/KeyboardShortcutManager.cs | 28 ++----- src/Calculator/Common/ValidatingConverters.cs | 19 ++--- src/Calculator/Controls/CalculationResult.cs | 22 +++--- src/Calculator/Controls/CalculatorButton.cs | 8 +- src/Calculator/Controls/EquationTextBox.cs | 6 +- .../Controls/OperatorPanelButton.cs | 4 - .../Controls/OperatorPanelListView.cs | 4 - src/Calculator/Controls/OverflowTextBlock.cs | 8 +- src/Calculator/Controls/RadixButton.cs | 3 - .../Controls/SupplementaryItemsControl.cs | 8 -- .../ExpressionItemTemplateSelector.cs | 5 +- .../Converters/RadixToStringConverter.cs | 2 - .../KeyGraphFeaturesTemplateSelector.cs | 4 - src/Calculator/Utils/ThemeHelper.cs | 2 +- src/Calculator/Views/Calculator.xaml.cs | 6 +- .../CalculatorProgrammerDisplayPanel.xaml.cs | 2 +- .../CalculatorProgrammerOperators.xaml.cs | 20 +---- .../EquationInputArea.xaml.cs | 32 +++----- .../EquationStylePanelControl.xaml.cs | 12 +-- .../GraphingCalculator.xaml.cs | 48 ++++-------- .../GraphingCalculator/GraphingNumPad.xaml.cs | 4 +- .../GraphingSettings.xaml.cs | 2 +- src/Calculator/Views/HistoryList.xaml.cs | 14 +--- src/Calculator/Views/MainPage.xaml.cs | 22 ++---- src/Calculator/Views/Memory.xaml.cs | 15 +--- .../Views/SupplementaryResults.xaml.cs | 5 +- src/Calculator/Views/TitleBar.xaml.cs | 22 +++--- src/Calculator/Views/UnitConverter.xaml.cs | 9 +-- src/Calculator/WindowFrameService.cs | 4 +- src/CalculatorUITestFramework/HistoryItem.cs | 4 +- .../NavigationMenu.cs | 76 +++++-------------- src/CalculatorUITestFramework/NumberPad.cs | 4 +- .../ScientificOperatorsPanel.cs | 20 ++--- src/CalculatorUITestFramework/WinAppDriver.cs | 13 +--- .../WindowsDriverLocalService.cs | 34 ++------- .../WindowsDriverServiceBuilder.cs | 6 +- 38 files changed, 150 insertions(+), 375 deletions(-) diff --git a/src/Calculator/App.xaml.cs b/src/Calculator/App.xaml.cs index d6006bcf..c9a90cea 100644 --- a/src/Calculator/App.xaml.cs +++ b/src/Calculator/App.xaml.cs @@ -30,7 +30,7 @@ namespace CalculatorApp { namespace ApplicationResourceKeys { - public static partial class Globals + public static class Globals { public static readonly string AppMinWindowHeight = "AppMinWindowHeight"; public static readonly string AppMinWindowWidth = "AppMinWindowWidth"; @@ -253,8 +253,7 @@ namespace CalculatorApp int newWindowId = ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()); ActivationViewSwitcher activationViewSwitcher = null; - var activateEventArgs = (args as IViewSwitcherProvider); - if (activateEventArgs != null) + if (args is IViewSwitcherProvider activateEventArgs) { activationViewSwitcher = activateEventArgs.ViewSwitcher; } @@ -266,8 +265,7 @@ namespace CalculatorApp } else { - var activatedEventArgs = (args as IApplicationViewActivatedEventArgs); - if ((activatedEventArgs != null) && (activatedEventArgs.CurrentlyShownApplicationViewId != 0)) + if ((args is IApplicationViewActivatedEventArgs activatedEventArgs) && (activatedEventArgs.CurrentlyShownApplicationViewId != 0)) { // CSHARP_MIGRATION_ANNOTATION: // here we don't use ContinueWith() to interpret origin code because we would like to @@ -294,8 +292,7 @@ namespace CalculatorApp else { ActivationViewSwitcher activationViewSwitcher = null; - var activateEventArgs = (args as IViewSwitcherProvider); - if (activateEventArgs != null) + if (args is IViewSwitcherProvider activateEventArgs) { activationViewSwitcher = activateEventArgs.ViewSwitcher; } @@ -334,14 +331,13 @@ namespace CalculatorApp // for tablet mode: since system view activation policy is disabled so do ShowAsStandaloneAsync if activationViewSwitcher exists in // activationArgs ActivationViewSwitcher activationViewSwitcher = null; - var activateEventArgs = (args as IViewSwitcherProvider); - if (activateEventArgs != null) + if (args is IViewSwitcherProvider activateEventArgs) { activationViewSwitcher = activateEventArgs.ViewSwitcher; } if (activationViewSwitcher != null) { - var viewId = (args as IApplicationViewActivatedEventArgs).CurrentlyShownApplicationViewId; + var viewId = ((IApplicationViewActivatedEventArgs)args).CurrentlyShownApplicationViewId; if (viewId != 0) { _ = activationViewSwitcher.ShowAsStandaloneAsync(viewId); @@ -495,7 +491,7 @@ namespace CalculatorApp try { bool removed = m_secondaryWindows.Remove(viewId); - Debug.Assert(removed != false, "Window does not exist in the list"); + Debug.Assert(removed, "Window does not exist in the list"); } finally { diff --git a/src/Calculator/Common/AlwaysSelectedCollectionView.cs b/src/Calculator/Common/AlwaysSelectedCollectionView.cs index cada6702..df309862 100644 --- a/src/Calculator/Common/AlwaysSelectedCollectionView.cs +++ b/src/Calculator/Common/AlwaysSelectedCollectionView.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; @@ -44,10 +44,10 @@ namespace CalculatorApp // restore the selection to the way we wanted it to begin with if (CurrentPosition >= 0 && CurrentPosition < m_source.Count) { - Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => + Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { CurrentChanged?.Invoke(this, null); - })).AsTask().Wait(); + }).AsTask().Wait(); } return false; } @@ -196,10 +196,6 @@ namespace CalculatorApp public sealed class AlwaysSelectedCollectionViewConverter : Windows.UI.Xaml.Data.IValueConverter { - public AlwaysSelectedCollectionViewConverter() - { - } - public object Convert(object value, Type targetType, object parameter, string language) { if (value is IList result) diff --git a/src/Calculator/Common/KeyboardShortcutManager.cs b/src/Calculator/Common/KeyboardShortcutManager.cs index f9918b4b..9ece2698 100644 --- a/src/Calculator/Common/KeyboardShortcutManager.cs +++ b/src/Calculator/Common/KeyboardShortcutManager.cs @@ -115,10 +115,6 @@ namespace CalculatorApp public sealed class KeyboardShortcutManager : DependencyObject { - public KeyboardShortcutManager() - { - } - public static readonly DependencyProperty CharacterProperty = DependencyProperty.RegisterAttached( "Character", @@ -484,13 +480,8 @@ namespace CalculatorApp // Writer lock for the static maps lock (s_keyboardShortcutMapLockMutex) { - Control control = (target as ButtonBase); - - if (control == null) - { - // Handling Ctrl+E shortcut for Date Calc, target would be NavigationView^ in that case - control = (target as MUXC.NavigationView); - } + // Handling Ctrl+E shortcut for Date Calc, target would be NavigationView^ in that case + Control control = (target as ButtonBase) ?? (Control)(target as MUXC.NavigationView); int viewId = Utilities.GetWindowId(); @@ -580,7 +571,7 @@ namespace CalculatorApp private static bool CanNavigateModeByShortcut(MUXC.NavigationView navView, object nvi , ApplicationViewModel vm, ViewMode toMode) { - if (nvi != null && nvi is NavCategory navCategory) + if (nvi is NavCategory navCategory) { return navCategory.IsEnabled && navView.Visibility == Visibility.Visible @@ -601,21 +592,18 @@ namespace CalculatorApp { if (itemRef.Target is MUXC.NavigationView item) { - var navView = item; - - var menuItems = ((List)navView.MenuItemsSource); + var menuItems = ((List)item.MenuItemsSource); if (menuItems != null) { - var vm = (navView.DataContext as ApplicationViewModel); - if (null != vm) + if (item.DataContext is ApplicationViewModel vm) { - ViewMode realToMode = toMode.HasValue ? toMode.Value : NavCategoryStates.GetViewModeForVirtualKey(((MyVirtualKey)key)); + ViewMode realToMode = toMode ?? NavCategoryStates.GetViewModeForVirtualKey(((MyVirtualKey)key)); var nvi = menuItems[NavCategoryStates.GetFlatIndex(realToMode)]; - if (CanNavigateModeByShortcut(navView, nvi, vm, realToMode)) + if (CanNavigateModeByShortcut(item, nvi, vm, realToMode)) { vm.Mode = realToMode; - navView.SelectedItem = nvi; + item.SelectedItem = nvi; } } } diff --git a/src/Calculator/Common/ValidatingConverters.cs b/src/Calculator/Common/ValidatingConverters.cs index b6e88bac..b618da3b 100644 --- a/src/Calculator/Common/ValidatingConverters.cs +++ b/src/Calculator/Common/ValidatingConverters.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; @@ -8,9 +8,6 @@ namespace CalculatorApp { public sealed class ValidSelectedItemConverter : Windows.UI.Xaml.Data.IValueConverter { - public ValidSelectedItemConverter() - { } - public object Convert(object value, Type targetType, object parameter, string language) { // Pass through as we don't want to change the value from the source @@ -31,9 +28,6 @@ namespace CalculatorApp public sealed class ValidSelectedIndexConverter : Windows.UI.Xaml.Data.IValueConverter { - public ValidSelectedIndexConverter() - { } - public object Convert(object value, Type targetType, object parameter, string language) { // Pass through as we don't want to change the value from the source @@ -44,15 +38,12 @@ namespace CalculatorApp { // The value to be valid has to be a boxed int32 value // extract that value and ensure it is valid, ie >= 0 - if (value != null) + if (value is Windows.Foundation.IPropertyValue box && box.Type == Windows.Foundation.PropertyType.Int32) { - if (value is Windows.Foundation.IPropertyValue box && box.Type == Windows.Foundation.PropertyType.Int32) + int index = box.GetInt32(); + if (index >= 0) { - int index = box.GetInt32(); - if (index >= 0) - { - return value; - } + return value; } } // The value is not valid therefore stop the binding right here diff --git a/src/Calculator/Controls/CalculationResult.cs b/src/Calculator/Controls/CalculationResult.cs index 78a65d0d..07f02992 100644 --- a/src/Calculator/Controls/CalculationResult.cs +++ b/src/Calculator/Controls/CalculationResult.cs @@ -33,11 +33,11 @@ namespace CalculatorApp // Using a DependencyProperty as the backing store for MinFontSize. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinFontSizeProperty = - DependencyProperty.Register(nameof(MinFontSize), typeof(double), typeof(CalculationResult), new PropertyMetadata(0.0, new PropertyChangedCallback((sender, args) => + DependencyProperty.Register(nameof(MinFontSize), typeof(double), typeof(CalculationResult), new PropertyMetadata(0.0, (sender, args) => { var self = (CalculationResult)sender; self.OnMinFontSizePropertyChanged((double)args.OldValue, (double)args.NewValue); - }))); + })); public double MaxFontSize { @@ -47,11 +47,11 @@ namespace CalculatorApp // Using a DependencyProperty as the backing store for MaxFontSize. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxFontSizeProperty = - DependencyProperty.Register(nameof(MaxFontSize), typeof(double), typeof(CalculationResult), new PropertyMetadata(30.0, new PropertyChangedCallback((sender, args) => + DependencyProperty.Register(nameof(MaxFontSize), typeof(double), typeof(CalculationResult), new PropertyMetadata(30.0, (sender, args) => { var self = (CalculationResult)sender; self.OnMaxFontSizePropertyChanged((double)args.OldValue, (double)args.NewValue); - }))); + })); public Thickness DisplayMargin { @@ -71,11 +71,11 @@ namespace CalculatorApp // Using a DependencyProperty as the backing store for IsActive. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsActiveProperty = - DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(CalculationResult), new PropertyMetadata(default(bool), new PropertyChangedCallback((sender, args) => + DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(CalculationResult), new PropertyMetadata(default(bool), (sender, args) => { var self = (CalculationResult)sender; self.OnIsActivePropertyChanged((bool)args.OldValue, (bool)args.NewValue); - }))); + })); public string DisplayValue { @@ -85,11 +85,11 @@ namespace CalculatorApp // Using a DependencyProperty as the backing store for DisplayValue. This enables animation, styling, binding, etc... public static readonly DependencyProperty DisplayValueProperty = - DependencyProperty.Register(nameof(DisplayValue), typeof(string), typeof(CalculationResult), new PropertyMetadata(string.Empty, new PropertyChangedCallback((sender, args) => + DependencyProperty.Register(nameof(DisplayValue), typeof(string), typeof(CalculationResult), new PropertyMetadata(string.Empty, (sender, args) => { var self = (CalculationResult)sender; self.OnDisplayValuePropertyChanged((string)args.OldValue, (string)args.NewValue); - }))); + })); public bool IsInError { @@ -99,11 +99,11 @@ namespace CalculatorApp // Using a DependencyProperty as the backing store for IsInError. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsInErrorProperty = - DependencyProperty.Register(nameof(IsInError), typeof(bool), typeof(CalculationResult), new PropertyMetadata(default(bool), new PropertyChangedCallback((sender, args) => + DependencyProperty.Register(nameof(IsInError), typeof(bool), typeof(CalculationResult), new PropertyMetadata(default(bool), (sender, args) => { var self = (CalculationResult)sender; self.OnIsInErrorPropertyChanged((bool)args.OldValue, (bool)args.NewValue); - }))); + })); public bool IsOperatorCommand { @@ -151,7 +151,7 @@ namespace CalculatorApp if (widthDiff > WIDTHCUTOFF) { - fontSizeChange = Math.Min((double)Math.Max((double)Math.Floor(WIDTHTOFONTSCALAR * widthDiff) - WIDTHTOFONTOFFSET, INCREMENTOFFSET), MAXFONTINCREMENT); + fontSizeChange = Math.Min(Math.Max(Math.Floor(WIDTHTOFONTSCALAR * widthDiff) - WIDTHTOFONTOFFSET, INCREMENTOFFSET), MAXFONTINCREMENT); } if (m_textBlock.ActualWidth < containerSize && Math.Abs(m_textBlock.FontSize - MaxFontSize) > FONTTOLERANCE && !m_haveCalculatedMax) { diff --git a/src/Calculator/Controls/CalculatorButton.cs b/src/Calculator/Controls/CalculatorButton.cs index a081eeff..eae30f2c 100644 --- a/src/Calculator/Controls/CalculatorButton.cs +++ b/src/Calculator/Controls/CalculatorButton.cs @@ -33,11 +33,11 @@ namespace CalculatorApp // Using a DependencyProperty as the backing store for ButtonId. This enables animation, styling, binding, etc... public static readonly DependencyProperty ButtonIdProperty = - DependencyProperty.Register(nameof(ButtonId), typeof(NumbersAndOperatorsEnum), typeof(CalculatorButton), new PropertyMetadata(default(NumbersAndOperatorsEnum), new PropertyChangedCallback((sender, args) => + DependencyProperty.Register(nameof(ButtonId), typeof(NumbersAndOperatorsEnum), typeof(CalculatorButton), new PropertyMetadata(default(NumbersAndOperatorsEnum), (sender, args) => { var self = (CalculatorButton)sender; self.OnButtonIdPropertyChanged((NumbersAndOperatorsEnum)args.OldValue, (NumbersAndOperatorsEnum)args.NewValue); - }))); + })); public string AuditoryFeedback { @@ -47,11 +47,11 @@ namespace CalculatorApp // Using a DependencyProperty as the backing store for AuditoryFeedback. This enables animation, styling, binding, etc... public static readonly DependencyProperty AuditoryFeedbackProperty = - DependencyProperty.Register(nameof(AuditoryFeedback), typeof(string), typeof(CalculatorButton), new PropertyMetadata(string.Empty, new PropertyChangedCallback((sender, args) => + DependencyProperty.Register(nameof(AuditoryFeedback), typeof(string), typeof(CalculatorButton), new PropertyMetadata(string.Empty, (sender, args) => { var self = (CalculatorButton)sender; self.OnAuditoryFeedbackPropertyChanged((string)args.OldValue, (string)args.NewValue); - }))); + })); public Windows.UI.Xaml.Media.Brush HoverBackground { diff --git a/src/Calculator/Controls/EquationTextBox.cs b/src/Calculator/Controls/EquationTextBox.cs index 84943124..4ce4b966 100644 --- a/src/Calculator/Controls/EquationTextBox.cs +++ b/src/Calculator/Controls/EquationTextBox.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using CalculatorApp.ViewModel.Common; @@ -16,10 +16,6 @@ namespace CalculatorApp { public sealed class EquationTextBox : Windows.UI.Xaml.Controls.Control { - public EquationTextBox() - { - } - public Windows.UI.Xaml.Media.SolidColorBrush EquationColor { get => (Windows.UI.Xaml.Media.SolidColorBrush)GetValue(EquationColorProperty); diff --git a/src/Calculator/Controls/OperatorPanelButton.cs b/src/Calculator/Controls/OperatorPanelButton.cs index a5dfe7d2..ee35fccb 100644 --- a/src/Calculator/Controls/OperatorPanelButton.cs +++ b/src/Calculator/Controls/OperatorPanelButton.cs @@ -10,10 +10,6 @@ namespace CalculatorApp { public sealed class OperatorPanelButton : Windows.UI.Xaml.Controls.Primitives.ToggleButton { - public OperatorPanelButton() - { - } - public string Text { get => (string)GetValue(TextProperty); diff --git a/src/Calculator/Controls/OperatorPanelListView.cs b/src/Calculator/Controls/OperatorPanelListView.cs index 9f7ae6d3..048516a4 100644 --- a/src/Calculator/Controls/OperatorPanelListView.cs +++ b/src/Calculator/Controls/OperatorPanelListView.cs @@ -12,10 +12,6 @@ namespace CalculatorApp { public sealed class OperatorPanelListView : Windows.UI.Xaml.Controls.ListView { - public OperatorPanelListView() - { - } - protected override void OnApplyTemplate() { m_scrollViewer = GetTemplateChild("ScrollViewer") as ScrollViewer; diff --git a/src/Calculator/Controls/OverflowTextBlock.cs b/src/Calculator/Controls/OverflowTextBlock.cs index 13d4d951..8039c3e3 100644 --- a/src/Calculator/Controls/OverflowTextBlock.cs +++ b/src/Calculator/Controls/OverflowTextBlock.cs @@ -37,11 +37,11 @@ namespace CalculatorApp // Using a DependencyProperty as the backing store for TokensUpdated. This enables animation, styling, binding, etc... public static readonly DependencyProperty TokensUpdatedProperty = - DependencyProperty.Register(nameof(TokensUpdated), typeof(bool), typeof(OverflowTextBlock), new PropertyMetadata(default(bool), new PropertyChangedCallback((sender, args) => + DependencyProperty.Register(nameof(TokensUpdated), typeof(bool), typeof(OverflowTextBlock), new PropertyMetadata(default(bool), (sender, args) => { var self = (OverflowTextBlock)sender; self.OnTokensUpdatedPropertyChanged((bool)args.OldValue, (bool)args.NewValue); - }))); + })); public OverflowButtonPlacement ScrollButtonsPlacement { @@ -51,11 +51,11 @@ namespace CalculatorApp // Using a DependencyProperty as the backing store for ScrollButtonsPlacement. This enables animation, styling, binding, etc... public static readonly DependencyProperty ScrollButtonsPlacementProperty = - DependencyProperty.Register(nameof(ScrollButtonsPlacement), typeof(OverflowButtonPlacement), typeof(OverflowTextBlock), new PropertyMetadata(default(OverflowButtonPlacement), new PropertyChangedCallback((sender, args) => + DependencyProperty.Register(nameof(ScrollButtonsPlacement), typeof(OverflowButtonPlacement), typeof(OverflowTextBlock), new PropertyMetadata(default(OverflowButtonPlacement), (sender, args) => { var self = (OverflowTextBlock)sender; self.OnScrollButtonsPlacementPropertyChanged((OverflowButtonPlacement)args.OldValue, (OverflowButtonPlacement)args.NewValue); - }))); + })); public bool IsActive { diff --git a/src/Calculator/Controls/RadixButton.cs b/src/Calculator/Controls/RadixButton.cs index 42316e4d..5fa70833 100644 --- a/src/Calculator/Controls/RadixButton.cs +++ b/src/Calculator/Controls/RadixButton.cs @@ -9,9 +9,6 @@ namespace CalculatorApp { public sealed class RadixButton : Windows.UI.Xaml.Controls.RadioButton { - public RadixButton() - { } - internal string GetRawDisplayValue() { string radixContent = Content?.ToString(); diff --git a/src/Calculator/Controls/SupplementaryItemsControl.cs b/src/Calculator/Controls/SupplementaryItemsControl.cs index 90a5ffef..ccfb94d9 100644 --- a/src/Calculator/Controls/SupplementaryItemsControl.cs +++ b/src/Calculator/Controls/SupplementaryItemsControl.cs @@ -16,10 +16,6 @@ namespace CalculatorApp { public sealed class SupplementaryItemsControl : ItemsControl { - public SupplementaryItemsControl() - { - } - protected override DependencyObject GetContainerForItemOverride() { return new SupplementaryContentPresenter(); @@ -38,10 +34,6 @@ namespace CalculatorApp public sealed class SupplementaryContentPresenter : ContentPresenter { - public SupplementaryContentPresenter() - { - } - protected override AutomationPeer OnCreateAutomationPeer() { return new SupplementaryContentPresenterAP(this); diff --git a/src/Calculator/Converters/ExpressionItemTemplateSelector.cs b/src/Calculator/Converters/ExpressionItemTemplateSelector.cs index 086a9012..798a643b 100644 --- a/src/Calculator/Converters/ExpressionItemTemplateSelector.cs +++ b/src/Calculator/Converters/ExpressionItemTemplateSelector.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using CalculatorApp.ViewModel.Common; @@ -16,8 +16,7 @@ namespace CalculatorApp { protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { - DisplayExpressionToken token = (item as DisplayExpressionToken); - if (token != null) + if (item is DisplayExpressionToken token) { CalculatorApp.ViewModel.Common.TokenType type = token.Type; diff --git a/src/Calculator/Converters/RadixToStringConverter.cs b/src/Calculator/Converters/RadixToStringConverter.cs index 8c18fc56..7ff2e15d 100644 --- a/src/Calculator/Converters/RadixToStringConverter.cs +++ b/src/Calculator/Converters/RadixToStringConverter.cs @@ -42,8 +42,6 @@ namespace CalculatorApp convertedValue = resourceLoader.GetResourceString("Hex"); break; } - default: - break; } return convertedValue; diff --git a/src/Calculator/Selectors/KeyGraphFeaturesTemplateSelector.cs b/src/Calculator/Selectors/KeyGraphFeaturesTemplateSelector.cs index ebf67527..73596cd8 100644 --- a/src/Calculator/Selectors/KeyGraphFeaturesTemplateSelector.cs +++ b/src/Calculator/Selectors/KeyGraphFeaturesTemplateSelector.cs @@ -11,10 +11,6 @@ namespace CalculatorApp { public sealed class KeyGraphFeaturesTemplateSelector : Windows.UI.Xaml.Controls.DataTemplateSelector { - public KeyGraphFeaturesTemplateSelector() - { - } - public Windows.UI.Xaml.DataTemplate RichEditTemplate { get; set; } public Windows.UI.Xaml.DataTemplate GridTemplate { get; set; } public Windows.UI.Xaml.DataTemplate TextBlockTemplate { get; set; } diff --git a/src/Calculator/Utils/ThemeHelper.cs b/src/Calculator/Utils/ThemeHelper.cs index 08c8740a..6303884d 100644 --- a/src/Calculator/Utils/ThemeHelper.cs +++ b/src/Calculator/Utils/ThemeHelper.cs @@ -79,7 +79,7 @@ namespace CalculatorApp.Utils if (callbackToken.RootFrame.IsAlive) { Frame rootFrame = callbackToken.RootFrame.Target as Frame; - rootFrame.UnregisterPropertyChangedCallback(Frame.RequestedThemeProperty, callbackToken.Token); + rootFrame.UnregisterPropertyChangedCallback(FrameworkElement.RequestedThemeProperty, callbackToken.Token); } } } diff --git a/src/Calculator/Views/Calculator.xaml.cs b/src/Calculator/Views/Calculator.xaml.cs index c12e95a8..31d7accd 100644 --- a/src/Calculator/Views/Calculator.xaml.cs +++ b/src/Calculator/Views/Calculator.xaml.cs @@ -225,7 +225,7 @@ namespace CalculatorApp string memoryPaneName = AppResourceProvider.GetInstance().GetResourceString("MemoryPane"); MemoryFlyout.FlyoutPresenterStyle.Setters.Add(new Setter(AutomationProperties.NameProperty, memoryPaneName)); - if (Windows.Foundation.Metadata.ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.Primitives.FlyoutBase", "Closing")) + if (Windows.Foundation.Metadata.ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.Primitives.FlyoutBase", nameof(FlyoutBase.Closing))) { HistoryFlyout.Closing += HistoryFlyout_Closing; MemoryFlyout.Closing += OnMemoryFlyoutClosing; @@ -234,7 +234,7 @@ namespace CalculatorApp // Delay load things later when we get a chance. WeakReference weakThis = new WeakReference(this); _ = this.Dispatcher.RunAsync( - CoreDispatcherPriority.Normal, new DispatchedHandler(() => + CoreDispatcherPriority.Normal, () => { if (TraceLogger.GetInstance().IsWindowIdInLog(ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()))) { @@ -243,7 +243,7 @@ namespace CalculatorApp refThis.GetMemory(); } } - })); + }); } private void LoadResourceStrings() diff --git a/src/Calculator/Views/CalculatorProgrammerDisplayPanel.xaml.cs b/src/Calculator/Views/CalculatorProgrammerDisplayPanel.xaml.cs index 3d87273f..8803dc4b 100644 --- a/src/Calculator/Views/CalculatorProgrammerDisplayPanel.xaml.cs +++ b/src/Calculator/Views/CalculatorProgrammerDisplayPanel.xaml.cs @@ -36,7 +36,7 @@ namespace CalculatorApp { get { - Debug.Assert(DataContext as ViewModel.StandardCalculatorViewModel != null, "static_cast result must NOT be null"); + Debug.Assert(DataContext is ViewModel.StandardCalculatorViewModel, "static_cast result must NOT be null"); return DataContext as ViewModel.StandardCalculatorViewModel; } } diff --git a/src/Calculator/Views/CalculatorProgrammerOperators.xaml.cs b/src/Calculator/Views/CalculatorProgrammerOperators.xaml.cs index 8ae5fb99..d6048018 100644 --- a/src/Calculator/Views/CalculatorProgrammerOperators.xaml.cs +++ b/src/Calculator/Views/CalculatorProgrammerOperators.xaml.cs @@ -58,37 +58,25 @@ namespace CalculatorApp private void DecButtonChecked(object sender, RoutedEventArgs e) { TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.DecButton, ViewMode.Programmer); - if (Model != null) - { - Model.SwitchProgrammerModeBase(NumberBase.DecBase); - } + Model?.SwitchProgrammerModeBase(NumberBase.DecBase); } private void HexButtonChecked(object sender, RoutedEventArgs e) { TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.HexButton, ViewMode.Programmer); - if (Model != null) - { - Model.SwitchProgrammerModeBase(NumberBase.HexBase); - } + Model?.SwitchProgrammerModeBase(NumberBase.HexBase); } private void BinButtonChecked(object sender, RoutedEventArgs e) { TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.BinButton, ViewMode.Programmer); - if (Model != null) - { - Model.SwitchProgrammerModeBase(NumberBase.BinBase); - } + Model?.SwitchProgrammerModeBase(NumberBase.BinBase); } private void OctButtonChecked(object sender, RoutedEventArgs e) { TraceLogger.GetInstance().UpdateButtonUsage(NumbersAndOperatorsEnum.OctButton, ViewMode.Programmer); - if (Model != null) - { - Model.SwitchProgrammerModeBase(NumberBase.OctBase); - } + Model?.SwitchProgrammerModeBase(NumberBase.OctBase); } private void OnCopyMenuItemClicked(object sender, RoutedEventArgs e) diff --git a/src/Calculator/Views/GraphingCalculator/EquationInputArea.xaml.cs b/src/Calculator/Views/GraphingCalculator/EquationInputArea.xaml.cs index d6d03d8e..f6bfb756 100644 --- a/src/Calculator/Views/GraphingCalculator/EquationInputArea.xaml.cs +++ b/src/Calculator/Views/GraphingCalculator/EquationInputArea.xaml.cs @@ -38,8 +38,8 @@ namespace CalculatorApp m_accessibilitySettings.HighContrastChanged += OnHighContrastChanged; m_isHighContrast = m_accessibilitySettings.HighContrast; - m_uiSettings = new UISettings(); - m_uiSettings.ColorValuesChanged += OnColorValuesChanged; + var mUiSettings = new UISettings(); + mUiSettings.ColorValuesChanged += OnColorValuesChanged; ReloadAvailableColors(m_accessibilitySettings.HighContrast, true); @@ -258,8 +258,7 @@ namespace CalculatorApp } if (submission.Source == EquationSubmissionSource.ENTER_KEY - || (submission.Source == EquationSubmissionSource.FOCUS_LOST && submission.HasTextChanged && eq.Expression != null - && eq.Expression.Length > 0)) + || (submission.Source == EquationSubmissionSource.FOCUS_LOST && submission.HasTextChanged && !string.IsNullOrEmpty(eq.Expression))) { if (submission.Source == EquationSubmissionSource.ENTER_KEY) { @@ -355,13 +354,13 @@ namespace CalculatorApp { WeakReference weakThis = new WeakReference(this); - _ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => + _ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (weakThis.Target is EquationInputArea refThis && refThis.m_isHighContrast == refThis.m_accessibilitySettings.HighContrast) { refThis.ReloadAvailableColors(false, false); } - })); + }); } private void EquationTextBox_RemoveButtonClicked(object sender, RoutedEventArgs e) @@ -436,10 +435,7 @@ namespace CalculatorApp if (index >= 0) { var container = (UIElement)EquationInputList.ContainerFromIndex(index); - if (container != null) - { - container.StartBringIntoView(); - } + container?.StartBringIntoView(); } } } @@ -466,10 +462,7 @@ namespace CalculatorApp if (index >= 0) { var container = (UIElement)EquationInputList.ContainerFromIndex(index); - if (container != null) - { - container.StartBringIntoView(); - } + container?.StartBringIntoView(); } } } @@ -594,11 +587,11 @@ namespace CalculatorApp { TimeSpan timeSpan = new TimeSpan(10000000); // 1 tick = 100 nanoseconds, and 10000000 ticks = 1 second. DispatcherTimerDelayer delayer = new DispatcherTimerDelayer(timeSpan); - delayer.Action += new EventHandler((object s, object arg) => + delayer.Action += (object s, object arg) => { CalculatorApp.ViewModel.Common.TraceLogger.GetInstance().LogVariableChanged("Slider", name); variableSliders.Remove(name); - }); + }; delayer.Start(); variableSliders.Add(name, delayer); } @@ -612,12 +605,8 @@ namespace CalculatorApp private EquationViewModel GetViewModelFromEquationTextBox(object sender) { var tb = (EquationTextBox)sender; - if (tb == null) - { - return null; - } - var eq = (EquationViewModel)tb.DataContext; + var eq = (EquationViewModel)tb?.DataContext; return eq; } @@ -643,7 +632,6 @@ namespace CalculatorApp private const string IsMatchAppThemePropertyName = "IsMatchAppTheme"; private readonly Windows.UI.ViewManagement.AccessibilitySettings m_accessibilitySettings; - private readonly Windows.UI.ViewManagement.UISettings m_uiSettings; private int m_lastLineColorIndex; private int m_lastFunctionLabelIndex; private bool m_isHighContrast; diff --git a/src/Calculator/Views/GraphingCalculator/EquationStylePanelControl.xaml.cs b/src/Calculator/Views/GraphingCalculator/EquationStylePanelControl.xaml.cs index 58b5f7a9..83f3dc35 100644 --- a/src/Calculator/Views/GraphingCalculator/EquationStylePanelControl.xaml.cs +++ b/src/Calculator/Views/GraphingCalculator/EquationStylePanelControl.xaml.cs @@ -230,14 +230,7 @@ namespace CalculatorApp if (e.AddedItems.Count > 0) { var brush = (e.AddedItems[0] as SolidColorBrush); - if (brush == null) - { - SelectedColor = Colors.Black; - } - else - { - SelectedColor = brush.Color; - } + SelectedColor = brush?.Color ?? Colors.Black; CalculatorApp.ViewModel.Common.TraceLogger.GetInstance().LogGraphLineStyleChanged(LineStyleType.Color); } @@ -293,9 +286,8 @@ namespace CalculatorApp foreach (var item in StyleChooserBox.Items) { var style = ((EquationLineStyle)item); - var comboBoxItem = (StyleChooserBox.ContainerFromItem(style) as ComboBoxItem); - if (comboBoxItem == null) + if (!(StyleChooserBox.ContainerFromItem(style) is ComboBoxItem comboBoxItem)) { continue; } diff --git a/src/Calculator/Views/GraphingCalculator/GraphingCalculator.xaml.cs b/src/Calculator/Views/GraphingCalculator/GraphingCalculator.xaml.cs index 8e6526a1..4402e878 100644 --- a/src/Calculator/Views/GraphingCalculator/GraphingCalculator.xaml.cs +++ b/src/Calculator/Views/GraphingCalculator/GraphingCalculator.xaml.cs @@ -75,8 +75,8 @@ namespace CalculatorApp m_accessibilitySettings.HighContrastChanged += OnHighContrastChanged; - m_uiSettings = new UISettings(); - m_uiSettings.ColorValuesChanged += OnColorValuesChanged; + var mUiSettings = new UISettings(); + mUiSettings.ColorValuesChanged += OnColorValuesChanged; ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; @@ -376,10 +376,7 @@ namespace CalculatorApp var peer = FrameworkElementAutomationPeer.FromElement(TraceValue); - if (peer != null) - { - peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged); - } + peer?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged); PositionGraphPopup(); } @@ -402,19 +399,16 @@ namespace CalculatorApp try { - string rawHtml; - string equationHtml; - - rawHtml = "

" + resourceLoader.GetString("GraphImageAltText") + "

"; + var rawHtml = "

" + resourceLoader.GetString("GraphImageAltText") + "

"; var equations = ViewModel.Equations; bool hasEquations = false; if (equations.Count > 0) { - equationHtml = "" - + resourceLoader.GetString("EquationsShareHeader") + "" - + ""; + var equationHtml = "" + + resourceLoader.GetString("EquationsShareHeader") + "" + + "
"; foreach (var equation in equations) { @@ -429,8 +423,7 @@ namespace CalculatorApp expression = GraphingControl.ConvertToLinear(expression); - string equationColorHtml; - equationColorHtml = "color:rgb(" + color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString() + ");"; + var equationColorHtml = "color:rgb(" + color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString() + ");"; equationHtml += "
" @@ -518,7 +511,7 @@ namespace CalculatorApp private void GraphingControl_LosingFocus(UIElement sender, LosingFocusEventArgs args) { - if (!(args.NewFocusedElement is FrameworkElement newFocusElement) || newFocusElement.Name == null) + if (!(args.NewFocusedElement is FrameworkElement)) { // Because clicking on the swap chain panel will try to move focus to a control that can't actually take focus // we will get a null destination. So we are going to try and cancel that request. @@ -534,23 +527,13 @@ namespace CalculatorApp private void GraphingControl_GraphViewChangedEvent(object sender, GraphViewChangedReason reason) { - if (reason == GraphViewChangedReason.Manipulation) - { - IsManualAdjustment = true; - } - else - { - IsManualAdjustment = false; - } + IsManualAdjustment = reason == GraphViewChangedReason.Manipulation; UpdateGraphAutomationName(); var announcement = CalculatorAnnouncement.GetGraphViewChangedAnnouncement(GraphControlAutomationName); var peer = FrameworkElementAutomationPeer.FromElement(GraphingControl); - if (peer != null) - { - peer.RaiseNotificationEvent(announcement.Kind, announcement.Processing, announcement.Announcement, announcement.ActivityId); - } + peer?.RaiseNotificationEvent(announcement.Kind, announcement.Processing, announcement.Announcement, announcement.ActivityId); } private void GraphingControl_GraphPlottedEvent(object sender, RoutedEventArgs e) @@ -752,13 +735,13 @@ namespace CalculatorApp private void OnColorValuesChanged(UISettings sender, object args) { WeakReference weakThis = new WeakReference(this); - _ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => + _ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (weakThis.Target is GraphingCalculator refThis && IsMatchAppTheme) { refThis.UpdateGraphTheme(); } - })); + }); } private void UpdateGraphTheme() @@ -788,13 +771,13 @@ namespace CalculatorApp IsMatchAppTheme = isMatchAppTheme; WeakReference weakThis = new WeakReference(this); - _ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => + _ = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (weakThis.Target is GraphingCalculator refThis) { refThis.UpdateGraphTheme(); } - })); + }); } private const double zoomInScale = 1 / 1.0625; @@ -805,7 +788,6 @@ namespace CalculatorApp private CalculatorApp.ViewModel.GraphingCalculatorViewModel m_viewModel; private readonly Windows.UI.ViewManagement.AccessibilitySettings m_accessibilitySettings; private bool m_cursorShadowInitialized; - private readonly Windows.UI.ViewManagement.UISettings m_uiSettings; private Windows.UI.Xaml.Controls.Flyout m_graphFlyout; private CalculatorApp.GraphingSettings m_graphSettings; diff --git a/src/Calculator/Views/GraphingCalculator/GraphingNumPad.xaml.cs b/src/Calculator/Views/GraphingCalculator/GraphingNumPad.xaml.cs index 4f1ffc2a..55998d53 100644 --- a/src/Calculator/Views/GraphingCalculator/GraphingNumPad.xaml.cs +++ b/src/Calculator/Views/GraphingCalculator/GraphingNumPad.xaml.cs @@ -103,11 +103,11 @@ namespace CalculatorApp { InverseHyperbolicTrigFunctions.Visibility = Visibility.Visible; } - else if (isShiftChecked && !isHypeChecked) + else if (isShiftChecked) { InverseTrigFunctions.Visibility = Visibility.Visible; } - else if (!isShiftChecked && isHypeChecked) + else if (isHypeChecked) { HyperbolicTrigFunctions.Visibility = Visibility.Visible; } diff --git a/src/Calculator/Views/GraphingCalculator/GraphingSettings.xaml.cs b/src/Calculator/Views/GraphingCalculator/GraphingSettings.xaml.cs index d847408c..46929ab1 100644 --- a/src/Calculator/Views/GraphingCalculator/GraphingSettings.xaml.cs +++ b/src/Calculator/Views/GraphingCalculator/GraphingSettings.xaml.cs @@ -25,7 +25,7 @@ namespace CalculatorApp InitializeComponent(); } - public CalculatorApp.ViewModel.GraphingSettingsViewModel ViewModel { get; set; } + public CalculatorApp.ViewModel.GraphingSettingsViewModel ViewModel { get; } public bool IsMatchAppTheme { diff --git a/src/Calculator/Views/HistoryList.xaml.cs b/src/Calculator/Views/HistoryList.xaml.cs index 13f67e91..639c6dee 100644 --- a/src/Calculator/Views/HistoryList.xaml.cs +++ b/src/Calculator/Views/HistoryList.xaml.cs @@ -48,11 +48,8 @@ namespace CalculatorApp private void ListView_ItemClick(object sender, ItemClickEventArgs e) { - HistoryViewModel historyVM = (DataContext as HistoryViewModel); - HistoryItemViewModel clickedItem = (e.ClickedItem as HistoryItemViewModel); - // When the user clears the history list in the overlay view and presses enter, the clickedItem is nullptr - if (clickedItem != null && historyVM != null) + if (e.ClickedItem is HistoryItemViewModel clickedItem && DataContext is HistoryViewModel historyVM) { historyVM.ShowItem(clickedItem); } @@ -60,8 +57,7 @@ namespace CalculatorApp private void OnCopyMenuItemClicked(object sender, RoutedEventArgs e) { var listViewItem = HistoryContextMenu.Target; - var itemViewModel = (HistoryListView.ItemFromContainer(listViewItem) as HistoryItemViewModel); - if (itemViewModel != null) + if (HistoryListView.ItemFromContainer(listViewItem) is HistoryItemViewModel itemViewModel) { CopyPasteManager.CopyToClipboard(itemViewModel.Result); } @@ -69,16 +65,14 @@ namespace CalculatorApp private void OnDeleteMenuItemClicked(object sender, RoutedEventArgs e) { var listViewItem = HistoryContextMenu.Target; - var itemViewModel = (HistoryListView.ItemFromContainer(listViewItem) as HistoryItemViewModel); - if (itemViewModel != null) + if (HistoryListView.ItemFromContainer(listViewItem) is HistoryItemViewModel itemViewModel) { Model.DeleteItem(itemViewModel); } } private void OnDeleteSwipeInvoked(MUXC.SwipeItem sender, MUXC.SwipeItemInvokedEventArgs e) { - var swipedItem = (e.SwipeControl.DataContext as HistoryItemViewModel); - if (swipedItem != null) + if (e.SwipeControl.DataContext is HistoryItemViewModel swipedItem) { Model.DeleteItem(swipedItem); } diff --git a/src/Calculator/Views/MainPage.xaml.cs b/src/Calculator/Views/MainPage.xaml.cs index a20c92d9..26c2f328 100644 --- a/src/Calculator/Views/MainPage.xaml.cs +++ b/src/Calculator/Views/MainPage.xaml.cs @@ -66,10 +66,7 @@ namespace CalculatorApp Window.Current.SizeChanged -= WindowSizeChanged; m_accessibilitySettings.HighContrastChanged -= OnHighContrastChanged; - if (m_calculator != null) - { - m_calculator.UnregisterEventHandlers(); - } + m_calculator?.UnregisterEventHandlers(); } public void SetDefaultFocus() @@ -368,8 +365,7 @@ namespace CalculatorApp return; } - var item = (e.SelectedItemContainer as MUXC.NavigationViewItem); - if (item != null) + if (e.SelectedItemContainer is MUXC.NavigationViewItem item) { Model.Mode = (ViewMode)item.Tag; } @@ -435,10 +431,7 @@ namespace CalculatorApp private void UpdatePanelViewState() { - if (m_calculator != null) - { - m_calculator.UpdatePanelViewState(); - } + m_calculator?.UpdatePanelViewState(); } private void OnHighContrastChanged(AccessibilitySettings sender, object args) @@ -468,14 +461,14 @@ namespace CalculatorApp // Delay load things later when we get a chance. _ = Dispatcher.RunAsync( - CoreDispatcherPriority.Normal, new DispatchedHandler(() => + CoreDispatcherPriority.Normal, () => { if (TraceLogger.GetInstance().IsWindowIdInLog(ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()))) { AppLifecycleLogger.GetInstance().LaunchUIResponsive(); AppLifecycleLogger.GetInstance().LaunchVisibleComplete(); } - })); + }); } private void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) @@ -528,10 +521,7 @@ namespace CalculatorApp ShowHideControls(Model.Mode); } - if (m_dateCalculator != null) - { - m_dateCalculator.CloseCalendarFlyout(); - } + m_dateCalculator?.CloseCalendarFlyout(); } private void EnsureDateCalculator() diff --git a/src/Calculator/Views/Memory.xaml.cs b/src/Calculator/Views/Memory.xaml.cs index d327727a..8b93f6a0 100644 --- a/src/Calculator/Views/Memory.xaml.cs +++ b/src/Calculator/Views/Memory.xaml.cs @@ -60,28 +60,19 @@ namespace CalculatorApp private void OnClearMenuItemClicked(object sender, RoutedEventArgs e) { var memoryItem = GetMemoryItemForCurrentFlyout(); - if (memoryItem != null) - { - memoryItem.Clear(); - } + memoryItem?.Clear(); } private void OnMemoryAddMenuItemClicked(object sender, RoutedEventArgs e) { var memoryItem = GetMemoryItemForCurrentFlyout(); - if (memoryItem != null) - { - memoryItem.MemoryAdd(); - } + memoryItem?.MemoryAdd(); } private void OnMemorySubtractMenuItemClicked(object sender, RoutedEventArgs e) { var memoryItem = GetMemoryItemForCurrentFlyout(); - if (memoryItem != null) - { - memoryItem.MemorySubtract(); - } + memoryItem?.MemorySubtract(); } private MemoryItemViewModel GetMemoryItemForCurrentFlyout() diff --git a/src/Calculator/Views/SupplementaryResults.xaml.cs b/src/Calculator/Views/SupplementaryResults.xaml.cs index e01a1f06..4284b54a 100644 --- a/src/Calculator/Views/SupplementaryResults.xaml.cs +++ b/src/Calculator/Views/SupplementaryResults.xaml.cs @@ -1,4 +1,4 @@ -using CalculatorApp.ViewModel; +using CalculatorApp.ViewModel; using System; using System.Collections.Generic; @@ -46,9 +46,6 @@ namespace CalculatorApp public sealed class SupplementaryResultDataTemplateSelector : Windows.UI.Xaml.Controls.DataTemplateSelector { - public SupplementaryResultDataTemplateSelector() - { } - public Windows.UI.Xaml.DataTemplate RegularTemplate { get; set; } public Windows.UI.Xaml.DataTemplate DelighterTemplate { get; set; } diff --git a/src/Calculator/Views/TitleBar.xaml.cs b/src/Calculator/Views/TitleBar.xaml.cs index 54ca2025..30baf0a2 100644 --- a/src/Calculator/Views/TitleBar.xaml.cs +++ b/src/Calculator/Views/TitleBar.xaml.cs @@ -92,7 +92,7 @@ namespace CalculatorApp { if (Frame.RequestedThemeProperty == dp) { - _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { SetTitleBarControlColors(); })); + _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, SetTitleBarControlColors); } } @@ -120,8 +120,8 @@ namespace CalculatorApp return; } - double leftAddition = 0; - double rightAddition = 0; + double leftAddition; + double rightAddition; if (FlowDirection == FlowDirection.LeftToRight) { @@ -140,18 +140,14 @@ namespace CalculatorApp private void ColorValuesChanged(Windows.UI.ViewManagement.UISettings sender, object e) { - _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { SetTitleBarControlColors(); })); + _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, SetTitleBarControlColors); } private void SetTitleBarControlColors() { var applicationView = ApplicationView.GetForCurrentView(); - if (applicationView == null) - { - return; - } - var applicationTitleBar = applicationView.TitleBar; + var applicationTitleBar = applicationView?.TitleBar; if (applicationTitleBar == null) { return; @@ -184,11 +180,11 @@ namespace CalculatorApp private void OnHighContrastChanged(Windows.UI.ViewManagement.AccessibilitySettings sender, object args) { - _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => + _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { SetTitleBarControlColors(); SetTitleBarVisibility(false); - })); + }); } private void OnWindowActivated(object sender, WindowActivatedEventArgs e) @@ -281,12 +277,12 @@ namespace CalculatorApp public static readonly DependencyProperty BackButtonSpaceReservedProperty = DependencyProperty.Register( nameof(BackButtonSpaceReserved), typeof(bool), typeof(TitleBar), - new PropertyMetadata(false, new PropertyChangedCallback((sender, args) => + new PropertyMetadata(false, (sender, args) => { var self = sender as TitleBar; VisualStateManager.GoToState( self, (bool)args.NewValue ? self.BackButtonVisible.Name : self.BackButtonCollapsed.Name, true); - }))); + })); private readonly Windows.ApplicationModel.Core.CoreApplicationViewTitleBar m_coreTitleBar; private readonly Windows.UI.ViewManagement.UISettings m_uiSettings; diff --git a/src/Calculator/Views/UnitConverter.xaml.cs b/src/Calculator/Views/UnitConverter.xaml.cs index 5ea4ff66..e108189e 100644 --- a/src/Calculator/Views/UnitConverter.xaml.cs +++ b/src/Calculator/Views/UnitConverter.xaml.cs @@ -368,10 +368,7 @@ namespace CalculatorApp private void HideProgressRing() { - if (m_delayTimer != null) - { - m_delayTimer.Stop(); - } + m_delayTimer?.Stop(); CurrencyLoadingProgressRing.IsActive = false; } @@ -391,8 +388,8 @@ namespace CalculatorApp private static readonly Lazy uiSettings = new Lazy(true); private readonly Windows.UI.Xaml.Controls.MenuFlyout m_resultsFlyout = default; - private readonly string m_chargesMayApplyText = string.Empty; - private readonly string m_failedToRefreshText = string.Empty; + private readonly string m_chargesMayApplyText; + private readonly string m_failedToRefreshText; private bool m_meteredConnectionOverride; diff --git a/src/Calculator/WindowFrameService.cs b/src/Calculator/WindowFrameService.cs index e2501b3a..55f5c7d8 100644 --- a/src/Calculator/WindowFrameService.cs +++ b/src/Calculator/WindowFrameService.cs @@ -59,7 +59,7 @@ namespace CalculatorApp public Task HandleViewRelease() { TaskCompletionSource tsource = new TaskCompletionSource(); - _ = m_coreDispatcher.RunAsync(CoreDispatcherPriority.Low, new DispatchedHandler(() => + _ = m_coreDispatcher.RunAsync(CoreDispatcherPriority.Low, () => { KeyboardShortcutManager.OnWindowClosed(this.m_viewId); Window.Current.Content = null; @@ -70,7 +70,7 @@ namespace CalculatorApp tsource.SetResult(new object()); this.m_coreDispatcher.StopProcessEvents(); Window.Current.Close(); - })); + }); return tsource.Task; } diff --git a/src/CalculatorUITestFramework/HistoryItem.cs b/src/CalculatorUITestFramework/HistoryItem.cs index 2d4c4245..4c46fdc7 100644 --- a/src/CalculatorUITestFramework/HistoryItem.cs +++ b/src/CalculatorUITestFramework/HistoryItem.cs @@ -17,12 +17,12 @@ namespace CalculatorUITestFramework public string GetValue() { var equalSignIndex = Item.Text.IndexOf("="); - return Item.Text.Substring(equalSignIndex + 1).Trim(); + return Item.Text[(equalSignIndex + 1)..].Trim(); } public string GetExpression() { var equalSignIndex = Item.Text.IndexOf("="); - return Item.Text.Substring(0, equalSignIndex + 1).Trim(); + return Item.Text[..(equalSignIndex + 1)].Trim(); } } } diff --git a/src/CalculatorUITestFramework/NavigationMenu.cs b/src/CalculatorUITestFramework/NavigationMenu.cs index 13dab3ac..6de7ac15 100644 --- a/src/CalculatorUITestFramework/NavigationMenu.cs +++ b/src/CalculatorUITestFramework/NavigationMenu.cs @@ -41,63 +41,27 @@ namespace CalculatorUITestFramework /// The mode to be changed to public void ChangeCalculatorMode(CalculatorMode mode) { - string modeAccessibilityId; - switch (mode) + string modeAccessibilityId = mode switch { - case CalculatorMode.StandardCalculator: - modeAccessibilityId = "Standard"; - break; - case CalculatorMode.ScientificCalculator: - modeAccessibilityId = "Scientific"; - break; - case CalculatorMode.ProgrammerCalculator: - modeAccessibilityId = "Programmer"; - break; - case CalculatorMode.DateCalculator: - modeAccessibilityId = "Date"; - break; - case CalculatorMode.Currency: - modeAccessibilityId = "Currency"; - break; - case CalculatorMode.Volume: - modeAccessibilityId = "Volume"; - break; - case CalculatorMode.Length: - modeAccessibilityId = "Length"; - break; - case CalculatorMode.Weight: - modeAccessibilityId = "Weight"; - break; - case CalculatorMode.Temperature: - modeAccessibilityId = "Temperature"; - break; - case CalculatorMode.Energy: - modeAccessibilityId = "Energy"; - break; - case CalculatorMode.Area: - modeAccessibilityId = "Area"; - break; - case CalculatorMode.Speed: - modeAccessibilityId = "Speed"; - break; - case CalculatorMode.Time: - modeAccessibilityId = "Time"; - break; - case CalculatorMode.Power: - modeAccessibilityId = "Power"; - break; - case CalculatorMode.Data: - modeAccessibilityId = "Data"; - break; - case CalculatorMode.Pressure: - modeAccessibilityId = "Pressure"; - break; - case CalculatorMode.Angle: - modeAccessibilityId = "Angle"; - break; - default: - throw (new ArgumentException("The mode is not valid")); - } + CalculatorMode.StandardCalculator => "Standard", + CalculatorMode.ScientificCalculator => "Scientific", + CalculatorMode.ProgrammerCalculator => "Programmer", + CalculatorMode.DateCalculator => "Date", + CalculatorMode.Currency => "Currency", + CalculatorMode.Volume => "Volume", + CalculatorMode.Length => "Length", + CalculatorMode.Weight => "Weight", + CalculatorMode.Temperature => "Temperature", + CalculatorMode.Energy => "Energy", + CalculatorMode.Area => "Area", + CalculatorMode.Speed => "Speed", + CalculatorMode.Time => "Time", + CalculatorMode.Power => "Power", + CalculatorMode.Data => "Data", + CalculatorMode.Pressure => "Pressure", + CalculatorMode.Angle => "Angle", + _ => throw (new ArgumentException("The mode is not valid")) + }; this.NavigationMenuButton.Click(); this.NavigationMenuPane.WaitForDisplayed(); diff --git a/src/CalculatorUITestFramework/NumberPad.cs b/src/CalculatorUITestFramework/NumberPad.cs index 225fb570..7df07ca5 100644 --- a/src/CalculatorUITestFramework/NumberPad.cs +++ b/src/CalculatorUITestFramework/NumberPad.cs @@ -34,7 +34,7 @@ namespace CalculatorUITestFramework string numberStr = number.ToString(CultureInfo.InvariantCulture); if (numberStr.StartsWith("-")) { - numberStr = numberStr.Substring(1) + "-"; + numberStr = numberStr[1..] + "-"; } foreach (char digit in numberStr) { @@ -77,7 +77,7 @@ namespace CalculatorUITestFramework this.NegateButton.Click(); break; default: - throw (new ArgumentException(string.Format("{0} is not valid", digit))); + throw (new ArgumentException($"{digit} is not valid")); } } } diff --git a/src/CalculatorUITestFramework/ScientificOperatorsPanel.cs b/src/CalculatorUITestFramework/ScientificOperatorsPanel.cs index ce94241c..b1146f05 100644 --- a/src/CalculatorUITestFramework/ScientificOperatorsPanel.cs +++ b/src/CalculatorUITestFramework/ScientificOperatorsPanel.cs @@ -109,21 +109,13 @@ namespace CalculatorUITestFramework public void SetAngleOperator(AngleOperatorState value) { //set the desired string value for the button - string desiredId; - switch (value) + string desiredId = value switch { - case AngleOperatorState.Degrees: - desiredId = "degButton"; - break; - case AngleOperatorState.Gradians: - desiredId = "gradButton"; - break; - case AngleOperatorState.Radians: - desiredId = "radButton"; - break; - default: - throw new NotImplementedException(); - } + AngleOperatorState.Degrees => "degButton", + AngleOperatorState.Gradians => "gradButton", + AngleOperatorState.Radians => "radButton", + _ => throw new NotImplementedException() + }; while (this.DegRadGradButton.GetAttribute("AutomationId") != desiredId) { this.DegRadGradButton.Click(); diff --git a/src/CalculatorUITestFramework/WinAppDriver.cs b/src/CalculatorUITestFramework/WinAppDriver.cs index df8d4d32..629afe7a 100644 --- a/src/CalculatorUITestFramework/WinAppDriver.cs +++ b/src/CalculatorUITestFramework/WinAppDriver.cs @@ -16,18 +16,7 @@ namespace CalculatorUITestFramework public MemoryPanel MemoryPanel = new MemoryPanel(); private const string defaultAppId = "Microsoft.WindowsCalculator.Dev_8wekyb3d8bbwe!App"; private static WinAppDriver instance = null; - public static WinAppDriver Instance - { - get - { - if (instance == null) - { - instance = new WinAppDriver(); - } - return instance; - } - - } + public static WinAppDriver Instance => instance ??= new WinAppDriver(); public WindowsDriver CalculatorSession { get; private set; } diff --git a/src/CalculatorUITestFramework/WindowsDriverLocalService.cs b/src/CalculatorUITestFramework/WindowsDriverLocalService.cs index 16a21229..b479d2eb 100644 --- a/src/CalculatorUITestFramework/WindowsDriverLocalService.cs +++ b/src/CalculatorUITestFramework/WindowsDriverLocalService.cs @@ -18,6 +18,7 @@ using System; using System.Diagnostics; using System.IO; using System.Net; +using System.Net.Http; using System.Runtime.CompilerServices; namespace CalculatorUITestFramework @@ -143,11 +144,11 @@ namespace CalculatorUITestFramework private bool Ping() { - bool pinged = false; - Uri status; - Uri service = this.ServiceUrl; + var httpClient = new HttpClient(); + httpClient.Timeout = this.InitializationTimeout; + if (service.IsLoopback) { status = new Uri("http://localhost:" + Convert.ToString(this.Port) + "/status"); @@ -157,31 +158,8 @@ namespace CalculatorUITestFramework status = new Uri(service + "/status"); } - DateTime endTime = DateTime.Now.Add(this.InitializationTimeout); - while (!pinged & DateTime.Now < endTime) - { - HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(status); - HttpWebResponse response = null; - try - { - using (response = (HttpWebResponse)request.GetResponse()) - { - pinged = true; - } - } - catch (Exception) - { - pinged = false; - } - finally - { - if (response != null) - { - response.Close(); - } - } - } - return pinged; + var httpResponse = httpClient.GetAsync(status); + return httpResponse.Result.IsSuccessStatusCode; } } } diff --git a/src/CalculatorUITestFramework/WindowsDriverServiceBuilder.cs b/src/CalculatorUITestFramework/WindowsDriverServiceBuilder.cs index bdf60574..e58e261f 100644 --- a/src/CalculatorUITestFramework/WindowsDriverServiceBuilder.cs +++ b/src/CalculatorUITestFramework/WindowsDriverServiceBuilder.cs @@ -39,16 +39,12 @@ namespace CalculatorUITestFramework public WindowsDriverServiceBuilder WithFileInfo(FileInfo fileInfo) { - this.FileInfo = fileInfo ?? throw new ArgumentNullException("FileInfo should not be NULL"); + this.FileInfo = fileInfo ?? throw new ArgumentNullException("FileInfo should not be null"); return this; } public WindowsDriverServiceBuilder WithStartUpTimeOut(TimeSpan startUpTimeout) { - if (startUpTimeout == null) - { - throw new ArgumentNullException("A startup timeout should not be NULL"); - } this.StartUpTimeout = startUpTimeout; return this; }