Example #1
0
 /// <summary>
 /// Initializes a new instance of ServiceLog.
 /// </summary>
 /// <param name="logMode">The LogMode defining the level of detail of the log.</param>
 /// <param name="maxFileSize">The max file size in byte.</param>
 private WsapmLog(LogMode logMode, uint maxFileSize)
 {
     this.settingsFolder = WsapmTools.GetCommonApplicationDataFolder();
     this.logFile        = WsapmTools.GetCommonApplicationLogFile();
     this.LogMode        = logMode;
     this.MaxLogFileSize = maxFileSize;
 }
Example #2
0
 /// <summary>
 /// Initializes a new instance of SettingsManager.
 /// </summary>
 public SettingsManager()
 {
     this.settingsFolder = WsapmTools.GetCommonApplicationDataFolder();
     this.settingsFile   = WsapmTools.GetCommonApplicationDataFile();
     this.serializer     = new XmlSerializer(typeof(WsapmSettings));
     InitFileSystemWatcher();
 }
Example #3
0
 public TemporaryUptimeManager()
 {
     this.settingsFolder      = WsapmTools.GetCommonApplicationDataFolder();
     this.temporaryUptimeFile = WsapmTools.GetTemporaryUptimeFile();
     this.serializer          = new XmlSerializer(typeof(TemporaryUptime));
     InitFileSystemWatcher();
 }
Example #4
0
        /// <summary>
        /// Start the resume automatic timer.
        /// </summary>
        /// <remarks>This has to be done in order to prevent system entering standby after a few minutes after the ResumeAutomatic event when no ResumeSuspend event follows,
        /// i.e. system is woken, but user is not present.</remarks>
        private void StartResumeAutomaticTimer()
        {
            // Only start resume automatic timer if system was really woken by WSAPM timer.
            // Otherwise the system is already running when the wake timer elapses.
            if (!SystemWokenByWakeTimer())
            {
                return;
            }

            StopResumeAutomaticTimer();
            this.resumeAutomaticTimer = new Timer();

            // The resumeAutomaticTimer's interval has to be shorter than the Wsapm's timer!
            var interval = TimeSpan.FromMinutes(WsapmTools.GetCurrentWindowsIdleTimeoutAcMinutes()).TotalMilliseconds;

            if (this.monitoringTimer != null)
            {
                var delay = TimeSpan.FromSeconds(10).TotalMilliseconds;
                interval = this.monitoringTimer.Interval - delay;
            }

            SuspendStandby(new CheckSuspendResult(true, string.Format(Resources.Wsapm_Core.WsapmManager_TimerStartedAfterResumeAutomatic, TimeSpan.FromMilliseconds(interval).TotalMinutes.ToString("00"))));
            this.resumeAutomaticTimer.Interval  = interval;
            this.resumeAutomaticTimer.Elapsed  += resumeAutomaticTimer_Elapsed;
            this.resumeAutomaticTimer.AutoReset = false;
            this.resumeAutomaticTimer.Start();
        }
Example #5
0
        /// <summary>
        /// Validates the given settings.
        /// </summary>
        /// <param name="settings"></param>
        private void ValidateSettings(WsapmSettings settings)
        {
            // Validate settings and print warning when needed.
            if (!WsapmTools.ValidateCheckInterval(settings))
            {
                var winIdleTimeoutAcMinutes = WsapmTools.GetCurrentWindowsIdleTimeoutAcMinutes();
                WsapmLog.Log.WriteWarning(String.Format(Resources.Wsapm_Core.WsapmManager_ValidationErrorCheckInterval, winIdleTimeoutAcMinutes, settings.MonitoringTimerInterval), LogMode.Verbose);
            }

            // Validate if wake timers are allowed.
            if (!WsapmTools.ValidateWakeTimers(settings))
            {
                WsapmLog.Log.WriteWarning(Resources.Wsapm_Core.WsapmManager_ValidationErrorWakeTimers, LogMode.Verbose);
            }
        }
