Generelle Ausnahmenanzeige

This commit is contained in:
2023-03-03 21:23:48 +01:00
parent 101ce32c06
commit 6ea4a47b98
18 changed files with 1226 additions and 1346 deletions

View File

@@ -78,6 +78,9 @@
<Compile Include="Core\OwnChatCache.cs" /> <Compile Include="Core\OwnChatCache.cs" />
<Compile Include="Core\OwnChatRichTextBox.cs" /> <Compile Include="Core\OwnChatRichTextBox.cs" />
<Compile Include="Data\LookupResult.cs" /> <Compile Include="Data\LookupResult.cs" />
<Compile Include="ExceptionViewControl.xaml.cs">
<DependentUpon>ExceptionViewControl.xaml</DependentUpon>
</Compile>
<Compile Include="Extensions\IDictionaryTExtensions.cs" /> <Compile Include="Extensions\IDictionaryTExtensions.cs" />
<Compile Include="Extensions\IListTExtensions.cs" /> <Compile Include="Extensions\IListTExtensions.cs" />
<Compile Include="HauptKlassen\Chat.cs" /> <Compile Include="HauptKlassen\Chat.cs" />
@@ -126,6 +129,10 @@
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</Page> </Page>
<Page Include="ExceptionViewControl.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="LoginControl.xaml"> <Page Include="LoginControl.xaml">
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>

View File

@@ -1,5 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
@@ -81,23 +80,16 @@ namespace ChatController
public void PassEmojiToChatMainControl(string emojiCode) public void PassEmojiToChatMainControl(string emojiCode)
{ {
try Dispatcher.Invoke(
{ DispatcherPriority.Normal,
Dispatcher.Invoke( (ThreadStart) delegate
DispatcherPriority.Normal, {
(ThreadStart) delegate _ChatMainControl.Chatbox.Focus();
{
_ChatMainControl.Chatbox.Focus();
var selectionStart = _ChatMainControl.Chatbox.SelectionStart; var selectionStart = _ChatMainControl.Chatbox.SelectionStart;
_ChatMainControl.Chatbox.Text = _ChatMainControl.Chatbox.Text.Insert(selectionStart, emojiCode); _ChatMainControl.Chatbox.Text = _ChatMainControl.Chatbox.Text.Insert(selectionStart, emojiCode);
_ChatMainControl.Chatbox.SelectionStart = selectionStart + emojiCode.Length; _ChatMainControl.Chatbox.SelectionStart = selectionStart + emojiCode.Length;
}); });
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
} }
} }
} }

View File

@@ -67,11 +67,13 @@ namespace ChatController.ChatKlassen
get => _Image; get => _Image;
set set
{ {
if(!Equals(_Image, value)) if(Equals(_Image, value))
{ {
_Image = value; return;
OnPropertyChanged(nameof(Image));
} }
_Image = value;
OnPropertyChanged(nameof(Image));
} }
} }

View File

@@ -11,7 +11,7 @@
mc:Ignorable="d" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="600" d:DesignHeight="300" d:DesignWidth="600"
Loaded="ChatMainControl_OnLoaded" Loaded="ChatMainControl_OnLoaded"
SnapsToDevicePixels="True" d:DataContext="{d:DesignData Type=ChatMainControl}"> SnapsToDevicePixels="True" d:DataContext="{d:DesignData Type=chatController:ChatMainControl}">
<UserControl.Resources> <UserControl.Resources>
<converter:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" /> <converter:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
<converter:StringEmptyToVisibilityConverter x:Key="StringEmptyToVisibilityConverter" /> <converter:StringEmptyToVisibilityConverter x:Key="StringEmptyToVisibilityConverter" />

View File

