Friday, January 20, 2012

Windows Services

PROBLEM: Recently I created a simple windows service with .net 4 to perform a check periodically on the status of our company's websites (are they up or not) and send an email notification if they aren't.

SOLUTION: While not particularly challenging there definitely some lessons learnt...
  • Firstly, people (http://weblogs.asp.net/jgalloway/archive/2005/10/24/428303.aspx) will point out that probably creating a console program which can be scheduled with the windows scheduler is the easier and better approach to this problem, but I mainly just wanted the experience in creating a windows service.
  • Some good web service examples:
  • Add a try/catch around your code in Main which logs any exceptions - useful to determine problems if your service won't start correctly etc.
  • To debug a windows service in Visual Studio you need to open the solution and then choose Debug > Attach to Process... > Tick both "Show processes from all users" and "Show processes in all sessions" and then click the exe and choose Attach. Set a breakpoint and away you go (remember to stop the timer while debugging if it is set to raise an event frequently otherwise you won't be able to step through the code easily).
  • When using windows logging, logs are identified by their first 8 characters - if you try and create two different logs, with the same first 8 characters, it will cause an exception.
  • The HttpWebRequest.GetResponse method returns various HttpStatusCode enums BUT quite often will raise an exception (e.g. if the website is down), so make sure you use a try/catch and it is from the exception (cast to WebException) that you can get the HttpStatusCode i.e. WebException.Response.StatusCode).
  • When you create a new log (not a new entry within a log), the windows Event Viewer doesn't do a great job at refreshing and showing it (even when you choose refresh) - just close the Event Viewer and open it again.
  • If you are testing a service and constantly installing and uninstalling it, you may get the system into a state where the install starts failing or complaining that the service has been marked for deletion but can't be removed. Try shutting down the Services window and see if that makes a difference, or try manually uninstalling it view Add/Remove Programs or via installutil /u but usually you'll just resolve it quicker by restarting your computer.
  • If you want to use an app.config with your windows service, you'll need to manually add a reference to the System.Configuration DLL so that you can use ConfigurationManager.AppSettings["BLAH"] (it's not included by default in a windows service project).

No comments:

Post a Comment