From: <jos...@us...> - 2008-12-10 18:57:13
|
Revision: 2407 http://mp-plugins.svn.sourceforge.net/mp-plugins/?rev=2407&view=rev Author: josch-hh Date: 2008-12-10 18:57:07 +0000 (Wed, 10 Dec 2008) Log Message: ----------- Added Paths: ----------- trunk/plugins/TVSAuditor/ trunk/plugins/TVSAuditor/TVSAuditor/ trunk/plugins/TVSAuditor/TVSAuditor/CardInfo.cs trunk/plugins/TVSAuditor/TVSAuditor/CommonSettings.cs trunk/plugins/TVSAuditor/TVSAuditor/Logging/ trunk/plugins/TVSAuditor/TVSAuditor/Logging/ErrorFileLogHandler.cs trunk/plugins/TVSAuditor/TVSAuditor/Logging/FileLogHandler.cs trunk/plugins/TVSAuditor/TVSAuditor/Logging/GuiLogHandler.cs trunk/plugins/TVSAuditor/TVSAuditor/Logging/ILogHandler.cs trunk/plugins/TVSAuditor/TVSAuditor/Logging/Logger.cs trunk/plugins/TVSAuditor/TVSAuditor/Properties/ trunk/plugins/TVSAuditor/TVSAuditor/Properties/AssemblyInfo.cs trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.cs trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.csproj trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.csproj.user trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditorInstaller.cs trunk/plugins/TVSAuditor/TVSAuditor/TVSinterface.cs trunk/plugins/TVSAuditor/TVSAuditor/Tools.cs trunk/plugins/TVSAuditor/TVSAuditor/app.config trunk/plugins/TVSAuditor/TVSAuditor/bin/ trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/ trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/DirectShowLib.dll trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/TVSAuditor.exe trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/TVSAuditor.exe.config trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/TVSAuditor.pdb trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/TVSAuditor.vshost.exe trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/TVSAuditor.vshost.exe.config trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/TVSAuditor.vshost.exe.manifest trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/TvControl.dll trunk/plugins/TVSAuditor/TVSAuditor/bin/Debug/TvLibrary.Interfaces.dll trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/ trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/DirectShowLib.dll trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/InstallUtil.InstallLog trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/TVSAuditor.exe trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/TVSAuditor.exe.config trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/TVSAuditor.pdb trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/TVSAuditor.xml trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/TVSauditor.InstallLog trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/TVSauditor.InstallState trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/TvControl.dll trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/TvLibrary.Interfaces.dll trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/install.cmd trunk/plugins/TVSAuditor/TVSAuditor/bin/Release/uninstall.cmd trunk/plugins/TVSAuditor/TVSAuditor/install.cmd trunk/plugins/TVSAuditor/TVSAuditor/obj/ trunk/plugins/TVSAuditor/TVSAuditor/obj/Debug/ trunk/plugins/TVSAuditor/TVSAuditor/obj/Debug/Refactor/ trunk/plugins/TVSAuditor/TVSAuditor/obj/Debug/ResolveAssemblyReference.cache trunk/plugins/TVSAuditor/TVSAuditor/obj/Debug/TVSAuditor.csproj.FileListAbsolute.txt trunk/plugins/TVSAuditor/TVSAuditor/obj/Debug/TVSAuditor.exe trunk/plugins/TVSAuditor/TVSAuditor/obj/Debug/TVSAuditor.pdb trunk/plugins/TVSAuditor/TVSAuditor/obj/Debug/TempPE/ trunk/plugins/TVSAuditor/TVSAuditor/obj/Release/ trunk/plugins/TVSAuditor/TVSAuditor/obj/Release/Refactor/ trunk/plugins/TVSAuditor/TVSAuditor/obj/Release/TVSAuditor.csproj.FileListAbsolute.txt trunk/plugins/TVSAuditor/TVSAuditor/obj/Release/TVSAuditor.exe trunk/plugins/TVSAuditor/TVSAuditor/obj/Release/TVSAuditor.pdb trunk/plugins/TVSAuditor/TVSAuditor/obj/Release/TempPE/ trunk/plugins/TVSAuditor/TVSAuditor/uninstall.cmd trunk/plugins/TVSAuditor/TVSAuditor.sln trunk/plugins/TVSAuditor/TVSAuditor.suo Added: trunk/plugins/TVSAuditor/TVSAuditor/CardInfo.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/CardInfo.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/CardInfo.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace TVSAuditor +{ + public class CardInfo + { + + private string username; + private TVSinterface.CardStatus status; + private string cardname; + private int cardId; + + + public CardInfo() + { + } + + public string Username { + get { return username;} + set { username = value; } + } + + + public string Cardname + { + get { return cardname; } + set { cardname = value; } + } + + + public int CardId + { + get { return cardId; } + set { cardId = value; } + } + + + public TVSinterface.CardStatus Status + { + get { return status; } + set { status = value; } + } + + } +} Added: trunk/plugins/TVSAuditor/TVSAuditor/CommonSettings.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/CommonSettings.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/CommonSettings.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,258 @@ +using System; +using System.Text; +using System.Xml; +using System.IO; + +namespace TVSAuditor +{ + public static class CommonSettings + { + + public const string APP_DATA_DIRECTORY_NAME = "TVSAuditor"; + public const string TVSERVICE_PROCESS_NAME = "TVService"; + public const string SETTINGS_FILENAME = "TVSAuditor.xml"; + + private const string CPU_MAX_USAGE_BUSY_KEY = "CpuUsageBusy"; + private const string CPU_MAX_USAGE_IDLE_KEY = "CpuUsageIdle"; + private const string MEMORY_MAX_USAGE_KEY = "MemoryUsage"; + private const string TIMESHIFT_USERS_KEY = "TimeshiftUsers"; + private const string AUDIT_INTERVAL_KEY = "AuditInterval"; + private const string LOG_LEVEL_KEY = "LogLevel"; + private const string COMMON_SETTINGS_ELEMENT = "CommonSettings"; + + private static string[] SPLIT_STRING = new string[] { "," }; + private static XmlDocument doc; + + + public static int AuditInterval + { + get + { + int retVal = 180000; + int.TryParse(LoadElement(AUDIT_INTERVAL_KEY), out retVal); + return retVal; + } + set + { + CreateElement(AUDIT_INTERVAL_KEY, value.ToString()); + } + } + + + public static Logger.Level LogLevel + { + get + { + try + { + return (Logger.Level)Enum.Parse(typeof(Logger.Level), LoadElement(LOG_LEVEL_KEY).ToUpper()); + } + catch (Exception) + { + Logger.Warn("Unkown log level from settings file - Possible levels are: DEBUG, INFO, WARNING, ERROR"); + return Logger.Level.INFO; + } + } + set + { + CreateElement(LOG_LEVEL_KEY, value.ToString("G")); + } + } + + + public static string[] TimeshiftUsers + { + get + { + string[] users = LoadElement(MEMORY_MAX_USAGE_KEY).Split(SPLIT_STRING,StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < users.Length; i++) + { + users[i] = users[i].Trim(); + } + return users; + } + set + { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < value.Length; i++) + { + if (!String.IsNullOrEmpty(value[i].Trim())) + sb.Append(value[i].Trim()); + if (i < value.Length - 1) sb.Append(SPLIT_STRING); + } + CreateElement(TIMESHIFT_USERS_KEY, sb.ToString()); + } + } + + + + public static double MemoryMaxUsage + { + get + { + double retVal = 100f; + double.TryParse(LoadElement(MEMORY_MAX_USAGE_KEY), out retVal); + return retVal; + } + set + { + CreateElement(MEMORY_MAX_USAGE_KEY, value.ToString("f")); + } + } + + + public static float CpuMaxUsageBusy + { + get { + float retVal = 100f; + float.TryParse(LoadElement(CPU_MAX_USAGE_BUSY_KEY), out retVal); + return retVal; + } + set + { + CreateElement(CPU_MAX_USAGE_BUSY_KEY, value.ToString("f")); + } + } + + + public static float CpuMaxUsageIdle + { + get + { + float retVal = 100f; + float.TryParse(LoadElement(CPU_MAX_USAGE_IDLE_KEY), out retVal); + return retVal; + } + set + { + CreateElement(CPU_MAX_USAGE_IDLE_KEY, value.ToString("f")); + } + } + + + public static string AppDataPath + { + get + { + return Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\" + APP_DATA_DIRECTORY_NAME; + } + } + + + public static void InitialLoading() + { + doc = new XmlDocument(); + FileStream fs = null; + + if (!Directory.Exists(AppDataPath)) Directory.CreateDirectory(AppDataPath); + string file = AppDataPath + @"\" + SETTINGS_FILENAME; + + try + { + if (!File.Exists(file)) + { + Logger.Info("Settings Load - Initializing new settings file"); + XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); + doc.AppendChild(dec); + XmlComment comment = doc.CreateComment("Settings " + SETTINGS_FILENAME); + doc.AppendChild(comment); + XmlElement startElem = doc.CreateElement(COMMON_SETTINGS_ELEMENT); + doc.AppendChild(startElem); + } + else + { + Logger.Info("Settings Load - Loading settings from " + file); + fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + doc.Load(fs); + } + } + catch (Exception ex) + { + Logger.Warn("Settings Load - Error loading settings " + ex.Message); + } + finally + { + try + { + if (fs != null) fs.Close(); + } + catch (Exception ex) + { + Logger.Warn("Settings Load - Error closing settings file " + ex.Message); + } + } + } + + + private static void CreateElement(string key, string value) + { + if (key == null || value == null) throw new ArgumentException("key or value can't be null"); + + if (doc == null) InitialLoading(); + + for (int i = 0; i < doc.DocumentElement.ChildNodes.Count; i++) + { + if (doc.DocumentElement.ChildNodes[i].Name == key) + { + doc.DocumentElement.ChildNodes[i].InnerText = value; + return; + } + } + + XmlElement elem = doc.CreateElement(key); + elem.InnerText = value; + doc.DocumentElement.AppendChild(elem); + } + + + private static string LoadElement(string key) + { + if (key == null) return ""; + + if (doc == null) InitialLoading(); + + if (doc.DocumentElement == null) throw new Exception("Settings file corrupted"); + + for (int i = 0; i < doc.DocumentElement.ChildNodes.Count; i++) + { + if (doc.DocumentElement.ChildNodes[i].Name == key) + return doc.DocumentElement.ChildNodes[i].InnerText; + } + return ""; + } + + + public static void Save() + { + if (doc == null) throw new Exception("doc is null, settings file not initially loaded"); + + string file = AppDataPath + @"\" + SETTINGS_FILENAME; + + XmlTextWriter writer = null; + try + { + if (!Directory.Exists(AppDataPath)) Directory.CreateDirectory(AppDataPath); + writer = new XmlTextWriter(file, Encoding.UTF8); + Logger.Info("Settings Save - Saving settings to " + file); + writer.Formatting = Formatting.Indented; + doc.WriteTo(writer); + } + catch (Exception ex) + { + Logger.Warn("Settings Save - Error saving settings " + ex.Message); + } + finally + { + try + { + if (writer != null) writer.Close(); + } + catch (Exception ex) + { + Logger.Warn("Settings Save - Error closing settings file " + ex.Message); + } + } + } + + } +} Added: trunk/plugins/TVSAuditor/TVSAuditor/Logging/ErrorFileLogHandler.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/Logging/ErrorFileLogHandler.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/Logging/ErrorFileLogHandler.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,19 @@ +using System; + +namespace TVSAuditor +{ + public class ErrorFileLogHandler: FileLogHandler + { + + public ErrorFileLogHandler(string logFile) : base(logFile) + { + } + + + public override void Log(string message, Logger.Level level) + { + if (level < Logger.Level.WARNING) return; + base.Log(message, level); + } + } +} Added: trunk/plugins/TVSAuditor/TVSAuditor/Logging/FileLogHandler.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/Logging/FileLogHandler.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/Logging/FileLogHandler.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,130 @@ +using System; +using System.IO; + +namespace TVSAuditor +{ + public class FileLogHandler : ILogHandler + { + + protected string logFile; + protected string logDir; + protected object syncAccess = new object(); + protected StreamWriter writer; + + + public FileLogHandler(string logFile) + { + if (logFile == null) throw new ArgumentException("logfile can't be null"); + this.logFile = logFile; + + try + { + logDir = Directory.GetParent(logFile).FullName; + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.Message); + } + + RotateLogFile(); + Open(); + Logger.AddLogHandler(this); + } + + + protected void Open() + { + try + { + string logDir = Directory.GetParent(logFile).FullName; + if (!Directory.Exists(logDir)) + { + Directory.CreateDirectory(logDir); + } + writer = new StreamWriter(File.Open(logFile, FileMode.Append, FileAccess.Write, FileShare.Read)); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.Message); + try + { + if (writer != null) writer.Close(); + } + catch (Exception ex2) + { + System.Diagnostics.Debug.WriteLine(ex2.Message); + } + } + } + + + public void Close() + { + try + { + if (writer != null) writer.Close(); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.Message); + } + } + + + public void RotateLogFile() + { + if (String.IsNullOrEmpty(logFile)) return; + + + int count = 5; + for (int i = count; i > 0; i--) + { + try + { + string sourceFile = logFile + "." + (i - 1); + string targetFile = logFile + "." + i; + if (i == 1) sourceFile = logFile; + + if (File.Exists(targetFile)) File.Delete(targetFile); + if (File.Exists(sourceFile)) File.Move(sourceFile, targetFile); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.Message); + } + } + } + + + public void DeleteLogFile() + { + if (String.IsNullOrEmpty(logFile)) return; + + try + { + if (File.Exists(logFile)) File.Delete(logFile); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.Message); + } + } + + + public virtual void Log(string message, Logger.Level level) + { + try + { + writer.WriteLine(DateTime.Now + " - " + level.ToString("G") + "\t" + message); + writer.Flush(); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.Message); + } + } + + + } + +} Added: trunk/plugins/TVSAuditor/TVSAuditor/Logging/GuiLogHandler.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/Logging/GuiLogHandler.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/Logging/GuiLogHandler.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,60 @@ +using System; +using System.Text; + +namespace TVSAuditor +{ + public class GuiLogHandler : ILogHandler + { + + private SendMessage sendMessage; + + + public delegate void SendMessage(string message); + + + public GuiLogHandler(SendMessage sendMessage) + { + if (sendMessage == null) throw new ArgumentException("SendMessage can't be null"); + this.sendMessage = sendMessage; + Logger.AddLogHandler(this); + } + + + public void Log(string message, Logger.Level level) + { + string logLevel; + switch (level) + { + case Logger.Level.INFO: + logLevel = "Info"; + break; + case Logger.Level.WARNING: + logLevel = "Warning"; + break; + case Logger.Level.ERROR: + logLevel = "Error"; + break; + default: + logLevel = "Unknow"; + return; + } + + StringBuilder sb = new StringBuilder(); + sb.Append(DateTime.Now.ToString()); + sb.Append(" :: "); + sb.Append(logLevel); + sb.Append(" :: "); + sb.Append(message); + sb.Append(Environment.NewLine); + + sendMessage(sb.ToString()); + } + + + public void Close() + { + // No need to close anything + } + + } +} Added: trunk/plugins/TVSAuditor/TVSAuditor/Logging/ILogHandler.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/Logging/ILogHandler.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/Logging/ILogHandler.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,12 @@ + +namespace TVSAuditor +{ + public interface ILogHandler + { + + void Log(string message, Logger.Level level); + + void Close(); + + } +} Added: trunk/plugins/TVSAuditor/TVSAuditor/Logging/Logger.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/Logging/Logger.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/Logging/Logger.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,97 @@ +using System.Collections.Generic; + +namespace TVSAuditor +{ + public static class Logger + { + public enum Level { + DEBUG = 50, + INFO = 100, + WARNING = 200, + ERROR = 300 + } + + private static Level reportLevel = Level.INFO; + + private static List<ILogHandler> logHandler = new List<ILogHandler>(); + + + public static Level ReportLevel + { + get { return reportLevel; } + set { reportLevel = value; } + } + + + public static bool IsLoggable(Level level) + { + return (level > reportLevel); + } + + + public static void AddLogHandler(ILogHandler lh) + { + if (lh != null && ! logHandler.Contains(lh)) + logHandler.Add(lh); + } + + + public static void RemoveLogHandler(ILogHandler lh) + { + if (lh != null) + logHandler.Remove(lh); + } + + + public static void RemoveAllHandlers() + { + logHandler.Clear(); + } + + + public static void Close() + { + foreach (ILogHandler lh in logHandler) + { + if (lh != null) + lh.Close(); + } + } + + + public static void Log(string logMessage, Level level) + { + if (level < reportLevel) return; + + foreach (ILogHandler lh in logHandler) + { + if (lh != null) + lh.Log(logMessage, level); + } + } + + + public static void Info(string logMessage) + { + Log(logMessage, Level.INFO); + } + + + public static void Warn(string logMessage) + { + Log(logMessage, Level.WARNING); + } + + + public static void Error(string logMessage) + { + Log(logMessage, Level.ERROR); + } + + + public static void Debug(string logMessage) + { + Log(logMessage, Level.DEBUG); + } + } +} Added: trunk/plugins/TVSAuditor/TVSAuditor/Properties/AssemblyInfo.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/Properties/AssemblyInfo.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/Properties/AssemblyInfo.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die mit einer Assembly verknüpft sind. +[assembly: AssemblyTitle("TVSAuditor")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("TVSAuditor")] +[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar +// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von +// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. +[assembly: ComVisible(false)] + +// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +[assembly: Guid("82559b46-4223-4aeb-b2f9-29508b64f529")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +[assembly: AssemblyVersion("0.0.1.8")] +[assembly: AssemblyFileVersion("0.0.1.8")] Added: trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,303 @@ +using System.Collections.Generic; +using System.IO; +using System; +using System.ServiceProcess; +using System.Timers; + + +namespace TVSAuditor +{ + + public class TVSAuditor : ServiceBase + { + + public const string LOGFILENAME = "TVSAuditor.log"; + public const string ERROR_LOGFILENAME = "TVSAuditor.err"; + public const string SERVICE_NAME = "TVSAuditor"; + + + private Timer timer; + private TVSinterface tvsi; + + + static void Main() + { +//#if (!DEBUG) + ServiceBase.Run(new TVSAuditor()); +//#else +// TVSAuditor service = new TVSAuditor(); + +// service.AuditEvent(null, null); +//#endif + } + + + public TVSAuditor() + { + new FileLogHandler(CommonSettings.AppDataPath + @"\" + LOGFILENAME); + new ErrorFileLogHandler(CommonSettings.AppDataPath + @"\" + ERROR_LOGFILENAME); + + // Set default value for settings if no settings file found + if (File.Exists(CommonSettings.AppDataPath + @"\" + CommonSettings.SETTINGS_FILENAME)) + { + CommonSettings.InitialLoading(); + } + else + { + CommonSettings.LogLevel = Logger.Level.DEBUG; + CommonSettings.AuditInterval = 300; + CommonSettings.CpuMaxUsageBusy = 70f; + CommonSettings.CpuMaxUsageIdle = 30f; + CommonSettings.MemoryMaxUsage = 100d; + //CommonSettings.TimeshiftUsers = new string[] { "" }; + CommonSettings.Save(); + } + + Logger.ReportLevel = CommonSettings.LogLevel; + + this.ServiceName = SERVICE_NAME; + this.EventLog.Log = "Application"; + + try + { + EventLog.WriteEntry("Logging to " + CommonSettings.AppDataPath + @"\" + LOGFILENAME); + } + catch (Exception ex) + { + // Try to log to own logging system + Logger.Warn("Unable to log to Windows eventlog: " + ex.Message); + } + + // These Flags set whether or not to handle that specific + // type of event. Set to true if you need it, false otherwise. + this.CanHandlePowerEvent = true; + this.CanHandleSessionChangeEvent = true; + this.CanPauseAndContinue = true; + this.CanShutdown = true; + this.CanStop = true; + + } + + + protected override void Dispose(bool disposing) + { + Logger.Close(); + base.Dispose(disposing); + } + + + protected override void OnStart(string[] args) + { + string path = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); + string serviceVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(path + @"\" + SERVICE_NAME + ".exe").ProductVersion; + + Logger.Info("Starting " + SERVICE_NAME + " v" + serviceVersion); + Logger.Info("Log level: " + Logger.ReportLevel.ToString("G")); + timer = new Timer(); + timer.Elapsed += new ElapsedEventHandler( AuditEvent ); + timer.Interval = CommonSettings.AuditInterval * 1000; + timer.Start(); + Logger.Info("Started audit timer with interval: " + CommonSettings.AuditInterval + "s"); + } + + + protected override void OnStop() + { + Logger.Info("Stoping " + SERVICE_NAME); + if (timer != null) + { + timer.Stop(); + timer.Dispose(); + } + } + + + protected override void OnPause() + { + Logger.Info("Pause " + SERVICE_NAME); + if (timer != null) + { + timer.Stop(); + } + } + + + protected override void OnContinue() + { + Logger.Info("Continue " + SERVICE_NAME); + if (timer != null) + { + timer.Start(); + } + } + + + protected override void OnShutdown() + { + Logger.Info("System Shutdown"); + base.OnShutdown(); + } + + + protected override void OnCustomCommand(int command) + { + base.OnCustomCommand(command); + } + + + protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) + { + Logger.Info("PowerEvent: " + powerStatus.ToString()); + return base.OnPowerEvent(powerStatus); + } + + + protected override void OnSessionChange(SessionChangeDescription changeDescription) + { + Logger.Info("SessionEvent: " + changeDescription.Reason.ToString()); + base.OnSessionChange(changeDescription); + } + + + + private void AuditEvent(object source, ElapsedEventArgs e) + { + string serviceName = CommonSettings.TVSERVICE_PROCESS_NAME; + + if (!Tools.IsServiceRunning(serviceName)) + { + Logger.Warn("TVService is not running, abording audit"); + return; + } + + DateTime startDate = DateTime.Now; + Logger.Debug("**** START Audit for timestamp: " + startDate); + + // Connect to TVS + if (tvsi != null) + { + tvsi.Disconnect(); + tvsi = null; + } + tvsi = new TVSinterface(); + // Add card to hide + //tvsi.AddCardToHide("RadioWebStream Card (builtin)"); + if (!TVSinterface.IsConnected()) + { + Logger.Warn("AP00: Unable to connect to TVService - ACTION: Should Restart TVService"); + return; + } + + // Show stati for all cards + //tvsi.ShowAllCardsStatus(); + + // Preload settings + float cpuMaxUsageBusy = CommonSettings.CpuMaxUsageBusy; + Logger.Debug("A: Loaded CPU max busy usage from settings: " + cpuMaxUsageBusy + "%"); + float cpuMaxUsageIdle = CommonSettings.CpuMaxUsageIdle; + Logger.Debug("A: Loaded CPU max idle usage from settings: " + cpuMaxUsageIdle + "%"); + double memMaxUsage = CommonSettings.MemoryMaxUsage; + Logger.Debug("A: Loaded Memory max usage from settings: " + memMaxUsage + "MB"); + + // Get process information + float cpuUsage = Tools.GetCpuUsage(serviceName, 5, 800); + Logger.Info("A: Current CPU usage: " + cpuUsage.ToString("F") + "%"); + double memUsage = Tools.GetMemoryUsage(serviceName); + Logger.Info("A: Current Memory usage: " + memUsage.ToString("F") + "MB"); + + // Get common card idle status + bool anyRecording = tvsi.AreAnyCards(TVSinterface.CardStatus.Recording); + Logger.Info("A: Are any cards recording: " + anyRecording); + bool anyTimeshifting = tvsi.AreAnyCards(TVSinterface.CardStatus.TimeShifting); + Logger.Info("A: Are any cards timeshifting: " + anyTimeshifting); + bool anyGrabbingEpg = tvsi.AreAnyCards(TVSinterface.CardStatus.GrabbingEpg); + Logger.Info("A: Are any cards grabbing epg: " + anyGrabbingEpg); + + bool allCardsIdle = tvsi.AreAllCardsIdle(); + Logger.Info("A: Are all cards idle: " + allCardsIdle); + + + if (memUsage > memMaxUsage) + { + Logger.Info("AP0: Memory usage is to high - ACTION: Should Restart TVService"); + } + else + { + Logger.Info("AP0: Memory usage on normal level - ACTION: Restart TVService NOT necessary"); + } + + + if (!allCardsIdle) + { + Logger.Info("AP1: At least one card is in use"); + + if (tvsi.AreAnyCards(TVSinterface.CardStatus.Recording) || tvsi.AreAnyCards(TVSinterface.CardStatus.TimeShifting)) + { + if (cpuUsage > cpuMaxUsageBusy) + { + Logger.Info("AP11: CPU usage for TVS(epg grabbing) to high - ACTION: Should Restart TVService"); + } + else + { + Logger.Info("AP11: CPU usage for TVS(epg grabbing) on normal level - ACTION: Restart TVService NOT necessary"); + } + } + else + { + if (cpuUsage > cpuMaxUsageIdle) + { + Logger.Info("AP12: CPU usage for TVS(epg grabbing) to high - ACTION: Should Restart TVService"); + } + else + { + Logger.Info("AP12: CPU usage for TVS(epg grabbing) on normal level - ACTION: Restart TVService NOT necessary"); + } + } + } + else + { + Logger.Info("AP2: No cards are in use"); + if (cpuUsage > cpuMaxUsageIdle) + { + Logger.Info("AP21: CPU usage for TVS(idle) to high - ACTION: Should Restart TVService"); + } + else + { + Logger.Info("AP21: CPU usage for TVS(idle) on normal level - ACTION: Restart TVService NOT necessary"); + } + } + + + // Disconnect from TVS + tvsi.Disconnect(); + tvsi = null; + + Logger.Debug("**** END Audit for timestamp: " + startDate); + System.GC.Collect(); + } + + + private void RestartTVS() + { + string serviceName = CommonSettings.TVSERVICE_PROCESS_NAME; + + if (!Tools.ServiceStop(serviceName, 10)) + { + if (!Tools.ProcessStop(serviceName, 10, true)) + { + Logger.Warn("TVService can't be killed !!!"); + } + + } + + System.Threading.Thread.Sleep(2000); + + if (!Tools.ServiceStart(serviceName, 30)) + { + Logger.Warn("TVService can't be started"); + } + } + + } + +} Added: trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.csproj =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.csproj (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.csproj 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,81 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>9.0.30729</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{BA83ED82-64A8-4DCB-B4D9-AAA3F4FFE785}</ProjectGuid> + <OutputType>Exe</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>TVSAuditor</RootNamespace> + <AssemblyName>TVSAuditor</AssemblyName> + <TargetFrameworkVersion>v2.0</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + <TargetFrameworkSubset> + </TargetFrameworkSubset> + <StartupObject>TVSAuditor.TVSAuditor</StartupObject> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> + <ItemGroup> + <Compile Include="CardInfo.cs" /> + <Compile Include="CommonSettings.cs" /> + <Compile Include="Logging\ErrorFileLogHandler.cs" /> + <Compile Include="Logging\FileLogHandler.cs" /> + <Compile Include="Logging\GuiLogHandler.cs" /> + <Compile Include="Logging\ILogHandler.cs" /> + <Compile Include="Logging\Logger.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="TVSAuditor.cs"> + <SubType>Component</SubType> + </Compile> + <Compile Include="TVSAuditorInstaller.cs"> + <SubType>Component</SubType> + </Compile> + <Compile Include="Tools.cs" /> + <Compile Include="TVSinterface.cs" /> + </ItemGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Configuration.Install" /> + <Reference Include="System.Data" /> + <Reference Include="System.ServiceProcess" /> + <Reference Include="System.Windows.Forms" /> + <Reference Include="System.XML" /> + <Reference Include="TvControl, Version=0.9.3.968, Culture=neutral, processorArchitecture=x86"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\..\..\..\..\..\Program Files\Team MediaPortal\MediaPortal TV Server\TvControl.dll</HintPath> + </Reference> + <Reference Include="TvLibrary.Interfaces, Version=0.9.3.965, Culture=neutral, processorArchitecture=x86"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\..\..\..\..\..\Program Files\Team MediaPortal\MediaPortal TV Server\TvLibrary.Interfaces.dll</HintPath> + </Reference> + </ItemGroup> + <ItemGroup> + <None Include="app.config" /> + </ItemGroup> +</Project> \ No newline at end of file Added: trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.csproj.user =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.csproj.user (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditor.csproj.user 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1 @@ +<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" /> \ No newline at end of file Added: trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditorInstaller.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditorInstaller.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/TVSAuditorInstaller.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,35 @@ +using System.ComponentModel; +using System.Configuration.Install; +using System.ServiceProcess; + +namespace TVSAuditor +{ + [RunInstaller(true)] + public class TVSAuditorInstaller : Installer + { + + public TVSAuditorInstaller() + { + ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller(); + ServiceInstaller serviceInstaller = new ServiceInstaller(); + + // Service Account Information + serviceProcessInstaller.Account = ServiceAccount.LocalSystem; + serviceProcessInstaller.Username = null; + serviceProcessInstaller.Password = null; + + // Service Information + serviceInstaller.DisplayName = TVSAuditor.SERVICE_NAME; + serviceInstaller.StartType = ServiceStartMode.Automatic; + serviceInstaller.Description = + "Audits the state of Mediaportal's TVService during runtime and schdules a restart if necessary"; + + // This must be identical to the MpshService.ServiceBase name + serviceInstaller.ServiceName = TVSAuditor.SERVICE_NAME; + + this.Installers.Add(serviceProcessInstaller); + this.Installers.Add(serviceInstaller); + } + } + +} Added: trunk/plugins/TVSAuditor/TVSAuditor/TVSinterface.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/TVSinterface.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/TVSinterface.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,289 @@ +using System; +using System.Collections.Generic; +using System.Collections; +using System.Text; +using System.Text.RegularExpressions; +using TvControl; +using TvLibrary.Channels; + +namespace TVSAuditor +{ + public class TVSinterface + { + + public static Regex NO_USERNAME_PATTERN = new Regex("NoUser"); + public static Regex EPG_USERNAME_PATTERN = new Regex("epg"); + public static Regex RECORDING_USERNAME_PATTERN = new Regex(@"scheduler\d+"); + + public enum CardStatus : int + { + TimeShifting = 1, + Recording = 2, + GrabbingEpg = 4 + } + + + private enum InternalCardStatus : int + { + TunerLocked = 1, + CardLocked = 2, + CardInUse = 3 + } + + + private User user; + private Dictionary<string, int> hideMap; + + + public TVSinterface() + { + user = new User(); + hideMap = new Dictionary<string, int>(); + RemoteControl.Clear(); + RemoteControl.HostName = "localhost"; + } + + + public void AddCardToHide(string name) + { + if (name == null) throw new ArgumentNullException("name can't be null"); + + int cardCount = CardCount(); + for (int i = 0; i < cardCount; ++i) + { + try + { + int cardId = RemoteControl.Instance.CardId(i); + string currentName = RemoteControl.Instance.CardName(cardId); + if (name == currentName) + hideMap.Add(name, i); + } + catch (Exception ex) + { + Logger.Warn("Tvsi: Problem getting card name - " + ex.Message); + } + } + } + + + public void RemoveCardToHide(string name) + { + if (name == null) throw new ArgumentNullException("name can't be null"); + hideMap.Remove(name); + } + + + public string[] GetHideList() + { + string[] nameArray = new string[hideMap.Count]; + hideMap.Keys.CopyTo(nameArray,0); + + return nameArray; + } + + + public static bool IsConnected() + { + return RemoteControl.IsConnected; + } + + + public void Disconnect() + { + user = null; + RemoteControl.Clear(); + } + + + public void ShowAllCardsStatus() + { + int cardCount = CardCount(); + for (int i = 0; i < cardCount; ++i) + { + if (hideMap.ContainsValue(i)) continue; + ShowCardStatus(i); + } + } + + + public int CardCount() + { + try + { + return RemoteControl.Instance.Cards; + } + catch (Exception ex) + { + Logger.Warn("Tvsi: Problem getting number of cards - " + ex.Message); + } + + return -1; + } + + + public void ShowCardStatus(int index) + { + try + { + int cardId = RemoteControl.Instance.CardId(index); + user = new User(); + user.CardId = cardId; + VirtualCard card = new VirtualCard(user, RemoteControl.HostName); + + string messageHeader = "Tvsi: card " + index; + StringBuilder sb = new StringBuilder(messageHeader); + sb.Append(" Type: " + card.Type); + sb.Append(", Name: " + card.Name); + sb.Append(", Device: " + card.Device); + sb.Append(", IsScanning: " + card.IsScanning); + sb.Append(", IsScrambled: " + card.IsScrambled); + sb.Append(", ChannelName: " + card.ChannelName); + sb.Append(", Channel: " + card.Channel); + sb.Append(", SignalQuality: " + card.SignalQuality); + sb.Append(", SignalLevel: " + card.SignalLevel); + sb.Append(", IsTunerLocked: " + card.IsTunerLocked); + Logger.Debug(sb.ToString()); + + } + catch (Exception ex) + { + Logger.Warn("Tvsi: Problem showing card " + index + " stati - " + ex.Message); + } + } + + + private bool IsCard(int index, InternalCardStatus internalStatus, string username) + { + if (username == null) throw new ArgumentNullException("username can't be null"); + + bool retVal = false; + try + { + int cardId = RemoteControl.Instance.CardId(index); + user = new User(); + user.CardId = cardId; + user.Name = username; + string cardname = RemoteControl.Instance.CardName(cardId); + VirtualCard card = new VirtualCard(user, RemoteControl.HostName); + + switch (internalStatus) + { + case InternalCardStatus.TunerLocked: + retVal = RemoteControl.Instance.TunerLocked(cardId); + break; + case InternalCardStatus.CardLocked: + retVal = card.IsLocked(out user); + break; + case InternalCardStatus.CardInUse: + retVal = RemoteControl.Instance.IsCardInUse(cardId, out user); + break; + } + Logger.Debug("Tvsi: Status for card " + cardname + ", user " + username + ", action " + internalStatus.ToString("G") + " is: " + retVal); + + } + catch (Exception ex) + { + Logger.Warn("Tvsi: Unable to determine card" + index + " usage - " + ex.Message); + } + + return retVal; + } + + + public bool IsAnyCardRecording() + { + try + { + return RemoteControl.Instance.IsAnyCardRecording(); + + } + catch (Exception ex) + { + Logger.Warn("Tvsi: Unable to determine any recording card - " + ex.Message); + } + + return false; + } + + + public bool AreAllCardsIdle() + { + int cardCount = CardCount(); + for (int i = 0; i < cardCount; ++i) + { + if (hideMap.ContainsValue(i)) continue; + + string username = CardUser(i, InternalCardStatus.CardInUse); + if (!NO_USERNAME_PATTERN.IsMatch(username)) return false; + } + return true; + } + + + private string CardUser(int index, InternalCardStatus internalStatus) + { + string username = NO_USERNAME_PATTERN.ToString(); + bool inUse = false; + try + { + int cardId = RemoteControl.Instance.CardId(index); + user = new User(); + user.CardId = cardId; + string cardname = RemoteControl.Instance.CardName(cardId); + VirtualCard card = new VirtualCard(user, RemoteControl.HostName); + + switch (internalStatus) + { + case InternalCardStatus.TunerLocked: + inUse = RemoteControl.Instance.TunerLocked(cardId); + break; + case InternalCardStatus.CardLocked: + inUse = card.IsLocked(out user); + break; + case InternalCardStatus.CardInUse: + inUse = RemoteControl.Instance.IsCardInUse(cardId, out user); + break; + } + if (user != null) username = user.Name; + Logger.Debug("Tvsi: User for " + cardname + " with status " + internalStatus.ToString("G") + " is: " + username); + } + catch (Exception ex) + { + Logger.Warn("Tvsi: Unable to determine user for card" + index + " - " + ex.Message); + } + + return username; + } + + + public bool AreAnyCards(CardStatus status) + { + int cardCount = CardCount(); + for (int i = 0; i < cardCount; ++i) + { + if (hideMap.ContainsValue(i)) continue; + + string username = CardUser(i, InternalCardStatus.CardInUse); + switch (status) + { + case CardStatus.TimeShifting: + if (!NO_USERNAME_PATTERN.IsMatch(username) && + !EPG_USERNAME_PATTERN.IsMatch(username) && + !RECORDING_USERNAME_PATTERN.IsMatch(username)) + return true; + break; + case CardStatus.Recording: + if (RECORDING_USERNAME_PATTERN.IsMatch(username)) + return true; + break; + case CardStatus.GrabbingEpg: + if (EPG_USERNAME_PATTERN.IsMatch(username)) + return true; + break; + } + } + return false; + } + + } +} Added: trunk/plugins/TVSAuditor/TVSAuditor/Tools.cs =================================================================== --- trunk/plugins/TVSAuditor/TVSAuditor/Tools.cs (rev 0) +++ trunk/plugins/TVSAuditor/TVSAuditor/Tools.cs 2008-12-10 18:57:07 UTC (rev 2407) @@ -0,0 +1,663 @@ +using System; +using System.ServiceProcess; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Net.NetworkInformation; +using Microsoft.Win32; + +namespace TVSAuditor +{ + public static class Tools + { + + private const int SE_PRIVILEGE_ENABLED = 0x00000002; + private const int TOKEN_QUERY = 0x00000008; + private const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; + private const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; + public const int EWX_LOGOFF = 0x00000000; + public const int EWX_SHUTDOWN = 0x00000001; + public const int EWX_REBOOT = 0x00000002; + public const int EWX_FORCE = 0x00000004; + public const int EWX_POWEROFF = 0x00000008; + public const int EWX_FORCEIFHUNG = 0x00000010; + public const string RK_RUN = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"; + + [Flags] + public enum EXECUTION_STATE : uint + { + ES_SYSTEM_REQUIRED = 0x00000001, + ES_DISPLAY_REQUIRED = 0x00000002, + ES_CONTINUOUS = 0x80000000, + ES_AWAYMODE_REQUIRED = 0x00000040 + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + private struct TokPriv1Luid + { + public int Count; + public long Luid; + public int Attr; + } + + [DllImport("kernel32.dll", ExactSpelling = true)] + private static extern IntPtr GetCurrentProcess(); + + [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] + private static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok); + + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool LookupPrivilegeValue(string host, string name, ref long pluid); + + [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] + private static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen); + + [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)] + private static extern bool ExitWindowsEx(int uFlags, int dwReason); + + [DllImport("Kernel32.DLL")] + private static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE state); + + [DllImport("user32")] + private static extern bool SetFocus(IntPtr hWnd); + + [DllImport("user32")] + private static extern bool SetForegroundWindow(IntPtr hWnd); + + [DllImport("user32")] + private static extern IntPtr GetForegroundWindow(); + + [DllImport("user32")] + private static extern bool BringWindowToTop(IntPtr hWnd); + + [DllImport("user32")] + private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); + + [DllImport("user32")] + private static extern bool AttachThreadInput(int nThreadId, int nThreadIdTo, bool bAttach); + + [DllImport("user32")] + private static extern int GetWindowThreadProcessId(IntPtr hWnd, int unused); + + [DllImport("user32")] + static extern bool IsWindowVisible(IntPtr hWnd); + + [DllImport("user32")] + static extern bool IsIconic(IntPtr hWnd); + + + public static bool ExitWindows(int flag) + { + bool ok = false; + + TokPriv1Luid tp; + tp.Count = 1; + tp.Luid = 0; + tp.Attr = SE_PRIVILEGE_ENABLED; + + try + { + IntPtr hproc = GetCurrentProcess(); + IntPtr htok = IntPtr.Zero; + ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok); + ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid); + ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero); + ok = ExitWindowsEx(flag, 0); + } + catch (Exception ex) + { + Logger.Warn("ExitWindows \"" + flag.ToString() + "\" - " + ex.Message); + } + return ok; + } + + + public static void KeepAlive() + { + SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_AWAYMODE_REQUIRED); + } + + + public static void TurnDisplayOn() + { + Logger.Info("Turn Display On - Trying to wake up the Display/TV"); + SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED); + } + + + public static void Xsleep(int timeout) + { + if (timeout <= 0) return; + + DateTime currentMoment = DateTime.Now; + TimeSpan duration = new TimeSpan(0, 0, 0, timeout, 0); + DateTime end = currentMoment.Add(duration); + + while (end >= currentMoment) + { + System.Threading.Thread.Sleep(500); + currentMoment = DateTime.Now; + } + } + + + public static bool Ping(string host) + { + if (host == null) throw new ArgumentException("host can't be null"); + + Ping ping = new Ping(); + byte[] buffer = new byte[32]; + int timeout = 1000; + PingOptions pingOptions = new PingOptions(); + PingReply reply = ping.Send(host, timeout, buffer, pingOptions); + + + bool pingSuccess = false; + if (reply.Status == IPStatus.Success) + { + Logger.Info("Ping - Host \"" + host + "\" successfully reached within " + reply.RoundtripTime + "ms"); + pingSuccess = true; + //Console.WriteLine("Antwort in {0}ms erhalten", reply.RoundtripTime); + } + else if (reply.Status == IPStatus.TimedOut) + { + Logger.Info("Ping - Connection to host \"" + host + "\" timed out"); + pingSuccess = false; + } + else + { + Logger.Info("Ping - Unable to reach host \"" + host + "\", Message: " + reply.Status.ToString()); + pingSuccess = false; + } + + return pingSuccess; + } + + + public static string[] GetNetworkInterfaceNames() + { + NetworkInterface[] nifs = NetworkInterface.GetAllNetworkInterfaces(); + string[] nifNames = new string[nifs.Length]; + for (int i = 0; i < nifs.Length; i++) + { + nifNames[i] = nifs[i].Name; + } + return nifNames; + } + + + public static string GetNetworkInterfaceLoopbackName() + { + return NetworkInterface.GetAllNetworkInterfaces()[NetworkInterface.LoopbackInterfaceIndex].Name; + } + + + public static NetworkInterface GetNetworkInterface(string nifName) + { + NetworkInterface[] nifs = NetworkInterface.GetAllNetworkInterfaces(); + + NetworkInterface nif = null; + for (int i = 0; i < nifs.Length; i++) + { + if (nifs[i].Name.Equals(nifName)) + { + nif = nifs[i]; + break; + } + } + return nif; + } + + + public static bool CheckNetworkConnection(string nifName, int timeout) + { + if (nifName == null) throw new ArgumentException("nifName can't be null"); + if (timeout <= 0) return true; + + NetworkInterface nif = GetNetworkInterface(nifName); + if (nif == null) return false; + + DateTime currentMoment = DateTime.Now; + TimeSpan duration = new TimeSpan(0, 0, 0, timeout, 0); + DateTime end = currentMoment.Add(duration); + + bool gotConnection = false; + + while (end >= currentMoment) + { + // It seems that we need to retrieve the nif every time we check for its status... otherwise status will not be up to date + nif = GetNetworkInterface(nifName); + if (nif.OperationalStatus == OperationalStatus.Up) + { + gotConnection = true; + break; + } + System.Threading.Thread.Sleep(500); + currentMoment = DateTime.Now; + } + + if (gotConnection) Logger.Info("Check Network Connection - Interface " + nifName + " is UP"); + else Logger.Info("Check Network Connection - Interface " + nifName + " was not ready within " + timeout + "s"); + + return gotConnection; + } + + + public static bool IsProcessRunning(string processName) + { + ... [truncated message content] |