diff --git a/App.xaml.cs b/App.xaml.cs index f184685..6cc0421 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -1,19 +1,19 @@ using Chat.ContentDialogs; +using System; +using System.Globalization; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; -using System; -using System.Globalization; namespace Chat { - sealed partial class App : Application + public sealed partial class App : Application { public App() { - this.InitializeComponent(); - this.Suspending += OnSuspending; - this.UnhandledException += App_UnhandledException; + InitializeComponent(); + Suspending += OnSuspending; + UnhandledException += App_UnhandledException; } private async void App_UnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e) @@ -21,18 +21,20 @@ private async void App_UnhandledException(object sender, Windows.UI.Xaml.Unhandl e.Handled = true; string ExceptionDesc = e.Exception.Message + "\nHRESULT: 0x" + e.Exception.HResult.ToString("X4", new CultureInfo("en-US")) + "\n" + e.Exception.StackTrace + "\n" + e.Exception.Source; if (e.Exception.InnerException != null) + { ExceptionDesc += "\n\n" + e.Exception.InnerException.Message + "\nHRESULT: 0x" + e.Exception.InnerException.HResult.ToString("X4", new CultureInfo("en-US")) + "\n" + e.Exception.InnerException.StackTrace + "\n" + e.Exception.InnerException.Source; - else + } + else + { ExceptionDesc += "\n\nNo inner exception was thrown"; + } - await new UnhandledExceptionContentDialog(ExceptionDesc).ShowAsync(); + _ = await new UnhandledExceptionContentDialog(ExceptionDesc).ShowAsync(); } protected override void OnLaunched(LaunchActivatedEventArgs e) { - Shell rootShell = Window.Current.Content as Shell; - - if (rootShell == null) + if (Window.Current.Content is not Shell rootShell) { rootShell = new Shell(); @@ -42,7 +44,9 @@ protected override void OnLaunched(LaunchActivatedEventArgs e) } if (e != null) + { rootShell.HandleArguments(e); + } Window.Current.Content = rootShell; } @@ -56,10 +60,9 @@ protected override void OnLaunched(LaunchActivatedEventArgs e) protected override void OnActivated(IActivatedEventArgs e) { - if (e != null && e.Kind == ActivationKind.Protocol || e != null && e.Kind == ActivationKind.ToastNotification) + if ((e != null && e.Kind == ActivationKind.Protocol) || (e != null && e.Kind == ActivationKind.ToastNotification)) { - Shell rootShell = Window.Current.Content as Shell; - if (rootShell == null) + if (Window.Current.Content is not Shell rootShell) { rootShell = new Shell(); @@ -79,7 +82,7 @@ protected override void OnActivated(IActivatedEventArgs e) private void OnSuspending(object sender, SuspendingEventArgs e) { - var deferral = e.SuspendingOperation.GetDeferral(); + SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } diff --git a/Chat.BackgroundTasks/BackgroundTaskUtils.cs b/Chat.BackgroundTasks/BackgroundTaskUtils.cs index 3291b04..64f0938 100644 --- a/Chat.BackgroundTasks/BackgroundTaskUtils.cs +++ b/Chat.BackgroundTasks/BackgroundTaskUtils.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Windows.ApplicationModel.Background; -using Windows.ApplicationModel.Chat; using Windows.Devices.Sms; -using System; namespace Chat.BackgroundTasks { @@ -107,7 +106,7 @@ internal static void UnRegisterBackgroundTask() if (BackgroundTaskRegistration.AllTasks.Any(i => i.Value.Name.Equals(taskName))) { - var task = BackgroundTaskRegistration.AllTasks.First(i => i.Value.Name.Equals(taskName)); + KeyValuePair task = BackgroundTaskRegistration.AllTasks.First(i => i.Value.Name.Equals(taskName)); task.Value.Unregister(true); } } @@ -117,16 +116,18 @@ internal static void RegisterBackgroundTask(IBackgroundTrigger trigger) string taskName = typeof(T).Name; if (BackgroundTaskRegistration.AllTasks.Any(i => i.Value.Name.Equals(taskName))) + { return; + } - var builder = new BackgroundTaskBuilder() + BackgroundTaskBuilder builder = new BackgroundTaskBuilder() { Name = taskName, TaskEntryPoint = typeof(T).FullName }; builder.SetTrigger(trigger); - builder.Register(); + _ = builder.Register(); } } } diff --git a/Chat.BackgroundTasks/Chat.BackgroundTasks.csproj b/Chat.BackgroundTasks/Chat.BackgroundTasks.csproj index 3e9a194..9419e35 100644 --- a/Chat.BackgroundTasks/Chat.BackgroundTasks.csproj +++ b/Chat.BackgroundTasks/Chat.BackgroundTasks.csproj @@ -11,7 +11,7 @@ Chat.BackgroundTasks en-US UAP - 10.0.19041.0 + 10.0.22621.0 10.0.16299.0 14 512 @@ -130,10 +130,10 @@ - 6.2.13 + 6.2.14 - 7.1.0 + 7.1.3 diff --git a/Chat.BackgroundTasks/ChatMessageNotificationBackgroundTask.cs b/Chat.BackgroundTasks/ChatMessageNotificationBackgroundTask.cs index 6b3d86e..b1ed21e 100644 --- a/Chat.BackgroundTasks/ChatMessageNotificationBackgroundTask.cs +++ b/Chat.BackgroundTasks/ChatMessageNotificationBackgroundTask.cs @@ -1,9 +1,7 @@ using Chat.Common; using Microsoft.Toolkit.Uwp.Notifications; using System; -using System.IO; using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.ApplicationModel.Chat; @@ -43,12 +41,12 @@ private async Task SaveFile(IRandomAccessStreamReference stream, string StorageFile file = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); - using (var srcStream = await stream.OpenReadAsync()) - using (var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite)) - using (var reader = new DataReader(srcStream.GetInputStreamAt(0))) + using (IRandomAccessStreamWithContentType srcStream = await stream.OpenReadAsync()) + using (IRandomAccessStream targetStream = await file.OpenAsync(FileAccessMode.ReadWrite)) + using (DataReader reader = new DataReader(srcStream.GetInputStreamAt(0))) { - var output = targetStream.GetOutputStreamAt(0); - await reader.LoadAsync((uint)srcStream.Size); + IOutputStream output = targetStream.GetOutputStreamAt(0); + _ = await reader.LoadAsync((uint)srcStream.Size); while (reader.UnconsumedBufferLength > 0) { uint dataToRead = reader.UnconsumedBufferLength > 64 @@ -56,10 +54,10 @@ private async Task SaveFile(IRandomAccessStreamReference stream, string : reader.UnconsumedBufferLength; IBuffer buffer = reader.ReadBuffer(dataToRead); - await output.WriteAsync(buffer); + _ = await output.WriteAsync(buffer); } - await output.FlushAsync(); + _ = await output.FlushAsync(); return file.Path; } @@ -67,13 +65,13 @@ private async Task SaveFile(IRandomAccessStreamReference stream, string private async Task DisplayToast(ChatMessage message) { - var information = await ContactUtils.FindContactInformationFromSender(message.From); + ContactUtils.ContactInformation information = await ContactUtils.FindContactInformationFromSender(message.From); string thumbnailpath = ""; string text = ""; string deviceid = SmsDevice2.GetDefault().DeviceId; - foreach (var attachment in message.Attachments) + foreach (ChatMessageAttachment attachment in message.Attachments) { try { @@ -92,14 +90,14 @@ private async Task DisplayToast(ChatMessage message) if (attachment.MimeType.StartsWith("image/")) { text += "Image content in this message. "; - var imageextension = attachment.MimeType.Split('/').Last(); + string imageextension = attachment.MimeType.Split('/').Last(); thumbnailpath = await SaveFile(attachment.DataStreamReference, "messagepicture." + DateTimeOffset.Now.ToUnixTimeMilliseconds() + "." + imageextension); } if (attachment.MimeType.StartsWith("audio/")) { text += "Audio content in this message. "; - var audioextension = attachment.MimeType.Split('/').Last(); + string audioextension = attachment.MimeType.Split('/').Last(); } } catch @@ -108,7 +106,7 @@ private async Task DisplayToast(ChatMessage message) } } - var toastContent = new ToastContent() + ToastContent toastContent = new ToastContent() { Visual = new ToastVisual() { @@ -167,7 +165,7 @@ private async Task DisplayToast(ChatMessage message) } }; - var toastNotif = new ToastNotification(toastContent.GetXml()); + ToastNotification toastNotif = new ToastNotification(toastContent.GetXml()); ToastNotificationManager.CreateToastNotifier().Show(toastNotif); } } diff --git a/Chat.BackgroundTasks/SmsBackgroundTask.cs b/Chat.BackgroundTasks/SmsBackgroundTask.cs index 0caab7f..46ec962 100644 --- a/Chat.BackgroundTasks/SmsBackgroundTask.cs +++ b/Chat.BackgroundTasks/SmsBackgroundTask.cs @@ -1,13 +1,9 @@ using Chat.Common; using Microsoft.Toolkit.Uwp.Notifications; using System; -using System.IO; -using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.Devices.Sms; -using Windows.Storage; -using Windows.Storage.Streams; using Windows.UI.Notifications; namespace Chat.BackgroundTasks @@ -72,7 +68,7 @@ private async Task DisplayToast(IBackgroundTaskInstance taskInstance) return; } - var toastContent = new ToastContent() + ToastContent toastContent = new ToastContent() { Visual = new ToastVisual() { @@ -127,7 +123,7 @@ private async Task DisplayToast(IBackgroundTaskInstance taskInstance) } }; - var toastNotif = new ToastNotification(toastContent.GetXml()); + ToastNotification toastNotif = new ToastNotification(toastContent.GetXml()); ToastNotificationManager.CreateToastNotifier().Show(toastNotif); try diff --git a/Chat.BackgroundTasks/SmsReplyBackgroundTask.cs b/Chat.BackgroundTasks/SmsReplyBackgroundTask.cs index 06e3a7d..be134d8 100644 --- a/Chat.BackgroundTasks/SmsReplyBackgroundTask.cs +++ b/Chat.BackgroundTasks/SmsReplyBackgroundTask.cs @@ -29,7 +29,7 @@ private async Task HandleTaskActions(IBackgroundTaskInstance taskInstance) } - var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail; + ToastNotificationActionTriggerDetail details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail; string arguments = details.Argument; @@ -45,7 +45,7 @@ private async Task HandleTaskActions(IBackgroundTaskInstance taskInstance) { string messagetosend = (string)details.UserInput["textBox"]; SmsDevice2 smsDevice = SmsDevice2.FromId(deviceid); - await SmsUtils.SendTextMessageAsync(smsDevice, from, messagetosend); + _ = await SmsUtils.SendTextMessageAsync(smsDevice, from, messagetosend); } catch { diff --git a/Chat.BackgroundTasks/UpdateTask.cs b/Chat.BackgroundTasks/UpdateTask.cs index dc92294..82849b7 100644 --- a/Chat.BackgroundTasks/UpdateTask.cs +++ b/Chat.BackgroundTasks/UpdateTask.cs @@ -18,7 +18,7 @@ public void Run(IBackgroundTaskInstance taskInstance) BackgroundTaskUtils.UnRegisterToastNotificationBackgroundTasks(); BackgroundTaskUtils.RegisterToastNotificationBackgroundTasks(); - var toastContent = new ToastContent() + ToastContent toastContent = new ToastContent() { Visual = new ToastVisual() { @@ -40,7 +40,7 @@ public void Run(IBackgroundTaskInstance taskInstance) }; // Create the toast notification - var toastNotif = new ToastNotification(toastContent.GetXml()); + ToastNotification toastNotif = new ToastNotification(toastContent.GetXml()); // And send the notification ToastNotificationManager.CreateToastNotifier().Show(toastNotif); diff --git a/Chat.Common/BadgeHandler.cs b/Chat.Common/BadgeHandler.cs index 240a0ff..e21a8ae 100644 --- a/Chat.Common/BadgeHandler.cs +++ b/Chat.Common/BadgeHandler.cs @@ -1,8 +1,4 @@ -using Windows.Data.Xml.Dom; -using Windows.Storage; -using Windows.UI.Notifications; - -namespace Chat.Common +namespace Chat.Common { public class BadgeHandler { diff --git a/Chat.Common/Chat.Common.csproj b/Chat.Common/Chat.Common.csproj index d12d6a1..0ff0f39 100644 --- a/Chat.Common/Chat.Common.csproj +++ b/Chat.Common/Chat.Common.csproj @@ -11,7 +11,7 @@ Chat.Common en-US UAP - 10.0.19041.0 + 10.0.22621.0 10.0.16299.0 14 512 @@ -128,7 +128,7 @@ - 6.2.13 + 6.2.14 diff --git a/Chat.Common/ContactUtils.cs b/Chat.Common/ContactUtils.cs index bc472a1..b58dfc0 100644 --- a/Chat.Common/ContactUtils.cs +++ b/Chat.Common/ContactUtils.cs @@ -6,9 +6,9 @@ using System.Threading.Tasks; using Windows.ApplicationModel.Contacts; using Windows.Devices.Sms; +using Windows.Globalization.PhoneNumberFormatting; using Windows.Storage; using Windows.Storage.Streams; -using Windows.Globalization.PhoneNumberFormatting; namespace Chat.Common { @@ -16,20 +16,31 @@ public class ContactUtils { public class ContactInformation { - public string DisplayName { get; set; } - public string ThumbnailPath { get; set; } - public string PhoneNumberKind { get; set; } + public string DisplayName + { + get; set; + } + public string ThumbnailPath + { + get; set; + } + public string PhoneNumberKind + { + get; set; + } } public static async Task GetMyself() { - var store = await ContactManager.RequestStoreAsync(); + ContactStore store = await ContactManager.RequestStoreAsync(); if (store != null) { - var contact = await store.GetMeContactAsync(); + Contact contact = await store.GetMeContactAsync(); if (contact != null) + { return contact; + } } Contact blankcontact = new Contact(); @@ -39,8 +50,14 @@ public static async Task GetMyself() private class PhoneNumberInfo2 { - public string Number { get; set; } - public string CountryCode { get; set; } + public string Number + { + get; set; + } + public string CountryCode + { + get; set; + } } private static PhoneNumberInfo2 GetPhoneNumberInformation(string phonenumber) @@ -52,8 +69,8 @@ private static PhoneNumberInfo2 GetPhoneNumberInformation(string phonenumber) var supportedCodes = phoneUtil.GetSupportedRegions().ToArray(); var result = phoneUtil.TryGetValidNumber(phonenumber, supportedCodes, out number);*/ - var countrycode = ""; - var nationalnumber = phonenumber; + string countrycode = ""; + string nationalnumber = phonenumber; /*if (result) { @@ -69,25 +86,27 @@ private static PhoneNumberInfo2 GetPhoneNumberInformation(string phonenumber) public static bool ArePhoneNumbersMostLikelyTheSame(string num1, string num2) { - var formatter = new PhoneNumberFormatter(); + PhoneNumberFormatter formatter = new PhoneNumberFormatter(); - var fnum1 = formatter.FormatPartialString(num1); - var fnum2 = formatter.FormatPartialString(num2); + string fnum1 = formatter.FormatPartialString(num1); + string fnum2 = formatter.FormatPartialString(num2); if (fnum1 == fnum2) + { return true; + } - var inum1 = new PhoneNumberInfo(fnum1); - var inum2 = new PhoneNumberInfo(fnum2); + PhoneNumberInfo inum1 = new PhoneNumberInfo(fnum1); + PhoneNumberInfo inum2 = new PhoneNumberInfo(fnum2); - var match = inum1.CheckNumberMatch(inum2); + PhoneNumberMatchResult match = inum1.CheckNumberMatch(inum2); if (match == PhoneNumberMatchResult.ExactMatch || match == PhoneNumberMatchResult.NationalSignificantNumberMatch || match == PhoneNumberMatchResult.ShortNationalSignificantNumberMatch) { return true; } - var info = GetPhoneNumberInformation(num1); + PhoneNumberInfo2 info = GetPhoneNumberInformation(num1); string number = info.Number; string countrycode = info.CountryCode; @@ -95,11 +114,13 @@ public static bool ArePhoneNumbersMostLikelyTheSame(string num1, string num2) if (string.IsNullOrEmpty(countrycode)) { if (num2.ToLower().Replace(" ", "").Replace("(", "").Replace(")", "") == number.ToLower().Replace(" ", "").Replace("(", "").Replace(")", "")) + { return true; + } } else { - var info2 = GetPhoneNumberInformation(num1); + PhoneNumberInfo2 info2 = GetPhoneNumberInformation(num1); string number2 = info2.Number; string countrycode2 = info2.CountryCode; @@ -111,7 +132,9 @@ public static bool ArePhoneNumbersMostLikelyTheSame(string num1, string num2) else if (string.IsNullOrEmpty(countrycode2)) { if (num2.Replace(" ", "").Replace("(", "").Replace(")", "") == number.ToLower().Replace(" ", "").Replace("(", "").Replace(")", "")) + { return true; + } } else if (number == number2) { @@ -125,17 +148,19 @@ public static async Task BindPhoneNumberToGlobalContact(string phonenum { try { - var store = await ContactManager.RequestStoreAsync(); + ContactStore store = await ContactManager.RequestStoreAsync(); if (store != null) { - var contacts = await store.FindContactsAsync(); + IReadOnlyList contacts = await store.FindContactsAsync(); - foreach (var contact in contacts) + foreach (Contact contact in contacts) { - foreach (var num in contact.Phones) + foreach (ContactPhone num in contact.Phones) { if (ArePhoneNumbersMostLikelyTheSame(phonenumber, num.Number)) + { return contact; + } } } } @@ -150,7 +175,7 @@ public static async Task BindPhoneNumberToGlobalContact(string phonenum return blankcontact; } - public async static Task FindContactInformationFromSmsMessage(ISmsMessageBase message) + public static async Task FindContactInformationFromSmsMessage(ISmsMessageBase message) { string from = ""; @@ -189,13 +214,13 @@ public async static Task FindContactInformationFromSmsMessag return await FindContactInformationFromSender(from); } - public async static Task FindContactInformationFromSender(string from) + public static async Task FindContactInformationFromSender(string from) { ContactInformation info = new ContactInformation() { DisplayName = from, PhoneNumberKind = "Unknown", ThumbnailPath = "" }; try { - var contact = await BindPhoneNumberToGlobalContact(from); + Contact contact = await BindPhoneNumberToGlobalContact(from); info.DisplayName = contact.DisplayName; try @@ -211,12 +236,12 @@ public async static Task FindContactInformationFromSender(st StorageFile file = await storageFolder.CreateFileAsync(contact.Id + ".png", CreationCollisionOption.ReplaceExisting); - using (var srcStream = await contact.SmallDisplayPicture.OpenReadAsync()) - using (var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite)) - using (var reader = new DataReader(srcStream.GetInputStreamAt(0))) + using (IRandomAccessStreamWithContentType srcStream = await contact.SmallDisplayPicture.OpenReadAsync()) + using (IRandomAccessStream targetStream = await file.OpenAsync(FileAccessMode.ReadWrite)) + using (DataReader reader = new DataReader(srcStream.GetInputStreamAt(0))) { - var output = targetStream.GetOutputStreamAt(0); - await reader.LoadAsync((uint)srcStream.Size); + IOutputStream output = targetStream.GetOutputStreamAt(0); + _ = await reader.LoadAsync((uint)srcStream.Size); while (reader.UnconsumedBufferLength > 0) { uint dataToRead = reader.UnconsumedBufferLength > 64 @@ -224,10 +249,10 @@ public async static Task FindContactInformationFromSender(st : reader.UnconsumedBufferLength; IBuffer buffer = reader.ReadBuffer(dataToRead); - await output.WriteAsync(buffer); + _ = await output.WriteAsync(buffer); } - await output.FlushAsync(); + _ = await output.FlushAsync(); info.ThumbnailPath = file.Path; } @@ -240,38 +265,37 @@ public async static Task FindContactInformationFromSender(st return info; } - public async static void AssignAppToPhoneContacts() + public static async void AssignAppToPhoneContacts() { try { - var store = await ContactManager.RequestStoreAsync(); + ContactStore store = await ContactManager.RequestStoreAsync(); - var contacts = await store.FindContactsAsync(); + IReadOnlyList contacts = await store.FindContactsAsync(); if (contacts != null) { - var phonecontacts = contacts.Where(x => x.Phones.Count != 0); + IEnumerable phonecontacts = contacts.Where(x => x.Phones.Count != 0); if (phonecontacts != null) { - foreach (var phonecontact in phonecontacts) + foreach (Contact phonecontact in phonecontacts) { ContactAnnotationStore annotationStore = await ContactManager.RequestAnnotationStoreAsync(ContactAnnotationStoreAccessType.AppAnnotationsReadWrite); ContactAnnotationList annotationList; IReadOnlyList annotationLists = await annotationStore.FindAnnotationListsAsync(); - if (0 == annotationLists.Count) - annotationList = await annotationStore.CreateAnnotationListAsync(); - else - annotationList = annotationLists[0]; + annotationList = 0 == annotationLists.Count ? await annotationStore.CreateAnnotationListAsync() : annotationLists[0]; - ContactAnnotation annotation = new ContactAnnotation(); - annotation.ContactId = phonecontact.Id; - annotation.RemoteId = phonecontact.Id; + ContactAnnotation annotation = new ContactAnnotation + { + ContactId = phonecontact.Id, + RemoteId = phonecontact.Id, - annotation.SupportedOperations = ContactAnnotationOperations.Message; + SupportedOperations = ContactAnnotationOperations.Message + }; - await annotationList.TrySaveAnnotationAsync(annotation); + _ = await annotationList.TrySaveAnnotationAsync(annotation); } } } diff --git a/Chat.Common/SmsUtils.cs b/Chat.Common/SmsUtils.cs index 7393bd6..e14d6d4 100644 --- a/Chat.Common/SmsUtils.cs +++ b/Chat.Common/SmsUtils.cs @@ -7,17 +7,17 @@ namespace Chat.Common { public class SmsUtils { - public async static Task SendTextMessageAsync(SmsDevice2 device, string[] numbers, string textmessage, string transportId = "0") + public static async Task SendTextMessageAsync(SmsDevice2 device, string[] numbers, string textmessage, string transportId = "0") { bool returnresult = true; ChatMessageStore store = await ChatMessageManager.RequestStoreAsync(); if (string.IsNullOrEmpty(transportId) || await ChatMessageManager.GetTransportAsync(transportId) == null) { - var transports = await ChatMessageManager.GetTransportsAsync(); + System.Collections.Generic.IReadOnlyList transports = await ChatMessageManager.GetTransportsAsync(); if (transports.Count != 0) { - var transport = transports[0]; + ChatMessageTransport transport = transports[0]; transportId = transport.TransportId; } else @@ -27,26 +27,29 @@ public async static Task SendTextMessageAsync(SmsDevice2 device, string[] } try { - SmsTextMessage2 message = new SmsTextMessage2(); - message.Body = textmessage; + SmsTextMessage2 message = new SmsTextMessage2 + { + Body = textmessage + }; - foreach (var number in numbers) + foreach (string number in numbers) { - var num = number.Trim(); + string num = number.Trim(); message.To = num; try { SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(message); - var offset = new DateTimeOffset(DateTime.Now); + DateTimeOffset offset = new DateTimeOffset(DateTime.Now); returnresult &= result.IsSuccessful; try { - ChatMessage msg = new ChatMessage(); - - msg.Body = textmessage; + ChatMessage msg = new ChatMessage + { + Body = textmessage + }; msg.Recipients.Add(num); msg.LocalTimestamp = offset; @@ -79,7 +82,7 @@ public async static Task SendTextMessageAsync(SmsDevice2 device, string[] return returnresult; } - public async static Task SendTextMessageAsync(SmsDevice2 device, string number, string textmessage, string transportId = "0") + public static async Task SendTextMessageAsync(SmsDevice2 device, string number, string textmessage, string transportId = "0") { return await SendTextMessageAsync(device, new string[1] { number }, textmessage, transportId); } diff --git a/Chat.csproj b/Chat.csproj index 43d346f..6744b2d 100644 --- a/Chat.csproj +++ b/Chat.csproj @@ -11,8 +11,8 @@ Chat en-US UAP - 10.0.19041.0 - 10.0.16299.0 + 10.0.22621.0 + 10.0.17763.0 14 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} @@ -21,10 +21,10 @@ False 0C621A92C67CDD2186E4CD138C08E1F1DE8D16B4 True - False + True True Always - arm|arm64 + arm64 0 SHA256 @@ -219,23 +219,23 @@ + + 8.2.2 + 0.0.33 - 6.2.13 + 6.2.14 - 7.1.0 + 7.1.3 - 7.1.0 + 7.1.3 - 2.7.0 - - - 5.4.1.1 + 2.8.6 diff --git a/ContentDialogs/AboutContentDialog.xaml.cs b/ContentDialogs/AboutContentDialog.xaml.cs index d0499b1..13e7b1e 100644 --- a/ContentDialogs/AboutContentDialog.xaml.cs +++ b/ContentDialogs/AboutContentDialog.xaml.cs @@ -1,5 +1,5 @@ using Chat.ViewModels; -using GalaSoft.MvvmLight.Command; +using CommunityToolkit.Mvvm.Input; using System.Windows.Input; using Windows.UI.Xaml.Controls; @@ -13,7 +13,7 @@ public sealed partial class AboutContentDialog : ContentDialog public AboutContentDialog() { - this.InitializeComponent(); + InitializeComponent(); } private ICommand _closeDialogCommand; @@ -21,14 +21,8 @@ public ICommand CloseDialogCommand { get { - if (_closeDialogCommand == null) - { - _closeDialogCommand = new RelayCommand( - () => - { - Hide(); - }); - } + _closeDialogCommand ??= new RelayCommand( + Hide); return _closeDialogCommand; } } diff --git a/ContentDialogs/CellularUnavailableContentDialog.xaml.cs b/ContentDialogs/CellularUnavailableContentDialog.xaml.cs index 5c8a769..47b5162 100644 --- a/ContentDialogs/CellularUnavailableContentDialog.xaml.cs +++ b/ContentDialogs/CellularUnavailableContentDialog.xaml.cs @@ -1,4 +1,4 @@ -using GalaSoft.MvvmLight.Command; +using CommunityToolkit.Mvvm.Input; using System.Windows.Input; using Windows.UI.Xaml.Controls; @@ -8,7 +8,7 @@ public sealed partial class CellularUnavailableContentDialog : ContentDialog { public CellularUnavailableContentDialog() { - this.InitializeComponent(); + InitializeComponent(); } private ICommand _closeDialogCommand; @@ -16,14 +16,8 @@ public ICommand CloseDialogCommand { get { - if (_closeDialogCommand == null) - { - _closeDialogCommand = new RelayCommand( - () => - { - Hide(); - }); - } + _closeDialogCommand ??= new RelayCommand( + Hide); return _closeDialogCommand; } } diff --git a/ContentDialogs/UnhandledExceptionContentDialog.xaml.cs b/ContentDialogs/UnhandledExceptionContentDialog.xaml.cs index afe6390..e120f23 100644 --- a/ContentDialogs/UnhandledExceptionContentDialog.xaml.cs +++ b/ContentDialogs/UnhandledExceptionContentDialog.xaml.cs @@ -1,19 +1,6 @@ -using GalaSoft.MvvmLight.Command; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; +using CommunityToolkit.Mvvm.Input; using System.Windows.Input; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; // The Content Dialog item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 @@ -23,7 +10,7 @@ public sealed partial class UnhandledExceptionContentDialog : ContentDialog { public UnhandledExceptionContentDialog(string Description) { - this.InitializeComponent(); + InitializeComponent(); UnhandledExceptionDescription.Text = Description; } @@ -32,14 +19,8 @@ public ICommand CloseDialogCommand { get { - if (_closeDialogCommand == null) - { - _closeDialogCommand = new RelayCommand( - () => - { - Hide(); - }); - } + _closeDialogCommand ??= new RelayCommand( + Hide); return _closeDialogCommand; } } diff --git a/Controls/CellularLineControl.xaml.cs b/Controls/CellularLineControl.xaml.cs index 96b06fb..72e5c61 100644 --- a/Controls/CellularLineControl.xaml.cs +++ b/Controls/CellularLineControl.xaml.cs @@ -12,11 +12,14 @@ namespace Chat.Controls { public sealed partial class CellularLineControl : ComboBoxItem { - public SmsDevice2 device { get; internal set; } + public SmsDevice2 device + { + get; internal set; + } public CellularLineControl(SmsDevice2 device) { - this.InitializeComponent(); + InitializeComponent(); this.device = device; Load(); @@ -29,14 +32,16 @@ private async void Load() if (device != null) { if (device.AccountPhoneNumber != null) + { displayname = device.AccountPhoneNumber; + } switch (device.DeviceStatus) { case SmsDeviceStatus.DeviceBlocked: { StatusIcon.Text = ""; - var pad = StatusIcon.Padding; + Windows.UI.Xaml.Thickness pad = StatusIcon.Padding; pad.Top = 0; StatusIcon.Padding = pad; break; @@ -44,7 +49,7 @@ private async void Load() case SmsDeviceStatus.DeviceFailure: { StatusIcon.Text = ""; - var pad = StatusIcon.Padding; + Windows.UI.Xaml.Thickness pad = StatusIcon.Padding; pad.Top = 0; StatusIcon.Padding = pad; break; @@ -57,7 +62,7 @@ private async void Load() case SmsDeviceStatus.Off: { StatusIcon.Text = ""; - var pad = StatusIcon.Padding; + Windows.UI.Xaml.Thickness pad = StatusIcon.Padding; pad.Top = 0; StatusIcon.Padding = pad; break; @@ -65,7 +70,7 @@ private async void Load() case SmsDeviceStatus.Ready: { StatusIcon.Text = ""; - var pad = StatusIcon.Padding; + Windows.UI.Xaml.Thickness pad = StatusIcon.Padding; pad.Top = 0; StatusIcon.Padding = pad; break; @@ -85,7 +90,7 @@ private async void Load() string selectorStr = MobileBroadbandModem.GetDeviceSelector(); DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selectorStr); - foreach (var mdevice in devices) + foreach (DeviceInformation mdevice in devices) { MobileBroadbandModem modem = MobileBroadbandModem.FromId(mdevice.Id); if (modem.DeviceInformation.TelephoneNumbers.Count > 0) @@ -97,10 +102,10 @@ private async void Load() // from https://github.com/ADeltaX/MobileShell/blob/experiments/src/App.xaml.cs PhoneCallStore store = await PhoneCallManager.RequestStoreAsync(); PhoneLineWatcher watcher = store.RequestLineWatcher(); - List phoneLines = new List(); - TaskCompletionSource lineEnumerationCompletion = new TaskCompletionSource(); + List phoneLines = []; + TaskCompletionSource lineEnumerationCompletion = new(); - watcher.LineAdded += async (o, args) => { var line = await PhoneLine.FromIdAsync(args.LineId); phoneLines.Add(line); }; + watcher.LineAdded += async (o, args) => { PhoneLine line = await PhoneLine.FromIdAsync(args.LineId); phoneLines.Add(line); }; watcher.Stopped += (o, args) => lineEnumerationCompletion.TrySetResult(false); watcher.EnumerationCompleted += (o, args) => lineEnumerationCompletion.TrySetResult(true); @@ -110,15 +115,19 @@ private async void Load() { watcher.Stop(); - List returnedLines = new List(); + List returnedLines = []; foreach (PhoneLine phoneLine in phoneLines) + { if (phoneLine != null && phoneLine.Transport == PhoneLineTransport.Cellular) + { returnedLines.Add(phoneLine); + } + } if (returnedLines.Any(x => x.NetworkName == modem.CurrentNetwork.RegisteredProviderName)) { - var line = returnedLines.First(x => x.NetworkName == modem.CurrentNetwork.RegisteredProviderName); + PhoneLine line = returnedLines.First(x => x.NetworkName == modem.CurrentNetwork.RegisteredProviderName); displayname += " (SIM " + (line.CellularDetails.SimSlotIndex + 1) + ")"; } } diff --git a/Controls/ChatMenuItemControl.xaml.cs b/Controls/ChatMenuItemControl.xaml.cs index f5451b3..5c60a2b 100644 --- a/Controls/ChatMenuItemControl.xaml.cs +++ b/Controls/ChatMenuItemControl.xaml.cs @@ -1,27 +1,29 @@ using Chat.ViewModels; +using Microsoft.UI.Xaml.Controls; using System; using Windows.ApplicationModel.Chat; -using Microsoft.UI.Xaml.Controls; namespace Chat.Controls { public sealed partial class ChatMenuItemControl : NavigationViewItem { public ChatMenuItemViewModel ViewModel { get; } = new ChatMenuItemViewModel(""); - public string ConversationId { get; internal set; } + public string ConversationId + { + get; internal set; + } public ChatMenuItemControl(string ConversationId) { - this.InitializeComponent(); + InitializeComponent(); this.ConversationId = ConversationId; ViewModel.Initialize(ConversationId); } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private async void DeleteConvoButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { - var store = await ChatMessageManager.RequestStoreAsync(); + ChatMessageStore store = await ChatMessageManager.RequestStoreAsync(); await (await store.GetConversationAsync(ConversationId)).DeleteAsync(); } } diff --git a/Controls/ChatMessageViewControl.xaml.cs b/Controls/ChatMessageViewControl.xaml.cs index 7380f9a..99c823d 100644 --- a/Controls/ChatMessageViewControl.xaml.cs +++ b/Controls/ChatMessageViewControl.xaml.cs @@ -1,12 +1,12 @@ using Chat.ViewModels; -using GalaSoft.MvvmLight.Command; +using CommunityToolkit.Mvvm.Input; +using System; using System.Windows.Input; using Windows.ApplicationModel.Chat; -using Windows.UI.Xaml.Controls; -using System; using Windows.ApplicationModel.DataTransfer; -using Windows.UI.Xaml; using Windows.Foundation; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; namespace Chat.Controls { @@ -14,10 +14,13 @@ public sealed partial class ChatMessageViewControl : UserControl { public ChatMessageViewModel ViewModel { get; } = new ChatMessageViewModel(""); - public string messageId { get; internal set; } + public string messageId + { + get; internal set; + } public ChatMessageViewControl(string messageId) { - this.InitializeComponent(); + InitializeComponent(); this.messageId = messageId; ViewModel.Initialize(messageId); @@ -31,19 +34,19 @@ private void ChatMessageViewControl_Loaded(object sender, RoutedEventArgs e) public void RefreshVisuals() { - var height = ((Shell)Window.Current.Content).ActualHeight; - var width = ((Shell)Window.Current.Content).ActualWidth; + double height = ((Shell)Window.Current.Content).ActualHeight; + double width = ((Shell)Window.Current.Content).ActualWidth; - var ttv = ChatBubble.TransformToVisual(Window.Current.Content); + Windows.UI.Xaml.Media.GeneralTransform ttv = ChatBubble.TransformToVisual(Window.Current.Content); Point screenCoords = ttv.TransformPoint(new Point(0, 0)); - var controlWidth = ChatBubble.Width; - var controlHeight = ChatBubble.Height; + double controlWidth = ChatBubble.Width; + double controlHeight = ChatBubble.Height; BgColor.Width = width; BgColor.Height = height; - var marg = BgColor.Margin; + Thickness marg = BgColor.Margin; marg.Left = screenCoords.X - width; marg.Top = screenCoords.Y - height; marg.Right = screenCoords.X - width - controlWidth; @@ -57,15 +60,12 @@ public ICommand MessageDelete { get { - if (_messageDelete == null) - { - _messageDelete = new RelayCommand( + _messageDelete ??= new RelayCommand( async () => { - var store = await ChatMessageManager.RequestStoreAsync(); + ChatMessageStore store = await ChatMessageManager.RequestStoreAsync(); await store.DeleteMessageAsync(messageId); }); - } return _messageDelete; } } @@ -75,14 +75,11 @@ public ICommand MessageForward { get { - if (_messageForward == null) - { - _messageForward = new RelayCommand( + _messageForward ??= new RelayCommand( () => { }); - } return _messageForward; } } @@ -92,18 +89,15 @@ public ICommand MessageCopy { get { - if (_messageCopy == null) - { - _messageCopy = new RelayCommand( + _messageCopy ??= new RelayCommand( async () => { - var store = await ChatMessageManager.RequestStoreAsync(); - var msg = await store.GetMessageAsync(messageId); - var dataPackage = new DataPackage(); + ChatMessageStore store = await ChatMessageManager.RequestStoreAsync(); + ChatMessage msg = await store.GetMessageAsync(messageId); + DataPackage dataPackage = new(); dataPackage.SetText(msg.Body); Clipboard.SetContent(dataPackage); }); - } return _messageCopy; } } @@ -113,19 +107,15 @@ public ICommand MessageDetails { get { - if (_messageDetails == null) - { - _messageDetails = new RelayCommand( + _messageDetails ??= new RelayCommand( () => { }); - } return _messageDetails; } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private void UserControl_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e) { messageMenuFlyout.ShowAt(this, e.GetPosition(this)); diff --git a/Controls/ContactPhoneViewControl.xaml.cs b/Controls/ContactPhoneViewControl.xaml.cs index b90f1f4..87501ab 100644 --- a/Controls/ContactPhoneViewControl.xaml.cs +++ b/Controls/ContactPhoneViewControl.xaml.cs @@ -5,11 +5,14 @@ namespace Chat.Controls { public sealed partial class ContactPhoneViewControl : UserControl { - public ContactPhone contactPhone { get; internal set; } + public ContactPhone contactPhone + { + get; internal set; + } public ContactPhoneViewControl(ContactPhone contactPhone, Contact contact) { - this.InitializeComponent(); + InitializeComponent(); if (contactPhone != null && contact != null) { this.contactPhone = contactPhone; diff --git a/Controls/TitlebarControl.xaml.cs b/Controls/TitlebarControl.xaml.cs index bafada6..703a4c4 100644 --- a/Controls/TitlebarControl.xaml.cs +++ b/Controls/TitlebarControl.xaml.cs @@ -75,10 +75,13 @@ private void Back_Click(object sender, RoutedEventArgs e) BackButtonClick?.Invoke(this, e); } - public async void RefreshColor() + public void RefreshColor() { ApplicationViewTitleBar titlebar = ApplicationView.GetForCurrentView().TitleBar; - SolidColorBrush transparentColorBrush = new() { Opacity = 0 }; + SolidColorBrush transparentColorBrush = new() + { + Opacity = 0 + }; Color transparentColor = transparentColorBrush.Color; titlebar.BackgroundColor = transparentColor; @@ -198,7 +201,7 @@ public string Title private void AttachDebuggerButton_Click(object sender, RoutedEventArgs e) { - Debugger.Launch(); + _ = Debugger.Launch(); if (Debugger.IsAttached) { diff --git a/Helpers/Observable.cs b/Helpers/Observable.cs index b5642e5..c9bfd62 100644 --- a/Helpers/Observable.cs +++ b/Helpers/Observable.cs @@ -7,7 +7,7 @@ public class Observable : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; - protected void Set(ref T storage, T value, [CallerMemberName]string propertyName = null) + protected void Set(ref T storage, T value, [CallerMemberName] string propertyName = null) { if (Equals(storage, value)) { @@ -18,6 +18,9 @@ protected void Set(ref T storage, T value, [CallerMemberName]string propertyN OnPropertyChanged(propertyName); } - protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + protected void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } } } diff --git a/Package.appxmanifest b/Package.appxmanifest index 0508ad6..8df3800 100644 --- a/Package.appxmanifest +++ b/Package.appxmanifest @@ -10,7 +10,7 @@ + Version="1.0.122.0" /> diff --git a/Pages/ComposePage.xaml.cs b/Pages/ComposePage.xaml.cs index 4a0d8fc..280641f 100644 --- a/Pages/ComposePage.xaml.cs +++ b/Pages/ComposePage.xaml.cs @@ -1,8 +1,7 @@ using Chat.Common; using Chat.Controls; -using Chat.Helpers; using Chat.ViewModels; -using GalaSoft.MvvmLight.Command; +using CommunityToolkit.Mvvm.Input; using System; using System.Collections.Generic; using System.Linq; @@ -22,13 +21,13 @@ public sealed partial class ComposePage : Page public ComposePage() { - this.InitializeComponent(); + InitializeComponent(); Loaded += ComposePage_Loaded; } private void ComposePage_Loaded(object sender, RoutedEventArgs e) { - ContactPickerBox.Focus(FocusState.Pointer); + _ = ContactPickerBox.Focus(FocusState.Pointer); } protected override void OnNavigatedTo(NavigationEventArgs e) @@ -37,36 +36,34 @@ protected override void OnNavigatedTo(NavigationEventArgs e) if (e != null) { - var args = e.Parameter as Contact; - if (args != null) + if (e.Parameter is Contact args) { ContactPickerBox.Text = args.DisplayName; } } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private async void ContactPickerBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { - var store = await ContactManager.RequestStoreAsync(); - List contactControls = new List(); + ContactStore store = await ContactManager.RequestStoreAsync(); + List contactControls = []; try { if (!sender.Text.Contains(";", StringComparison.InvariantCulture)) { - var contacts = await store.FindContactsAsync(sender.Text); + IReadOnlyList contacts = await store.FindContactsAsync(sender.Text); if (contacts != null) { - var phonecontacts = contacts.Where(x => x.Phones.Count != 0); + IEnumerable phonecontacts = contacts.Where(x => x.Phones.Count != 0); if (phonecontacts != null) { - foreach (var phonecontact in phonecontacts) + foreach (Contact phonecontact in phonecontacts) { - foreach (var phone in phonecontact.Phones) + foreach (ContactPhone phone in phonecontact.Phones) { - var control = new ContactPhoneViewControl(phone, phonecontact); + ContactPhoneViewControl control = new(phone, phonecontact); contactControls.Add(control); } } @@ -86,30 +83,35 @@ private async void ContactPickerBox_QuerySubmitted(AutoSuggestBox sender, AutoSu { if (args.ChosenSuggestion == null) { - var picker = new ContactPicker(); - picker.CommitButtonText = "Select"; - picker.SelectionMode = ContactSelectionMode.Fields; + ContactPicker picker = new() + { + CommitButtonText = "Select", + SelectionMode = ContactSelectionMode.Fields + }; picker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber); - var result = await picker.PickContactAsync(); + Contact result = await picker.PickContactAsync(); if (result != null) { if (string.IsNullOrEmpty(ContactPickerBox.Text)) + { ContactPickerBox.Text = result.Phones.First().Number; + } else + { ContactPickerBox.Text += "; " + result.Phones.First().Number; - ContactPickerBox.Focus(FocusState.Pointer); + } + + _ = ContactPickerBox.Focus(FocusState.Pointer); } } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private void ContactPickerBox_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args) { ContactPickerBox.Text = (args.SelectedItem as ContactPhoneViewControl).contactPhone.Number; } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private void CellularLineComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (CellularLineComboBox.SelectedItem != null) @@ -118,7 +120,6 @@ private void CellularLineComboBox_SelectionChanged(object sender, SelectionChang } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private void ComposeTextBox_TextChanged(object sender, TextChangedEventArgs e) { if (CellularLineComboBox.SelectedItem != null) @@ -132,14 +133,11 @@ public ICommand ShowAttachments { get { - if (_showAttachments == null) - { - _showAttachments = new RelayCommand( + _showAttachments ??= new RelayCommand( () => { - FlyoutBase.ShowAttachedFlyout((FrameworkElement)AttachmentButton); + FlyoutBase.ShowAttachedFlyout(AttachmentButton); }); - } return _showAttachments; } } @@ -150,31 +148,30 @@ public ICommand SendReply { get { - if (_sendReply == null) - { - _sendReply = new RelayCommand( + _sendReply ??= new RelayCommand( async () => { SendButton.IsEnabled = false; ComposeTextBox.IsEnabled = false; - var smsDevice = ViewModel.SelectedLine.device; + Windows.Devices.Sms.SmsDevice2 smsDevice = ViewModel.SelectedLine.device; try { - var result = await SmsUtils.SendTextMessageAsync(smsDevice, ContactPickerBox.Text.Split(';'), ComposeTextBox.Text); + bool result = await SmsUtils.SendTextMessageAsync(smsDevice, ContactPickerBox.Text.Split(';'), ComposeTextBox.Text); if (!result) - await new MessageDialog("We could not send one or some messages.", "Something went wrong").ShowAsync(); + { + _ = await new MessageDialog("We could not send one or some messages.", "Something went wrong").ShowAsync(); + } } catch (Exception ex) { - await new MessageDialog($"We could not send one or some messages.\n{ex}", "Something went wrong").ShowAsync(); + _ = await new MessageDialog($"We could not send one or some messages.\n{ex}", "Something went wrong").ShowAsync(); } SendButton.IsEnabled = true; ComposeTextBox.IsEnabled = true; ComposeTextBox.Text = ""; }); - } return _sendReply; } } diff --git a/Pages/ConversationPage.xaml.cs b/Pages/ConversationPage.xaml.cs index ba0207f..fb56ce5 100644 --- a/Pages/ConversationPage.xaml.cs +++ b/Pages/ConversationPage.xaml.cs @@ -1,8 +1,7 @@ using Chat.Common; using Chat.Controls; -using Chat.Helpers; using Chat.ViewModels; -using GalaSoft.MvvmLight.Command; +using CommunityToolkit.Mvvm.Input; using System; using System.Linq; using System.Windows.Input; @@ -24,7 +23,7 @@ public sealed partial class ConversationPage : Page public ConversationPage() { - this.InitializeComponent(); + InitializeComponent(); MessageListView.Loaded += MessageListView_Loaded; MessageListView.SizeChanged += MessageListView_SizeChanged; @@ -32,9 +31,9 @@ public ConversationPage() private void MessageListView_SizeChanged(object sender, SizeChangedEventArgs e) { - foreach (var item in MessageListView.Items) + foreach (object item in MessageListView.Items) { - var control = item as ChatMessageViewControl; + ChatMessageViewControl control = item as ChatMessageViewControl; control.RefreshVisuals(); } } @@ -48,14 +47,13 @@ private void MessageListView_Loaded(object sender, RoutedEventArgs e) private void ScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e) { - foreach (var item in MessageListView.Items) + foreach (object item in MessageListView.Items) { - var control = item as ChatMessageViewControl; + ChatMessageViewControl control = item as ChatMessageViewControl; control.RefreshVisuals(); } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private void CellularLineComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (CellularLineComboBox.SelectedItem != null) @@ -64,7 +62,6 @@ private void CellularLineComboBox_SelectionChanged(object sender, SelectionChang } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private void ComposeTextBox_TextChanged(object sender, TextChangedEventArgs e) { if (CellularLineComboBox.SelectedItem != null) @@ -78,14 +75,11 @@ public ICommand ShowAttachments { get { - if (_showAttachments == null) - { - _showAttachments = new RelayCommand( + _showAttachments ??= new RelayCommand( () => { - FlyoutBase.ShowAttachedFlyout((FrameworkElement)AttachmentButton); + FlyoutBase.ShowAttachedFlyout(AttachmentButton); }); - } return _showAttachments; } } @@ -95,15 +89,12 @@ public ICommand StartCall { get { - if (_startCall == null) - { - _startCall = new RelayCommand( + _startCall ??= new RelayCommand( async () => { - var store = await ChatMessageManager.RequestStoreAsync(); - await Launcher.LaunchUriAsync(new Uri("tel:" + (await store.GetConversationAsync(ConversationId)).Participants.First())); + ChatMessageStore store = await ChatMessageManager.RequestStoreAsync(); + _ = await Launcher.LaunchUriAsync(new Uri("tel:" + (await store.GetConversationAsync(ConversationId)).Participants.First())); }); - } return _startCall; } } @@ -113,32 +104,31 @@ public ICommand SendReply { get { - if (_sendReply == null) - { - _sendReply = new RelayCommand( + _sendReply ??= new RelayCommand( async () => { SendButton.IsEnabled = false; ComposeTextBox.IsEnabled = false; - var smsDevice = ViewModel.SelectedLine.device; + Windows.Devices.Sms.SmsDevice2 smsDevice = ViewModel.SelectedLine.device; try { - var store = await ChatMessageManager.RequestStoreAsync(); - var result = await SmsUtils.SendTextMessageAsync(smsDevice, (await store.GetConversationAsync(ConversationId)).Participants.First(), ComposeTextBox.Text); + ChatMessageStore store = await ChatMessageManager.RequestStoreAsync(); + bool result = await SmsUtils.SendTextMessageAsync(smsDevice, (await store.GetConversationAsync(ConversationId)).Participants.First(), ComposeTextBox.Text); if (!result) - await new MessageDialog("We could not send one or some messages.", "Something went wrong").ShowAsync(); + { + _ = await new MessageDialog("We could not send one or some messages.", "Something went wrong").ShowAsync(); + } } catch (Exception ex) { - await new MessageDialog($"We could not send one or some messages.\n{ex}", "Something went wrong").ShowAsync(); + _ = await new MessageDialog($"We could not send one or some messages.\n{ex}", "Something went wrong").ShowAsync(); } SendButton.IsEnabled = true; ComposeTextBox.IsEnabled = true; ComposeTextBox.Text = ""; }); - } return _sendReply; } } @@ -149,8 +139,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) if (e != null) { - var args = e.Parameter as string; - if (args != null) + if (e.Parameter is string args) { ConversationId = args; ViewModel.Initialize(ConversationId); diff --git a/Shell.xaml.cs b/Shell.xaml.cs index 5813eb8..128c3d4 100644 --- a/Shell.xaml.cs +++ b/Shell.xaml.cs @@ -3,7 +3,7 @@ using Chat.Controls; using Chat.Pages; using Chat.ViewModels; -using GalaSoft.MvvmLight.Command; +using CommunityToolkit.Mvvm.Input; using System; using System.Globalization; using System.Linq; @@ -22,18 +22,16 @@ public sealed partial class Shell : UserControl public Shell() { - this.InitializeComponent(); + InitializeComponent(); } public void HandleArguments(object e) { - var args = e as ProtocolActivatedEventArgs; - if (args != null) + if (e is ProtocolActivatedEventArgs args) { HandleArguments(args); } - var args2 = e as ToastNotificationActivatedEventArgs; - if (args2 != null) + if (e is ToastNotificationActivatedEventArgs args2) { HandleArguments(args2); } @@ -43,13 +41,13 @@ private async void HandleArguments(ProtocolActivatedEventArgs args) { Uri uri = args.Uri; string unescpateduri = Uri.UnescapeDataString(uri.Query); - var contactid = unescpateduri.Replace("?ContactRemoteIds=", "", StringComparison.InvariantCulture); + string contactid = unescpateduri.Replace("?ContactRemoteIds=", "", StringComparison.InvariantCulture); if (uri.Scheme == "ms-ipmessaging") { ContactStore store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite); Contact contact = await store.GetContactAsync(contactid); - MainFrame.Navigate(typeof(ComposePage), contact); + _ = MainFrame.Navigate(typeof(ComposePage), contact); } } @@ -69,7 +67,7 @@ private async void HandleArguments(ToastNotificationActivatedEventArgs args) { string messagetosend = (string)args.UserInput["textBox"]; SmsDevice2 smsDevice = SmsDevice2.FromId(deviceid); - await SmsUtils.SendTextMessageAsync(smsDevice, from, messagetosend); + _ = await SmsUtils.SendTextMessageAsync(smsDevice, from, messagetosend); } catch { @@ -81,10 +79,10 @@ private async void HandleArguments(ToastNotificationActivatedEventArgs args) case "openthread": { ChatMenuItemControl selectedConvo = null; - foreach (var convo in ViewModel.ChatConversations) + foreach (ChatMenuItemControl convo in ViewModel.ChatConversations) { - var contact = convo.ViewModel.Contact; - foreach (var num in contact.Phones) + Contact contact = convo.ViewModel.Contact; + foreach (ContactPhone num in contact.Phones) { if (ContactUtils.ArePhoneNumbersMostLikelyTheSame(from, num.Number)) { @@ -93,10 +91,15 @@ private async void HandleArguments(ToastNotificationActivatedEventArgs args) } } if (selectedConvo != null) + { break; + } } if (selectedConvo != null) + { ViewModel.SelectedItem = selectedConvo; + } + break; } } @@ -107,15 +110,12 @@ public ICommand NewConvoCommand { get { - if (_newConvoCommand == null) - { - _newConvoCommand = new RelayCommand( + _newConvoCommand ??= new RelayCommand( () => { - MainFrame.Navigate(typeof(ComposePage)); + _ = MainFrame.Navigate(typeof(ComposePage)); ViewModel.SelectedItem = null; }); - } return _newConvoCommand; } } @@ -125,9 +125,7 @@ public ICommand OpenAboutCommand { get { - if (_openAboutCommand == null) - { - _openAboutCommand = new RelayCommand( + _openAboutCommand ??= new RelayCommand( async () => { #if !DEBUG @@ -135,21 +133,22 @@ public ICommand OpenAboutCommand #else Windows.ApplicationModel.Chat.ChatMessageStore store = await Windows.ApplicationModel.Chat.ChatMessageManager.RequestStoreAsync(); string transportId = await Windows.ApplicationModel.Chat.ChatMessageManager.RegisterTransportAsync(); - Windows.ApplicationModel.Chat.ChatMessage msg = new Windows.ApplicationModel.Chat.ChatMessage(); - - msg.Body = "Hello how are you?"; + Windows.ApplicationModel.Chat.ChatMessage msg = new() + { + Body = "Hello how are you?", - msg.TransportId = transportId; + TransportId = transportId, - msg.MessageOperatorKind = Windows.ApplicationModel.Chat.ChatMessageOperatorKind.Sms; - msg.Status = Windows.ApplicationModel.Chat.ChatMessageStatus.Sent; + MessageOperatorKind = Windows.ApplicationModel.Chat.ChatMessageOperatorKind.Sms, + Status = Windows.ApplicationModel.Chat.ChatMessageStatus.Sent + }; bool alternate = new Random().Next(2) == 2; msg.Recipients.Clear(); msg.From = ""; - var offset = new DateTimeOffset(DateTime.Now); + DateTimeOffset offset = new(DateTime.Now); msg.LocalTimestamp = offset; msg.NetworkTimestamp = offset; @@ -168,16 +167,16 @@ public ICommand OpenAboutCommand await store.SaveMessageAsync(msg); #endif }); - } return _openAboutCommand; } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "")] private void NavigationView_SelectionChanged(MUXC.NavigationView sender, MUXC.NavigationViewSelectionChangedEventArgs args) { if (args.SelectedItem != null) - MainFrame.Navigate(typeof(ConversationPage), (args.SelectedItem as ChatMenuItemControl).ConversationId); + { + _ = MainFrame.Navigate(typeof(ConversationPage), (args.SelectedItem as ChatMenuItemControl).ConversationId); + } } } } diff --git a/ViewModels/AboutViewModel.cs b/ViewModels/AboutViewModel.cs index 2056000..1ae9341 100644 --- a/ViewModels/AboutViewModel.cs +++ b/ViewModels/AboutViewModel.cs @@ -9,15 +9,15 @@ public class AboutViewModel : Observable private string _appName; public string AppName { - get { return _appName; } - set { Set(ref _appName, value); } + get => _appName; + set => Set(ref _appName, value); } private string _versionNumber; public string VersionNumber { - get { return _versionNumber; } - set { Set(ref _versionNumber, value); } + get => _versionNumber; + set => Set(ref _versionNumber, value); } @@ -38,7 +38,7 @@ public void Initialize() // Methods private static string GetAppName() { - var package = Package.Current; + Package package = Package.Current; string appName = package.DisplayName; return appName; @@ -46,9 +46,9 @@ private static string GetAppName() private static string GetVersionNumber() { - var package = Package.Current; - var packageId = package.Id; - var version = packageId.Version; + Package package = Package.Current; + PackageId packageId = package.Id; + PackageVersion version = packageId.Version; return $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"; } diff --git a/ViewModels/ChatMenuItemViewModel.cs b/ViewModels/ChatMenuItemViewModel.cs index 5fc36b0..a537446 100644 --- a/ViewModels/ChatMenuItemViewModel.cs +++ b/ViewModels/ChatMenuItemViewModel.cs @@ -16,29 +16,29 @@ public class ChatMenuItemViewModel : Observable private Contact _contact; public Contact Contact { - get { return _contact; } - set { Set(ref _contact, value); } + get => _contact; + set => Set(ref _contact, value); } private string _displayName; public string DisplayName { - get { return _displayName; } - set { Set(ref _displayName, value); } + get => _displayName; + set => Set(ref _displayName, value); } private string _displayDescription; public string DisplayDescription { - get { return _displayDescription; } - set { Set(ref _displayDescription, value); } + get => _displayDescription; + set => Set(ref _displayDescription, value); } private DateTime _timeStamp; public DateTime TimeStamp { - get { return _timeStamp; } - set { Set(ref _timeStamp, value); } + get => _timeStamp; + set => Set(ref _timeStamp, value); } private ChatMessageStore _store; @@ -57,19 +57,21 @@ public ChatMenuItemViewModel(string ConvoId) public async void Initialize(string ConvoId) { if (string.IsNullOrEmpty(ConvoId)) + { return; + } _store = await ChatMessageManager.RequestStoreAsync(); _conversationid = ConvoId; - var convo = await _store.GetConversationAsync(_conversationid); + ChatConversation convo = await _store.GetConversationAsync(_conversationid); if (convo == null) { DropEvents(); return; } - (var tmpContact, var tmpDisplayName) = await GetContactInformation(); + (Contact tmpContact, string tmpDisplayName) = await GetContactInformation(); (DisplayDescription, TimeStamp) = await GetLastMessageInfo(); (Contact, DisplayName) = (tmpContact, tmpDisplayName); @@ -79,8 +81,14 @@ public async void Initialize(string ConvoId) private void Subscribe(bool enabled) { - if (!enabled && mSubscribed) _store.StoreChanged -= Store_StoreChanged; - else if (enabled && !mSubscribed) _store.StoreChanged += Store_StoreChanged; + if (!enabled && mSubscribed) + { + _store.StoreChanged -= Store_StoreChanged; + } + else if (enabled && !mSubscribed) + { + _store.StoreChanged += Store_StoreChanged; + } mSubscribed = enabled; } @@ -92,19 +100,18 @@ public void DropEvents() // Methods - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] private async Task<(Contact, string)> GetContactInformation() { try { - var convo = await _store.GetConversationAsync(_conversationid); - var contact = await ContactUtils.BindPhoneNumberToGlobalContact(convo.Participants.First()); + ChatConversation convo = await _store.GetConversationAsync(_conversationid); + Contact contact = await ContactUtils.BindPhoneNumberToGlobalContact(convo.Participants.First()); return (contact, contact.DisplayName); } catch { - Contact blankcontact = new Contact(); + Contact blankcontact = new(); blankcontact.Phones.Add(new ContactPhone() { Number = "Unknown", Kind = ContactPhoneKind.Other }); return (blankcontact, "Unknown"); } @@ -112,14 +119,14 @@ public void DropEvents() private async Task<(string, DateTime)> GetLastMessageInfo() { - var convo = await _store.GetConversationAsync(_conversationid); + ChatConversation convo = await _store.GetConversationAsync(_conversationid); - var messageReader = convo.GetMessageReader(); - var lastMessageId = convo.MostRecentMessageId; + ChatMessageReader messageReader = convo.GetMessageReader(); + string lastMessageId = convo.MostRecentMessageId; - var messages = await messageReader.ReadBatchAsync(); + System.Collections.Generic.IReadOnlyList messages = await messageReader.ReadBatchAsync(); - var lastMessage = messages.Where(x => x.Id == lastMessageId).First(); + ChatMessage lastMessage = messages.Where(x => x.Id == lastMessageId).First(); return (lastMessage.Body, lastMessage.LocalTimestamp.LocalDateTime); } @@ -127,13 +134,15 @@ public void DropEvents() private async void Store_StoreChanged(ChatMessageStore sender, ChatMessageStoreChangedEventArgs args) { if (args.Id != _conversationid) + { return; + } switch (args.Kind) { case ChatStoreChangedEventKind.ConversationModified: { - var conversation = await _store.GetConversationAsync(args.Id); + ChatConversation conversation = await _store.GetConversationAsync(args.Id); if (conversation == null) { @@ -141,7 +150,7 @@ private async void Store_StoreChanged(ChatMessageStore sender, ChatMessageStoreC break; } - (var str, var dt) = await GetLastMessageInfo(); + (string str, DateTime dt) = await GetLastMessageInfo(); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => diff --git a/ViewModels/ChatMessageViewModel.cs b/ViewModels/ChatMessageViewModel.cs index 1ae00e8..7211355 100644 --- a/ViewModels/ChatMessageViewModel.cs +++ b/ViewModels/ChatMessageViewModel.cs @@ -6,8 +6,6 @@ using Windows.ApplicationModel.Chat; using Windows.ApplicationModel.Contacts; using Windows.ApplicationModel.Core; -using Windows.Storage; -using Windows.Storage.Streams; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; @@ -20,43 +18,43 @@ public class ChatMessageViewModel : Observable private DateTime _timeStamp; public DateTime TimeStamp { - get { return _timeStamp; } - set { Set(ref _timeStamp, value); } + get => _timeStamp; + set => Set(ref _timeStamp, value); } private Visibility _incomingVisibility; public Visibility IncomingVisibility { - get { return _incomingVisibility; } - set { Set(ref _incomingVisibility, value); } + get => _incomingVisibility; + set => Set(ref _incomingVisibility, value); } private string _messageBody; public string MessageBody { - get { return _messageBody; } - set { Set(ref _messageBody, value); } + get => _messageBody; + set => Set(ref _messageBody, value); } private Contact _contact; public Contact Contact { - get { return _contact; } - set { Set(ref _contact, value); } + get => _contact; + set => Set(ref _contact, value); } private HorizontalAlignment _alignment; public HorizontalAlignment Alignment { - get { return _alignment; } - set { Set(ref _alignment, value); } + get => _alignment; + set => Set(ref _alignment, value); } private ImageSource _image; public ImageSource Image { - get { return _image; } - set { Set(ref _image, value); } + get => _image; + set => Set(ref _image, value); } private ChatMessageStore _store; @@ -74,22 +72,24 @@ public ChatMessageViewModel(string MessageId) public async void Initialize(string MessageId) { if (string.IsNullOrEmpty(MessageId)) + { return; + } _store = await ChatMessageManager.RequestStoreAsync(); _messageid = MessageId; - var _tmpContact = await GetContactInformation(); - (var _align, var _visi) = await GetMessageVisuals(); + Contact _tmpContact = await GetContactInformation(); + (HorizontalAlignment _align, Visibility _visi) = await GetMessageVisuals(); (MessageBody, TimeStamp) = await GetMessageInfo(); (Alignment, IncomingVisibility) = (_align, _visi); Contact = _tmpContact; - var message = await _store.GetMessageAsync(_messageid); + ChatMessage message = await _store.GetMessageAsync(_messageid); - foreach (var attachment in message.Attachments) + foreach (ChatMessageAttachment attachment in message.Attachments) { try { @@ -100,25 +100,25 @@ public async void Initialize(string MessageId) if (attachment.MimeType == "text/vcard") { - + } if (attachment.MimeType.StartsWith("image/", StringComparison.InvariantCulture)) { - var imageextension = attachment.MimeType.Split('/').Last(); - var img = new BitmapImage(); + string imageextension = attachment.MimeType.Split('/').Last(); + BitmapImage img = new(); await img.SetSourceAsync(await attachment.DataStreamReference.OpenReadAsync()); Image = img; } if (attachment.MimeType.StartsWith("audio/", StringComparison.InvariantCulture)) { - var audioextension = attachment.MimeType.Split('/').Last(); + string audioextension = attachment.MimeType.Split('/').Last(); } } catch { - + } } @@ -128,8 +128,14 @@ public async void Initialize(string MessageId) private void Subscribe(bool enabled) { - if (!enabled && mSubscribed) _store.StoreChanged -= Store_StoreChanged; - else if (enabled && !mSubscribed) _store.StoreChanged += Store_StoreChanged; + if (!enabled && mSubscribed) + { + _store.StoreChanged -= Store_StoreChanged; + } + else if (enabled && !mSubscribed) + { + _store.StoreChanged += Store_StoreChanged; + } mSubscribed = enabled; } @@ -142,32 +148,31 @@ public void DropEvents() // Methods private async Task GetContactInformation() { - var msg = await _store.GetMessageAsync(_messageid); - - if (!msg.IsIncoming) - return await ContactUtils.GetMyself(); + ChatMessage msg = await _store.GetMessageAsync(_messageid); - return await ContactUtils.BindPhoneNumberToGlobalContact(msg.From); + return !msg.IsIncoming ? await ContactUtils.GetMyself() : await ContactUtils.BindPhoneNumberToGlobalContact(msg.From); } private async Task<(HorizontalAlignment, Visibility)> GetMessageVisuals() { - var msg = await _store.GetMessageAsync(_messageid); - var align = msg.IsIncoming ? HorizontalAlignment.Left : HorizontalAlignment.Right; - var visi = msg.IsIncoming ? Visibility.Collapsed : Visibility.Visible; + ChatMessage msg = await _store.GetMessageAsync(_messageid); + HorizontalAlignment align = msg.IsIncoming ? HorizontalAlignment.Left : HorizontalAlignment.Right; + Visibility visi = msg.IsIncoming ? Visibility.Collapsed : Visibility.Visible; return (align, visi); } private async Task<(string, DateTime)> GetMessageInfo() { - var msg = await _store.GetMessageAsync(_messageid); + ChatMessage msg = await _store.GetMessageAsync(_messageid); return (msg.Body, msg.LocalTimestamp.LocalDateTime); } private async void Store_StoreChanged(ChatMessageStore sender, ChatMessageStoreChangedEventArgs args) { if (args.Id != _messageid) + { return; + } switch (args.Kind) { @@ -183,7 +188,7 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPrio } case ChatStoreChangedEventKind.MessageModified: { - (var body, var ts) = await GetMessageInfo(); + (string body, DateTime ts) = await GetMessageInfo(); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => diff --git a/ViewModels/ComposeViewModel.cs b/ViewModels/ComposeViewModel.cs index cf2c534..cbc0fe8 100644 --- a/ViewModels/ComposeViewModel.cs +++ b/ViewModels/ComposeViewModel.cs @@ -13,15 +13,15 @@ public class ComposeViewModel : Observable private ObservableCollection _cellularLines; public ObservableCollection CellularLines { - get { return _cellularLines; } - internal set { Set(ref _cellularLines, value); } + get => _cellularLines; + internal set => Set(ref _cellularLines, value); } private CellularLineControl _selectedLine; public CellularLineControl SelectedLine { - get { return _selectedLine; } - set { Set(ref _selectedLine, value); } + get => _selectedLine; + set => Set(ref _selectedLine, value); } // Constructor @@ -37,20 +37,22 @@ public async void Initialize() CellularLines = await GetSmsDevices(); if (CellularLines.Count != 0) + { SelectedLine = CellularLines[0]; + } } // Methods private static async Task> GetSmsDevices() { - ObservableCollection collection = new ObservableCollection(); - var smsDevices = await DeviceInformation.FindAllAsync(SmsDevice2.GetDeviceSelector(), null); - foreach (var smsDevice in smsDevices) + ObservableCollection collection = []; + DeviceInformationCollection smsDevices = await DeviceInformation.FindAllAsync(SmsDevice2.GetDeviceSelector(), null); + foreach (DeviceInformation smsDevice in smsDevices) { try { SmsDevice2 dev = SmsDevice2.FromId(smsDevice.Id); - CellularLineControl control = new CellularLineControl(dev); + CellularLineControl control = new(dev); collection.Add(control); } catch diff --git a/ViewModels/ConversationViewModel.cs b/ViewModels/ConversationViewModel.cs index c64a5b3..8f70c79 100644 --- a/ViewModels/ConversationViewModel.cs +++ b/ViewModels/ConversationViewModel.cs @@ -20,43 +20,43 @@ public class ConversationViewModel : Observable private ObservableCollection _chatMessages; public ObservableCollection ChatMessages { - get { return _chatMessages; } - internal set { Set(ref _chatMessages, value); } + get => _chatMessages; + internal set => Set(ref _chatMessages, value); } private ObservableCollection _cellularLines; public ObservableCollection CellularLines { - get { return _cellularLines; } - internal set { Set(ref _cellularLines, value); } + get => _cellularLines; + internal set => Set(ref _cellularLines, value); } private CellularLineControl _selectedLine; public CellularLineControl SelectedLine { - get { return _selectedLine; } - set { Set(ref _selectedLine, value); } + get => _selectedLine; + set => Set(ref _selectedLine, value); } private Contact _contact; public Contact Contact { - get { return _contact; } - set { Set(ref _contact, value); } + get => _contact; + set => Set(ref _contact, value); } private string _displayName; public string DisplayName { - get { return _displayName; } - set { Set(ref _displayName, value); } + get => _displayName; + set => Set(ref _displayName, value); } private string _displayDescription; public string DisplayDescription { - get { return _displayDescription; } - set { Set(ref _displayDescription, value); } + get => _displayDescription; + set => Set(ref _displayDescription, value); } private ChatMessageStore _store; @@ -75,11 +75,13 @@ public ConversationViewModel(string ConvoId) public async void Initialize(string ConvoId) { if (string.IsNullOrEmpty(ConvoId)) + { return; + } if (ChatMessages != null && ChatMessages.Count != 0) { - foreach (var msg in ChatMessages) + foreach (ChatMessageViewControl msg in ChatMessages) { msg.ViewModel.DropEvents(); } @@ -93,8 +95,8 @@ public async void Initialize(string ConvoId) _store = await ChatMessageManager.RequestStoreAsync(); _conversationid = ConvoId; - var _tmpchatMessages = await GetMessages(); - var _tmpCellLines = await GetSmsDevices(); + ObservableCollection _tmpchatMessages = await GetMessages(); + ObservableCollection _tmpCellLines = await GetSmsDevices(); (Contact, DisplayName) = await GetContactInformation(); ChatMessages = _tmpchatMessages; @@ -102,7 +104,9 @@ public async void Initialize(string ConvoId) CellularLines = _tmpCellLines; if (CellularLines.Count != 0) + { SelectedLine = CellularLines[0]; + } _store.ChangeTracker.Enable(); Subscribe(true); @@ -110,7 +114,7 @@ public async void Initialize(string ConvoId) private void ChatMessages_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { - foreach (var item in ChatMessages) + foreach (ChatMessageViewControl item in ChatMessages) { item.RefreshVisuals(); } @@ -118,8 +122,14 @@ private void ChatMessages_CollectionChanged(object sender, System.Collections.Sp private void Subscribe(bool enabled) { - if (!enabled && mSubscribed) _store.StoreChanged -= Store_StoreChanged; - else if (enabled && !mSubscribed) _store.StoreChanged += Store_StoreChanged; + if (!enabled && mSubscribed) + { + _store.StoreChanged -= Store_StoreChanged; + } + else if (enabled && !mSubscribed) + { + _store.StoreChanged += Store_StoreChanged; + } mSubscribed = enabled; } @@ -132,11 +142,11 @@ public void DropEvents() // Methods private async Task> GetMessages() { - ObservableCollection collection = new ObservableCollection(); + ObservableCollection collection = []; - var convo = await _store.GetConversationAsync(_conversationid); - var reader = convo.GetMessageReader(); - var messages = await reader.ReadBatchAsync(); + ChatConversation convo = await _store.GetConversationAsync(_conversationid); + ChatMessageReader reader = convo.GetMessageReader(); + System.Collections.Generic.IReadOnlyList messages = await reader.ReadBatchAsync(); messages.ToList().ForEach(x => collection.Insert(0, new ChatMessageViewControl(x.Id))); @@ -145,19 +155,19 @@ private async Task> GetMessages() private async void UpdateMessages() { - var convo = await _store.GetConversationAsync(_conversationid); + ChatConversation convo = await _store.GetConversationAsync(_conversationid); if (convo == null) { DropEvents(); return; } - var reader = convo.GetMessageReader(); - var messages = await reader.ReadBatchAsync(); + ChatMessageReader reader = convo.GetMessageReader(); + System.Collections.Generic.IReadOnlyList messages = await reader.ReadBatchAsync(); - var currindex = ChatMessages.Count(); + int currindex = ChatMessages.Count(); - foreach (var message in messages) + foreach (ChatMessage message in messages) { if (ChatMessages.Any(x => x.messageId == message.Id)) { @@ -165,7 +175,9 @@ private async void UpdateMessages() } if (currindex > ChatMessages.Count()) + { currindex = ChatMessages.Count(); + } await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => @@ -182,19 +194,18 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPrio } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] private async Task<(Contact, string)> GetContactInformation() { try { - var convo = await _store.GetConversationAsync(_conversationid); - var contact = await ContactUtils.BindPhoneNumberToGlobalContact(convo.Participants.First()); + ChatConversation convo = await _store.GetConversationAsync(_conversationid); + Contact contact = await ContactUtils.BindPhoneNumberToGlobalContact(convo.Participants.First()); return (contact, contact.DisplayName); } catch { - Contact blankcontact = new Contact(); + Contact blankcontact = new(); blankcontact.Phones.Add(new ContactPhone() { Number = "Unknown", Kind = ContactPhoneKind.Other }); return (blankcontact, "Unknown"); } @@ -202,14 +213,14 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPrio private static async Task> GetSmsDevices() { - ObservableCollection collection = new ObservableCollection(); - var smsDevices = await DeviceInformation.FindAllAsync(SmsDevice2.GetDeviceSelector(), null); - foreach (var smsDevice in smsDevices) + ObservableCollection collection = []; + DeviceInformationCollection smsDevices = await DeviceInformation.FindAllAsync(SmsDevice2.GetDeviceSelector(), null); + foreach (DeviceInformation smsDevice in smsDevices) { try { SmsDevice2 dev = SmsDevice2.FromId(smsDevice.Id); - CellularLineControl control = new CellularLineControl(dev); + CellularLineControl control = new(dev); collection.Add(control); } catch @@ -224,13 +235,15 @@ private static async Task> GetSmsDevic private async void Store_StoreChanged(ChatMessageStore sender, ChatMessageStoreChangedEventArgs args) { if (args.Id != _conversationid) + { return; + } switch (args.Kind) { case ChatStoreChangedEventKind.ConversationModified: { - var conversation = await _store.GetConversationAsync(args.Id); + ChatConversation conversation = await _store.GetConversationAsync(args.Id); if (conversation == null) { diff --git a/ViewModels/ShellViewModel.cs b/ViewModels/ShellViewModel.cs index e8169c4..8d3d19d 100644 --- a/ViewModels/ShellViewModel.cs +++ b/ViewModels/ShellViewModel.cs @@ -5,14 +5,12 @@ using Chat.Helpers; using System; using System.Collections.ObjectModel; -using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Windows.ApplicationModel.Chat; using Windows.ApplicationModel.Core; using Windows.Devices.Enumeration; using Windows.Devices.Sms; -using Windows.Networking.NetworkOperators; using Windows.UI.Core; namespace Chat.ViewModels @@ -23,15 +21,15 @@ public class ShellViewModel : Observable private ObservableCollection _chatConversations; public ObservableCollection ChatConversations { - get { return _chatConversations; } - internal set { Set(ref _chatConversations, value); } + get => _chatConversations; + internal set => Set(ref _chatConversations, value); } private ChatMenuItemControl _selectedItem; public ChatMenuItemControl SelectedItem { - get { return _selectedItem; } - set { Set(ref _selectedItem, value); } + get => _selectedItem; + set => Set(ref _selectedItem, value); } private ChatMessageStore _store; @@ -52,14 +50,16 @@ public async void Initialize() ChatConversations = await GetChats(); if (ChatConversations.Count != 0) + { SelectedItem = ChatConversations[0]; + } - if (!(await PerformMandatoryChecks())) + if (!await PerformMandatoryChecks()) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { - await new CellularUnavailableContentDialog().ShowAsync(); + _ = await new CellularUnavailableContentDialog().ShowAsync(); }); } @@ -67,14 +67,13 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPrio _store.StoreChanged += Store_StoreChanged; } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] private static async Task PerformMandatoryChecks() { bool available = false; try { - var smsDevices = await DeviceInformation.FindAllAsync(SmsDevice2.GetDeviceSelector(), null); - foreach (var smsDevice in smsDevices) + DeviceInformationCollection smsDevices = await DeviceInformation.FindAllAsync(SmsDevice2.GetDeviceSelector(), null); + foreach (DeviceInformation smsDevice in smsDevices) { try { @@ -103,12 +102,12 @@ private static async Task PerformMandatoryChecks() // Methods private async Task> GetChats() { - ObservableCollection collection = new ObservableCollection(); + ObservableCollection collection = []; - var reader = _store.GetConversationReader(); - var convos = await reader.ReadBatchAsync(); + ChatConversationReader reader = _store.GetConversationReader(); + System.Collections.Generic.IReadOnlyList convos = await reader.ReadBatchAsync(); - foreach (var convo in convos) + foreach (ChatConversation convo in convos) { collection.Add(new ChatMenuItemControl(convo.Id)); } @@ -122,22 +121,24 @@ private async void Store_StoreChanged(ChatMessageStore sender, ChatMessageStoreC { case ChatStoreChangedEventKind.ConversationModified: { - var conversation = await _store.GetConversationAsync(args.Id); + ChatConversation conversation = await _store.GetConversationAsync(args.Id); if (conversation == null) { if (ChatConversations.Any(x => x.ConversationId == args.Id)) { - var existingConversation = ChatConversations.First(x => x.ConversationId == args.Id); + ChatMenuItemControl existingConversation = ChatConversations.First(x => x.ConversationId == args.Id); bool wasSelected = SelectedItem == existingConversation; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { - ChatConversations.Remove(existingConversation); + _ = ChatConversations.Remove(existingConversation); if (wasSelected && ChatConversations.Count != 0) + { SelectedItem = ChatConversations[0]; + } }); } break; @@ -177,16 +178,18 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPrio { if (ChatConversations.Any(x => x.ConversationId == args.Id)) { - var existingConversation = ChatConversations.First(x => x.ConversationId == args.Id); + ChatMenuItemControl existingConversation = ChatConversations.First(x => x.ConversationId == args.Id); bool wasSelected = SelectedItem == existingConversation; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { - ChatConversations.Remove(existingConversation); + _ = ChatConversations.Remove(existingConversation); if (wasSelected && ChatConversations.Count != 0) + { SelectedItem = ChatConversations[0]; + } }); } break;