From 70e9c98adbcd9450fa1adb51efe97ae753785443 Mon Sep 17 00:00:00 2001 From: Vincent Gromfeld Date: Fri, 28 Feb 2020 15:15:14 +0100 Subject: [PATCH 1/6] remove unused fields --- .../Markdown/Blocks/YamlHeaderBlock.cs | 3 -- .../Markdown/Inlines/ImageInline.cs | 4 +- .../Markdown/MarkdownDocument.cs | 2 +- Microsoft.Toolkit.Parsers/Rss/RssHelper.cs | 8 ++- .../OAuth/OAuthParameter.cs | 2 +- .../ObservableGattDeviceService.cs | 9 ++-- .../DesktopNotificationManagerCompat.cs | 6 +-- .../Builder/ToastContentBuilder.Actions.cs | 7 ++- .../Toasts/ToastPeople.cs | 2 +- .../Program.cs | 8 +-- .../Analyzer.cs | 4 +- .../PlatformSpecificAnalyzerCS.cs | 5 +- .../PlatformSpecificAnalyzerVB.cs | 5 +- .../Pages/SampleController.xaml.cs | 3 +- .../ImageCache/ImageCachePage.xaml.cs | 2 +- .../LinkedIn Service/LinkedInPage.xaml.cs | 4 +- .../SamplePages/LiveTile/LiveTilePage.xaml.cs | 2 +- .../MarkdownTextBlockPage.xaml.cs | 4 +- .../WeatherLiveTileAndToastPage.xaml.cs | 2 +- .../Shell.SamplePicker.cs | 11 ++--- .../ConnectedAnimationHelper.cs | 3 +- .../ExpressionNodes/ExpressionNode.cs | 2 +- .../Automation/DataGridAutomationPeer.cs | 3 +- .../DataGrid/DataGrid.cs | 12 ++--- .../DataGrid/DataGridCellsPresenter.cs | 3 -- .../DataGrid/DataGridColumnHeader.cs | 7 +-- .../DataGridColumnHeadersPresenter.cs | 5 +- .../DataGrid/DataGridColumns.cs | 3 +- .../DataGrid/DataGridDataConnection.cs | 11 ++--- .../DataGrid/DataGridError.cs | 2 +- .../DataGrid/DataGridRows.cs | 8 ++- .../DataGrid/DataGridTemplateColumn.cs | 2 +- .../Utilities/IndexToValueTable.cs | 9 ++-- .../Utilities/TypeHelper.cs | 8 ++- .../BladeView/BladeView.Properties.cs | 2 - .../Carousel/CarouselPanel.cs | 8 +-- .../ImageCropper/ImageCropper.Animations.cs | 1 - .../ImageCropper/ImageCropper.Events.cs | 3 -- .../ImageCropper/ImageCropper.Logic.cs | 11 ++--- .../InAppNotification.AttachedProperties.cs | 1 - .../OrbitView/OrbitView.cs | 2 +- .../RemoteSystemKindToSymbolConverter.cs | 2 +- .../RotatorTile/RotatorTile.cs | 3 -- .../TextToolbar/Formats/Formatter.cs | 7 +-- .../Formats/MarkDown/MarkDownFormatter.cs | 3 +- .../Formats/RichText/RichTextFormatter.cs | 3 +- Microsoft.Toolkit.Uwp.UI/Cache/CacheBase.cs | 19 ++----- .../Cache/InMemoryStorage.cs | 12 ++--- .../Extensions/TextBoxMask/TextBoxMask.cs | 1 - .../Extensions/TextBoxRegEx/TextBoxRegex.cs | 2 +- .../Extensions/StringExtensions.cs | 21 ++------ .../Helpers/BackgroundTaskHelper.cs | 6 ++- .../Helpers/CameraHelper/CameraHelper.cs | 49 ++++++++----------- .../Helpers/CameraHelper/FrameEventArgs.cs | 2 +- .../ObjectStorage/BaseObjectStorageHelper.cs | 11 +---- .../Helpers/PrintHelper/PrintHelperOptions.cs | 17 ------- .../RemoteDeviceHelper/RemoteDeviceHelper.cs | 27 ---------- .../Helpers/WeakEventListener.cs | 6 +-- .../Extensions/StringExtensions.cs | 39 +++------------ Microsoft.Toolkit/Helpers/Singleton.cs | 2 +- .../UI/Controls/Test_UniformGrid_FreeSpots.cs | 12 ----- .../TestToastContentBuilder.cs | 7 +-- 62 files changed, 126 insertions(+), 324 deletions(-) diff --git a/Microsoft.Toolkit.Parsers/Markdown/Blocks/YamlHeaderBlock.cs b/Microsoft.Toolkit.Parsers/Markdown/Blocks/YamlHeaderBlock.cs index b2ca0c7b238..1cfd33c1a0c 100644 --- a/Microsoft.Toolkit.Parsers/Markdown/Blocks/YamlHeaderBlock.cs +++ b/Microsoft.Toolkit.Parsers/Markdown/Blocks/YamlHeaderBlock.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; -using System.Text; using Microsoft.Toolkit.Parsers.Markdown.Helpers; namespace Microsoft.Toolkit.Parsers.Markdown.Blocks @@ -108,8 +107,6 @@ internal static YamlHeaderBlock Parse(string markdown, int start, int end, out i } var result = new YamlHeaderBlock(); - var keys = new List(); - var values = new List(); result.Children = new Dictionary(); foreach (var item in elements) { diff --git a/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs b/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs index 0dd7cf42ea4..5d6c40c20ae 100644 --- a/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs +++ b/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs @@ -73,8 +73,6 @@ internal static void AddTripChars(List tripCharHelpers) /// A parsed markdown image, or null if this is not a markdown image. internal static InlineParseResult Parse(string markdown, int start, int end) { - int refstart = 0; - // Expect a '!' character. if (start >= end || markdown[start] != '!') { @@ -120,7 +118,7 @@ internal static InlineParseResult Parse(string markdown, int start, int end) if (pos < end && markdown[pos] == '[') { - refstart = pos; + var refstart = pos; // Find the reference ']' character while (pos < end) diff --git a/Microsoft.Toolkit.Parsers/Markdown/MarkdownDocument.cs b/Microsoft.Toolkit.Parsers/Markdown/MarkdownDocument.cs index 5d744328603..efa76254ece 100644 --- a/Microsoft.Toolkit.Parsers/Markdown/MarkdownDocument.cs +++ b/Microsoft.Toolkit.Parsers/Markdown/MarkdownDocument.cs @@ -55,7 +55,7 @@ public MarkdownDocument() /// The markdown text. public void Parse(string markdownText) { - Blocks = Parse(markdownText, 0, markdownText.Length, quoteDepth: 0, actualEnd: out int actualEnd); + Blocks = Parse(markdownText, 0, markdownText.Length, quoteDepth: 0, actualEnd: out _); // Remove any references from the list of blocks, and add them to a dictionary. for (int i = Blocks.Count - 1; i >= 0; i--) diff --git a/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs b/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs index 641335d3706..1bc9d0c64cf 100644 --- a/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs +++ b/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs @@ -337,8 +337,7 @@ private static IEnumerable GetImagesInHTMLString(string htmlString) if (matchHeight.Success) { var heightValue = matchHeight.Groups["height"].Value; - int size = 0; - if (int.TryParse(heightValue, out size) && size < 10) + if (int.TryParse(heightValue, out var heightIntValue) && heightIntValue < 10) { include = false; } @@ -348,8 +347,7 @@ private static IEnumerable GetImagesInHTMLString(string htmlString) if (matchWidth.Success) { var widthValue = matchWidth.Groups["width"].Value; - int size = 0; - if (int.TryParse(widthValue, out size) && size < 10) + if (int.TryParse(widthValue, out var widthIntValue) && widthIntValue < 10) { include = false; } @@ -376,7 +374,7 @@ private static IEnumerable GetImagesInHTMLString(string htmlString) /// /// Dictionary of timezones. /// - private static Dictionary timeZones = new Dictionary + private static readonly Dictionary timeZones = new Dictionary { { "ACDT", new[] { "-1030", "Australian Central Daylight" } }, { "ACST", new[] { "-0930", "Australian Central Standard" } }, diff --git a/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs b/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs index 88d0a13a293..be93787e951 100644 --- a/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs +++ b/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs @@ -49,7 +49,7 @@ public override string ToString() /// Formatted string of key / value. public string ToString(bool withQuotes) { - string format = null; + string format; if (withQuotes) { format = "{0}=\"{1}\""; diff --git a/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs b/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs index 001aca2ff0b..6ee1e3e89d7 100644 --- a/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs +++ b/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs @@ -48,7 +48,7 @@ public ObservableGattDeviceService(GattDeviceService service) Service = service; Name = GattUuidsService.ConvertUuidToName(service.Uuid); UUID = Service.Uuid.ToString(); - var t = GetAllCharacteristics(); + PopulateAllCharacteristicsAsync(); } /// @@ -147,10 +147,9 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName } /// - /// Gets all the characteristics of this service + /// Populate the characteristics in . /// - /// The status of the communication with the GATT device. - private async Task GetAllCharacteristics() + private async void PopulateAllCharacteristicsAsync() { var tokenSource = new CancellationTokenSource(5000); var getCharacteristicsTask = await Task.Run( @@ -167,8 +166,6 @@ private async Task GetAllCharacteristics() Characteristics.Add(new ObservableGattCharacteristics(gattCharacteristic, this)); } } - - return result.Status; } } } \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs b/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs index 81a0e1ed334..2c1687698a1 100644 --- a/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs +++ b/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs @@ -181,11 +181,11 @@ public static bool IsRunningAsUwp() else { int length = 0; - StringBuilder sb = new StringBuilder(0); - int result = GetCurrentPackageFullName(ref length, sb); + var sb = new StringBuilder(0); + GetCurrentPackageFullName(ref length, sb); sb = new StringBuilder(length); - result = GetCurrentPackageFullName(ref length, sb); + var result = GetCurrentPackageFullName(ref length, sb); _isRunningAsUwp = result != APPMODEL_ERROR_NO_PACKAGE; } diff --git a/Microsoft.Toolkit.Uwp.Notifications/Toasts/Builder/ToastContentBuilder.Actions.cs b/Microsoft.Toolkit.Uwp.Notifications/Toasts/Builder/ToastContentBuilder.Actions.cs index 4ce255d546c..031861ccbec 100644 --- a/Microsoft.Toolkit.Uwp.Notifications/Toasts/Builder/ToastContentBuilder.Actions.cs +++ b/Microsoft.Toolkit.Uwp.Notifications/Toasts/Builder/ToastContentBuilder.Actions.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace Microsoft.Toolkit.Uwp.Notifications { @@ -198,8 +197,8 @@ public ToastContentBuilder AddComboBox(string id, string title, string defaultSe for (int i = 0; i < choices.Count(); i++) { - var choice = choices.ElementAt(i); - box.Items.Add(new ToastSelectionBoxItem(choice.comboBoxItemId, choice.comboBoxItemContent)); + var (comboBoxItemId, comboBoxItemContent) = choices.ElementAt(i); + box.Items.Add(new ToastSelectionBoxItem(comboBoxItemId, comboBoxItemContent)); } return AddToastInput(box); @@ -208,7 +207,7 @@ public ToastContentBuilder AddComboBox(string id, string title, string defaultSe /// /// Add an input option to the Toast. /// - /// An instance of a class that impmement that will be used on the toast. + /// An instance of a class that implement that will be used on the toast. /// The current instance of public ToastContentBuilder AddToastInput(IToastInput input) { diff --git a/Microsoft.Toolkit.Uwp.Notifications/Toasts/ToastPeople.cs b/Microsoft.Toolkit.Uwp.Notifications/Toasts/ToastPeople.cs index 25f6370ad3a..a1e3a320c75 100644 --- a/Microsoft.Toolkit.Uwp.Notifications/Toasts/ToastPeople.cs +++ b/Microsoft.Toolkit.Uwp.Notifications/Toasts/ToastPeople.cs @@ -31,7 +31,7 @@ public sealed class ToastPeople internal void PopulateToastElement(Element_Toast toast) { - string hintPeople = null; + string hintPeople; if (RemoteId != null) { diff --git a/Microsoft.Toolkit.Uwp.PlatformDifferencesGen/Program.cs b/Microsoft.Toolkit.Uwp.PlatformDifferencesGen/Program.cs index 11839c02c9d..1cfaef00249 100644 --- a/Microsoft.Toolkit.Uwp.PlatformDifferencesGen/Program.cs +++ b/Microsoft.Toolkit.Uwp.PlatformDifferencesGen/Program.cs @@ -191,15 +191,11 @@ public static string AssemblyDirectory private static Dictionary> ProcessAssembly(Assembly assembly) { - int pos = assembly.FullName.IndexOf(", Culture"); - - string fileName = $"{assembly.FullName.Substring(0, pos)}.json"; - - Dictionary> types = new Dictionary>(); + var types = new Dictionary>(); foreach (var exportedType in assembly.ExportedTypes) { - List members = new List(); + var members = new List(); if (exportedType.IsEnum) { diff --git a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/Analyzer.cs b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/Analyzer.cs index 6692b5c799f..ebc19cd548b 100644 --- a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/Analyzer.cs +++ b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/Analyzer.cs @@ -314,9 +314,7 @@ public static HowToGuard GetGuardForSymbol(ISymbol target) private static TypePresenceIndicator CheckCollectionForType(Dictionary> collection, string typeName, ISymbol symbol) { - List newMembers = null; - - if (!collection.TryGetValue(typeName, out newMembers)) + if (!collection.TryGetValue(typeName, out var newMembers)) { return TypePresenceIndicator.NotFound; } diff --git a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerCS.cs b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerCS.cs index 9438fb95717..5d8e09ab74a 100644 --- a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerCS.cs +++ b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerCS.cs @@ -202,10 +202,7 @@ private void AnalyzeExpression(SyntaxNodeAnalysisContext context, ConcurrentDict } var line = loc.GetLineSpan().StartLinePosition.Line; - - Diagnostic diagnostic = null; - - if (reports.TryGetValue(line, out diagnostic) && diagnostic.Location.SourceSpan.Start <= loc.SourceSpan.Start) + if (reports.TryGetValue(line, out var diagnostic) && diagnostic.Location.SourceSpan.Start <= loc.SourceSpan.Start) { return; } diff --git a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerVB.cs b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerVB.cs index e403a5fa71e..115968ee68b 100644 --- a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerVB.cs +++ b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerVB.cs @@ -226,10 +226,7 @@ private void AnalyzeExpression(SyntaxNodeAnalysisContext context, ConcurrentDict } var line = loc.GetLineSpan().StartLinePosition.Line; - - Diagnostic diagnostic = null; - - if (reports.TryGetValue(line, out diagnostic) && diagnostic.Location.SourceSpan.Start <= loc.SourceSpan.Start) + if (reports.TryGetValue(line, out var diagnostic) && diagnostic.Location.SourceSpan.Start <= loc.SourceSpan.Start) { return; } diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Pages/SampleController.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/Pages/SampleController.xaml.cs index 6b60ed88bd0..7c93b2bafac 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Pages/SampleController.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Pages/SampleController.xaml.cs @@ -8,7 +8,6 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; -using System.Threading.Tasks; using Microsoft.Toolkit.Uwp.SampleApp.Common; using Microsoft.Toolkit.Uwp.SampleApp.Controls; using Microsoft.Toolkit.Uwp.SampleApp.Models; @@ -165,7 +164,7 @@ public void RefreshXamlRender() { if (CurrentSample != null) { - var code = string.Empty; + string code; if (InfoAreaPivot.SelectedItem == PropertiesPivotItem) { code = CurrentSample.BindedXamlCode; diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageCache/ImageCachePage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageCache/ImageCachePage.xaml.cs index 073db7e4c6e..63bd02f289a 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageCache/ImageCachePage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageCache/ImageCachePage.xaml.cs @@ -66,7 +66,7 @@ private async Task PreCacheImages(bool loadInMemory = false) private async Task LoadDataAsync() { var source = new PhotosDataSource(); - _photoItems = await new PhotosDataSource().GetItemsAsync(true); + _photoItems = await source.GetItemsAsync(true); } private async void PreCache_Tapped(object sender, RoutedEventArgs e) diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LinkedIn Service/LinkedInPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LinkedIn Service/LinkedInPage.xaml.cs index 452b4aeb84d..ba824ec0a9e 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LinkedIn Service/LinkedInPage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LinkedIn Service/LinkedInPage.xaml.cs @@ -39,7 +39,7 @@ private async void ConnectButton_Click(object sender, RoutedEventArgs e) CallbackUri = CallbackUri.Text }; - var succeeded = LinkedInService.Instance.Initialize(oAuthTokens, LinkedInPermissions.ReadBasicProfile | LinkedInPermissions.WriteShare); + LinkedInService.Instance.Initialize(oAuthTokens, LinkedInPermissions.ReadBasicProfile | LinkedInPermissions.WriteShare); var loggedIn = await LinkedInService.Instance.LoginAsync(); @@ -66,7 +66,7 @@ private async void ShareButton_Click(object sender, RoutedEventArgs e) return; } - var response = await LinkedInService.Instance.ShareActivityAsync(ShareText.Text); + await LinkedInService.Instance.ShareActivityAsync(ShareText.Text); var message = new MessageDialog("Share sent to LinkedIn"); await message.ShowAsync(); diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LiveTile/LiveTilePage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LiveTile/LiveTilePage.xaml.cs index 418ffb5c1d7..53642cff0f9 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LiveTile/LiveTilePage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LiveTile/LiveTilePage.xaml.cs @@ -170,7 +170,7 @@ private void Initialize() tile.VisualElements.Square150x150Logo = Constants.Square150x150Logo; tile.VisualElements.Wide310x150Logo = Constants.Wide310x150Logo; tile.VisualElements.Square310x310Logo = Constants.Square310x310Logo; - var dontWait = tile.UpdateAsync(); // Commit changes (no need to await) + _ = tile.UpdateAsync(); // Commit changes (no need to await) tile.CreateTileUpdater().Update(new TileNotification(_tileContent.GetXml())); } diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/MarkdownTextBlock/MarkdownTextBlockPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/MarkdownTextBlock/MarkdownTextBlockPage.xaml.cs index f7d84fdfca6..d19885094d6 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/MarkdownTextBlock/MarkdownTextBlockPage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/MarkdownTextBlock/MarkdownTextBlockPage.xaml.cs @@ -57,7 +57,7 @@ private void Current_ThemeChanged(object sender, Models.ThemeChangedArgs e) private async void MarkdownText_ImageClicked(object sender, LinkClickedEventArgs e) { - if (!Uri.TryCreate(e.Link, UriKind.Absolute, out Uri result)) + if (!Uri.IsWellFormedUriString(e.Link, UriKind.Absolute)) { await new MessageDialog("Masked relative Images needs to be manually handled.").ShowAsync(); } @@ -91,7 +91,7 @@ private void SetInitalText(string text) private async void MarkdownText_LinkClicked(object sender, LinkClickedEventArgs e) { - if (!Uri.TryCreate(e.Link, UriKind.Absolute, out Uri result)) + if (!Uri.IsWellFormedUriString(e.Link, UriKind.Absolute)) { await new MessageDialog("Masked relative links needs to be manually handled.").ShowAsync(); } diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/WeatherLiveTileAndToast/WeatherLiveTileAndToastPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/WeatherLiveTileAndToast/WeatherLiveTileAndToastPage.xaml.cs index 14993245414..d172b39aa34 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/WeatherLiveTileAndToast/WeatherLiveTileAndToastPage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/WeatherLiveTileAndToast/WeatherLiveTileAndToastPage.xaml.cs @@ -314,7 +314,7 @@ private void Initialize() tile.VisualElements.Square150x150Logo = Constants.Square150x150Logo; tile.VisualElements.Wide310x150Logo = Constants.Wide310x150Logo; tile.VisualElements.Square310x310Logo = Constants.Square310x310Logo; - var dontWait = tile.UpdateAsync(); // Commit changes (no need to await) + _ = tile.UpdateAsync(); // Commit changes (no need to await) tile.CreateTileUpdater().Update(new TileNotification(_tileContent.GetXml())); } diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs b/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs index 359353ec5ff..2693248f5d4 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Linq; using System.Numerics; -using System.Threading.Tasks; using Microsoft.Toolkit.Uwp.SampleApp.Pages; using Microsoft.Toolkit.Uwp.UI.Animations; using Microsoft.Toolkit.Uwp.UI.Controls; @@ -36,11 +35,11 @@ private Sample CurrentSample set { _currentSample = value; - var nop = SetNavViewSelection(); + SetNavViewSelection(); } } - private async Task SetNavViewSelection() + private async void SetNavViewSelection() { if (_currentSample != null) { @@ -59,10 +58,10 @@ private async Task SetNavViewSelection() private void HideSamplePicker() { - SamplePickerGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed; + SamplePickerGrid.Visibility = Visibility.Collapsed; _selectedCategory = null; - var noop = SetNavViewSelection(); + SetNavViewSelection(); } private async void ShowSamplePicker(Sample[] samples = null, bool group = false) @@ -323,7 +322,7 @@ private void HideMoreInfo() animation.Configuration = new DirectConnectedAnimationConfiguration(); } - var t = SamplePickerGridView.TryStartConnectedAnimationAsync(animation, MoreInfoContent.DataContext, "SampleIcon"); + _ = SamplePickerGridView.TryStartConnectedAnimationAsync(animation, MoreInfoContent.DataContext, "SampleIcon"); } MoreInfoContent.DataContext = null; diff --git a/Microsoft.Toolkit.Uwp.UI.Animations/ConnectedAnimations/ConnectedAnimationHelper.cs b/Microsoft.Toolkit.Uwp.UI.Animations/ConnectedAnimations/ConnectedAnimationHelper.cs index 555f5bba5a9..702eacacd4d 100644 --- a/Microsoft.Toolkit.Uwp.UI.Animations/ConnectedAnimations/ConnectedAnimationHelper.cs +++ b/Microsoft.Toolkit.Uwp.UI.Animations/ConnectedAnimations/ConnectedAnimationHelper.cs @@ -50,8 +50,7 @@ internal void SetParameterForNextFrameNavigation(object parameter) private void Frame_Navigating(object sender, Windows.UI.Xaml.Navigation.NavigatingCancelEventArgs e) { - object parameter = null; - + object parameter; if (_nextParameter != null) { parameter = _nextParameter; diff --git a/Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ExpressionNodes/ExpressionNode.cs b/Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ExpressionNodes/ExpressionNode.cs index 44fcd7ef4d8..48464ef9e4c 100644 --- a/Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ExpressionNodes/ExpressionNode.cs +++ b/Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ExpressionNodes/ExpressionNode.cs @@ -473,7 +473,7 @@ private string GetOperationString() private string ToExpressionStringInternal() { - string ret = string.Empty; + string ret; // Do a recursive depth-first traversal of the node tree to print out the full expression string switch (GetOperationKind()) diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/Automation/DataGridAutomationPeer.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/Automation/DataGridAutomationPeer.cs index 980586b3bf1..c2537307b49 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/Automation/DataGridAutomationPeer.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/Automation/DataGridAutomationPeer.cs @@ -724,8 +724,7 @@ internal void PopulateItemPeers() { if (item != null) { - DataGridItemAutomationPeer peer = null; - + DataGridItemAutomationPeer peer; if (oldChildren.ContainsKey(item)) { peer = oldChildren[item] as DataGridItemAutomationPeer; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs index 46ae26a4def..f7f7b207bca 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs @@ -3199,7 +3199,7 @@ public void ScrollIntoView(object item, DataGridColumn column) } else { - int slot = -1; + int slot; DataGridRowGroupInfo rowGroupInfo = null; ICollectionViewGroup collectionViewGroup = item as ICollectionViewGroup; if (collectionViewGroup != null) @@ -5631,13 +5631,12 @@ private void DataGrid_GotFocus(object sender, RoutedEventArgs e) } } - // Keep track of which row contains the newly focused element - DataGridRow focusedRow = null; DependencyObject focusedElement = e.OriginalSource as DependencyObject; _focusedObject = focusedElement; while (focusedElement != null) { - focusedRow = focusedElement as DataGridRow; + // Keep track of which row contains the newly focused element + var focusedRow = focusedElement as DataGridRow; if (focusedRow != null && focusedRow.OwningGrid == this && _focusedRow != focusedRow) { ResetFocusedRow(); @@ -5697,8 +5696,7 @@ private void DataGrid_KeyUp(object sender, KeyRoutedEventArgs e) { if (this.ColumnHeaders != null && this.AreColumnHeadersVisible) { - bool ctrl, shift; - KeyboardHelper.GetMetaKeyState(out ctrl, out shift); + KeyboardHelper.GetMetaKeyState(out _, out var shift); if (shift && this.LastHandledKeyDown != VirtualKey.Tab) { @@ -6598,7 +6596,7 @@ private void MakeFirstDisplayedCellCurrentCell() // No current cell, therefore no selection either - try to set the current cell to the // ItemsSource's ICollectionView.CurrentItem if it exists, otherwise use the first displayed cell. - int slot = 0; + int slot; if (this.DataConnection.CollectionView != null) { if (this.DataConnection.CollectionView.IsCurrentBeforeFirst || diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs index a7fbf293b1e..3f2d9cf4c87 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs @@ -274,9 +274,6 @@ protected override Size MeasureOverride(Size availableSize) // then we will resize all the columns to fit the available space. if (this.OwningGrid.UsesStarSizing && !this.OwningGrid.AutoSizingColumns) { - double adjustment = this.OwningGrid.CellsWidth - totalDisplayWidth; - totalDisplayWidth += adjustment - this.OwningGrid.AdjustColumnWidths(0, adjustment, false); - // Since we didn't know the final widths of the columns until we resized, // we waited until now to measure each cell double leftEdge = 0; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeader.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeader.cs index d3d0a5a1339..fa972cf7f98 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeader.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeader.cs @@ -712,7 +712,6 @@ private void DataGridColumnHeader_PointerReleased(object sender, PointerRoutedEv { // Completed a click or tap without dragging, so raise the DataGrid.Sorting event. InvokeProcessSort(); - handled = true; break; } @@ -897,8 +896,7 @@ private int GetReorderingTargetDisplayIndex(Point pointerPositionHeaders) { Debug.Assert(this.OwningGrid != null, "Expected non-null OwningGrid."); - double scrollAmount = 0; - DataGridColumn targetColumn = GetReorderingTargetColumn(pointerPositionHeaders, false /*scroll*/, out scrollAmount); + DataGridColumn targetColumn = GetReorderingTargetColumn(pointerPositionHeaders, false /*scroll*/, out _); if (targetColumn != null) { return targetColumn.DisplayIndex > this.OwningColumn.DisplayIndex ? targetColumn.DisplayIndex - 1 : targetColumn.DisplayIndex; @@ -1009,8 +1007,7 @@ private void OnPointerMove_Reorder(ref bool handled, Pointer pointer, Point poin this.OwningGrid.OnColumnHeaderDragDelta(dragDeltaEventArgs); // Find header we're hovering over - double scrollAmount = 0; - DataGridColumn targetColumn = GetReorderingTargetColumn(pointerPositionHeaders, !this.OwningColumn.IsFrozen /*scroll*/, out scrollAmount); + DataGridColumn targetColumn = GetReorderingTargetColumn(pointerPositionHeaders, !this.OwningColumn.IsFrozen /*scroll*/, out var scrollAmount); this.OwningGrid.ColumnHeaders.DragIndicatorOffset = pointerPosition.X - interactionInfo.DragStart.Value.X + scrollAmount; this.OwningGrid.ColumnHeaders.InvalidateArrange(); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs index f2f9efe104b..5b07ace3d7a 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs @@ -359,13 +359,10 @@ protected override Size MeasureOverride(Size availableSize) // then we will resize all the columns to fit the available space. if (this.OwningGrid.UsesStarSizing && !this.OwningGrid.AutoSizingColumns) { - double adjustment = double.IsPositiveInfinity(availableSize.Width) ? this.OwningGrid.CellsWidth : availableSize.Width - totalDisplayWidth; - totalDisplayWidth += adjustment - this.OwningGrid.AdjustColumnWidths(0, adjustment, false); - // Since we didn't know the final widths of the columns until we resized, // we waited until now to measure each header double leftEdge = 0; - foreach (DataGridColumn column in this.OwningGrid.ColumnsInternal.GetVisibleColumns()) + foreach (var column in this.OwningGrid.ColumnsInternal.GetVisibleColumns()) { column.ComputeLayoutRoundedWidth(leftEdge); column.HeaderCell.Measure(new Size(column.LayoutRoundedWidth, double.PositiveInfinity)); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumns.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumns.cs index ffa82e39272..97b55a71caf 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumns.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumns.cs @@ -1136,7 +1136,6 @@ private void AutoGenerateColumnsPrivate() private bool ComputeDisplayedColumns() { bool invalidate = false; - int numVisibleScrollingCols = 0; int visibleScrollingColumnsTmp = 0; double displayWidth = this.CellsWidth; double cx = 0; @@ -1194,7 +1193,7 @@ private bool ComputeDisplayedColumns() dataGridColumn = this.ColumnsInternal.GetNextVisibleColumn(dataGridColumn); } - numVisibleScrollingCols = visibleScrollingColumnsTmp; + var numVisibleScrollingCols = visibleScrollingColumnsTmp; // if we inflate the data area then we paint columns to the left of firstDisplayedScrollingCol if (cx < displayWidth) diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs index a7d8ca81265..986e91a6ee6 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs @@ -538,17 +538,14 @@ public bool GetPropertyIsReadOnly(string propertyName) return true; } - object[] index = null; - propertyInfo = propertyType.GetPropertyOrIndexer(propertyNames[i], out index); + propertyInfo = propertyType.GetPropertyOrIndexer(propertyNames[i], out _); if (propertyInfo == null || propertyInfo.GetIsReadOnly()) { // Either the property doesn't exist or it does exist but is read-only. return true; } - // Check if EditableAttribute is defined on the property and if it indicates uneditable - EditableAttribute editableAttribute = null; - editableAttribute = propertyInfo.GetCustomAttributes().OfType().FirstOrDefault(); + var editableAttribute = propertyInfo.GetCustomAttributes().OfType().FirstOrDefault(); if (editableAttribute != null && !editableAttribute.AllowEdit) { return true; @@ -705,9 +702,7 @@ internal void MoveCurrentTo(object item, int backupSlot, int columnIndex, DataGr _scrollForCurrentChanged = scrollIntoView; _backupSlotForCurrentChanged = backupSlot; - bool itemIsCollectionViewGroup = false; - - itemIsCollectionViewGroup = item is ICollectionViewGroup; + var itemIsCollectionViewGroup = item is ICollectionViewGroup; this.CollectionView.MoveCurrentTo((itemIsCollectionViewGroup || this.IndexOf(item) == this.NewItemPlaceholderIndex) ? null : item); _expectingCurrentChanged = false; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridError.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridError.cs index ebb55c374bc..e4eff6267a8 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridError.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridError.cs @@ -84,7 +84,7 @@ public static ArgumentException ValueIsNotAnInstanceOfEitherOr(string paramName, public static ArgumentOutOfRangeException ValueMustBeBetween(string paramName, string valueName, object lowValue, bool lowInclusive, object highValue, bool highInclusive) { - string message = null; + string message; if (lowInclusive && highInclusive) { diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRows.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRows.cs index fb524f71a56..330de25883d 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRows.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRows.cs @@ -1537,7 +1537,7 @@ private void ExpandSlots(int startSlot, int endSlot, bool isHeaderDisplayed, ref // Figure out which slots actually need to be expanded since some might already be collapsed double currentHeightChange = 0; int firstSlot = startSlot; - int lastSlot = endSlot; + int lastSlot; while (firstSlot <= endSlot) { firstSlot = _collapsedSlotsTable.GetNextIndex(firstSlot - 1); @@ -1553,9 +1553,8 @@ private void ExpandSlots(int startSlot, int endSlot, bool isHeaderDisplayed, ref if (!isHeaderDisplayed) { // Estimate the height change if the slots aren't displayed. If they are displayed, we can add real values - double headerHeight = 0; double rowCount = lastSlot - firstSlot + 1; - rowCount -= GetRowGroupHeaderCount(firstSlot, lastSlot, Visibility.Collapsed, out headerHeight); + rowCount -= GetRowGroupHeaderCount(firstSlot, lastSlot, Visibility.Collapsed, out var headerHeight); double detailsCount = GetDetailsCountInclusive(firstSlot, lastSlot); currentHeightChange += headerHeight + (detailsCount * this.RowDetailsHeightEstimate) + (rowCount * this.RowHeightEstimate); } @@ -1747,9 +1746,8 @@ private double GetExactSlotElementHeight(int slot) // Returns an estimate for the height of the slots between fromSlot and toSlot private double GetHeightEstimate(int fromSlot, int toSlot) { - double headerHeight = 0; double rowCount = toSlot - fromSlot + 1; - rowCount -= GetRowGroupHeaderCount(fromSlot, toSlot, Visibility.Visible, out headerHeight); + rowCount -= GetRowGroupHeaderCount(fromSlot, toSlot, Visibility.Visible, out var headerHeight); double detailsCount = GetDetailsCountInclusive(fromSlot, toSlot); return headerHeight + (detailsCount * this.RowDetailsHeightEstimate) + (rowCount * this.RowHeightEstimate); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridTemplateColumn.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridTemplateColumn.cs index 01dfee11fd2..5a9a7e527fc 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridTemplateColumn.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridTemplateColumn.cs @@ -82,7 +82,7 @@ internal bool HasDistinctTemplates /// The previous, unedited value in the cell being edited. protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue) { - editingElement = GenerateEditingElement(null, null); + _ = GenerateEditingElement(null, null); } /// diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/IndexToValueTable.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/IndexToValueTable.cs index 0117ec382d9..a850e54665f 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/IndexToValueTable.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/IndexToValueTable.cs @@ -428,10 +428,7 @@ public int GetNthIndex(int n) /// /// index to search for /// the value at the given index or the default value if index is not in the table - public T GetValueAt(int index) - { - return GetValueAt(index, out bool found); - } + public T GetValueAt(int index) => GetValueAt(index, out _); /// /// Returns the value at a given index or the default value if the index is not in the table @@ -697,7 +694,7 @@ private void AddValuesPrivate(int startIndex, int count, T value, int? startRang } else { - int lowerRangeIndex = startRangeIndex.HasValue ? startRangeIndex.Value : this.FindRangeIndex(startIndex); + int lowerRangeIndex = startRangeIndex ?? this.FindRangeIndex(startIndex); Range lowerRange = (lowerRangeIndex < 0) ? null : _list[lowerRangeIndex]; if (lowerRange == null) { @@ -770,7 +767,7 @@ private int FindRangeIndex(int index) // Do a binary search for the index int front = 0; int end = _list.Count - 1; - Range range = null; + Range range; while (end > front) { int median = (front + end) / 2; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/TypeHelper.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/TypeHelper.cs index 21e60652634..3792cb88f4c 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/TypeHelper.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/TypeHelper.cs @@ -176,8 +176,7 @@ internal static PropertyInfo GetNestedProperty(this Type parentType, string prop List propertyNames = SplitPropertyPath(propertyPath); for (int i = 0; i < propertyNames.Count; i++) { - object[] index = null; - propertyInfo = propertyType.GetPropertyOrIndexer(propertyNames[i], out index); + propertyInfo = propertyType.GetPropertyOrIndexer(propertyNames[i], out var index); if (propertyInfo == null) { item = null; @@ -272,9 +271,8 @@ internal static PropertyInfo GetPropertyOrIndexer(this Type type, string propert return null; } - PropertyInfo indexer = null; - string stringIndex = propertyPath.Substring(1, propertyPath.Length - 2); - indexer = FindIndexerInMembers(type.GetDefaultMembers(), stringIndex, out index); + var stringIndex = propertyPath.Substring(1, propertyPath.Length - 2); + var indexer = FindIndexerInMembers(type.GetDefaultMembers(), stringIndex, out index); if (indexer != null) { // We found the indexer, so return it. diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/BladeView/BladeView.Properties.cs b/Microsoft.Toolkit.Uwp.UI.Controls/BladeView/BladeView.Properties.cs index ecdaa957b40..9d56a557840 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/BladeView/BladeView.Properties.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/BladeView/BladeView.Properties.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using Windows.Foundation; using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; namespace Microsoft.Toolkit.Uwp.UI.Controls { @@ -69,7 +68,6 @@ public int AutoCollapseCountThreshold private static void OnBladeModeChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var bladeView = (BladeView)dependencyObject; - var bladeScrollViewer = bladeView.GetScrollViewer(); if (bladeView.BladeMode == BladeMode.Fullscreen) { diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs b/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs index 991199ffcb1..e933d64ce80 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs @@ -141,9 +141,6 @@ internal void OnManipulationCompleted(object sender, ManipulationCompletedRouted // Need to know which direction we took for this manipulation. var translation = Carousel.Orientation == Orientation.Horizontal ? e.Cumulative.Translation.X : e.Cumulative.Translation.Y; - // if manipulation is not enough to change index we will have to force refresh - var lastIndex = Carousel.SelectedIndex; - // potentially border effects bool hasBreak = false; @@ -250,8 +247,7 @@ protected override Size MeasureOverride(Size availableSize) } } - var width = 0d; - var height = 0d; + double width; // It's a Auto size, so we define the size should be 3 items if (double.IsInfinity(availableSize.Width)) @@ -263,6 +259,7 @@ protected override Size MeasureOverride(Size availableSize) width = availableSize.Width; } + double height; // It's a Auto size, so we define the size should be 3 items if (double.IsInfinity(availableSize.Height)) { @@ -385,7 +382,6 @@ private void ApplyProjection(UIElement element, Proj proj, Storyboard storyboard /// Return the new projection private Proj GetProjectionFromManipulation(UIElement element, double delta) { - PlaneProjection projection = element.Projection as PlaneProjection; CompositeTransform compositeTransform = element.RenderTransform as CompositeTransform; var bounds = Carousel.Orientation == Orientation.Horizontal ? desiredWidth : desiredHeight; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Animations.cs b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Animations.cs index 4087d1faa84..2ad3c7b3243 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Animations.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Animations.cs @@ -97,7 +97,6 @@ private static List GetRectKeyframes(Rect from, Rect to, { var rectKeyframes = new List(); var step = TimeSpan.FromMilliseconds(10); - var total = duration.TotalMilliseconds; var startPointFrom = new Point(from.X, from.Y); var endPointFrom = new Point(from.X + from.Width, from.Y + from.Height); var startPointTo = new Point(to.X, to.Y); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs index 1f47e0f822b..4f743a504a7 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs @@ -7,7 +7,6 @@ using Windows.System; using Windows.UI.Core; using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; namespace Microsoft.Toolkit.Uwp.UI.Controls @@ -24,8 +23,6 @@ private void ImageCropperThumb_KeyDown(object sender, KeyRoutedEventArgs e) if (e.Key == VirtualKey.Left) { diffPos.X--; - var upKeyState = Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Up); - var downKeyState = Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Down); if (Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Up) == CoreVirtualKeyStates.Down) { diffPos.Y--; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Logic.cs b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Logic.cs index 5f6a023ef46..44c216e0e7f 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Logic.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Logic.cs @@ -6,7 +6,6 @@ using System.Numerics; using Windows.Foundation; using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Hosting; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; @@ -103,7 +102,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) return; } - double radian = 0d, diffPointRadian = 0d, effectiveLength = 0d; + double radian = 0d, diffPointRadian = 0d; if (KeepAspectRatio) { radian = Math.Atan(UsedAspectRatio); @@ -178,7 +177,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) case ThumbPosition.UpperLeft: if (KeepAspectRatio) { - effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); + var effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); var originSizeChange = new Point(-effectiveLength * Math.Sin(radian), -effectiveLength * Math.Cos(radian)); var safeChange = GetSafeSizeChangeWhenKeepAspectRatio(_restrictedSelectRect, position, currentSelectedRect, originSizeChange, UsedAspectRatio); diffPos.X = -safeChange.X; @@ -192,7 +191,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) if (KeepAspectRatio) { diffPointRadian = -diffPointRadian; - effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); + var effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); var originSizeChange = new Point(-effectiveLength * Math.Sin(radian), -effectiveLength * Math.Cos(radian)); var safeChange = GetSafeSizeChangeWhenKeepAspectRatio(_restrictedSelectRect, position, currentSelectedRect, originSizeChange, UsedAspectRatio); diffPos.X = safeChange.X; @@ -206,7 +205,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) if (KeepAspectRatio) { diffPointRadian = -diffPointRadian; - effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); + var effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); var originSizeChange = new Point(effectiveLength * Math.Sin(radian), effectiveLength * Math.Cos(radian)); var safeChange = GetSafeSizeChangeWhenKeepAspectRatio(_restrictedSelectRect, position, currentSelectedRect, originSizeChange, UsedAspectRatio); diffPos.X = -safeChange.X; @@ -219,7 +218,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) case ThumbPosition.LowerRight: if (KeepAspectRatio) { - effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); + var effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); var originSizeChange = new Point(effectiveLength * Math.Sin(radian), effectiveLength * Math.Cos(radian)); var safeChange = GetSafeSizeChangeWhenKeepAspectRatio(_restrictedSelectRect, position, currentSelectedRect, originSizeChange, UsedAspectRatio); diffPos.X = safeChange.X; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/InAppNotification/InAppNotification.AttachedProperties.cs b/Microsoft.Toolkit.Uwp.UI.Controls/InAppNotification/InAppNotification.AttachedProperties.cs index be3f45b3c48..a566a9b52cf 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/InAppNotification/InAppNotification.AttachedProperties.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/InAppNotification/InAppNotification.AttachedProperties.cs @@ -43,7 +43,6 @@ private static void OnKeyFrameAnimationChanged(DependencyObject d, DependencyPro { if (e.NewValue is TimeSpan ts) { - var keyTimeFromAnimationDuration = KeyTime.FromTimeSpan(ts); if (d is DoubleKeyFrame dkf) { dkf.KeyTime = KeyTime.FromTimeSpan(ts); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/OrbitView/OrbitView.cs b/Microsoft.Toolkit.Uwp.UI.Controls/OrbitView/OrbitView.cs index 98fd7a3c80a..4cd44307cfc 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/OrbitView/OrbitView.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/OrbitView/OrbitView.cs @@ -622,7 +622,7 @@ private Line CreateAnchor(UIElement element, double x, double y) var elementNode = elementVisual.GetReference(); var centerNode = centerVisual.GetReference(); - ScalarNode expression = null; + ScalarNode expression; var elementY = elementNode.Offset.Y + (elementNode.Size.Y / 2); var centerY = centerNode.Offset.Y + (centerNode.Size.Y / 2); var elementX = elementNode.Offset.X + (elementNode.Size.X / 2); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/RemoteDevicePicker/RemoteSystemKindToSymbolConverter.cs b/Microsoft.Toolkit.Uwp.UI.Controls/RemoteDevicePicker/RemoteSystemKindToSymbolConverter.cs index b8abf8f3bc0..8b444c75030 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/RemoteDevicePicker/RemoteSystemKindToSymbolConverter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/RemoteDevicePicker/RemoteSystemKindToSymbolConverter.cs @@ -15,7 +15,7 @@ public class RemoteSystemKindToSymbolConverter : IValueConverter /// public object Convert(object value, Type targetType, object parameter, string language) { - string finalvalue = string.Empty; + string finalvalue; switch ((string)value) { case "Desktop": diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/RotatorTile/RotatorTile.cs b/Microsoft.Toolkit.Uwp.UI.Controls/RotatorTile/RotatorTile.cs index e68e58e1ab8..2aab5261187 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/RotatorTile/RotatorTile.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/RotatorTile/RotatorTile.cs @@ -168,7 +168,6 @@ private void RotatorTile_Unloaded(object sender, RoutedEventArgs e) /// private void Timer_Tick(object sender, object e) { - var item = GetItemAt(_currentIndex + 1); _timer.Interval = GetTileDuration(); UpdateNextItem(); } @@ -322,7 +321,6 @@ private object GetItemAt(int index) } else if (ItemsSource is IEnumerable) { - var items = ItemsSource as IEnumerable; var ienum = ((IEnumerable)ItemsSource).GetEnumerator(); int count = 0; while (ienum.MoveNext()) @@ -484,7 +482,6 @@ private void Incc_CollectionChanged(object sender, NotifyCollectionChangedEventA } else if (e.Action == NotifyCollectionChangedAction.Add) { - int endIndex = e.NewStartingIndex + e.NewItems.Count; if (e.NewItems?.Count > 0) { if (_currentIndex < 0) diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/Formatter.cs b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/Formatter.cs index 3c4190b36f9..25669a72fe1 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/Formatter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/Formatter.cs @@ -5,7 +5,6 @@ using System; using Microsoft.Toolkit.Uwp.UI.Controls.TextToolbarButtons; using Windows.UI.Text; -using Windows.UI.Xaml.Controls; namespace Microsoft.Toolkit.Uwp.UI.Controls.TextToolbarFormats { @@ -81,8 +80,7 @@ public virtual void EnsureAtNewLine() int counter = 0; bool atNewLine = false; - string docText = string.Empty; - Model.Editor.Document.GetText(TextGetOptions.NoHidden, out docText); + Model.Editor.Document.GetText(TextGetOptions.NoHidden, out var docText); var lines = docText.Split(new string[] { Return }, StringSplitOptions.None); foreach (var line in lines) @@ -176,8 +174,7 @@ public virtual string Text { get { - string currentvalue = string.Empty; - Model.Editor.Document.GetText(TextGetOptions.FormatRtf, out currentvalue); + Model.Editor.Document.GetText(TextGetOptions.FormatRtf, out var currentvalue); return currentvalue; } } diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/MarkDown/MarkDownFormatter.cs b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/MarkDown/MarkDownFormatter.cs index b0874115043..113fe7f77bf 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/MarkDown/MarkDownFormatter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/MarkDown/MarkDownFormatter.cs @@ -440,8 +440,7 @@ public override string Text { get { - string currentvalue = string.Empty; - Model.Editor.Document.GetText(TextGetOptions.UseCrlf, out currentvalue); + Model.Editor.Document.GetText(TextGetOptions.UseCrlf, out var currentvalue); return currentvalue.Replace('\n', '\r'); // Converts CRLF into double Return for Markdown new line. } } diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/RichText/RichTextFormatter.cs b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/RichText/RichTextFormatter.cs index edd0a94138e..3523ef61193 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/RichText/RichTextFormatter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/RichText/RichTextFormatter.cs @@ -95,8 +95,7 @@ public override string Text { get { - string currentvalue = string.Empty; - Model.Editor.Document.GetText(TextGetOptions.FormatRtf, out currentvalue); + Model.Editor.Document.GetText(TextGetOptions.FormatRtf, out var currentvalue); return currentvalue; } } diff --git a/Microsoft.Toolkit.Uwp.UI/Cache/CacheBase.cs b/Microsoft.Toolkit.Uwp.UI/Cache/CacheBase.cs index a43529a541f..1fa3d1b1716 100644 --- a/Microsoft.Toolkit.Uwp.UI/Cache/CacheBase.cs +++ b/Microsoft.Toolkit.Uwp.UI/Cache/CacheBase.cs @@ -11,7 +11,6 @@ using System.Threading; using System.Threading.Tasks; using Windows.Storage; -using Windows.Storage.Streams; namespace Microsoft.Toolkit.Uwp.UI { @@ -144,7 +143,7 @@ public Task ClearAsync(TimeSpan duration) /// awaitable task public async Task RemoveExpiredAsync(TimeSpan? duration = null) { - TimeSpan expiryDuration = duration.HasValue ? duration.Value : CacheDuration; + TimeSpan expiryDuration = duration ?? CacheDuration; var folder = await GetCacheFolderAsync().ConfigureAwait(false); var files = await folder.GetFilesAsync().AsTask().ConfigureAwait(false); @@ -197,10 +196,7 @@ public async Task RemoveAsync(IEnumerable uriForCachedItems) foreach (var uri in uriForCachedItems) { string fileName = GetCacheFileName(uri); - - StorageFile file = null; - - if (hashDictionary.TryGetValue(fileName, out file)) + if (hashDictionary.TryGetValue(fileName, out var file)) { filesToDelete.Add(file); keys.Add(fileName); @@ -335,10 +331,7 @@ private async Task GetItemAsync(Uri uri, bool throwOnError, bool preCacheOnly T instance = default(T); string fileName = GetCacheFileName(uri); - - ConcurrentRequest request = null; - - _concurrentTasks.TryGetValue(fileName, out request); + _concurrentTasks.TryGetValue(fileName, out var request); // if similar request exists check if it was preCacheOnly and validate that current request isn't preCacheOnly if (request != null && request.EnsureCachedCopy && !preCacheOnly) @@ -372,8 +365,7 @@ private async Task GetItemAsync(Uri uri, bool throwOnError, bool preCacheOnly } finally { - _concurrentTasks.TryRemove(fileName, out request); - request = null; + _concurrentTasks.TryRemove(fileName, out _); } return instance; @@ -381,7 +373,6 @@ private async Task GetItemAsync(Uri uri, bool throwOnError, bool preCacheOnly private async Task GetFromCacheOrDownloadAsync(Uri uri, string fileName, bool preCacheOnly, CancellationToken cancellationToken, List> initializerKeyValues) { - StorageFile baseFile = null; T instance = default(T); if (_inMemoryFileStorage.MaxItemCount > 0) @@ -399,7 +390,7 @@ private async Task GetFromCacheOrDownloadAsync(Uri uri, string fileName, bool } var folder = await GetCacheFolderAsync().ConfigureAwait(false); - baseFile = await folder.TryGetItemAsync(fileName).AsTask().ConfigureAwait(false) as StorageFile; + var baseFile = await folder.TryGetItemAsync(fileName).AsTask().ConfigureAwait(false) as StorageFile; bool downloadDataFile = baseFile == null || await IsFileOutOfDateAsync(baseFile, CacheDuration).ConfigureAwait(false); diff --git a/Microsoft.Toolkit.Uwp.UI/Cache/InMemoryStorage.cs b/Microsoft.Toolkit.Uwp.UI/Cache/InMemoryStorage.cs index d394213f1ce..3383c401062 100644 --- a/Microsoft.Toolkit.Uwp.UI/Cache/InMemoryStorage.cs +++ b/Microsoft.Toolkit.Uwp.UI/Cache/InMemoryStorage.cs @@ -82,11 +82,7 @@ public void Remove(IEnumerable keys) continue; } - InMemoryStorageItem tempItem = null; - - _inMemoryStorage.TryRemove(key, out tempItem); - - tempItem = null; + _inMemoryStorage.TryRemove(key, out _); } } @@ -119,9 +115,7 @@ public void SetItem(InMemoryStorageItem item) /// Valid item if not out of date or return null if out of date or item does not exist public InMemoryStorageItem GetItem(string id, TimeSpan duration) { - InMemoryStorageItem tempItem = null; - - if (!_inMemoryStorage.TryGetValue(id, out tempItem)) + if (!_inMemoryStorage.TryGetValue(id, out var tempItem)) { return null; } @@ -133,7 +127,7 @@ public InMemoryStorageItem GetItem(string id, TimeSpan duration) return tempItem; } - _inMemoryStorage.TryRemove(id, out tempItem); + _inMemoryStorage.TryRemove(id, out _); return null; } diff --git a/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxMask/TextBoxMask.cs b/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxMask/TextBoxMask.cs index 5eda2b7b13c..aa06c2fd5da 100644 --- a/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxMask/TextBoxMask.cs +++ b/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxMask/TextBoxMask.cs @@ -261,7 +261,6 @@ private static void Textbox_SelectionChanged(object sender, RoutedEventArgs e) private static void Textbox_TextChanging(TextBox textbox, TextBoxTextChangingEventArgs args) { - var mask = textbox.GetValue(MaskProperty) as string; var escapedMask = textbox.GetValue(EscapedMaskProperty) as string; var escapedChars = textbox.GetValue(EscapedCharacterIndicesProperty) as List; diff --git a/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxRegEx/TextBoxRegex.cs b/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxRegEx/TextBoxRegex.cs index e0d0cb5e277..3cc924678a9 100644 --- a/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxRegEx/TextBoxRegex.cs +++ b/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxRegEx/TextBoxRegex.cs @@ -62,7 +62,7 @@ private static void ValidateTextBox(TextBox textbox, bool force = true) { var validationType = (ValidationType)textbox.GetValue(ValidationTypeProperty); string regex; - bool regexMatch = false; + bool regexMatch; switch (validationType) { default: diff --git a/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs b/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs index b6e0dba55c9..9898ef02dd3 100644 --- a/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs +++ b/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs @@ -2,13 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Net; -using System.Text.RegularExpressions; -using System.Threading.Tasks; using Windows.ApplicationModel.Resources; namespace Microsoft.Toolkit.Uwp.Extensions @@ -18,17 +11,13 @@ namespace Microsoft.Toolkit.Uwp.Extensions /// public static class StringExtensions { - private static ResourceLoader _independentLoader = ResourceLoader.GetForViewIndependentUse(); - /// /// Retrieves the provided resource for the current view context. /// /// Resource key to retrieve. /// string value for given resource or empty string if not found. public static string GetViewLocalized(this string resourceKey) - { - return ResourceLoader.GetForCurrentView().GetString(resourceKey); - } + => ResourceLoader.GetForCurrentView().GetString(resourceKey); /// /// Retrieves the provided resource for the given key for use independent of the UI thread. @@ -36,9 +25,7 @@ public static string GetViewLocalized(this string resourceKey) /// Resource key to retrieve. /// string value for given resource or empty string if not found. public static string GetLocalized(this string resourceKey) - { - return _independentLoader.GetString(resourceKey); - } + => ResourceLoader.GetForViewIndependentUse().GetString(resourceKey); /// /// Retrieves the provided resource for the given key for use independent of the UI thread. @@ -47,8 +34,6 @@ public static string GetLocalized(this string resourceKey) /// Resource path to retrieve. /// string value for given resource or empty string if not found. public static string GetLocalized(this string resourceKey, string resourcePath) - { - return ResourceLoader.GetForViewIndependentUse(resourcePath).GetString(resourceKey); - } + => ResourceLoader.GetForViewIndependentUse(resourcePath).GetString(resourceKey); } } diff --git a/Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs b/Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs index 7f400811d85..baebb28059a 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs @@ -63,8 +63,10 @@ public static BackgroundTaskRegistration Register(string backgroundTaskName, str } // build the background task - BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); - builder.Name = backgroundTaskName; + BackgroundTaskBuilder builder = new BackgroundTaskBuilder + { + Name = backgroundTaskName + }; // check if we are registering in SPM mode if (backgroundTaskEntryPoint != string.Empty) diff --git a/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/CameraHelper.cs b/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/CameraHelper.cs index 2df16f0c836..4043fe1728c 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/CameraHelper.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/CameraHelper.cs @@ -21,12 +21,10 @@ namespace Microsoft.Toolkit.Uwp.Helpers public class CameraHelper : IDisposable { private static IReadOnlyList _frameSourceGroups; - private SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1); + private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1); private MediaCapture _mediaCapture; private MediaFrameReader _frameReader; private MediaFrameSourceGroup _group; - private MediaFrameSource _previewFrameSource; - private List _frameFormatsAvailable; private bool groupChanged = false; private bool _initialized; @@ -53,7 +51,7 @@ public static async Task> GetFrameSourceGro /// /// Gets a list of available on the source. /// - public List FrameFormatsAvailable { get => _frameFormatsAvailable; } + public IReadOnlyList FrameFormatsAvailable { get; private set; } /// /// Gets or sets the source group for camera video preview. @@ -71,7 +69,7 @@ public MediaFrameSourceGroup FrameSourceGroup /// /// Gets the currently selected for video preview. /// - public MediaFrameSource PreviewFrameSource { get => _previewFrameSource; } + public MediaFrameSource PreviewFrameSource { get; private set; } /// /// Occurs when a new frame arrives. @@ -89,9 +87,9 @@ public async Task InitializeAndStartCaptureAsync() CameraHelperResult result; try { - await semaphoreSlim.WaitAsync(); + await _semaphoreSlim.WaitAsync(); - // if FrameSourceGroup hasn't changed from last initialiazation, just return back. + // if FrameSourceGroup hasn't changed from last initialization, just return back. if (_initialized && _group != null && !groupChanged) { return CameraHelperResult.Success; @@ -130,9 +128,9 @@ public async Task InitializeAndStartCaptureAsync() result = await InitializeMediaCaptureAsync(); - if (_previewFrameSource != null) + if (PreviewFrameSource != null) { - _frameReader = await _mediaCapture.CreateFrameReaderAsync(_previewFrameSource); + _frameReader = await _mediaCapture.CreateFrameReaderAsync(PreviewFrameSource); if (Windows.Foundation.Metadata.ApiInformation.IsPropertyPresent("Windows.Media.Capture.Frames.MediaFrameReader", "AcquisitionMode")) { _frameReader.AcquisitionMode = MediaFrameReaderAcquisitionMode.Realtime; @@ -164,7 +162,7 @@ public async Task InitializeAndStartCaptureAsync() } finally { - semaphoreSlim.Release(); + _semaphoreSlim.Release(); } } @@ -174,7 +172,7 @@ public async Task InitializeAndStartCaptureAsync() /// A representing the asynchronous operation. public async Task CleanUpAsync() { - await semaphoreSlim.WaitAsync(); + await _semaphoreSlim.WaitAsync(); try { _initialized = false; @@ -188,7 +186,7 @@ public async Task CleanUpAsync() } finally { - semaphoreSlim.Release(); + _semaphoreSlim.Release(); } } @@ -211,35 +209,35 @@ private async Task InitializeMediaCaptureAsync() await _mediaCapture.InitializeAsync(settings); // Find the first video preview or record stream available - _previewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoPreview + PreviewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoPreview && source.Value.Info.SourceKind == MediaFrameSourceKind.Color).Value; - if (_previewFrameSource == null) + if (PreviewFrameSource == null) { - _previewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoRecord + PreviewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoRecord && source.Value.Info.SourceKind == MediaFrameSourceKind.Color).Value; } - if (_previewFrameSource == null) + if (PreviewFrameSource == null) { return CameraHelperResult.NoFrameSourceAvailable; } // Get only formats of a certain framerate and compatible subtype for previewing, order them by resolution - _frameFormatsAvailable = _previewFrameSource.SupportedFormats.Where(format => + FrameFormatsAvailable = PreviewFrameSource.SupportedFormats.Where(format => format.FrameRate.Numerator / format.FrameRate.Denominator >= 15 // fps && (string.Compare(format.Subtype, MediaEncodingSubtypes.Nv12, true) == 0 || string.Compare(format.Subtype, MediaEncodingSubtypes.Bgra8, true) == 0 || string.Compare(format.Subtype, MediaEncodingSubtypes.Yuy2, true) == 0 || string.Compare(format.Subtype, MediaEncodingSubtypes.Rgb32, true) == 0))?.OrderBy(format => format.VideoFormat.Width * format.VideoFormat.Height).ToList(); - if (_frameFormatsAvailable == null || !_frameFormatsAvailable.Any()) + if (FrameFormatsAvailable == null || !FrameFormatsAvailable.Any()) { return CameraHelperResult.NoCompatibleFrameFormatAvailable; } - // Set the format with the higest resolution available by default - var defaultFormat = _frameFormatsAvailable.Last(); - await _previewFrameSource.SetFormatAsync(defaultFormat); + // Set the format with the highest resolution available by default + var defaultFormat = FrameFormatsAvailable.Last(); + await PreviewFrameSource.SetFormatAsync(defaultFormat); } catch (UnauthorizedAccessException) { @@ -306,7 +304,8 @@ private void Reader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEvent private bool disposedValue = false; - private async void Dispose(bool disposing) + /// + public async void Dispose() { if (!disposedValue) { @@ -314,11 +313,5 @@ private async void Dispose(bool disposing) await CleanUpAsync(); } } - - /// - public void Dispose() - { - Dispose(true); - } } } diff --git a/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/FrameEventArgs.cs b/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/FrameEventArgs.cs index ce860bffa1e..a3cb0e0ff8d 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/FrameEventArgs.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/FrameEventArgs.cs @@ -15,9 +15,9 @@ namespace Microsoft.Toolkit.Uwp.Helpers /// public class FrameEventArgs : EventArgs { + private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); private VideoFrame _videoFrame; private VideoFrame _videoFrameCopy; - private SemaphoreSlim _semaphore = new SemaphoreSlim(1); /// /// Gets the video frame. diff --git a/Microsoft.Toolkit.Uwp/Helpers/ObjectStorage/BaseObjectStorageHelper.cs b/Microsoft.Toolkit.Uwp/Helpers/ObjectStorage/BaseObjectStorageHelper.cs index 32c6c41cb6b..c3abcc49fbc 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/ObjectStorage/BaseObjectStorageHelper.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/ObjectStorage/BaseObjectStorageHelper.cs @@ -16,8 +16,6 @@ namespace Microsoft.Toolkit.Uwp.Helpers /// public abstract class BaseObjectStorageHelper : IObjectStorageHelper { - private JsonSerializer serializer = new JsonSerializer(); - /// /// Gets or sets the settings container. /// @@ -67,14 +65,7 @@ public bool KeyExists(string compositeKey, string key) /// The T object public T Read(string key, T @default = default(T)) { - object value = null; - - if (!Settings.Values.TryGetValue(key, out value)) - { - return @default; - } - - if (value == null) + if (!Settings.Values.TryGetValue(key, out var value) || value == null) { return @default; } diff --git a/Microsoft.Toolkit.Uwp/Helpers/PrintHelper/PrintHelperOptions.cs b/Microsoft.Toolkit.Uwp/Helpers/PrintHelper/PrintHelperOptions.cs index 4e66ef6f987..8f4429730e8 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/PrintHelper/PrintHelperOptions.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/PrintHelper/PrintHelperOptions.cs @@ -6,8 +6,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Text; -using System.Threading.Tasks; using Windows.Graphics.Printing; namespace Microsoft.Toolkit.Uwp.Helpers @@ -144,20 +142,5 @@ private void InitializePossibleDisplayOptions() .Where(p => p.PropertyType == typeof(string)) .Select(p => (string)p.GetValue(null)); } - - private void InitializeDefaultOptions() - { - Bordering = PrintBordering.Default; - MediaSize = PrintMediaSize.Default; - MediaType = PrintMediaType.Default; - HolePunch = PrintHolePunch.Default; - Binding = PrintBinding.Default; - Duplex = PrintDuplex.Default; - ColorMode = PrintColorMode.Default; - Collation = PrintCollation.Default; - PrintQuality = PrintQuality.Default; - Staple = PrintStaple.Default; - Orientation = PrintOrientation.Default; - } } } diff --git a/Microsoft.Toolkit.Uwp/Helpers/RemoteDeviceHelper/RemoteDeviceHelper.cs b/Microsoft.Toolkit.Uwp/Helpers/RemoteDeviceHelper/RemoteDeviceHelper.cs index 3f551784a38..ecfa44c2553 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/RemoteDeviceHelper/RemoteDeviceHelper.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/RemoteDeviceHelper/RemoteDeviceHelper.cs @@ -50,33 +50,6 @@ public void GenerateSystems() GenerateSystemsWithFilterAsync(null); } - /// - /// Initiate Enumeration with specific RemoteSystemStatusType - /// - private void GenerateSystemsByFilters(RemoteSystemStatusType remoteSystemStatusType, RemoteSystemAuthorizationKind remoteSystemAuthorizationKind, RemoteSystemDiscoveryType remoteSystemDiscoveryType) - { - var remoteSystemStatusTypeFilter = new RemoteSystemStatusTypeFilter(remoteSystemStatusType); - var remoteSystemDiscoveryTypeFilter = new RemoteSystemDiscoveryTypeFilter(remoteSystemDiscoveryType); - var remoteSystemAuthorizationKindFilter = new RemoteSystemAuthorizationKindFilter(remoteSystemAuthorizationKind); - var filters = new List(); - if (remoteSystemStatusTypeFilter != null) - { - filters.Add(remoteSystemStatusTypeFilter); - } - - if (remoteSystemDiscoveryTypeFilter != null) - { - filters.Add(remoteSystemDiscoveryTypeFilter); - } - - if (remoteSystemAuthorizationKindFilter != null) - { - filters.Add(remoteSystemAuthorizationKindFilter); - } - - GenerateSystemsWithFilterAsync(filters); - } - /// /// Initiate Enumeration with specific RemoteSysemKind with Filters /// diff --git a/Microsoft.Toolkit.Uwp/Helpers/WeakEventListener.cs b/Microsoft.Toolkit.Uwp/Helpers/WeakEventListener.cs index 6dc4082a94d..3a69d3d95dc 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/WeakEventListener.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/WeakEventListener.cs @@ -20,7 +20,7 @@ public sealed class WeakEventListener /// /// WeakReference to the instance listening for the event. /// - private WeakReference weakInstance; + private readonly WeakReference _weakInstance; /// /// Initializes a new instance of the class. @@ -33,7 +33,7 @@ public WeakEventListener(TInstance instance) throw new ArgumentNullException(nameof(instance)); } - weakInstance = new WeakReference(instance); + _weakInstance = new WeakReference(instance); } /// @@ -53,7 +53,7 @@ public WeakEventListener(TInstance instance) /// Event arguments. public void OnEvent(TSource source, TEventArgs eventArgs) { - TInstance target = (TInstance)weakInstance.Target; + var target = (TInstance)_weakInstance.Target; if (target != null) { // Call registered action diff --git a/Microsoft.Toolkit/Extensions/StringExtensions.cs b/Microsoft.Toolkit/Extensions/StringExtensions.cs index 6a979bf0c80..9192cb6810c 100644 --- a/Microsoft.Toolkit/Extensions/StringExtensions.cs +++ b/Microsoft.Toolkit/Extensions/StringExtensions.cs @@ -55,10 +55,7 @@ public static class StringExtensions /// /// The string to test. /// true for a valid email address; otherwise, false. - public static bool IsEmail(this string str) - { - return Regex.IsMatch(str, EmailRegex); - } + public static bool IsEmail(this string str) => Regex.IsMatch(str, EmailRegex); /// /// Determines whether a string is a valid decimal number. @@ -66,39 +63,28 @@ public static bool IsEmail(this string str) /// The string to test. /// true for a valid decimal number; otherwise, false. public static bool IsDecimal(this string str) - { - return decimal.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal _decimal); - } + => decimal.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out _); /// /// Determines whether a string is a valid integer. /// /// The string to test. /// true for a valid integer; otherwise, false. - public static bool IsNumeric(this string str) - { - return int.TryParse(str, out int _integer); - } + public static bool IsNumeric(this string str) => int.TryParse(str, out _); /// /// Determines whether a string is a valid phone number. /// /// The string to test. /// true for a valid phone number; otherwise, false. - public static bool IsPhoneNumber(this string str) - { - return Regex.IsMatch(str, PhoneNumberRegex); - } + public static bool IsPhoneNumber(this string str) => Regex.IsMatch(str, PhoneNumberRegex); /// /// Determines whether a string contains only letters. /// /// The string to test. /// true if the string contains only letters; otherwise, false. - public static bool IsCharacterString(this string str) - { - return Regex.IsMatch(str, CharactersRegex); - } + public static bool IsCharacterString(this string str) => Regex.IsMatch(str, CharactersRegex); /// /// Returns a string representation of an object. @@ -106,10 +92,7 @@ public static bool IsCharacterString(this string str) /// The object to convert. /// String representation of the object. [Obsolete("Use value?.ToString() instead. This will be removed in the next release of the toolkit.")] - public static string ToSafeString(this object value) - { - return value?.ToString(); - } + public static string ToSafeString(this object value) => value?.ToString(); /// /// Returns a string with HTML comments, scripts, styles, and tags removed. @@ -156,10 +139,7 @@ public static string FixHtml(this string html) /// The string to be truncated. /// The maximum length. /// Truncated string. - public static string Truncate(this string value, int length) - { - return Truncate(value, length, false); - } + public static string Truncate(this string value, int length) => Truncate(value, length, false); /// /// Provide better linking for resourced strings. @@ -167,10 +147,7 @@ public static string Truncate(this string value, int length) /// The format of the string being linked. /// The object which will receive the linked String. /// Truncated string. - public static string AsFormat(this string format, params object[] args) - { - return string.Format(format, args); - } + public static string AsFormat(this string format, params object[] args) => string.Format(format, args); /// /// Truncates a string to the specified length. diff --git a/Microsoft.Toolkit/Helpers/Singleton.cs b/Microsoft.Toolkit/Helpers/Singleton.cs index 9886c7a4bd6..3e0291814a3 100644 --- a/Microsoft.Toolkit/Helpers/Singleton.cs +++ b/Microsoft.Toolkit/Helpers/Singleton.cs @@ -29,7 +29,7 @@ public static class Singleton where T : new() { // Use ConcurrentDictionary for thread safety. - private static ConcurrentDictionary _instances = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary _instances = new ConcurrentDictionary(); /// /// Gets the instance of the Singleton class. diff --git a/UnitTests/UI/Controls/Test_UniformGrid_FreeSpots.cs b/UnitTests/UI/Controls/Test_UniformGrid_FreeSpots.cs index 2c7841d5d91..1c7be7e7b22 100644 --- a/UnitTests/UI/Controls/Test_UniformGrid_FreeSpots.cs +++ b/UnitTests/UI/Controls/Test_UniformGrid_FreeSpots.cs @@ -18,8 +18,6 @@ public class Test_UniformGrid_FreeSpots [UITestMethod] public void Test_UniformGrid_GetFreeSpots_Basic() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[4, 5] { { false, true, false, true, false }, @@ -50,8 +48,6 @@ public void Test_UniformGrid_GetFreeSpots_Basic() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_FirstColumn() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[4, 5] { { true, false, false, true, false }, @@ -82,8 +78,6 @@ public void Test_UniformGrid_GetFreeSpots_FirstColumn() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBoundMinusOne() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[3, 3] { { false, false, false }, @@ -112,8 +106,6 @@ public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBoundMinusOne() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBound() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[3, 3] { { false, false, false }, @@ -142,8 +134,6 @@ public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBound() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBound_TopDown() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[3, 3] { { false, false, false }, @@ -172,8 +162,6 @@ public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBound_TopDown() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_VerticalOrientation() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[4, 5] { { false, false, false, true, false }, diff --git a/UnitTests/UnitTests.Notifications.Shared/TestToastContentBuilder.cs b/UnitTests/UnitTests.Notifications.Shared/TestToastContentBuilder.cs index 10f2f0cc401..9aacfab13a1 100644 --- a/UnitTests/UnitTests.Notifications.Shared/TestToastContentBuilder.cs +++ b/UnitTests/UnitTests.Notifications.Shared/TestToastContentBuilder.cs @@ -5,10 +5,7 @@ using Microsoft.Toolkit.Uwp.Notifications; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace UnitTests.Notifications { @@ -418,7 +415,7 @@ public void AddTextTest_WithMoreThan4LinesOfText_ThrowInvalidOperationException( ToastContentBuilder builder = new ToastContentBuilder(); // Act - ToastContentBuilder anotherReference = builder.AddText(testText1) + _ = builder.AddText(testText1) .AddText(testText2) .AddText(testText3) .AddText(testText4); @@ -433,7 +430,7 @@ public void AddTextTest_WithMaxLinesValueLargerThan2_ThrowArgumentOutOfRangeExce ToastContentBuilder builder = new ToastContentBuilder(); // Act - ToastContentBuilder anotherReference = builder.AddText(testText1, hintMaxLines: 3); + _ = builder.AddText(testText1, hintMaxLines: 3); } [TestMethod] From c998f0985df9a229066267877aa0d69633afd22c Mon Sep 17 00:00:00 2001 From: Vincent Date: Wed, 11 Mar 2020 15:48:17 +0100 Subject: [PATCH 2/6] address comments --- Microsoft.Toolkit.Parsers/Rss/RssHelper.cs | 6 +++--- .../DataGrid/DataGrid.cs | 2 +- .../DataGrid/DataGridCellsPresenter.cs | 3 +++ .../DataGrid/DataGridColumnHeadersPresenter.cs | 3 +++ .../DataGrid/DataGridDataConnection.cs | 1 + .../ImageCropper/ImageCropper.Events.cs | 6 ++++-- Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs | 4 +++- 7 files changed, 18 insertions(+), 7 deletions(-) diff --git a/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs b/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs index 1bc9d0c64cf..e17afdbf233 100644 --- a/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs +++ b/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs @@ -311,9 +311,9 @@ public static string TimeZoneToOffset(string tz) tz = tz.ToUpper().Trim(); - if (timeZones.ContainsKey(tz)) + if (TimeZones.ContainsKey(tz)) { - return timeZones[tz].First(); + return TimeZones[tz].First(); } return null; @@ -374,7 +374,7 @@ private static IEnumerable GetImagesInHTMLString(string htmlString) /// /// Dictionary of timezones. /// - private static readonly Dictionary timeZones = new Dictionary + private static readonly Dictionary TimeZones = new Dictionary { { "ACDT", new[] { "-1030", "Australian Central Daylight" } }, { "ACST", new[] { "-0930", "Australian Central Standard" } }, diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs index f7f7b207bca..a4099d34afe 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs @@ -3207,7 +3207,7 @@ public void ScrollIntoView(object item, DataGridColumn column) rowGroupInfo = RowGroupInfoFromCollectionViewGroup(collectionViewGroup); if (rowGroupInfo == null) { - Debug.Assert(false, "Expected non-null rowGroupInfo."); + Debug.Fail("Expected non-null rowGroupInfo."); return; } diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs index 3f2d9cf4c87..f7409ced760 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs @@ -274,6 +274,9 @@ protected override Size MeasureOverride(Size availableSize) // then we will resize all the columns to fit the available space. if (this.OwningGrid.UsesStarSizing && !this.OwningGrid.AutoSizingColumns) { + double adjustment = this.OwningGrid.CellsWidth - totalDisplayWidth; + this.OwningGrid.AdjustColumnWidths(0, adjustment, false); + // Since we didn't know the final widths of the columns until we resized, // we waited until now to measure each cell double leftEdge = 0; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs index 5b07ace3d7a..7f0d0ea763f 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs @@ -359,6 +359,9 @@ protected override Size MeasureOverride(Size availableSize) // then we will resize all the columns to fit the available space. if (this.OwningGrid.UsesStarSizing && !this.OwningGrid.AutoSizingColumns) { + double adjustment = double.IsPositiveInfinity(availableSize.Width) ? this.OwningGrid.CellsWidth : availableSize.Width - totalDisplayWidth; + this.OwningGrid.AdjustColumnWidths(0, adjustment, false); + // Since we didn't know the final widths of the columns until we resized, // we waited until now to measure each header double leftEdge = 0; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs index 986e91a6ee6..d584336951c 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs @@ -544,6 +544,7 @@ public bool GetPropertyIsReadOnly(string propertyName) // Either the property doesn't exist or it does exist but is read-only. return true; } + // Check if EditableAttribute is defined on the property and if it indicates uneditable var editableAttribute = propertyInfo.GetCustomAttributes().OfType().FirstOrDefault(); if (editableAttribute != null && !editableAttribute.AllowEdit) diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs index 4f743a504a7..82614619a95 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs @@ -23,12 +23,14 @@ private void ImageCropperThumb_KeyDown(object sender, KeyRoutedEventArgs e) if (e.Key == VirtualKey.Left) { diffPos.X--; - if (Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Up) == CoreVirtualKeyStates.Down) + var upKeyState = Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Up); + var downKeyState = Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Down); + if (upKeyState == CoreVirtualKeyStates.Down) { diffPos.Y--; } - if (Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Down) == CoreVirtualKeyStates.Down) + if (downKeyState == CoreVirtualKeyStates.Down) { diffPos.Y++; } diff --git a/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs b/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs index 9898ef02dd3..b70792c75a7 100644 --- a/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs +++ b/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs @@ -11,6 +11,8 @@ namespace Microsoft.Toolkit.Uwp.Extensions /// public static class StringExtensions { + private static readonly ResourceLoader IndependentLoader = ResourceLoader.GetForViewIndependentUse(); + /// /// Retrieves the provided resource for the current view context. /// @@ -25,7 +27,7 @@ public static string GetViewLocalized(this string resourceKey) /// Resource key to retrieve. /// string value for given resource or empty string if not found. public static string GetLocalized(this string resourceKey) - => ResourceLoader.GetForViewIndependentUse().GetString(resourceKey); + => IndependentLoader.GetString(resourceKey); /// /// Retrieves the provided resource for the given key for use independent of the UI thread. From 84a79955701909a896929b0c1004811c954fb5ba Mon Sep 17 00:00:00 2001 From: Vincent Date: Fri, 13 Mar 2020 13:02:06 +0100 Subject: [PATCH 3/6] fixed style cop issue --- Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs b/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs index e933d64ce80..b5b9dff9138 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs @@ -247,9 +247,8 @@ protected override Size MeasureOverride(Size availableSize) } } - double width; - // It's a Auto size, so we define the size should be 3 items + double width; if (double.IsInfinity(availableSize.Width)) { width = Carousel.Orientation == Orientation.Horizontal ? containerWidth * (Children.Count > 3 ? 3 : Children.Count) : containerWidth; @@ -259,8 +258,8 @@ protected override Size MeasureOverride(Size availableSize) width = availableSize.Width; } - double height; // It's a Auto size, so we define the size should be 3 items + double height; if (double.IsInfinity(availableSize.Height)) { height = Carousel.Orientation == Orientation.Vertical ? containerHeight * (Children.Count > 3 ? 3 : Children.Count) : containerHeight; From bd1242fa6483faa51a540a313bb8425130cc56be Mon Sep 17 00:00:00 2001 From: Ze Groumf Date: Thu, 19 Mar 2020 22:42:58 +0100 Subject: [PATCH 4/6] rename variable --- .../DesktopNotificationManagerCompat.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs b/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs index 2c1687698a1..1002a84ff31 100644 --- a/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs +++ b/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs @@ -185,9 +185,9 @@ public static bool IsRunningAsUwp() GetCurrentPackageFullName(ref length, sb); sb = new StringBuilder(length); - var result = GetCurrentPackageFullName(ref length, sb); + var error = GetCurrentPackageFullName(ref length, sb); - _isRunningAsUwp = result != APPMODEL_ERROR_NO_PACKAGE; + _isRunningAsUwp = error != APPMODEL_ERROR_NO_PACKAGE; } } From d203d0a0f1692212516655cc5f2f2a5532a18b7b Mon Sep 17 00:00:00 2001 From: Ze Groumf Date: Thu, 19 Mar 2020 22:43:43 +0100 Subject: [PATCH 5/6] revert var to int --- Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs | 2 +- .../DesktopNotificationManagerCompat.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs b/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs index 5d6c40c20ae..135dfec69a6 100644 --- a/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs +++ b/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs @@ -118,7 +118,7 @@ internal static InlineParseResult Parse(string markdown, int start, int end) if (pos < end && markdown[pos] == '[') { - var refstart = pos; + int refstart = pos; // Find the reference ']' character while (pos < end) diff --git a/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs b/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs index 1002a84ff31..89cecae17eb 100644 --- a/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs +++ b/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs @@ -185,7 +185,7 @@ public static bool IsRunningAsUwp() GetCurrentPackageFullName(ref length, sb); sb = new StringBuilder(length); - var error = GetCurrentPackageFullName(ref length, sb); + int error = GetCurrentPackageFullName(ref length, sb); _isRunningAsUwp = error != APPMODEL_ERROR_NO_PACKAGE; } From d55bdd19a4fe412a19b5f474b0dd07da7aab14c4 Mon Sep 17 00:00:00 2001 From: Vincent Date: Fri, 20 Mar 2020 16:14:46 +0100 Subject: [PATCH 6/6] restore task return value + add discards --- .../BluetoothLEHelper/ObservableGattDeviceService.cs | 7 +++++-- Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs | 7 ++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs b/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs index 6ee1e3e89d7..7ddd6543090 100644 --- a/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs +++ b/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs @@ -48,7 +48,7 @@ public ObservableGattDeviceService(GattDeviceService service) Service = service; Name = GattUuidsService.ConvertUuidToName(service.Uuid); UUID = Service.Uuid.ToString(); - PopulateAllCharacteristicsAsync(); + _ = PopulateAllCharacteristicsAsync(); } /// @@ -149,7 +149,8 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName /// /// Populate the characteristics in . /// - private async void PopulateAllCharacteristicsAsync() + /// The status of the communication with the GATT device. + private async Task PopulateAllCharacteristicsAsync() { var tokenSource = new CancellationTokenSource(5000); var getCharacteristicsTask = await Task.Run( @@ -166,6 +167,8 @@ private async void PopulateAllCharacteristicsAsync() Characteristics.Add(new ObservableGattCharacteristics(gattCharacteristic, this)); } } + + return result.Status; } } } \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs b/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs index 2693248f5d4..936e8fffb82 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Linq; using System.Numerics; +using System.Threading.Tasks; using Microsoft.Toolkit.Uwp.SampleApp.Pages; using Microsoft.Toolkit.Uwp.UI.Animations; using Microsoft.Toolkit.Uwp.UI.Controls; @@ -35,11 +36,11 @@ private Sample CurrentSample set { _currentSample = value; - SetNavViewSelection(); + _ = SetNavViewSelectionAsync(); } } - private async void SetNavViewSelection() + private async Task SetNavViewSelectionAsync() { if (_currentSample != null) { @@ -61,7 +62,7 @@ private void HideSamplePicker() SamplePickerGrid.Visibility = Visibility.Collapsed; _selectedCategory = null; - SetNavViewSelection(); + _ = SetNavViewSelectionAsync(); } private async void ShowSamplePicker(Sample[] samples = null, bool group = false)