1 // Licensed to the .NET Foundation under one or more agreements. 2 // The .NET Foundation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System.ComponentModel; 6 using System.Diagnostics; 7 using System; 8 using System.Collections; 9 using System.IO; 10 using System.Reflection; 11 using System.Threading; 12 using System.Text; 13 using System.Runtime.InteropServices; 14 using System.Globalization; 15 16 namespace System.ServiceProcess.Tests 17 { 18 public class TestService : ServiceBase 19 { TestService(string serviceName)20 public TestService(string serviceName) 21 { 22 this.ServiceName = serviceName; 23 24 // Enable all the events 25 this.CanPauseAndContinue = true; 26 this.CanStop = true; 27 this.CanShutdown = true; 28 29 // We cannot easily test these so disable the events 30 this.CanHandleSessionChangeEvent = false; 31 this.CanHandlePowerEvent = false; 32 } 33 GetLogPath(string serviceName)34 public static string GetLogPath(string serviceName) 35 { 36 return typeof(TestService).Assembly.Location + "." + serviceName + ".log"; 37 } 38 OnContinue()39 protected override void OnContinue() 40 { 41 WriteLog(nameof(OnContinue)); 42 base.OnContinue(); 43 } 44 OnCustomCommand(int command)45 protected override void OnCustomCommand(int command) 46 { 47 WriteLog(nameof(OnCustomCommand) + " command=" + command); 48 base.OnCustomCommand(command); 49 } 50 OnPause()51 protected override void OnPause() 52 { 53 WriteLog(nameof(OnPause)); 54 base.OnPause(); 55 } 56 OnSessionChange(SessionChangeDescription changeDescription)57 protected override void OnSessionChange(SessionChangeDescription changeDescription) 58 { 59 WriteLog(nameof(OnSessionChange) + " change=" + changeDescription.ToString()); 60 base.OnSessionChange(changeDescription); 61 } 62 OnPowerEvent(PowerBroadcastStatus powerStatus)63 protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) 64 { 65 WriteLog(nameof(OnPowerEvent) + " status=" + powerStatus.ToString()); 66 return base.OnPowerEvent(powerStatus); 67 } 68 OnShutdown()69 protected override void OnShutdown() 70 { 71 WriteLog(nameof(OnShutdown)); 72 base.OnShutdown(); 73 } 74 OnStart(string[] args)75 protected override void OnStart(string[] args) 76 { 77 File.Delete(GetLogPath(ServiceName)); 78 79 WriteLog(nameof(OnStart) + " args=" + string.Join(",", args)); 80 base.OnStart(args); 81 } 82 OnStop()83 protected override void OnStop() 84 { 85 WriteLog(nameof(OnStop)); 86 base.OnStop(); 87 } 88 WriteLog(string msg)89 private void WriteLog(string msg) 90 { 91 File.AppendAllText(GetLogPath(ServiceName), msg + Environment.NewLine); 92 } 93 } 94 } 95