diff --git a/.vs/Server Dashboard/DesignTimeBuild/.dtbcache.v2 b/.vs/Server Dashboard/DesignTimeBuild/.dtbcache.v2 index cf13afc..a58d5a4 100644 Binary files a/.vs/Server Dashboard/DesignTimeBuild/.dtbcache.v2 and b/.vs/Server Dashboard/DesignTimeBuild/.dtbcache.v2 differ diff --git a/.vs/Server Dashboard/v16/.suo b/.vs/Server Dashboard/v16/.suo index ee03118..969c625 100644 Binary files a/.vs/Server Dashboard/v16/.suo and b/.vs/Server Dashboard/v16/.suo differ diff --git a/Server Dashboard Socket/Channel/ClientChannel.cs b/Server Dashboard Socket/Channel/ClientChannel.cs index 8237350..ffb0802 100644 --- a/Server Dashboard Socket/Channel/ClientChannel.cs +++ b/Server Dashboard Socket/Channel/ClientChannel.cs @@ -6,13 +6,14 @@ using System.Text; using System.Threading.Tasks; namespace Server_Dashboard_Socket { + /// /// Client Socket /// /// The Protocol type, either JsonMessageProtocol or XmlMessageProtocol /// The message type, either JObject or XDocument public class ClientChannel : SocketChannel - where TProtocol : Protocol, new(){ + where TProtocol : Protocol, new() { /// /// Connect to the socket async @@ -28,4 +29,4 @@ namespace Server_Dashboard_Socket { Attach(socket); } } -} +} \ No newline at end of file diff --git a/Server Dashboard Socket/Channel/SocketChannel.cs b/Server Dashboard Socket/Channel/SocketChannel.cs index d85b4f0..ff210ad 100644 --- a/Server Dashboard Socket/Channel/SocketChannel.cs +++ b/Server Dashboard Socket/Channel/SocketChannel.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; namespace Server_Dashboard_Socket { + /// /// Generic Channel class that handles the connection and message sending / receiving /// Inherits IDisposable to correctly cut the connection to the server @@ -14,13 +15,12 @@ namespace Server_Dashboard_Socket { /// The message type, either JObject or XDocument public abstract class SocketChannel : IDisposable where TProtocol : Protocol, new() { - protected bool isDisposable = false; - NetworkStream networkStream; - readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - readonly TProtocol protocol = new TProtocol(); + private NetworkStream networkStream; + private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + private readonly TProtocol protocol = new TProtocol(); - Func messageCallback; + private Func messageCallback; /// /// Attaches the socket to a network stream that owns the socket @@ -69,10 +69,12 @@ namespace Server_Dashboard_Socket { /// Deconstructor sets Dispose to false /// ~SocketChannel() => Dispose(false); + /// /// Sets dispose to true /// public void Dispose() => Dispose(true); + /// /// Disposes open sockets /// @@ -86,10 +88,10 @@ namespace Server_Dashboard_Socket { Close(); //If its closed, dispose it networkStream?.Dispose(); - //Wait with the garbage collection untill the disposing is done + //Wait with the garbage collection until the disposing is done if (isDisposing) GC.SuppressFinalize(this); } } } -} +} \ No newline at end of file diff --git a/Server Dashboard Socket/Client/SocketClient.cs b/Server Dashboard Socket/Client/SocketClient.cs index 3cb7517..ca44d7a 100644 --- a/Server Dashboard Socket/Client/SocketClient.cs +++ b/Server Dashboard Socket/Client/SocketClient.cs @@ -11,6 +11,7 @@ using Newtonsoft.Json.Linq; using System.Xml.Linq; namespace Server_Dashboard_Socket { + public class SocketClient { public SocketClient() { @@ -22,7 +23,7 @@ namespace Server_Dashboard_Socket { } private async void Start() { - //Creates a new endpoint with the IP adress and port + //Creates a new endpoint with the IP address and port var endpoint = new IPEndPoint(IPAddress.Loopback, 9000); //Creates a new Channel for the Json protocol @@ -50,16 +51,17 @@ namespace Server_Dashboard_Socket { /// /// The json to be converted back /// Task completed - static Task OnMessage(JObject jobject) { + private static Task OnMessage(JObject jobject) { Console.WriteLine(Convert(jobject)); return Task.CompletedTask; } + /// /// When it receives a message it gets converted from XDocument back to MyMessage /// /// The xml to be converted back /// Task completed - static Task OnMessage(XDocument xDocument) { + private static Task OnMessage(XDocument xDocument) { Console.WriteLine(Convert(xDocument)); return Task.CompletedTask; } @@ -69,14 +71,14 @@ namespace Server_Dashboard_Socket { /// /// The json to be converted /// MyMessage object - static MyMessage Convert(JObject jObject) => jObject.ToObject(typeof(MyMessage)) as MyMessage; + private static MyMessage Convert(JObject jObject) => jObject.ToObject(typeof(MyMessage)) as MyMessage; /// /// Converts XDocument to MyMessage /// /// The xml to be converted /// MyMessage object - static MyMessage Convert(XDocument xmlDocument) => new XmlSerializer(typeof(MyMessage)).Deserialize(new StringReader(xmlDocument.ToString())) as MyMessage; + private static MyMessage Convert(XDocument xmlDocument) => new XmlSerializer(typeof(MyMessage)).Deserialize(new StringReader(xmlDocument.ToString())) as MyMessage; } /// @@ -87,4 +89,4 @@ namespace Server_Dashboard_Socket { public int IntProperty { get; set; } public string StringProperty { get; set; } } -} +} \ No newline at end of file diff --git a/Server Dashboard Socket/EchoServer.cs b/Server Dashboard Socket/EchoServer.cs index ab52804..2d4339b 100644 --- a/Server Dashboard Socket/EchoServer.cs +++ b/Server Dashboard Socket/EchoServer.cs @@ -4,10 +4,12 @@ using System.Net.Sockets; using System.Threading.Tasks; namespace Server_Dashboard_Socket { + /// /// Basic echo server to test the socket connection /// public class EchoServer { + /// /// Start the socket on 127.0.0.1:9000 /// @@ -32,27 +34,26 @@ namespace Server_Dashboard_Socket { /// poop private async Task DoEcho(Socket socket) { while (true) { - //Listen for incomming connection requests and accept them + //Listen for incoming connection requests and accept them Socket clientSocket = await Task.Factory.FromAsync( new Func(socket.BeginAccept), new Func(socket.EndAccept), null).ConfigureAwait(false); //Create a network stream and make it the owner of the socket //This will close the socket if the stream is closed and vice verca - using(NetworkStream stream = new NetworkStream(clientSocket, true)) { - //New buffer for the message in bytes - byte[] buffer = new byte[1024]; - while (true) { - //Read everything that somes in - int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); - //If its 0 just leave since its a obscolete connection - if (bytesRead == 0) - break; - //Send it back to the sender - await stream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false); - } + await using NetworkStream stream = new NetworkStream(clientSocket, true); + //New buffer for the message in bytes + byte[] buffer = new byte[1024]; + while (true) { + //Read everything that comes in + int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); + //If its 0 just leave since its a obsolete connection + if (bytesRead == 0) + break; + //Send it back to the sender + await stream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false); } } } } -} +} \ No newline at end of file diff --git a/Server Dashboard Socket/Protocol/JsonMessageProtocol.cs b/Server Dashboard Socket/Protocol/JsonMessageProtocol.cs index 0683a4c..e1c67cd 100644 --- a/Server Dashboard Socket/Protocol/JsonMessageProtocol.cs +++ b/Server Dashboard Socket/Protocol/JsonMessageProtocol.cs @@ -7,21 +7,21 @@ using System.IO; using System.Text; namespace Server_Dashboard_Socket.Protocol { + /// /// Json serializer class /// public class JsonMessageProtocol : Protocol { //The Json serializer and the settings - static readonly JsonSerializer serializer; - static readonly JsonSerializerSettings settings; + private static readonly JsonSerializer serializer; /// /// Settings for the Json Serializer /// static JsonMessageProtocol() { //Set the settings - settings = new JsonSerializerSettings { + JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateTimeZoneHandling = DateTimeZoneHandling.Utc, ContractResolver = new DefaultContractResolver { @@ -34,6 +34,7 @@ namespace Server_Dashboard_Socket.Protocol { //Creates the serializer with the settings serializer = JsonSerializer.Create(settings); } + //Decode the message, to Json protected override JObject Decode(byte[] message) => JObject.Parse(Encoding.UTF8.GetString(message)); @@ -50,4 +51,4 @@ namespace Server_Dashboard_Socket.Protocol { return Encoding.UTF8.GetBytes(sb.ToString()); } } -} +} \ No newline at end of file diff --git a/Server Dashboard Socket/Protocol/Protocol.cs b/Server Dashboard Socket/Protocol/Protocol.cs index 1135573..0b67e08 100644 --- a/Server Dashboard Socket/Protocol/Protocol.cs +++ b/Server Dashboard Socket/Protocol/Protocol.cs @@ -6,13 +6,15 @@ using System.Text; using System.Threading.Tasks; namespace Server_Dashboard_Socket { + /// /// Generic Protocol class for Json and Xml serialization /// /// JsonMessageProtocol or XmlMessageProtocol public abstract class Protocol { + //Header size is always 4 - const int HEADER_SIZE = 4; + private const int HeaderSize = 4; /// /// Gets the message and checks with the header if the message is valid or not @@ -26,7 +28,7 @@ namespace Server_Dashboard_Socket { //Validates the length AssertValidMessageLength(bodyLength); //Returns the body message type - return await Readbody(networkStream, bodyLength).ConfigureAwait(false); + return await ReadBody(networkStream, bodyLength).ConfigureAwait(false); } /// @@ -50,8 +52,8 @@ namespace Server_Dashboard_Socket { /// /// A network stream /// Header as Integer - async Task ReadHeader(NetworkStream networkStream) { - byte[] headerBytes = await ReadAsync(networkStream, HEADER_SIZE).ConfigureAwait(false); + private async Task ReadHeader(NetworkStream networkStream) { + byte[] headerBytes = await ReadAsync(networkStream, HeaderSize).ConfigureAwait(false); return IPAddress.HostToNetworkOrder(BitConverter.ToInt32(headerBytes)); } @@ -61,7 +63,7 @@ namespace Server_Dashboard_Socket { /// A network stream /// Length of the body /// Decoded body - async Task Readbody(NetworkStream networkStream, int bodyLength) { + private async Task ReadBody(NetworkStream networkStream, int bodyLength) { //Reads the bytes from the stream into an array byte[] bodyBytes = await ReadAsync(networkStream, bodyLength).ConfigureAwait(false); //Decodes it and returns the string @@ -74,13 +76,13 @@ namespace Server_Dashboard_Socket { /// A network stream /// how many bytes there are to read /// Every byte from the Stream - async Task ReadAsync(NetworkStream networkStream, int bytesToRead) { + private async Task ReadAsync(NetworkStream networkStream, int bytesToRead) { //new buffer that is as big as the content(watch out for buffer overflows) byte[] buffer = new byte[bytesToRead]; - //keep acount of the bytes that are already read + //keep account of the bytes that are already read int bytesRead = 0; //White we still have something to read - while(bytesRead < bytesToRead){ + while (bytesRead < bytesToRead) { //Read it from the stream var bytesReceived = await networkStream.ReadAsync(buffer, bytesRead, (bytesToRead - bytesRead)).ConfigureAwait(false); //If it happens to be 0 close the socket @@ -94,7 +96,7 @@ namespace Server_Dashboard_Socket { /// /// Encode the message from human readable to bytes for the stream /// - /// The message as anything e.g. object or strng + /// The message as anything e.g. object or string /// The message to be send /// The Header and Body as bytes[] protected (byte[] header, byte[] body) Encode(T message) { @@ -121,12 +123,13 @@ namespace Server_Dashboard_Socket { if (messageLength < 1) throw new ArgumentOutOfRangeException("Invalid message length"); } + /// /// Encode the message so it can be send via the network stream /// /// Message type e.g. object or string /// The message to be send /// - protected abstract byte[] EncodeBody (T message); + protected abstract byte[] EncodeBody(T message); } -} +} \ No newline at end of file diff --git a/Server Dashboard Socket/bin/Debug/netcoreapp3.1/Server Dashboard Socket.dll b/Server Dashboard Socket/bin/Debug/netcoreapp3.1/Server Dashboard Socket.dll index 73421ca..1bd2888 100644 Binary files a/Server Dashboard Socket/bin/Debug/netcoreapp3.1/Server Dashboard Socket.dll and b/Server Dashboard Socket/bin/Debug/netcoreapp3.1/Server Dashboard Socket.dll differ diff --git a/Server Dashboard Socket/bin/Debug/netcoreapp3.1/Server Dashboard Socket.pdb b/Server Dashboard Socket/bin/Debug/netcoreapp3.1/Server Dashboard Socket.pdb index 5d8e128..cfffdd0 100644 Binary files a/Server Dashboard Socket/bin/Debug/netcoreapp3.1/Server Dashboard Socket.pdb and b/Server Dashboard Socket/bin/Debug/netcoreapp3.1/Server Dashboard Socket.pdb differ diff --git a/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.csprojAssemblyReference.cache b/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.csprojAssemblyReference.cache index cb6af33..151a8b4 100644 Binary files a/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.csprojAssemblyReference.cache and b/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.csprojAssemblyReference.cache differ diff --git a/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.dll b/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.dll index 73421ca..1bd2888 100644 Binary files a/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.dll and b/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.dll differ diff --git a/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.pdb b/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.pdb index 5d8e128..cfffdd0 100644 Binary files a/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.pdb and b/Server Dashboard Socket/obj/Debug/netcoreapp3.1/Server Dashboard Socket.pdb differ diff --git a/Server Dashboard/App.xaml b/Server Dashboard/App.xaml index cf4f5d7..42f442e 100644 --- a/Server Dashboard/App.xaml +++ b/Server Dashboard/App.xaml @@ -9,18 +9,18 @@ - + - + - - - + + + - Open Sans + Open Sans - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + - + - + - + - + - + @@ -330,26 +337,26 @@ - + \ No newline at end of file diff --git a/Server Dashboard/Assets/Images/JetBrains.ReSharper.web.exe b/Server Dashboard/Assets/Images/JetBrains.ReSharper.web.exe new file mode 100644 index 0000000..acd2b40 Binary files /dev/null and b/Server Dashboard/Assets/Images/JetBrains.ReSharper.web.exe differ diff --git a/Server Dashboard/AttachedProperty/BaseAttachedProperty.cs b/Server Dashboard/AttachedProperty/BaseAttachedProperty.cs index 1046070..c50fe4b 100644 --- a/Server Dashboard/AttachedProperty/BaseAttachedProperty.cs +++ b/Server Dashboard/AttachedProperty/BaseAttachedProperty.cs @@ -4,22 +4,30 @@ using System.Text; using System.Windows; namespace Server_Dashboard { + /// /// Attached property base class /// - /// - /// - public abstract class BaseAttachedProperty - where Parent : BaseAttachedProperty, new() { + /// + /// + public abstract class BaseAttachedProperty + where TParent : BaseAttachedProperty, new() { + public event Action ValueChanged = (sender, e) => { }; - public static Parent Instance { get; private set; } = new Parent(); - public static readonly DependencyProperty ValueProperty = DependencyProperty.RegisterAttached("Value", typeof(Property), typeof(BaseAttachedProperty), new PropertyMetadata(new PropertyChangedCallback(OnValuePropertyChanged))); + + public static TParent Instance { get; private set; } = new TParent(); + public static readonly DependencyProperty ValueProperty = DependencyProperty.RegisterAttached("Value", typeof(TProperty), typeof(BaseAttachedProperty), new PropertyMetadata(new PropertyChangedCallback(OnValuePropertyChanged))); + private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Instance.OnValueChanged(d, e); Instance.ValueChanged(d, e); } - public static Property GetValue(DependencyObject d) => (Property)d.GetValue(ValueProperty); - public static void SetValue(DependencyObject d, Property value) => d.SetValue(ValueProperty, value); - public virtual void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { } + + public static TProperty GetValue(DependencyObject d) => (TProperty)d.GetValue(ValueProperty); + + public static void SetValue(DependencyObject d, TProperty value) => d.SetValue(ValueProperty, value); + + public virtual void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { + } } -} +} \ No newline at end of file diff --git a/Server Dashboard/AttachedProperty/HyperlinkProperties.cs b/Server Dashboard/AttachedProperty/HyperlinkProperties.cs index 47d27c6..44055c7 100644 --- a/Server Dashboard/AttachedProperty/HyperlinkProperties.cs +++ b/Server Dashboard/AttachedProperty/HyperlinkProperties.cs @@ -6,7 +6,9 @@ using System.Windows; using System.Windows.Documents; namespace Server_Dashboard { + public static class HyperlinkExtensions { + public static bool GetIsExternal(DependencyObject obj) { return (bool)obj.GetValue(IsExternalProperty); } @@ -14,23 +16,25 @@ namespace Server_Dashboard { public static void SetIsExternal(DependencyObject obj, bool value) { obj.SetValue(IsExternalProperty, value); } + public static readonly DependencyProperty IsExternalProperty = DependencyProperty.RegisterAttached("IsExternal", typeof(bool), typeof(HyperlinkExtensions), new UIPropertyMetadata(false, OnIsExternalChanged)); private static void OnIsExternalChanged(object sender, DependencyPropertyChangedEventArgs args) { var hyperlink = sender as Hyperlink; - if ((bool)args.NewValue) - hyperlink.RequestNavigate += Hyperlink_RequestNavigate; - else + if ((bool)args.NewValue) { + if (hyperlink != null) + hyperlink.RequestNavigate += Hyperlink_RequestNavigate; + } else if (hyperlink != null) hyperlink.RequestNavigate -= Hyperlink_RequestNavigate; } private static void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e) { try { Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true }); - } catch { } + } catch (Exception) { } e.Handled = true; } } -} +} \ No newline at end of file diff --git a/Server Dashboard/AttachedProperty/PasswordBoxProperties.cs b/Server Dashboard/AttachedProperty/PasswordBoxProperties.cs index 132d7b6..37fb622 100644 --- a/Server Dashboard/AttachedProperty/PasswordBoxProperties.cs +++ b/Server Dashboard/AttachedProperty/PasswordBoxProperties.cs @@ -2,17 +2,18 @@ using System.Windows.Controls; namespace Server_Dashboard { + public class MonitorPasswordProperty : BaseAttachedProperty { + public override void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { - var passwordBox = sender as PasswordBox; - if (passwordBox == null) + if (!(sender is PasswordBox passwordBox)) return; passwordBox.PasswordChanged -= PasswordBox_PasswordChanged; - if ((bool)e.NewValue) { - HasTextProperty.SetValue(passwordBox); - passwordBox.PasswordChanged += PasswordBox_PasswordChanged; - } + if (!(bool)e.NewValue) + return; + HasTextProperty.SetValue(passwordBox); + passwordBox.PasswordChanged += PasswordBox_PasswordChanged; } private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e) { @@ -21,8 +22,9 @@ namespace Server_Dashboard { } public class HasTextProperty : BaseAttachedProperty { + public static void SetValue(DependencyObject sender) { SetValue(sender, ((PasswordBox)sender).SecurePassword.Length < 1); } } -} +} \ No newline at end of file diff --git a/Server Dashboard/AttachedProperty/WindowProperties.cs b/Server Dashboard/AttachedProperty/WindowProperties.cs index 68a2709..23e0380 100644 --- a/Server Dashboard/AttachedProperty/WindowProperties.cs +++ b/Server Dashboard/AttachedProperty/WindowProperties.cs @@ -1,7 +1,9 @@ using System.Windows; namespace Server_Dashboard { + public class CloseProperty : BaseAttachedProperty { + public override void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { if (sender is Window window) { window.Loaded += (s, e) => { @@ -14,4 +16,4 @@ namespace Server_Dashboard { } } } -} +} \ No newline at end of file diff --git a/Server Dashboard/Controls/DoubleRoundProgressBar/DoubleRoundProgressBar.xaml b/Server Dashboard/Controls/DoubleRoundProgressBar/DoubleRoundProgressBar.xaml index 7974b65..fa40c89 100644 --- a/Server Dashboard/Controls/DoubleRoundProgressBar/DoubleRoundProgressBar.xaml +++ b/Server Dashboard/Controls/DoubleRoundProgressBar/DoubleRoundProgressBar.xaml @@ -12,7 +12,7 @@ - + diff --git a/Server Dashboard/Controls/DoubleRoundProgressBar/DoubleRoundProgressBar.xaml.cs b/Server Dashboard/Controls/DoubleRoundProgressBar/DoubleRoundProgressBar.xaml.cs index 5023996..45ecb3a 100644 --- a/Server Dashboard/Controls/DoubleRoundProgressBar/DoubleRoundProgressBar.xaml.cs +++ b/Server Dashboard/Controls/DoubleRoundProgressBar/DoubleRoundProgressBar.xaml.cs @@ -1,16 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using System.Windows; +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; namespace Server_Dashboard.Controls.DoubleRoundProgressBar { @@ -20,51 +10,51 @@ namespace Server_Dashboard.Controls.DoubleRoundProgressBar { public partial class DoubleRoundProgressBar : UserControl { //Property for the ReadIndicatorBrush - public static DependencyProperty ReadIndicatorBrushProperty = DependencyProperty.Register("ReadIndicatorBrush", typeof(Brush), typeof(DoubleRoundProgressBar)); + public static readonly DependencyProperty ReadIndicatorBrushProperty = DependencyProperty.Register("ReadIndicatorBrush", typeof(Brush), typeof(DoubleRoundProgressBar)); public Brush ReadIndicatorBrush { - get { return (Brush)GetValue(ReadIndicatorBrushProperty); } - set { SetValue(ReadIndicatorBrushProperty, value); } + get => (Brush)GetValue(ReadIndicatorBrushProperty); + set => SetValue(ReadIndicatorBrushProperty, value); } //Property for the WriteIndicatorBrush - public static DependencyProperty WriteIndicatorBrushProperty = DependencyProperty.Register("WriteIndicatorBrush", typeof(Brush), typeof(DoubleRoundProgressBar)); + public static readonly DependencyProperty WriteIndicatorBrushProperty = DependencyProperty.Register("WriteIndicatorBrush", typeof(Brush), typeof(DoubleRoundProgressBar)); public Brush WriteIndicatorBrush { - get { return (Brush)GetValue(WriteIndicatorBrushProperty); } - set { SetValue(WriteIndicatorBrushProperty, value); } + get => (Brush)GetValue(WriteIndicatorBrushProperty); + set => SetValue(WriteIndicatorBrushProperty, value); } //Property for the BackgroundBrush - public static DependencyProperty BackgroundBrushProperty = DependencyProperty.Register("BackgroundBrush", typeof(Brush), typeof(DoubleRoundProgressBar)); + public static readonly DependencyProperty BackgroundBrushProperty = DependencyProperty.Register("BackgroundBrush", typeof(Brush), typeof(DoubleRoundProgressBar)); public Brush BackgroundBrush { - get { return (Brush)GetValue(BackgroundBrushProperty); } - set { SetValue(BackgroundBrushProperty, value); } + get => (Brush)GetValue(BackgroundBrushProperty); + set => SetValue(BackgroundBrushProperty, value); } //Property for the ProgressBorderBrush - public static DependencyProperty ProgressBorderBrushProperty = DependencyProperty.Register("ProgressBorderBrush", typeof(Brush), typeof(DoubleRoundProgressBar)); + public static readonly DependencyProperty ProgressBorderBrushProperty = DependencyProperty.Register("ProgressBorderBrush", typeof(Brush), typeof(DoubleRoundProgressBar)); public Brush ProgressBorderBrush { - get { return (Brush)GetValue(ProgressBorderBrushProperty); } - set { SetValue(ProgressBorderBrushProperty, value); } + get => (Brush)GetValue(ProgressBorderBrushProperty); + set => SetValue(ProgressBorderBrushProperty, value); } //Property for the Value Write - public static DependencyProperty ValueWriteProperty = DependencyProperty.Register("ValueWrite", typeof(int), typeof(DoubleRoundProgressBar)); + public static readonly DependencyProperty ValueWriteProperty = DependencyProperty.Register("ValueWrite", typeof(int), typeof(DoubleRoundProgressBar)); public int ValueWrite { - get { return (int)GetValue(ValueWriteProperty); } - set { SetValue(ValueWriteProperty, value); } + get => (int)GetValue(ValueWriteProperty); + set => SetValue(ValueWriteProperty, value); } //Property for the Value Read - public static DependencyProperty ValueReadProperty = DependencyProperty.Register("ValueRead", typeof(int), typeof(DoubleRoundProgressBar)); + public static readonly DependencyProperty ValueReadProperty = DependencyProperty.Register("ValueRead", typeof(int), typeof(DoubleRoundProgressBar)); public int ValueRead { - get { return (int)GetValue(ValueReadProperty); } - set { SetValue(ValueReadProperty, value); } + get => (int)GetValue(ValueReadProperty); + set => SetValue(ValueReadProperty, value); } public DoubleRoundProgressBar() { diff --git a/Server Dashboard/Controls/HalfRoundProgressBar/HalfRoundProgressBar.xaml.cs b/Server Dashboard/Controls/HalfRoundProgressBar/HalfRoundProgressBar.xaml.cs index f68b2f7..8fc1584 100644 --- a/Server Dashboard/Controls/HalfRoundProgressBar/HalfRoundProgressBar.xaml.cs +++ b/Server Dashboard/Controls/HalfRoundProgressBar/HalfRoundProgressBar.xaml.cs @@ -1,54 +1,44 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using System.Windows; +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; namespace Server_Dashboard.Controls.HalfRoundProgressBar { /// - /// Dependency Properties + /// Dependency Properties /// public partial class HalfRoundProgressBar : UserControl { //Indicator Brush Property - public static DependencyProperty IndicatorBrushProperty = DependencyProperty.Register("IndicatorBrush", typeof(Brush), typeof(HalfRoundProgressBar)); + public static readonly DependencyProperty IndicatorBrushProperty = DependencyProperty.Register("IndicatorBrush", typeof(Brush), typeof(HalfRoundProgressBar)); public Brush IndicatorBrush { - get { return (Brush)GetValue(IndicatorBrushProperty); } - set { SetValue(IndicatorBrushProperty, value); } + get => (Brush)GetValue(IndicatorBrushProperty); + set => SetValue(IndicatorBrushProperty, value); } //Background Brush Property - public static DependencyProperty BackgroundBrushProperty = DependencyProperty.Register("BackgroundBrush", typeof(Brush), typeof(HalfRoundProgressBar)); + public static readonly DependencyProperty BackgroundBrushProperty = DependencyProperty.Register("BackgroundBrush", typeof(Brush), typeof(HalfRoundProgressBar)); public Brush BackgroundBrush { - get { return (Brush)GetValue(BackgroundBrushProperty); } - set { SetValue(BackgroundBrushProperty, value); } + get => (Brush)GetValue(BackgroundBrushProperty); + set => SetValue(BackgroundBrushProperty, value); } //ProgressBorder Property - public static DependencyProperty ProgressBorderBrushProperty = DependencyProperty.Register("ProgressBorderBrush", typeof(Brush), typeof(HalfRoundProgressBar)); + public static readonly DependencyProperty ProgressBorderBrushProperty = DependencyProperty.Register("ProgressBorderBrush", typeof(Brush), typeof(HalfRoundProgressBar)); public Brush ProgressBorderBrush { - get { return (Brush)GetValue(ProgressBorderBrushProperty); } - set { SetValue(ProgressBorderBrushProperty, value); } + get => (Brush)GetValue(ProgressBorderBrushProperty); + set => SetValue(ProgressBorderBrushProperty, value); } //Value - public static DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(HalfRoundProgressBar)); + public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(HalfRoundProgressBar)); public int Value { - get { return (int)GetValue(ValueProperty); } - set { SetValue(ValueProperty, value); } + get => (int)GetValue(ValueProperty); + set => SetValue(ValueProperty, value); } public HalfRoundProgressBar() { diff --git a/Server Dashboard/Controls/ServerModules/ServerModule.xaml b/Server Dashboard/Controls/ServerModules/ServerModule.xaml index 2421fe8..d0ff7bf 100644 --- a/Server Dashboard/Controls/ServerModules/ServerModule.xaml +++ b/Server Dashboard/Controls/ServerModules/ServerModule.xaml @@ -7,165 +7,264 @@ xmlns:halfroundprogressbar="clr-namespace:Server_Dashboard.Controls.HalfRoundProgressBar" xmlns:doubleroundprogressbar="clr-namespace:Server_Dashboard.Controls.DoubleRoundProgressBar" mc:Ignorable="d"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/Server Dashboard/Database/DatabaseHandler.cs b/Server Dashboard/Database/DatabaseHandler.cs index 8bc1a22..67737fa 100644 --- a/Server Dashboard/Database/DatabaseHandler.cs +++ b/Server Dashboard/Database/DatabaseHandler.cs @@ -1,12 +1,7 @@ -using Microsoft.Win32; -using System; -using System.Collections.Generic; +using System; using System.Configuration; using System.Data; using System.Data.SqlClient; -using System.Reflection; -using System.Threading.Tasks; -using System.Windows.Media.Imaging; namespace Server_Dashboard { @@ -39,17 +34,11 @@ namespace Server_Dashboard { com.Parameters.Add("@valid", SqlDbType.NVarChar, 250); com.Parameters["@valid"].Direction = ParameterDirection.Output; //Execute query and return number of rows affected - int sqlResponse = com.ExecuteNonQuery(); + com.ExecuteNonQuery(); //Checks if there are any rows successful //If the query returns 0 the query wasn't successful - //if its any number above 0 it was successfull - if (Convert.ToInt32(com.Parameters["@Valid"].Value) == 0) { - //Error, not successful - return 1; - } else { - //Successful - return 0; - } + //if its any number above 0 it was successful + return Convert.ToInt32(com.Parameters["@Valid"].Value) == 0 ? 1 : 0; //Catch any error } catch (SqlException ex) { return ex.Number; @@ -66,7 +55,7 @@ namespace Server_Dashboard { //Open the connection con.Open(); //SQL Query - string query = "SELECT ID, Username, Email, RegistrationDate FROM UserData WHERE Username = @username"; + const string query = "SELECT ID, Username, Email, RegistrationDate FROM UserData WHERE Username = @username"; //Creates a new command using SqlCommand com = new SqlCommand(query, con);//For security reasons the values are added with this function //this will avoid SQL Injections @@ -78,9 +67,9 @@ namespace Server_Dashboard { return resultTable; //Checks if there are any rows successful //If the query returns 0 the query wasn't successful - //if its any number above 0 it was successfull + //if its any number above 0 it was successful //Catch any error - } catch (SqlException ex) { + } catch (SqlException) { return null; } finally { //Always close the connection @@ -95,7 +84,7 @@ namespace Server_Dashboard { //Open the connection con.Open(); //SQL Query - string query = "SELECT Creator, CreationTime, ModuleName, MI.Image FROM ModuleData LEFT JOIN ModuleIcon MI on ModuleData.ID = MI.Module WHERE UserID = @userID"; + const string query = "SELECT Creator, CreationTime, ModuleName, MI.Image, ModuleData.ID FROM ModuleData LEFT JOIN ModuleIcon MI on ModuleData.ID = MI.Module WHERE UserID = @userID"; //Creates a new command using SqlCommand com = new SqlCommand(query, con);//For security reasons the values are added with this function //this will avoid SQL Injections @@ -107,9 +96,9 @@ namespace Server_Dashboard { return resultTable; //Checks if there are any rows successful //If the query returns 0 the query wasn't successful - //if its any number above 0 it was successfull + //if its any number above 0 it was successful //Catch any error - } catch (SqlException ex) { + } catch (SqlException) { return null; } finally { //Always close the connection @@ -118,20 +107,20 @@ namespace Server_Dashboard { } /// - /// This function will fetch every Serverdata for each module + /// This function will fetch every server data for each module /// This will need some optimization, for now we just asynchronously - /// fetch the serverdata for each module + /// fetch the server data for each module /// /// ModuleID to fetch the data from /// - public static DataTable GetServerData(string mid) { + public static DataTable GetServerData(int mid) { //Creates the database connection using SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ServerDashboardDB"].ConnectionString); try { //Open the connection con.Open(); //SQL Query - string query = "SELECT * FROM ServerData WHERE ModuleID = @mid"; + const string query = "SELECT * FROM ServerData WHERE ModuleID = @mid"; //Creates a new command using SqlCommand com = new SqlCommand(query, con);//For security reasons the values are added with this function //this will avoid SQL Injections @@ -143,9 +132,9 @@ namespace Server_Dashboard { return resultTable; //Checks if there are any rows successful //If the query returns 0 the query wasn't successful - //if its any number above 0 it was successfull + //if its any number above 0 it was successful //Catch any error - } catch (SqlException ex) { + } catch (SqlException) { return null; } finally { //Always close the connection @@ -156,21 +145,21 @@ namespace Server_Dashboard { /// /// Creates a new Module for the current user /// - /// Server IP Address + /// Server IP Address /// Module name, default is Module /// Server name, default is Server /// Username of the current user /// module icon as byte[] - /// port, defalt ist 22 + /// port, default ist 22 /// - public static int CreateNewModule(string ipAdress, string moduleName, string serverName, string username, byte[] moduleIcon, string port = "22") { + public static int CreateNewModule(string ipAddress, string moduleName, string serverName, string username, byte[] moduleIcon, string port = "22") { //Creates the database connection using SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ServerDashboardDB"].ConnectionString); try { //Open the connection con.Open(); //SQL Query - string query = "EXEC AddNewModuleToUser @UserName = @username, @DateTime = @time, @ModuleName = @moduleName, @ServerName = @serverName, @ModuleIcon = @moduleIcon, @IPAddress = @ipAdress, @Port = @port"; + const string query = "EXEC AddNewModuleToUser @UserName = @username, @DateTime = @time, @ModuleName = @moduleName, @ServerName = @serverName, @ModuleIcon = @moduleIcon, @IPAddress = @ipAddress, @Port = @port"; //Creates a new command using SqlCommand com = new SqlCommand(query, con); //For security reasons the values are added with this function @@ -183,20 +172,14 @@ namespace Server_Dashboard { if (moduleIcon == null) com.Parameters["@moduleIcon"].Value = DBNull.Value; //com.Parameters.AddWithValue("@moduleIcon", moduleIcon); - com.Parameters.AddWithValue("@ipAdress", ipAdress); + com.Parameters.AddWithValue("@ipAddress", ipAddress); com.Parameters.AddWithValue("@port", port); //Execute query and return number of rows affected int sqlResponse = com.ExecuteNonQuery(); //Checks if there are any rows successful //If the query returns 0 the query wasn't successful - //if its any number above 0 it was successfull - if (sqlResponse == 0) { - //Error, not successful - return 1; - } else { - //Successful - return 0; - } + //if its any number above 0 it was successful + return sqlResponse == 0 ? 1 : 0; //Catch any error } catch (SqlException ex) { return ex.Number; @@ -207,7 +190,7 @@ namespace Server_Dashboard { } /// - /// Currently obscolete, would check the Username and Cookie + /// Currently obsolete, would check the Username and Cookie /// /// Locally stored user cookie /// Locally stored username @@ -219,7 +202,7 @@ namespace Server_Dashboard { //Open the connection con.Open(); //SQL Query - string query = "((SELECT Cookie FROM UserData WHERE Username = @username) = @cookie)"; + const string query = "((SELECT Cookie FROM UserData WHERE Username = @username) = @cookie)"; //Creates a new command using SqlCommand com = new SqlCommand(query, con); //For security reasons the values are added with this function @@ -231,13 +214,7 @@ namespace Server_Dashboard { //Checks if there are any rows successful //If the query returns 0 the query wasn't successful //if its any number above 0 it was successfull - if (sqlResponse == 0) { - //Error, not successful - return 1; - } else { - //Successful - return 0; - } + return sqlResponse == 0 ? 1 : 0; //Catch any error } catch (SqlException ex) { return ex.Number; @@ -258,7 +235,7 @@ namespace Server_Dashboard { //Open the connection con.Open(); //SQL Query - string query = "UPDATE UserData SET Cookie = null WHERE Username = @username"; + const string query = "UPDATE UserData SET Cookie = null WHERE Username = @username"; //Creates a new command using SqlCommand com = new SqlCommand(query, con); //For security reasons the values are added with this function @@ -268,14 +245,8 @@ namespace Server_Dashboard { int sqlResponse = com.ExecuteNonQuery(); //Checks if there are any rows successful //If the query returns 0 the query wasn't successful - //if its any number above 0 it was successfull - if (sqlResponse == 0) { - //Error, not successful - return 1; - } else { - //Successful - return 0; - } + //if its any number above 0 it was successful + return sqlResponse == 0 ? 1 : 0; //Catch any error } catch (SqlException ex) { return ex.Number; @@ -293,30 +264,31 @@ namespace Server_Dashboard { /// [0] is false, [1] is true, [2] connection error public static int AddCookie(string username, string cookie) { //Creates the database connection - using SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ServerDashboardDB"].ConnectionString); + using SqlConnection con = + new SqlConnection(ConfigurationManager.ConnectionStrings["ServerDashboardDB"].ConnectionString); try { //Open the connection con.Open(); + //SQL Query - string query = "UPDATE UserData SET Cookie = @cookie WHERE Username = @username"; + const string query = "UPDATE UserData SET Cookie = @cookie WHERE Username = @username"; + //Creates a new command using SqlCommand com = new SqlCommand(query, con); + //For security reasons the values are added with this function //this will avoid SQL Injections com.Parameters.Add("@cookie", SqlDbType.NVarChar, -1).Value = cookie; com.Parameters.AddWithValue("@username", username); + //Execute query and return number of rows affected int sqlResponse = com.ExecuteNonQuery(); + //Checks if there are any rows successful //If the query returns 0 the query wasn't successful - //if its any number above 0 it was successfull - if (sqlResponse == 0) { - //Error, not successful - return 1; - } else { - //Successful - return 0; - } + //if its any number above 0 it was successful + return sqlResponse == 0 ? 1 : 0; + //Catch any error } catch (SqlException ex) { return ex.Number; @@ -324,8 +296,8 @@ namespace Server_Dashboard { //Always close the connection con.Close(); } - - #endregion Public Methods } + + #endregion Public Methods } } \ No newline at end of file diff --git a/Server Dashboard/Interfaces/IHavePassword.cs b/Server Dashboard/Interfaces/IHavePassword.cs index 3ceecd7..bd7689c 100644 --- a/Server Dashboard/Interfaces/IHavePassword.cs +++ b/Server Dashboard/Interfaces/IHavePassword.cs @@ -4,10 +4,11 @@ using System.Security; using System.Text; namespace Server_Dashboard { + /// /// Interface that makes a SecurePassword go one way /// public interface IHavePassword { SecureString SecurePassword { get; } } -} +} \ No newline at end of file diff --git a/Server Dashboard/Interfaces/IWindowHelper.cs b/Server Dashboard/Interfaces/IWindowHelper.cs index defc651..194e829 100644 --- a/Server Dashboard/Interfaces/IWindowHelper.cs +++ b/Server Dashboard/Interfaces/IWindowHelper.cs @@ -3,10 +3,11 @@ using System.Collections.Generic; using System.Text; namespace Server_Dashboard { + /// /// Interface to help close a window with a button /// - interface IWindowHelper { + internal interface IWindowHelper { Action Close { get; set; } } -} +} \ No newline at end of file diff --git a/Server Dashboard/Security/SecureStringHelpers.cs b/Server Dashboard/Security/SecureStringHelpers.cs index a5f1bc2..688708b 100644 --- a/Server Dashboard/Security/SecureStringHelpers.cs +++ b/Server Dashboard/Security/SecureStringHelpers.cs @@ -5,10 +5,12 @@ using System.Security; using System.Text; namespace Server_Dashboard { + /// /// Secure string helper class to unsecure the Password b4 it goes to the database /// public static class SecureStringHelpers { + //Unsecures a given password public static string Unsecure(this SecureString secureString) { //If empty return nothing @@ -26,4 +28,4 @@ namespace Server_Dashboard { } } } -} +} \ No newline at end of file diff --git a/Server Dashboard/User/ModuleData/ModuleData.cs b/Server Dashboard/User/ModuleData/ModuleData.cs index 213ca75..e2d3c3d 100644 --- a/Server Dashboard/User/ModuleData/ModuleData.cs +++ b/Server Dashboard/User/ModuleData/ModuleData.cs @@ -29,7 +29,7 @@ namespace Server_Dashboard { public DateTime CreationDate { get; set; } //List that contains all the serverinformation over a period of time(lifespan of the module) - public List ServerInformation { get; set; } + public ServerInformation ServerInformation { get; set; } /// /// This will set the Module status indicator red or green if the server is available or not diff --git a/Server Dashboard/User/ModuleData/ServerData/ServerInformation.cs b/Server Dashboard/User/ModuleData/ServerData/ServerInformation.cs index fb2cdbe..77f08b5 100644 --- a/Server Dashboard/User/ModuleData/ServerData/ServerInformation.cs +++ b/Server Dashboard/User/ModuleData/ServerData/ServerInformation.cs @@ -11,13 +11,13 @@ namespace Server_Dashboard { /// internal class ServerInformation { public string ServerName { get; set; } - public string OSUserName { get; set; } + public string OsUserName { get; set; } public double CpuTemp { get; set; } public double GpuTemp { get; set; } - public DateTime Uptime { get; set; } + public TimeSpan Uptime { get; set; } public DateTime DeployDate { get; set; } - public string PublicIpAdress { get; set; } - public string PrivateIpAdress { get; set; } + public string PublicIpAddress { get; set; } + public string PrivateIpAddress { get; set; } public int GpuUsage { get; set; } public int CpuUsage { get; set; } public double NetworkUP { get; set; } diff --git a/Server Dashboard/ValueConverter/ValueToAngleConverter.cs b/Server Dashboard/ValueConverter/ValueToAngleConverter.cs index 13c39ef..05a7808 100644 --- a/Server Dashboard/ValueConverter/ValueToAngleConverter.cs +++ b/Server Dashboard/ValueConverter/ValueToAngleConverter.cs @@ -5,13 +5,15 @@ using System.Text; using System.Windows.Data; namespace Server_Dashboard { + /// /// Value to angle converter /// [ValueConversion(typeof(int), typeof(double))] public class ValueToAngleConverter : IValueConverter { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => (int)value * 0.01 * 360; public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => (int)((double)value / 360); } -} +} \ No newline at end of file diff --git a/Server Dashboard/ViewModels/BaseViewModel/BaseViewModel.cs b/Server Dashboard/ViewModels/BaseViewModel/BaseViewModel.cs index 266566f..5b582f1 100644 --- a/Server Dashboard/ViewModels/BaseViewModel/BaseViewModel.cs +++ b/Server Dashboard/ViewModels/BaseViewModel/BaseViewModel.cs @@ -1,18 +1,17 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; +using System.ComponentModel; namespace Server_Dashboard { + /// /// Base View Model all the other view models inherit from /// Makes me write the INotifyPropertyChanged only once /// public class BaseViewModel : INotifyPropertyChanged { + public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { }; protected void OnPropertyChanged(string prop) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop)); } } -} +} \ No newline at end of file diff --git a/Server Dashboard/ViewModels/Dashboard/DashboardModuleViewModel.cs b/Server Dashboard/ViewModels/Dashboard/DashboardModuleViewModel.cs index f14c8a0..8c83ac7 100644 --- a/Server Dashboard/ViewModels/Dashboard/DashboardModuleViewModel.cs +++ b/Server Dashboard/ViewModels/Dashboard/DashboardModuleViewModel.cs @@ -16,37 +16,49 @@ namespace Server_Dashboard { //List with all Modules inside public ObservableCollection Modules { get; set; } - //Creates Default Modules, remove before release and when implementing the actual data comming from the socket + //Creates Default Modules, remove before release and when implementing the actual data coming from the socket public DashboardModuleViewModel(DataTable moduleData) { Modules = new ObservableCollection(); foreach (DataRow row in moduleData.Rows) { - if (row[0] != null) { - byte[] iconBytes = row[3] == DBNull.Value ? null : (byte[])row[3]; - Modules.Add(new ModuleData(true) { - ModuleName = (string)row?[2], - Creator = (string)row?[0], - ModuleIcon = ConvertByteToBitmapImage(iconBytes), - CreationDate = (DateTime)row?[1], - ServerInformation = null - }); + if (row[0] == null) + return; + byte[] iconBytes = row[3] == DBNull.Value ? null : (byte[])row[3]; + DataTable serverData = DatabaseHandler.GetServerData((int)row[4]); + ServerInformation serverInformation = null; + if (serverData.Rows.Count != 0) { + DataRow serverRow = serverData.Rows[0]; + serverInformation = new ServerInformation { + ServerName = (string)serverRow[4] ?? "", + PublicIpAddress = (string)serverRow[6] ?? "", + PrivateIpAddress = (string)serverRow[5] ?? "", + Uptime = (TimeSpan)serverRow[7], + OsUserName = (string)serverRow[3] ?? "" + }; } + Modules.Add(new ModuleData(false) { + ModuleName = (string)row[2] ?? "", + Creator = (string)row[0] ?? "", + ModuleIcon = ConvertByteToBitmapImage(iconBytes), + CreationDate = (DateTime)row[1], + ServerInformation = serverInformation + }); } } - private BitmapImage ConvertByteToBitmapImage(byte[] icon) { - if (icon != null) { - try { - using MemoryStream ms = new MemoryStream(icon); - BitmapImage moduleIcon = new BitmapImage(); - moduleIcon.BeginInit(); - moduleIcon.StreamSource = ms; - moduleIcon.CreateOptions = BitmapCreateOptions.PreservePixelFormat; - moduleIcon.CacheOption = BitmapCacheOption.OnLoad; - moduleIcon.EndInit(); - moduleIcon.Freeze(); - return moduleIcon; - } catch { } - } + private static BitmapImage ConvertByteToBitmapImage(byte[] icon) { + if (icon == null) + return null; + try { + using MemoryStream ms = new MemoryStream(icon); + BitmapImage moduleIcon = new BitmapImage(); + moduleIcon.BeginInit(); + moduleIcon.StreamSource = ms; + moduleIcon.CreateOptions = BitmapCreateOptions.PreservePixelFormat; + moduleIcon.CacheOption = BitmapCacheOption.OnLoad; + moduleIcon.EndInit(); + moduleIcon.Freeze(); + return moduleIcon; + } catch { } return null; } } diff --git a/Server Dashboard/ViewModels/Dashboard/DashboardViewModel.cs b/Server Dashboard/ViewModels/Dashboard/DashboardViewModel.cs index 909f52f..4b7445e 100644 --- a/Server Dashboard/ViewModels/Dashboard/DashboardViewModel.cs +++ b/Server Dashboard/ViewModels/Dashboard/DashboardViewModel.cs @@ -1,13 +1,9 @@ using Server_Dashboard.Views.DashboardPages.ModuleCRUD; using System.Collections.ObjectModel; +using System.Data; using System.Diagnostics; using System.Windows; using System.Windows.Input; -using Server_Dashboard_Socket; -using System; -using System.Data; -using System.Collections.Generic; -using System.Linq; namespace Server_Dashboard { @@ -53,7 +49,7 @@ namespace Server_Dashboard { #region Constructor public DashboardViewModel(string username) { - //Command inits + //Command init OpenLinkCommand = new RelayCommand(OpenLink); OpenNewModuleWindowCommand = new RelayCommand(OpenNewModuleWindow); @@ -77,16 +73,14 @@ namespace Server_Dashboard { /// Opens a given link in the default browser /// /// The Link to be opened e.g. https://github.com/Crylia/Server-Dashboard - private void OpenLink(object param) { - Process.Start(new ProcessStartInfo((string)param) { UseShellExecute = true }); - } + private static void OpenLink(object param) => Process.Start(new ProcessStartInfo((string)param) { UseShellExecute = true }); /// /// Creates a new window to create a new Module /// /// Nothing private void OpenNewModuleWindow(object param) { - //Creates a new CreateModulePopup and sets this view model as datacontext + //Creates a new CreateModulePopup and sets this view model as data context CreateModulePopup cmp = new CreateModulePopup { DataContext = new CreateModuleViewModel(User.UserName) }; @@ -98,9 +92,8 @@ namespace Server_Dashboard { } private void GetModules() { - DataTable moduleData = DatabaseHandler.GetUserModuleData(User.UID); - dmvm = new DashboardModuleViewModel(moduleData); - //Sets the local module to the dashboardviewmodule modules + dmvm = new DashboardModuleViewModel(DatabaseHandler.GetUserModuleData(User.UID)); + //Sets the local module to the dashboard view module modules Modules = dmvm.Modules; } diff --git a/Server Dashboard/ViewModels/Dashboard/ModuleCRUD/CreateModuleViewModel.cs b/Server Dashboard/ViewModels/Dashboard/ModuleCRUD/CreateModuleViewModel.cs index a43ee15..0f3f95f 100644 --- a/Server Dashboard/ViewModels/Dashboard/ModuleCRUD/CreateModuleViewModel.cs +++ b/Server Dashboard/ViewModels/Dashboard/ModuleCRUD/CreateModuleViewModel.cs @@ -17,7 +17,7 @@ namespace Server_Dashboard { private string serverName; public string ServerName { - get { return serverName; } + get => serverName; set { if (serverName != value) serverName = value; @@ -28,7 +28,7 @@ namespace Server_Dashboard { private string moduleName; public string ModuleName { - get { return moduleName; } + get => moduleName; set { if (moduleName != value) moduleName = value; @@ -36,21 +36,21 @@ namespace Server_Dashboard { } } - private string ipAdress; + private string ipAddress; - public string IPAdress { - get { return ipAdress; } + public string IpAddress { + get => ipAddress; set { - if (ipAdress != value) - ipAdress = value; - OnPropertyChanged(nameof(ipAdress)); + if (ipAddress != value) + ipAddress = value; + OnPropertyChanged(nameof(ipAddress)); } } private string port; public string Port { - get { return port; } + get => port; set { if (port != value) port = value; @@ -61,7 +61,7 @@ namespace Server_Dashboard { private BitmapImage moduleIcon; public BitmapImage ModuleIcon { - get { return moduleIcon; } + get => moduleIcon; set { if (moduleIcon != value) moduleIcon = value; @@ -72,7 +72,7 @@ namespace Server_Dashboard { private string userInformationMessage; public string UserInformationMessage { - get { return userInformationMessage; } + get => userInformationMessage; set { if (userInformationMessage != value) userInformationMessage = value; @@ -108,39 +108,39 @@ namespace Server_Dashboard { /// Nothing private async void CreateModuleAsync(object param) { //Checks if the IP field is not empty and valid - if (!String.IsNullOrWhiteSpace(ipAdress) && ipFilter.IsMatch(ipAdress)) { - //Gives the Module a default name if the user doesnt name it - if (String.IsNullOrWhiteSpace(moduleName)) + if (!string.IsNullOrWhiteSpace(ipAddress) && ipFilter.IsMatch(ipAddress)) { + //Gives the Module a default name if the user doesn't name it + if (string.IsNullOrWhiteSpace(moduleName)) moduleName = "Module"; - //Gives the Server a default name is the user doesnt name it - if (String.IsNullOrWhiteSpace(serverName)) + //Gives the Server a default name is the user doesn't name it + if (string.IsNullOrWhiteSpace(serverName)) serverName = "Server"; - //Makes sure the name isnt any longer than characters + //Makes sure the name isn't any longer than characters if (moduleName.Length >= 20) { UserInformationMessage = "The Module Name is too long"; return; } - //Makes sure the name isnt any longer than characters + //Makes sure the name isn't any longer than characters if (serverName.Length >= 20) { UserInformationMessage = "The Server Name is too long"; return; } - //Clears the error message if there isnt any error + //Clears the error message if there isn't any error UserInformationMessage = ""; byte[] moduleIconStream = null; if (moduleIcon != null) { try { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(moduleIcon)); - using MemoryStream ms = new MemoryStream(); + await using MemoryStream ms = new MemoryStream(); encoder.Save(ms); moduleIconStream = ms.ToArray(); - } catch { } + } catch (Exception) { } } - if (await Task.Run(() => DatabaseHandler.CreateNewModule(ipAdress, moduleName, serverName, username, moduleIconStream, port)) == 0) { + if (await Task.Run(() => DatabaseHandler.CreateNewModule(ipAddress, moduleName, serverName, username, moduleIconStream, port)) == 0) { Close?.Invoke(); } else { - UserInformationMessage = "Unknown error occured, please try again later"; + UserInformationMessage = "Unknown error occurred, please try again later"; } } else { UserInformationMessage = "The IP Address is invalid"; @@ -156,7 +156,7 @@ namespace Server_Dashboard { Title = "Choose an Image", Filter = "Supported format|*.jpg;*.jpeg;*.png" }; - if ((bool)ofd.ShowDialog()) { + if (Convert.ToBoolean(ofd.ShowDialog())) { ModuleIcon = new BitmapImage(new Uri(ofd.FileName)); } } diff --git a/Server Dashboard/ViewModels/Login/LoginViewModel.cs b/Server Dashboard/ViewModels/Login/LoginViewModel.cs index c20bb79..eb39aa9 100644 --- a/Server Dashboard/ViewModels/Login/LoginViewModel.cs +++ b/Server Dashboard/ViewModels/Login/LoginViewModel.cs @@ -81,11 +81,11 @@ namespace Server_Dashboard { LoginCommand = new RelayCommand(LoginAsync); //Checks if the Username and Cookie is saved in the Settings.settings if (!String.IsNullOrEmpty(Settings.Default.Username) && !String.IsNullOrEmpty(Settings.Default.Cookies)) { - //Takes the saved Username and Remember me button status and prefills the username and checks the Remember me button + //Takes the saved Username and Remember me button status and pre fills the username and checks the Remember me button Username = Settings.Default.Username; RememberUser = Settings.Default.RememberMe; } - //TODO: Autologin + //TODO: Auto login //AutoLoginAsync(); } @@ -108,7 +108,7 @@ namespace Server_Dashboard { if (!String.IsNullOrWhiteSpace(Username) && !String.IsNullOrWhiteSpace((parameter as IHavePassword).SecurePassword.Unsecure())) { //Sets loading to true to show the loading icon Loading = "Visible"; - //Sends the Username and Password to the database and saved the result, 1 successfull, 0 wrong username or password + //Sends the Username and Password to the database and saved the result, 1 successful, 0 wrong username or password int result = await Task.Run(() => DatabaseHandler.CheckLogin(Username, (parameter as IHavePassword).SecurePassword.Unsecure())); //hides the loading again Loading = "Hidden"; @@ -142,7 +142,7 @@ namespace Server_Dashboard { //If the remember user option is checked and the cookie is not set save everything locally if (RememberUser && Settings.Default.Username != Username) { //Creates a new GUID with the username at the end, this is the cookie - var cookie = $"{Guid.NewGuid().ToString()}+user:{Username}"; + var cookie = $"{Guid.NewGuid()}+user:{Username}"; //Saves cookie, Username Remember me option to the local storage (Settings.settings) Settings.Default.Cookies = cookie; Settings.Default.Username = Username; @@ -197,7 +197,7 @@ namespace Server_Dashboard { #region private functions - //TODO: Add autologin function that locks the UI untill the user hits the abort button or the login completes + //TODO: Add auto login function that locks the UI until the user hits the abort button or the login completes /*private async void AutoLoginAsync() { if (Settings.Default.RememberMe && !String.IsNullOrEmpty(Settings.Default.Username) && !String.IsNullOrEmpty(Settings.Default.Cookies)) { Loading = "Visible"; diff --git a/Server Dashboard/Views/Dashboard/CRUD Popup/CreateModulePopup.xaml b/Server Dashboard/Views/Dashboard/CRUD Popup/CreateModulePopup.xaml index 2bee832..c306732 100644 --- a/Server Dashboard/Views/Dashboard/CRUD Popup/CreateModulePopup.xaml +++ b/Server Dashboard/Views/Dashboard/CRUD Popup/CreateModulePopup.xaml @@ -9,35 +9,35 @@ d:DataContext="{d:DesignInstance Type=root:DashboardModuleViewModel}" mc:Ignorable="d" ResizeMode="NoResize" Height="700" Width="500" d:WindowStyle="None" ap:CloseProperty.Value="True"> - + - + - - + + - - + + - + - @@ -45,34 +45,34 @@ - + - - - - - - - + + + + + + + - + - + - - + + - + @@ -82,18 +82,18 @@ - + - + - - + + - + @@ -101,21 +101,21 @@ - + - + - + - + - - + + - + @@ -124,17 +124,17 @@ - + - + - + - + @@ -142,8 +142,8 @@ - - + + - - + @@ -198,7 +196,7 @@ - + diff --git a/Server Dashboard/Views/Pages/MainDashboardPage.xaml b/Server Dashboard/Views/Pages/MainDashboardPage.xaml index 2533058..0e1adc8 100644 --- a/Server Dashboard/Views/Pages/MainDashboardPage.xaml +++ b/Server Dashboard/Views/Pages/MainDashboardPage.xaml @@ -1,48 +1,71 @@  - + - + - - + + - - - - + + + - public partial class DashboardWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector { - - #line 44 "..\..\..\..\Views\DashboardWindow.xaml" - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] - internal System.Windows.Controls.Grid TopBarGrid; - - #line default - #line hidden - private bool _contentLoaded; /// @@ -85,12 +75,6 @@ namespace Server_Dashboard.Views { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { - switch (connectionId) - { - case 1: - this.TopBarGrid = ((System.Windows.Controls.Grid)(target)); - return; - } this._contentLoaded = true; } } diff --git a/Server Dashboard/obj/Debug/netcoreapp3.1/Views/DashboardWindow.g.i.cs b/Server Dashboard/obj/Debug/netcoreapp3.1/Views/DashboardWindow.g.i.cs index f48e0bd..164b1ce 100644 --- a/Server Dashboard/obj/Debug/netcoreapp3.1/Views/DashboardWindow.g.i.cs +++ b/Server Dashboard/obj/Debug/netcoreapp3.1/Views/DashboardWindow.g.i.cs @@ -1,4 +1,4 @@ -#pragma checksum "..\..\..\..\Views\DashboardWindow.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "3593041613773C511381544197463CBAC4FA5B88" +#pragma checksum "..\..\..\..\Views\DashboardWindow.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7D684497049C84ED9B984ABA13FB98FAA7EC8050" //------------------------------------------------------------------------------ // // This code was generated by a tool. @@ -14,8 +14,6 @@ using Microsoft.Xaml.Behaviors.Core; using Microsoft.Xaml.Behaviors.Input; using Microsoft.Xaml.Behaviors.Layout; using Microsoft.Xaml.Behaviors.Media; -using Server_Dashboard; -using Server_Dashboard.Views; using Server_Dashboard.Views.DashboardPages; using SharpVectors.Converters; using System; @@ -49,14 +47,6 @@ namespace Server_Dashboard.Views { /// public partial class DashboardWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector { - - #line 44 "..\..\..\..\Views\DashboardWindow.xaml" - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] - internal System.Windows.Controls.Grid TopBarGrid; - - #line default - #line hidden - private bool _contentLoaded; /// @@ -85,12 +75,6 @@ namespace Server_Dashboard.Views { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { - switch (connectionId) - { - case 1: - this.TopBarGrid = ((System.Windows.Controls.Grid)(target)); - return; - } this._contentLoaded = true; } } diff --git a/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.baml b/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.baml index 8d351ca..488b566 100644 Binary files a/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.baml and b/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.baml differ diff --git a/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.g.cs b/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.g.cs index 2158cc0..c84c853 100644 --- a/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.g.cs +++ b/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.g.cs @@ -1,4 +1,4 @@ -#pragma checksum "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "47F667437FD33C591010E2D8FB596082CE45DAC4" +#pragma checksum "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "17174C7675263D17294DBE843DB6C895C1BCC3FF" //------------------------------------------------------------------------------ // // This code was generated by a tool. @@ -9,15 +9,7 @@ // //------------------------------------------------------------------------------ -using Microsoft.Xaml.Behaviors; -using Microsoft.Xaml.Behaviors.Core; -using Microsoft.Xaml.Behaviors.Input; -using Microsoft.Xaml.Behaviors.Layout; -using Microsoft.Xaml.Behaviors.Media; -using Server_Dashboard; using Server_Dashboard.Controls.ServerModules; -using Server_Dashboard.Views.DashboardPages; -using Server_Dashboard.Views.DashboardPages.ModuleCRUD; using System; using System.Diagnostics; using System.Windows; @@ -49,30 +41,6 @@ namespace Server_Dashboard.Views.DashboardPages { /// public partial class MainDashboardPage : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { - - #line 30 "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] - internal System.Windows.Controls.Button CreateModule; - - #line default - #line hidden - - - #line 31 "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] - internal System.Windows.Controls.Button RemoveModule; - - #line default - #line hidden - - - #line 32 "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] - internal System.Windows.Controls.Button ChangeModule; - - #line default - #line hidden - private bool _contentLoaded; /// @@ -101,18 +69,6 @@ namespace Server_Dashboard.Views.DashboardPages { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { - switch (connectionId) - { - case 1: - this.CreateModule = ((System.Windows.Controls.Button)(target)); - return; - case 2: - this.RemoveModule = ((System.Windows.Controls.Button)(target)); - return; - case 3: - this.ChangeModule = ((System.Windows.Controls.Button)(target)); - return; - } this._contentLoaded = true; } } diff --git a/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.g.i.cs b/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.g.i.cs index 2158cc0..c84c853 100644 --- a/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.g.i.cs +++ b/Server Dashboard/obj/Debug/netcoreapp3.1/Views/Pages/MainDashboardPage.g.i.cs @@ -1,4 +1,4 @@ -#pragma checksum "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "47F667437FD33C591010E2D8FB596082CE45DAC4" +#pragma checksum "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "17174C7675263D17294DBE843DB6C895C1BCC3FF" //------------------------------------------------------------------------------ // // This code was generated by a tool. @@ -9,15 +9,7 @@ // //------------------------------------------------------------------------------ -using Microsoft.Xaml.Behaviors; -using Microsoft.Xaml.Behaviors.Core; -using Microsoft.Xaml.Behaviors.Input; -using Microsoft.Xaml.Behaviors.Layout; -using Microsoft.Xaml.Behaviors.Media; -using Server_Dashboard; using Server_Dashboard.Controls.ServerModules; -using Server_Dashboard.Views.DashboardPages; -using Server_Dashboard.Views.DashboardPages.ModuleCRUD; using System; using System.Diagnostics; using System.Windows; @@ -49,30 +41,6 @@ namespace Server_Dashboard.Views.DashboardPages { /// public partial class MainDashboardPage : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { - - #line 30 "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] - internal System.Windows.Controls.Button CreateModule; - - #line default - #line hidden - - - #line 31 "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] - internal System.Windows.Controls.Button RemoveModule; - - #line default - #line hidden - - - #line 32 "..\..\..\..\..\Views\Pages\MainDashboardPage.xaml" - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] - internal System.Windows.Controls.Button ChangeModule; - - #line default - #line hidden - private bool _contentLoaded; /// @@ -101,18 +69,6 @@ namespace Server_Dashboard.Views.DashboardPages { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { - switch (connectionId) - { - case 1: - this.CreateModule = ((System.Windows.Controls.Button)(target)); - return; - case 2: - this.RemoveModule = ((System.Windows.Controls.Button)(target)); - return; - case 3: - this.ChangeModule = ((System.Windows.Controls.Button)(target)); - return; - } this._contentLoaded = true; } }