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

Commit

Permalink
feat: pause and resume all processes on company software start
Browse files Browse the repository at this point in the history
  • Loading branch information
lukas-houille committed Dec 15, 2023
1 parent a774d4d commit 986de4e
Show file tree
Hide file tree
Showing 7 changed files with 122 additions and 18 deletions.
5 changes: 5 additions & 0 deletions EasyGUI/Controls/SettingsPopup.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,13 @@ private void ValidateButton_OnClick(object sender, RoutedEventArgs e)
Application.Restart();
Process.GetCurrentProcess().Kill();
}

// Invoke reload config event
ReloadConfig?.Invoke(this, EventArgs.Empty);
}

public event EventHandler? ReloadConfig;

private void SettingsPopup_OnLoaded(object sender, RoutedEventArgs e)
{
UpdateProperties();
Expand Down
3 changes: 2 additions & 1 deletion EasyGUI/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
Visibility="Collapsed" />
<controls:SettingsPopup
x:Name="SettingsPopup"
Visibility="Collapsed" />
Visibility="Collapsed"
ReloadConfig="SettingsPopup_OnReloadConfig"/>
</Grid>
</Window>
5 changes: 5 additions & 0 deletions EasyGUI/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,9 @@ private void UpdateJob(Job job)
Jobs.Remove(job);
Jobs.Insert(jobIndex, job);
}

private void SettingsPopup_OnReloadConfig(object? sender, EventArgs e)
{
_jobManager.ReloadConfig();
}
}
2 changes: 2 additions & 0 deletions EasyLib/EasyLib.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Windows.Compatibility" Version="8.0.0"/>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3"/>
<PackageReference Include="System.Management" Version="8.0.0"/>
</ItemGroup>

</Project>
68 changes: 68 additions & 0 deletions EasyLib/Events/ProcessStartEvent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System.Management;

namespace EasyLib.Events;

public class ProcessStartEvent
{
private readonly JobManager _jobManager;
private readonly ManagementEventWatcher _processStartEvent;
private readonly ManagementEventWatcher _processStopEvent;
private int _numberOfRunningProcesses;

/// <summary>
/// create the start and stop event for a process and bind the event to the job manager
/// </summary>
/// <param name="processName"></param>
/// <param name="jobManager"></param>
public ProcessStartEvent(string? processName, JobManager jobManager)
{
// check if system is running Windows
_jobManager = jobManager;
#pragma warning disable CA1416
_processStartEvent =
new ManagementEventWatcher(
new WqlEventQuery($"SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = '{processName}'"));
_processStartEvent.EventArrived += ProcessStarted;
// on stop
_processStopEvent = new ManagementEventWatcher(new WqlEventQuery(
$"SELECT * FROM Win32_ProcessStopTrace WHERE ProcessName = '{processName}'"));
_processStopEvent.EventArrived += ProcessStopped;
_processStartEvent.Start();
_processStopEvent.Start();
#pragma warning restore CA1416
}

private void ProcessStarted(object sender, EventArrivedEventArgs e)
{
if (_numberOfRunningProcesses == 0)
{
_jobManager.PauseAllJobs();
Interlocked.Increment(ref _numberOfRunningProcesses);
}
else
{
Interlocked.Increment(ref _numberOfRunningProcesses);
}
}

private void ProcessStopped(object sender, EventArrivedEventArgs e)
{
if (_numberOfRunningProcesses == 1)
{
_jobManager.ResumeAllJobs();
Interlocked.Decrement(ref _numberOfRunningProcesses);
}
else
{
Interlocked.Decrement(ref _numberOfRunningProcesses);
}
}

public void Stop()
{
#pragma warning disable CA1416
_processStopEvent.Stop();
_processStartEvent.Stop();
#pragma warning restore CA1416
}
}
20 changes: 5 additions & 15 deletions EasyLib/Job/Job.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Diagnostics;
using EasyLib.Enums;
using EasyLib.Events;
using EasyLib.Files;
Expand All @@ -23,7 +22,6 @@ public class Job(
JobState state = JobState.End) : IJobStatusPublisher, IJobStatusSubscriber
{
public static readonly Semaphore MaxSizeFileCopying = new Semaphore(1, 1);
public static ulong CurrentPriorityRunning = 0;
public static readonly EventWaitHandle NotifyWaitingJobs = new EventWaitHandle(initialState: false, ManualReset);

/// <summary>
Expand All @@ -43,6 +41,8 @@ public Job(JsonJob job) : this(job.name, job.source_folder, job.destination_fold
CurrentFileDestination = job.active_job_info?.current_file_destination ?? string.Empty;
}

public static ulong CurrentPriorityRunning { get; set; }

private List<IJobStatusSubscriber> Subscribers { get; } = new();
public string DestinationFolder { get; set; } = destinationFolder;
public ulong FilesBytesCopied { get; set; }
Expand Down Expand Up @@ -111,6 +111,8 @@ public JsonJob ToJsonJob()
/// <returns>True if the job is started correctly</returns>
public bool Resume()
{
CancellationToken.Dispose();
CancellationToken = new CancellationTokenSource();
return Start(true);
}

Expand All @@ -136,17 +138,6 @@ private bool Start(bool resume)
return false;
}