Example #6
0
        /// <summary>
        /// Deletes the settings from the computer.
        /// </summary>
        public void DeleteSettings()
        {
            if (!WsapmTools.SettingsAvailable())
            {
                return;
            }

            try
            {
                Directory.Delete(WsapmTools.GetCommonApplicationDataFolder(), true);
            }
            catch (Exception ex)
            {
                throw new WsapmException(Resources.Wsapm_Core.SettingsManager_DeleteSettingsError, ex);
            }

            this.LoadSettings();
        }
Example #7
0
 /// <summary>
 /// Starts the monitoring timer.
 /// </summary>
 private void StartMonitoringTimer()
 {
     try
     {
         StopMonitoringTimer();
         this.monitoringTimer           = new Timer();
         this.monitoringTimer.AutoReset = false; // The timer gets re-started manually.
         double monitoringTimerIntervalDefault = WsapmTools.GetTimerIntervalInMilliseconds(1);
         double monitoringIntervalSettings     = WsapmTools.GetTimerIntervalInMilliseconds(this.currentSettings.MonitoringTimerInterval);
         this.monitoringTimer.Interval = monitoringIntervalSettings <= 0 ? monitoringTimerIntervalDefault : monitoringIntervalSettings;
         this.monitoringTimer.Elapsed += monitoringTimer_Elapsed;
         this.monitoringTimer.Start();
         WsapmLog.Log.WriteLine(Resources.Wsapm_Core.WsapmManager_StartMonitoringTimer, LogMode.Verbose);
     }
     catch (Exception ex)
     {
         WriteErrorLog(ex);
     }
 }
Example #8
0
        /// <summary>
        /// Loads the default settings.
        /// </summary>
        public WsapmSettings GetDefaultSettings()
        {
            var newSettings = new WsapmSettings();

            newSettings.MonitoringTimerInterval    = WsapmTools.GetOptimalCheckIntervalInMinutes();
            newSettings.MaxLogFileSize             = WsapmConvert.ConvertKBToByte(100);
            newSettings.NetworkInterfacesToMonitor = new System.Collections.Generic.List <NetworkInterfaceToMonitor>();
            newSettings.HddsToMonitor = new System.Collections.Generic.List <HddToMonitor>();
            newSettings.EnableCheckNetworkResourceAccess = false;
            newSettings.CheckNetworkResourcesType        = NetworkShareAccessType.Files;
            newSettings.CpuLoad                    = 0.0f;
            newSettings.MemoryLoad                 = 0.0f;
            newSettings.UptimeSchedulers           = new System.Collections.Generic.List <UptimeScheduler>();
            newSettings.WakeSchedulers             = new System.Collections.Generic.List <WakeScheduler>();
            newSettings.LogMode                    = LogMode.Normal;
            newSettings.EnableRemoteShutdown       = false;
            newSettings.RemoteShutdownPort         = 9;
            newSettings.RemoteShutdownPasswordHash = string.Empty;
            return(newSettings);
        }
Example #9
0
        /// <summary>
        /// Loads the temporary uptime.
        /// </summary>
        /// <returns></returns>
        public TemporaryUptime LoadTemporaryUptime()
        {
            try
            {
                if (!Directory.Exists(WsapmTools.GetCommonApplicationDataFolder()) || !File.Exists(this.temporaryUptimeFile))
                {
                    return(null);
                }

                using (FileStream fs = new FileStream(this.temporaryUptimeFile, FileMode.Open, FileAccess.Read))
                {
                    TemporaryUptime temporaryUptime = this.serializer.Deserialize(fs) as TemporaryUptime;
                    return(temporaryUptime);
                }
            }
            catch (IOException ex)
            {
                throw new WsapmException(Resources.Wsapm_Core.TemporaryUptimeManager_LoadTemporaryUptimeError, ex);
            }
        }
Example #10
0
        /// <summary>
        /// Loads settings from settings file.
        /// </summary>
        /// <returns>The loaded settings.</returns>
        public WsapmSettings LoadSettings()
        {
            try
            {
                if (!Directory.Exists(WsapmTools.GetCommonApplicationDataFolder()) || !File.Exists(this.settingsFile))
                {
                    var newSetings = GetDefaultSettings();
                    return(newSetings);
                }

                using (FileStream fs = new FileStream(this.settingsFile, FileMode.Open, FileAccess.Read))
                {
                    WsapmSettings settings = this.serializer.Deserialize(fs) as WsapmSettings;
                    return(settings);
                }
            }
            catch (IOException ex)
            {
                throw new WsapmException(Resources.Wsapm_Core.SettingsManager_LoadSettingsError, ex);
            }
        }
