using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Security.AccessControl;
using System.ServiceProcess;
using System.Text;
using System.Windows;
using System.Windows.Forms;
namespace UseMonitor
{
/// <summary>
/// Used to contain variables needed by multiple methods
/// </summary>
public class DataContainer
{
public static string filesource = Environment.GetEnvironmentVariable("userprofile") + @"\Desktop\UseMonitor\UseMonitor\bin\Debug\";
public static string filename = filesource + "system_use.log";
public static DateTime startTime;
public static DateTime endTime;
public static string systemName = Environment.MachineName; // YOUR-4DACD0EA75
public static string userName = Environment.UserName; // HP_Administrator
public static string[] userList = { "HP_Administrator" };
}
public partial class UseMonitor : ServiceBase
{
public UseMonitor()
{
SystemEvents.SessionEnding += new SessionEndingEventHandler(OnSessionEnding);
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// check that the log file exists
if (!File.Exists(DataContainer.filename))
CreateLog();
// update the log file
UpdateLog(false);
}
protected override void OnStop()
{
UpdateLog("[S]");
SystemEvents.SessionEnding -= new SessionEndingEventHandler(OnSessionEnding);
}
void OnSessionEnding(object sender, SessionEndingEventArgs e)
{
UpdateLog(true);
}
public static void CreateLog()
{
StreamWriter log;
log = File.CreateText(DataContainer.filename);
log.WriteLine("This Log File Was Generated By UseMonitor.");
log.WriteLine("Each entry in this log contains a boot date and time, shutdown/log off date and time, and a total time the session was active.");
log.WriteLine("");
log.WriteLine("Legend:");
log.WriteLine("[S] - The UseMonitor service was stopped prematurly and does not have an acurate session end time.");
log.WriteLine(""); log.WriteLine("");
log.WriteLine("======================================================");
log.WriteLine(""); log.WriteLine("");
log.Close();
// lock the file for all users on the system
foreach (string user in DataContainer.userList)
{
LockFile(DataContainer.filename, DataContainer.systemName + "\\" + user, true);
}
}
public static void UpdateLog(bool stop)
{
// get data needed
string[] time = GetTime();
int line = GetLogLength(DataContainer.filename);
// unlock the log file
LockFile(DataContainer.filename, DataContainer.systemName + "\\" + DataContainer.userName, false);
// append data to the file
StreamWriter SW;
SW = File.AppendText(DataContainer.filename);
if (stop)
{
DataContainer.endTime = DateTime.Parse(time[0] + " " + time[1] + " " + time[2]);
TimeSpan totalTime = DataContainer.endTime.Subtract(DataContainer.startTime);
SW.WriteLine(" " + time[0] + " " + time[1] + time[2] + " " + WriteTime(totalTime));
}
else
{
DataContainer.startTime = DateTime.Parse(time[0] + " " + time[1] + " " + time[2]);
SW.Write(time[0] + " " + time[1] + time[2]);
}
SW.Close();
// re-lock the log file
LockFile(DataContainer.filename, DataContainer.systemName + "\\" + DataContainer.userName, true);
}
public static void UpdateLog(string comment)
{
// get data needed
string[] time = GetTime();
int line = GetLogLength(DataContainer.filename);
// unlock the log file
LockFile(DataContainer.filename, DataContainer.systemName + "\\" + DataContainer.userName, false);
// append data to the file
StreamWriter SW;
SW = File.AppendText(DataContainer.filename);
DataContainer.endTime = DateTime.Parse(time[0] + " " + time[1] + " " + time[2]);
TimeSpan totalTime = DataContainer.endTime.Subtract(DataContainer.startTime);
SW.WriteLine(" " + time[0] + " " + time[1] + time[2] + " " + WriteTime(totalTime) + " " + comment);
SW.Close();
// re-lock the log file
LockFile(DataContainer.filename, DataContainer.systemName + "\\" + DataContainer.userName, true);
}
public static int GetLogLength(string filename)
{
int count = 0;
using (var reader = File.OpenText(filename))
{
while (reader.ReadLine() != null)
{
count++;
}
}
return count;
}
public static string[] GetTime()
{
return DateTime.Now.ToString().Split(new Char[] { ' ' });
}
public static string WriteTime(TimeSpan time)
{
return time.Days + ":" + time.Hours + ":" + time.Minutes + ":" + time.Seconds;
}
public static void AddFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType)
{
// Get a FileSecurity object that represents the
// current security settings.
System.Security.AccessControl.FileSecurity fSecurity = File.GetAccessControl(fileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
// Set the new access settings.
File.SetAccessControl(fileName, fSecurity);
}
public static void RemoveFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType)
{
// Get a FileSecurity object that represents the
// current security settings.
System.Security.AccessControl.FileSecurity fSecurity = File.GetAccessControl(fileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.RemoveAccessRule(new FileSystemAccessRule(account, rights, controlType));
// Set the new access settings.
File.SetAccessControl(fileName, fSecurity);
}
public static void LockFile(string filename, string account, bool lockfile)
{
if (lockfile)
{
AddFileSecurity(filename, account, FileSystemRights.Write, AccessControlType.Deny);
AddFileSecurity(filename, account, FileSystemRights.Delete, AccessControlType.Deny);
AddFileSecurity(filename, account, FileSystemRights.ChangePermissions, AccessControlType.Deny);
}
else
{
RemoveFileSecurity(filename, account, FileSystemRights.Write, AccessControlType.Deny);
RemoveFileSecurity(filename, account, FileSystemRights.Delete, AccessControlType.Deny);
RemoveFileSecurity(filename, account, FileSystemRights.ChangePermissions, AccessControlType.Deny);
}
}
}
}