<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Nick Nguyen's Blog - code</title>
    <link>http://www.nansoftware.com/blog/</link>
    <description>Just Bing It...Just Kidding</description>
    <language>en-us</language>
    <copyright>NaN Software</copyright>
    <lastBuildDate>Mon, 04 Jan 2010 15:02:56 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>nick.nguyen@nansoftware.com</managingEditor>
    <webMaster>nick.nguyen@nansoftware.com</webMaster>
    <item>
      <trackback:ping>http://www.nansoftware.com/blog/Trackback.aspx?guid=67cbac88-0b16-466d-862d-02c6ce8296e5</trackback:ping>
      <pingback:server>http://www.nansoftware.com/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nansoftware.com/blog/PermaLink,guid,67cbac88-0b16-466d-862d-02c6ce8296e5.aspx</pingback:target>
      <dc:creator>Nick Nguyen</dc:creator>
      <wfw:comment>http://www.nansoftware.com/blog/CommentView,guid,67cbac88-0b16-466d-862d-02c6ce8296e5.aspx</wfw:comment>
      <wfw:commentRss>http://www.nansoftware.com/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=67cbac88-0b16-466d-862d-02c6ce8296e5</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
 
</p>
        <p>
Historically, debugging windows services can be a minor pain. One either has to either
emulate the service controller behavior using a separate console application project
or install the service, start it, set a break point and attach the debugger.
</p>
        <p>
          <strong>
          </strong> 
</p>
        <p>
          <strong>
            <font color="#0080ff" size="3">Mimicking a console application</font>
          </strong>
        </p>
        <p>
          <strong>
          </strong> 
</p>
        <p>
          <strong>Listing 1: ServiceBase extension method</strong>
        </p>
        <pre class="brush: csharp;">        /// &lt;summary&gt;
        /// Runs the service.
        /// &lt;/summary&gt;
        /// &lt;param name="serviceBase"&gt;The service base.&lt;/param&gt;
        /// &lt;param name="args"&gt;The args.&lt;/param&gt;
        public static void RunService(this ServiceBase serviceBase, string[] args)
        {
            if (Debugger.IsAttached)
            {
                using (var autoResetEvent = new AutoResetEvent(false))
                {
                    const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase |
                                               BindingFlags.Instance;

                    var methodInfo = serviceBase.GetType().GetMethod("OnStart", flags);
                    if (methodInfo != null)
                        methodInfo.Invoke(serviceBase, new object[] { args });

                    autoResetEvent.WaitOne();
                }
            }
            else
            {
                ServiceBase.Run(new[] { serviceBase });
            }
        }</pre>
        <p>
Pretty simple stuff…check that the debugger is attached…use reflection to invoke the
protected ‘OnStart’ method and block the main thread infinitely with an ‘AutoResetEvent';
otherwise, run the service as normal. Here’s the usage: 
</p>
        <pre class="brush: csharp;">    internal static class Program
    {
        /// &lt;summary&gt;
        /// The main entry point for the application.
        /// &lt;/summary&gt;
        private static void Main()
        {
//            ServiceBase[] ServicesToRun;
//            ServicesToRun = new ServiceBase[] 
//            { 
//                new Service1() 
//            };
//            ServiceBase.Run(ServicesToRun);

            new Service1().RunService(null);
        }
    }</pre>
        <p>
  
</p>
        <p>
          <strong>Listing 3: Key service controller event handlers</strong>
        </p>
        <pre class="brush: csharp;">private void OnServiceTimerElapsed(object sender, ElapsedEventArgs e)
        {
            _serviceTimer.Stop();

            var dateTime = DateTime.Now;
            Debug.WriteLine(string.Format("Timer elapsed at {0} {1}...", dateTime.ToShortDateString(), dateTime.ToLongTimeString()));

            _serviceTimer.Start();
        }

        protected override void OnStart(string[] args)
        {
            _serviceTimer.AutoReset = true;
            _serviceTimer.Enabled = true;
            _serviceTimer.Start();

            Debug.WriteLine("Service started...");
        }</pre>
        <p>
 
</p>
        <p>
