James Ray Anderson

James Ray Anderson
James Ray Anderson
0 comments

Debugging A Service In C#

1:49 PM
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.


  1. Open the program.cs of the service.
  2. Add a using System.Reflection statement.
  3. In the static void Main() add a string[] args. For example: static void Main(string[] args)
  4. See the sample below. Substitite MyService with the actual class name.
  5. 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.
  6. 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:

 
Toggle Footer
Top