If you ever needed to debug a service that you built in C# and you couldn't attach to the process because it did not remain started (the very reason you are likely debugging it) then you might find this helpful.
- Open the program.cs of the service.
- Add a using System.Reflection statement.
- In the static void Main() add a string[] args. For example: static void Main(string[] args)
- See the sample below. Substitite MyService with the actual class name.
- In the Project Properties, go to the Debug tab and in the "Start Options" for the "Command line arguments:" enter in the value of DebugMode.
- Compile and start your service.
   /// <summary>
   /// The main entry point for the application.
   /// </summary>
        static void Main(string[] args)
  {
            ServiceBase[] ServicesToRun;
      #if (DEBUG)
                //The following code provides a means for running in "debugmode", which
                //allows convenient debugging of a service while it is running. 
                if (args.Length > 0)
                {
                    if (args[0].ToString() == "DebugMode")
                    {
                        //Create the instance and invoke the OnStart method
                        MyService svc = new MyService();
                        BindingFlags flags = BindingFlags.Instance  BindingFlags.NonPublic;
                        MethodInfo method = typeof(ServiceBase).GetMethod("OnStart", flags);
                        method.Invoke(svc, new object[] { args });
                        //Create a windows form to attach to.
                        System.Windows.Forms.Application.Run();
                    }
                    else
                    {
                        //Run as a normal service
                        ServicesToRun = new ServiceBase[] { new MyService() };
                        ServiceBase.Run(ServicesToRun);
                    }
                }
                else
                {
                    //Run as a normal service
                    ServicesToRun = new ServiceBase[] { new MyService() };
                    ServiceBase.Run(ServicesToRun);
                }
     #else
                //Run as a normal service
                ServicesToRun = new ServiceBase[] { new MyService() };
                ServiceBase.Run(ServicesToRun);
     #endif
      }
0 comments:
Post a Comment