// Wait for the company software to be closed
if (ConfigManager.Instance.CheckProcessRunning())
{
var processName = Path.GetFileNameWithoutExtension(ConfigManager.Instance.CompanySoftwareProcessPath);
var processes = Process.GetProcessesByName(processName);
foreach (var process in processes)
{
process.WaitForExit();
}
}

// Reset the job stats if the job is not resumed
if (!resume)
{
Expand Down Expand Up @@ -241,14 +232,13 @@ public bool Cancel()
return true;
}

private bool _resetJobStats()
private void _resetJobStats()
{
FilesCount = 0;
FilesSizeBytes = 0;
FilesCopied = 0;
FilesBytesCopied = 0;
State = JobState.End;
return true;
}

private void _notifySubscribersForChangeState(JobState subState)
Expand Down
37 changes: 35 additions & 2 deletions EasyLib/JobManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public partial class JobManager : IJobStatusSubscriber, IJobStatusPublisher
/// </summary>
private readonly List<IJobStatusSubscriber> _subscribers = new();

private ProcessStartEvent _pauseJobEvent;


public JobManager(bool ramOnly = false)
{
Expand All @@ -34,6 +36,8 @@ public JobManager(bool ramOnly = false)
{
FetchJobs();
}

_pauseJobEvent = new ProcessStartEvent(ConfigManager.Instance.CompanySoftwareProcessPath, this);
}

public void Subscribe(IJobStatusSubscriber subscriber)
Expand Down Expand Up @@ -279,6 +283,14 @@ public void PauseJob(Job.Job job)
StateManager.Instance.WriteJobs(_jobs);
}

public void PauseAllJobs()
{
foreach (var job in _jobs)
{
PauseJob(job);
}
}

public JobCheckRule CheckJobRules(int id, string name, string source, string destination, bool testEmpty = true)
{
if (!Path.IsPathFullyQualified(source))
Expand Down Expand Up @@ -336,8 +348,29 @@ public JobCheckRule CheckJobRules(int id, string name, string source, string des

public void ResumeJob(Job.Job job)
{
job.Subscribe(this);
job.Resume();
job.Unsubscribe(this);
}

public void ResumeAllJobs()
{
foreach (var job in _jobs)
{
if (job.State != JobState.End)
{
job.Resume();
}
}
}

public bool ReloadConfig()
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT) // only on Windows can run this feature
{
_pauseJobEvent.Stop();
_pauseJobEvent = new ProcessStartEvent(ConfigManager.Instance.CompanySoftwareProcessPath, this);
return true;
}

return false;
}
}

0 comments on commit 986de4e

Please sign in to comment.