@@ -40,7 +40,6 @@ using Timer = System.Windows.Forms.Timer;
namespace ChatController namespace ChatController
{ {
// Test
public partial class ChatMainControl : INotifyPropertyChanged public partial class ChatMainControl : INotifyPropertyChanged
{ {
private readonly Dictionary<long, List<NotifyIcon>> _Group2NotifyIcons = new Dictionary<long, List<NotifyIcon>>(); private readonly Dictionary<long, List<NotifyIcon>> _Group2NotifyIcons = new Dictionary<long, List<NotifyIcon>>();
@@ -55,14 +54,16 @@ namespace ChatController
set set
{ {
if(!Equals(_ThreadExceptionMessage, value)) if(Equals(_ThreadExceptionMessage, value))
{ {
_ThreadExceptionMessage = value; return;
OnPropertyChanged(nameof(ThreadExceptionMessage));
OnPropertyChanged(nameof(CurrentContactInformationString));
OnPropertyChanged(nameof(CurrencContactInfoForeground));
OnPropertyChanged(nameof(ThreadExceptionImageSource));
} }
_ThreadExceptionMessage = value;
OnPropertyChanged(nameof(ThreadExceptionMessage));
OnPropertyChanged(nameof(CurrentContactInformationString));
OnPropertyChanged(nameof(CurrencContactInfoForeground));
OnPropertyChanged(nameof(ThreadExceptionImageSource));
} }
} }
@@ -84,11 +85,13 @@ namespace ChatController
{ {
_ContainingWindow = value; _ContainingWindow = value;
if(!(value is null)) if(value is null)
{ {
_ContainingWindow.Deactivated += ContainingWindowOnDeactivated; return;
_ContainingWindow.Activated += ContainingWindowOnActivated;
} }
_ContainingWindow.Deactivated += ContainingWindowOnDeactivated;
_ContainingWindow.Activated += ContainingWindowOnActivated;
} }
} }
@@ -115,17 +118,19 @@ namespace ChatController
set set
{ {
if(!Equals(_CurrentContact, value)) if(Equals(_CurrentContact, value))
{ {
_CurrentContact = value; return;
OnPropertyChanged(nameof(CurrentContact));
OnPropertyChanged(nameof(ChatMessageInputGridVisibility));
OnPropertyChanged(nameof(Chat));
OnPropertyChanged(nameof(CurrentContactInformationString));
OnPropertyChanged(nameof(CurrencContactInfoForeground));
OnPropertyChanged(nameof(ThreadExceptionImageSource));
} }
_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) foreach(var file in files)
{ {
if(File.Exists(file)) if(!File.Exists(file))
{ {
try continue;
{
File.Delete(file);
}
catch(IOException)
{
}
} }
File.Delete(file);
} }
} }
finally finally
{ {
this.Dispatch(() => this.Dispatch(EndWaiting);
{
EndWaiting();
});
} }
}); });
@@ -263,7 +260,6 @@ namespace ChatController
_ContactList = new ObservableSortCollection<ContactDependencyObject>(); _ContactList = new ObservableSortCollection<ContactDependencyObject>();
// ToDo: Hier tritt eine NullPointer-Exception auf!
foreach(var contact in Chat.AddContacts()) foreach(var contact in Chat.AddContacts())
{ {
ContactList.Add(new ContactDependencyObject(contact)); ContactList.Add(new ContactDependencyObject(contact));
@@ -299,7 +295,7 @@ namespace ChatController
var contact = _ContactList.FirstOrDefault(a => a.Contact.GroupId == pGroupId); var contact = _ContactList.FirstOrDefault(a => a.Contact.GroupId == pGroupId);
if (!(contact is null)) if(!(contact is null))
{ {
notificationIcon = Utils.ImageSourceToIcon(contact.Contact.Image); notificationIcon = Utils.ImageSourceToIcon(contact.Contact.Image);
} }
@@ -331,7 +327,7 @@ namespace ChatController
notifyIcon.BalloonTipClosed += (sender, args) => 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); DisposeAndRemoveNotification((NotifyIcon)sender, pGroupId);
}; };
@@ -386,94 +382,75 @@ namespace ChatController
private void SelectContact(Contact contact) 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; Chat.LoadChatMessagesForContactAsync(currentContact, GetFirstMessage(), chatMessages =>
{
StartWaitingImmediately(); this.Dispatch(() =>
_ScrollPrueferAktivieren = false;
if(contact.HasUnreadMessages)
{ {
contact.HasUnreadMessages = false; _ChatMessages.Clear();
_ChatMessages.AddRangeIfElementsNotIn(chatMessages);
OnPropertyChanged(nameof(_ChatMessages));
Clientlist.Items.Refresh(); WpfUtils.ScrollToBottomOfListBox(ChatListBox);
OnPropertyChanged(nameof(ContactList));
}
var currentContact = contact; ChatListBox.ContextMenu = Chat.ErstelleKontextMenue();
contact.IsNewMessage = false; SetContextHandler();
_ScrollPrueferAktivieren = true;
var shouldChangeIcon = _ContactList.Any(contactDependencyObject => contactDependencyObject.Contact.IsNewMessage); ListenForMessages();
if(shouldChangeIcon) Cursor = Cursors.Arrow;
{
ContainingWindow.Icon = Utils.ConvertIconToImageSource(Resource.ownchat_favicon);
}
CurrentContact = currentContact; WriteToNewSyncFile();
OnPropertyChanged(nameof(IsSendButtonEnabled)); ShouldInterruptContactsThread = false;
foreach(ContactDependencyObject item in Clientlist.Items) EndWaiting();
{
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();
});
}); });
} });
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() private void SetContextHandler()
@@ -514,16 +491,18 @@ namespace ChatController
} }
// neu und vor Einfügen setzen und anpassen // neu und vor Einfügen setzen und anpassen
if(contextItems.Count > 2) if(contextItems.Count <= 2)
{ {
var copyMenuItem = (MenuItem) contextItems[2]; return;
copyMenuItem.Click += CopyOnClick;
} }
var copyMenuItem = (MenuItem) contextItems[2];
copyMenuItem.Click += CopyOnClick;
} }
private void SaveAsOnClick(object sender, RoutedEventArgs routedEventArgs) private void SaveAsOnClick(object sender, RoutedEventArgs routedEventArgs)
{ {
foreach (var items in ChatListBox.SelectedItems) foreach(var items in ChatListBox.SelectedItems)
{ {
var chatMessage = (ChatMessage) items; var chatMessage = (ChatMessage) items;
@@ -658,42 +637,44 @@ namespace ChatController
{ {
var pathToOriginalImage = Chat.OpenFile(); var pathToOriginalImage = Chat.OpenFile();
if(File.Exists(pathToOriginalImage)) if(!File.Exists(pathToOriginalImage))
{ {
StartWaitingImmediately("Skaliere Bild ..."); return;
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();
} }
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 else
{ {
@@ -772,41 +753,36 @@ namespace ChatController
private void Chatbox_OnGotFocus(object sender, RoutedEventArgs e) private void Chatbox_OnGotFocus(object sender, RoutedEventArgs e)
{ {
if (Chatbox.Text.Equals("Nachricht schreiben")) if(!Chatbox.Text.Equals("Nachricht schreiben"))
{ {
Chatbox.Text = string.Empty; return;
Chatbox.Foreground = new SolidColorBrush(Colors.Black);
} }
Chatbox.Text = string.Empty;
Chatbox.Foreground = new SolidColorBrush(Colors.Black);
} }
private void Chatbox_OnKeyDownHandler(object sender, KeyEventArgs e) private void Chatbox_OnKeyDownHandler(object sender, KeyEventArgs e)
{ {
try //if (e.Key == Key.Return)
{ //{
//if (e.Key == Key.Return) // if(CurrentContact != null && !string.IsNullOrEmpty(Chatbox.Text))
//{ // {
// if(CurrentContact != null && !string.IsNullOrEmpty(Chatbox.Text)) // Chat.AddNewMessage(Chatbox.Text, CurrentContact.GroupId);
// {
// Chat.AddNewMessage(Chatbox.Text, CurrentContact.GroupId);
// OnPropertyChanged(nameof(CurrentChatMessages)); // OnPropertyChanged(nameof(CurrentChatMessages));
// ChatListBox.Items.MoveCurrentToLast(); // ChatListBox.Items.MoveCurrentToLast();
// ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); // 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(IsBroadcastButtonEnabled));
OnPropertyChanged(nameof(IsSendButtonEnabled)); OnPropertyChanged(nameof(IsSendButtonEnabled));
}
catch (Exception ed)
{
MessageBox.Show("Beim Senden einer Nachricht ist ein Fehler aufgetreten. " + ed.Message + "\n" + ed.StackTrace, "Fehler", MessageBoxButton.OK);
}
} }
private void Chatbox_OnKeyUpHandler(object sender, KeyEventArgs e) private void Chatbox_OnKeyUpHandler(object sender, KeyEventArgs e)
@@ -827,9 +803,9 @@ namespace ChatController
private void Chat_OnScrollChanged(object sender, ScrollChangedEventArgs e) private void Chat_OnScrollChanged(object sender, ScrollChangedEventArgs e)
{ {
var scrollBarList = Utils.GetVisualChildCollection<ScrollBar>(ChatListBox); var scrollBarList = Utils.GetVisualChildCollection<ScrollBar>(ChatListBox);
foreach (var scrollBar in scrollBarList) foreach(var scrollBar in scrollBarList)
{ {
if (scrollBar.Orientation == Orientation.Horizontal) if(scrollBar.Orientation == Orientation.Horizontal)
{ {
_ScrollPrueferAktivieren = true; _ScrollPrueferAktivieren = true;
} }
@@ -842,38 +818,44 @@ namespace ChatController
private void VerticalScrollbarChanged(object sender, RoutedPropertyChangedEventArgs<double> routedPropertyChangedEventArgs) private void VerticalScrollbarChanged(object sender, RoutedPropertyChangedEventArgs<double> 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(); ChatListBox.ScrollIntoView(currentChatMessage);
});
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);
});
});
}
}
}
} }
private void ListenForMessages() private void ListenForMessages()
@@ -906,74 +888,70 @@ namespace ChatController
this.Dispatch(() => 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) continue;
{
// 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;
}
}
}
} }
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)); if(!updatedContacts.Contains(contactDependencyObject.Contact))
OnPropertyChanged(nameof(ChatMessages)); {
OnPropertyChanged(nameof(ContactList)); _ContactList.ToList().Remove(contactDependencyObject);
} }
catch(Exception exception)
{
Console.WriteLine(exception);
throw;
} }
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) private bool UserFilter(object item)
{ {
if (string.IsNullOrEmpty(Suche.Text)) if(string.IsNullOrEmpty(Suche.Text))
{ {
return true; return true;
} }
@@ -1040,44 +1018,48 @@ namespace ChatController
private void Chat_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) 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 bitmapImage = new BitmapImage(uri);
{ bitmapImage.Freeze();
var uri = new Uri(selectedMessage.OriginalImage);
if(uri.IsFile) Chat.ShowPictureWindow(bitmapImage, "Test");
{
var bitmapImage = new BitmapImage(uri);
bitmapImage.Freeze();
Chat.ShowPictureWindow(bitmapImage, "Test"); return;
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);
}
} }
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(); callback?.Invoke();
} }
} }
catch(Exception exception) finally
{ {
EndWaiting(); EndWaiting();
MessageBox.Show(exception.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
} }
} }
@@ -1128,14 +1109,16 @@ namespace ChatController
public void StartWaitingImmediately(string dialogText = null) public void StartWaitingImmediately(string dialogText = null)
{ {
if (_WaitLayer is null) if(!(_WaitLayer is null))
{ {
_WaitLayer = new ChatControlWaitLayer(dialogText); return;
Grid.SetRowSpan(_WaitLayer, 3);
RootGrid.Children.Add(_WaitLayer);
Panel.SetZIndex(_WaitLayer, int.MaxValue);
_WaitLayer.RefreshChatUI();
} }
_WaitLayer = new ChatControlWaitLayer(dialogText);
Grid.SetRowSpan(_WaitLayer, 3);
RootGrid.Children.Add(_WaitLayer);
Panel.SetZIndex(_WaitLayer, int.MaxValue);
_WaitLayer.RefreshChatUI();
} }
public void EndWaiting() public void EndWaiting()
@@ -1144,11 +1127,13 @@ namespace ChatController
DispatcherPriority.Background, DispatcherPriority.Background,
(Action) delegate (Action) delegate
{ {
if(!(_WaitLayer is null)) if(_WaitLayer is null)
{ {
RootGrid.Children.Remove(_WaitLayer); return;
_WaitLayer = null;
} }
RootGrid.Children.Remove(_WaitLayer);
_WaitLayer = null;
}); });
} }
@@ -1197,10 +1182,9 @@ namespace ChatController
}); });
}); });
} }
catch (Exception e) finally
{ {
EndWaiting(); EndWaiting();
MessageBox.Show("Ein Fehler bei der Synchronisation ist aufgetreten.\nFehler:\n" + e.Message, "Fehler", MessageBoxButton.OK);
} }
} }
@@ -1209,7 +1193,7 @@ namespace ChatController
{ {
try 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.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name), FileAttributes.Normal);
File.Delete(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name)); File.Delete(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name));
@@ -1305,16 +1289,18 @@ namespace ChatController
// Wird im BeWoPlaner benutzt // Wird im BeWoPlaner benutzt
public void ResetNumberOfUnreadMessages(Dictionary<long, DateTime> pGroupId2DateTime) public void ResetNumberOfUnreadMessages(Dictionary<long, DateTime> 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() public void DeleteTempFiles()
{ {
foreach (var file in _CreatedTempFiles) foreach(var file in _CreatedTempFiles)
{ {
try try
{ {
if (File.Exists(file)) if(File.Exists(file))
{ {
File.Delete(file); File.Delete(file);
} }
} }
catch (Exception) catch(Exception)
{ {
//ignore okeee //ignore okeee
} }
@@ -1449,15 +1435,15 @@ namespace ChatController
private CancellationTokenSource _CancellationTokenSource; 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; private string _BroadcastInfoText;
public string BroadcastInfoText public string BroadcastInfoText
{ {
get => _BroadcastInfoText ?? (_BroadcastInfoText = _DefaultBroadcastInfoText); get => _BroadcastInfoText ?? (_BroadcastInfoText = DefaultBroadcastInfoText);
set set
{ {
_BroadcastInfoText = $"{_DefaultBroadcastInfoText}{Environment.NewLine}{value}"; _BroadcastInfoText = $"{DefaultBroadcastInfoText}{Environment.NewLine}{value}";
OnPropertyChanged(BroadcastInfoText); OnPropertyChanged(BroadcastInfoText);
} }
} }
@@ -1497,7 +1483,7 @@ namespace ChatController
DeselectAllContacts(); DeselectAllContacts();
if (Chat.IsInBroadcastMode) if(Chat.IsInBroadcastMode)
{ {
_CancellationTokenSource = new CancellationTokenSource(); _CancellationTokenSource = new CancellationTokenSource();
_PreviousContact = CurrentContact; _PreviousContact = CurrentContact;
@@ -1598,18 +1584,20 @@ namespace ChatController
private void SelectAllContacts_OnClick(object sender, RoutedEventArgs e) private void SelectAllContacts_OnClick(object sender, RoutedEventArgs e)
{ {
if(sender is CheckBox checkBox) if(!(sender is CheckBox checkBox))
{ {
var isChecked = checkBox.IsChecked ?? false; return;
foreach (var contactDependencyObject in ContactList)
{
contactDependencyObject.SetValue(ListItemHelper.IsCheckedProperty, isChecked);
}
OnPropertyChanged(nameof(ContactList));
OnPropertyChanged(nameof(IsBroadcastButtonEnabled));
} }
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) private void SendBroatcastButton_OnClick(object sender, RoutedEventArgs e)
@@ -1626,42 +1614,46 @@ namespace ChatController
private void AddMediaFileToBroadcastMessage_OnClick(object sender, RoutedEventArgs e) private void AddMediaFileToBroadcastMessage_OnClick(object sender, RoutedEventArgs e)
{ {
if(Chat.IsInBroadcastMode) if(!Chat.IsInBroadcastMode)
{ {
var originalFilePath = Chat.OpenFile(); return;
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();
}
} }
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() private void CloseBroadcastMode()
@@ -1741,7 +1733,7 @@ namespace ChatController
private void DeselectAllContacts() private void DeselectAllContacts()
{ {
foreach (var contactDependencyObject in ContactList) foreach(var contactDependencyObject in ContactList)
{ {
contactDependencyObject.SetValue(ListItemHelper.IsCheckedProperty, false); contactDependencyObject.SetValue(ListItemHelper.IsCheckedProperty, false);
} }

View File

@@ -0,0 +1,57 @@
<UserControl x:Class="ChatController.ExceptionViewControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<Style x:Key="OrangeButtonStyle" TargetType="{x:Type Button}">
<Setter Property="FontSize" Value="14" />
<Setter Property="Margin" Value="5" />
<Setter Property="Height" Value="40" />
<Setter Property="MinWidth" Value="100"></Setter>
<Setter Property="BorderBrush" Value="#FF5A00" />
<Setter Property="Background" Value="#FF5A00" />
<Setter Property="Foreground" Value="White"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Border" Background="#FF5A00" CornerRadius="5" Padding="5,2">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#FF988F" TargetName="Border" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="#FF7654" TargetName="Border" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" Value="LightGray" TargetName="Border" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" TextWrapping="Wrap" FontWeight="Bold" Text="Es ist leider ein unbekannter Fehler aufgetreten. Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut. Wir sind stets bemüht, das Programm zu verbessern, daher freuen wir uns auch, wenn Sie die Fehlerdetails unten in einer Mail an support@bewoplaner.de senden." Margin="5, 5, 5, 10" FontSize="14" />
<TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Margin="5" FontSize="12" TextDecorations="Underline">Fehlerdetails:</TextBlock>
<TextBox Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Margin="5" IsReadOnly="True" Text="{Binding Path=Exception.StackTrace, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
<Button Grid.Column="0" Grid.Row="3" Style="{StaticResource OrangeButtonStyle}" HorizontalAlignment="Left" Click="CopyToClipboardButton_OnClick">In die Zwischenablage kopieren</Button>
<Button Grid.Column="2" Grid.Row="3" Style="{StaticResource OrangeButtonStyle}" HorizontalAlignment="Right" Click="OkButton_OnClick">OK</Button>
</Grid>
</UserControl>

View File

@@ -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);
}
}
}

View File

@@ -73,32 +73,25 @@ namespace ChatController.HauptKlassen
private static bool PinPublicKey(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors) private static bool PinPublicKey(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
{ {
try if(certificate is null || chain is null)
{
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)
{ {
return false; 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"; private const string PubKeyX3 = "3082010A02820101009CD30CF05AE52E47B7725D3783B3686330EAD735261925E1BDBE35F170922FB7B84B4105ABA99E350858ECB12AC468870BA3E375E4E6F3A76271BA7981601FD7919A9FF3D0786771C8690E9591CFFEE699E9603C48CC7ECA4D7712249D471B5AEBB9EC1E37001C9CAC7BA705EACE4AEBBD41E53698B9CBFD6D3C9668DF232A42900C867467C87FA59AB8526114133F65E98287CBDBFA0E56F68689F3853F9786AFB0DC1AEF6B0D95167DC42BA065B299043675806BAC4AF31B9049782FA2964F2A20252904C674C0D031CD8F31389516BAA833B843F1B11FC3307FA27931133D2D36F8E3FCF2336AB93931C5AFC48D0D1D641633AAFA8429B6D40BC0D87DC3930203010001";
@@ -134,37 +127,30 @@ namespace ChatController.HauptKlassen
private void LoadMessagesFromServerAsync(long groupId, Action callback) 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<UserMessages>(response.Content);
var client = new RestClient(url); if(_UserMessages?.Response?.HasMorePages ?? false)
var request = new RestRequest();
request.AddHeader(Constants.Token, ChatDaten.AuthToken);
request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer);
client.ExecuteAsync(request, response =>
{ {
_UserMessages = JsonConvert.DeserializeObject<UserMessages>(response.Content); _NextPage = _UserMessages.Response.NextPage;
_HasNextPage = true;
if (_UserMessages?.Response?.HasMorePages ?? false) }
{ else
_NextPage = _UserMessages.Response.NextPage; {
_HasNextPage = true; _HasNextPage = false;
} }
else
{
_HasNextPage = false;
}
callback?.Invoke(); callback?.Invoke();
}); });
}
catch (Exception exception)
{
ThreadExceptionCallback?.Invoke(exception);
}
} }
public void LoadMoreMessagesAsync(Contact contact, ChatMessage previousMessage, Action<List<ChatMessage>> callback) public void LoadMoreMessagesAsync(Contact contact, ChatMessage previousMessage, Action<List<ChatMessage>> callback)
@@ -177,43 +163,36 @@ namespace ChatController.HauptKlassen
private void LoadMoreMessagesFromServerAsync(long groupId, string page, Action callback) 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<UserMessages>(response.Content);
if(_AdditionalUserMessages?.Response?.HasMorePages ?? false)
{ {
callback?.Invoke(); _NextPage = _AdditionalUserMessages.Response.NextPage;
return;
} }
var pageParam = page.Split('=')[1]; _HasNextPage = _AdditionalUserMessages?.Response?.HasMorePages ?? false;
var url = $"{ChatDaten.ServerUrl}/api/chat/messages?groupid={groupId}&page={pageParam}"; callback?.Invoke();
});
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<UserMessages>(response.Content);
if (_AdditionalUserMessages?.Response?.HasMorePages ?? false)
{
_NextPage = _AdditionalUserMessages.Response.NextPage;
}
_HasNextPage = _AdditionalUserMessages?.Response?.HasMorePages ?? false;
callback?.Invoke();
});
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
} }
private double _FormerMessagesCount; 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 span = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var timespan = Convert.ToInt64(span.TotalSeconds); 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; timespan = _UserMessages.Response.Messages.First().Created_At;
} }
@@ -259,8 +238,8 @@ namespace ChatController.HauptKlassen
} }
catch(Exception exception) catch(Exception exception)
{ {
ExceptionCallback?.Invoke(exception);
callback?.Invoke(0d); callback?.Invoke(0d);
throw exception;
} }
} }
@@ -279,184 +258,125 @@ namespace ChatController.HauptKlassen
private void LoadNumberOfNewMessagesFromServerAsync(long groupId, Action<double> callback) private void LoadNumberOfNewMessagesFromServerAsync(long groupId, Action<double> 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<MessageCounter>(response.Content);
var client = new RestClient(url); callback?.Invoke(messageCounter?.MessageCount ?? 0);
var request = new RestRequest(); });
request.AddHeader(Constants.Token, ChatDaten.AuthToken);
request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer);
client.ExecuteAsync(request, response =>
{
var messageCounter = JsonConvert.DeserializeObject<MessageCounter>(response.Content);
callback?.Invoke(messageCounter?.MessageCount ?? 0);
});
}
catch(Exception exception)
{
ThreadExceptionCallback?.Invoke(exception);
}
} }
private void LoadGroupsAsync(Action<ChatGruppenDaten> callback) private void LoadGroupsAsync(Action<ChatGruppenDaten> 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<ChatGruppenDaten>(response.Content);
var client = new RestClient(url); callback?.Invoke(contacts);
var request = new RestRequest(); });
request.AddHeader(Constants.Token, ChatDaten.AuthToken);
request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer);
client.ExecuteAsync(request, response =>
{
var contacts = JsonConvert.DeserializeObject<ChatGruppenDaten>(response.Content);
callback?.Invoke(contacts);
});
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
} }
public void UpdateContactList(Action<IOrderedEnumerable<Contact>> callback) public void UpdateContactList(Action<IOrderedEnumerable<Contact>> 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)); callback?.Invoke(contacts.OrderByDescending(c => c.TimeStamp));
}); });
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
} }
public List<ChatMessage> AddNewMessage(string pMessage, long pGroupId, ChatMessage previousMessage) public List<ChatMessage> AddNewMessage(string pMessage, long pGroupId, ChatMessage previousMessage)
{ {
var result = new List<ChatMessage>(); var time = DateTime.Now;
try 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 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 result = AddSeparators(new List<ChatMessage> {previousMessage, chatMessage});
result = AddSeparators(new List<ChatMessage> {previousMessage, chatMessage});
result.Remove(previousMessage);
return result;
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
result.Remove(previousMessage);
return result; return result;
} }
public async Task SendMessage(string message, long groupId) 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()) var httpRequest = new HttpRequestMessage {Method = HttpMethod.Post, RequestUri = requestUri, Content = multiPartContent};
{
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}; httpRequest.Headers.Add("Token", ChatDaten.AuthToken);
httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer);
httpRequest.Headers.Add("Token", ChatDaten.AuthToken); var httpClient = new HttpClient();
httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer); await httpClient.SendAsync(httpRequest, CancellationToken.None);
var httpClient = new HttpClient();
await httpClient.SendAsync(httpRequest, CancellationToken.None);
}
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
} }
} }
public string OpenFile() public string OpenFile()
{ {
try var openFileDialog = new OpenFileDialog
{ {
var openFileDialog = new OpenFileDialog Filter = Resource.OpenFileDialogFilter_Test
{ };
Filter = Resource.OpenFileDialogFilter_Test
};
var result = openFileDialog.ShowDialog(); var result = openFileDialog.ShowDialog();
return result == DialogResult.OK ? openFileDialog.FileName : null; return result == DialogResult.OK ? openFileDialog.FileName : null;
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
return null;
}
} }
public List<ChatMessage> AddNewFile(string pathToScaledFile, string originalFilePath, long groupId, ChatMessage previousMessage, string chatBoxText) public List<ChatMessage> AddNewFile(string pathToScaledFile, string originalFilePath, long groupId, ChatMessage previousMessage, string chatBoxText)
{ {
var result = new List<ChatMessage>(); var result = new List<ChatMessage>();
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<ChatMessage> { previousMessage, chatMessage });
result.Remove(previousMessage);
return result; return result;
} }
catch(Exception exception)
{ var messageId = 0;
if(!(exception is IOException)) var userName = ChatDaten.LoggedInUser.Response.User.UserName;
{ var sendTime = DateTime.Now;
ExceptionCallback?.Invoke(exception); 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<ChatMessage> { previousMessage, chatMessage });
result.Remove(previousMessage);
return result; return result;
} }
@@ -533,7 +453,7 @@ namespace ChatController.HauptKlassen
var sendtime = DateTime.Now; 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 bitmapImage = new BitmapImage();
var memoryStream = new MemoryStream(file); var memoryStream = new MemoryStream(file);
@@ -563,14 +483,7 @@ namespace ChatController.HauptKlassen
public async Task SendFileToContact(Contact currentContact, string scaledImagePath, string originalFilePath, string message) public async Task SendFileToContact(Contact currentContact, string scaledImagePath, string originalFilePath, string message)
{ {
try await SendFile(scaledImagePath, currentContact, originalFilePath, message);
{
await SendFile(scaledImagePath, currentContact, originalFilePath, message);
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
} }
private async Task SendFile(string pFile, Contact currentContact, string pOriginalFilePath, string 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) public void SaveFileAs(ChatMessage pChatMessage)
{ {
if (!(pChatMessage.PictureSource is null)) if(!(pChatMessage.PictureSource is null))
{ {
SaveAs(1, Path.GetFileName(pChatMessage.OriginalImage), DownloadMediaFile(pChatMessage.OriginalImage)); SaveAs(1, Path.GetFileName(pChatMessage.OriginalImage), DownloadMediaFile(pChatMessage.OriginalImage));
} }
@@ -669,63 +582,47 @@ namespace ChatController.HauptKlassen
{ {
byte[] mediaFile = null; 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.Credentials = CredentialCache.DefaultCredentials; webClient.Headers[Constants.CustomerId] = ChatDaten.Kundennummer;
webClient.Headers[Constants.Token] = ChatDaten.AuthToken; mediaFile = webClient.DownloadData(pFilePath);
webClient.Headers[Constants.CustomerId] = ChatDaten.Kundennummer; }
mediaFile = webClient.DownloadData(pFilePath);
}
return mediaFile;
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
return mediaFile; return mediaFile;
} }
private void SaveAs(int pFilterType, string pFileName, byte[] pMediaFile) 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)}; case 1:
saveFileDialog.Filter = Resource.SaveFileDialogFilter_Images;
switch(pFilterType) saveFileDialog.Title = Resource.SaveFIleDialogTitle_Images;
{ saveFileDialog.ShowDialog();
case 1: break;
saveFileDialog.Filter = Resource.SaveFileDialogFilter_Images; case 2:
saveFileDialog.Title = Resource.SaveFIleDialogTitle_Images; saveFileDialog.Filter = Resource.SaveFileDialogFilter_Documents;
saveFileDialog.ShowDialog(); saveFileDialog.Title = Resource.SaveFIleDialogTitle_Documents;
break; saveFileDialog.ShowDialog();
case 2: break;
saveFileDialog.Filter = Resource.SaveFileDialogFilter_Documents; case 3:
saveFileDialog.Title = Resource.SaveFIleDialogTitle_Documents; saveFileDialog.Filter = Resource.SaveFileDialogFilter_Audio;
saveFileDialog.ShowDialog(); saveFileDialog.Title = Resource.SaveFIleDialogTitle_Audio;
break; saveFileDialog.ShowDialog();
case 3: break;
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();
}
} }
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)) 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)) pChatMainControl.AddMessages(AddFileToMessage(mediaFile, fileName, pGroupOid, pChatMainControl.GetFirstMessage()));
{
var fileName = Path.GetFileName(pathToFile); CollectionViewSource.GetDefaultView(pChatMainControl.ChatListBox.ItemsSource).Refresh();
var mediaFile = File.ReadAllBytes(pathToFile);
pChatMainControl.AddMessages(AddFileToMessage(mediaFile, fileName, pGroupOid, pChatMainControl.GetFirstMessage())); pChatMainControl.ChatListBox.Items.MoveCurrentToLast();
pChatMainControl.ChatListBox.ScrollIntoView(pChatMainControl.ChatListBox.Items.CurrentItem);
CollectionViewSource.GetDefaultView(pChatMainControl.ChatListBox.ItemsSource).Refresh();
pChatMainControl.ChatListBox.Items.MoveCurrentToLast(); await SendMediaMessage(fileName, pGroupOid, mediaFile, null);
pChatMainControl.ChatListBox.ScrollIntoView(pChatMainControl.ChatListBox.Items.CurrentItem);
await SendMediaMessage(fileName, pGroupOid, mediaFile, null);
}
} }
} }
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
} }
else else
{ {
@@ -825,85 +715,71 @@ namespace ChatController.HauptKlassen
public void ShowProfilePicture(Contact currentContact) public void ShowProfilePicture(Contact currentContact)
{ {
try ShowPictureWindow(currentContact.Image, currentContact.Name);
{
ShowPictureWindow(currentContact.Image, currentContact.Name);
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
} }
public void ShowPictureWindow(ImageSource imageSource, string title) 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); if(primaryScreenWidth2 > primaryScreenHeight2)
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) windowMaxHeight = (int)(.8 * primaryScreenHeight2);
{ windowMaxWidth = (int)(windowMaxHeight * imageAspectRatio);
windowMaxHeight = (int)(.8 * primaryScreenHeight2);
windowMaxWidth = (int)(windowMaxHeight * imageAspectRatio);
}
else
{
windowMaxWidth = (int)(.8 * primaryScreenWidth2);
windowMaxHeight = (int)(windowMaxWidth * imageAspectRatio);
}
} }
else
var maximumWindowSize = new System.Windows.Size(windowMaxWidth, windowMaxHeight);
var minHeight = 232 / imageAspectRatio;
var minWidth = 232d;
var window = new Window
{ {
Title = title, windowMaxWidth = (int)(.8 * primaryScreenWidth2);
MinHeight = minHeight, windowMaxHeight = (int)(windowMaxWidth * imageAspectRatio);
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();
} }
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<ImageSource, string> downloadCompletedCallback) public void ShowPicture(string originalImage, long groupId, Action<ImageSource, string> downloadCompletedCallback)
@@ -913,20 +789,13 @@ namespace ChatController.HauptKlassen
return; 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"); downloadCompletedCallback?.Invoke(imageSource, last ?? "Bild");
}); });
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
} }
public void ReloadGroupsAsync(Action<ChatGruppenDaten> callback) public void ReloadGroupsAsync(Action<ChatGruppenDaten> callback)
@@ -951,22 +820,14 @@ namespace ChatController.HauptKlassen
public List<Contact> UpdateContacts(ChatGruppenDaten chatDaten) public List<Contact> UpdateContacts(ChatGruppenDaten chatDaten)
{ {
try _Contacts.Clear();
if(!(chatDaten?.Response is null))
{ {
_Contacts.Clear(); _Contacts.AddRange(GenerateContactsFromServerResponse(chatDaten.Response.Groups.ToArray()));
}
if(!(chatDaten?.Response is null))
{
_Contacts.AddRange(GenerateContactsFromServerResponse(chatDaten.Response.Groups.ToArray()));
}
return _Contacts; return _Contacts;
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
return null;
}
} }
public List<Contact> GenerateContactsFromServerResponse(GroupInput[] pGroupInputs, bool pShouldUpdateLastTimeStamp = false) public List<Contact> GenerateContactsFromServerResponse(GroupInput[] pGroupInputs, bool pShouldUpdateLastTimeStamp = false)
@@ -1015,17 +876,16 @@ namespace ChatController.HauptKlassen
groupInput.Avatar, groupInput.Avatar,
key, groupInput.Users.ToDictionary(user => user.Oid, user => user.Picture))); 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)) continue;
{ }
var unixTimeStamp = DateTime.Parse(latestMessage.Timestamp.Date).GetUnixTimeStamp();
if(LastTimeStamp < unixTimeStamp) var unixTimeStamp = DateTime.Parse(latestMessage.Timestamp.Date).GetUnixTimeStamp();
{
LastTimeStamp = unixTimeStamp; if(LastTimeStamp < unixTimeStamp)
} {
} LastTimeStamp = unixTimeStamp;
} }
} }
@@ -1092,32 +952,25 @@ namespace ChatController.HauptKlassen
public void DownloadFileAsync(string uri, string path, Action callback) 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); if(response.StatusCode == HttpStatusCode.OK)
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) response.RawBytes.SaveAs(path);
{ }
response.RawBytes.SaveAs(path); else
} {
else throw new Exception("Die Datei konnte nicht heruntergeladen werden.");
{ }
throw new Exception("Die Datei konnte nicht heruntergeladen werden.");
}
callback?.Invoke(); callback?.Invoke();
}); });
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
} }
private bool _IsInBroadcastMode; private bool _IsInBroadcastMode;

