Skip to content
Snippets Groups Projects
Commit f5a847cc authored by Philipp Müller's avatar Philipp Müller
Browse files

Merge branch 'process-monitoring' into 'develop'

Process monitoring

See merge request borst/procrastinator!5
parents 966670ce 498fdfa4
No related branches found
No related tags found
1 merge request!5Process monitoring
Showing
with 651 additions and 1 deletion
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
.vscode/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
/.dotnet
/.packages
/.tools/vswhere/2.5.2
/.tools/native/iltools
### OSX ###
.DS_Store
.AppleDouble
.LSOverride
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
\ No newline at end of file
No preview for this file type
No preview for this file type
No preview for this file type
File deleted
File deleted
[
"Obsidian",
"notepad",
"chrome",
"firefox"
]
\ No newline at end of file
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Remove="Assets\blockedProcesses.json" />
<None Remove="Assets\logo.png" /> <None Remove="Assets\logo.png" />
</ItemGroup> </ItemGroup>
...@@ -33,6 +34,14 @@ ...@@ -33,6 +34,14 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Management" Version="9.0.0" />
</ItemGroup>
<ItemGroup>
<Content Include="Assets\blockedProcesses.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Resource Include="Assets\logo.png" /> <Resource Include="Assets\logo.png" />
</ItemGroup> </ItemGroup>
......
using System.Text; using InnoLabProjektDektopApp.Services;
using System.Text;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Data; using System.Windows.Data;
...@@ -16,6 +17,7 @@ namespace InnoLabProjektDektopApp ...@@ -16,6 +17,7 @@ namespace InnoLabProjektDektopApp
/// </summary> /// </summary>
public partial class Overview : Window public partial class Overview : Window
{ {
private ProcessMonitor processMonitor = new ProcessMonitor();
public Overview() public Overview()
{ {
InitializeComponent(); InitializeComponent();
...@@ -23,10 +25,12 @@ namespace InnoLabProjektDektopApp ...@@ -23,10 +25,12 @@ namespace InnoLabProjektDektopApp
} }
private void Option1_Click(object sender, RoutedEventArgs e) private void Option1_Click(object sender, RoutedEventArgs e)
{ {
processMonitor.StartMonitoring();
//this.Content = new AnotherWindow().Content; //this.Content = new AnotherWindow().Content;
} }
private void Option2_Click(object sender, RoutedEventArgs e) private void Option2_Click(object sender, RoutedEventArgs e)
{ {
processMonitor.StopMonitoring();
//this.Content = new AnotherWindow().Content; //this.Content = new AnotherWindow().Content;
} }
private void Option3_Click(object sender, RoutedEventArgs e) private void Option3_Click(object sender, RoutedEventArgs e)
......
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Windows;
namespace InnoLabProjektDektopApp.Services
{
public class ProcessInfo
{
public string ProcessName { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public ProcessInfo(string processName, DateTime startTime, DateTime endTime)
{
ProcessName = processName;
StartTime = startTime;
EndTime = endTime;
}
}
class ProcessMonitor
{
private readonly Dictionary<string, DateTime> processStartTimes = [];
private static List<string> blockedProcesses = [];
private bool isMonitoring = false;
private readonly List<ProcessInfo> processInfoList = new();
public ProcessMonitor()
{
blockedProcesses = LoadBlockedProcesses();
}
public async void StartMonitoring()
{
Debug.WriteLine("Started Process Monitoring");
var query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1),
"TargetInstance isa \"Win32_Process\"");
var watcher = new ManagementEventWatcher { Query = query };
isMonitoring = true;
await Task.Run(() =>
{
while (isMonitoring)
{
var e = watcher.WaitForNextEvent();
Task.Run(() => HandleNewProcess(e));
}
});
}
public void StopMonitoring()
{
Debug.WriteLine("Stopping Process Monitoring");
isMonitoring = false;
// make sure, that all processes have been tracked (it may take up to 100ms)
Task.Delay(200).Wait();
TimeSpan totalDistractionTime = CalculateTotalDistractionTime();
Debug.WriteLine("Total distraction time: {0}", totalDistractionTime);
}
private void HandleNewProcess(ManagementBaseObject e)
{
var processName = Path.GetFileNameWithoutExtension((string)((ManagementBaseObject)e["TargetInstance"])["Name"]);
if (processStartTimes.TryGetValue(processName, out _))
{
return;
}
processStartTimes[processName] = DateTime.Now;
if (IsProcessOnBlockedList(processName))
{
var result = MessageBox.Show($"Are you sure you want to get distracted by {processName}?", "Distracting Process Detected",
MessageBoxButton.YesNo,
MessageBoxImage.Question,
MessageBoxResult.No,
MessageBoxOptions.DefaultDesktopOnly
);
if (result == MessageBoxResult.No)
{
KillProcessesByName(processName);
processStartTimes.Remove(processName);
}
else
{
TrackProcess(processName, DateTime.Now);
}
}
}
private static void KillProcessesByName(String processName)
{
var runningProcesses = GetRunningProcessList();
if (!runningProcesses.TryGetValue(processName, out List<Process>? processes) || processes == null)
{
return; // Return early if the process name is not found or processes is null
}
Debug.WriteLine("Killing {0} processes with the Name {1}", processes.Count, processName);
foreach (var process in processes)
{
process.Kill();
}
}
private static Dictionary<string, List<Process>> GetRunningProcessList()
{
var processlist = Process.GetProcesses();
var processDictionary = new Dictionary<string, List<Process>>();
foreach (var process in processlist)
{
var processName = process.ProcessName;
if (!processDictionary.TryGetValue(processName, out List<Process>? value))
{
value = [];
processDictionary[processName] = value;
}
value.Add(process);
}
return processDictionary;
}
private static bool IsProcessOnBlockedList(string processName)
{
return blockedProcesses.Contains(processName);
}
private async void TrackProcess(string processName, DateTime startTime)
{
Debug.WriteLine($"Start monitoring the {processName} process");
Process? process = GetRunningProcessList().TryGetValue(processName, out List<Process>? processes) ? processes[0] : null;
if (process == null)
{
Debug.WriteLine("Process exited before we could track it.");
return;
}
// Token to handle task cancellation
using var cts = new CancellationTokenSource();
var token = cts.Token;
// Task to wait for the process to exit
var waitForExitTask = Task.Run(() => process.WaitForExit(), token);
// Task to monitor the isMonitoring flag
var monitorTask = Task.Run(async () =>
{
while (isMonitoring)
{
await Task.Delay(100); // Check every 100ms
}
cts.Cancel(); // Cancel the waitForExitTask if isMonitoring becomes false
});
try
{
// Await the completion of either the waitForExitTask or the monitorTask
await Task.WhenAny(waitForExitTask, monitorTask);
}
catch (OperationCanceledException)
{
Debug.WriteLine("Process monitoring was canceled.");
}
processStartTimes.Remove(processName);
var endTime = DateTime.Now;
processInfoList.Add(new ProcessInfo(processName, startTime, endTime));
Debug.WriteLine("Process monitoring complete.");
Debug.WriteLine("The Process has been running for {0} seconds", endTime - startTime);
}
public TimeSpan CalculateTotalDistractionTime()
{
var intervals = processInfoList
.OrderBy(p => p.StartTime)
.Select(p => (p.StartTime, p.EndTime))
.ToList();
if (intervals.Count == 0)
return TimeSpan.Zero;
var mergedIntervals = new List<(DateTime Start, DateTime End)> { intervals[0] };
foreach (var interval in intervals.Skip(1))
{
var last = mergedIntervals.Last();
if (interval.StartTime <= last.End)
{
mergedIntervals[mergedIntervals.Count - 1] = (last.Start, new DateTime(Math.Max(last.End.Ticks, interval.EndTime.Ticks)));
}
else
{
mergedIntervals.Add(interval);
}
}
return mergedIntervals.Aggregate(TimeSpan.Zero, (sum, interval) => sum + (interval.End - interval.Start));
}
private static List<string> LoadBlockedProcesses()
{
var blockedProcessesFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets\\blockedProcesses.json");
var fileContent = File.ReadAllText(blockedProcessesFilePath);
return JsonConvert.DeserializeObject<List<string>>(fileContent) ?? [];
}
}
}
...@@ -7,9 +7,48 @@ ...@@ -7,9 +7,48 @@
"targets": { "targets": {
".NETCoreApp,Version=v8.0": { ".NETCoreApp,Version=v8.0": {
"InnoLabProjektDektopApp/1.0.0": { "InnoLabProjektDektopApp/1.0.0": {
"dependencies": {
"Newtonsoft.Json": "13.0.3",
"System.Management": "9.0.0"
},
"runtime": { "runtime": {
"InnoLabProjektDektopApp.dll": {} "InnoLabProjektDektopApp.dll": {}
} }
},
"Newtonsoft.Json/13.0.3": {
"runtime": {
"lib/net6.0/Newtonsoft.Json.dll": {
"assemblyVersion": "13.0.0.0",
"fileVersion": "13.0.3.27908"
}
}
},
"System.CodeDom/9.0.0": {
"runtime": {
"lib/net8.0/System.CodeDom.dll": {
"assemblyVersion": "9.0.0.0",
"fileVersion": "9.0.24.52809"
}
}
},
"System.Management/9.0.0": {
"dependencies": {
"System.CodeDom": "9.0.0"
},
"runtime": {
"lib/net8.0/System.Management.dll": {
"assemblyVersion": "9.0.0.0",
"fileVersion": "9.0.24.52809"
}
},
"runtimeTargets": {
"runtimes/win/lib/net8.0/System.Management.dll": {
"rid": "win",
"assetType": "runtime",
"assemblyVersion": "9.0.0.0",
"fileVersion": "9.0.24.52809"
}
}
} }
} }
}, },
...@@ -18,6 +57,27 @@ ...@@ -18,6 +57,27 @@
"type": "project", "type": "project",
"serviceable": false, "serviceable": false,
"sha512": "" "sha512": ""
},
"Newtonsoft.Json/13.0.3": {
"type": "package",
"serviceable": true,
"sha512": "sha512-HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==",
"path": "newtonsoft.json/13.0.3",
"hashPath": "newtonsoft.json.13.0.3.nupkg.sha512"
},
"System.CodeDom/9.0.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-oTE5IfuMoET8yaZP/vdvy9xO47guAv/rOhe4DODuFBN3ySprcQOlXqO3j+e/H/YpKKR5sglrxRaZ2HYOhNJrqA==",
"path": "system.codedom/9.0.0",
"hashPath": "system.codedom.9.0.0.nupkg.sha512"
},
"System.Management/9.0.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-bVh4xAMI5grY5GZoklKcMBLirhC8Lqzp63Ft3zXJacwGAlLyFdF4k0qz4pnKIlO6HyL2Z4zqmHm9UkzEo6FFsA==",
"path": "system.management/9.0.0",
"hashPath": "system.management.9.0.0.nupkg.sha512"
} }
} }
} }
\ No newline at end of file
No preview for this file type
No preview for this file type
No preview for this file type
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment