Der Login läuft jetzt mit RestSharp.

Die Akzentfarbe von den Chatgruppen vom Server wird berücksichtigt.
Bilder sind im richtigen Seitenverhältnis skaliert.
Ein Bild, das man gerade erst verschickt hat und das man öffnen will, bevor es auf dem Server angekommen ist, wird jetzt erst angezeigt, sobald es auf dem Server ist.
Die Textbox für eine neue Nachricht wird nur angezeigt, wenn eine Gruppe ausgewählt ist und wenn man das Recht hat Nachrichten an diese Gruppe zu verschicken.
Diverse Codeverbesserungen.
This commit is contained in:
Lyndon Jetten
2020-06-17 19:36:52 +02:00
parent 71f9a15c8e
commit e8ef515e7a
30 changed files with 2345 additions and 2019 deletions

View File

@@ -4,7 +4,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Foreground="{DynamicResource BSOrangeBrush}">
Foreground="#FF5A00">
<UserControl.Resources>
<Style TargetType="{x:Type Rectangle}">
@@ -72,7 +72,7 @@
<TranslateTransform X="0" Y="0" />
</TransformGroup>
</Grid.RenderTransform>
<Viewbox StretchDirection="Both" Stretch="Fill" MaxWidth="{Binding Path=Width, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" MaxHeight="{Binding Path=Height, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
<Viewbox StretchDirection="Both" Stretch="Fill" MaxWidth="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" MaxHeight="{Binding Path=ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
<Canvas Width="100" Height="100">
<Canvas Width="100" Height="100" Canvas.Left="0" Canvas.Top="0">
<Rectangle Canvas.Left="44" Canvas.Top="0" RadiusX="6" RadiusY="6"/>

View File

@@ -46,7 +46,7 @@
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="RestSharp, Version=105.2.3.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\BeWo\packages\RestSharp.105.2.3\lib\net45\RestSharp.dll</HintPath>
<HintPath>..\PrototypChat\packages\RestSharp.105.2.3\lib\net45\RestSharp.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
@@ -69,11 +69,14 @@
<Compile Include="ChatKlassen\ChatControlExtensions.cs" />
<Compile Include="ChatKlassen\Contact.cs" />
<Compile Include="ChatKlassen\ChatMessage.cs" />
<Compile Include="ChatKlassen\CurrentContact.cs" />
<Compile Include="ChatKlassen\MessageCounter.cs" />
<Compile Include="ChatMainControl.xaml.cs">
<DependentUpon>ChatMainControl.xaml</DependentUpon>
</Compile>
<Compile Include="Converter\BoolToVisibilityConverter.cs" />
<Compile Include="Converter\StringEmptyToVisibilityConverter.cs" />
<Compile Include="Converter\StringToBoolConverter.cs" />
<Compile Include="Data\LookupResult.cs" />
<Compile Include="Data\OwnChatApi.cs" />
<Compile Include="Extensions\IDictionaryTExtensions.cs" />
<Compile Include="Extensions\IListTExtensions.cs" />
@@ -99,7 +102,10 @@
<DependentUpon>Resource.resx</DependentUpon>
</Compile>
<Compile Include="Utilities\Constants.cs" />
<Compile Include="Utilities\Extensions\ControlExtensions.cs" />
<Compile Include="Utilities\Extensions\DateTimeExtensions.cs" />
<Compile Include="Utilities\FileUtils.cs" />
<Compile Include="Utilities\OwnChatEnums.cs" />
<Compile Include="Utilities\SyncFileInfoStruct.cs" />
<Compile Include="Utilities\Utils.cs" />
</ItemGroup>
@@ -155,7 +161,9 @@
<EmbeddedResource Include="Resource.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Resource.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -3,124 +3,123 @@
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"
xmlns:local="clr-namespace:ChatController"
xmlns:hauptKlassen="clr-namespace:ChatController.HauptKlassen"
mc:Ignorable="d"
d:DesignHeight="200" d:DesignWidth="300">
<Grid>
<TabControl>
<TabItem Header="1" x:Name="TabItem1" >
<ListBox x:Name="EmojisListBox1" HorizontalAlignment="Left" Height="114" VerticalAlignment="Top" Width="285" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}" >
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" Height="22" MinWidth="22" FontSize="18" Foreground="OrangeRed" Margin="1" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="2" x:Name="TabItem2">
<ListBox x:Name="EmojisListBox2" HorizontalAlignment="Left" Height="114" VerticalAlignment="Top" Width="285" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" Height="22" Width="22" FontSize="18" Foreground="OrangeRed"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="3" x:Name="TabItem3">
<ListBox x:Name="EmojisListBox3" HorizontalAlignment="Left" Height="114" VerticalAlignment="Top" Width="285" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" Height="22" Width="22" FontSize="18" Foreground="OrangeRed"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="4" x:Name="TabItem4">
<ListBox x:Name="EmojisListBox4" HorizontalAlignment="Left" Height="114" VerticalAlignment="Top" Width="285" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" Height="22" Width="22" FontSize="18" Foreground="OrangeRed"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="5" x:Name="TabItem5">
<ListBox x:Name="EmojisListBox5" HorizontalAlignment="Left" Height="114" VerticalAlignment="Top" Width="285" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" Height="22" Width="22" FontSize="18" Foreground="OrangeRed"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="6" x:Name="TabItem6">
<ListBox x:Name="EmojisListBox6" HorizontalAlignment="Left" Height="114" VerticalAlignment="Top" Width="285" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" Height="22" Width="22" FontSize="18" Foreground="OrangeRed"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="7" x:Name="TabItem7">
<ListBox x:Name="EmojisListBox7" HorizontalAlignment="Left" Height="114" VerticalAlignment="Top" Width="285" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" Height="22" Width="22" FontSize="18" Foreground="OrangeRed"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
</TabControl>
<TabControl>
<TabItem Header="1" x:Name="TabItem1" >
<ListBox x:Name="EmojisListBox1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}" >
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" FontSize="18" Foreground="#FF5A00" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="2" x:Name="TabItem2">
<ListBox x:Name="EmojisListBox2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" FontSize="18" Foreground="#FF5A00" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="3" x:Name="TabItem3">
<ListBox x:Name="EmojisListBox3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" FontSize="18" Foreground="#FF5A00" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="4" x:Name="TabItem4">
<ListBox x:Name="EmojisListBox4" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" FontSize="18" Foreground="#FF5A00" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="5" x:Name="TabItem5">
<ListBox x:Name="EmojisListBox5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" FontSize="18" Foreground="#FF5A00" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="6" x:Name="TabItem6">
<ListBox x:Name="EmojisListBox6" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" FontSize="18" Foreground="#FF5A00" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
<TabItem Header="7" x:Name="TabItem7">
<ListBox x:Name="EmojisListBox7" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="OnEmojiClick" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type hauptKlassen:DirectoryListing}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding EmojiCode}" FontSize="18" Foreground="#FF5A00" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</TabItem>
</TabControl>
</Grid>
</UserControl>

View File

@@ -1,163 +1,95 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using ChatController.HauptKlassen;
namespace ChatController
{
/// <summary>
/// Interaktionslogik für ChatEmojiiControl.xaml
/// </summary>
public partial class ChatEmojiiControl : UserControl
public partial class ChatEmojiiControl
{
private ChatMainControl _ChatMainControl;
private readonly ChatEmoji _ChatEmoji;
ChatMainControl chatView;
private ChatEmoji _emojii;
private readonly List<ListBox> _EmojiListBoxes = new List<ListBox>();
public ChatEmojiiControl()
{
InitializeComponent();
_emojii = new ChatEmoji();
_ChatEmoji = new ChatEmoji();
SetEmojis();
}
public void InitChatView(ChatMainControl c)
public void InitChatView(ChatMainControl chatMainControl)
{
chatView = c;
_ChatMainControl = chatMainControl;
}
public void SetEmojis()
{
EmojisListBox1.ItemsSource = _emojii.EmojisListBox1;
EmojisListBox2.ItemsSource = _emojii.EmojisListBox2;
EmojisListBox3.ItemsSource = _emojii.EmojisListBox3;
EmojisListBox4.ItemsSource = _emojii.EmojisListBox4;
EmojisListBox5.ItemsSource = _emojii.EmojisListBox5;
EmojisListBox6.ItemsSource = _emojii.EmojisListBox6;
EmojisListBox7.ItemsSource = _emojii.EmojisListBox7;
EmojisListBox1.ItemsSource = _ChatEmoji.EmojisListBox1;
EmojisListBox2.ItemsSource = _ChatEmoji.EmojisListBox2;
EmojisListBox3.ItemsSource = _ChatEmoji.EmojisListBox3;
EmojisListBox4.ItemsSource = _ChatEmoji.EmojisListBox4;
EmojisListBox5.ItemsSource = _ChatEmoji.EmojisListBox5;
EmojisListBox6.ItemsSource = _ChatEmoji.EmojisListBox6;
EmojisListBox7.ItemsSource = _ChatEmoji.EmojisListBox7;
TabItem1.Header = _emojii.TabItem1;
TabItem2.Header = _emojii.TabItem2;
TabItem3.Header = _emojii.TabItem3;
TabItem4.Header = _emojii.TabItem4;
TabItem5.Header = _emojii.TabItem5;
TabItem6.Header = _emojii.TabItem6;
TabItem7.Header = _emojii.TabItem7;
_EmojiListBoxes.AddRange(
new List<ListBox>
{
EmojisListBox1,
EmojisListBox2,
EmojisListBox3,
EmojisListBox4,
EmojisListBox5,
EmojisListBox6,
EmojisListBox7
}
);
TabItem1.Header = _ChatEmoji.TabItem1;
TabItem2.Header = _ChatEmoji.TabItem2;
TabItem3.Header = _ChatEmoji.TabItem3;
TabItem4.Header = _ChatEmoji.TabItem4;
TabItem5.Header = _ChatEmoji.TabItem5;
TabItem6.Header = _ChatEmoji.TabItem6;
TabItem7.Header = _ChatEmoji.TabItem7;
}
private void OnEmojiClick(object sender, RoutedEventArgs e)
{
foreach (Object selecteditem in EmojisListBox1.SelectedItems)
foreach(var emojiListBox in _EmojiListBoxes)
{
DirectoryListing Item = selecteditem as DirectoryListing;
if (Item.EmojiCode != "")
foreach(var selectedItem in emojiListBox.SelectedItems)
{
ÜbergebeEmojiAnChatView(Item.EmojiCode, Item.Pfad);
var directoryListing = selectedItem as DirectoryListing;
if(!string.IsNullOrWhiteSpace(directoryListing?.EmojiCode))
{
PassEmojiToChatMainControl(directoryListing.EmojiCode);
}
}
emojiListBox.SelectedIndex = -1;
}
foreach (Object selecteditem in EmojisListBox2.SelectedItems)
{
DirectoryListing Item = selecteditem as DirectoryListing;
if (Item.EmojiCode != "")
{
ÜbergebeEmojiAnChatView(Item.EmojiCode, Item.Pfad);
}
}
foreach (Object selecteditem in EmojisListBox3.SelectedItems)
{
DirectoryListing Item = selecteditem as DirectoryListing;
if (Item.EmojiCode != "")
{
ÜbergebeEmojiAnChatView(Item.EmojiCode, Item.Pfad);
}
}
foreach (Object selecteditem in EmojisListBox4.SelectedItems)
{
DirectoryListing Item = selecteditem as DirectoryListing;
if (Item.EmojiCode != "")
{
ÜbergebeEmojiAnChatView(Item.EmojiCode, Item.Pfad);
}
}
foreach (Object selecteditem in EmojisListBox5.SelectedItems)
{
DirectoryListing Item = selecteditem as DirectoryListing;
if (Item.EmojiCode != "")
{
ÜbergebeEmojiAnChatView(Item.EmojiCode, Item.Pfad);
}
}
foreach (Object selecteditem in EmojisListBox6.SelectedItems)
{
DirectoryListing Item = selecteditem as DirectoryListing;
if (Item.EmojiCode != "")
{
ÜbergebeEmojiAnChatView(Item.EmojiCode, Item.Pfad);
}
}
foreach (Object selecteditem in EmojisListBox7.SelectedItems)
{
DirectoryListing Item = selecteditem as DirectoryListing;
if (Item.EmojiCode != "")
{
ÜbergebeEmojiAnChatView(Item.EmojiCode, Item.Pfad);
}
}
EmojisListBox1.SelectedIndex = -1;
EmojisListBox2.SelectedIndex = -1;
EmojisListBox3.SelectedIndex = -1;
EmojisListBox4.SelectedIndex = -1;
EmojisListBox5.SelectedIndex = -1;
EmojisListBox6.SelectedIndex = -1;
EmojisListBox7.SelectedIndex = -1;
// ChatEmojiView.Activate();
}
public void ÜbergebeEmojiAnChatView(string emojiicode, string muell)
public void PassEmojiToChatMainControl(string emojiCode)
{
try
{
Dispatcher.Invoke(
DispatcherPriority.Normal,
(ThreadStart)delegate
(ThreadStart) delegate
{
chatView.Chatbox.Focus();
chatView.Chatbox.Text += " " + emojiicode;
chatView.Chatbox.SelectionStart = chatView.Chatbox.Text.Length;
_ChatMainControl.Chatbox.Focus();
_ChatMainControl.Chatbox.Text += emojiCode;
_ChatMainControl.Chatbox.SelectionStart = _ChatMainControl.Chatbox.Text.Length;
});
}
catch (Exception e)
@@ -165,6 +97,5 @@ namespace ChatController
MessageBox.Show(e.Message);
}
}
}
}

View File

