Skip to content

Commit

Permalink
Move to net7; fix socket; add reboot command (#40)
Browse files Browse the repository at this point in the history
move to .Net7
add reboot program closes #38
fix socket closes #39
  • Loading branch information
mrerro authored Dec 11, 2022
1 parent a65014c commit eac899b
Show file tree
Hide file tree
Showing 9 changed files with 151 additions and 68 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/deploy-printer-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:

- uses: actions/setup-dotnet@v1
with:
dotnet-version: 6.0.x
dotnet-version: 7.0.x

- run: dotnet restore ${{ env.PROJECT_PATH }}

Expand All @@ -28,7 +28,7 @@ jobs:
uses: thedoctor0/zip-release@main
with:
type: 'zip'
directory: 'PrinterApp/bin/Release/net6.0-windows/win-x86/publish/'
directory: 'PrinterApp/bin/Release/net7.0-windows/win-x86/publish/'
filename: 'PrinterApp_x86.zip'
exclusions: '*.pdb'

Expand All @@ -43,5 +43,5 @@ jobs:
- uses: csexton/release-asset-action@v2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
file: 'PrinterApp/bin/Release/net6.0-windows/win-x86/publish/PrinterApp_x86.zip'
file: 'PrinterApp/bin/Release/net7.0-windows/win-x86/publish/PrinterApp_x86.zip'
release-url: ${{ steps.create_release.outputs.upload_url }}
4 changes: 3 additions & 1 deletion PrinterApp/App.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PrinterApp"
Startup="App_OnStartup" Exit="App_OnExit">
Startup="App_OnStartup"
ShutdownMode="OnExplicitShutdown"
Exit="App_OnExit">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
Expand Down
104 changes: 92 additions & 12 deletions PrinterApp/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,100 @@ namespace PrinterApp
/// </summary>
public partial class App : Application
{
private readonly AutoUpdater _autoUpdater = new();
private readonly ConfigFile _configFile = new();
private PrinterModel _printerModel;
private MainWindow _mainWindow;

private readonly string _assemblyVersion =
Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? string.Empty;

private App()
{
var fileName = GetType().Namespace!;
ConfigureLogger(fileName);
_configFile.LoadConfig(fileName);
if (!Directory.Exists(_configFile.TempSavePath))
Directory.CreateDirectory(_configFile.TempSavePath);

var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
var str = Environment.ProcessPath ?? string.Empty;
key?.SetValue(GetType().Namespace, _configFile.StartWithWindows ? str : string.Empty);

if (_configFile.AutoUpdate) _autoUpdater.StartTimer();

_printerModel = new PrinterModel(_configFile, _autoUpdater);
_printerModel.Reboot += RebootHandler;
_mainWindow = new MainWindow(_printerModel);
_mainWindow.Title = $"{_mainWindow.Title} {_assemblyVersion}";
_mainWindow.Closing += MainWindowClosing;
_mainWindow.Closed += MainWindowClosed;

Marketing.LoadProgram();
}

private void RebootHandler()
{
_printerModel.PrinterViewModel.DownloadNotInProgress = false;
_printerModel.PrinterViewModel.CodeTextBoxText = "REBOOT";
_mainWindow.Close();
}

private void MainWindowClosed(object? sender, EventArgs e)
{
if (_printerModel.PrinterViewModel.CodeTextBoxText != "REBOOT") return;
_printerModel = new PrinterModel(_configFile, _autoUpdater);
_printerModel.Reboot += RebootHandler;
_mainWindow = new MainWindow(_printerModel);
_mainWindow.Title = $"{_mainWindow.Title} {_assemblyVersion}";
_mainWindow.Closing += MainWindowClosing;
_mainWindow.Closed += MainWindowClosed;
_mainWindow.Show();
}

private void MainWindowClosing(object? sender, System.ComponentModel.CancelEventArgs e)
{
switch (_printerModel.PrinterViewModel.CodeTextBoxText)
{
case "UPDATE":
_printerModel.PrinterViewModel.CodeTextBoxText = "";
_autoUpdater.ManualUpdate();
e.Cancel = true;
return;
case "REBOOT":
_printerModel.SocketsClose();
Marketing.ManualReboot();
return;
}

if (_printerModel.WrongExitCode())
{
Marketing.CloseWithoutAccessProgram();
Log.Information(
$"{GetType().Name} {MethodBase.GetCurrentMethod()?.Name}: Attempt to close without access");
e.Cancel = true;
return;
}

_printerModel.SocketsClose();
_autoUpdater.StopTimer();
Current.Shutdown();
}

private void App_OnStartup(object sender, StartupEventArgs e)
{
var fileName = GetType().Namespace;
_mainWindow.Show();
}

private void App_OnExit(object sender, ExitEventArgs e)
{
Log.Debug("App_OnExit");
Log.CloseAndFlush();
}

private static void ConfigureLogger(string fileName)
{
#if DEBUG
var log = new LoggerConfiguration()
.MinimumLevel.Debug()
Expand All @@ -32,17 +123,6 @@ private void App_OnStartup(object sender, StartupEventArgs e)
.CreateLogger();
#endif
Log.Logger = log;

//Since we no longer have the StarupUri, we have to manually open our window.
MainWindow = new MainWindow();
var assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString();
MainWindow.Title = $"{MainWindow.Title} {assemblyVersion}";
MainWindow.Show();
}

private void App_OnExit(object sender, ExitEventArgs e)
{
Log.CloseAndFlush();
}
}
}
1 change: 0 additions & 1 deletion PrinterApp/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
xmlns:local="clr-namespace:PrinterApp"
mc:Ignorable="d"
Title="PrintApp" Height="900" Width="1600"
Closing="MainWindow_OnClosing"
FontFamily="/PrinterApp;component/Fonts/#Roboto"
WindowState="Maximized"
WindowStyle="None"
Expand Down
39 changes: 7 additions & 32 deletions PrinterApp/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Serilog;
using System;
using System.ComponentModel;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Timers;
Expand All @@ -16,18 +15,16 @@ namespace PrinterApp
/// </summary>
public partial class MainWindow : Window
{
private readonly PrinterModel _printerModel;
private readonly Regex _regex = new("[a-zA-Z0-9]{0,8}");
private readonly AutoUpdater _autoUpdater = new();
private readonly Random _random = new(Guid.NewGuid().GetHashCode());
private const int FlakesCount = 12;
private readonly double[] _flakesTargetsCanvasLeft = new double[FlakesCount];
private readonly PrinterModel _printerModel;

public MainWindow()
public MainWindow(PrinterModel printerModel)
{
ConfigFile configFile = new();
configFile.LoadConfig(GetType().Namespace!);
_printerModel = new PrinterModel(configFile, _autoUpdater);
_printerModel = printerModel;

for (var i = 0; i < FlakesCount; i++)
{
_printerModel.PrinterViewModel.FlakesCanvasTop.Add(0);
Expand All @@ -37,7 +34,7 @@ public MainWindow()
Loaded += (_, _) =>
{
MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
if (configFile.AutoUpdate) _autoUpdater.StartTimer();

SetNewYearTimer();
for (var i = 0; i < FlakesCount; i++)
{
Expand Down Expand Up @@ -91,7 +88,7 @@ public MainWindow()
};
DataContext = _printerModel.PrinterViewModel;
InitializeComponent();
//TODO what this?
//what this?
if (40 + Height < SystemParameters.PrimaryScreenHeight)
Top = 40;
Left = SystemParameters.PrimaryScreenWidth - 20 - Width;
Expand All @@ -102,6 +99,7 @@ public MainWindow()
Topmost = false;
ShowInTaskbar = true;
#endif
Marketing.MainWindowLoaded();
}

private bool IsTextAllowed(string text)
Expand Down Expand Up @@ -158,29 +156,6 @@ private void Print_OnClick(object sender, RoutedEventArgs e)
}
}

private void MainWindow_OnClosing(object? sender, CancelEventArgs e)
{
if (_printerModel.PrinterViewModel.CodeTextBoxText == "UPDATE")
{
_printerModel.PrinterViewModel.CodeTextBoxText = "";
_autoUpdater.ManualUpdate();
e.Cancel = true;
return;
}

if (_printerModel.WrongExitCode())
{
Marketing.CloseWithoutAccessProgram();
Log.Information(
$"{GetType().Name} {MethodBase.GetCurrentMethod()?.Name}: Attempt to close without access");
e.Cancel = true;
return;
}

_printerModel.SocketsClose();
_autoUpdater.StopTimer();
}

private void UIElement_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter) return;
Expand Down
27 changes: 27 additions & 0 deletions PrinterApp/Marketing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,15 @@ public static void LoadProgram()
pathTo: "");
}