Example #11
0
        private void WriteErrorLog(Exception ex)
        {
            var sb = new StringBuilder();

            sb.Append(Resources.Wsapm_Core.WsapmManager_ErrorLogFileCaption);
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            sb.Append(ex.Message);
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            sb.Append(Resources.Wsapm_Core.WsapmManager_ErrorLogStacktraceCaption);
            sb.Append(Environment.NewLine);
            sb.Append(ex.StackTrace);
            var errorString = sb.ToString();
            var fileName    = WsapmTools.GetNewErrorLogFileName();

            try
            {
                File.WriteAllText(fileName, errorString);
            }
            catch (Exception)
            {
            }
        }
Example #12
0
        /// <summary>
        /// Determines if the state of the check interval is valid with the current Windows power options.
        /// </summary>
        /// <param name="settings">The WsampSettings to validate.</param>
        /// <returns>True if the state of the check interval is valid with the current Windows power options, otherwise false.</returns>
        public static bool ValidateCheckInterval(WsapmSettings settings)
        {
            var winIdleTimeoutAcMinutes = WsapmTools.GetCurrentWindowsIdleTimeoutAcMinutes();

            return(!(settings.MonitoringTimerInterval >= winIdleTimeoutAcMinutes));
        }
Example #13
0
        /// <summary>
        /// Determines if the state of WakeScheduler and Windows power options are valid.
        /// </summary>
        /// <param name="settings">The WsampSettings to validate.</param>
        /// <returns>True if the state of the setting's WakeScheduler is valid with the current Windows power options, otherwise false.</returns>
        public static bool ValidateWakeTimers(WsapmSettings settings)
        {
            bool atLeastOneWakeSchedulerActive = false;

            if (settings.WakeSchedulers != null)
            {
                foreach (var wakeScheduler in settings.WakeSchedulers)
                {
                    if (wakeScheduler.EnableWakeScheduler)
                    {
                        atLeastOneWakeSchedulerActive = true;
                        break;
                    }
                }
            }

            return(!(settings.WakeSchedulers != null && atLeastOneWakeSchedulerActive && !WsapmTools.GetWakeTimersAllowed()));
        }
Example #14
0
 /// <summary>
 /// Returns true if setting are saved on the computer.
 /// </summary>
 /// <returns>True if settings are available, otherwise false.</returns>
 public static bool SettingsAvailable()
 {
     return(Directory.Exists(WsapmTools.GetCommonApplicationDataFolder()));
 }