View File

@@ -83,38 +83,39 @@ namespace ChatController.HauptKlassen
// Wird im BeWoPlaner benutzt // Wird im BeWoPlaner benutzt
public ChatDatenUebergabe AnmeldevorgangDurchFuehren() public ChatDatenUebergabe AnmeldevorgangDurchFuehren()
{ {
if(ServerErmittlung()) if(!ServerErmittlung())
{ {
var dic = new Dictionary<string, string> return null;
{
{ "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; var dic = new Dictionary<string, string>
{
{ "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<ChatDatenUebergabe> callback, Action<string> exceptionCallback) public void DoLoginAsync(Action<ChatDatenUebergabe> callback, Action<string> exceptionCallback)
{ {
try LookupServerUrlAsync(isConnectedWithServer =>
{
LookupServerUrlAsync(isConnectedWithServer =>
{ {
if(isConnectedWithServer) if(isConnectedWithServer)
{ {
@@ -139,163 +140,114 @@ namespace ChatController.HauptKlassen
errorMessage => { exceptionCallback?.Invoke(errorMessage); }); errorMessage => { exceptionCallback?.Invoke(errorMessage); });
} }
}, errorMessage => { exceptionCallback?.Invoke(errorMessage); }); }, errorMessage => { exceptionCallback?.Invoke(errorMessage); });
}
catch(Exception)
{
callback?.Invoke(null);
}
} }
public void LookupServerUrlAsync(Action<bool> callback, Action<string> exceptionCallback) public void LookupServerUrlAsync(Action<bool> callback, Action<string> 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<LookupResult>(response.Content);
_BaseUrl = lookupResult.Url;
ServerUrl = _BaseUrl;
var result = false;
switch(lookupResult.Status)
{ {
callback?.Invoke(false); case 0:
return; 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; callback?.Invoke(result);
});
var client = new RestClient(DictionaryServerUrl);
var request = new RestRequest(_Tenant);
client.ExecuteAsync(request, response =>
{
var lookupResult = JsonConvert.DeserializeObject<LookupResult>(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.");
}
} }
public bool ServerErmittlung() 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 try
{ {
var serverURl = DictionaryServerUrl + _Tenant; var jsonDatentyp = JsonConvert.DeserializeObject<AuthenticationDataType1>(responseFromServer);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = WebRequest.Create(serverURl);
request.Credentials = CredentialCache.DefaultCredentials; switch(jsonDatentyp.Status)
WebResponse response;
try
{ {
response = request.GetResponse(); case 1:
} if (_ShouldShowMessageBox)
catch(Exception) {
{ MessageBox.Show("Fehler: Kundennummer unbekannt.\nBitte überprüfen Sie die Anmeldeinformationen.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk);
if (_ShouldShowMessageBox) }
{
MessageBox.Show("Fehler: Es konnte keine Verbindung aufgebaut werden.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
}
return false; return false;
} case 2:
if (_ShouldShowMessageBox)
var responseFromServer = Utils.ReadStream(response);
try
{
var jsonDatentyp = JsonConvert.DeserializeObject<AuthenticationDataType1>(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<AuthenticationDataType2>(responseFromServer);
switch(jsonDatentyp.Status)
{ {
case 1: MessageBox.Show("Der Diensttyp ist für die angegebene Kundennummer nicht definiert.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk);
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; return false;
}
catch(Exception e)
{
if(_ShouldShowMessageBox)
{
MessageBox.Show("Fehler: " + e.Message, "ownChat Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
} }
response.Close(); _BaseUrl = jsonDatentyp.Url;
ServerUrl = _BaseUrl;
return true;
} }
catch(Exception e) catch(Exception)
{ {
if(_ShouldShowMessageBox) var jsonDatentyp = JsonConvert.DeserializeObject<AuthenticationDataType2>(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; return true;
@@ -303,104 +255,86 @@ namespace ChatController.HauptKlassen
private void VerbindeMitChatServer(Dictionary<string, string> postparameter) private void VerbindeMitChatServer(Dictionary<string, string> 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<UserDaten>(response.Content);
var requestBody = postparameter.Keys.Aggregate(string.Empty, (current, key) => current + HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(postparameter[key]) + "&"); if(userDaten.Success)
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)
{ {
Debug.WriteLine(response.Content); _AuthToken = userDaten.Response.User.Token;
var userDaten = JsonConvert.DeserializeObject<UserDaten>(response.Content); _UserId = userDaten.Response.User.Oid;
if (userDaten.Success) Utils.AuthToken = _AuthToken;
{ Utils.Tenant = _Tenant;
_AuthToken = userDaten.Response.User.Token;
_UserId = userDaten.Response.User.Oid;
Utils.AuthToken = _AuthToken; _LoggedInUser = userDaten;
Utils.Tenant = _Tenant;
_LoggedInUser = userDaten; _OwnchatVerbindungsaufbauOk = true;
_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;
}
} }
else 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(response.Content, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
{
MessageBox.Show("Fehler:" + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
}
} }
} }
private void GetGroups() 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); if(string.IsNullOrEmpty(serverResponse))
request.Credentials = CredentialCache.DefaultCredentials;
request.Headers[Constants.Token] = _AuthToken;
request.Headers[Constants.CustomerId] = _Tenant;
using (var response = request.GetResponse())
{ {
var serverResponse = Utils.ReadStream(response); return;
if (!string.IsNullOrEmpty(serverResponse))
{
var jsonDaten = JsonConvert.DeserializeObject<ChatGruppenDaten>(serverResponse);
_AllGroups = jsonDaten;
_GruppeholenverbindungsaufbauOk = true;
}
}
}
catch (Exception e)
{
if (_ShouldShowMessageBox)
{
MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
} }
var jsonDaten = JsonConvert.DeserializeObject<ChatGruppenDaten>(serverResponse);
_AllGroups = jsonDaten;
_GruppeholenverbindungsaufbauOk = true;
} }
} }
@@ -479,32 +413,25 @@ namespace ChatController.HauptKlassen
public long GetMaiximumAllowedFileUploadSize(string pToken, string pCustomerId) public long GetMaiximumAllowedFileUploadSize(string pToken, string pCustomerId)
{ {
long maximumFileSize; long maximumFileSize = 0L;
try 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); var definiti = new {file_upload_max_size = ""};
request.Headers[Constants.Token] = pToken;
request.Headers[Constants.CustomerId] = pCustomerId;
request.Credentials = CredentialCache.DefaultCredentials; var jsonDatentyp = JsonConvert.DeserializeAnonymousType(responseFromServer, definiti);
request.Proxy = null; maximumFileSize = Convert.ToInt64(jsonDatentyp.file_upload_max_size);
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;
} }
return maximumFileSize; return maximumFileSize;
@@ -522,7 +449,6 @@ namespace ChatController.HauptKlassen
client.ExecuteAsync(request, response => client.ExecuteAsync(request, response =>
{ {
Debug.WriteLine("+++>Maximale Dateigröße erhalten");
var maxFileSizeAnonymous = JsonConvert.DeserializeAnonymousType(response.Content, new { file_upload_max_size = string.Empty }); var maxFileSizeAnonymous = JsonConvert.DeserializeAnonymousType(response.Content, new { file_upload_max_size = string.Empty });
var maxUploadFileSize = Convert.ToInt64(maxFileSizeAnonymous.file_upload_max_size); var maxUploadFileSize = Convert.ToInt64(maxFileSizeAnonymous.file_upload_max_size);

View File

@@ -2,7 +2,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.IO; using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Windows; using System.Windows;
@@ -29,11 +28,13 @@ namespace ChatController
set set
{ {
if (!Equals(_Benutzername, value)) if(Equals(_Benutzername, value))
{ {
_Benutzername = value; return;
OnPropertyChanged(nameof(UserName));
} }
_Benutzername = value;
OnPropertyChanged(nameof(UserName));
} }
} }
@@ -50,11 +51,13 @@ namespace ChatController
set set
{ {
if(!Equals(_ChatCode, value)) if(Equals(_ChatCode, value))
{ {
_ChatCode = value; return;
OnPropertyChanged(nameof(ChatCode));
} }
_ChatCode = value;
OnPropertyChanged(nameof(ChatCode));
} }
} }
@@ -64,11 +67,13 @@ namespace ChatController
set set
{ {
if(!Equals(_Kundennummer, value)) if(Equals(_Kundennummer, value))
{ {
_Kundennummer = value; return;
OnPropertyChanged(nameof(Tenant));
} }
_Kundennummer = value;
OnPropertyChanged(nameof(Tenant));
} }
} }
@@ -104,24 +109,28 @@ namespace ChatController
private void StartWaitingImmediately() private void StartWaitingImmediately()
{ {
if (_WaitLayer is null) if(!(_WaitLayer is null))
{ {
_WaitLayer = new ChatControlWaitLayer(); return;
Panel.SetZIndex(_WaitLayer, int.MaxValue);
RootGrid.Children.Add(_WaitLayer);
_WaitLayer.RefreshUI();
} }
_WaitLayer = new ChatControlWaitLayer();
Panel.SetZIndex(_WaitLayer, int.MaxValue);
RootGrid.Children.Add(_WaitLayer);
_WaitLayer.RefreshUI();
} }
private void EndWaiting() private void EndWaiting()
{ {
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) delegate Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) delegate
{ {
if(!(_WaitLayer is null)) if(_WaitLayer is null)
{ {
RootGrid.Children.Remove(_WaitLayer); return;
_WaitLayer = null;
} }
RootGrid.Children.Remove(_WaitLayer);
_WaitLayer = null;
}); });
} }
@@ -129,7 +138,7 @@ namespace ChatController
{ {
try 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(); StartWaiting();
@@ -141,12 +150,14 @@ namespace ChatController
{ {
EndWaiting(); EndWaiting();
if(chatDatenUebergabe != null) if(chatDatenUebergabe is null)
{ {
AutosetDaten(); return;
OnLogin?.Invoke(chatDatenUebergabe);
} }
AutosetDaten();
OnLogin?.Invoke(chatDatenUebergabe);
}); });
}, },
errorMessage => errorMessage =>
@@ -164,9 +175,8 @@ namespace ChatController
MessageBox.Show("Bitte alle Felder ausfüllen!", "Info", MessageBoxButton.OK); 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(); EndWaiting();
Cursor = Cursors.Arrow; Cursor = Cursors.Arrow;
} }
@@ -174,86 +184,64 @@ namespace ChatController
private void LoadTenantAndChatCodeFromFile() private void LoadTenantAndChatCodeFromFile()
{ {
try if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName)))
{ {
if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) var lines = new List<string>();
using(var streamReader = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), true))
{ {
var lines = new List<string>(); string line;
using(var streamReader = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), true))
{
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 encodedTextBytes = Convert.FromBase64String(line);
var plainText = Encoding.UTF8.GetString(encodedTextBytes); var plainText = Encoding.UTF8.GetString(encodedTextBytes);
lines.Add(plainText); UserName = plainText;
} }
} else if(counter == 1)
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);
{
try
{
var encodedTextBytes = Convert.FromBase64String(line);
var plainText = Encoding.UTF8.GetString(encodedTextBytes); var plainText = Encoding.UTF8.GetString(encodedTextBytes);
UserName = plainText; Password = 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++;
} }
counter++;
} }
} }
#endif
}
catch(Exception e)
{
MessageBox.Show("Fehler: \n" + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
} }
#endif
} }
private void LeseDateiFallsVorhanden() private void LeseDateiFallsVorhanden()
@@ -263,63 +251,46 @@ namespace ChatController
private void AutosetDaten() 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));
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);
}
} }
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() 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); Directory.CreateDirectory(companyFilePath);
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;
} }
catch (Exception ex)
var bewoFilePath = Path.Combine(companyFilePath, "OwnChat");
if(!Directory.Exists(bewoFilePath))
{ {
MessageBox.Show( Directory.CreateDirectory(bewoFilePath);
"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);
} }
return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
return bewoFilePath;
} }
public void Login() public void Login()