public static void MainWindowLoaded()
{
Post(
action: "print terminal main window loaded",
status: "ok",
pathFrom: "",
pathTo: "");
}

public static void CloseWithoutAccessProgram()
{
Post(
Expand Down Expand Up @@ -135,6 +144,15 @@ public static void ManualUpdate()
pathTo: "");
}

public static void ManualReboot()
{
Post(
action: "print terminal manual reboot",
status: "ok",
pathFrom: "",
pathTo: "");
}

public static void SocketException(string status)
{
Post(
Expand All @@ -143,5 +161,14 @@ public static void SocketException(string status)
pathFrom: "",
pathTo: "");
}

public static void SocketConnected()
{
Post(
action: "print terminal socket connected",
status: "ok",
pathFrom: "",
pathTo: "");
}
}
}
4 changes: 2 additions & 2 deletions PrinterApp/PrinterApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<TargetFramework>net7.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<Platforms>x86</Platforms>
Expand All @@ -11,7 +11,7 @@
<Title>PrinterApp</Title>
<Description>gui fo work https://app.profcomff.com/print/docs</Description>
<Authors>Dyakov EI</Authors>
<Version>2.1.2.0</Version>
<Version>2.1.3.0</Version>
<Company>dyakov.space</Company>
<Copyright>dyakov.space @ 2022</Copyright>
</PropertyGroup>
Expand Down
29 changes: 13 additions & 16 deletions PrinterApp/PrinterModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ public class PrinterModel
private readonly HttpClient _httpClient;
private bool _socketClose;