@@ -3,31 +3,51 @@ using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;
using ChatController.Utilities;
using static System.Windows.HorizontalAlignment;
namespace ChatController.ChatKlassen
{
public class ChatMessage
{
public int TimeStringMaxWidth => IsSeparator ? int.MaxValue : 350;
public int MessageMaxWidth => IsSeparator ? int.MaxValue : 500;
public string SeparatorTimeString => SendTime.ToString("dd. MMMM yyyy");
public bool IsSeparator { get; set; }
public long FileSize { get; set; }
// Separator
public ChatMessage(DateTime sendTime)
{
Id = Guid.NewGuid();
IsSeparator = true;
SendTime = sendTime;
MessageType = ChatMessageType.Separator;
}
//Chat-Ansicht
public ChatMessage(string username, string message, DateTime sendtime, bool isme, long pGroupId, long fileSize)
{
Id = Guid.NewGuid();
Username = username;
UserMessage = message;
SendTime = sendtime;
IsMyMessage = isme;
Farbgebung(isme);
VisibilityRegelung(IsHyperlink(message) ? "HyperlinkMessage" : "Message");
GroupId = pGroupId;
MessageType = IsHyperlink(message) ? ChatMessageType.Hyperlink : ChatMessageType.Message;
}
// Image-Ansicht
public ChatMessage(string username, string message, DateTime sendtime, bool isme, ImageSource image, string originalImage, string imageName, long pGroupId, long fileSize)
{
Id = Guid.NewGuid();
Username = username;
UserMessage = message;
SendTime = sendtime;
@@ -37,101 +57,34 @@ namespace ChatController.ChatKlassen
OriginalImage = originalImage;
OriginalImageName = imageName;
Farbgebung(isme);
VisibilityRegelung("Image");
GroupId = pGroupId;
MessageType = ChatMessageType.Image;
}
//Dokumenten-Ansicht
public ChatMessage(string pUsername, string pMessageText, DateTime pSendTime, string pSmallerImagePath, bool pIsLoggedInUsersMessage, string pUrl, long pGroupId, long fileSize)
{
Username = pUsername;
Id = Guid.NewGuid();
Username = pUsername;
UserMessage = pMessageText;
SendTime = pSendTime;
SendTime = pSendTime;
IsMyMessage = pIsLoggedInUsersMessage;
FilePath = pUrl;
Farbgebung(pIsLoggedInUsersMessage);
Thumbnail = Utilities.Utils.CreateImageSourceFromPath(pSmallerImagePath);
Thumbnail = Utils.CreateImageSourceFromPath(pSmallerImagePath);
VisibilityRegelung("Dokumente");
GroupId = pGroupId;
MessageType = ChatMessageType.Document;
}
public ChatMessageType MessageType { get; }
public ImageSource Thumbnail { get; }
private void Farbgebung(bool isme)
{
if (isme)
{
ChatColor = new BrushConverter().ConvertFromString("#ff5e00") as SolidColorBrush;
Posi = "Right";
}
else
{
ChatColor = new BrushConverter().ConvertFromString("#FFFFFF") as SolidColorBrush; //"#cccccc"
Posi = "Left";
}
_farbeRechtsColor = new BrushConverter().ConvertFromString("#505050") as SolidColorBrush;
_farbeLinksColor = new BrushConverter().ConvertFromString("#505050") as SolidColorBrush;
}
private void VisibilityRegelung(string Ansicht)
{
switch (Ansicht)
{
case "Message":
ChatVisibility = Visibility.Visible;
HyperlinkVisibility = Visibility.Collapsed;
_pictureVisibility = Visibility.Collapsed;
DokumentVisibility = Visibility.Collapsed;
_gifPictureVisibility = Visibility.Collapsed;
_picturePlaceHolderVisibility = Visibility.Collapsed;
break;
case "HyperlinkMessage":
HyperlinkVisibility = Visibility.Visible;
ChatVisibility = Visibility.Collapsed;
_pictureVisibility = Visibility.Collapsed;
DokumentVisibility = Visibility.Collapsed;
_gifPictureVisibility = Visibility.Collapsed;
_picturePlaceHolderVisibility = Visibility.Collapsed;
break;
case "Image":
_pictureVisibility = Visibility.Visible;
ChatVisibility = Visibility.Collapsed;
HyperlinkVisibility = Visibility.Collapsed;
DokumentVisibility = Visibility.Collapsed;
_picturePlaceHolderVisibility = Visibility.Collapsed;
break;
case "Default_Image":
_picturePlaceHolderVisibility = Visibility.Visible;
_pictureVisibility = Visibility.Collapsed;
ChatVisibility = Visibility.Collapsed;
HyperlinkVisibility = Visibility.Collapsed;
DokumentVisibility = Visibility.Collapsed;
break;
case "Dokumente":
DokumentVisibility = Visibility.Visible;
_pictureVisibility = Visibility.Collapsed;
ChatVisibility = Visibility.Collapsed;
HyperlinkVisibility = Visibility.Collapsed;
_picturePlaceHolderVisibility = Visibility.Collapsed;
break;
}
}
private static readonly Regex UrlRegex = new Regex(@"(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~/|/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&amp;(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?");
private static readonly Regex _UrlRegex = new Regex(@"(?#Protocol)^(http(?:s?)\:(\/\/|\\\\)|(w){3}(2|3)?\.{1})(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&amp;(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?");
public static bool IsHyperlink(string word)
{
@@ -144,7 +97,7 @@ namespace ChatController.ChatKlassen
{
if (word.IndexOfAny(@":.\/".ToCharArray()) != -1)
{
if (UrlRegex.IsMatch(word))
if (_UrlRegex.IsMatch(word))
{
var uri = new Uri(word, UriKind.RelativeOrAbsolute);
@@ -173,97 +126,96 @@ namespace ChatController.ChatKlassen
}
public bool IsMyMessage { get; set; }
public string Username { get; }
public string UserMessage { get; }
public DateTime SendTime { get; }
public string UserTimeStringLeft => IsMyMessage ? null : Username;
public string UserTimeStringRight => SendTimeString;
public string SendTimeString => SendTime.Date == DateTime.Today ? $"Heute {SendTime:HH:mm}" : SendTime.ToString("dd.MMM HH:mm");
public string SendTimeString => SendTime.Date == DateTime.Today ? $"Heute {SendTime:HH:mm}" : SendTime.ToString("dd. MMM HH:mm");
public Brush ChatColor { get; private set; }
public string Posi { get; private set; }
public Brush BorderBrush => IsSeparator ? new SolidColorBrush(Colors.Transparent) : IsMyMessage ? new SolidColorBrush(Color.FromRgb(255, 90, 0)) : new SolidColorBrush(Color.FromRgb(229, 229, 229));
public Brush HighlightedBorderBrush => IsSeparator ? new SolidColorBrush(Colors.Transparent) : IsMyMessage ? new SolidColorBrush(Color.FromRgb(255, 153, 153)) : new SolidColorBrush(Color.FromRgb(247, 247, 247));
public Brush Foreground => new BrushConverter().ConvertFromString("#505050") as SolidColorBrush;
public HorizontalAlignment HorizontalAlignmentValue => IsSeparator ? HorizontalAlignment.Stretch : IsMyMessage ? Right : Left;
public string OriginalImage { get; }
public string OriginalImageName { get; }
public Visibility ChatVisibility { get; set; }
public Visibility HyperlinkVisibility { get; set; }
public Visibility ChatVisibility => MessageType == ChatMessageType.Message ? Visibility.Visible : Visibility.Collapsed;
private Visibility _pictureVisibility;
public Visibility PictureVisibility
{
get => _pictureVisibility;
set
{
_pictureVisibility = value;
OnPropertyChanged(nameof(PictureVisibility));
}
}
public Visibility HyperlinkVisibility => MessageType == ChatMessageType.Hyperlink ? Visibility.Visible : Visibility.Collapsed;
private Visibility _picturePlaceHolderVisibility;
public Visibility PicturePlaceHolderVisibility
{
get => _picturePlaceHolderVisibility;
set
{
_picturePlaceHolderVisibility = value;
OnPropertyChanged(nameof(PicturePlaceHolderVisibility));
}
}
public Visibility PictureVisibility => MessageType == ChatMessageType.Image ? Visibility.Visible : Visibility.Collapsed;
private Visibility _gifPictureVisibility;
public Visibility GifPictureVisibility
{
get => _gifPictureVisibility;
set
{
_gifPictureVisibility = value;
OnPropertyChanged(nameof(GifPictureVisibility));
}
}
public Visibility PicturePlaceHolderVisibility => MessageType == ChatMessageType.DefaultImage ? Visibility.Visible : Visibility.Collapsed;
public Visibility DokumentVisibility => MessageType == ChatMessageType.Document ? Visibility.Visible : Visibility.Collapsed;
public Visibility DokumentVisibility { get; set; }
public ImageSource ImageSources { get; }
public object FilePath { get; }
public long? ChatMessageOid { get; private set; }
private Brush _farbeLinksColor;
public Brush FarbeLinksColor
{
get => _farbeLinksColor;
set
{
_farbeLinksColor = value;
OnPropertyChanged(nameof(FarbeLinksColor));
}
}
private Brush _farbeRechtsColor;
public Brush FarbeRechtsColor
{
get => _farbeRechtsColor;
set
{
_farbeRechtsColor = value;
OnPropertyChanged(nameof(FarbeRechtsColor));
}
}
public long GroupId { get; }
public event PropertyChangedEventHandler PropertyChanged;
public Guid Id { get; }
public Uri UserMessageAsUri
{
get
{
if(IsHyperlink(UserMessage))
{
if(!UserMessage.Contains("http"))
{
return new Uri("http://" + UserMessage);
}
}
return null;
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public override bool Equals(object obj)
{
if(obj is ChatMessage message)
{
if(message.IsSeparator && IsSeparator)
{
return SendTime == message.SendTime;
}
return message.Id.Equals(Id);
}
return false;
}
public override string ToString()
{
return SendTime.ToString("dd.MM.yyyy HH:mm:ss");
}
public override int GetHashCode()
{
return Id.GetHashCode() << 16;
}
}
}

View File

@@ -1,12 +1,14 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Media;
using ChatController.LoginKlassen;
using static System.String;
using Brush = System.Windows.Media.Brush;
namespace ChatController.ChatKlassen
{
public class Contact
public class Contact : INotifyPropertyChanged
{
public string Name { get; }
@@ -24,14 +26,14 @@ namespace ChatController.ChatKlassen
public bool IsNewMessage { get; set; }
private Brush _color;
private Brush _Color;
public Brush Color
{
get => _color;
get => _Color;
set
{
_color = value;
_Color = value;
OnPropertyChanged(nameof(Color));
}
}
@@ -47,11 +49,11 @@ namespace ChatController.ChatKlassen
if (_HasUnreadMessages)
{
_color = new BrushConverter().ConvertFromString("#ff5e00") as SolidColorBrush;
_Color = new BrushConverter().ConvertFromString("#ff5e00") as SolidColorBrush;
}
else
{
_color = new SolidColorBrush(Colors.Gray);
_Color = new SolidColorBrush(Colors.Gray);
}
OnPropertyChanged(nameof(HasUnreadMessages));
@@ -59,48 +61,93 @@ namespace ChatController.ChatKlassen
}
}
private Brush _ContactChatColor;
public Brush ContactChatColor
{
get => _ContactChatColor;
set
{
_ContactChatColor = value;
OnPropertyChanged(nameof(ContactChatColor));
}
}
public ImageSource Image { get; }
public DateTime TimeStamp { get; set; }
public int GroupId { get; set; }
public int UserOid { get; set; }
public string UserIdManage { get; set; }
public Contact(string pName, ImageSource pImage, GroupLatestMessage pLatestMessage, DateTime pTimeStamp, int pGroupId, string pUserIdManage, bool pOnlyEmployees, int pUserCount)
public bool IsChatMessageInputGridVisible { get; }
public Bitmap ProfilePicture { get; }
public Contact(string pName, GroupLatestMessage pLatestMessage, DateTime pTimeStamp, int pGroupId, string pUserIdManage, bool pOnlyEmployees, int pUserCount, bool isChatMessageInputGridVisible, string accentColorBrushString, Bitmap profilePicture, ImageSource image)
{
Name = pName;
ReceivedMessage = pLatestMessage;
Image = pImage;
TimeStamp = pTimeStamp;
GroupId = pGroupId;
UserIdManage = pUserIdManage;
Name = pName;
ReceivedMessage = pLatestMessage;
TimeStamp = pTimeStamp;
GroupId = pGroupId;
UserIdManage = pUserIdManage;
HasUnreadMessages = false;
if (UserIdManage != null)
ProfilePicture = profilePicture;
IsChatMessageInputGridVisible = isChatMessageInputGridVisible;
AccentColorBrush = new BrushConverter().ConvertFromString($"#{accentColorBrushString}") as SolidColorBrush ?? new SolidColorBrush(Colors.Black);
Image = image;
}
private sealed class ContactEqualityComparer : IEqualityComparer<Contact>
{
public bool Equals(Contact x, Contact y)
{
_ContactChatColor = new BrushConverter().ConvertFromString("#3B7799") as SolidColorBrush;
if(ReferenceEquals(x, y))
{
return true;
}
if(x is null)
{
return false;
}
if(y is null)
{
return false;
}
if(x.GetType() != y.GetType())
{
return false;
}
return x.Name == y.Name &&
x.IsNewMessage == y.IsNewMessage &&
Equals(x.ProfilePicture, y.ProfilePicture) &&
x.TimeStamp.Equals(y.TimeStamp) &&
x.GroupId == y.GroupId &&
x.UserOid == y.UserOid &&
x.UserIdManage == y.UserIdManage &&
x.IsChatMessageInputGridVisible == y.IsChatMessageInputGridVisible;
}
else if (pOnlyEmployees && pUserCount > 2)
public int GetHashCode(Contact obj)
{
_ContactChatColor = new BrushConverter().ConvertFromString("#45993B") as SolidColorBrush;
}
else
{
_ContactChatColor = new BrushConverter().ConvertFromString("#000000") as SolidColorBrush;
unchecked
{
var hashCode = obj.Name != null ? obj.Name.GetHashCode() : 0;
hashCode = (hashCode * 397) ^ obj.IsNewMessage.GetHashCode();
hashCode = (hashCode * 397) ^ (obj.ProfilePicture != null ? obj.ProfilePicture.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ obj.TimeStamp.GetHashCode();
hashCode = (hashCode * 397) ^ obj.GroupId;
hashCode = (hashCode * 397) ^ obj.UserOid;
hashCode = (hashCode * 397) ^ (obj.UserIdManage != null ? obj.UserIdManage.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ obj.IsChatMessageInputGridVisible.GetHashCode();
return hashCode;
}
}
}
public SolidColorBrush AccentColorBrush { get; }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)

View File

@@ -1,29 +0,0 @@
using System;
using System.Windows.Media;
namespace ChatController.ChatKlassen
{
public class CurrentContact
{
public Contact Contact { get; set; }
public string Name { get; }
public ImageSource Image { get; }
public DateTime TimeStamp { get; set; }
public long GroupId { get; set; }
public string UserIdManage { get; set; }
public CurrentContact(Contact pContact)
{
if(pContact != null) {
Contact = pContact;
Image = pContact.Image;
TimeStamp = pContact.TimeStamp;
Name = pContact.Name;
UserIdManage = pContact.UserIdManage;
GroupId = pContact.GroupId;
}
}
}
}

View File

@@ -2,41 +2,46 @@
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"
xmlns:local="clr-namespace:ChatController"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:converter="clr-namespace:ChatController.Converter"
xmlns:chatKlassen="clr-namespace:ChatController.ChatKlassen"
mc:Ignorable="d" x:Name="ChatControlling"
d:DesignHeight="300" d:DesignWidth="600"
SnapsToDevicePixels="True" >
<UserControl.Resources>
<SolidColorBrush x:Key="DarkBackColor" Color="#FFA9B8C2" />
<SolidColorBrush x:Key="LightBackColor" Color="#E8EFF4" />
<SolidColorBrush x:Key="ButtonForeground" Color="#ff5e00" />
<Style x:Key="MainNavigationScrollViewer" TargetType="{x:Type ScrollViewer}">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ScrollViewer}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
Loaded="ChatMainControl_OnLoaded"
SnapsToDevicePixels="True" d:DataContext="{d:DesignData ChatMainControl}">
<UserControl.Resources>
<converter:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
<converter:StringEmptyToVisibilityConverter x:Key="StringEmptyToVisibilityConverter" />
<converter:StringToBoolConverter x:Key="StringToBoolConverter" />
<ScrollContentPresenter Grid.Column="0"/>
<SolidColorBrush x:Key="DarkBackColor" Color="#FFA9B8C2" />
<SolidColorBrush x:Key="LightBackColor" Color="#E8EFF4" />
<SolidColorBrush x:Key="ButtonForeground" Color="#ff5e00" />
<ScrollBar Name="PART_VerticalScrollBar"
<Style x:Key="MainNavigationScrollViewer" TargetType="{x:Type ScrollViewer}">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ScrollViewer}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollContentPresenter Grid.Column="0"/>
<ScrollBar Name="PART_VerticalScrollBar"
Value="{TemplateBinding VerticalOffset}"
Maximum="{TemplateBinding ScrollableHeight}"
ViewportSize="{TemplateBinding ViewportHeight}"
Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"
Grid.Row="0" Grid.Column="1"/>
<ScrollBar Name="PART_HorizontalScrollBar"
<ScrollBar Name="PART_HorizontalScrollBar"
Orientation="Horizontal"
Grid.Row="1"
Grid.Column="0"
@@ -45,288 +50,385 @@
ViewportSize="{TemplateBinding ViewportWidth}"
Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ControlTemplate x:Key="ContactListBoxTemplate" TargetType="{x:Type ListBox}">
<Border x:Name="Bd" SnapsToDevicePixels="True" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}">
<ScrollViewer Focusable="False" Padding="{TemplateBinding Padding}" Style="{StaticResource MainNavigationScrollViewer}" HorizontalScrollBarVisibility="Disabled">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</ScrollViewer>
</Border>
</ControlTemplate>
<Style x:Key="ContactListStyle" TargetType="{x:Type ListBox}">
<Setter Property="Template" Value="{StaticResource ContactListBoxTemplate}" />
</Style>
<Style x:Key="ContactListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="HorizontalContentAlignment" Value="{Binding Path=HorizontalContentAlignment, RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type ItemsControl}, Mode=FindAncestor}}" />
<Setter Property="VerticalContentAlignment" Value="{Binding Path=VerticalContentAlignment, RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type ItemsControl}, Mode=FindAncestor}}" />
<Setter Property="Margin" Value="0,0,0,0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<Border x:Name="ItemBorder" MinHeight="20" Background="White" BorderThickness="0,0,0,1" BorderBrush="{StaticResource LightBackColor}">
</Border>
<Border x:Name="ItemContent" MinHeight="20">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="5,3,5,3" OpacityMask="{x:Null}" SnapsToDevicePixels="True">
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ControlTemplate x:Key="ContactListBoxTemplate" TargetType="{x:Type ListBox}">
<Border x:Name="Bd" SnapsToDevicePixels="True" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}">
<ScrollViewer Focusable="False" Padding="{TemplateBinding Padding}" Style="{StaticResource MainNavigationScrollViewer}" HorizontalScrollBarVisibility="Disabled">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</ScrollViewer>
</Border>
</ControlTemplate>
<Style x:Key="ContactListStyle" TargetType="{x:Type ListBox}">
<Setter Property="Template" Value="{StaticResource ContactListBoxTemplate}" />
</Style>
<Style x:Key="ContactListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="HorizontalContentAlignment" Value="{Binding Path=HorizontalContentAlignment, RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type ItemsControl}, Mode=FindAncestor}}" />
<Setter Property="VerticalContentAlignment" Value="{Binding Path=VerticalContentAlignment, RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type ItemsControl}, Mode=FindAncestor}}" />
<Setter Property="Margin" Value="0,0,0,0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<Border x:Name="ItemBorder" MinHeight="20" Background="White" BorderThickness="0,0,0,1" BorderBrush="{StaticResource LightBackColor}">
</Border>
<Border x:Name="ItemContent" MinHeight="20">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="5,3,5,3" OpacityMask="{x:Null}" SnapsToDevicePixels="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="7"/>
<ColumnDefinition Width="35"/>
<ColumnDefinition Width="7"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="7"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Ellipse Grid.Column="1" Width='32' Height='32' RenderOptions.BitmapScalingMode="HighQuality">
<Ellipse.Fill>
<ImageBrush ImageSource='{Binding Image}' Stretch='UniformToFill' RenderOptions.BitmapScalingMode="HighQuality" />
</Ellipse.Fill>
</Ellipse>
<Grid Grid.Column="3" >
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Path=Name, FallbackValue=FirstName}" Foreground="{Binding Path=AccentColorBrush}" FontSize="16" Margin="1" />
<TextBlock Text="{Binding Path=ReceivedMessage.Text}" Grid.Row="1" FontSize="14" Foreground="{Binding Path=Color}" Margin="1" />
</Grid>
</Grid>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" TargetName="ItemBorder" Value="{StaticResource DarkBackColor}" />
</Trigger>
<Trigger Property="ListBoxItem.IsSelected" Value="True">
<Setter Property="Background" TargetName="ItemBorder" Value="{StaticResource DarkBackColor}" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ListBoxItem.IsSelected" Value="True" />
<Condition Property="Selector.IsSelectionActive" Value="False" />
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="ItemBorder" Value="{StaticResource DarkBackColor}" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Gruppensuchtemplate -->
<ControlTemplate x:Key="SearchTextBoxTemplate" TargetType="{x:Type TextBox}">
<Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="2,2,2,2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ScrollViewer Grid.Column="1" x:Name="PART_ContentHost" Margin="0,2,0,0" />
<Canvas Grid.Column="0" Width="14" Margin="3,4,2,2">
<Ellipse Stroke="#FFA0A0A0" Height="10" Width="10" StrokeThickness="2" Fill="{x:Null}" />
<Line Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FFA0A0A0" Canvas.Left="6" Canvas.Top="7.4" Y1="0" Y2="5" StrokeThickness="3" X2="4" />
</Canvas>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<!-- /Gruppensuchtemplate -->
</UserControl.Resources>
<Grid x:Name="RootGrid">
<Border x:Name="rootBorder" Background="{StaticResource DarkBackColor}" Padding="0" Margin="0" BorderThickness="0">
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Column="0" Grid.Row="0" >
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="7"/>
<ColumnDefinition Width="35"/>
<ColumnDefinition Width="7"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="7"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Ellipse Grid.Column="1" Width='32' Height='32' RenderOptions.BitmapScalingMode="HighQuality">
<Ellipse.Fill>
<ImageBrush ImageSource='{Binding Image}' Stretch='Fill' RenderOptions.BitmapScalingMode="HighQuality" />
</Ellipse.Fill>
</Ellipse>
<Grid Grid.Column="3" >
<Grid Grid.Column="0" Grid.Row="0" >
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Path=Name, FallbackValue=FirstName}" Foreground="{Binding Path=ContactChatColor}" FontSize="16" Margin="1" />
<TextBlock Text="{Binding Path=ReceivedMessage.Text}" Grid.Row="1" FontSize="14" Foreground="{Binding Path=Color}" Margin="1" />
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel x:Name="ReloadGruppen" Grid.Row="0" Grid.Column="1" Height="25" Width="25" HorizontalAlignment="Right" Orientation="Horizontal" VerticalAlignment="Center" Visibility="Visible" Margin="0,0,3,0">
<Button Background="Transparent" HorizontalAlignment="Right" BorderThickness="0" VerticalAlignment="Center" VerticalContentAlignment="Center" Width="25" Height="25" Click="ButtonReloadGruppen_OnClick" >
<Image ToolTip="Gruppen Aktualisieren" Margin="0,0,0,0" Width="20" Height="20" Source="pack://application:,,,/ChatController;component/Ressourcen/SymbolRefresh32.png" RenderOptions.BitmapScalingMode="HighQuality" HorizontalAlignment="Center" />
</Button>
</StackPanel>
<TextBox Grid.Column="0" x:Name="Suche" Height="22" HorizontalAlignment="Stretch" Margin="5" TabIndex="0" Template="{DynamicResource SearchTextBoxTemplate}" BorderThickness="0,0,0,0" TextChanged="Suche_OnTextChanged" />
</Grid>
<Grid Grid.Column="0" Grid.Row="1" >
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListView x:Name="Clientlist" HorizontalAlignment="Stretch" Grid.Row="0" Grid.Column="0" VerticalAlignment="Stretch" BorderThickness="0" Background="White"
ItemsSource="{Binding ContactList, UpdateSourceTrigger=PropertyChanged}"
ItemContainerStyle="{StaticResource ContactListBoxItemStyle}" SelectionChanged="Clientlist_OnSelectionChanged" Style="{StaticResource ContactListStyle}">
</ListView>
</Grid>
</Grid>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" TargetName="ItemBorder" Value="{StaticResource DarkBackColor}" />
</Trigger>
<Trigger Property="ListBoxItem.IsSelected" Value="True">
<Setter Property="Background" TargetName="ItemBorder" Value="{StaticResource DarkBackColor}" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ListBoxItem.IsSelected" Value="True" />
<Condition Property="Selector.IsSelectionActive" Value="False" />
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="ItemBorder" Value="{StaticResource DarkBackColor}" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ControlTemplate x:Key="SearchTextBoxTemplate" TargetType="{x:Type TextBox}">
<Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="2,2,2,2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ScrollViewer Grid.Column="1" x:Name="PART_ContentHost" Margin="0,2,0,0" />
<Canvas Grid.Column="0" Width="14" Margin="3,4,2,2">
<Ellipse Stroke="#FFA0A0A0" Height="10" Width="10" StrokeThickness="2" Fill="{x:Null}" />
<Line Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FFA0A0A0" Canvas.Left="6" Canvas.Top="7.4" Y1="0" Y2="5" StrokeThickness="3" X2="4" />
</Canvas>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</UserControl.Resources>
<Grid>
<Border x:Name="rootBorder" Background="{StaticResource DarkBackColor}" Padding="0" Margin="0" BorderThickness="0">
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Column="0" Grid.Row="0" >
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Grid.Row="0" >
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel x:Name="ReloadGruppen" Grid.Row="0" Grid.Column="1" Height="25" Width="25" HorizontalAlignment="Right" Orientation="Horizontal" VerticalAlignment="Center" Visibility="Visible" Margin="0,0,3,0">
<Button Background="Transparent" HorizontalAlignment="Right" BorderThickness="0" VerticalAlignment="Center" VerticalContentAlignment="Center" Width="25" Height="25" Click="ButtonReloadGruppen_OnClick" >
<Image ToolTip="Gruppen Aktualisieren" Margin="0,0,0,0" Width="20" Height="20" Source="pack://application:,,,/ChatController;component/Ressourcen/SymbolRefresh32.png" RenderOptions.BitmapScalingMode="HighQuality" HorizontalAlignment="Center" />
</Button>
</StackPanel>
<TextBox Grid.Column="0" x:Name="Suche" Height="22" HorizontalAlignment="Stretch" Margin="5" TabIndex="0" Template="{DynamicResource SearchTextBoxTemplate}" BorderThickness="0,0,0,0" TextChanged="Suche_OnTextChanged" />
</Grid>
<Grid Grid.Column="0" Grid.Row="1" >
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListView x:Name="Clientlist" HorizontalAlignment="Stretch" Grid.Row="0" Grid.Column="0" VerticalAlignment="Stretch" BorderThickness="0" Background="White"
ItemContainerStyle="{StaticResource ContactListBoxItemStyle}" SelectionChanged="Clientlist_OnSelectionChanged" Style="{StaticResource ContactListStyle}">
</ListView>
</Grid>
</Grid>
<Grid Grid.Column="1" Grid.Row="0" x:Name="GridRechts">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*" />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox x:Name="AktChatUserList" HorizontalAlignment="Left" Margin="0" Grid.Row="0" Background="Transparent" BorderBrush="Transparent" VerticalAlignment="Bottom" ItemTemplate="{DynamicResource DataTemplate2}" MouseDoubleClick="AktChatUser_OnMouseDoubleClick" >
<ListBox.Resources>
<DataTemplate x:Key="DataTemplate2">
<Grid>
<Grid Grid.Column="1" Grid.Row="0" x:Name="GridRechts">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="10*" />
<RowDefinition Height="50"/>
<RowDefinition Height="*" />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Ellipse Width='40' Height='40' VerticalAlignment="Center" RenderOptions.BitmapScalingMode="HighQuality">
<Ellipse.Fill >
<ImageBrush ImageSource='{Binding Image}' Stretch='Fill'/>
</Ellipse.Fill>
</Ellipse>
<TextBlock Grid.Column="1" Margin="8" Text="{Binding Path=Name, FallbackValue=FirstName}" FontSize="16" />
</Grid>
</DataTemplate>
</ListBox.Resources>
</ListBox>
<ListBox x:Name="ChatListBox" HorizontalAlignment="Stretch" ScrollViewer.CanContentScroll="False" VerticalAlignment="Stretch" Grid.Row="1" VirtualizingStackPanel.IsVirtualizing="True" BorderThickness="0"
VirtualizingStackPanel.VirtualizationMode="Recycling" SelectionMode="Extended" MouseDoubleClick="Chat_OnMouseDoubleClick" ScrollViewer.ScrollChanged="Chat_OnScrollChanged" Background="{StaticResource LightBackColor}"
ContextMenuOpening="Chat_OnContextMenuOpening" Padding="20">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="{Binding Posi}" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Border BorderBrush="{Binding ChatColor}" BorderThickness="1,1,1,1" CornerRadius="8,8,8,8" Background="{Binding ChatColor}">
<DockPanel MinHeight="15" Margin="5" LastChildFill="True" Background="{Binding ChatColor}">
<StackPanel DockPanel.Dock="Bottom" Visibility="{Binding ChatVisibility}">
<TextBlock VerticalAlignment="Center" Text="{Binding UserMessage}" MinWidth="0" MaxWidth="500" TextWrapping="Wrap" FontSize="14"/>
</StackPanel>
<StackPanel DockPanel.Dock="Bottom" Visibility="{Binding HyperlinkVisibility}" >
<TextBlock>
<Hyperlink NavigateUri="{Binding UserMessage}" RequestNavigate="Hyperlink_OnRequestNavigate" >
<TextBlock VerticalAlignment="Center" Text="{Binding UserMessage}" MinWidth="0" MaxWidth="500" TextWrapping="Wrap" FontSize="14"/>
</Hyperlink>
</TextBlock>
</StackPanel>
<DockPanel DockPanel.Dock="Bottom" Visibility="{Binding PictureVisibility}" >
<StackPanel Orientation="Vertical">
<Image MaxHeight="200" MaxWidth="300" Source="{Binding ImageSources}" x:Name="imgChatMessage" Stretch="None"/>
<TextBlock Text="{Binding UserMessage}" VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="14"/>
</StackPanel>
</DockPanel>
<DockPanel DockPanel.Dock="Bottom" Visibility="{Binding PicturePlaceHolderVisibility}" >
<StackPanel Orientation="Vertical">
<Image Source="pack://application:,,,/ChatController;component/Ressourcen/ClipboardDisabled.png" Stretch="None" />
<TextBlock Text="{Binding UserMessage}" VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="14" />
</StackPanel>
</DockPanel>
<DockPanel DockPanel.Dock="Bottom" Visibility="{Binding DokumentVisibility}" >
<StackPanel Orientation="Vertical">
<Image ToolTip="Dokument öffnen" Height="100" Width="150" Source="{Binding Path=Thumbnail}" Stretch="Uniform" VerticalAlignment="Center" HorizontalAlignment="Center" />
<TextBlock Margin="2,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{Binding UserMessage}" FontSize="14"/>
</StackPanel>
</DockPanel>
<StackPanel DockPanel.Dock="Left" Margin="0,0,0,0">
<TextBlock Text="{Binding UserTimeStringLeft}" MaxWidth="350" FontSize="11" HorizontalAlignment="Left" TextAlignment="Left" VerticalAlignment="Center" Foreground="{Binding FarbeRechtsColor}" />
</StackPanel>
<StackPanel DockPanel.Dock="Right" Margin="5,0,0,5">
<TextBlock Text="{Binding UserTimeStringRight}" MaxWidth="350" FontSize="11" HorizontalAlignment="Right" TextAlignment="Right" VerticalAlignment="Center" Foreground="{Binding FarbeRechtsColor}" />
</StackPanel>
</DockPanel>
</Border>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid Grid.Row="2" Margin="10" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ListBox x:Name="AktChatUserList" HorizontalAlignment="Left" Margin="0" Grid.Row="0" Background="Transparent" BorderBrush="Transparent" VerticalAlignment="Bottom" ItemTemplate="{DynamicResource DataTemplate2}" MouseDoubleClick="AktChatUser_OnMouseDoubleClick" >
<ListBox.Resources>
<DataTemplate x:Key="DataTemplate2" DataType="chatKlassen:Contact">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="10*" />
</Grid.RowDefinitions>
<Grid Grid.Column="0" MinHeight="25" Margin="0,0,3,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<Ellipse Width='40' Height='40' VerticalAlignment="Center" RenderOptions.BitmapScalingMode="HighQuality">
<Ellipse.Fill >
<ImageBrush ImageSource='{Binding Image}' Stretch="UniformToFill"/>
</Ellipse.Fill>
</Ellipse>
<TextBox x:Name="Chatbox" HorizontalAlignment="Stretch" Grid.Column="0" Grid.ColumnSpan="3" TextWrapping="Wrap" Text="Nachricht schreiben" VerticalScrollBarVisibility="Hidden" MaxHeight="200" Visibility="Visible" BorderThickness="0,0,0,0"
VerticalContentAlignment="Center" MinHeight="25" Padding="10,0,60,0" ToolTip="Schreiben Sie hier eine Nachricht hinein" Foreground="DarkGray" VerticalAlignment="Center" GotFocus="Chatbox_OnGotFocus" KeyDown="Chatbox_OnKeyDownHandler">
<TextBox.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="2"/>
</Style>
</TextBox.Resources>
</TextBox>
<TextBlock Grid.Column="1" Margin="8" Text="{Binding Path=Name, FallbackValue=FirstName}" FontSize="16" Foreground="{Binding AccentColorBrush}" />
</Grid>
</DataTemplate>
</ListBox.Resources>
</ListBox>
<StackPanel Grid.Column="1" Grid.ColumnSpan="2" Margin="1" Orientation="Horizontal">
<Button Margin="1,0,0,0" x:Name="MediaButton" Background="Transparent" Height="25" Width="28" BorderThickness="0" Padding="0" VerticalAlignment="Bottom" ToolTip="Datei einfügen" Click="MediaButton_OnClick" >
<Image Height="22" Width="22" Source='pack://application:,,,/ChatController;component/Ressourcen/paperclip2.png' RenderOptions.BitmapScalingMode="HighQuality" HorizontalAlignment="Center"/>
</Button>
<Button Width="28" Height="25" BorderThickness="0" Background="Transparent" x:Name="EmojiButton" Margin="2,0,0,0" Padding="0" VerticalAlignment="Bottom" ToolTip="Emoji einfügen" Click="EmojiButton_OnClick">
<Image Height="24" Width="24" Source='pack://application:,,,/ChatController;component/Ressourcen/glucklicher.png' RenderOptions.BitmapScalingMode="HighQuality" HorizontalAlignment="Center" />
</Button>
</StackPanel>
</Grid>
<ListBox x:Name="ChatListBox" ItemsSource="{Binding CurrentChatMessages, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Stretch" ScrollViewer.CanContentScroll="False" VerticalAlignment="Stretch" Grid.Row="1"
VirtualizingStackPanel.IsVirtualizing="True" BorderThickness="0" VirtualizingStackPanel.VirtualizationMode="Recycling" SelectionMode="Extended"
MouseDoubleClick="Chat_OnMouseDoubleClick" ScrollViewer.ScrollChanged="Chat_OnScrollChanged" Background="{StaticResource LightBackColor}"
ContextMenuOpening="Chat_OnContextMenuOpening" Padding="20" d:DataContext="{d:DesignData ChatMessage}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="{Binding HorizontalAlignmentValue}" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Background" Value="Transparent"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1,1,1,1"
Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" CornerRadius="8" Background="{Binding BorderBrush}" >
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" TargetName="Bd" Value="{Binding HighlightedBorderBrush}"></Setter>
</Trigger>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true"/>
<Condition Property="Selector.IsSelectionActive" Value="false"/>
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="Bd" Value="{Binding BorderBrush}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}}"/>
<Setter TargetName="Bd" Property="CornerRadius" Value="8" />
<Setter TargetName="Bd" Property="BorderThickness" Value="1,1,1,1" />
</MultiTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true" />
<Condition Property="Selector.IsSelectionActive" Value="true" />
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="Bd" Value="{Binding HighlightedBorderBrush}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}}"/>
<Setter TargetName="Bd" Property="CornerRadius" Value="8" />
<Setter TargetName="Bd" Property="BorderThickness" Value="1" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="chatKlassen:ChatMessage">
<StackPanel>
<Border>
<Grid HorizontalAlignment="Stretch" Background="Transparent">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Separator Grid.Column="0" Visibility="{Binding IsSeparator, Converter={StaticResource BoolToVisibilityConverter}, ConverterParameter=reverse}" VerticalContentAlignment="Center" />
<Label Content="{Binding SeparatorTimeString}" HorizontalAlignment="Center" Grid.Column="1" Visibility="{Binding IsSeparator, Converter={StaticResource BoolToVisibilityConverter}, ConverterParameter=reverse}"></Label>
<Separator Grid.Column="2" Visibility="{Binding IsSeparator, Converter={StaticResource BoolToVisibilityConverter}, ConverterParameter=reverse}" />
<Button x:Name="SendButton" Content=" Senden " HorizontalAlignment="Stretch" Margin="2,0,0,0" Grid.Column="1" VerticalAlignment="Bottom" Click="SendButton_OnClick" Background="{StaticResource ButtonForeground}" Height="25" >
<Button.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="3"/>
<Setter Property="Padding" Value="1,1,1,1" />
</Style>
</Button.Resources>
</Button>
<DockPanel Grid.Column="0" Grid.ColumnSpan="3" MinHeight="15" Margin="5" LastChildFill="True"
Visibility="{Binding IsSeparator, Converter={StaticResource BoolToVisibilityConverter}}">
<StackPanel DockPanel.Dock="Bottom" Visibility="{Binding ChatVisibility}">
<TextBlock VerticalAlignment="Center" Text="{Binding UserMessage}" MinWidth="0" MaxWidth="{Binding MessageMaxWidth}" TextWrapping="Wrap" FontSize="14"/>
</StackPanel>
<StackPanel DockPanel.Dock="Bottom" Visibility="{Binding HyperlinkVisibility}" >
<TextBlock>
<Hyperlink NavigateUri="{Binding UserMessageAsUri}" RequestNavigate="Hyperlink_OnRequestNavigate" >
<TextBlock VerticalAlignment="Center" Text="{Binding UserMessage}" MinWidth="0" MaxWidth="{Binding MessageMaxWidth}" TextWrapping="Wrap" FontSize="14"/>
</Hyperlink>
</TextBlock>
</StackPanel>
<DockPanel DockPanel.Dock="Bottom" Visibility="{Binding PictureVisibility}" >
<StackPanel Orientation="Vertical">
<Image MaxWidth="300" Source="{Binding ImageSources}" x:Name="imgChatMessage" Stretch="UniformToFill"/>
<TextBlock Text="{Binding UserMessage}" VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="14"/>
</StackPanel>
</DockPanel>
<DockPanel DockPanel.Dock="Bottom" Visibility="{Binding PicturePlaceHolderVisibility}" >
<StackPanel Orientation="Vertical">
<Image Source="pack://application:,,,/ChatController;component/Ressourcen/ClipboardDisabled.png" Stretch="None" />
<TextBlock Text="{Binding UserMessage}" VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="14" />
</StackPanel>
</DockPanel>
<DockPanel DockPanel.Dock="Bottom" Visibility="{Binding DokumentVisibility}" >
<StackPanel Orientation="Vertical">
<Image ToolTip="Dokument öffnen" Height="100" Width="150" Source="{Binding Path=Thumbnail}" Stretch="Uniform" VerticalAlignment="Center" HorizontalAlignment="Center" />
<TextBlock Margin="2,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{Binding UserMessage}" FontSize="14"/>
</StackPanel>
</DockPanel>
<StackPanel DockPanel.Dock="Left" Margin="0,0,0,0">
<TextBlock Text="{Binding UserTimeStringLeft}" MaxWidth="{Binding TimeStringMaxWidth}" FontSize="11" HorizontalAlignment="Left" TextAlignment="Left" VerticalAlignment="Center" Foreground="{Binding Foreground}" />
</StackPanel>
<StackPanel DockPanel.Dock="Right" Margin="5,0,0,5">
<TextBlock Text="{Binding UserTimeStringRight}" MaxWidth="{Binding TimeStringMaxWidth}" FontSize="11" HorizontalAlignment="Right" TextAlignment="Right" VerticalAlignment="Center" Foreground="{Binding Foreground}" />
</StackPanel>
</DockPanel>
</Grid>
</Border>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid Grid.Row="2" Visibility="{Binding ChatMessageInputGridVisibility}" VerticalAlignment="Stretch" MinHeight="25" MaxHeight="200">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox x:Name="Chatbox"
Grid.Column="0"
HorizontalAlignment="Stretch"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"
Visibility="Visible"
BorderThickness="0"
VerticalContentAlignment="Top"
MinHeight="25" MaxHeight="200"
FontSize="15"
Padding="2"
ToolTip="Schreiben Sie hier eine Nachricht hinein"
Margin="2"
VerticalAlignment="Stretch"
GotFocus="Chatbox_OnGotFocus"
KeyDown="Chatbox_OnKeyDownHandler">
<TextBox.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="2"/>
</Style>
</TextBox.Resources>
</TextBox>
<TextBlock Padding="4,2,2,2"
Margin="2"
Grid.Column="0"
Text="Nachricht schreiben..."
Foreground="DimGray"
IsHitTestVisible="False"
VerticalAlignment="Stretch"
MinHeight="25" MaxHeight="200"
FontSize="15"
Height="{Binding ElementName=Chatbox, Path=ActualHeight}"
HorizontalAlignment="Stretch"
Visibility="{Binding ElementName=Chatbox, Path=Text, Converter={StaticResource StringEmptyToVisibilityConverter}}">
<TextBlock.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="2"/>
</Style>
</TextBlock.Resources>
</TextBlock>
<Button Grid.Column="1"
Margin="2"
x:Name="MediaButton"
Background="Transparent"
Width="28"
Height="28"
BorderThickness="0"
Padding="2"
VerticalAlignment="Bottom"
ToolTip="Datei einfügen"
Click="MediaButton_OnClick" >
<Image Width="22" Height="22" Source='pack://application:,,,/ChatController;component/Ressourcen/paperclip2.png' RenderOptions.BitmapScalingMode="HighQuality" HorizontalAlignment="Center"/>
</Button>
<Button Grid.Column="2"
Width="28"
Height="28"
BorderThickness="0"
Background="Transparent"
x:Name="EmojiButton"
Margin="2"
Padding="0"
VerticalAlignment="Bottom"
ToolTip="Emoji einfügen"
Click="EmojiButton_OnClick">
<Image Width="24" Height="24" Source='pack://application:,,,/ChatController;component/Ressourcen/glucklicher.png' RenderOptions.BitmapScalingMode="HighQuality" HorizontalAlignment="Center" />
</Button>
<Button x:Name="SendButton" Height="25" Content="Senden" Padding="5,2" Margin="3" Grid.Column="3" VerticalAlignment="Bottom"
Click="SendButton_OnClick" Background="{DynamicResource ButtonForeground}" IsEnabled="{Binding ElementName=Chatbox, Path=Text, Converter={StaticResource StringToBoolConverter}}">
<Button.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="3"/>
<Setter Property="Padding" Value="1" />
</Style>
</Button.Resources>
</Button>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
</Border>
</Border>
</Grid>
</UserControl>