To see this in action hit F5 or run the service project instance and you can see that
the service is running based on the timer elapsed event in Listing 3. <a href="http://www.nansoftware.com/blog/content/binary/WindowsLiveWriter/DebuggingaWindowsServiceLikeaConsoleApp_A496/image_6.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="service debug tracing" border="0" alt="service debug tracing" align="left" src="http://www.nansoftware.com/blog/content/binary/WindowsLiveWriter/DebuggingaWindowsServiceLikeaConsoleApp_A496/image_thumb_2.png" width="484" height="375" /></a></p>
        <img width="0" height="0" src="http://www.nansoftware.com/blog/aggbug.ashx?id=67cbac88-0b16-466d-862d-02c6ce8296e5" />
      </body>
      <title>Debug Windows Services Like a Console App</title>
      <guid isPermaLink="false">http://www.nansoftware.com/blog/PermaLink,guid,67cbac88-0b16-466d-862d-02c6ce8296e5.aspx</guid>
      <link>http://www.nansoftware.com/blog/Debug-Windows-Services-Like-A-Console-App.aspx</link>
      <pubDate>Mon, 04 Jan 2010 15:02:56 GMT</pubDate>
      <description>&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Historically, debugging windows services can be a minor pain. One either has to either
emulate the service controller behavior using a separate console application project
or install the service, start it, set a break point and attach the debugger.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;&lt;/strong&gt;&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;&lt;font color="#0080ff" size="3"&gt;Mimicking a console application&lt;/font&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;&lt;/strong&gt;&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Listing 1: ServiceBase extension method&lt;/strong&gt;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;        /// &amp;lt;summary&amp;gt;
        /// Runs the service.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;serviceBase&amp;quot;&amp;gt;The service base.&amp;lt;/param&amp;gt;
        /// &amp;lt;param name=&amp;quot;args&amp;quot;&amp;gt;The args.&amp;lt;/param&amp;gt;
        public static void RunService(this ServiceBase serviceBase, string[] args)
        {
            if (Debugger.IsAttached)
            {
                using (var autoResetEvent = new AutoResetEvent(false))
                {
                    const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase |
                                               BindingFlags.Instance;

                    var methodInfo = serviceBase.GetType().GetMethod(&amp;quot;OnStart&amp;quot;, flags);
                    if (methodInfo != null)
                        methodInfo.Invoke(serviceBase, new object[] { args });

                    autoResetEvent.WaitOne();
                }
            }
            else
            {
                ServiceBase.Run(new[] { serviceBase });
            }
        }&lt;/pre&gt;
&lt;p&gt;
Pretty simple stuff…check that the debugger is attached…use reflection to invoke the
protected ‘OnStart’ method and block the main thread infinitely with an ‘AutoResetEvent';
otherwise, run the service as normal. Here’s the usage: 
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;    internal static class Program
    {
        /// &amp;lt;summary&amp;gt;
        /// The main entry point for the application.
        /// &amp;lt;/summary&amp;gt;
        private static void Main()
        {
//            ServiceBase[] ServicesToRun;
//            ServicesToRun = new ServiceBase[] 
//            { 
//                new Service1() 
//            };
//            ServiceBase.Run(ServicesToRun);

            new Service1().RunService(null);
        }
    }&lt;/pre&gt;
&lt;p&gt;
&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Listing 3: Key service controller event handlers&lt;/strong&gt;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;private void OnServiceTimerElapsed(object sender, ElapsedEventArgs e)
        {
            _serviceTimer.Stop();

            var dateTime = DateTime.Now;
            Debug.WriteLine(string.Format(&amp;quot;Timer elapsed at {0} {1}...&amp;quot;, dateTime.ToShortDateString(), dateTime.ToLongTimeString()));

            _serviceTimer.Start();
        }

        protected override void OnStart(string[] args)
        {
            _serviceTimer.AutoReset = true;
            _serviceTimer.Enabled = true;
            _serviceTimer.Start();

            Debug.WriteLine(&amp;quot;Service started...&amp;quot;);
        }&lt;/pre&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
To see this in action hit F5 or run the service project instance and you can see that
the service is running based on the timer elapsed event in Listing 3. &lt;a href="http://www.nansoftware.com/blog/content/binary/WindowsLiveWriter/DebuggingaWindowsServiceLikeaConsoleApp_A496/image_6.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="service debug tracing" border="0" alt="service debug tracing" align="left" src="http://www.nansoftware.com/blog/content/binary/WindowsLiveWriter/DebuggingaWindowsServiceLikeaConsoleApp_A496/image_thumb_2.png" width="484" height="375" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nansoftware.com/blog/aggbug.ashx?id=67cbac88-0b16-466d-862d-02c6ce8296e5" /&gt;</description>
      <comments>http://www.nansoftware.com/blog/CommentView,guid,67cbac88-0b16-466d-862d-02c6ce8296e5.aspx</comments>
      <category>code</category>
    </item>
  </channel>
</rss>