View File

@@ -12,122 +12,115 @@ namespace ChatController.Utilities
{ {
public static string ScaleImage(string pFile, string pFormat, long maxUploadSize) 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) 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)
{ {
return pFile; 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) public static bool CheckFileSize(string pathToFile, long maxFileSize)

View File

@@ -213,31 +213,22 @@ namespace ChatController.Utilities
public static string GetAndCreateUserAppDataPath() 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); Directory.CreateDirectory(companyFilePath);
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);
} }
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() public static string GenerateTempName()
@@ -253,18 +244,10 @@ namespace ChatController.Utilities
public static byte[] ImageToByteArray(Image pImage) 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();
pImage.Save(memoryStream, ImageFormat.Bmp);
return memoryStream.ToArray();
}
}
catch(Exception exception)
{
MessageBox.Show("Fehler: " + exception.Message, "Fehler", MessageBoxButton.OK);
return null;
} }
} }

View File

@@ -2,6 +2,7 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ownChat" xmlns:local="clr-namespace:ownChat"
DispatcherUnhandledException="App_DispatcherUnhandledException"
StartupUri="LoginMaske.xaml"> StartupUri="LoginMaske.xaml">
<Application.Resources> <Application.Resources>

View File

@@ -1,6 +1,14 @@
namespace ownChat using System.Windows.Threading;
namespace ownChat
{ {
public partial class App public partial class App
{ {
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args)
{
new ExceptionWindow(args.Exception) { Owner = MainWindow }.Show();
args.Handled = true;
}
} }
} }