public delegate void RebootHandler();

public event RebootHandler? Reboot;

public PrinterModel(ConfigFile configFile, AutoUpdater autoUpdater)
{
_configFile = configFile;
Expand All @@ -58,23 +62,13 @@ public PrinterModel(ConfigFile configFile, AutoUpdater autoUpdater)
_httpClient.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("token", _configFile.AuthorizationToken);

if (!Directory.Exists(_configFile.TempSavePath))
Directory.CreateDirectory(_configFile.TempSavePath);

var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
var str = Environment.ProcessPath ?? string.Empty;
key?.SetValue(GetType().Namespace, _configFile.StartWithWindows ? str : string.Empty);

if (SearchSumatraPdf() == "")
{
MessageBox.Show(SumatraError);
throw new Exception();
}

SocketsStartAsync();

Marketing.LoadProgram();
}

private static string SearchSumatraPdf()
Expand Down Expand Up @@ -333,6 +327,7 @@ private async void SocketsStartAsync()
return;
}

Marketing.SocketConnected();
_socketClose = false;
var buffer = new byte[128 * 1024];
while (!_socketClose)
Expand Down Expand Up @@ -361,12 +356,9 @@ await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Good Bye",
Marketing.SocketException(status: exception.Message);
Log.Error($"{GetType().Name} {MethodBase.GetCurrentMethod()?.Name}: {exception}");
PrinterViewModel.PrintQr = null!;
if (socket.State == WebSocketState.Aborted ||
socket.State == WebSocketState.Closed && socket.CloseStatus == null)
{
await Task.Delay(5000);
SocketsStartAsync();
}
socket.Abort();
await Task.Delay(5000);
SocketsStartAsync();
}
}

Expand All @@ -383,6 +375,11 @@ private async Task ParseResponseFromSocket(WebsocketReceiveOptions? websocketRec
_autoUpdater.ManualUpdate();
}

if (websocketReceiveOptions.Reboot)
{
Application.Current.Dispatcher.Invoke(() => { Reboot?.Invoke(); });
}

if (websocketReceiveOptions.QrToken == null!)
{
Marketing.SocketException("websocketReceiveOptions QrToken is null");
Expand Down
Loading

0 comments on commit eac899b

Please sign in to comment.