From 6ea4a47b988d4b854369cd08548d02b49d560b0c Mon Sep 17 00:00:00 2001 From: Lyndon Jetten Date: Fri, 3 Mar 2023 21:23:48 +0100 Subject: [PATCH] Generelle Ausnahmenanzeige --- ChatController/ChatController.csproj | 7 + ChatController/ChatEmojiiControl.xaml.cs | 28 +- ChatController/ChatKlassen/Contact.cs | 8 +- ChatController/ChatMainControl.xaml | 2 +- ChatController/ChatMainControl.xaml.cs | 722 ++++++++++---------- ChatController/ExceptionViewControl.xaml | 57 ++ ChatController/ExceptionViewControl.xaml.cs | 46 ++ ChatController/HauptKlassen/Chat.cs | 693 ++++++++----------- ChatController/HauptKlassen/Login.cs | 438 +++++------- ChatController/LoginControl.xaml.cs | 239 +++---- ChatController/Utilities/FileUtils.cs | 217 +++--- ChatController/Utilities/Utils.cs | 49 +- PrototypChat/App.xaml | 1 + PrototypChat/App.xaml.cs | 10 +- PrototypChat/ExceptionWindow.xaml | 12 + PrototypChat/ExceptionWindow.xaml.cs | 18 + PrototypChat/MainWindow.xaml.cs | 18 +- PrototypChat/PrototypChat.csproj | 7 + 18 files changed, 1226 insertions(+), 1346 deletions(-) create mode 100644 ChatController/ExceptionViewControl.xaml create mode 100644 ChatController/ExceptionViewControl.xaml.cs create mode 100644 PrototypChat/ExceptionWindow.xaml create mode 100644 PrototypChat/ExceptionWindow.xaml.cs diff --git a/ChatController/ChatController.csproj b/ChatController/ChatController.csproj index 1352518..f9cd21c 100644 --- a/ChatController/ChatController.csproj +++ b/ChatController/ChatController.csproj @@ -78,6 +78,9 @@ + + ExceptionViewControl.xaml + @@ -126,6 +129,10 @@ Designer MSBuild:Compile + + Designer + MSBuild:Compile + Designer MSBuild:Compile diff --git a/ChatController/ChatEmojiiControl.xaml.cs b/ChatController/ChatEmojiiControl.xaml.cs index fc14c8f..4f72560 100644 --- a/ChatController/ChatEmojiiControl.xaml.cs +++ b/ChatController/ChatEmojiiControl.xaml.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading; using System.Windows; using System.Windows.Controls; @@ -81,23 +80,16 @@ namespace ChatController public void PassEmojiToChatMainControl(string emojiCode) { - try - { - Dispatcher.Invoke( - DispatcherPriority.Normal, - (ThreadStart) delegate - { - _ChatMainControl.Chatbox.Focus(); + Dispatcher.Invoke( + DispatcherPriority.Normal, + (ThreadStart) delegate + { + _ChatMainControl.Chatbox.Focus(); - var selectionStart = _ChatMainControl.Chatbox.SelectionStart; - _ChatMainControl.Chatbox.Text = _ChatMainControl.Chatbox.Text.Insert(selectionStart, emojiCode); - _ChatMainControl.Chatbox.SelectionStart = selectionStart + emojiCode.Length; - }); - } - catch (Exception e) - { - MessageBox.Show(e.Message); - } + var selectionStart = _ChatMainControl.Chatbox.SelectionStart; + _ChatMainControl.Chatbox.Text = _ChatMainControl.Chatbox.Text.Insert(selectionStart, emojiCode); + _ChatMainControl.Chatbox.SelectionStart = selectionStart + emojiCode.Length; + }); } } } diff --git a/ChatController/ChatKlassen/Contact.cs b/ChatController/ChatKlassen/Contact.cs index d57a250..cd68a52 100644 --- a/ChatController/ChatKlassen/Contact.cs +++ b/ChatController/ChatKlassen/Contact.cs @@ -67,11 +67,13 @@ namespace ChatController.ChatKlassen get => _Image; set { - if(!Equals(_Image, value)) + if(Equals(_Image, value)) { - _Image = value; - OnPropertyChanged(nameof(Image)); + return; } + + _Image = value; + OnPropertyChanged(nameof(Image)); } } diff --git a/ChatController/ChatMainControl.xaml b/ChatController/ChatMainControl.xaml index e225a20..6de679e 100644 --- a/ChatController/ChatMainControl.xaml +++ b/ChatController/ChatMainControl.xaml @@ -11,7 +11,7 @@ mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="600" Loaded="ChatMainControl_OnLoaded" - SnapsToDevicePixels="True" d:DataContext="{d:DesignData Type=ChatMainControl}"> + SnapsToDevicePixels="True" d:DataContext="{d:DesignData Type=chatController:ChatMainControl}"> diff --git a/ChatController/ChatMainControl.xaml.cs b/ChatController/ChatMainControl.xaml.cs index 419c663..b39cb63 100644 --- a/ChatController/ChatMainControl.xaml.cs +++ b/ChatController/ChatMainControl.xaml.cs @@ -40,7 +40,6 @@ using Timer = System.Windows.Forms.Timer; namespace ChatController { - // Test public partial class ChatMainControl : INotifyPropertyChanged { private readonly Dictionary> _Group2NotifyIcons = new Dictionary>(); @@ -55,14 +54,16 @@ namespace ChatController set { - if(!Equals(_ThreadExceptionMessage, value)) + if(Equals(_ThreadExceptionMessage, value)) { - _ThreadExceptionMessage = value; - OnPropertyChanged(nameof(ThreadExceptionMessage)); - OnPropertyChanged(nameof(CurrentContactInformationString)); - OnPropertyChanged(nameof(CurrencContactInfoForeground)); - OnPropertyChanged(nameof(ThreadExceptionImageSource)); + return; } + + _ThreadExceptionMessage = value; + OnPropertyChanged(nameof(ThreadExceptionMessage)); + OnPropertyChanged(nameof(CurrentContactInformationString)); + OnPropertyChanged(nameof(CurrencContactInfoForeground)); + OnPropertyChanged(nameof(ThreadExceptionImageSource)); } } @@ -84,11 +85,13 @@ namespace ChatController { _ContainingWindow = value; - if(!(value is null)) + if(value is null) { - _ContainingWindow.Deactivated += ContainingWindowOnDeactivated; - _ContainingWindow.Activated += ContainingWindowOnActivated; + return; } + + _ContainingWindow.Deactivated += ContainingWindowOnDeactivated; + _ContainingWindow.Activated += ContainingWindowOnActivated; } } @@ -115,17 +118,19 @@ namespace ChatController set { - if(!Equals(_CurrentContact, value)) + if(Equals(_CurrentContact, value)) { - _CurrentContact = value; - - OnPropertyChanged(nameof(CurrentContact)); - OnPropertyChanged(nameof(ChatMessageInputGridVisibility)); - OnPropertyChanged(nameof(Chat)); - OnPropertyChanged(nameof(CurrentContactInformationString)); - OnPropertyChanged(nameof(CurrencContactInfoForeground)); - OnPropertyChanged(nameof(ThreadExceptionImageSource)); + return; } + + _CurrentContact = value; + + OnPropertyChanged(nameof(CurrentContact)); + OnPropertyChanged(nameof(ChatMessageInputGridVisibility)); + OnPropertyChanged(nameof(Chat)); + OnPropertyChanged(nameof(CurrentContactInformationString)); + OnPropertyChanged(nameof(CurrencContactInfoForeground)); + OnPropertyChanged(nameof(ThreadExceptionImageSource)); } } @@ -199,25 +204,17 @@ namespace ChatController foreach(var file in files) { - if(File.Exists(file)) + if(!File.Exists(file)) { - try - { - File.Delete(file); - } - catch(IOException) - { - - } + continue; } + + File.Delete(file); } } finally { - this.Dispatch(() => - { - EndWaiting(); - }); + this.Dispatch(EndWaiting); } }); @@ -263,7 +260,6 @@ namespace ChatController _ContactList = new ObservableSortCollection(); - // ToDo: Hier tritt eine NullPointer-Exception auf! foreach(var contact in Chat.AddContacts()) { ContactList.Add(new ContactDependencyObject(contact)); @@ -299,7 +295,7 @@ namespace ChatController var contact = _ContactList.FirstOrDefault(a => a.Contact.GroupId == pGroupId); - if (!(contact is null)) + if(!(contact is null)) { notificationIcon = Utils.ImageSourceToIcon(contact.Contact.Image); } @@ -331,7 +327,7 @@ namespace ChatController notifyIcon.BalloonTipClosed += (sender, args) => { - // TODO: wird beim ausblenden bzw. automatischem Schließen des "Balloons" ausgelöst + // Wird beim ausblenden bzw. automatischem Schließen des "Balloons" ausgelöst DisposeAndRemoveNotification((NotifyIcon)sender, pGroupId); }; @@ -386,94 +382,75 @@ namespace ChatController private void SelectContact(Contact contact) { - try + if(contact is null) { - if(contact is null) + return; + } + + ChatMessageFileWrapper = null; + + ShouldInterruptContactsThread = true; + + StartWaitingImmediately(); + + _ScrollPrueferAktivieren = false; + + if(contact.HasUnreadMessages) + { + contact.HasUnreadMessages = false; + + Clientlist.Items.Refresh(); + OnPropertyChanged(nameof(ContactList)); + } + + var currentContact = contact; + contact.IsNewMessage = false; + + var shouldChangeIcon = _ContactList.Any(contactDependencyObject => contactDependencyObject.Contact.IsNewMessage); + if(shouldChangeIcon) + { + ContainingWindow.Icon = Utils.ConvertIconToImageSource(Resource.ownchat_favicon); + } + + CurrentContact = currentContact; + + OnPropertyChanged(nameof(IsSendButtonEnabled)); + + foreach(ContactDependencyObject item in Clientlist.Items) + { + if(item.Contact.Equals(contact)) { - return; + Clientlist.SelectedItem = item; } + } - ChatMessageFileWrapper = null; + _ChatMessages.Clear(); + OnPropertyChanged(nameof(_ChatMessages)); - ShouldInterruptContactsThread = true; - - StartWaitingImmediately(); - - _ScrollPrueferAktivieren = false; - - if(contact.HasUnreadMessages) + Chat.LoadChatMessagesForContactAsync(currentContact, GetFirstMessage(), chatMessages => + { + this.Dispatch(() => { - contact.HasUnreadMessages = false; + _ChatMessages.Clear(); + _ChatMessages.AddRangeIfElementsNotIn(chatMessages); + OnPropertyChanged(nameof(_ChatMessages)); - Clientlist.Items.Refresh(); - OnPropertyChanged(nameof(ContactList)); - } + WpfUtils.ScrollToBottomOfListBox(ChatListBox); - var currentContact = contact; - contact.IsNewMessage = false; + ChatListBox.ContextMenu = Chat.ErstelleKontextMenue(); + SetContextHandler(); + _ScrollPrueferAktivieren = true; - var shouldChangeIcon = _ContactList.Any(contactDependencyObject => contactDependencyObject.Contact.IsNewMessage); - if(shouldChangeIcon) - { - ContainingWindow.Icon = Utils.ConvertIconToImageSource(Resource.ownchat_favicon); - } + ListenForMessages(); + Cursor = Cursors.Arrow; - CurrentContact = currentContact; + WriteToNewSyncFile(); - OnPropertyChanged(nameof(IsSendButtonEnabled)); + ShouldInterruptContactsThread = false; - foreach(ContactDependencyObject item in Clientlist.Items) - { - if(item.Contact.Equals(contact)) - { - Clientlist.SelectedItem = item; - } - } - - _ChatMessages.Clear(); - OnPropertyChanged(nameof(_ChatMessages)); - - Chat.LoadChatMessagesForContactAsync(currentContact, GetFirstMessage(), chatMessages => - { - this.Dispatch(() => - { - _ChatMessages.Clear(); - _ChatMessages.AddRangeIfElementsNotIn(chatMessages); - OnPropertyChanged(nameof(_ChatMessages)); - - WpfUtils.ScrollToBottomOfListBox(ChatListBox); - - ChatListBox.ContextMenu = Chat.ErstelleKontextMenue(); - SetContextHandler(); - _ScrollPrueferAktivieren = true; - - ListenForMessages(); - Cursor = Cursors.Arrow; - - WriteToNewSyncFile(); - - ShouldInterruptContactsThread = false; - - EndWaiting(); - }); + EndWaiting(); }); - } - catch(Exception exception) - { -#if DEBUG - var desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); - - using(var fileStream = new FileStream(Path.Combine(desktop, "ownchat_log.txt"), FileMode.OpenOrCreate)) - { - using(var streamWriter = new StreamWriter(fileStream)) - { - streamWriter.WriteLine(exception.ToString()); - } - } -#endif - - MessageBox.Show(exception.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); - } + }); } private void SetContextHandler() @@ -514,16 +491,18 @@ namespace ChatController } // neu und vor Einfügen setzen und anpassen - if(contextItems.Count > 2) + if(contextItems.Count <= 2) { - var copyMenuItem = (MenuItem) contextItems[2]; - copyMenuItem.Click += CopyOnClick; + return; } + + var copyMenuItem = (MenuItem) contextItems[2]; + copyMenuItem.Click += CopyOnClick; } private void SaveAsOnClick(object sender, RoutedEventArgs routedEventArgs) { - foreach (var items in ChatListBox.SelectedItems) + foreach(var items in ChatListBox.SelectedItems) { var chatMessage = (ChatMessage) items; @@ -658,42 +637,44 @@ namespace ChatController { var pathToOriginalImage = Chat.OpenFile(); - if(File.Exists(pathToOriginalImage)) + if(!File.Exists(pathToOriginalImage)) { - StartWaitingImmediately("Skaliere Bild ..."); - - var scalingTask = new Task(() => - { - try - { - var pathToScaledImage = FileUtils.ScaleImage(pathToOriginalImage, Path.GetExtension(pathToOriginalImage.ToUpperInvariant()), Chat.ChatDaten.MaxUploadSize); - - var isFileSizeTooLarge = FileUtils.CheckFileSize(pathToScaledImage, Chat.ChatDaten.MaxUploadSize); - - if(isFileSizeTooLarge) - { - this.Dispatch(() => - { - EndWaiting(); - MessageBox.Show($"Die ausgewählte Datei ist zu groß. Die maximale Größe beträgt {Chat.ChatDaten.MaxUploadSize / 1000 / 1000} MB", "Senden nicht möglich", MessageBoxButton.OK, MessageBoxImage.Warning); - }); - - return; - } - - if(File.Exists(pathToScaledImage)) - { - ChatMessageFileWrapper = new ChatMessageFileWrapper(pathToOriginalImage, pathToScaledImage, $"{Chat.ChatDaten.ServerUrl}/document.png"); - } - } - finally - { - this.Dispatch(EndWaiting); - } - }); - - scalingTask.Start(); + return; } + + StartWaitingImmediately("Skaliere Bild ..."); + + var scalingTask = new Task(() => + { + try + { + var pathToScaledImage = FileUtils.ScaleImage(pathToOriginalImage, Path.GetExtension(pathToOriginalImage.ToUpperInvariant()), Chat.ChatDaten.MaxUploadSize); + + var isFileSizeTooLarge = FileUtils.CheckFileSize(pathToScaledImage, Chat.ChatDaten.MaxUploadSize); + + if(isFileSizeTooLarge) + { + this.Dispatch(() => + { + EndWaiting(); + MessageBox.Show($"Die ausgewählte Datei ist zu groß. Die maximale Größe beträgt {Chat.ChatDaten.MaxUploadSize / 1000 / 1000} MB", "Senden nicht möglich", MessageBoxButton.OK, MessageBoxImage.Warning); + }); + + return; + } + + if(File.Exists(pathToScaledImage)) + { + ChatMessageFileWrapper = new ChatMessageFileWrapper(pathToOriginalImage, pathToScaledImage, $"{Chat.ChatDaten.ServerUrl}/document.png"); + } + } + finally + { + this.Dispatch(EndWaiting); + } + }); + + scalingTask.Start(); } else { @@ -772,41 +753,36 @@ namespace ChatController private void Chatbox_OnGotFocus(object sender, RoutedEventArgs e) { - if (Chatbox.Text.Equals("Nachricht schreiben")) + if(!Chatbox.Text.Equals("Nachricht schreiben")) { - Chatbox.Text = string.Empty; - Chatbox.Foreground = new SolidColorBrush(Colors.Black); + return; } + + Chatbox.Text = string.Empty; + Chatbox.Foreground = new SolidColorBrush(Colors.Black); } private void Chatbox_OnKeyDownHandler(object sender, KeyEventArgs e) { - try - { - //if (e.Key == Key.Return) - //{ - // if(CurrentContact != null && !string.IsNullOrEmpty(Chatbox.Text)) - // { - // Chat.AddNewMessage(Chatbox.Text, CurrentContact.GroupId); + //if (e.Key == Key.Return) + //{ + // if(CurrentContact != null && !string.IsNullOrEmpty(Chatbox.Text)) + // { + // Chat.AddNewMessage(Chatbox.Text, CurrentContact.GroupId); - // OnPropertyChanged(nameof(CurrentChatMessages)); + // OnPropertyChanged(nameof(CurrentChatMessages)); - // ChatListBox.Items.MoveCurrentToLast(); - // ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); + // ChatListBox.Items.MoveCurrentToLast(); + // ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); - // Chat.SendMessage(Chatbox.Text, CurrentContact.GroupId); + // Chat.SendMessage(Chatbox.Text, CurrentContact.GroupId); - // Chatbox.Text = string.Empty; - // } - //} + // Chatbox.Text = string.Empty; + // } + //} - OnPropertyChanged(nameof(IsBroadcastButtonEnabled)); - OnPropertyChanged(nameof(IsSendButtonEnabled)); - } - catch (Exception ed) - { - MessageBox.Show("Beim Senden einer Nachricht ist ein Fehler aufgetreten. " + ed.Message + "\n" + ed.StackTrace, "Fehler", MessageBoxButton.OK); - } + OnPropertyChanged(nameof(IsBroadcastButtonEnabled)); + OnPropertyChanged(nameof(IsSendButtonEnabled)); } private void Chatbox_OnKeyUpHandler(object sender, KeyEventArgs e) @@ -827,9 +803,9 @@ namespace ChatController private void Chat_OnScrollChanged(object sender, ScrollChangedEventArgs e) { var scrollBarList = Utils.GetVisualChildCollection(ChatListBox); - foreach (var scrollBar in scrollBarList) + foreach(var scrollBar in scrollBarList) { - if (scrollBar.Orientation == Orientation.Horizontal) + if(scrollBar.Orientation == Orientation.Horizontal) { _ScrollPrueferAktivieren = true; } @@ -842,38 +818,44 @@ namespace ChatController private void VerticalScrollbarChanged(object sender, RoutedPropertyChangedEventArgs routedPropertyChangedEventArgs) { - if (_ScrollPrueferAktivieren) + if(!_ScrollPrueferAktivieren) { - var scrollBar = (ScrollBar) sender; + return; + } - if(!(scrollBar.Value > 0)) + var scrollBar = (ScrollBar) sender; + + if(scrollBar.Value > 0) + { + return; + } + + StartWaitingImmediately(); + + _ScrollPrueferAktivieren = false; + + ChatMessages.MoveCurrentToFirst(); + + var currentChatMessage = ChatMessages.CurrentItem; + + if(Clientlist.SelectedItem is null) + { + return; + } + + var selectedContact = ((ContactDependencyObject) Clientlist.SelectedItem).Contact; + + Chat.LoadMoreMessagesAsync(selectedContact, GetFirstMessage(), chatMessages => + { + this.Dispatch(() => { - StartWaitingImmediately(); + EndWaiting(); - _ScrollPrueferAktivieren = false; + _ChatMessages.AddRangeIfElementsNotIn(chatMessages); - ChatMessages.MoveCurrentToFirst(); - - var currentChatMessage = ChatMessages.CurrentItem; - - if(!(Clientlist.SelectedItem is null)) - { - var selectedContact = ((ContactDependencyObject) Clientlist.SelectedItem).Contact; - - Chat.LoadMoreMessagesAsync(selectedContact, GetFirstMessage(), chatMessages => - { - this.Dispatch(() => - { - EndWaiting(); - - _ChatMessages.AddRangeIfElementsNotIn(chatMessages); - - ChatListBox.ScrollIntoView(currentChatMessage); - }); - }); - } - } - } + ChatListBox.ScrollIntoView(currentChatMessage); + }); + }); } private void ListenForMessages() @@ -906,74 +888,70 @@ namespace ChatController this.Dispatch(() => { - try + foreach (var contactDependencyObject in _ContactList) { - foreach (var contactDependencyObject in _ContactList) + foreach (var newContact in updatedContacts) { - foreach (var newContact in updatedContacts) + if(contactDependencyObject.Contact.GroupId != newContact.GroupId) { - if (contactDependencyObject.Contact.GroupId == newContact.GroupId) - { - // ReceivedMessage kann null sein! - if (!(contactDependencyObject.Contact.ReceivedMessage is null) && !contactDependencyObject.Contact.ReceivedMessage.Id.Equals(newContact.ReceivedMessage?.Id)) - { - contactDependencyObject.Contact.ReceivedMessage = newContact.ReceivedMessage; - contactDependencyObject.Contact.TimeStamp = newContact.TimeStamp; - - Contact selectedContact = null; - - if(Clientlist.SelectedItem is ContactDependencyObject selectedContactDependencyObject) - { - selectedContact = selectedContactDependencyObject.Contact; - } - - // Angemeldeter Benutzer - var userOid = Chat.ChatDaten.LoggedInUser.Response.User.Oid; - - var senderId = contactDependencyObject.Contact.ReceivedMessage?.UserId; - var receiverId = userOid; - var receiverGroupId = newContact.GroupId; - var selectedGroupId = selectedContact?.GroupId; - - if (senderId != receiverId && (_IsInBackground || receiverGroupId != selectedGroupId)) - { - if (!(ContainingWindow is null)) - { - ContainingWindow.Icon = Utils.ConvertIconToImageSource(Resource.oC_favico_NewMessage); - } - - ShowNotification(newContact.Name, newContact.ReceivedMessage, newContact.GroupId); - } - - // Wenn der momentan ausgewählte Kontakt der aktuelle Kontakt in der Schleife ist, werden die Nachrichten nicht als ungelesen angezeigt, sonst schon. - if (!(CurrentContact is null) && newContact.GroupId == CurrentContact.GroupId) - { - contactDependencyObject.Contact.HasUnreadMessages = false; - } - else - { - contactDependencyObject.Contact.HasUnreadMessages = true; - contactDependencyObject.Contact.IsNewMessage = true; - } - } - } + continue; } - if (!updatedContacts.Contains(contactDependencyObject.Contact)) + // ReceivedMessage kann null sein! + if(contactDependencyObject.Contact.ReceivedMessage is null || contactDependencyObject.Contact.ReceivedMessage.Id.Equals(newContact.ReceivedMessage?.Id)) { - _ContactList.ToList().Remove(contactDependencyObject); + continue; + } + + contactDependencyObject.Contact.ReceivedMessage = newContact.ReceivedMessage; + contactDependencyObject.Contact.TimeStamp = newContact.TimeStamp; + + Contact selectedContact = null; + + if(Clientlist.SelectedItem is ContactDependencyObject selectedContactDependencyObject) + { + selectedContact = selectedContactDependencyObject.Contact; + } + + // Angemeldeter Benutzer + var userOid = Chat.ChatDaten.LoggedInUser.Response.User.Oid; + + var senderId = contactDependencyObject.Contact.ReceivedMessage?.UserId; + var receiverId = userOid; + var receiverGroupId = newContact.GroupId; + var selectedGroupId = selectedContact?.GroupId; + + if(senderId != receiverId && (_IsInBackground || receiverGroupId != selectedGroupId)) + { + if(!(ContainingWindow is null)) + { + ContainingWindow.Icon = Utils.ConvertIconToImageSource(Resource.oC_favico_NewMessage); + } + + ShowNotification(newContact.Name, newContact.ReceivedMessage, newContact.GroupId); + } + + // Wenn der momentan ausgewählte Kontakt der aktuelle Kontakt in der Schleife ist, werden die Nachrichten nicht als ungelesen angezeigt, sonst schon. + if(!(CurrentContact is null) && newContact.GroupId == CurrentContact.GroupId) + { + contactDependencyObject.Contact.HasUnreadMessages = false; + } + else + { + contactDependencyObject.Contact.HasUnreadMessages = true; + contactDependencyObject.Contact.IsNewMessage = true; } } - ContactList.Sort((x, y) => DateTime.Compare(y.Contact.TimeStamp, x.Contact.TimeStamp)); - OnPropertyChanged(nameof(ChatMessages)); - OnPropertyChanged(nameof(ContactList)); - } - catch(Exception exception) - { - Console.WriteLine(exception); - throw; + if(!updatedContacts.Contains(contactDependencyObject.Contact)) + { + _ContactList.ToList().Remove(contactDependencyObject); + } } + + ContactList.Sort((x, y) => DateTime.Compare(y.Contact.TimeStamp, x.Contact.TimeStamp)); + OnPropertyChanged(nameof(ChatMessages)); + OnPropertyChanged(nameof(ContactList)); }); }); } @@ -1025,7 +1003,7 @@ namespace ChatController private bool UserFilter(object item) { - if (string.IsNullOrEmpty(Suche.Text)) + if(string.IsNullOrEmpty(Suche.Text)) { return true; } @@ -1040,44 +1018,48 @@ namespace ChatController private void Chat_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { - if(ChatListBox.SelectedItems.Count > 0) + if(ChatListBox.SelectedItems.Count <= 0) { - var selectedItem = ChatListBox.SelectedItems[0]; + return; + } - if(selectedItem is ChatMessage selectedMessage) + var selectedItem = ChatListBox.SelectedItems[0]; + + if(!(selectedItem is ChatMessage selectedMessage)) + { + return; + } + + if(!string.IsNullOrEmpty(selectedMessage.OriginalImage)) + { + var uri = new Uri(selectedMessage.OriginalImage); + + if(uri.IsFile) { - if(!string.IsNullOrEmpty(selectedMessage.OriginalImage)) - { - var uri = new Uri(selectedMessage.OriginalImage); + var bitmapImage = new BitmapImage(uri); + bitmapImage.Freeze(); - if(uri.IsFile) - { - var bitmapImage = new BitmapImage(uri); - bitmapImage.Freeze(); + Chat.ShowPictureWindow(bitmapImage, "Test"); - Chat.ShowPictureWindow(bitmapImage, "Test"); - - return; - } - - StartWaitingImmediately(); - - Chat.ShowPicture(selectedMessage.OriginalImage, CurrentContact.GroupId, (imageSource, windowTitle) => - { - this.Dispatch(() => - { - EndWaiting(); - Chat.ShowPictureWindow(imageSource, windowTitle); - }); - }); - } - else if(!(selectedMessage.FilePath is null)) - { - StartWaitingImmediately(); - - LoadDocumentAsync(selectedMessage.FilePath, Path.GetFileName(selectedMessage.FilePath), EndWaiting); - } + return; } + + StartWaitingImmediately(); + + Chat.ShowPicture(selectedMessage.OriginalImage, CurrentContact.GroupId, (imageSource, windowTitle) => + { + this.Dispatch(() => + { + EndWaiting(); + Chat.ShowPictureWindow(imageSource, windowTitle); + }); + }); + } + else if(!(selectedMessage.FilePath is null)) + { + StartWaitingImmediately(); + + LoadDocumentAsync(selectedMessage.FilePath, Path.GetFileName(selectedMessage.FilePath), EndWaiting); } } @@ -1111,11 +1093,10 @@ namespace ChatController callback?.Invoke(); } } - catch(Exception exception) + finally { EndWaiting(); - MessageBox.Show(exception.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); } } @@ -1128,14 +1109,16 @@ namespace ChatController public void StartWaitingImmediately(string dialogText = null) { - if (_WaitLayer is null) + if(!(_WaitLayer is null)) { - _WaitLayer = new ChatControlWaitLayer(dialogText); - Grid.SetRowSpan(_WaitLayer, 3); - RootGrid.Children.Add(_WaitLayer); - Panel.SetZIndex(_WaitLayer, int.MaxValue); - _WaitLayer.RefreshChatUI(); + return; } + + _WaitLayer = new ChatControlWaitLayer(dialogText); + Grid.SetRowSpan(_WaitLayer, 3); + RootGrid.Children.Add(_WaitLayer); + Panel.SetZIndex(_WaitLayer, int.MaxValue); + _WaitLayer.RefreshChatUI(); } public void EndWaiting() @@ -1144,11 +1127,13 @@ namespace ChatController DispatcherPriority.Background, (Action) delegate { - if(!(_WaitLayer is null)) + if(_WaitLayer is null) { - RootGrid.Children.Remove(_WaitLayer); - _WaitLayer = null; + return; } + + RootGrid.Children.Remove(_WaitLayer); + _WaitLayer = null; }); } @@ -1197,10 +1182,9 @@ namespace ChatController }); }); } - catch (Exception e) + finally { EndWaiting(); - MessageBox.Show("Ein Fehler bei der Synchronisation ist aufgetreten.\nFehler:\n" + e.Message, "Fehler", MessageBoxButton.OK); } } @@ -1209,7 +1193,7 @@ namespace ChatController { try { - if (File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name))) + if(File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name))) { File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name), FileAttributes.Normal); File.Delete(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name)); @@ -1305,16 +1289,18 @@ namespace ChatController // Wird im BeWoPlaner benutzt public void ResetNumberOfUnreadMessages(Dictionary pGroupId2DateTime) { - if(!(pGroupId2DateTime is null)) + if(pGroupId2DateTime is null) { - foreach(var contactDependencyObject in _ContactList) + return; + } + + foreach(var contactDependencyObject in _ContactList) + { + foreach(var groupId2DateTime in pGroupId2DateTime) { - foreach(var groupId2DateTime in pGroupId2DateTime) + if(contactDependencyObject.Contact.GroupId == groupId2DateTime.Key) { - if(contactDependencyObject.Contact.GroupId == groupId2DateTime.Key) - { - contactDependencyObject.Contact.HasUnreadMessages = false; - } + contactDependencyObject.Contact.HasUnreadMessages = false; } } } @@ -1351,16 +1337,16 @@ namespace ChatController public void DeleteTempFiles() { - foreach (var file in _CreatedTempFiles) + foreach(var file in _CreatedTempFiles) { try { - if (File.Exists(file)) + if(File.Exists(file)) { File.Delete(file); } } - catch (Exception) + catch(Exception) { //ignore okeee } @@ -1449,15 +1435,15 @@ namespace ChatController private CancellationTokenSource _CancellationTokenSource; - private string _DefaultBroadcastInfoText = "Sie befinden Sich im Stapel-Modus. In diesem Modus können Sie eine Nachricht in einem Schritt an mehrere Empfänger & Gruppen senden. Bitte setzen Sie dazu in der Kontaktliste bei den gewünschten Empfängern & Gruppen ein Häkchen und schreiben Sie Ihre Nachricht wie gewohnt. Wenn Sie auf senden klicken, wird die Nachricht an alle ausgewählten Empfänger & Gruppen gesendet."; + private const string DefaultBroadcastInfoText = "Sie befinden Sich im Stapel-Modus. In diesem Modus können Sie eine Nachricht in einem Schritt an mehrere Empfänger & Gruppen senden. Bitte setzen Sie dazu in der Kontaktliste bei den gewünschten Empfängern & Gruppen ein Häkchen und schreiben Sie Ihre Nachricht wie gewohnt. Wenn Sie auf senden klicken, wird die Nachricht an alle ausgewählten Empfänger & Gruppen gesendet."; private string _BroadcastInfoText; public string BroadcastInfoText { - get => _BroadcastInfoText ?? (_BroadcastInfoText = _DefaultBroadcastInfoText); + get => _BroadcastInfoText ?? (_BroadcastInfoText = DefaultBroadcastInfoText); set { - _BroadcastInfoText = $"{_DefaultBroadcastInfoText}{Environment.NewLine}{value}"; + _BroadcastInfoText = $"{DefaultBroadcastInfoText}{Environment.NewLine}{value}"; OnPropertyChanged(BroadcastInfoText); } } @@ -1497,7 +1483,7 @@ namespace ChatController DeselectAllContacts(); - if (Chat.IsInBroadcastMode) + if(Chat.IsInBroadcastMode) { _CancellationTokenSource = new CancellationTokenSource(); _PreviousContact = CurrentContact; @@ -1598,18 +1584,20 @@ namespace ChatController private void SelectAllContacts_OnClick(object sender, RoutedEventArgs e) { - if(sender is CheckBox checkBox) + if(!(sender is CheckBox checkBox)) { - var isChecked = checkBox.IsChecked ?? false; - - foreach (var contactDependencyObject in ContactList) - { - contactDependencyObject.SetValue(ListItemHelper.IsCheckedProperty, isChecked); - } - - OnPropertyChanged(nameof(ContactList)); - OnPropertyChanged(nameof(IsBroadcastButtonEnabled)); + return; } + + var isChecked = checkBox.IsChecked ?? false; + + foreach(var contactDependencyObject in ContactList) + { + contactDependencyObject.SetValue(ListItemHelper.IsCheckedProperty, isChecked); + } + + OnPropertyChanged(nameof(ContactList)); + OnPropertyChanged(nameof(IsBroadcastButtonEnabled)); } private void SendBroatcastButton_OnClick(object sender, RoutedEventArgs e) @@ -1626,42 +1614,46 @@ namespace ChatController private void AddMediaFileToBroadcastMessage_OnClick(object sender, RoutedEventArgs e) { - if(Chat.IsInBroadcastMode) + if(!Chat.IsInBroadcastMode) { - var originalFilePath = Chat.OpenFile(); - - if(File.Exists(originalFilePath)) - { - StartWaitingImmediately("Skaliere Bild ..."); - - var scalingTask = new Task(() => - { - try - { - var scaledImagePath = FileUtils.ScaleImage(originalFilePath, Path.GetExtension(originalFilePath.ToUpperInvariant()), Chat.ChatDaten.MaxUploadSize); - - var isFileSizeTooLarge = FileUtils.CheckFileSize(scaledImagePath, Chat.ChatDaten.MaxUploadSize); - - if(isFileSizeTooLarge) - { - MessageBox.Show($"Die ausgewählte Datei ist zu groß. Die maximale Größe beträgt {Chat.ChatDaten.MaxUploadSize / 1000 / 1000} MB", "Senden nicht möglich", MessageBoxButton.OK, MessageBoxImage.Warning); - return; - } - - if(File.Exists(scaledImagePath)) - { - BroadcastMessageFileWrapper = new ChatMessageFileWrapper(originalFilePath, scaledImagePath, $"{Chat.ChatDaten.ServerUrl}/document.png"); - } - } - finally - { - this.Dispatch(EndWaiting); - } - }); - - scalingTask.Start(); - } + return; } + + var originalFilePath = Chat.OpenFile(); + + if(!File.Exists(originalFilePath)) + { + return; + } + + StartWaitingImmediately("Skaliere Bild ..."); + + var scalingTask = new Task(() => + { + try + { + var scaledImagePath = FileUtils.ScaleImage(originalFilePath, Path.GetExtension(originalFilePath.ToUpperInvariant()), Chat.ChatDaten.MaxUploadSize); + + var isFileSizeTooLarge = FileUtils.CheckFileSize(scaledImagePath, Chat.ChatDaten.MaxUploadSize); + + if(isFileSizeTooLarge) + { + MessageBox.Show($"Die ausgewählte Datei ist zu groß. Die maximale Größe beträgt {Chat.ChatDaten.MaxUploadSize / 1000 / 1000} MB", "Senden nicht möglich", MessageBoxButton.OK, MessageBoxImage.Warning); + return; + } + + if(File.Exists(scaledImagePath)) + { + BroadcastMessageFileWrapper = new ChatMessageFileWrapper(originalFilePath, scaledImagePath, $"{Chat.ChatDaten.ServerUrl}/document.png"); + } + } + finally + { + this.Dispatch(EndWaiting); + } + }); + + scalingTask.Start(); } private void CloseBroadcastMode() @@ -1741,7 +1733,7 @@ namespace ChatController private void DeselectAllContacts() { - foreach (var contactDependencyObject in ContactList) + foreach(var contactDependencyObject in ContactList) { contactDependencyObject.SetValue(ListItemHelper.IsCheckedProperty, false); } diff --git a/ChatController/ExceptionViewControl.xaml b/ChatController/ExceptionViewControl.xaml new file mode 100644 index 0000000..f0290a4 --- /dev/null +++ b/ChatController/ExceptionViewControl.xaml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + Fehlerdetails: + + + + + diff --git a/ChatController/ExceptionViewControl.xaml.cs b/ChatController/ExceptionViewControl.xaml.cs new file mode 100644 index 0000000..e4b746d --- /dev/null +++ b/ChatController/ExceptionViewControl.xaml.cs @@ -0,0 +1,46 @@ +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Windows; + +namespace ChatController +{ + public partial class ExceptionViewControl : INotifyPropertyChanged + { + public event EventHandler OkButtonClicked; + + private Exception _Exception; + public Exception Exception + { + get => _Exception; + set + { + _Exception = value; + OnPropertyChanged(); + } + } + + public ExceptionViewControl() + { + InitializeComponent(); + DataContext = this; + } + + public event PropertyChangedEventHandler PropertyChanged; + + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private void OkButton_OnClick(object sender, RoutedEventArgs args) + { + OkButtonClicked?.Invoke(this, args); + } + + private void CopyToClipboardButton_OnClick(object sender, RoutedEventArgs args) + { + Clipboard.SetText(Exception.StackTrace); + } + } +} diff --git a/ChatController/HauptKlassen/Chat.cs b/ChatController/HauptKlassen/Chat.cs index 593e5b8..d19ad3b 100644 --- a/ChatController/HauptKlassen/Chat.cs +++ b/ChatController/HauptKlassen/Chat.cs @@ -73,32 +73,25 @@ namespace ChatController.HauptKlassen private static bool PinPublicKey(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors) { - try - { - if(certificate is null || chain is null) - { - return false; - } - - var chainContainsPk = false; - - foreach(var element in chain.ChainElements) - { - var pk = element.Certificate.GetPublicKeyString(); - if(pk == PubKeyX3 || pk == PubKeyR3 || pk == PubKeyE1) - { - chainContainsPk = true; - } - } - - var subjectAccepted = certificate.Subject.Trim().ToLower().EndsWith(".bewoplaner.de") || certificate.Subject.Trim().ToLower().EndsWith(".ownchat.de"); - - return chainContainsPk && subjectAccepted; - } - catch(Exception) + if(certificate is null || chain is null) { return false; } + + var chainContainsPk = false; + + foreach(var element in chain.ChainElements) + { + var pk = element.Certificate.GetPublicKeyString(); + if(pk == PubKeyX3 || pk == PubKeyR3 || pk == PubKeyE1) + { + chainContainsPk = true; + } + } + + var subjectAccepted = certificate.Subject.Trim().ToLower().EndsWith(".bewoplaner.de") || certificate.Subject.Trim().ToLower().EndsWith(".ownchat.de"); + + return chainContainsPk && subjectAccepted; } private const string PubKeyX3 = "3082010A02820101009CD30CF05AE52E47B7725D3783B3686330EAD735261925E1BDBE35F170922FB7B84B4105ABA99E350858ECB12AC468870BA3E375E4E6F3A76271BA7981601FD7919A9FF3D0786771C8690E9591CFFEE699E9603C48CC7ECA4D7712249D471B5AEBB9EC1E37001C9CAC7BA705EACE4AEBBD41E53698B9CBFD6D3C9668DF232A42900C867467C87FA59AB8526114133F65E98287CBDBFA0E56F68689F3853F9786AFB0DC1AEF6B0D95167DC42BA065B299043675806BAC4AF31B9049782FA2964F2A20252904C674C0D031CD8F31389516BAA833B843F1B11FC3307FA27931133D2D36F8E3FCF2336AB93931C5AFC48D0D1D641633AAFA8429B6D40BC0D87DC3930203010001"; @@ -134,37 +127,30 @@ namespace ChatController.HauptKlassen private void LoadMessagesFromServerAsync(long groupId, Action callback) { - try + var url = $"{ChatDaten.ServerUrl}{Constants.LoadMessagesForGroupUrl}{groupId}"; + + var client = new RestClient(url); + var request = new RestRequest(); + + request.AddHeader(Constants.Token, ChatDaten.AuthToken); + request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); + + client.ExecuteAsync(request, response => { - var url = $"{ChatDaten.ServerUrl}{Constants.LoadMessagesForGroupUrl}{groupId}"; + _UserMessages = JsonConvert.DeserializeObject(response.Content); - var client = new RestClient(url); - var request = new RestRequest(); - - request.AddHeader(Constants.Token, ChatDaten.AuthToken); - request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); - - client.ExecuteAsync(request, response => + if(_UserMessages?.Response?.HasMorePages ?? false) { - _UserMessages = JsonConvert.DeserializeObject(response.Content); - - if (_UserMessages?.Response?.HasMorePages ?? false) - { - _NextPage = _UserMessages.Response.NextPage; - _HasNextPage = true; - } - else - { - _HasNextPage = false; - } + _NextPage = _UserMessages.Response.NextPage; + _HasNextPage = true; + } + else + { + _HasNextPage = false; + } - callback?.Invoke(); - }); - } - catch (Exception exception) - { - ThreadExceptionCallback?.Invoke(exception); - } + callback?.Invoke(); + }); } public void LoadMoreMessagesAsync(Contact contact, ChatMessage previousMessage, Action> callback) @@ -177,43 +163,36 @@ namespace ChatController.HauptKlassen private void LoadMoreMessagesFromServerAsync(long groupId, string page, Action callback) { - try + if(page is null || !page.Contains("=")) { - if(page is null || !page.Contains("=")) + callback?.Invoke(); + return; + } + + var pageParam = page.Split('=')[1]; + + var url = $"{ChatDaten.ServerUrl}/api/chat/messages?groupid={groupId}&page={pageParam}"; + + var client = new RestClient(url); + var request = new RestRequest(); + + request.AddHeader(Constants.Token, ChatDaten.AuthToken); + request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); + + client.ExecuteAsync(request, response => + { + _AdditionalUserMessages = null; + _AdditionalUserMessages = JsonConvert.DeserializeObject(response.Content); + + if(_AdditionalUserMessages?.Response?.HasMorePages ?? false) { - callback?.Invoke(); - return; + _NextPage = _AdditionalUserMessages.Response.NextPage; } - var pageParam = page.Split('=')[1]; + _HasNextPage = _AdditionalUserMessages?.Response?.HasMorePages ?? false; - var url = $"{ChatDaten.ServerUrl}/api/chat/messages?groupid={groupId}&page={pageParam}"; - - var client = new RestClient(url); - var request = new RestRequest(); - - request.AddHeader(Constants.Token, ChatDaten.AuthToken); - request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); - - client.ExecuteAsync(request, response => - { - _AdditionalUserMessages = null; - _AdditionalUserMessages = JsonConvert.DeserializeObject(response.Content); - - if (_AdditionalUserMessages?.Response?.HasMorePages ?? false) - { - _NextPage = _AdditionalUserMessages.Response.NextPage; - } - - _HasNextPage = _AdditionalUserMessages?.Response?.HasMorePages ?? false; - - callback?.Invoke(); - }); - } - catch(Exception exception) - { - ExceptionCallback?.Invoke(exception); - } + callback?.Invoke(); + }); } private double _FormerMessagesCount; @@ -223,7 +202,7 @@ namespace ChatController.HauptKlassen var span = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var timespan = Convert.ToInt64(span.TotalSeconds); - if (!(_UserMessages is null) && _UserMessages.Response.Messages.Length > 0) + if(!(_UserMessages is null) && _UserMessages.Response.Messages.Length > 0) { timespan = _UserMessages.Response.Messages.First().Created_At; } @@ -259,8 +238,8 @@ namespace ChatController.HauptKlassen } catch(Exception exception) { - ExceptionCallback?.Invoke(exception); callback?.Invoke(0d); + throw exception; } } @@ -279,184 +258,125 @@ namespace ChatController.HauptKlassen private void LoadNumberOfNewMessagesFromServerAsync(long groupId, Action callback) { - try + var url = $"{ChatDaten.ServerUrl}{Constants.LoadOwnChatNewsUrl}{groupId}/{LastTimeStamp}"; + + var client = new RestClient(url); + var request = new RestRequest(); + + request.AddHeader(Constants.Token, ChatDaten.AuthToken); + request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); + + client.ExecuteAsync(request, response => { - var url = $"{ChatDaten.ServerUrl}{Constants.LoadOwnChatNewsUrl}{groupId}/{LastTimeStamp}"; + var messageCounter = JsonConvert.DeserializeObject(response.Content); - var client = new RestClient(url); - var request = new RestRequest(); - - request.AddHeader(Constants.Token, ChatDaten.AuthToken); - request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); - - client.ExecuteAsync(request, response => - { - var messageCounter = JsonConvert.DeserializeObject(response.Content); - - callback?.Invoke(messageCounter?.MessageCount ?? 0); - }); - } - catch(Exception exception) - { - ThreadExceptionCallback?.Invoke(exception); - } + callback?.Invoke(messageCounter?.MessageCount ?? 0); + }); } private void LoadGroupsAsync(Action callback) { - try + var url = $"{ChatDaten.ServerUrl}{Constants.GetChatGroupsUrl}"; + + var client = new RestClient(url); + var request = new RestRequest(); + + request.AddHeader(Constants.Token, ChatDaten.AuthToken); + request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); + + client.ExecuteAsync(request, response => { - var url = $"{ChatDaten.ServerUrl}{Constants.GetChatGroupsUrl}"; + var contacts = JsonConvert.DeserializeObject(response.Content); - var client = new RestClient(url); - var request = new RestRequest(); - - request.AddHeader(Constants.Token, ChatDaten.AuthToken); - request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); - - client.ExecuteAsync(request, response => - { - var contacts = JsonConvert.DeserializeObject(response.Content); - - callback?.Invoke(contacts); - }); - } - catch(Exception exception) - { - ExceptionCallback?.Invoke(exception); - } + callback?.Invoke(contacts); + }); } public void UpdateContactList(Action> callback) { - try + LoadGroupsAsync(rawData => { - LoadGroupsAsync(rawData => - { - var contacts = GenerateContactsFromServerResponse(rawData.Response.Groups.ToArray(), true); + var contacts = GenerateContactsFromServerResponse(rawData.Response.Groups.ToArray(), true); - callback?.Invoke(contacts.OrderByDescending(c => c.TimeStamp)); - }); - } - catch(Exception exception) - { - ExceptionCallback?.Invoke(exception); - } + callback?.Invoke(contacts.OrderByDescending(c => c.TimeStamp)); + }); } public List AddNewMessage(string pMessage, long pGroupId, ChatMessage previousMessage) { - var result = new List(); + var time = DateTime.Now; - try - { - var time = DateTime.Now; + var chatMessage = new ChatMessage(pGroupId, 0, ChatDaten.LoggedInUser.Response.User.UserName, pMessage, time, true, 0, null, null, null, null, null, ChatMessageType.Message, ChatDaten.LoggedInUser.Response.User.Oid); - var chatMessage = new ChatMessage(pGroupId, 0, ChatDaten.LoggedInUser.Response.User.UserName, pMessage, time, true, 0, null, null, null, null, null, ChatMessageType.Message, ChatDaten.LoggedInUser.Response.User.Oid); - - result = AddSeparators(new List {previousMessage, chatMessage}); - - result.Remove(previousMessage); - - return result; - } - catch (Exception exception) - { - ExceptionCallback?.Invoke(exception); - } + var result = AddSeparators(new List {previousMessage, chatMessage}); + result.Remove(previousMessage); + return result; } public async Task SendMessage(string message, long groupId) { - try + var endurl = ChatDaten.ServerUrl + Constants.SendMessageUrl; + + using (var multiPartContent = new MultipartFormDataContent()) { - var endurl = ChatDaten.ServerUrl + Constants.SendMessageUrl; + multiPartContent.Add(new StringContent(groupId.ToString()), "groupid"); + multiPartContent.Add(new StringContent(message), "text"); + + var requestUri = new Uri(endurl); - using (var multiPartContent = new MultipartFormDataContent()) - { - multiPartContent.Add(new StringContent(groupId.ToString()), "groupid"); - multiPartContent.Add(new StringContent(message), "text"); - - var requestUri = new Uri(endurl); + var httpRequest = new HttpRequestMessage {Method = HttpMethod.Post, RequestUri = requestUri, Content = multiPartContent}; - var httpRequest = new HttpRequestMessage {Method = HttpMethod.Post, RequestUri = requestUri, Content = multiPartContent}; + httpRequest.Headers.Add("Token", ChatDaten.AuthToken); + httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer); - httpRequest.Headers.Add("Token", ChatDaten.AuthToken); - httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer); - - var httpClient = new HttpClient(); - await httpClient.SendAsync(httpRequest, CancellationToken.None); - } - } - catch (Exception exception) - { - ExceptionCallback?.Invoke(exception); + var httpClient = new HttpClient(); + await httpClient.SendAsync(httpRequest, CancellationToken.None); } } public string OpenFile() { - try + var openFileDialog = new OpenFileDialog { - var openFileDialog = new OpenFileDialog - { - Filter = Resource.OpenFileDialogFilter_Test - }; + Filter = Resource.OpenFileDialogFilter_Test + }; - var result = openFileDialog.ShowDialog(); - - return result == DialogResult.OK ? openFileDialog.FileName : null; - } - catch (Exception exception) - { - ExceptionCallback?.Invoke(exception); - return null; - } + var result = openFileDialog.ShowDialog(); + + return result == DialogResult.OK ? openFileDialog.FileName : null; } public List AddNewFile(string pathToScaledFile, string originalFilePath, long groupId, ChatMessage previousMessage, string chatBoxText) { var result = new List(); - try + if(string.IsNullOrEmpty(pathToScaledFile) || string.IsNullOrEmpty(originalFilePath)) { - if(string.IsNullOrEmpty(pathToScaledFile) || string.IsNullOrEmpty(originalFilePath)) - { - return result; - } - - var messageId = 0; - var userName = ChatDaten.LoggedInUser.Response.User.UserName; - var sendTime = DateTime.Now; - var fileName = Path.GetFileName(pathToScaledFile); - var imageFile = GetImageFile(pathToScaledFile, out var fileSize); - var isImage = Constants.ImageFileExtensions.Contains(Path.GetExtension(pathToScaledFile).ToUpperInvariant()); - var messageText = string.IsNullOrWhiteSpace(chatBoxText) ? fileName : chatBoxText; - var filePath = isImage ? null : pathToScaledFile; - var originalImage = isImage ? pathToScaledFile : null; - var imageName = isImage ? fileName : null; - var linkToThumbnail = isImage ? null : $"{ChatDaten.ServerUrl}/document.png"; - var logo = isImage ? imageFile : null; - var chatMessageType = isImage ? ChatMessageType.Image : ChatMessageType.Document; - var senderId = ChatDaten.LoggedInUser.Response.User.Oid; - - var chatMessage = new ChatMessage(groupId, messageId, userName, messageText, sendTime, true, fileSize, filePath, originalImage, imageName, linkToThumbnail, logo, chatMessageType, senderId); - - result = AddSeparators(new List { previousMessage, chatMessage }); - - result.Remove(previousMessage); - return result; } - catch(Exception exception) - { - if(!(exception is IOException)) - { - ExceptionCallback?.Invoke(exception); - } - } + + var messageId = 0; + var userName = ChatDaten.LoggedInUser.Response.User.UserName; + var sendTime = DateTime.Now; + var fileName = Path.GetFileName(pathToScaledFile); + var imageFile = GetImageFile(pathToScaledFile, out var fileSize); + var isImage = Constants.ImageFileExtensions.Contains(Path.GetExtension(pathToScaledFile).ToUpperInvariant()); + var messageText = string.IsNullOrWhiteSpace(chatBoxText) ? fileName : chatBoxText; + var filePath = isImage ? null : pathToScaledFile; + var originalImage = isImage ? pathToScaledFile : null; + var imageName = isImage ? fileName : null; + var linkToThumbnail = isImage ? null : $"{ChatDaten.ServerUrl}/document.png"; + var logo = isImage ? imageFile : null; + var chatMessageType = isImage ? ChatMessageType.Image : ChatMessageType.Document; + var senderId = ChatDaten.LoggedInUser.Response.User.Oid; + + var chatMessage = new ChatMessage(groupId, messageId, userName, messageText, sendTime, true, fileSize, filePath, originalImage, imageName, linkToThumbnail, logo, chatMessageType, senderId); + + result = AddSeparators(new List { previousMessage, chatMessage }); + + result.Remove(previousMessage); return result; } @@ -533,7 +453,7 @@ namespace ChatController.HauptKlassen var sendtime = DateTime.Now; - if (Constants.ImageFileExtensions.Contains(Path.GetExtension(fileName).ToUpperInvariant())) + if(Constants.ImageFileExtensions.Contains(Path.GetExtension(fileName).ToUpperInvariant())) { var bitmapImage = new BitmapImage(); var memoryStream = new MemoryStream(file); @@ -563,14 +483,7 @@ namespace ChatController.HauptKlassen public async Task SendFileToContact(Contact currentContact, string scaledImagePath, string originalFilePath, string message) { - try - { - await SendFile(scaledImagePath, currentContact, originalFilePath, message); - } - catch(Exception exception) - { - ExceptionCallback?.Invoke(exception); - } + await SendFile(scaledImagePath, currentContact, originalFilePath, message); } private async Task SendFile(string pFile, Contact currentContact, string pOriginalFilePath, string message) @@ -659,7 +572,7 @@ namespace ChatController.HauptKlassen public void SaveFileAs(ChatMessage pChatMessage) { - if (!(pChatMessage.PictureSource is null)) + if(!(pChatMessage.PictureSource is null)) { SaveAs(1, Path.GetFileName(pChatMessage.OriginalImage), DownloadMediaFile(pChatMessage.OriginalImage)); } @@ -669,63 +582,47 @@ namespace ChatController.HauptKlassen { byte[] mediaFile = null; - try + using(var webClient = new WebClient()) { - using(var webClient = new WebClient()) - { - webClient.Credentials = CredentialCache.DefaultCredentials; - webClient.Headers[Constants.Token] = ChatDaten.AuthToken; - webClient.Headers[Constants.CustomerId] = ChatDaten.Kundennummer; - mediaFile = webClient.DownloadData(pFilePath); - } + webClient.Credentials = CredentialCache.DefaultCredentials; + webClient.Headers[Constants.Token] = ChatDaten.AuthToken; + webClient.Headers[Constants.CustomerId] = ChatDaten.Kundennummer; + mediaFile = webClient.DownloadData(pFilePath); + } - return mediaFile; - } - catch(Exception exception) - { - ExceptionCallback?.Invoke(exception); - } - return mediaFile; } private void SaveAs(int pFilterType, string pFileName, byte[] pMediaFile) { - try + var saveFileDialog = new SaveFileDialog {FileName = Path.GetFileName(pFileName)}; + + switch(pFilterType) { - var saveFileDialog = new SaveFileDialog {FileName = Path.GetFileName(pFileName)}; - - switch(pFilterType) - { - case 1: - saveFileDialog.Filter = Resource.SaveFileDialogFilter_Images; - saveFileDialog.Title = Resource.SaveFIleDialogTitle_Images; - saveFileDialog.ShowDialog(); - break; - case 2: - saveFileDialog.Filter = Resource.SaveFileDialogFilter_Documents; - saveFileDialog.Title = Resource.SaveFIleDialogTitle_Documents; - saveFileDialog.ShowDialog(); - break; - case 3: - saveFileDialog.Filter = Resource.SaveFileDialogFilter_Audio; - saveFileDialog.Title = Resource.SaveFIleDialogTitle_Audio; - saveFileDialog.ShowDialog(); - break; - } - - if (!string.IsNullOrEmpty(saveFileDialog.FileName)) - { - var fileStream = (FileStream)saveFileDialog.OpenFile(); - - fileStream.Write(pMediaFile, 0, pMediaFile.Length); - - fileStream.Close(); - } + case 1: + saveFileDialog.Filter = Resource.SaveFileDialogFilter_Images; + saveFileDialog.Title = Resource.SaveFIleDialogTitle_Images; + saveFileDialog.ShowDialog(); + break; + case 2: + saveFileDialog.Filter = Resource.SaveFileDialogFilter_Documents; + saveFileDialog.Title = Resource.SaveFIleDialogTitle_Documents; + saveFileDialog.ShowDialog(); + break; + case 3: + saveFileDialog.Filter = Resource.SaveFileDialogFilter_Audio; + saveFileDialog.Title = Resource.SaveFIleDialogTitle_Audio; + saveFileDialog.ShowDialog(); + break; } - catch (Exception exception) + + if (!string.IsNullOrEmpty(saveFileDialog.FileName)) { - ExceptionCallback?.Invoke(exception); + var fileStream = (FileStream)saveFileDialog.OpenFile(); + + fileStream.Write(pMediaFile, 0, pMediaFile.Length); + + fileStream.Close(); } } @@ -740,33 +637,26 @@ namespace ChatController.HauptKlassen if(dataObject.GetDataPresent(DataFormats.FileDrop)) { - try + if(dataObject.GetData(DataFormats.FileDrop) is string[] fileList) { - if(dataObject.GetData(DataFormats.FileDrop) is string[] fileList) + var pathToFile = fileList[0]; + + if(File.Exists(pathToFile)) { - var pathToFile = fileList[0]; + var fileName = Path.GetFileName(pathToFile); + + var mediaFile = File.ReadAllBytes(pathToFile); - if(File.Exists(pathToFile)) - { - var fileName = Path.GetFileName(pathToFile); - - var mediaFile = File.ReadAllBytes(pathToFile); + pChatMainControl.AddMessages(AddFileToMessage(mediaFile, fileName, pGroupOid, pChatMainControl.GetFirstMessage())); + + CollectionViewSource.GetDefaultView(pChatMainControl.ChatListBox.ItemsSource).Refresh(); - pChatMainControl.AddMessages(AddFileToMessage(mediaFile, fileName, pGroupOid, pChatMainControl.GetFirstMessage())); - - CollectionViewSource.GetDefaultView(pChatMainControl.ChatListBox.ItemsSource).Refresh(); + pChatMainControl.ChatListBox.Items.MoveCurrentToLast(); + pChatMainControl.ChatListBox.ScrollIntoView(pChatMainControl.ChatListBox.Items.CurrentItem); - pChatMainControl.ChatListBox.Items.MoveCurrentToLast(); - pChatMainControl.ChatListBox.ScrollIntoView(pChatMainControl.ChatListBox.Items.CurrentItem); - - await SendMediaMessage(fileName, pGroupOid, mediaFile, null); - } + await SendMediaMessage(fileName, pGroupOid, mediaFile, null); } } - catch(Exception exception) - { - ExceptionCallback?.Invoke(exception); - } } else { @@ -825,85 +715,71 @@ namespace ChatController.HauptKlassen public void ShowProfilePicture(Contact currentContact) { - try - { - ShowPictureWindow(currentContact.Image, currentContact.Name); - } - catch (Exception exception) - { - ExceptionCallback?.Invoke(exception); - } + ShowPictureWindow(currentContact.Image, currentContact.Name); } public void ShowPictureWindow(ImageSource imageSource, string title) { - try + var imageWidth = Convert.ToInt32(imageSource.Width); + var imageHeight = Convert.ToInt32(imageSource.Height); + + var imageAspectRatio = imageWidth / (double)imageHeight; + + var primaryScreenWidth2 = SystemParameters.PrimaryScreenWidth; + var primaryScreenHeight2 = SystemParameters.PrimaryScreenHeight; + + var windowMaxWidth = imageWidth; + var windowMaxHeight = imageHeight; + + if(windowMaxWidth > .8 * primaryScreenWidth2 || windowMaxHeight > .8 * primaryScreenHeight2) { - var imageWidth = Convert.ToInt32(imageSource.Width); - var imageHeight = Convert.ToInt32(imageSource.Height); - - var imageAspectRatio = imageWidth / (double)imageHeight; - - var primaryScreenWidth2 = SystemParameters.PrimaryScreenWidth; - var primaryScreenHeight2 = SystemParameters.PrimaryScreenHeight; - - var windowMaxWidth = imageWidth; - var windowMaxHeight = imageHeight; - - if(windowMaxWidth > .8 * primaryScreenWidth2 || windowMaxHeight > .8 * primaryScreenHeight2) + if(primaryScreenWidth2 > primaryScreenHeight2) { - if(primaryScreenWidth2 > primaryScreenHeight2) - { - windowMaxHeight = (int)(.8 * primaryScreenHeight2); - windowMaxWidth = (int)(windowMaxHeight * imageAspectRatio); - } - else - { - windowMaxWidth = (int)(.8 * primaryScreenWidth2); - windowMaxHeight = (int)(windowMaxWidth * imageAspectRatio); - } + windowMaxHeight = (int)(.8 * primaryScreenHeight2); + windowMaxWidth = (int)(windowMaxHeight * imageAspectRatio); } - - var maximumWindowSize = new System.Windows.Size(windowMaxWidth, windowMaxHeight); - - var minHeight = 232 / imageAspectRatio; - var minWidth = 232d; - - var window = new Window + else { - Title = title, - MinHeight = minHeight, - MinWidth = minWidth - }; - - var grid = new Grid - { - Width = maximumWindowSize.Width, - Height = maximumWindowSize.Height, - MinHeight = minHeight, - MinWidth = minWidth - }; - - var image = new System.Windows.Controls.Image - { - Source = imageSource, - Margin = new Thickness(0) - }; - - grid.Children.Clear(); - grid.Children.Add(image); - - window.SizeToContent = SizeToContent.WidthAndHeight; - window.Content = grid; - window.Margin = new Thickness(0); - window.WindowStartupLocation = WindowStartupLocation.CenterScreen; - - window.ShowDialog(); + windowMaxWidth = (int)(.8 * primaryScreenWidth2); + windowMaxHeight = (int)(windowMaxWidth * imageAspectRatio); + } } - catch(Exception exception) + + var maximumWindowSize = new System.Windows.Size(windowMaxWidth, windowMaxHeight); + + var minHeight = 232 / imageAspectRatio; + var minWidth = 232d; + + var window = new Window { - ExceptionCallback?.Invoke(exception); - } + Title = title, + MinHeight = minHeight, + MinWidth = minWidth + }; + + var grid = new Grid + { + Width = maximumWindowSize.Width, + Height = maximumWindowSize.Height, + MinHeight = minHeight, + MinWidth = minWidth + }; + + var image = new System.Windows.Controls.Image + { + Source = imageSource, + Margin = new Thickness(0) + }; + + grid.Children.Clear(); + grid.Children.Add(image); + + window.SizeToContent = SizeToContent.WidthAndHeight; + window.Content = grid; + window.Margin = new Thickness(0); + window.WindowStartupLocation = WindowStartupLocation.CenterScreen; + + window.ShowDialog(); } public void ShowPicture(string originalImage, long groupId, Action downloadCompletedCallback) @@ -913,20 +789,13 @@ namespace ChatController.HauptKlassen return; } - try + Utils.DownloadImageAsync(originalImage, $"group-{groupId}", CacheCategory.MessageAttachment, imageSource => { - Utils.DownloadImageAsync(originalImage, $"group-{groupId}", CacheCategory.MessageAttachment, imageSource => - { - var splitName = originalImage.Split('/'); - var last = splitName.LastOrDefault(); + var splitName = originalImage.Split('/'); + var last = splitName.LastOrDefault(); - downloadCompletedCallback?.Invoke(imageSource, last ?? "Bild"); - }); - } - catch(Exception exception) - { - ExceptionCallback?.Invoke(exception); - } + downloadCompletedCallback?.Invoke(imageSource, last ?? "Bild"); + }); } public void ReloadGroupsAsync(Action callback) @@ -951,22 +820,14 @@ namespace ChatController.HauptKlassen public List UpdateContacts(ChatGruppenDaten chatDaten) { - try + _Contacts.Clear(); + + if(!(chatDaten?.Response is null)) { - _Contacts.Clear(); - - if(!(chatDaten?.Response is null)) - { - _Contacts.AddRange(GenerateContactsFromServerResponse(chatDaten.Response.Groups.ToArray())); - } + _Contacts.AddRange(GenerateContactsFromServerResponse(chatDaten.Response.Groups.ToArray())); + } - return _Contacts; - } - catch(Exception exception) - { - ExceptionCallback?.Invoke(exception); - return null; - } + return _Contacts; } public List GenerateContactsFromServerResponse(GroupInput[] pGroupInputs, bool pShouldUpdateLastTimeStamp = false) @@ -1015,17 +876,16 @@ namespace ChatController.HauptKlassen groupInput.Avatar, key, groupInput.Users.ToDictionary(user => user.Oid, user => user.Picture))); - if(pShouldUpdateLastTimeStamp) + if(!pShouldUpdateLastTimeStamp || latestMessage?.Timestamp?.Date is null) { - if(!(latestMessage?.Timestamp?.Date is null)) - { - var unixTimeStamp = DateTime.Parse(latestMessage.Timestamp.Date).GetUnixTimeStamp(); + continue; + } - if(LastTimeStamp < unixTimeStamp) - { - LastTimeStamp = unixTimeStamp; - } - } + var unixTimeStamp = DateTime.Parse(latestMessage.Timestamp.Date).GetUnixTimeStamp(); + + if(LastTimeStamp < unixTimeStamp) + { + LastTimeStamp = unixTimeStamp; } } @@ -1092,32 +952,25 @@ namespace ChatController.HauptKlassen public void DownloadFileAsync(string uri, string path, Action callback) { - try + var client = new RestClient(uri); + var request = new RestRequest(); + + request.AddHeader(Constants.Token, ChatDaten.AuthToken); + request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); + + client.ExecuteAsync(request, response => { - var client = new RestClient(uri); - var request = new RestRequest(); - - request.AddHeader(Constants.Token, ChatDaten.AuthToken); - request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); - - client.ExecuteAsync(request, response => + if(response.StatusCode == HttpStatusCode.OK) { - if(response.StatusCode == HttpStatusCode.OK) - { - response.RawBytes.SaveAs(path); - } - else - { - throw new Exception("Die Datei konnte nicht heruntergeladen werden."); - } + response.RawBytes.SaveAs(path); + } + else + { + throw new Exception("Die Datei konnte nicht heruntergeladen werden."); + } - callback?.Invoke(); - }); - } - catch (Exception exception) - { - ExceptionCallback?.Invoke(exception); - } + callback?.Invoke(); + }); } private bool _IsInBroadcastMode; diff --git a/ChatController/HauptKlassen/Login.cs b/ChatController/HauptKlassen/Login.cs index 7269e36..bdaf7ce 100644 --- a/ChatController/HauptKlassen/Login.cs +++ b/ChatController/HauptKlassen/Login.cs @@ -83,38 +83,39 @@ namespace ChatController.HauptKlassen // Wird im BeWoPlaner benutzt public ChatDatenUebergabe AnmeldevorgangDurchFuehren() { - if(ServerErmittlung()) + if(!ServerErmittlung()) { - var dic = new Dictionary - { - { "username", _UserName}, - { "password", _Password}, - { "chatcode", _ChatCode} - }; - - VerbindeMitChatServer(dic); - - if(_OwnchatVerbindungsaufbauOk) - { - GetGroups(); - } - - if(_GruppeholenverbindungsaufbauOk) - { - var maxUploadSize = GetMaiximumAllowedFileUploadSize(_AuthToken, _Tenant); - - return new ChatDatenUebergabe(_LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant, _ApiKey, maxUploadSize); - } + return null; } - return null; + var dic = new Dictionary + { + { "username", _UserName}, + { "password", _Password}, + { "chatcode", _ChatCode} + }; + + VerbindeMitChatServer(dic); + + if(_OwnchatVerbindungsaufbauOk) + { + GetGroups(); + } + + if(!_GruppeholenverbindungsaufbauOk) + { + return null; + } + + var maxUploadSize = GetMaiximumAllowedFileUploadSize(_AuthToken, _Tenant); + + return new ChatDatenUebergabe(_LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant, _ApiKey, maxUploadSize); + } public void DoLoginAsync(Action callback, Action exceptionCallback) { - try - { - LookupServerUrlAsync(isConnectedWithServer => + LookupServerUrlAsync(isConnectedWithServer => { if(isConnectedWithServer) { @@ -139,163 +140,114 @@ namespace ChatController.HauptKlassen errorMessage => { exceptionCallback?.Invoke(errorMessage); }); } }, errorMessage => { exceptionCallback?.Invoke(errorMessage); }); - } - catch(Exception) - { - callback?.Invoke(null); - } } public void LookupServerUrlAsync(Action callback, Action exceptionCallback) { - try + if(!string.IsNullOrWhiteSpace(ServerUrl)) { - if(!string.IsNullOrWhiteSpace(ServerUrl)) + callback?.Invoke(false); + return; + } + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + + var client = new RestClient(DictionaryServerUrl); + var request = new RestRequest(_Tenant); + + client.ExecuteAsync(request, response => + { + var lookupResult = JsonConvert.DeserializeObject(response.Content); + + _BaseUrl = lookupResult.Url; + ServerUrl = _BaseUrl; + + var result = false; + + switch(lookupResult.Status) { - callback?.Invoke(false); - return; + case 0: + result = true; + break; + case 1: + exceptionCallback?.Invoke("Fehler: Kundennummer unbekannt.\nBitte überprüfen Sie die Anmeldeinformationen."); + break; + case 2: + exceptionCallback?.Invoke("Der Diensttyp ist für die angegebene Kundennummer nicht definiert."); + MessageBox.Show("Der Diensttyp ist für die angegebene Kundennummer nicht definiert.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); + break; } - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; - - var client = new RestClient(DictionaryServerUrl); - var request = new RestRequest(_Tenant); - - client.ExecuteAsync(request, response => - { - var lookupResult = JsonConvert.DeserializeObject(response.Content); - - _BaseUrl = lookupResult.Url; - ServerUrl = _BaseUrl; - - var result = false; - - switch(lookupResult.Status) - { - case 0: - result = true; - break; - case 1: - exceptionCallback?.Invoke("Fehler: Kundennummer unbekannt.\nBitte überprüfen Sie die Anmeldeinformationen."); - break; - case 2: - exceptionCallback?.Invoke("Der Diensttyp ist für die angegebene Kundennummer nicht definiert."); - MessageBox.Show("Der Diensttyp ist für die angegebene Kundennummer nicht definiert.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); - break; - } - - callback?.Invoke(result); - }); - } - catch(Exception) - { - exceptionCallback?.Invoke("Fehler: Es konnte keine Verbindung aufgebaut werden."); - } + callback?.Invoke(result); + }); } public bool ServerErmittlung() { - if (string.IsNullOrEmpty(ServerUrl)) + if(string.IsNullOrEmpty(ServerUrl)) { + var serverURl = DictionaryServerUrl + _Tenant; + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + var request = WebRequest.Create(serverURl); + + request.Credentials = CredentialCache.DefaultCredentials; + + var response = request.GetResponse(); + var responseFromServer = Utils.ReadStream(response); + try { - var serverURl = DictionaryServerUrl + _Tenant; - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; - var request = WebRequest.Create(serverURl); + var jsonDatentyp = JsonConvert.DeserializeObject(responseFromServer); - request.Credentials = CredentialCache.DefaultCredentials; - - WebResponse response; - - try + switch(jsonDatentyp.Status) { - response = request.GetResponse(); - } - catch(Exception) - { - if (_ShouldShowMessageBox) - { - MessageBox.Show("Fehler: Es konnte keine Verbindung aufgebaut werden.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); - } + case 1: + if (_ShouldShowMessageBox) + { + MessageBox.Show("Fehler: Kundennummer unbekannt.\nBitte überprüfen Sie die Anmeldeinformationen.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); + } - return false; - } - - var responseFromServer = Utils.ReadStream(response); - - try - { - var jsonDatentyp = JsonConvert.DeserializeObject(responseFromServer); - - switch(jsonDatentyp.Status) - { - case 1: - if (_ShouldShowMessageBox) - { - MessageBox.Show("Fehler: Kundennummer unbekannt.\nBitte überprüfen Sie die Anmeldeinformationen.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); - } - - return false; - case 2: - if (_ShouldShowMessageBox) - { - MessageBox.Show("Der Diensttyp ist für die angegebene Kundennummer nicht definiert.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); - } - - return false; - } - - _BaseUrl = jsonDatentyp.Url; - } - catch(Exception) - { - try - { - var jsonDatentyp = JsonConvert.DeserializeObject(responseFromServer); - - switch(jsonDatentyp.Status) + return false; + case 2: + if (_ShouldShowMessageBox) { - case 1: - if (_ShouldShowMessageBox) - { - MessageBox.Show("Fehler: Kundennummer unbekannt.\nBitte überprüfen Sie die Anmeldeinformationen.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); - } - - return false; - case 2: - if (_ShouldShowMessageBox) - { - MessageBox.Show("Der Diensttyp ist für die angegebene Kundennummer nicht definiert.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); - } - - return false; + MessageBox.Show("Der Diensttyp ist für die angegebene Kundennummer nicht definiert.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); } - - _BaseUrl = jsonDatentyp.Url; - } - catch(Exception e) - { - if(_ShouldShowMessageBox) - { - MessageBox.Show("Fehler: " + e.Message, "ownChat Fehler", MessageBoxButton.OK, MessageBoxImage.Error); - } - } + + return false; } - response.Close(); - - ServerUrl = _BaseUrl; - return true; + _BaseUrl = jsonDatentyp.Url; } - catch(Exception e) + catch(Exception) { - if(_ShouldShowMessageBox) + var jsonDatentyp = JsonConvert.DeserializeObject(responseFromServer); + + switch(jsonDatentyp.Status) { - MessageBox.Show("Fehler: " + e.Message, "ownChat Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + case 1: + if (_ShouldShowMessageBox) + { + MessageBox.Show("Fehler: Kundennummer unbekannt.\nBitte überprüfen Sie die Anmeldeinformationen.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); + } + + return false; + case 2: + if (_ShouldShowMessageBox) + { + MessageBox.Show("Der Diensttyp ist für die angegebene Kundennummer nicht definiert.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); + } + + return false; } - - return false; + + _BaseUrl = jsonDatentyp.Url; } + + response.Close(); + + ServerUrl = _BaseUrl; + return true; } return true; @@ -303,104 +255,86 @@ namespace ChatController.HauptKlassen private void VerbindeMitChatServer(Dictionary postparameter) { - try + var endurl = _BaseUrl + Constants.LoginWithChatCodeUrl; + + var requestBody = postparameter.Keys.Aggregate(string.Empty, (current, key) => current + HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(postparameter[key]) + "&"); + + var client = new RestClient(endurl); + var request = new RestRequest(Method.POST); + + request.AddHeader("content-type", "application/x-www-form-urlencoded"); + request.AddParameter(Constants.CustomerId, _Tenant, ParameterType.HttpHeader); + request.AddParameter("application/x-www-form-urlencoded", requestBody, ParameterType.RequestBody); + + var response = client.Post(request); + + if(response.StatusCode == HttpStatusCode.OK) { - var endurl = _BaseUrl + Constants.LoginWithChatCodeUrl; + Debug.WriteLine(response.Content); + var userDaten = JsonConvert.DeserializeObject(response.Content); - var requestBody = postparameter.Keys.Aggregate(string.Empty, (current, key) => current + HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(postparameter[key]) + "&"); - - var client = new RestClient(endurl); - var request = new RestRequest(Method.POST); - - request.AddHeader("content-type", "application/x-www-form-urlencoded"); - request.AddParameter(Constants.CustomerId, _Tenant, ParameterType.HttpHeader); - request.AddParameter("application/x-www-form-urlencoded", requestBody, ParameterType.RequestBody); - - var response = client.Post(request); - - if (response.StatusCode == HttpStatusCode.OK) + if(userDaten.Success) { - Debug.WriteLine(response.Content); - var userDaten = JsonConvert.DeserializeObject(response.Content); + _AuthToken = userDaten.Response.User.Token; + _UserId = userDaten.Response.User.Oid; - if (userDaten.Success) - { - _AuthToken = userDaten.Response.User.Token; - _UserId = userDaten.Response.User.Oid; + Utils.AuthToken = _AuthToken; + Utils.Tenant = _Tenant; - Utils.AuthToken = _AuthToken; - Utils.Tenant = _Tenant; + _LoggedInUser = userDaten; - _LoggedInUser = userDaten; - - _OwnchatVerbindungsaufbauOk = true; - } - else - { - if(!(userDaten.Error?.ChatCodeFailed is null)) - { - if (_ShouldShowMessageBox) - { - MessageBox.Show("Fehler: " + userDaten.Error.ChatCodeFailed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error); - } - } - else if(!(userDaten.Error?.LoginFailed is null)) - { - if (_ShouldShowMessageBox) - { - MessageBox.Show("Fehler: " + userDaten.Error.LoginFailed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error); - } - } - - _OwnchatVerbindungsaufbauOk = false; - } + _OwnchatVerbindungsaufbauOk = true; } else { - MessageBox.Show(response.Content, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + if(!(userDaten.Error?.ChatCodeFailed is null)) + { + if(_ShouldShowMessageBox) + { + MessageBox.Show("Fehler: " + userDaten.Error.ChatCodeFailed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error); + } + } + else if(!(userDaten.Error?.LoginFailed is null)) + { + if(_ShouldShowMessageBox) + { + MessageBox.Show("Fehler: " + userDaten.Error.LoginFailed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error); + } + } + + _OwnchatVerbindungsaufbauOk = false; } } - catch(Exception e) + else { - if(_ShouldShowMessageBox) - { - MessageBox.Show("Fehler:" + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); - } + MessageBox.Show(response.Content, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); } } private void GetGroups() { - try + var endurl = _BaseUrl + Constants.GetChatGroupsUrl; + + var request = WebRequest.Create(endurl); + + request.Credentials = CredentialCache.DefaultCredentials; + request.Headers[Constants.Token] = _AuthToken; + request.Headers[Constants.CustomerId] = _Tenant; + + using(var response = request.GetResponse()) { - var endurl = _BaseUrl + Constants.GetChatGroupsUrl; + var serverResponse = Utils.ReadStream(response); - var request = WebRequest.Create(endurl); - - request.Credentials = CredentialCache.DefaultCredentials; - request.Headers[Constants.Token] = _AuthToken; - request.Headers[Constants.CustomerId] = _Tenant; - - using (var response = request.GetResponse()) + if(string.IsNullOrEmpty(serverResponse)) { - var serverResponse = Utils.ReadStream(response); - - if (!string.IsNullOrEmpty(serverResponse)) - { - var jsonDaten = JsonConvert.DeserializeObject(serverResponse); - - _AllGroups = jsonDaten; - - _GruppeholenverbindungsaufbauOk = true; - } - } - } - catch (Exception e) - { - if (_ShouldShowMessageBox) - { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + return; } + + var jsonDaten = JsonConvert.DeserializeObject(serverResponse); + + _AllGroups = jsonDaten; + + _GruppeholenverbindungsaufbauOk = true; } } @@ -479,32 +413,25 @@ namespace ChatController.HauptKlassen public long GetMaiximumAllowedFileUploadSize(string pToken, string pCustomerId) { - long maximumFileSize; - - try + long maximumFileSize = 0L; + + var endurl = ServerUrl + Constants.MaxUploadFileSizeUrl; + + var request = WebRequest.Create(endurl); + request.Headers[Constants.Token] = pToken; + request.Headers[Constants.CustomerId] = pCustomerId; + + request.Credentials = CredentialCache.DefaultCredentials; + request.Proxy = null; + + using (var response = request.GetResponse()) { - var endurl = ServerUrl + Constants.MaxUploadFileSizeUrl; + var responseFromServer = Utils.ReadStream(response); - var request = WebRequest.Create(endurl); - request.Headers[Constants.Token] = pToken; - request.Headers[Constants.CustomerId] = pCustomerId; + var definiti = new {file_upload_max_size = ""}; - request.Credentials = CredentialCache.DefaultCredentials; - request.Proxy = null; - - using (var response = request.GetResponse()) - { - var responseFromServer = Utils.ReadStream(response); - - var definiti = new {file_upload_max_size = ""}; - - var jsonDatentyp = JsonConvert.DeserializeAnonymousType(responseFromServer, definiti); - maximumFileSize = Convert.ToInt64(jsonDatentyp.file_upload_max_size); - } - } - catch (Exception e) - { - return 0; + var jsonDatentyp = JsonConvert.DeserializeAnonymousType(responseFromServer, definiti); + maximumFileSize = Convert.ToInt64(jsonDatentyp.file_upload_max_size); } return maximumFileSize; @@ -522,7 +449,6 @@ namespace ChatController.HauptKlassen client.ExecuteAsync(request, response => { - Debug.WriteLine("+++>Maximale Dateigröße erhalten"); var maxFileSizeAnonymous = JsonConvert.DeserializeAnonymousType(response.Content, new { file_upload_max_size = string.Empty }); var maxUploadFileSize = Convert.ToInt64(maxFileSizeAnonymous.file_upload_max_size); diff --git a/ChatController/LoginControl.xaml.cs b/ChatController/LoginControl.xaml.cs index 5292911..5dd5fed 100644 --- a/ChatController/LoginControl.xaml.cs +++ b/ChatController/LoginControl.xaml.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.ComponentModel; using System.IO; -using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Windows; @@ -29,11 +28,13 @@ namespace ChatController set { - if (!Equals(_Benutzername, value)) + if(Equals(_Benutzername, value)) { - _Benutzername = value; - OnPropertyChanged(nameof(UserName)); + return; } + + _Benutzername = value; + OnPropertyChanged(nameof(UserName)); } } @@ -50,11 +51,13 @@ namespace ChatController set { - if(!Equals(_ChatCode, value)) + if(Equals(_ChatCode, value)) { - _ChatCode = value; - OnPropertyChanged(nameof(ChatCode)); + return; } + + _ChatCode = value; + OnPropertyChanged(nameof(ChatCode)); } } @@ -64,11 +67,13 @@ namespace ChatController set { - if(!Equals(_Kundennummer, value)) + if(Equals(_Kundennummer, value)) { - _Kundennummer = value; - OnPropertyChanged(nameof(Tenant)); + return; } + + _Kundennummer = value; + OnPropertyChanged(nameof(Tenant)); } } @@ -104,24 +109,28 @@ namespace ChatController private void StartWaitingImmediately() { - if (_WaitLayer is null) + if(!(_WaitLayer is null)) { - _WaitLayer = new ChatControlWaitLayer(); - Panel.SetZIndex(_WaitLayer, int.MaxValue); - RootGrid.Children.Add(_WaitLayer); - _WaitLayer.RefreshUI(); + return; } + + _WaitLayer = new ChatControlWaitLayer(); + Panel.SetZIndex(_WaitLayer, int.MaxValue); + RootGrid.Children.Add(_WaitLayer); + _WaitLayer.RefreshUI(); } private void EndWaiting() { Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) delegate { - if(!(_WaitLayer is null)) + if(_WaitLayer is null) { - RootGrid.Children.Remove(_WaitLayer); - _WaitLayer = null; + return; } + + RootGrid.Children.Remove(_WaitLayer); + _WaitLayer = null; }); } @@ -129,7 +138,7 @@ namespace ChatController { try { - if (!string.IsNullOrWhiteSpace(_Kundennummer) && !string.IsNullOrWhiteSpace(_ChatCode) && !string.IsNullOrWhiteSpace(_Benutzername) && Password.Length > 0) + if(!string.IsNullOrWhiteSpace(_Kundennummer) && !string.IsNullOrWhiteSpace(_ChatCode) && !string.IsNullOrWhiteSpace(_Benutzername) && Password.Length > 0) { StartWaiting(); @@ -141,12 +150,14 @@ namespace ChatController { EndWaiting(); - if(chatDatenUebergabe != null) + if(chatDatenUebergabe is null) { - AutosetDaten(); - - OnLogin?.Invoke(chatDatenUebergabe); + return; } + + AutosetDaten(); + + OnLogin?.Invoke(chatDatenUebergabe); }); }, errorMessage => @@ -164,9 +175,8 @@ namespace ChatController MessageBox.Show("Bitte alle Felder ausfüllen!", "Info", MessageBoxButton.OK); } } - catch (Exception exception) + finally { - MessageBox.Show("Fehler: " + exception.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); EndWaiting(); Cursor = Cursors.Arrow; } @@ -174,86 +184,64 @@ namespace ChatController private void LoadTenantAndChatCodeFromFile() { - try + if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) { - if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) + var lines = new List(); + using(var streamReader = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), true)) { - var lines = new List(); - using(var streamReader = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), true)) - { - string line; + string line; - while(!((line = streamReader.ReadLine()) is null)) + while(!((line = streamReader.ReadLine()) is null)) + { + var encodedTextBytes = Convert.FromBase64String(line); + + var plainText = Encoding.UTF8.GetString(encodedTextBytes); + + lines.Add(plainText); + } + } + + if(lines.Count == 2) + { + _Kundennummer = lines[0]; + _ChatCode = lines[1]; + } + } + + #if DEBUG + var debugFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "debug-info.txt"); + if (File.Exists(debugFile)) + { + using(var streamReader2 = new StreamReader(debugFile, true)) + { + string line; + + var counter = 0; + + while(!((line = streamReader2.ReadLine()) is null)) + { + if(counter == 0) { var encodedTextBytes = Convert.FromBase64String(line); var plainText = Encoding.UTF8.GetString(encodedTextBytes); - lines.Add(plainText); + UserName = plainText; } - } - - if(lines.Count == 2) - { - _Kundennummer = lines[0]; - _ChatCode = lines[1]; - } - } - - #if DEBUG - var debugFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "debug-info.txt"); - if (File.Exists(debugFile)) - { - using(var streamReader2 = new StreamReader(debugFile, true)) - { - string line; - - var counter = 0; - - while(!((line = streamReader2.ReadLine()) is null)) + else if(counter == 1) { - if(counter == 0) - { - try - { - var encodedTextBytes = Convert.FromBase64String(line); + var encodedTextBytes = Convert.FromBase64String(line); - var plainText = Encoding.UTF8.GetString(encodedTextBytes); + var plainText = Encoding.UTF8.GetString(encodedTextBytes); - UserName = plainText; - } - catch (Exception) - { - MessageBox.Show("Der Zeile muss im Base64-Format kodiert sein.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); - } - - } - else if(counter == 1) - { - try - { - var encodedTextBytes = Convert.FromBase64String(line); - - var plainText = Encoding.UTF8.GetString(encodedTextBytes); - - Password = plainText; - } - catch (Exception) - { - MessageBox.Show("Der Zeile muss im Base64-Format kodiert sein.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); - } - } - - counter++; + Password = plainText; } + + counter++; } } - #endif - } - catch(Exception e) - { - MessageBox.Show("Fehler: \n" + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); } + #endif } private void LeseDateiFallsVorhanden() @@ -263,63 +251,46 @@ namespace ChatController private void AutosetDaten() { - try + if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) { - if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) - { - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), FileAttributes.Normal); - File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName)); - } - - using(var streamWriter = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) - { - Encoding utf8Encoding = new UTF8Encoding(); - var tenantBytes = utf8Encoding.GetBytes(_Kundennummer); - var encodedTenant = Convert.ToBase64String(tenantBytes); - - var chatCodeBytes = utf8Encoding.GetBytes(_ChatCode); - var encodedChatCode = Convert.ToBase64String(chatCodeBytes); - - streamWriter.WriteLine(encodedTenant); - streamWriter.WriteLine(encodedChatCode); - - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), FileAttributes.ReadOnly); - } + File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), FileAttributes.Normal); + File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName)); } - catch (Exception e) + + using(var streamWriter = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) { - MessageBox.Show("Fehler: \n" + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + Encoding utf8Encoding = new UTF8Encoding(); + var tenantBytes = utf8Encoding.GetBytes(_Kundennummer); + var encodedTenant = Convert.ToBase64String(tenantBytes); + + var chatCodeBytes = utf8Encoding.GetBytes(_ChatCode); + var encodedChatCode = Convert.ToBase64String(chatCodeBytes); + + streamWriter.WriteLine(encodedTenant); + streamWriter.WriteLine(encodedChatCode); + + File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), FileAttributes.ReadOnly); } } private static string GetAndCreateUserAppDataPath() { - try + var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + var companyFilePath = Path.Combine(localAppData, "ownSoft"); + + if(!Directory.Exists(companyFilePath)) { - var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - var companyFilePath = Path.Combine(localAppData, "ownSoft"); - - if(!Directory.Exists(companyFilePath)) - { - Directory.CreateDirectory(companyFilePath); - } - - var bewoFilePath = Path.Combine(companyFilePath, "OwnChat"); - - if(!Directory.Exists(bewoFilePath)) - { - Directory.CreateDirectory(bewoFilePath); - } - - return bewoFilePath; + Directory.CreateDirectory(companyFilePath); } - catch (Exception ex) + + var bewoFilePath = Path.Combine(companyFilePath, "OwnChat"); + + if(!Directory.Exists(bewoFilePath)) { - MessageBox.Show( - "Fehler beim Anlegen des Anwendungsordners. Sie besitzen nicht die erforderlichen Rechte, bitte wenden Sie sich an Ihren Systemadministrator.\n" + - ex.Message, "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Exclamation); + Directory.CreateDirectory(bewoFilePath); } - return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + + return bewoFilePath; } public void Login() diff --git a/ChatController/Utilities/FileUtils.cs b/ChatController/Utilities/FileUtils.cs index 2216f4a..97e8029 100644 --- a/ChatController/Utilities/FileUtils.cs +++ b/ChatController/Utilities/FileUtils.cs @@ -12,122 +12,115 @@ namespace ChatController.Utilities { public static string ScaleImage(string pFile, string pFormat, long maxUploadSize) { - try - { - var isImageFile = Constants.ImageFileExtensions.Contains(Path.GetExtension(pFile).ToUpperInvariant()); + var isImageFile = Constants.ImageFileExtensions.Contains(Path.GetExtension(pFile).ToUpperInvariant()); - if(!isImageFile) - { - return pFile; - } - - byte[] mediaFile; - using(Stream reader = File.OpenRead(pFile)) - { - mediaFile = Utils.ReadFully(reader); - } - - var memoryStream = new MemoryStream(mediaFile); - var image = Image.FromStream(memoryStream); - - float width, height; - - if(image.Height < image.Width) - { - if(image.Height > 1080) - { - var factor = (float)image.Height / 1080; - - height = 1080; - - width = image.Width / factor; - } - else - { - return pFile; - } - } - else if(image.Height < 1080 && image.Width < 1080) - { - return pFile; - } - else - { - if(image.Width > 1080) - { - var factor = (float)image.Width / 1080; - - width = 1080; - - height = image.Height / factor; - } - else - { - return pFile; - } - } - - var scaledBitmap = new Bitmap(image, new Size((int)width, (int)height)); - - const int orientationId = 0x0112; - - if(image.PropertyIdList.Contains(orientationId)) - { - var item = image.GetPropertyItem(orientationId); - - scaledBitmap.SetPropertyItem(item); - } - - using(var graphics = Graphics.FromImage(image)) - { - graphics.Clear(Color.Transparent); - - graphics.InterpolationMode = InterpolationMode.Low; - - graphics.DrawImage(scaledBitmap, (int)width, (int)height); - } - - // tmp_img_owch_ - var filePath = $"{Path.GetTempPath()}{Guid.NewGuid()}_tmp_img_owch{pFormat}"; - - if(pFormat.Equals(".JPG") || pFormat.Equals(".JPE") || pFormat.Equals(".JPEG") || pFormat.Equals(".BMP")) - { - scaledBitmap.Save(filePath, ImageFormat.Jpeg); - } - else if(pFormat.Equals(".PNG")) - { - scaledBitmap.Save(filePath, ImageFormat.Png); - } - else if(pFormat.Equals(".GIF")) - { - scaledBitmap.Save(filePath, ImageFormat.Gif); - } - - if(File.Exists(filePath)) - { - var fileInfo = new FileInfo(filePath); - var fileInfoLength = fileInfo.Length; - - if(maxUploadSize < fileInfoLength) - { - File.Delete(filePath); - return string.Empty; - } - } - else - { - return string.Empty; - } - - memoryStream.Dispose(); - memoryStream.Close(); - - return filePath; - } - catch(Exception exception) + if(!isImageFile) { return pFile; } + + byte[] mediaFile; + using(Stream reader = File.OpenRead(pFile)) + { + mediaFile = Utils.ReadFully(reader); + } + + var memoryStream = new MemoryStream(mediaFile); + var image = Image.FromStream(memoryStream); + + float width, height; + + if(image.Height < image.Width) + { + if(image.Height > 1080) + { + var factor = (float)image.Height / 1080; + + height = 1080; + + width = image.Width / factor; + } + else + { + return pFile; + } + } + else if(image.Height < 1080 && image.Width < 1080) + { + return pFile; + } + else + { + if(image.Width > 1080) + { + var factor = (float)image.Width / 1080; + + width = 1080; + + height = image.Height / factor; + } + else + { + return pFile; + } + } + + var scaledBitmap = new Bitmap(image, new Size((int)width, (int)height)); + + const int orientationId = 0x0112; + + if(image.PropertyIdList.Contains(orientationId)) + { + var item = image.GetPropertyItem(orientationId); + + scaledBitmap.SetPropertyItem(item); + } + + using(var graphics = Graphics.FromImage(image)) + { + graphics.Clear(Color.Transparent); + + graphics.InterpolationMode = InterpolationMode.Low; + + graphics.DrawImage(scaledBitmap, (int)width, (int)height); + } + + // tmp_img_owch_ + var filePath = $"{Path.GetTempPath()}{Guid.NewGuid()}_tmp_img_owch{pFormat}"; + + if(pFormat.Equals(".JPG") || pFormat.Equals(".JPE") || pFormat.Equals(".JPEG") || pFormat.Equals(".BMP")) + { + scaledBitmap.Save(filePath, ImageFormat.Jpeg); + } + else if(pFormat.Equals(".PNG")) + { + scaledBitmap.Save(filePath, ImageFormat.Png); + } + else if(pFormat.Equals(".GIF")) + { + scaledBitmap.Save(filePath, ImageFormat.Gif); + } + + if(File.Exists(filePath)) + { + var fileInfo = new FileInfo(filePath); + var fileInfoLength = fileInfo.Length; + + if(maxUploadSize < fileInfoLength) + { + File.Delete(filePath); + return string.Empty; + } + } + else + { + return string.Empty; + } + + memoryStream.Dispose(); + memoryStream.Close(); + + return filePath; } public static bool CheckFileSize(string pathToFile, long maxFileSize) diff --git a/ChatController/Utilities/Utils.cs b/ChatController/Utilities/Utils.cs index 1d859f0..190f3be 100644 --- a/ChatController/Utilities/Utils.cs +++ b/ChatController/Utilities/Utils.cs @@ -213,31 +213,22 @@ namespace ChatController.Utilities public static string GetAndCreateUserAppDataPath() { - try + var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + var companyFilePath = Path.Combine(localAppData, Resource.CompanyName); + + if(!Directory.Exists(companyFilePath)) { - var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - var companyFilePath = Path.Combine(localAppData, Resource.CompanyName); - - if(!Directory.Exists(companyFilePath)) - { - Directory.CreateDirectory(companyFilePath); - } - - var bewoFilePath = Path.Combine(companyFilePath, Resource.ApplicationFolderName); - - if(!Directory.Exists(bewoFilePath)) - { - Directory.CreateDirectory(bewoFilePath); - } - - return bewoFilePath; - } - catch(Exception exception) - { - MessageBox.Show("Fehler beim Anlegen des Anwendungsordners. Sie besitzen nicht die erforderlichen Rechte, bitte wenden Sie sich an Ihren Systemadministrator.\n" + exception.Message, "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Exclamation); + Directory.CreateDirectory(companyFilePath); } - return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var bewoFilePath = Path.Combine(companyFilePath, Resource.ApplicationFolderName); + + if(!Directory.Exists(bewoFilePath)) + { + Directory.CreateDirectory(bewoFilePath); + } + + return bewoFilePath; } public static string GenerateTempName() @@ -253,18 +244,10 @@ namespace ChatController.Utilities public static byte[] ImageToByteArray(Image pImage) { - try + using(var memoryStream = new MemoryStream()) { - using(var memoryStream = new MemoryStream()) - { - pImage.Save(memoryStream, ImageFormat.Bmp); - return memoryStream.ToArray(); - } - } - catch(Exception exception) - { - MessageBox.Show("Fehler: " + exception.Message, "Fehler", MessageBoxButton.OK); - return null; + pImage.Save(memoryStream, ImageFormat.Bmp); + return memoryStream.ToArray(); } } diff --git a/PrototypChat/App.xaml b/PrototypChat/App.xaml index c03b568..55dac70 100644 --- a/PrototypChat/App.xaml +++ b/PrototypChat/App.xaml @@ -2,6 +2,7 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ownChat" + DispatcherUnhandledException="App_DispatcherUnhandledException" StartupUri="LoginMaske.xaml"> diff --git a/PrototypChat/App.xaml.cs b/PrototypChat/App.xaml.cs index 363f8d5..72ab0a5 100644 --- a/PrototypChat/App.xaml.cs +++ b/PrototypChat/App.xaml.cs @@ -1,6 +1,14 @@ -namespace ownChat +using System.Windows.Threading; + +namespace ownChat { public partial class App { + private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args) + { + new ExceptionWindow(args.Exception) { Owner = MainWindow }.Show(); + + args.Handled = true; + } } } diff --git a/PrototypChat/ExceptionWindow.xaml b/PrototypChat/ExceptionWindow.xaml new file mode 100644 index 0000000..ac45078 --- /dev/null +++ b/PrototypChat/ExceptionWindow.xaml @@ -0,0 +1,12 @@ + + + + + diff --git a/PrototypChat/ExceptionWindow.xaml.cs b/PrototypChat/ExceptionWindow.xaml.cs new file mode 100644 index 0000000..7db6408 --- /dev/null +++ b/PrototypChat/ExceptionWindow.xaml.cs @@ -0,0 +1,18 @@ +using System; + +namespace ownChat +{ + public partial class ExceptionWindow + { + public ExceptionWindow(Exception exception) + { + InitializeComponent(); + ExceptionViewControl.Exception = exception; + } + + private void ExceptionViewControl_OnOkButtonClicked(object sender, EventArgs e) + { + Close(); + } + } +} diff --git a/PrototypChat/MainWindow.xaml.cs b/PrototypChat/MainWindow.xaml.cs index 651514b..308a6da 100644 --- a/PrototypChat/MainWindow.xaml.cs +++ b/PrototypChat/MainWindow.xaml.cs @@ -17,6 +17,9 @@ namespace ownChat { InitializeComponent(); + var currentDomain = AppDomain.CurrentDomain; + currentDomain.UnhandledException += ExceptionHandler; + ChatMainControl.ContainingWindow = this; ChatMainControl.InitMitChatdaten(x); @@ -24,6 +27,13 @@ namespace ownChat _EmojiView = new ChatEmojisView(ChatMainControl); } + private void ExceptionHandler(object sender, UnhandledExceptionEventArgs args) + { + var exception = (Exception)args.ExceptionObject; + + new ExceptionWindow(exception) { Owner = this }.Show(); + } + private void ChatMainControl_OnOnEmojii(System.Windows.Controls.Button emojiButton) { _EmojiView.Visibility = Visibility.Visible; @@ -31,11 +41,13 @@ namespace ownChat var pointToScreen = emojiButton.PointToScreen(new Point(0, 0)); var presentationSource = PresentationSource.FromVisual(emojiButton); - if(presentationSource?.CompositionTarget != null) + if(presentationSource?.CompositionTarget == null) { - _EmojiView.Top = pointToScreen.Y / presentationSource.CompositionTarget.TransformToDevice.M22 - _EmojiView.Height - 5; - _EmojiView.Left = pointToScreen.X / presentationSource.CompositionTarget.TransformToDevice.M11 - 270; + return; } + + _EmojiView.Top = pointToScreen.Y / presentationSource.CompositionTarget.TransformToDevice.M22 - _EmojiView.Height - 5; + _EmojiView.Left = pointToScreen.X / presentationSource.CompositionTarget.TransformToDevice.M11 - 270; } private void MainWindow_OnClosed(object sender, EventArgs e) diff --git a/PrototypChat/PrototypChat.csproj b/PrototypChat/PrototypChat.csproj index eb4f7e2..b51a80b 100644 --- a/PrototypChat/PrototypChat.csproj +++ b/PrototypChat/PrototypChat.csproj @@ -105,6 +105,10 @@ Designer MSBuild:Compile + + Designer + MSBuild:Compile + Designer MSBuild:Compile @@ -117,6 +121,9 @@ App.xaml Code + + ExceptionWindow.xaml + LoginMaske.xaml