View File

@@ -1,9 +1,12 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
@@ -13,14 +16,13 @@ using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;
using ChatController.Annotations;
using ChatController.ChatKlassen;
using ChatController.Extensions;
using ChatController.HauptKlassen;
using ChatController.LoginKlassen;
using ChatController.Utilities;
using ChatController.Utilities.Extensions;
using Button = System.Windows.Controls.Button;
using Cursors = System.Windows.Input.Cursors;
using DataFormats = System.Windows.DataFormats;
@@ -35,7 +37,7 @@ using Timer = System.Windows.Forms.Timer;
namespace ChatController
{
public partial class ChatMainControl
public partial class ChatMainControl : INotifyPropertyChanged
{
private readonly Dictionary<long, List<NotifyIcon>> _Group2NotifyIcons = new Dictionary<long, List<NotifyIcon>>();
@@ -50,6 +52,7 @@ namespace ChatController
set
{
_ContainingWindow = value;
if(value != null)
{
_ContainingWindow.Deactivated += ContainingWindowOnDeactivated;
@@ -59,11 +62,49 @@ namespace ChatController
}
private Chat _Chat;
private CurrentContact _CurrentContact;
private Contact _CurrentContact;
private bool _IsChatBoxOnFocus;
public ObservableCollection<ChatMessage> CurrentChatMessages => _CurrentContact != null && _Chat != null ? new ObservableCollection<ChatMessage>(_Chat.Messages) : new ObservableCollection<ChatMessage>();
private IOrderedEnumerable<Contact> _ContactList;
public Contact CurrentContact
{
get => _CurrentContact;
set
{
if(!Equals(_CurrentContact, value))
{
_CurrentContact = value;
OnPropertyChanged(nameof(CurrentContact));
OnPropertyChanged(nameof(ChatMessageInputGridVisibility));
OnPropertyChanged(nameof(CurrentChatMessages));
}
}
}
public ObservableCollection<Contact> ContactList
{
get
{
return _ContactList == null ? new ObservableCollection<Contact>() : new ObservableCollection<Contact>(_ContactList.OrderByDescending(contact => contact.TimeStamp));
}
}
public Visibility ChatMessageInputGridVisibility
{
get
{
if(_CurrentContact == null)
{
return Visibility.Collapsed;
}
return _CurrentContact.IsChatMessageInputGridVisible ? Visibility.Visible : Visibility.Collapsed;
}
}
private List<Contact> _ContactList;
private bool _ScrollPrueferAktivieren;
@@ -81,6 +122,8 @@ namespace ChatController
{
InitializeComponent();
DataContext = this;
ReloadGruppen.Visibility = Visibility.Collapsed;
}
@@ -96,11 +139,15 @@ namespace ChatController
public void InitMitChatdaten(ChatDatenUebergabe cdu)
{
_Chat = new Chat(cdu);
_Chat = new Chat(cdu, exception => {
this.Dispatch(() => {
EndWaiting();
MessageBox.Show($"Fehler: {exception.Message}", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
});
});
_ContactList = _Chat.AddContacts();
Clientlist.ItemsSource = _ContactList;
OnPropertyChanged(nameof(ContactList));
ReadNewSyncFile();
@@ -118,9 +165,6 @@ namespace ChatController
}
}
var view = (CollectionView) CollectionViewSource.GetDefaultView(Clientlist.ItemsSource);
view.Filter = UserFilter;
GlobalListeningThreadtimer?.Stop();
GlobalListeningThreadtimer = null;
InitGlobalListeningThread();
@@ -205,6 +249,7 @@ namespace ChatController
}
}
// WebRequest: LoadChatMessagesForContact
private void SelectContact(Contact pContact)
{
if(pContact == null)
@@ -226,7 +271,7 @@ namespace ChatController
Clientlist.Items.Refresh();
}
var currentContact = new CurrentContact(pContact);
var currentContact = pContact;
pContact.IsNewMessage = false;
var shouldChangeIcon = _ContactList.Any(contact => contact.IsNewMessage);
@@ -236,7 +281,7 @@ namespace ChatController
}
AktChatUserList.Items.Add(currentContact);
_CurrentContact = currentContact;
CurrentContact = currentContact;
if(Clientlist.Items.Contains(pContact))
{
@@ -245,7 +290,7 @@ namespace ChatController
var chatMessages = _Chat.LoadChatMessagesForContact(currentContact);
ChatListBox.ItemsSource = chatMessages;
OnPropertyChanged(nameof(CurrentChatMessages));
if (VisualTreeHelper.GetChildrenCount(ChatListBox) > 0)
{
@@ -270,192 +315,215 @@ namespace ChatController
{
var contextItems = ChatListBox?.ContextMenu?.Items;
if(contextItems == null)
{
return;
}
foreach (var menuItemText in _MenuItemName2Callback.Keys)
{
var cb = _MenuItemName2Callback[menuItemText];
var callback = _MenuItemName2Callback[menuItemText];
var menuItem = new MenuItem();
menuItem.Click += (s, e2) =>
{
cb(menuItemText);
callback(menuItemText);
};
menuItem.Header = menuItemText;
contextItems.Add(menuItem);
}
var item2 = (MenuItem)contextItems[0];
item2.Click += Item2OnClick; // umbenenen in Speichern unter
var item3 = (MenuItem)contextItems[1];
item3.Click += Item3OnClick; //Umbenenen in Einfügen
if(contextItems.Count > 0)
{
var saveAsMenuItem = (MenuItem) contextItems[0];
saveAsMenuItem.Click += SaveAsOnClick;
}
if(contextItems.Count > 1)
{
var pasteMenuItem = (MenuItem) contextItems[1];
pasteMenuItem.Click += PasteOnClick;
}
// neu und vor Einfügen setzen und anpassen
var item4 = (MenuItem) contextItems[2];
item4.Click += Item4OnClick; //Umbenenen in Kopieren
}
private void Item2OnClick(object sender, RoutedEventArgs routedEventArgs)
{
foreach (var items in ChatListBox.SelectedItems)
if(contextItems.Count > 2)
{
var item = (ChatMessage)items;
_Chat.SaveFileAs(item);
var copyMenuItem = (MenuItem) contextItems[2];
copyMenuItem.Click += CopyOnClick;
}
}
private void Item3OnClick(object sender, RoutedEventArgs routedEventArgs)
private void SaveAsOnClick(object sender, RoutedEventArgs routedEventArgs)
{
var kontakt = (CurrentContact)AktChatUserList.Items[0];
foreach (var items in ChatListBox.SelectedItems)
{
var chatMessage = (ChatMessage) items;
_Chat.SaveFileAs(chatMessage);
}
}
private void PasteOnClick(object sender, RoutedEventArgs routedEventArgs)
{
var kontakt = (Contact)AktChatUserList.Items[0];
_Chat.Paste(kontakt.GroupId,this);
}
private void Item4OnClick(object sender, RoutedEventArgs routedEventArgs)
private void CopyOnClick(object sender, RoutedEventArgs routedEventArgs)
{
string chatmessages = "";
var chatMessages = string.Empty;
foreach (var items in ChatListBox.SelectedItems)
{
var item = (ChatMessage)items;
var item = (ChatMessage) items;
chatmessages += item.UserMessage + "\n";
chatMessages += item.UserMessage + "\n";
}
if(!chatmessages.Equals(""))
_Chat.Copy(chatmessages, 1);
if(!string.IsNullOrWhiteSpace(chatMessages))
{
_Chat.Copy(chatMessages, 1);
}
}
private void Chat_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var chatItems = ChatListBox.SelectedItems;
if (chatItems.Count > 0)
if(ChatListBox?.ContextMenu == null)
{
foreach (var items in chatItems)
return;
}
if(ChatListBox.SelectedItems is List<ChatMessage> chatMessages)
{
if(chatMessages.Count > 0)
{
var item = items as ChatMessage;
if (item != null && item.ImageSources != null)
foreach(var items in chatMessages)
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[0];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
else
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[0];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
}
var item = items as ChatMessage;
if(item?.ImageSources != null)
{
if(ChatListBox.ContextMenu != null)
{
var contextItems = ChatListBox.ContextMenu.Items;
((MenuItem)contextItems[0]).Visibility = Visibility.Visible;
}
}
else
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[0];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
}
if (item.ImageSources == null && item.FilePath == null)
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem) contextItems[2];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
else
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[2];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
if(item.ImageSources == null && item.FilePath == null)
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[2];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
else
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[2];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
}
}
}
else
{
//Schalte speichern unter Aus
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[0];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
}
//prüfe ob was in dem Speicher vorhanden ist //Einfügen
var dataObject = System.Windows.Forms.Clipboard.GetDataObject();
if(dataObject != null && dataObject.GetDataPresent(DataFormats.FileDrop))
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem) contextItems[1];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
else if(dataObject != null && dataObject.GetDataPresent(DataFormats.Text))
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem) contextItems[1];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
else if(dataObject != null && dataObject.GetDataPresent(DataFormats.Bitmap))
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem) contextItems[1];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
else
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
}
//prüfe ob dokumentation erlaubt
var kontakt = (Contact)AktChatUserList.Items[0];
if(kontakt.UserIdManage == null && ChatListBox.ContextMenu.Items.Count > 3)
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[3];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
}
else if(ChatListBox.ContextMenu.Items.Count > 3)
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[3];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
if(ChatListBox.ContextMenu.Items.Count == 0)
{
ChatListBox.ContextMenu.Visibility = Visibility.Collapsed;
}
}
else
{
//Schalte speichern unter Aus
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[0];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
}
//prüfe ob was in dem Speicher vorhanden ist //Einfügen
var d = System.Windows.Forms.Clipboard.GetDataObject();
if (d.GetDataPresent(DataFormats.FileDrop))
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
else if (d.GetDataPresent(DataFormats.Text))
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
else if (d.GetDataPresent(DataFormats.Bitmap))
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
else
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
}
//prüfe ob dokumentation erlaubt
var kontakt = (CurrentContact)AktChatUserList.Items[0];
if (kontakt.UserIdManage == null && ChatListBox.ContextMenu.Items.Count > 3)
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[3];
ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
}
else if (ChatListBox.ContextMenu.Items.Count > 3)
{
var contextItems = ChatListBox.ContextMenu.Items;
var ContextItemSpeichernUnter = (MenuItem)contextItems[3];
ContextItemSpeichernUnter.Visibility = Visibility.Visible;
}
if (ChatListBox.ContextMenu.Items.Count == 0)
{
ChatListBox.ContextMenu.Visibility = Visibility.Collapsed;
}
}
private void MediaButton_OnClick(object sender, RoutedEventArgs e)
{
if (AktChatUserList.Items.Count > 0)
{
var kontakt = (CurrentContact)AktChatUserList.Items[0];
var medium = _Chat.OpenFile();
var fileToOpen = _Chat.OpenFile();
if(medium != null) {
if(fileToOpen != null)
{
var filePath = FileUtils.ScaleImage(fileToOpen, Path.GetExtension(fileToOpen.ToUpperInvariant()), _Chat.ChatDaten.MaxUploadSize);
string convertetMedia = _Chat.ScaleImage(medium, Path.GetExtension(medium.ToUpperInvariant()));
var isFileSizeTooLarge = FileUtils.CheckFileSize(filePath, _Chat.ChatDaten.MaxUploadSize);
if (!convertetMedia.Equals(""))
if(isFileSizeTooLarge)
{
_Chat.AddNewFile(convertetMedia,medium,kontakt.GroupId);
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;
}
CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh();
if (!string.IsNullOrWhiteSpace(filePath))
{
//_Chat.AddNewFile(filePath, fileToOpen, CurrentContact.GroupId);
OnPropertyChanged(nameof(CurrentChatMessages));
ChatListBox.Items.MoveCurrentToLast();
ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);
_Chat.SendFileToContact(kontakt, convertetMedia,medium);
_Chat.SendFileToContact(CurrentContact, filePath,fileToOpen);
if (!convertetMedia.Equals("") && !convertetMedia.Equals(medium) && File.Exists(convertetMedia))
if (!string.IsNullOrWhiteSpace(filePath) && !filePath.Equals(fileToOpen) && File.Exists(filePath))
{
File.Delete(convertetMedia);
File.Delete(filePath);
}
}
else
{
MessageBox.Show("Die gewählte Datei ist zu groß!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
}
else
@@ -466,51 +534,18 @@ namespace ChatController
private void SendButton_OnClick(object sender, RoutedEventArgs e)
{
if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals("") && _IsChatBoxOnFocus)
if (!AktChatUserList.Items.IsEmpty && !string.IsNullOrEmpty(Chatbox.Text))
{
if (!Chatbox.Text.Equals(""))
{
var kontakt = (CurrentContact)AktChatUserList.Items[0];
_Chat.AddNewMessage(Chatbox.Text, kontakt.GroupId);
CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh();
_Chat.AddNewMessage(Chatbox.Text, CurrentContact.GroupId);
ChatListBox.Items.MoveCurrentToLast();
ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);
_Chat.SendMessage(Chatbox.Text, kontakt.GroupId);
OnPropertyChanged(nameof(CurrentChatMessages));
Chatbox.Text = "";
if (Chatbox.Text.Equals(""))
{
Chatbox.Text = "Nachricht schreiben";
Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray);
_IsChatBoxOnFocus = false;
}
}
}
else
{
if (AktChatUserList.Items.IsEmpty)
{
MessageBox.Show("Bitte wählen Sie einen Chatpartner aus.", "Fehler", MessageBoxButton.OK);
if (string.IsNullOrEmpty(Chatbox.Text))
{
Chatbox.Text = "Nachricht schreiben";
Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray);
_IsChatBoxOnFocus = false;
}
}
else if (string.IsNullOrEmpty(Chatbox.Text))
{
MessageBox.Show("Sie können keine leere Nachricht verschicken.", "Fehler", MessageBoxButton.OK);
Chatbox.Text = "Nachricht schreiben";
Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray);
_IsChatBoxOnFocus = false;
}
ChatListBox.Items.MoveCurrentToLast();
ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);
_Chat.SendMessage(Chatbox.Text, CurrentContact.GroupId);
Chatbox.Text = string.Empty;
}
}
@@ -518,9 +553,8 @@ namespace ChatController
{
if (Chatbox.Text.Equals("Nachricht schreiben"))
{
Chatbox.Text = "";
Chatbox.Text = string.Empty;
Chatbox.Foreground = new SolidColorBrush(Colors.Black);
_IsChatBoxOnFocus = true;
}
}
@@ -530,32 +564,18 @@ namespace ChatController
{
if (e.Key == Key.Return)
{
if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals(""))
if (!AktChatUserList.Items.IsEmpty && !string.IsNullOrEmpty(Chatbox.Text))
{
var kontakt = (CurrentContact)AktChatUserList.Items[0];
_Chat.AddNewMessage(Chatbox.Text, kontakt.GroupId);
CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh();
_Chat.AddNewMessage(Chatbox.Text, CurrentContact.GroupId);
OnPropertyChanged(nameof(CurrentChatMessages));
ChatListBox.Items.MoveCurrentToLast();
ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);
_Chat.SendMessage(Chatbox.Text, kontakt.GroupId);
_Chat.SendMessage(Chatbox.Text, CurrentContact.GroupId);
Chatbox.Text = "";
}
else
{
if (AktChatUserList.Items.IsEmpty)
{
MessageBox.Show("Bitte wählen Sie einen Chatpartner aus.", "Fehler", MessageBoxButton.OK);
}
else if (Chatbox.Text.Equals(""))
{
MessageBox.Show("Sie können keine leere Nachricht verschicken.", "Fehler", MessageBoxButton.OK);
}
Chatbox.Text = string.Empty;
}
}
}
@@ -570,17 +590,13 @@ namespace ChatController
public event EmojiiDelegate OnEmojii;
private void EmojiButton_OnClick(object sender, RoutedEventArgs e)
{
//hier wie bei login
if (OnEmojii != null)
{
OnEmojii(EmojiButton);
}
{
OnEmojii?.Invoke(EmojiButton);
}
private void Chat_OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
var scrollBarList = GetVisualChildCollection<ScrollBar>(ChatListBox);
var scrollBarList = Utils.GetVisualChildCollection<ScrollBar>(ChatListBox);
foreach (var scrollBar in scrollBarList)
{
if (scrollBar.Orientation == Orientation.Horizontal)
@@ -594,74 +610,46 @@ namespace ChatController
}
}
// TODO: Asynchron machen?
private void VerticalScrollbarChanged(object sender, RoutedPropertyChangedEventArgs<double> routedPropertyChangedEventArgs)
{
if (_ScrollPrueferAktivieren == true)
if (_ScrollPrueferAktivieren)
{
var x = (ScrollBar) sender;
var scrollBar = (ScrollBar) sender;
if (x.Value > 0)
{
//nix
}
else
if (!(scrollBar.Value > 0))
{
Cursor = Cursors.Wait;
//StartWaiting();
_ScrollPrueferAktivieren = false;
ChatListBox.Items.MoveCurrentToFirst();
ChatMessage item = ChatListBox.Items.CurrentItem as ChatMessage;
var currentChatMessage = ChatListBox.Items.CurrentItem as ChatMessage;
ChatListBox.ItemsSource = null;
var kontakt = (Contact) Clientlist.SelectedItem;
var kontakt = (Contact)Clientlist.SelectedItem;
_Chat.LoadMoreMessages(kontakt); // Ab hier käme das ins Callback
var xy = _Chat.LoadMoreMessages(kontakt);
OnPropertyChanged(nameof(CurrentChatMessages));
ChatListBox.ItemsSource = xy;
ChatListBox.ScrollIntoView(item);
//EndWaiting();
if(currentChatMessage != null)
{
ChatListBox.ScrollIntoView(currentChatMessage);
}
Cursor = Cursors.Arrow;
}
}
}
}
private static List<T> GetVisualChildCollection<T>(object parent) where T : Visual
{
var visualCollection = new List<T>();
GetVisualChildCollection(parent as DependencyObject, visualCollection);
return visualCollection;
}
private static void GetVisualChildCollection<T>(DependencyObject parent, ICollection<T> visualCollection) where T : Visual
{
var count = VisualTreeHelper.GetChildrenCount(parent);
for (var i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T item)
{
visualCollection.Add(item);
}
else
{
GetVisualChildCollection(child, visualCollection);
}
}
}
private void ListenForMessages()
{
_ListeningThreadTimer?.Stop();
_ListeningThreadTimer = null;
InitListeningThread((CurrentContact)AktChatUserList.Items[0]);
EmojisListeningThreadTimer?.Stop();
EmojisListeningThreadTimer = null;
InitListeningThread((Contact)AktChatUserList.Items[0]);
}
public Timer _ListeningThreadTimer;
public Timer EmojisListeningThreadTimer;
public Timer GlobalListeningThreadtimer { get; set; }
private void InitGlobalListeningThread()
@@ -689,11 +677,11 @@ namespace ChatController
{
var contacts = _Chat.NeueGroupklassenKontakte().ToList();
CurrentContact currentContact = null;
Contact currentContact = null;
if (AktChatUserList.HasItems)
{
currentContact = (CurrentContact)AktChatUserList.Items[0];
currentContact = (Contact) AktChatUserList.Items[0];
}
foreach (var contact in _ContactList)
@@ -709,7 +697,7 @@ namespace ChatController
contact.TimeStamp = newContact.TimeStamp;
// TODO: Prüfen, ob die App im Hintergrund oder minimiert ist
if ((Clientlist.SelectedItem != null && !((Contact)Clientlist.SelectedItem).GroupId.Equals(newContact.GroupId) || Clientlist.SelectedItem == null) || _IsInBackground)
if (Clientlist.SelectedItem != null && !((Contact)Clientlist.SelectedItem).GroupId.Equals(newContact.GroupId) || Clientlist.SelectedItem == null || _IsInBackground)
{
ContainingWindow.Icon = Utils.GetImageSourceFromIcon(Resource.oC_favico_NewMessage);
ShowNotification(newContact.Name, newContact.ReceivedMessage, newContact.GroupId);
@@ -745,20 +733,20 @@ namespace ChatController
}
}
private void InitListeningThread(CurrentContact pCurrentContacObject)
private void InitListeningThread(Contact currentContact)
{
_ListeningThreadTimer = new Timer {Tag = pCurrentContacObject};
_ListeningThreadTimer.Tick += ListeningThreadTimerTickEvent;
_ListeningThreadTimer.Interval = 2000;
_ListeningThreadTimer.Start();
EmojisListeningThreadTimer = new Timer {Tag = currentContact};
EmojisListeningThreadTimer.Tick += ListeningThreadTimerTickEvent;
EmojisListeningThreadTimer.Interval = 2000;
EmojisListeningThreadTimer.Start();
}
private void ListeningThreadTimerTickEvent(object sender, EventArgs e)
{
ListenForMessagesForCurrentContact((CurrentContact) ((Timer) sender).Tag);
ListenForMessagesForCurrentContact((Contact) ((Timer) sender).Tag);
}
private void ListenForMessagesForCurrentContact(CurrentContact pCurrentContact)
private void ListenForMessagesForCurrentContact(Contact pCurrentContact)
{
if (!ShouldInterruptContactsThread)
{
@@ -771,7 +759,7 @@ namespace ChatController
{
_Chat.LoadChatMessagesForContact(pCurrentContact);
CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh();
OnPropertyChanged(nameof(CurrentChatMessages));
ChatListBox.Items.MoveCurrentToLast();
ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);
@@ -782,15 +770,18 @@ namespace ChatController
private void Suche_OnTextChanged(object sender, TextChangedEventArgs e)
{
OnPropertyChanged(nameof(CurrentChatMessages));
CollectionViewSource.GetDefaultView(Clientlist.ItemsSource).Refresh();
}
private bool UserFilter(object item)
{
if (String.IsNullOrEmpty(Suche.Text))
if (string.IsNullOrEmpty(Suche.Text))
{
return true;
else
return ((item as Contact).Name.IndexOf(Suche.Text, StringComparison.OrdinalIgnoreCase) >= 0);
}
return (item as Contact).Name.IndexOf(Suche.Text, StringComparison.OrdinalIgnoreCase) >= 0;
}
private void Chat_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
@@ -798,19 +789,20 @@ namespace ChatController
Cursor = Cursors.Wait;
var chatItems = ChatListBox.SelectedItems;
if (chatItems.Count > 0)
{
foreach (var items in chatItems)
{
var item = items as ChatMessage;
if (item != null && item.ImageSources != null)
if (item?.OriginalImage != null)
{
StartWaiting();
_Chat.ShowPicture(item, EndWaiting);
StartWaitingImmediately();
_Chat.ShowPicture(item.OriginalImage, EndWaiting);
}
else if(item != null && item.FilePath != null)
else if(item?.FilePath != null)
{
var filename = Path.GetFileName(item.FilePath.ToString());
LoadDocument(item.FilePath.ToString(), filename);
@@ -860,7 +852,7 @@ namespace ChatController
}
}
private ChatControlWaitLayer _waitLayer;
private ChatControlWaitLayer _WaitLayer;
public void StartWaiting()
{
@@ -869,14 +861,13 @@ namespace ChatController
public void StartWaitingImmediately()
{
if (_waitLayer == null)
if (_WaitLayer == null)
{
_waitLayer = new ChatControlWaitLayer();
//Grid.SetColumnSpan(_waitLayer, 3);
Grid.SetRowSpan(_waitLayer, 3);
GridRechts.Children.Add(_waitLayer);
Panel.SetZIndex(_waitLayer, int.MaxValue);
_waitLayer.RefreshChatUI();
_WaitLayer = new ChatControlWaitLayer();
Grid.SetRowSpan(_WaitLayer, 3);
RootGrid.Children.Add(_WaitLayer);
Panel.SetZIndex(_WaitLayer, int.MaxValue);
_WaitLayer.RefreshChatUI();
}
}
@@ -884,12 +875,12 @@ namespace ChatController
{
Dispatcher.BeginInvoke(
DispatcherPriority.Background,
(Action)delegate
(Action) delegate
{
if (_waitLayer != null)
if(_WaitLayer != null)
{
GridRechts.Children.Remove(_waitLayer);
_waitLayer = null;
RootGrid.Children.Remove(_WaitLayer);
_WaitLayer = null;
}
});
}
@@ -908,22 +899,26 @@ namespace ChatController
{
try
{
Cursor = Cursors.Wait;
StartWaitingImmediately();
WriteToNewSyncFile();
var aktuelleGruppen = _Chat.UpdateGroups();
_Chat.ReloadGroupsAsync(data =>
{
this.Dispatch(() =>
{
_ContactList = _Chat.GroupklassenAktuallisieren(data); // <- dauert eine Sekunde!
OnPropertyChanged(nameof(ContactList));
_ContactList = _Chat.GroupklassenAktuallisieren(aktuelleGruppen);
ReadNewSyncFile();
ReadNewSyncFile();
Clientlist.Items.Refresh();
Cursor = Cursors.Arrow;
EndWaiting();
});
});
}
catch (Exception e)
{
EndWaiting();
MessageBox.Show("Ein Fehler bei der Synchronisation ist aufgetreten.\nFehler:\n" + e.Message, "Fehler", MessageBoxButton.OK);
}
}
@@ -1008,6 +1003,7 @@ namespace ChatController
}
}
// Wird im BeWoPlaner benutzt
public List<Contact> GetContactsWithoutUnreadMessages()
{
var contacts = new List<Contact>();
@@ -1025,6 +1021,7 @@ namespace ChatController
return contacts;
}
// Wird im BeWoPlaner benutzt
public void ResetNumberOfUnreadMessages(Dictionary<long, DateTime> pGroupId2DateTime)
{
if(pGroupId2DateTime != null)
@@ -1042,6 +1039,7 @@ namespace ChatController
}
}
// Wird im BeWoPlaner benutzt
public List<ChatMessage> GetSelectedMessages()
{
var messages = (from object selectedItem in ChatListBox.SelectedItems select selectedItem as ChatMessage).ToList();
@@ -1049,11 +1047,12 @@ namespace ChatController
return messages.Count > 0 ? messages : null;
}
public CurrentContact GetCurrentContact()
// Wird im BeWoPlaner benutzt
public Contact GetCurrentContact()
{
if(AktChatUserList != null && AktChatUserList.Items.Count > 0)
{
var contact = (CurrentContact) AktChatUserList.Items[0];
var contact = (Contact) AktChatUserList.Items[0];
return contact.UserIdManage == null ? null : contact;
}
@@ -1061,6 +1060,7 @@ namespace ChatController
return null;
}
// Wird im BeWoPlaner benutzt
public void AddContextMenu(string menuItemText, Action<string> callBackAction)
{
if (!_MenuItemName2Callback.ContainsKey(menuItemText))
@@ -1069,7 +1069,7 @@ namespace ChatController
}
}
public void DeleteTempFiles()
public void DeleteTempFiles()
{
foreach (var file in _CreatedTempFiles)
{
@@ -1086,5 +1086,19 @@ namespace ChatController
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void ChatMainControl_OnLoaded(object sender, RoutedEventArgs e)
{
var view = (CollectionView)CollectionViewSource.GetDefaultView(Clientlist.ItemsSource);
view.Filter = UserFilter;
}
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace ChatController.Converter
{
public class BoolToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value is bool boolValue)
{
if(parameter is string reverseString && Equals(reverseString, "reverse"))
{
return boolValue ? Visibility.Visible : Visibility.Collapsed;
}
return boolValue ? Visibility.Collapsed : Visibility.Visible;
}
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace ChatController.Converter
{
public class StringEmptyToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value is string text)
{
return string.IsNullOrWhiteSpace(text) ? Visibility.Visible : Visibility.Hidden;
}
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Globalization;
using System.Windows.Data;
namespace ChatController.Converter
{
public class StringToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value is string text)
{
return !string.IsNullOrWhiteSpace(text);
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,14 @@
using Newtonsoft.Json;
namespace ChatController.Data
{
public class LookupResult
{
public int Status { get; set; }
[JsonProperty("URL")]
public string Url { get; set; }
public string SyncType { get; set; }
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,11 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Web;
using System.Windows;
using ChatController.Data;
using ChatController.LoginKlassen;
using ChatController.Utilities;
@@ -14,11 +16,12 @@ namespace ChatController.HauptKlassen
{
public class Login
{
private string _Url = string.Empty;
private string _BaseUrl = string.Empty;
private const string _NewUrl = "https://dict.ownchat.de/api/server/resolve/1/";
private const string DictionaryServerUrl = "https://dict.ownchat.de/api/server/resolve/1/";
public string ServerUrl { get; set; } = string.Empty;
private string _AuthToken = string.Empty;
private readonly string _UserName;
@@ -29,10 +32,9 @@ namespace ChatController.HauptKlassen
private long? _UserId;
private bool _ownchatVerbindungsaufbauOK;
private bool _gruppeholenverbindungsaufbauOK;
private bool _OwnchatVerbindungsaufbauOk;
private bool _GruppeholenverbindungsaufbauOk;
private AuthenticationData _serverconect;
private UserDaten _LoggedInUser;
private ChatGruppenDaten _AllGroups;
@@ -44,61 +46,146 @@ namespace ChatController.HauptKlassen
_ChatCode = pChatCode;
_UserName = pUserName;
_Password = pPassword;
_ApiKey = "0000";//default, damit nichts kaputt geht
_ApiKey = "0000";
}
// Wird im BeWoPlaner benutzt
public Login(string pTenant, string pChatCode, string pUserName, string pPassword, string pApiKey)
{
_Tenant = pTenant;
_Tenant = pTenant;
_ChatCode = pChatCode;
_UserName = pUserName;
_Password = pPassword;
_ApiKey = pApiKey;
_ApiKey = pApiKey;
}
//
public Login(string pTenant)
// Wird im BeWoPlaner benutzt
public Login(string tenant, Action<string> callback)
{
_Tenant = pTenant;
_Tenant = tenant;
_ShouldShowMessageBox = false;
ServerErmittlung();
LookupServerUrlAsync(isSuccessful => { callback(ServerUrl); });
}
public ChatDatenUebergabe AnmeldevorgangDurchFuehren()
{
if(ServerErmittlung()){
var dic = new Dictionary<string, string>
{
{"username", _UserName},
if(ServerErmittlung())
{
var dic = new Dictionary<string, string>
{
{ "username", _UserName},
{ "password", _Password},
{ "chatcode", _ChatCode}
};
};
VerbindeMitChatServer(dic);
if (_ownchatVerbindungsaufbauOK)
{
GetGroups();
}
if (_gruppeholenverbindungsaufbauOK)
{
var maxUploadSize = GetMaiximumAllowedFileUploadSize(_AuthToken,_Tenant);
VerbindeMitChatServer(dic);
return new ChatDatenUebergabe(_serverconect, _LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant, _ApiKey, maxUploadSize);
}
}
if(_OwnchatVerbindungsaufbauOk)
{
GetGroups();
}
return null;
if(_GruppeholenverbindungsaufbauOk)
{
var maxUploadSize = GetMaiximumAllowedFileUploadSize(_AuthToken, _Tenant);
return new ChatDatenUebergabe(_LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant, _ApiKey, maxUploadSize);
}
}
return null;
}
public void DoLoginAsync(Action<ChatDatenUebergabe> callback, Action<string> exceptionCallback)
{
try
{
LookupServerUrlAsync(isConnectedWithServer =>
{
if(isConnectedWithServer)
{
ConnectWithChatServerAsync(
isSuccessfullyLoggedIn =>
{
if (isSuccessfullyLoggedIn)
{
GetGroupsAsync(wasSuccessful =>
{
if (wasSuccessful)
{
GetMaximumAllowedFileUploadSizeAsync(maxUploadFileSize =>
{
callback?.Invoke(new ChatDatenUebergabe(_LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant, _ApiKey, maxUploadFileSize));
});
}
});
}
},
errorMessage => { exceptionCallback?.Invoke(errorMessage); });
}
});
}
catch (Exception exception)
{
callback?.Invoke(null);
}
}
public void LookupServerUrlAsync(Action<bool> callback)
{
try
{
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)
{
case 0:
result = true;
break;
case 1:
MessageBox.Show("Fehler: Kundennummer unbekannt.\nBitte überprüfen Sie die Anmeldeinformationen.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk);
break;
case 2:
MessageBox.Show("Der Diensttyp ist für die angegebene Kundennummer nicht definiert.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk);
break;
}
callback?.Invoke(result);
});
}
catch (Exception exception)
{
MessageBox.Show("Fehler: Es konnte keine Verbindung aufgebaut werden.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public bool ServerErmittlung()
{
if (string.IsNullOrEmpty(ServerUrl))
{
try
{
var serverURl = _NewUrl + _Tenant;
var serverURl = DictionaryServerUrl + _Tenant;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = WebRequest.Create(serverURl);
@@ -144,7 +231,7 @@ namespace ChatController.HauptKlassen
return false;
}
_Url = jsonDatentyp.Url;
_BaseUrl = jsonDatentyp.Url;
}
catch (Exception eds)
{
@@ -170,7 +257,7 @@ namespace ChatController.HauptKlassen
return false;
}
_Url = jsonDatentyp.Url;
_BaseUrl = jsonDatentyp.Url;
}
catch (Exception e)
{
@@ -183,7 +270,7 @@ namespace ChatController.HauptKlassen
response.Close();
ServerUrl = _Url;
ServerUrl = _BaseUrl;
return true;
}
catch (Exception e)
@@ -204,7 +291,7 @@ namespace ChatController.HauptKlassen
{
try
{
var endurl = _Url + "/api/user/loginwithchatcode";
var endurl = _BaseUrl + Constants.LoginWithChatCodeUrl;
var requestBody = postparameter.Keys.Aggregate(string.Empty, (current, key) => current + HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(postparameter[key]) + "&");
@@ -219,6 +306,7 @@ namespace ChatController.HauptKlassen
if (response.StatusCode == HttpStatusCode.OK)
{
Debug.WriteLine(response.Content);
var userDaten = JsonConvert.DeserializeObject<UserDaten>(response.Content);
if(userDaten.Success)
@@ -226,28 +314,31 @@ namespace ChatController.HauptKlassen
_AuthToken = userDaten.Response.User.Token;
_UserId = userDaten.Response.User.Oid;
Utils.AuthToken = _AuthToken;
Utils.Tenant = _Tenant;
_LoggedInUser = userDaten;
_ownchatVerbindungsaufbauOK = true;
_OwnchatVerbindungsaufbauOk = true;
}
else
{
if(userDaten.Errors.chatcode_failed != null)
if(userDaten.Error?.ChatCodeFailed != null)
{
if(_ShouldShowMessageBox)
{
MessageBox.Show("Fehler: " + userDaten.Errors.chatcode_failed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show("Fehler: " + userDaten.Error.ChatCodeFailed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else if(userDaten.Errors.login_failed != null)
else if(userDaten.Error?.LoginFailed != null)
{
if(_ShouldShowMessageBox)
{
MessageBox.Show("Fehler: " + userDaten.Errors.login_failed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show("Fehler: " + userDaten.Error.LoginFailed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
_ownchatVerbindungsaufbauOK = false;
_OwnchatVerbindungsaufbauOk = false;
}
}
else
@@ -268,7 +359,7 @@ namespace ChatController.HauptKlassen
{
try
{
var endurl = _Url + Constants.GetChatGroupsUrl;
var endurl = _BaseUrl + Constants.GetChatGroupsUrl;
var request = WebRequest.Create(endurl);
@@ -282,11 +373,13 @@ namespace ChatController.HauptKlassen
if (!string.IsNullOrEmpty(serverResponse))
{
Debug.WriteLine($"'ChatGruppenDaten' (Gruppen): {serverResponse}");
var jsonDaten = JsonConvert.DeserializeObject<ChatGruppenDaten>(serverResponse);
_AllGroups = jsonDaten;
_gruppeholenverbindungsaufbauOK = true;
_GruppeholenverbindungsaufbauOk = true;
}
}
}
@@ -299,6 +392,79 @@ namespace ChatController.HauptKlassen
}
}
private void ConnectWithChatServerAsync(Action<bool> callback, Action<string> exceptionCallback)
{
var url = _BaseUrl + Constants.LoginWithChatCodeUrl;
var requestBody = $"{HttpUtility.UrlEncode("username")}={HttpUtility.UrlEncode(_UserName)}&{HttpUtility.UrlEncode("password")}={HttpUtility.UrlEncode(_Password)}&{HttpUtility.UrlEncode("chatcode")}={HttpUtility.UrlEncode(_ChatCode)}";
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader(Constants.ContentTypeKey, Constants.FormUrlEncodedContentTypeValue);
request.AddParameter(Constants.CustomerId, _Tenant, ParameterType.HttpHeader);
request.AddParameter(Constants.FormUrlEncodedContentTypeValue, requestBody, ParameterType.RequestBody);
client.PostAsync(request, (response, handle) =>
{
Debug.WriteLine(response.Content);
var connectionData = JsonConvert.DeserializeObject<UserDaten>(response.Content);
if (connectionData.Success)
{
_AuthToken = connectionData.Response.User.Token;
_UserId = connectionData.Response.User.Oid;
Utils.AuthToken = _AuthToken;
Utils.Tenant = _Tenant;
_LoggedInUser = connectionData;
callback?.Invoke(true);
}
else
{
var errorMessage = string.Empty;
if (connectionData.Error?.ChatCodeFailed != null)
{
errorMessage = $"Fehler: {connectionData.Error.ChatCodeFailed[0]}";
}
else if (connectionData.Error?.LoginFailed != null)
{
errorMessage = $"Fehler: {connectionData.Error.LoginFailed[0]}";
}
if (!string.IsNullOrWhiteSpace(errorMessage))
{
exceptionCallback?.Invoke(errorMessage);
}
}
});
}
private void GetGroupsAsync(Action<bool> callback)
{
var url = _BaseUrl + Constants.GetChatGroupsUrl;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient(url);
var request = new RestRequest();
request.AddHeader(Constants.Token, _AuthToken);
request.AddHeader(Constants.CustomerId, _Tenant);
client.ExecuteAsync(request, response =>
{
var groups = JsonConvert.DeserializeObject<ChatGruppenDaten>(response.Content);
_AllGroups = groups;
callback?.Invoke(true);
});
}
#region Maximal erlaubte File Größe
public long GetMaiximumAllowedFileUploadSize(string pToken, string pCustomerId)
@@ -333,7 +499,27 @@ namespace ChatController.HauptKlassen
return maximumFileSize;
}
public void GetMaximumAllowedFileUploadSizeAsync(Action<long> callback)
{
var url = ServerUrl + Constants.MaxUploadFileSizeUrl;
var client = new RestClient(url);
var request = new RestRequest();
request.AddHeader(Constants.Token, _AuthToken);
request.AddHeader(Constants.CustomerId, _Tenant);
client.ExecuteAsync(request, response =>
{
var maxFileSizeAnonymous = JsonConvert.DeserializeAnonymousType(response.Content, new {file_upload_max_size = string.Empty});
var maxUploadFileSize = Convert.ToInt64(maxFileSizeAnonymous.file_upload_max_size);
callback?.Invoke(maxUploadFileSize);
});
}
#endregion
}
}

View File

@@ -3,68 +3,61 @@
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="300" d:DesignWidth="300">
mc:Ignorable="d">
<Grid>
<Grid.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage UriSource="Ressourcen/ownChat-Background.png" />
</ImageBrush.ImageSource>
</ImageBrush>
</Grid.Background>
<Grid.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage UriSource="Ressourcen/ownChat-Background.png" />
</ImageBrush.ImageSource>
</ImageBrush>
</Grid.Background>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="GroupBoxLogin" >
<Grid>
<Grid Name="RootGrid">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="20"/>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="GroupBoxLogin" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0" Margin="3" Foreground="White">Kundennummer:</Label>
<TextBox x:Name="TextBoxKundennummer" Grid.Column="1" Grid.Row="0" Margin="3" VerticalContentAlignment="Center"/>
<Label FontSize="15" Grid.Column="0" Grid.Row="0" Margin="3" Foreground="White">Kundennummer:</Label>
<TextBox FontSize="15" Grid.Column="1" Grid.Row="0" Margin="3" VerticalContentAlignment="Center" Text="{Binding Path=Tenant, UpdateSourceTrigger=PropertyChanged}"/>
<Label Grid.Column="0" Grid.Row="1" Margin="3" Foreground="White">ChatCode:</Label>
<TextBox x:Name="TextBoxChatCode" Grid.Column="1" Grid.Row="1" Margin="3" VerticalContentAlignment="Center"/>
<Label FontSize="15" Grid.Column="0" Grid.Row="1" Margin="3" Foreground="White">ChatCode:</Label>
<TextBox FontSize="15" x:Name="TextBoxChatCode" Grid.Column="1" Grid.Row="1" Margin="3" VerticalContentAlignment="Center" Text="{Binding Path=ChatCode, UpdateSourceTrigger=PropertyChanged}"/>
<Label Grid.Column="0" Grid.Row="2" Margin="3" Foreground="White">Benutzername:</Label>
<TextBox x:Name="TextBoxBenutzerName" Grid.Column="1" Grid.Row="2" Margin="3" VerticalContentAlignment="Center" />
<Label FontSize="15" Grid.Column="0" Grid.Row="2" Margin="3" Foreground="White">Benutzername:</Label>
<TextBox FontSize="15" x:Name="TextBoxBenutzerName" Grid.Column="1" Grid.Row="2" Margin="3" VerticalContentAlignment="Center" Text="{Binding Path=UserName, UpdateSourceTrigger=PropertyChanged}" />
<Label Grid.Column="0" Grid.Row="3" Margin="3" Foreground="White">Passwort:</Label>
<PasswordBox x:Name="TextBoxPasswort" Grid.Column="1" Grid.Row="3" Margin="3" VerticalContentAlignment="Center" KeyUp="TextBoxPasswort_OnKeyUp"/>
<Label FontSize="15" Grid.Column="0" Grid.Row="3" Margin="3" Foreground="White">Passwort:</Label>
<PasswordBox FontSize="15" x:Name="PasswordBox" Grid.Column="1" Grid.Row="3" Margin="3" VerticalContentAlignment="Center" />
<!--
<CheckBox x:Name="Merken" Margin="3" Content="Passwort Speichern" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="4"/>-->
<Button Grid.ColumnSpan="2" Grid.Column="0" Grid.Row="5" Click="AnmeldenButton_OnClick" Content="Anmelden" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3" Width="80" Background="#ff5e00" HorizontalContentAlignment="Center" >
<Button.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="3"/>
<Setter Property="Padding" Value="1,1,1,1" />
</Style>
</Button.Resources>
</Button>
</Grid>
</Border>
<Label x:Name="lblVersion" HorizontalAlignment="Right" VerticalAlignment="Bottom" Foreground="White"/>
</Grid>
<Button FontSize="15" Grid.ColumnSpan="2" Grid.Column="0" Grid.Row="5" VerticalContentAlignment="Center" Click="AnmeldenButton_OnClick" Content="Anmelden" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3" Width="100" Height="40" Background="#ff5e00" HorizontalContentAlignment="Center" >
<Button.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="5"/>
<Setter Property="Padding" Value="1" />
</Style>
</Button.Resources>
</Button>
</Grid>
</Border>
<Label HorizontalAlignment="Right" VerticalAlignment="Bottom" Foreground="White" Content="{Binding Path=Version, Mode=OneWay}" />
</Grid>
</Grid>
</UserControl>

View File

@@ -1,52 +1,95 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Web;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Threading;
using ChatController.Annotations;
using ChatController.HauptKlassen;
using ChatController.LoginKlassen;
using Newtonsoft.Json;
using ChatController.Utilities;
using ChatController.Utilities.Extensions;
using Cursors = System.Windows.Input.Cursors;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MessageBox = System.Windows.MessageBox;
using Path = System.IO.Path;
namespace ChatController
{
public partial class LoginControl
public partial class LoginControl : INotifyPropertyChanged
{
private ChatControlWaitLayer _WaitLayer;
public string UserName
{
get => _Benutzername;
set
{
if (!Equals(_Benutzername, value))
{
_Benutzername = value;
OnPropertyChanged(nameof(UserName));
}
}
}
public string Password
{
get => PasswordBox.Password;
set => PasswordBox.Password = value;
}
public string ChatCode
{
get => _ChatCode;
set
{
if(!Equals(_ChatCode, value))
{
_ChatCode = value;
OnPropertyChanged(nameof(ChatCode));
}
}
}
public string Tenant
{
get => _Kundennummer;
set
{
if(!Equals(_Kundennummer, value))
{
_Kundennummer = value;
OnPropertyChanged(nameof(Tenant));
}
}
}
public delegate void LoginDelegate(ChatDatenUebergabe cdu);
public event LoginDelegate OnLogin;
private string _newUrl = "https://dict.ownchat.de/api/server/resolve/1/";
private string _benutzername = "";
private string _passwort = "";
private string _chatCode = "";
private string _kundennummer = "";
private string _authToken = "";
private string _version = "1.3";
private string _Benutzername = string.Empty;
private string _ChatCode = string.Empty;
private string _Kundennummer = string.Empty;
private readonly string _Version = "1.3";
public string Version => $"Version: {_Version}";
public LoginControl()
{
InitializeComponent();
//encrypt verschlüsselte datei
DataContext = this;
LeseDateiFallsVorhanden();
//var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
lblVersion.Content = $"Version: {_version}";
#if DEBUG
TextBoxBenutzerName.Text = "BaeurleC";
TextBoxPasswort.Password = "asFdgAE5ERfdsew4!";
#endif
}
private void AnmeldenButton_OnClick(object sender, RoutedEventArgs e)
@@ -54,35 +97,67 @@ namespace ChatController
Anmelden();
}
private void TextBoxPasswort_OnKeyUp(object sender, KeyEventArgs e)
private void StartWaiting()
{
if (e.Key == Key.Return)
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) StartWaitingImmediately);
}
private void StartWaitingImmediately()
{
if (_WaitLayer == null)
{
Anmelden();
_WaitLayer = new ChatControlWaitLayer();
Panel.SetZIndex(_WaitLayer, int.MaxValue);
RootGrid.Children.Add(_WaitLayer);
_WaitLayer.RefreshUI();
}
}
private void EndWaiting()
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) delegate
{
if (_WaitLayer != null)
{
RootGrid.Children.Remove(_WaitLayer);
_WaitLayer = null;
}
});
}
private void Anmelden()
{
try
{
//TODO Abfrage einführen, die prüft, ob eine Verbindung überhaupt hergestellt werden kann | Fehlermeldungen genauer definieren
if (!TextBoxKundennummer.Text.Equals("") && !TextBoxChatCode.Text.Equals("") && !TextBoxBenutzerName.Text.Equals("") && !TextBoxPasswort.Password.Equals(""))
if (!string.IsNullOrWhiteSpace(_Kundennummer) && !string.IsNullOrWhiteSpace(_ChatCode) && !string.IsNullOrWhiteSpace(_Benutzername) && Password.Length > 0)
{
Cursor = Cursors.Wait;
StartWaiting();
var _login = new Login(TextBoxKundennummer.Text, TextBoxChatCode.Text, TextBoxBenutzerName.Text, TextBoxPasswort.Password);
var login = new Login(_Kundennummer, _ChatCode, _Benutzername, PasswordBox.Password);
var x = _login.AnmeldevorgangDurchFuehren();
if (OnLogin != null && x != null)
login.DoLoginAsync(chatDatenUebergabe =>
{
AutosetDaten();
this.Dispatch(() =>
{
EndWaiting();
OnLogin?.Invoke(x);
}
if(chatDatenUebergabe != null)
{
AutosetDaten();
Cursor = Cursors.Arrow;
OnLogin?.Invoke(chatDatenUebergabe);
}
});
},
errorMessage =>
{
this.Dispatch(() =>
{
EndWaiting();
MessageBox.Show(errorMessage, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
});
});
}
else
{
@@ -92,183 +167,78 @@ namespace ChatController
catch (Exception exception)
{
MessageBox.Show("Fehler: " + exception.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
EndWaiting();
Cursor = Cursors.Arrow;
}
}
#region Speichern / Laden / Löschen der Datei
#region wird vorerst nicht gebraucht
private void SpeichereDatenInDatei()
{
try
{
if (!File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"))) {
using (StreamWriter sw = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt")))
{
Encoding enc = new UTF8Encoding();
//var byt = enc.GetBytes(TextBoxKundennummer.Text);
//var bytes = Convert.ToBase64String(byt);
//var byt2 = enc.GetBytes(TextBoxChatCode.Text);
//var bytes2 = Convert.ToBase64String(byt2);
var byt3 = enc.GetBytes(TextBoxBenutzerName.Text);
var bytes3 = Convert.ToBase64String(byt3);
var byt4 = enc.GetBytes(TextBoxPasswort.Password);
var bytes4 = Convert.ToBase64String(byt4);
//var byt5 = enc.GetBytes(Merken.IsChecked.ToString());
//var bytes5 = Convert.ToBase64String(byt5);
//sw.WriteLine(bytes);
//sw.WriteLine(bytes2);
sw.WriteLine(bytes3);
sw.WriteLine(bytes4);
//sw.WriteLine(bytes5);
File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"), FileAttributes.ReadOnly);
}
}
}
catch (Exception e)
{
MessageBox.Show("Ups, da ist was schief gelaufen: \n" + e.Message, "Fehler", MessageBoxButton.OK);
}
}
private void LoescheGespeicherteDatei()
private void LoadTenantAndChatCodeFromFile()
{
try
{
if (File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt")))
if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName)))
{
File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"), FileAttributes.Normal);
File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"));
}
}
catch (Exception e)
{
MessageBox.Show("Ups, da ist was schief gelaufen: \n" + e.Message, "Fehler", MessageBoxButton.OK);
}
}
#endregion
private void LeseDateiFallsVorhanden()
{
try
{
if (File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChat.txt")))
{
List<string> merkdaten = new List<string>();
using (StreamReader sr = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChat.txt"), true))
var lines = new List<string>();
using(var streamReader = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), true))
{
string line = "";
string line;
while ((line = sr.ReadLine()) != null)
while((line = streamReader.ReadLine()) != null)
{
var encodedTextBytes = Convert.FromBase64String(line);
string plainText = Encoding.UTF8.GetString(encodedTextBytes);
var plainText = Encoding.UTF8.GetString(encodedTextBytes);
merkdaten.Add(plainText);
lines.Add(plainText);
}
}
if (merkdaten.Count == 2)
if(lines.Count == 2)
{
TextBoxKundennummer.Text = merkdaten[0];
TextBoxChatCode.Text = merkdaten[1];
_Kundennummer = lines[0];
_ChatCode = lines[1];
}
}
//if (File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"))) {
// List<string> daten = new List<string>();
// using (StreamReader sr = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"), true))
// {
// string line = "";
// while ((line = sr.ReadLine()) != null)
// {
// var encodedTextBytes = Convert.FromBase64String(line);
// string plainText = Encoding.UTF8.GetString(encodedTextBytes);
// daten.Add(plainText);
// }
// }
// if(daten.Count == 3) {
// TextBoxBenutzerName.Text = daten[0];
// TextBoxPasswort.Password = daten[1];
// // Merken.IsChecked = Convert.ToBoolean(daten[2]);
// }
//}
}
catch (Exception e)
catch(Exception e)
{
MessageBox.Show("Ups, da ist was schief gelaufen: \n" + e.Message, "Fehler", MessageBoxButton.OK);
MessageBox.Show("Fehler: \n" + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void LeseDateiFallsVorhanden()
{
LoadTenantAndChatCodeFromFile();
}
private void AutosetDaten()
{
try
{
if (!File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt")))
if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName)))
{
using (
StreamWriter sw = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt")))
{
Encoding enc = new UTF8Encoding();
var byt = enc.GetBytes(TextBoxKundennummer.Text);
var bytes = Convert.ToBase64String(byt);
var byt2 = enc.GetBytes(TextBoxChatCode.Text);
var bytes2 = Convert.ToBase64String(byt2);
sw.WriteLine(bytes);
sw.WriteLine(bytes2);
File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"),
FileAttributes.ReadOnly);
}
File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), FileAttributes.Normal);
File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName));
}
else
using(var streamWriter = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName)))
{
File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"), FileAttributes.Normal);
File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"));
Encoding utf8Encoding = new UTF8Encoding();
var tenantBytes = utf8Encoding.GetBytes(_Kundennummer);
var encodedTenant = Convert.ToBase64String(tenantBytes);
using (
StreamWriter sw = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt")))
{
var chatCodeBytes = utf8Encoding.GetBytes(_ChatCode);
var encodedChatCode = Convert.ToBase64String(chatCodeBytes);
Encoding enc = new UTF8Encoding();
var byt = enc.GetBytes(TextBoxKundennummer.Text);
var bytes = Convert.ToBase64String(byt);
streamWriter.WriteLine(encodedTenant);
streamWriter.WriteLine(encodedChatCode);
var byt2 = enc.GetBytes(TextBoxChatCode.Text);
var bytes2 = Convert.ToBase64String(byt2);
sw.WriteLine(bytes);
sw.WriteLine(bytes2);
File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"),
FileAttributes.ReadOnly);
}
File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), FileAttributes.ReadOnly);
}
}
catch (Exception e)
{
MessageBox.Show("Ups, da ist was schief gelaufen: \n" + e.Message, "Fehler", MessageBoxButton.OK);
MessageBox.Show("Fehler: \n" + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
@@ -276,19 +246,20 @@ namespace ChatController
{
try
{
string localAppData = Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData);
string companyFilePath
= Path.Combine(localAppData, "beyondSoft");
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var companyFilePath = Path.Combine(localAppData, "beyondSoft");
if (!Directory.Exists(companyFilePath))
{
Directory.CreateDirectory(companyFilePath);
}
string bewoFilePath
= Path.Combine(companyFilePath, "OwnChat");
var bewoFilePath = Path.Combine(companyFilePath, "OwnChat");
if (!Directory.Exists(bewoFilePath))
{
Directory.CreateDirectory(bewoFilePath);
}
return bewoFilePath;
}
@@ -301,157 +272,17 @@ namespace ChatController
return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}
#endregion
//Neue Region zum VErschlüsseln und entschlüsseln der Daten
#region Verschlüsseln/Entschlüsseln via Link // wird ersmal nicht mehr gebraucht
//TODO Kann erst nach erfolgreichem Login verschlüsselt werden
private bool Verschluss()
{
try
{
string URl = _newUrl + "api/ownchat/user/encryptcredentials";
string postdaten = "";
Dictionary<string, string> postparameter = new Dictionary<string, string>();
postparameter.Add("username", _benutzername);
postparameter.Add("password", _passwort);
//neu | hinzufügen laut document
postparameter.Add("chatcode", _chatCode);
int i = 0;
foreach (var key in postparameter.Keys)
{
//hier noch chatcode übergeben
postdaten += HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(postparameter[key]) + "&";
}
WebRequest requesten = WebRequest.Create(URl);
requesten.Method = "POST";
requesten.ContentType = "application/x-www-form-urlencoded";
requesten.Headers["Token"] = _authToken;
requesten.Headers["CustomerID"] = _kundennummer;
byte[] daten = Encoding.ASCII.GetBytes(postdaten);
requesten.ContentLength = daten.Length;
try
{
Stream requestStream = requesten.GetRequestStream();
requestStream.Write(daten, 0, daten.Length);
requestStream.Close();
}
catch (Exception e)
{
MessageBox.Show("Es konnte keine Verbindung aufgebaut werden.", "Fehler", MessageBoxButton.OK);
return false;
}
//response bereich | Verarbeiten
HttpWebResponse myHttpWebResponse = (HttpWebResponse)requesten.GetResponse();
Stream responseStream = myHttpWebResponse.GetResponseStream();
StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
var pageContent = myStreamReader.ReadToEnd();
//Bereich zum Verarbeiten der Erhaltenen Daten
var definiti = new { encryped = ""};
var jsonDatentyp = JsonConvert.DeserializeAnonymousType(pageContent, definiti);
return true;
}
catch (Exception e)
{
MessageBox.Show("Beim Verschlüsseln ist was schief gelaufen. \n" + e.Message,"Fehler",MessageBoxButton.OK);
return false;
}
}
private byte[] mediaDatei;
//TODO Entschluss weiter ausprogrammieren
private bool Entschluss()
{
try
{
string URl = _newUrl + "api/ownchat/user/decryptcredentials";
WebRequest requesten = WebRequest.Create(URl);
requesten.Method = "POST";
requesten.ContentType = "application/x-www-form-urlencoded";
requesten.Headers["CustomerID"] = _kundennummer;
byte[] daten = mediaDatei;
requesten.ContentLength = daten.Length;
try
{
Stream requestStream = requesten.GetRequestStream();
requestStream.Write(daten, 0, daten.Length);
requestStream.Close();
}
catch (Exception e)
{
MessageBox.Show("Es konnte keine Verbindung aufgebaut werden.", "Fehler", MessageBoxButton.OK);
return false;
}
//erhalte response
HttpWebResponse myHttpWebResponse = (HttpWebResponse)requesten.GetResponse();
Stream responseStream = myHttpWebResponse.GetResponseStream();
StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
var pageContent = myStreamReader.ReadToEnd();
//Bereich zum Verarbeiten der Erhaltenen Daten
var definiti = new { encrypted = "" };
var jsonDatentyp = JsonConvert.DeserializeAnonymousType(pageContent, definiti);
return true;
}
catch (Exception e)
{
MessageBox.Show("Beim Entschlüsseln ist was schief gelaufen. \n" + e.Message, "Fehler", MessageBoxButton.OK);
return false;
}
}
#endregion
public void Login()
{
Anmelden();
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

View File

@@ -2,47 +2,33 @@
{
public class ChatDatenUebergabe
{
private AuthenticationData _serverconect { get; }
private UserDaten _angemeldeterUser { get; }
private ChatGruppenDaten _alleGruppen { get; }
public UserDaten LoggedInUser { get; }
private string _ServerUrl { get; }
private string _AuthToken { get; }
private long? _Userid { get; }
private string _Tenant { get; }
private string _ApiKey { get; }
private long _MaxUploadSize { get; }
public ChatGruppenDaten AlleGruppen { get; }
public ChatDatenUebergabe(AuthenticationData serverConect, UserDaten angemeldeterUser, ChatGruppenDaten alleGruppen, string serverUrl, string authToken, long? userid, string kundennummer, string apikey,long maxUploadSize)
public string ServerUrl { get; }
public string AuthToken { get; }
public long? Userid { get; }
public string Kundennummer { get; }
public string ApiKey { get; }
public long MaxUploadSize { get; }
public ChatDatenUebergabe(UserDaten loggedInUser, ChatGruppenDaten alleGruppen, string serverUrl, string authToken, long? userid, string kundennummer, string apikey,long maxUploadSize)
{
_serverconect = serverConect;
_angemeldeterUser = angemeldeterUser;
_alleGruppen = alleGruppen;
LoggedInUser = loggedInUser;
AlleGruppen = alleGruppen;
_ServerUrl = serverUrl;
_AuthToken = authToken;
_Userid = userid;
_Tenant = kundennummer;
_ApiKey = apikey;
_MaxUploadSize = maxUploadSize;
ServerUrl = serverUrl;
AuthToken = authToken;
Userid = userid;
Kundennummer = kundennummer;
ApiKey = apikey;
MaxUploadSize = maxUploadSize;
}
public AuthenticationData Serverconect => _serverconect;
public UserDaten AngemeldeterUser => _angemeldeterUser;
public ChatGruppenDaten AlleGruppen => _alleGruppen;
public string ServerUrl => _ServerUrl;
public string AuthToken => _AuthToken;
public long? Userid => _Userid;
public string Kundennummer => _Tenant;
public string ApiKey => _ApiKey;
public long MaxUploadSize => _MaxUploadSize;
}
}

View File

@@ -1,14 +1,15 @@
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace ChatController.LoginKlassen
{
/// <summary>
/// Konvertiertes Objekt vom Server mit den Gruppen, Meldungen, Fehlern und ob die Abfragen an den Server erfolgreich war
/// </summary>
public class ChatGruppenDaten
{
public Dictionary<string, GroupInput[]> Response { get; set; }
public string Message { get; set; }
public string Errors { get; set; }
public bool Success { get; set; }
public ChatGruppenDatenResponse Response { get; set; }
}
public class GroupInput
@@ -20,13 +21,22 @@ namespace ChatController.LoginKlassen
public GroupLatestMessage LastMessage { get; set; }
public GroupUsers[] Users { get; set; }
public bool OnlyEmployees { get; set; }
[JsonProperty("accent_color")]
public string AccentColor { get; set; }
[JsonProperty("i_can_write")]
public bool CanWrite { get; set; }
[JsonProperty("i_can_see_participants")]
public bool CanSeeParticipants { get; set; }
}
public class GroupLatestMessage
{
public long Id { get; set; }
private string _Text;
private string _Text;
public string Text
{
get
@@ -78,4 +88,9 @@ namespace ChatController.LoginKlassen
public int TimeZoneType { get; set; }
public string TimeZone { get; set; }
}
public class ChatGruppenDatenResponse
{
public List<GroupInput> Groups { get; set; }
}
}

View File

@@ -10,16 +10,12 @@ namespace ChatController.LoginKlassen
public string Message { get; set; }
public Tetserror Errors { get; set; }
[JsonProperty("errors")]
public OwnChatLoginError Error { get; set; }
public bool Success { get; set; }
}
public class InputTest
{
public OwnChatLoginResponse User { get; set; }
}
public class OwnChatLoginResponse
{
[JsonProperty("file_upload_max_size")]
@@ -30,10 +26,13 @@ namespace ChatController.LoginKlassen
public OwnChatUser User { get; set; }
}
public class Tetserror
public class OwnChatLoginError
{
public string[] chatcode_failed{ get; set; }
public string[] login_failed { get; set; }
[JsonProperty("chatcode_failed")]
public string[] ChatCodeFailed { get; set; }
[JsonProperty("login_failed")]
public string[] LoginFailed { get; set; }
}
public class OwnChatUser

View File

@@ -106,6 +106,15 @@ namespace ChatController {
}
}
/// <summary>
/// Looks up a localized string similar to Office Dokumente und Bilder |*.doc;*.docx;*.xls;*.ppt;*.txt;*.pdf;*.jpg;*.png;*.jpeg;*.jpe;*.gif;*.bmp.
/// </summary>
public static string OpenFileDialogFilter_Test {
get {
return ResourceManager.GetString("OpenFileDialogFilter_Test", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>

View File

@@ -160,4 +160,7 @@
<data name="SyncFile2Name" xml:space="preserve">
<value>ownChatNewMessageSync.txt</value>
</data>
<data name="OpenFileDialogFilter_Test" xml:space="preserve">
<value>Office Dokumente und Bilder |*.doc;*.docx;*.xls;*.ppt;*.txt;*.pdf;*.jpg;*.png;*.jpeg;*.jpe;*.gif;*.bmp</value>
</data>
</root>

View File

@@ -20,9 +20,16 @@ namespace ChatController.Utilities
public static readonly string GetChatGroupsUrl = "/api/chat/groups";
public static readonly string LoadMessagesForGroupUrl = "/api/chat/messages?groupid=";
public static readonly string LoadOwnChatNewsUrl = "/api/ownchat/news/";
public static readonly string SendMessageUrl = "/api/chat/messages/send";
public static readonly string UrlPageParameter = "&page=";
public static readonly int NotificationTimeout = 1500;
public static readonly string ContentTypeKey = "content-type";
public static readonly string FormUrlEncodedContentTypeValue = "application/x-www-form-urlencoded";
public static readonly string MultipartContentTypeValue = "multipart/form-data";
public static readonly string TenantAndChatCodeFileName = "ownChat.txt";
}
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Windows;
using System.Windows.Threading;
namespace ChatController.Utilities.Extensions
{
public static class ControlExtensions
{
private static readonly Action _EmptyDelegate = delegate { };
public static void Dispatch(this DispatcherObject p, Action action)
{
p.Dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
}
public static void RefreshUI(this UIElement uiElement)
{
uiElement.Dispatcher.Invoke(DispatcherPriority.Render, _EmptyDelegate);
}
}
}

View File

@@ -0,0 +1,131 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
namespace ChatController.Utilities
{
public class FileUtils
{
public static string ScaleImage(string pFile, string pFormat, long maxUploadSize)
{
try
{
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);
}
var filePath = Path.GetTempPath() + Guid.NewGuid() + 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;
}
}
public static bool CheckFileSize(string pathToFile, long maxFileSize)
{
var fileInfo = new FileInfo(pathToFile);
return fileInfo.Length > maxFileSize;
}
}
}

View File

@@ -0,0 +1,12 @@
namespace ChatController.Utilities
{
public enum ChatMessageType
{
Message,
Image,
DefaultImage,
Document,
Hyperlink,
Separator
}
}

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
@@ -6,7 +7,6 @@ using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
@@ -19,16 +19,91 @@ namespace ChatController.Utilities
{
public class Utils
{
public static DateTime DefaultDate = new DateTime(1,1,1);
public static string AuthToken { get; set; }
public static string Tenant { get; set; }
public static DateTime DefaultDate = new DateTime(1, 1, 1);
public static ImageSource AvatarToImageSourceConverter(string pAvatarPath, bool pIsEmployee, bool pIsGroup)
{
return CreateImageSourceFromPath(pAvatarPath, pIsGroup, pIsEmployee);
}
public static ImageSource CreateChatGroupPictureImageSource(string pPicturePath, bool pIsGroup, bool pIsEmployee)
public static Bitmap ConvertAvatarToBitmap(string linkToPicture, bool isEmployee, bool isGroup)
{
return CreateImageSourceFromPath(pPicturePath, pIsGroup, pIsEmployee);
Bitmap bitmap = null;
if(!string.IsNullOrWhiteSpace(linkToPicture))
{
var client = new RestClient(linkToPicture);
var request = new RestRequest(Method.GET)
{
ResponseWriter = responseStream =>
{
try
{
bitmap = new Bitmap(responseStream);
}
catch(Exception exception)
{
}
}
};
request.AddHeader(Constants.Token, AuthToken);
request.AddHeader(Constants.CustomerId, Tenant);
client.DownloadData(request);
}
if(bitmap != null)
{
return bitmap;
}
var defaultBitmap = (BitmapImage) GetDefaultImageSource(isGroup, isEmployee);
using(var outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(defaultBitmap));
enc.Save(outStream);
return new Bitmap(outStream);
}
}
public static void DownloadProfilePictureAsync(string avatarPath, bool isEmployee, bool isGroup, Action<ImageSource> callback)
{
var url = avatarPath;
var client = new RestClient(url);
var request = new RestRequest
{
ResponseWriter = stream =>
{
var bitmap = new BitmapImage();
var localStream = new MemoryStream();
stream.CopyTo(localStream);
localStream.Position = 0;
bitmap.BeginInit();
bitmap.StreamSource = localStream;
bitmap.EndInit();
bitmap.Freeze();
callback?.Invoke(bitmap);
}
};
}
private static ImageSource GetDefaultImageSource(bool pIsGroup, bool pIsEmployee)
@@ -43,7 +118,7 @@ namespace ChatController.Utilities
{
defaultImage = Constants.CustomerDefaultImagePath;
}
var resultBitmapImage = new BitmapImage();
resultBitmapImage.BeginInit();
@@ -60,6 +135,7 @@ namespace ChatController.Utilities
Bitmap bitmap = null;
var client = new RestClient(pPathToImageFile);
var request = new RestRequest(Method.GET)
{
ResponseWriter = stream =>
@@ -75,6 +151,9 @@ namespace ChatController.Utilities
}
};
request.AddHeader(Constants.Token, AuthToken);
request.AddHeader(Constants.CustomerId, Tenant);
client.DownloadData(request);
if (bitmap != null)
@@ -92,9 +171,6 @@ namespace ChatController.Utilities
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
memoryStream.Dispose();
memoryStream.Close();
return bitmapImage;
}
}
@@ -102,42 +178,6 @@ namespace ChatController.Utilities
return GetDefaultImageSource(pIsGroup, pIsEmployee);
}
public static ImageSource CreateImageSourceFromSmallerImage(string pUri)
{
Bitmap bitmap;
var request = WebRequest.Create(pUri);
using(var response = request.GetResponse())
{
using(var stream = response.GetResponseStream())
{
if(stream == null)
{
return null;
}
bitmap = new Bitmap(stream);
}
}
using(var memoryStream = new MemoryStream())
{
bitmap.Save(memoryStream, ImageFormat.Png);
memoryStream.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
memoryStream.Dispose();
memoryStream.Close();
return bitmapImage;
}
}
public static string ReadStream(WebResponse response)
{
@@ -226,7 +266,6 @@ namespace ChatController.Utilities
graphics.DrawIcon(pIcon, 0, 0);
graphics.Dispose();
bitmap.Save("icon.ico", ImageFormat.Icon);
@@ -289,10 +328,6 @@ namespace ChatController.Utilities
return Icon.FromHandle(bitmap.GetHicon());
}
public static DateTime FromUnixTimeStamp(long pUnixTimeStamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(pUnixTimeStamp);
}
public static byte[] ReadFully(Stream pStream)
{
using (var memStream = new MemoryStream())
@@ -326,5 +361,97 @@ namespace ChatController.Utilities
return RotateFlipType.RotateNoneFlipNone;
}
}
public static List<T> GetVisualChildCollection<T>(object parent) where T : Visual
{
var visualCollection = new List<T>();
GetVisualChildCollection(parent as DependencyObject, visualCollection);
return visualCollection;
}
public static void GetVisualChildCollection<T>(DependencyObject parent, ICollection<T> visualCollection) where T : Visual
{
var count = VisualTreeHelper.GetChildrenCount(parent);
for(var i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if(child is T item)
{
visualCollection.Add(item);
}
else
{
GetVisualChildCollection(child, visualCollection);
}
}
}
/*
* try
{
using (var form = new Form())
{
using (var ms = new MemoryStream(e.Result))
{
var image = System.Drawing.Image.FromStream(ms);
using (var bitmap = new Bitmap(image))
{
short orient = 0;
const int orientationId = 0x0112;
if (image.PropertyIdList.Contains(orientationId))
{
var item = image.GetPropertyItem(orientationId);
orient = BitConverter.ToInt16(item.Value, 0);
bitmap.SetPropertyItem(item);
}
var flipType = Utils.OrientationToFlipType(orient.ToString());
bitmap.RotateFlip(flipType);
form.StartPosition = FormStartPosition.CenterScreen;
form.ClientSize = bitmap.Size;
form.FormBorderStyle = FormBorderStyle.Sizable;
form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
using (var pictureBox = new PictureBox())
{
pictureBox.Dock = DockStyle.Fill;
pictureBox.Image = bitmap;
pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
form.Controls.Add(pictureBox);
downloadCompletedCallback?.Invoke();
form.ShowDialog();
}
}
}
}
*/
public Bitmap ConvertStreamToBitmap(Stream imageStream)
{
try
{
var image = Image.FromStream(imageStream);
return null;
}
catch(Exception exception)
{
throw exception;
}
}
}
}

View File

@@ -1,5 +1,4 @@
using System.Windows.Input;
using ChatController;
using ChatController.LoginKlassen;
namespace ownChat

View File

@@ -40,6 +40,7 @@ namespace ownChat
private void MainWindow_OnClosed(object sender, EventArgs e)
{
ChatMainControl.DeleteTempFiles();
ChatMainControl.WriteToNewSyncFile();
ChatMainControl.ClearNotifications();
Environment.Exit(0);

View File

@@ -72,6 +72,9 @@
<ApplicationIcon>ownchat_favicon.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="DevExpress.Mvvm.v17.1, Version=17.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Newtonsoft.Json">
<HintPath>..\libs\Newtonsoft.Json.dll</HintPath>
</Reference>