Example #15
0
        /// <summary>
        /// Writes a line to the log file.
        /// This action is not dependent of the LogMode.
        /// </summary>
        /// <param name="msg">The message to write in the log.</param>
        /// <remarks>This function is thread save.</remarks>
        private void WriteLine(string msg)
        {
            // First fire the event to inform clients.
            FireNewLogEntryEvent(msg);

            // Wite the log message to the log file.
            FileStream   fStream = null;
            StreamWriter writer  = null;

            try
            {
                lock (lockObj)
                {
                    if (!Directory.Exists(this.settingsFolder))
                    {
                        Directory.CreateDirectory(this.settingsFolder);
                    }

                    if (!File.Exists(this.logFile))
                    {
                        fStream = new FileStream(this.logFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                    }
                    else
                    {
                        if (this.MaxLogFileSize != 0)
                        {
                            FileInfo fi = new FileInfo(this.logFile);
                            var      currentFileSize = fi.Length;

                            if (currentFileSize > this.MaxLogFileSize)
                            {
                                File.Delete(this.logFile);
                                fStream = new FileStream(this.logFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                            }
                        }
                    }

                    writer = new StreamWriter(this.logFile, true);
                    writer.WriteLine(WsapmTools.GetTimeString() + ": " + msg);
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (writer != null)
                {
                    writer.Flush();
                    writer.Close();
                    writer = null;
                }

                if (fStream != null)
                {
                    fStream.Flush();
                    fStream.Close();
                    fStream = null;
                }
            }
        }
Example #16
0
        /// <summary>
        /// Checks if the HDD load is over the HDD load value in the settings.
        /// </summary>
        /// <param name="settings"></param>
        /// <returns>True, if the current HDD load is greater than the HDD load value in the settings, otherwise false.</returns>
        public CheckSuspendResult CheckHddLoad(WsapmSettings settings)
        {
            if (settings == null || !settings.EnableHddsToMonitor)
            {
                return(new CheckSuspendResult(false, String.Empty));
            }

            var availableHdds = WsapmTools.GetAvailableLogicalVolumeNames();

            foreach (var hddToMonitor in settings.HddsToMonitor)
            {
                if (hddToMonitor.Drive != WsapmConstants.AllHddsName && !availableHdds.Contains(hddToMonitor.Drive))
                {
                    // HDD not available -> don't check, just write entry in log.
                    WsapmLog.Log.WriteLine(string.Format(Wsapm.Core.Resources.Wsapm_Core.HddLoadCheck_HddNotAvailable, hddToMonitor.Drive), LogMode.Normal);
                    continue;
                }

                bool   checkAllHdds = false;
                string hddName      = hddToMonitor.Drive;

                if (hddToMonitor.Drive == WsapmConstants.AllHddsName)
                {
                    checkAllHdds = true;
                    hddName      = WsapmTools.GetCommonDiaplayNameAllDrives();
                }

                // Check load.
                try
                {
                    if (hddToMonitor.EnableCheckHddLoad && hddToMonitor.HddLoad != 0.0f)
                    {
                        var averageHddLoad = 0.0f;

                        if (checkAllHdds)
                        {
                            averageHddLoad = this.hddLoad.GetAverageHddLoadAllVolumesInBytesPerSecond(); // Byte/s
                        }
                        else
                        {
                            averageHddLoad = this.hddLoad.GetAverageHddLoadInBytesPerSecond(hddToMonitor.Drive); // Byte/s
                        }
                        var result = averageHddLoad > WsapmConvert.ConvertKBToByte(hddToMonitor.HddLoad);        // Settings are saved as KBit/s.

                        if (result)
                        {
                            return(new CheckSuspendResult(true, String.Format(Resources.Wsapm_Core.HddLoadCheck_HddLoadReason, hddName, hddToMonitor.HddLoad, WsapmConvert.ConvertByteToKB(averageHddLoad).ToString("0"))));
                        }
                        else
                        {
                            return(new CheckSuspendResult(false, String.Empty));
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Might happen if the performance counters get broken.
                    WsapmLog.Log.WriteError(ex);
                }
            }

            return(new CheckSuspendResult(false, String.Empty));
        }
Example #17
0
        /// <summary>
        /// Checks if the network load is over the network load value in the settings.
        /// </summary>
        /// <param name="settings"></param>
        /// <returns>True, if the current network load is greater than the network load value in the settings, otherwise false.</returns>
        public CheckSuspendResult CheckNetworkLoad(WsapmSettings settings)
        {
            if (settings == null || !settings.EnableNetworkInterfacesToMonitor)
            {
                return(new CheckSuspendResult(false, String.Empty));
            }

            var availableNics = WsapmTools.GetAvailableNetworkInterfaces();

            foreach (var networkInterfaceToMonitor in settings.NetworkInterfacesToMonitor)
            {
                if (networkInterfaceToMonitor.NetworkInterface != WsapmConstants.AllNetworkInterfacesName && !availableNics.Contains(networkInterfaceToMonitor.NetworkInterface))
                {
                    // NIC not available -> don't check, just write entry in log.
                    WsapmLog.Log.WriteLine(string.Format(Wsapm.Core.Resources.Wsapm_Core.NetworkLoadCheck_NicNotAvailable, networkInterfaceToMonitor.NetworkInterface), LogMode.Normal);
                    continue;
                }

                bool   checkAllNics = false;
                string nicName      = networkInterfaceToMonitor.NetworkInterface;

                if (networkInterfaceToMonitor.NetworkInterface == WsapmConstants.AllNetworkInterfacesName)
                {
                    checkAllNics = true;
                    nicName      = WsapmTools.GetCommonDiaplayNameAllNetworkInterfaces();
                }

                // Check total network load.
                try
                {
                    if (networkInterfaceToMonitor.EnableCheckNetworkLoadTotal && networkInterfaceToMonitor.NetworkLoadTotal != 0.0f)
                    {
                        var averageNetworkLoad = 0.0f;

                        if (checkAllNics)
                        {
                            averageNetworkLoad = this.networkLoad.GetAverageNetworkLoadTotalAllNicsInBytesPerSecond(); // Byte/s
                        }
                        else
                        {
                            averageNetworkLoad = this.networkLoad.GeAverageNetworkLoadTotalInBytesPerSecond(networkInterfaceToMonitor.NetworkInterface); // Byte/s
                        }
                        var result = averageNetworkLoad > WsapmConvert.ConvertKBitToByte(networkInterfaceToMonitor.NetworkLoadTotal);                    // Settings are saved as KBit/s.

                        if (result)
                        {
                            return(new CheckSuspendResult(true, String.Format(Resources.Wsapm_Core.NetworkLoadCheck_CombinedNetworkLoadReason, nicName, networkInterfaceToMonitor.NetworkLoadTotal, WsapmConvert.ConvertByteToKBit(averageNetworkLoad).ToString("0"))));
                        }
                        else
                        {
                            return(new CheckSuspendResult(false, String.Empty));
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Might happen if the performance counters get broken.
                    WsapmLog.Log.WriteError(ex);
                }

                // Check download network load.
                try
                {
                    if (networkInterfaceToMonitor.EnableCheckNetworkLoadDownload && networkInterfaceToMonitor.NetworkLoadDownload != 0.0f)
                    {
                        var averageNetworkReceived = 0.0f;

                        if (checkAllNics)
                        {
                            averageNetworkReceived = this.networkLoad.GetAverageNetworkLoadDownloaAllNicsInBytesPerSecond(); //Byte/s
                        }
                        else
                        {
                            averageNetworkReceived = this.networkLoad.GetAverageNetworkLoadDownloadInBytesPerSecond(networkInterfaceToMonitor.NetworkInterface); //Byte/s
                        }
                        var result = averageNetworkReceived > WsapmConvert.ConvertKBitToByte(networkInterfaceToMonitor.NetworkLoadDownload);                     // Settings are saved as KBit/s.

                        if (result)
                        {
                            return(new CheckSuspendResult(true, String.Format(Resources.Wsapm_Core.NetworkLoadCheck_DownloadNetworkLoadReason, nicName, networkInterfaceToMonitor.NetworkLoadDownload, WsapmConvert.ConvertByteToKBit(averageNetworkReceived).ToString("0"))));
                        }
                        else
                        {
                            return(new CheckSuspendResult(false, String.Empty));
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Might happen if the performance counters get broken.
                    WsapmLog.Log.WriteError(ex);
                }

                // Check upload network load.
                try
                {
                    if (networkInterfaceToMonitor.EnableCheckNetworkLoadUpload && networkInterfaceToMonitor.NetworkLoadUpload != 0.0f)
                    {
                        var averageNetworkSent = 0.0f;

                        if (checkAllNics)
                        {
                            averageNetworkSent = this.networkLoad.GetAverageNetworkLoadUploadAllNicsInBytesPerSecond(); // Byte/s
                        }
                        else
                        {
                            averageNetworkSent = this.networkLoad.GetAverageNetworkLoadUploadInBytesPerSecond(networkInterfaceToMonitor.NetworkInterface); // Byte/s
                        }
                        var result = averageNetworkSent > WsapmConvert.ConvertKBitToByte(networkInterfaceToMonitor.NetworkLoadUpload);                     // Settings are saved as KBit/s.

                        if (result)
                        {
                            return(new CheckSuspendResult(true, String.Format(Resources.Wsapm_Core.NetworkLoadCheck_UploadNetworkLoadReason, nicName, networkInterfaceToMonitor.NetworkLoadUpload, WsapmConvert.ConvertByteToKBit(averageNetworkSent).ToString("0"))));
                        }
                        else
                        {
                            return(new CheckSuspendResult(false, String.Empty));
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Might happen if the performance counters get broken.
                    WsapmLog.Log.WriteError(ex);
                }
            }

            return(new CheckSuspendResult(false, String.Empty));
        }