View File

@@ -0,0 +1,12 @@
<Window x:Class="ownChat.ExceptionWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:chatController="clr-namespace:ChatController;assembly=ChatController"
mc:Ignorable="d" WindowStartupLocation="CenterOwner"
Title="Es ist ein Fehler aufgetreten" Height="450" Width="800">
<Grid>
<chatController:ExceptionViewControl x:Name="ExceptionViewControl" OkButtonClicked="ExceptionViewControl_OnOkButtonClicked" />
</Grid>
</Window>

View File

@@ -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();
}
}
}

View File

@@ -17,6 +17,9 @@ namespace ownChat
{ {
InitializeComponent(); InitializeComponent();
var currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += ExceptionHandler;
ChatMainControl.ContainingWindow = this; ChatMainControl.ContainingWindow = this;
ChatMainControl.InitMitChatdaten(x); ChatMainControl.InitMitChatdaten(x);
@@ -24,6 +27,13 @@ namespace ownChat
_EmojiView = new ChatEmojisView(ChatMainControl); _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) private void ChatMainControl_OnOnEmojii(System.Windows.Controls.Button emojiButton)
{ {
_EmojiView.Visibility = Visibility.Visible; _EmojiView.Visibility = Visibility.Visible;
@@ -31,11 +41,13 @@ namespace ownChat
var pointToScreen = emojiButton.PointToScreen(new Point(0, 0)); var pointToScreen = emojiButton.PointToScreen(new Point(0, 0));
var presentationSource = PresentationSource.FromVisual(emojiButton); var presentationSource = PresentationSource.FromVisual(emojiButton);
if(presentationSource?.CompositionTarget != null) if(presentationSource?.CompositionTarget == null)
{ {
_EmojiView.Top = pointToScreen.Y / presentationSource.CompositionTarget.TransformToDevice.M22 - _EmojiView.Height - 5; return;
_EmojiView.Left = pointToScreen.X / presentationSource.CompositionTarget.TransformToDevice.M11 - 270;
} }
_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) private void MainWindow_OnClosed(object sender, EventArgs e)

View File

@@ -105,6 +105,10 @@
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</Page> </Page>
<Page Include="ExceptionWindow.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="LoginMaske.xaml"> <Page Include="LoginMaske.xaml">
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
@@ -117,6 +121,9 @@
<DependentUpon>App.xaml</DependentUpon> <DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Include="ExceptionWindow.xaml.cs">
<DependentUpon>ExceptionWindow.xaml</DependentUpon>
</Compile>
<Compile Include="LoginMaske.xaml.cs"> <Compile Include="LoginMaske.xaml.cs">
<DependentUpon>LoginMaske.xaml</DependentUpon> <DependentUpon>LoginMaske.xaml</DependentUpon>
</Compile> </Compile>