Chaos Monkey - Part 2 - Programmatically Resetting IIS at Scheduled Intervals

June 15, 2015

In this previous post I gave an example of a DOS batch script that simulated an unstable network. This is an alternative to that in .NET, which uses the `System.ServiceProcess` namespace

Let’s start with the main function:



        private static async Task MainLoop()
        {
            while (true)
            {
                Console.WriteLine("Stopping IIS");
                StopService("World Wide Web Publishing Service", 10000);

                await Task.Delay(3000);

                Console.WriteLine("Starting IIS");
                StartService("World Wide Web Publishing Service", 10000);

                await Task.Delay(5000);
            }
        }

This defines the flow of the code: essentially, it’s just stop the IIS service, wait, start it again… and wait. The service name for IIS is “World Wide Web Publishing Service” - at least for Windows 7 & 8 it is. The start and stop functions look like this:



        public static void StartService(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);

            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        }

        public static void StopService(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);

            // Only stop if it's started
            if (service.Status != ServiceControllerStatus.Running) return;

            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
        }

Obviously these could be used to stop and start any service; although you must be running as admin to affect admin services (such as IIS).

To test this, check you have a “default.htm” in your wwwroot and then navigate to localhost in a web browser. Run this app in the background and press F5 on your browser until you get an error.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024