Skip to content
This repository has been archived by the owner on Jan 25, 2024. It is now read-only.

Commit

Permalink
Finally working server connection
Browse files Browse the repository at this point in the history
Using WatsonTcp instead of SimpleTcpClient
  • Loading branch information
valnoxy committed Oct 7, 2022
1 parent d4791d6 commit 73bd55c
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 50 deletions.
14 changes: 12 additions & 2 deletions Service/Plugins/ZeroKey.Plugin.Lock/LockWorkstation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,19 @@ public void NcfRingDown(string id, Dictionary<string, object> parameters, System
try
{
// Check if User is currently running medatixx Client
Process[] pname = Process.GetProcessesByName("Client.UI");
if (pname.Length != 0)
{
Debug.WriteLine("Running medatixx Plugin (ignore lock) ...");
string appDir = AppContext.BaseDirectory;
ProcessAsUser.Launch($"{appDir}\\medatixx\\ZeroKey.Plugin.medatixx.exe -c {id} -s");
}
else
{
ProcessAsUser.Launch(@"C:\WINDOWS\system32\rundll32.exe user32.dll,LockWorkStation");
Process.Start(@"C:\WINDOWS\system32\rundll32.exe", "user32.dll,LockWorkStation");
}

string appDir = AppContext.BaseDirectory;
ProcessAsUser.Launch($"{appDir}\\medatixx\\ZeroKey.Plugin.medatixx.exe -c {id} -s");
// System.Threading.Thread.Sleep(8000);
// ProcessAsUser.Launch(@"C:\WINDOWS\system32\rundll32.exe user32.dll,LockWorkStation");
}
Expand Down
73 changes: 44 additions & 29 deletions Service/ZeroKey.ServerUI/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
using System.Diagnostics;
using System.IO;
using Newtonsoft.Json;
using SuperSimpleTcp;
using WatsonTcp;
using Wpf.Ui.Common;
using Clipboard = System.Windows.Clipboard;

Expand All @@ -19,21 +19,18 @@ namespace ZeroKey.ServerUI
public partial class MainWindow : Window
{
private static bool _dark = true;
private SimpleTcpServer server;
private WatsonTcpServer server;

public static List<string> AvailableUsers = new List<string>();
private string ip = GetLocalIpAddress();
private int port = 9000;

public MainWindow()
{
InitializeComponent();

// Set server info
string ip = GetLocalIpAddress();
int port = 9000;

if (ip != "No IPv4 address in the System!")
{
server = new SimpleTcpServer($"{ip}:{port}");
server = new WatsonTcpServer(ip,port);
Console.WriteLine($"Listening on {ip}:{port}");
}
else
Expand All @@ -45,7 +42,7 @@ public MainWindow()
// Set events
server.Events.ClientConnected += ClientConnected;
server.Events.ClientDisconnected += ClientDisconnected;
server.Events.DataReceived += DataReceived;
server.Events.MessageReceived += MessageReceived;

Wpf.Ui.Appearance.Theme.Apply(
Wpf.Ui.Appearance.ThemeType.Dark, // Theme type
Expand All @@ -59,37 +56,29 @@ public MainWindow()

#region Server Events

void ClientConnected(object sender, SuperSimpleTcp.ConnectionEventArgs e)
void ClientConnected(object sender, WatsonTcp.ConnectionEventArgs e)
{
Dispatcher.BeginInvoke(new Action(delegate
{
RootSnackbar.Appearance = ControlAppearance.Info;
RootSnackbar.Icon = SymbolRegular.Person24;
RootSnackbar.Show("Connected", $"New Connection with \"{e.IpPort}\".");
}));
AvailableUsers.Add(e.IpPort);
}

void ClientDisconnected(object sender, SuperSimpleTcp.ConnectionEventArgs e)
void ClientDisconnected(object sender, WatsonTcp.DisconnectionEventArgs e)
{
Dispatcher.BeginInvoke(new Action(delegate
{
RootSnackbar.Appearance = ControlAppearance.Info;
RootSnackbar.Icon = SymbolRegular.ArrowExit20;
RootSnackbar.Show("Connected", $"Client \"{e.IpPort}\" disconnected: {e.Reason}");
}));

try
{
int index = AvailableUsers.IndexOf(e.IpPort);
AvailableUsers.RemoveAt(index);
}
catch {; }
}

void DataReceived(object sender, SuperSimpleTcp.DataReceivedEventArgs e)
void MessageReceived(object sender, WatsonTcp.MessageReceivedEventArgs e)
{
string message = Encoding.UTF8.GetString(e.Data.Array, 0, e.Data.Count);
string message = Encoding.UTF8.GetString(e.Data);

switch (message)
{
Expand All @@ -98,13 +87,35 @@ void DataReceived(object sender, SuperSimpleTcp.DataReceivedEventArgs e)
Debug.WriteLine("[{0}] Got request command from client... sending config...", DateTime.Now);

// Send configuration to user
if (!File.Exists("Application.config"))
server.Send(e.IpPort, "null");
else
try
{
if (!File.Exists("Application.config"))
server.Send(e.IpPort, "null");
else
{
server.Send(e.IpPort, File.ReadAllText("Application.config"));
//if (File.Exists("medatixx.json")) im.SendMessage(e.From, File.ReadAllText("medatixx.json"));
}
}
catch (TimeoutException)
{
server.Send(e.IpPort, File.ReadAllText("Application.config"));
//if (File.Exists("medatixx.json")) im.SendMessage(e.From, File.ReadAllText("medatixx.json"));
Dispatcher.BeginInvoke(new Action(delegate
{
RootSnackbar.Appearance = ControlAppearance.Danger;
RootSnackbar.Icon = SymbolRegular.Warning24;
RootSnackbar.Show("Timeout", $"Failed to send config to client \"{e.IpPort}\".");
}));
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(new Action(delegate
{
RootSnackbar.Appearance = ControlAppearance.Danger;
RootSnackbar.Icon = SymbolRegular.Warning24;
RootSnackbar.Show("Error", $"Failed to send config to client \"{e.IpPort}\". {ex.Message}");
}));
}

break;
}

Expand All @@ -128,6 +139,8 @@ void DataReceived(object sender, SuperSimpleTcp.DataReceivedEventArgs e)
if (charObj == "2")
IsConfig = 2;

IEnumerable<string> clients = server.ListClients();

switch (IsConfig)
{
default:
Expand All @@ -140,9 +153,9 @@ void DataReceived(object sender, SuperSimpleTcp.DataReceivedEventArgs e)
Debug.WriteLine("[{0}] Got configuration from client... writing config...", DateTime.Now);
File.WriteAllText("Application.config", message);
Debug.WriteLine("[{0}] New configuration saved. Contacting all clients now ...", DateTime.Now);
foreach (string user in AvailableUsers)
foreach (string user in clients)
{
server.Send(user, parseConfig);
server.Send(user, message);
Debug.WriteLine("[{0}] Send config to {1}", DateTime.Now, user);
}

Expand All @@ -155,7 +168,7 @@ void DataReceived(object sender, SuperSimpleTcp.DataReceivedEventArgs e)
Debug.WriteLine("[{0}] Got medatixx configuration from client... writing config...", DateTime.Now);
File.WriteAllText("medatixx.json", message);
Debug.WriteLine("[{0}] New configuration saved. Contacting all clients now ...", DateTime.Now);
foreach (string user in AvailableUsers)
foreach (string user in clients)
{
server.Send(user, message);
Debug.WriteLine("[{0}] Send config to {1}", DateTime.Now, user);
Expand Down Expand Up @@ -227,6 +240,8 @@ private void ToggleSwitchOn_Click(object sender, RoutedEventArgs e)
}
catch (Exception ex) { MessageBox.Show("Cannot start server: " + $"\n{ex.Message}"); }

TbIp.Text = $"{ip}:{port}";

ResetPwBtn.IsEnabled = false;
ClearUserBtn.IsEnabled = false;
ClearBtn.IsEnabled = false;
Expand Down
4 changes: 2 additions & 2 deletions Service/ZeroKey.ServerUI/ZeroKey.ServerUI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="SuperSimpleTcp" Version="3.0.0" />
<PackageReference Include="System.ServiceProcess.ServiceController" Version="6.0.0" />
<PackageReference Include="WPF-UI" Version="2.0.2" />
<PackageReference Include="WatsonTcp" Version="4.8.14.14" />
<PackageReference Include="WPF-UI" Version="2.0.3" />
</ItemGroup>

<ItemGroup>
Expand Down
27 changes: 15 additions & 12 deletions Service/ZeroKeyServiceCore/ServiceCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
using System.Threading;
using ZeroKey.Service.Common;
using System.IO;
using System.Linq.Expressions;
using System.Net.Sockets;
using System.Net;
using Newtonsoft.Json;
using System.Management;
using SuperSimpleTcp;
using WatsonTcp;
using ZeroKey.Libraries;

namespace ZeroKey.Service.Core
Expand All @@ -32,7 +33,7 @@ public class ServiceCore
private TcpListener _registrationListener;
private Thread _registrationListenThread;

SimpleTcpClient client;
WatsonTcpClient client;
private int trys = 0;
private bool IsConnected = false;
private bool GotConfig = false;
Expand Down Expand Up @@ -289,6 +290,7 @@ public void Start()
_readerThread.Start();
_state = ServiceState.Running;
Log("Core started");
Debug.WriteLine("Service is now ready.");
}

private void InitialiseNetwork()
Expand Down Expand Up @@ -618,22 +620,23 @@ private void UpdateFriendlyName(NetworkMessage networkMessage)
SaveConfig();
}

private void LoginOK(object sender, SuperSimpleTcp.ConnectionEventArgs e)
private void ServerConnected(object sender, WatsonTcp.ConnectionEventArgs e)
{
Debug.WriteLine("Login successful.");
IsConnected = true;
}

private void Disconnected(object sender, SuperSimpleTcp.ConnectionEventArgs e)
private void ServerDisconnected(object sender, WatsonTcp.DisconnectionEventArgs e)
{
Debug.WriteLine("Disconnected.");
IsConnected = false;
}

private void DataReceived(object sender, SuperSimpleTcp.DataReceivedEventArgs e)
private void MessageReceived(object sender, WatsonTcp.MessageReceivedEventArgs e)
{
if (e.Data.Array == null) return;
string message = Encoding.UTF8.GetString(e.Data.Array, 0, e.Data.Count);
if (e.Data == null) return;

string message = Encoding.UTF8.GetString(e.Data);

Debug.WriteLine("Got response from server... sync file now...");

Expand Down Expand Up @@ -692,10 +695,10 @@ private bool LoadConfig()

if (!String.IsNullOrEmpty(ip))
{
client = new SimpleTcpClient($"{ip}:{port}");
client.Events.Connected += LoginOK;
client.Events.Disconnected += Disconnected;
client.Events.DataReceived += DataReceived;
client = new WatsonTcpClient(ip, port);
client.Events.ServerConnected += ServerConnected;
client.Events.ServerDisconnected += ServerDisconnected;
client.Events.MessageReceived += MessageReceived;
client.Connect();
Debug.WriteLine("Login requested!");

Expand Down Expand Up @@ -784,7 +787,7 @@ private bool RequestLogin()

if (!String.IsNullOrEmpty(ip))
{
client = new SimpleTcpClient($"{ip}:{port}");
client = new WatsonTcpClient(ip, port);
client.Connect();
Debug.WriteLine("Login requested!");

Expand Down
4 changes: 2 additions & 2 deletions Service/ZeroKeyServiceCore/ZeroKey.Service.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@
<PackageReference Include="Newtonsoft.Json">
<Version>13.0.1</Version>
</PackageReference>
<PackageReference Include="SuperSimpleTcp">
<Version>3.0.0</Version>
<PackageReference Include="WatsonTcp">
<Version>4.8.14.14</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
Expand Down
2 changes: 2 additions & 0 deletions Setup/Scripts/Script.iss
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ Source: "..\..\bin\Release\Service\ZeroKeyServiceHost.exe.config"; DestDir: {#Se
Source: "..\..\bin\Release\Service\Newtonsoft.Json.dll"; DestDir: {#ServiceAppPath}; Flags: ignoreversion
Source: "..\..\bin\Release\Service\ZeroKeyServiceCommon.dll"; DestDir: {#ServiceAppPath}; Flags: ignoreversion
Source: "..\..\bin\Release\Service\ZeroKeyServiceCore.dll"; DestDir: {#ServiceAppPath}; Flags: ignoreversion
Source: "..\..\bin\Release\Service\WatsonTcp.dll"; DestDir: {#ServiceAppPath}; Flags: ignoreversion
Source: "..\..\bin\Release\Service\Rijndael256.dll"; DestDir: {#ServiceAppPath}; Flags: ignoreversion
Source: "..\..\bin\Release\Service\ZeroKeyServiceHost.exe"; DestDir: {#ServiceAppPath}; Flags: ignoreversion; \
BeforeInstall: TaskKill('ZeroKeyServiceHost.exe')

Expand Down
3 changes: 1 addition & 2 deletions Setup/Scripts/Server.iss
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ ArchitecturesInstallIn64BitMode=x64

OutputDir=..\Result
OutputBaseFilename={#MyAppName}_{#GitCommitHash}_{#MyAppVersion}

CloseApplications=force
Compression=lzma
SolidCompression=yes
Expand All @@ -46,7 +45,7 @@ Source: "..\..\bin\Release\ServerUI\ZeroKey.ServerUI.exe"; DestDir: {app}; Flags
; Application files
Source: "..\..\bin\Release\ServerUI\Newtonsoft.Json.dll"; DestDir: {app}; Flags: ignoreversion
Source: "server.pfx"; DestDir: {app}; Flags: ignoreversion
Source: "..\..\bin\Release\ServerUI\SuperSimpleTcp.dll"; DestDir: {app}; Flags: ignoreversion
Source: "..\..\bin\Release\ServerUI\WatsonTcp.dll"; DestDir: {app}; Flags: ignoreversion
Source: "..\..\bin\Release\ServerUI\System.ServiceProcess.ServiceController.dll"; DestDir: {app}; Flags: ignoreversion
Source: "..\..\bin\Release\ServerUI\Wpf.Ui.dll"; DestDir: {app}; Flags: ignoreversion
Source: "..\..\bin\Release\ServerUI\ZeroKey.ServerUI.deps.json"; DestDir: {app}; Flags: ignoreversion
Expand Down
2 changes: 1 addition & 1 deletion UI/ZeroKey.UI.View/Resources/StringResources.de-DE.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<system:String x:Key="about_localauth">Lokale Autorisierung</system:String>
<system:String x:Key="about_remoteauth">Serverseitige Autorisierung</system:String>

<!-- FinishedStepView -->
<!-- FinishedStepView -->
<system:String x:Key="fsv_header">Fertig!</system:String>
<system:String x:Key="fsv_h2">Du kannst nun deine Karte zum Sperren und Entsperren deines PC's verwenden. Lege einfach deine Karte auf das Lesegerät.</system:String>
<system:String x:Key="fsv_h3">Auf der nächsten Seite können Sie auch weitere Karten für andere Benutzer hinzufügen oder den Zugang sperren.</system:String>
Expand Down

0 comments on commit 73bd55c

Please sign in to comment.