Setting Up Debug Mode for a Windows Service Project

January 14, 2011 by Ben Galluzzo    .NET, Debugging, Windows Service, C# |    Comments (0)

If you’ve tried to run a Windows Service project in debug mode, you’ve probably seen the message shown below.  To debug our code by default, we would have to install the service and then attach the debugger to a Process (Ctrl+Alt+P).  Obviously, this can get tedious.  There is a more appropriate and efficient way to debug the Windows Service project in which we’re developing.

DebugModeError_489x199

 

 

 

 

 

 

Let’s start out by constructing a simple Windows Service…  Add a Windows Service class item to the project; in our case, the class is named AgentService

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

using System.Timers;

namespace ProvingGrounds.Agent
{
    partial class AgentService : ServiceBase
    {
        private Timer timer = null;

        public AgentService()
        {
            InitializeComponent();

            timer = new Timer(6000);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Enabled = true;
            timer.AutoReset = true;
        }

        protected override void OnStart(string[] args)
        {
            Start();
        }

        protected override void OnStop()
        {
            Stop();
        }

        public void Start()
        {
            timer.Start();
        }

        public void Stop()
        {
            timer.Stop();
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //TODO:Do Something
        }
    }
}

 

Next, update Main() found in Program.cs to execute AgentService.

        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new AgentService() 
			};
            ServiceBase.Run(ServicesToRun);
        }

We should now have our Windows Service constructed. Feel free to compile it and then go ahead try running it in debug mode. You should be receiving our "Start Failure" error message.

Next, let's get this thing running in debug mode from Visual Studio. We can do this by adding the #if DEBUG preprocessor directive to our Main() function. We simply wrap the existing call to our AgentService with the conditional preprocessor directives.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

using System.Threading;

namespace ProvingGrounds.Agent
{
    static class Program
    {
        static void Main()
        {
            #if DEBUG
            
            AgentService agentService = new AgentService();
            agentService.Start();

            Thread.Sleep(Timeout.Infinite);

            agentService.Stop();

            #else

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new AgentService() 
			};
            ServiceBase.Run(ServicesToRun);
            
            #endif
        }
    }
}

 

That's all there is to.  Go ahead and hit F5 from Visual Studio and your Windows Project should be running in Debug Mode.

Rounding-Out A Class Library – Extension Methods

November 1, 2010 by Ben Galluzzo    .NET |    Comments (0)

One potential improvement to a custom class library could lie in the use of extension methods.  In short, extension methods are a quick and simple way to extend a type without modifying or recompiling the actual type which is being extended.  Utilizing an extension method is as simple as calling the ToString() method on a type.  At first it may seem difficult to come up with uses for extension methods.  However, working through a project, potential use for an extension method may present itself and also could very well reside in commonly created utility classes.  Operations often performed against a type in the same context is a perfect use for converting a utility function into an extension method.

Defining an extension method might seem a little odd at first to the uninitiated.  Take a bit of time to think about what’s happening under the hood to provide this added functionality, automatically, to an existing type. The first parameter of an extension method takes on the this modifier to accept the type on which the method operates.  Utilizing the extension methods requires adding a using directive of the namespace for which the extension method resides. 

Below are a couple very simple examples of extension methods and their use.  These two extension methods provide a boolean value for a check of a null value or an empty value against an Array type and also a for String type.

using System;

namespace ProvingGrounds.Lib
{
    public static class LibraryExtensions
    {
        public static bool IsNullOrEmpty(this Array _value)
        {
            return (_value == null || _value.Length == 0);
        }

        public static bool IsNullOrEmpty(this string _value)
        {
            return (_value == null || _value.Length == 0);
        }

    }
}
Utilizing these new extension methods can only be done if applying the proper using directive to the calling class; in this case, using ProvingGrounds.Lib.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ProvingGrounds.Lib;

namespace ProvingGrounds.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            string emptyTest = null;
            if (emptyTest.IsNullOrEmpty())
                System.Console.WriteLine("emptyTest is null or empty");
        }
    }
}

Omitting the proper using directive will result in the extension method not being available for use.

ExtensionMethod_271x101

 

 

 

 

Care should be taken when enabling more global usage. For instance, if the class housing the extension methods are added to the System namespace, their use can be made more readily available.

using System;

namespace System
{
    public static class SystemExtensions
    {
        public static bool IsNullOrEmpty(this Array _value)
        {
            return (_value == null || _value.Length == 0);
        }

        public static bool IsNullOrEmpty(this string _value)
        {
            return (_value == null || _value.Length == 0);
        }

    }
}

So there it is. A couple of very simply extension methods in practice. Have fun with them. Use them to simplify often used operations on types; operations whose functionality may already reside in common util classes.


SQL Saturday - 506 - Baltimore BI Edition

Month List