title: C# based Windows Service - Tries to do JIT Debugging in production
body: <p>I am getting this error in my event logs for a service I put into production:</p>
  
  <blockquote>
    <p>An unhandled win32 exception occurred
    in RivWorks.FeedHandler.exe [5496].
    Just-In-Time debugging this exception
    failed with the following error:
    Debugger could not be started because
    no user is logged on.</p>
  </blockquote>
  
  <p>I have it installed and running under a Win NT global account.  I have no idea why it is trying to drop into debugging mode.  It was built under the Release model.  Running on the 4.0 Framework.</p>
  
  <p>When I run on my dev machine, via an EXE entry point instead of the WinSvc entry point, everything runs just fine - BUT - I am already in "debug" mode.</p>
  
  <p>Any ideas of what to look for?</p>
  
  <hr>
  
  <p>2010-10-21 - NOTE - Changed the code base.</p>
  
  <pre><code>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.IO;
  using sysIO = System.IO;
  using RivWorks.FeedHandler;
  using System.Collections;
  
  namespace RivWorks.FeedHandler.Service
  {
      public partial class FeedListener : ServiceBase
      {
          #region Declarations
          private List&lt;string&gt; _keys = new List&lt;string&gt;();
          private System.Threading.Timer _clock = null;
          private FileSystemWatcher _watcher;
          private BackgroundWorker _worker;
          private Queue&lt;string&gt; _queue = new Queue&lt;string&gt;();
          private bool _isDequeueing = false;
          #endregion
  
          #region Constructor
          public FeedListener()
          {
              InitializeComponent();
          }
          #endregion
  
          #region Start/Stop
          protected override void OnStart(string[] args)
          {
              try
              {
                  WriteToEventLog("Enter Start", EventLogEntryType.Information);
                  _keys.AddRange(new string[] { "csv", "xml", "zip", "rivx" });
  
                  _worker = new BackgroundWorker();
                  _worker.WorkerReportsProgress = true;
                  _worker.WorkerSupportsCancellation = true;
                  _worker.DoWork += new DoWorkEventHandler(BackgroundWorkerDoWork);
                  _worker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorkerProgressChanged);
                  _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerRunWorkerCompleted);
  
                  _watcher = new FileSystemWatcher(AppSettings.Default.FTPRootPath, "*.*");
                  _watcher.IncludeSubdirectories = true;
                  _watcher.NotifyFilter = sysIO.NotifyFilters.DirectoryName | sysIO.NotifyFilters.FileName | sysIO.NotifyFilters.LastAccess | sysIO.NotifyFilters.CreationTime | sysIO.NotifyFilters.LastWrite;
                  _watcher.Created += new sysIO.FileSystemEventHandler(fileCreatedOrChanged);
                  _watcher.Changed += new sysIO.FileSystemEventHandler(fileCreatedOrChanged);
                  _watcher.EnableRaisingEvents = true;
  
                  // check every 15 minutes...
                  _clock = new System.Threading.Timer(Tick, null, 0, 900000);
                  WriteToEventLog("Exit Start", EventLogEntryType.Information);
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
                  this.Stop();
              }
          }
          protected override void OnStop()  
          {
              try
              {
                  _watcher.Dispose();
                  _watcher = null;
                  _clock.Dispose();
                  _clock = null;
                  _worker.Dispose();
                  _worker = null;
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          #endregion
  
          #region Event Handlers
          void fileCreatedOrChanged(object sender, sysIO.FileSystemEventArgs e)
          {
              try
              {
                  WriteToEventLog("Enter fileCreatedOrChanged", EventLogEntryType.Information);
  
                  if (!_queue.Contains(e.FullPath))
                      _queue.Enqueue(e.FullPath);
                  if (!_isDequeueing)
                      DeQueue();
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          #endregion
  
          #region Do work on another Thread
          void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
          {
              try
              {
                  WriteToEventLog("Enter BackgroundWorkerDoWork", EventLogEntryType.Information);
                  BackgroundWorker bw = sender as BackgroundWorker;
  
                  WriteToEventLog("Create Handler", EventLogEntryType.Information);
                  RivWorks.FeedHandler.Library.Handler handler = new RivWorks.FeedHandler.Library.Handler(Convert.ToBoolean(AppSettings.Default.InProduction), AppSettings.Default.ArchivePath);
  
                  WriteToEventLog("Setup Handler", EventLogEntryType.Information);
                  handler.Keys = _keys;
                  handler.RootDirectory = AppSettings.Default.RootDirectory;
                  handler.FtpPath = AppSettings.Default.FTPRootPath;
                  handler.WorkPath = AppSettings.Default.WorkPath;
                  handler.ArchivePath = AppSettings.Default.ArchivePath;
                  handler.EmailHost = AppSettings.Default.EmailHost;
                  handler.EmailPassword = AppSettings.Default.EmailPassword;
                  handler.EmailUser = AppSettings.Default.EmailUser;
                  handler.ErrorNotificationRecipients = AppSettings.Default.ErrorNotificationRecipients;
                  handler.InProduction = Convert.ToBoolean(AppSettings.Default.InProduction);
  
                  Library.DTO.FileHandler fileHandler = new Library.DTO.FileHandler(handler.FtpPath, handler.WorkPath, handler.ArchivePath, (string)e.Argument);
  
                  WriteToEventLog("Call Handler.Execute", EventLogEntryType.Information);
                  handler.Execute(bw, e, fileHandler);
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
              finally
              {
                  WriteToEventLog("Exit BackgroundWorkerDoWork", EventLogEntryType.Information);
              }
          }
          void BackgroundWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
          {
              try
              {
                  if (e.ProgressPercentage &gt;= 100)
                  {
                  }
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
          {
              try
              {
                  if (e.Cancelled)
                  {
                      WriteToEventLog("Cancelled.", EventLogEntryType.Warning);
                      if (e.Error != null)
                      {
                          WriteToEventLog(e.Error, EventLogEntryType.Error);
                      }
                  }
                  else if (e.Error != null)
                  {
                      WriteToEventLog(e.Error, EventLogEntryType.Error);
                  }
                  else
                  {
                      WriteToEventLog("Successfully completed.", EventLogEntryType.Information);
                  }
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          #endregion
  
          #region Private Methods
          private void Tick(object data)
          {
              try
              {
                  if (!_isDequeueing)
                  {
                      WriteToEventLog("Enter Tick.  FTP Root = " + AppSettings.Default.FTPRootPath, EventLogEntryType.Information);
  
                      foreach (string key in _keys)
                      {
                          List&lt;string&gt; files = Directory.GetFiles(Path.Combine(AppSettings.Default.FTPRootPath), "*." + key, SearchOption.AllDirectories).ToList();
                          foreach (string fileName in files)
                          {
                              if (File.Exists(fileName))
                              {
                                  // Toss this file name into the Queue...
                                  WriteToEventLog("Call _queue.Enqueue(" + fileName + ")", EventLogEntryType.Information);
                                  if (!_queue.Contains(fileName))
                                      _queue.Enqueue(fileName);
                              }
                          }
                      }
                      // Now, start handling the list of files...
                      DeQueue();
                  }
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
              finally
              {
                  WriteToEventLog("Exit Tick", EventLogEntryType.Information);
              }
          }
          private void DeQueue()
          {
              try
              {
                  _isDequeueing = true;
  
                  WriteToEventLog("Enter DeQueue", EventLogEntryType.Information);
  
                  while (_queue.Count &gt; 0)
                  {
                      string queuedFile = _queue.Dequeue();
                      WriteToEventLog("DeQueued " + queuedFile, EventLogEntryType.Information);
  
                      bool isValid = false;
                      foreach (string key in _keys)
                      {
                          if (Path.GetExtension(queuedFile).Replace(".", "").Equals(key, StringComparison.CurrentCultureIgnoreCase))
                              isValid = true;
                      }
  
                      if (isValid)
                      {
                          // Now, spin up a new thread and do the work on the file, based on file type...
                          WriteToEventLog("Call RunWorkerAsync", EventLogEntryType.Information);
                          string UserName = Path.GetDirectoryName(queuedFile).Replace(AppSettings.Default.FTPRootPath, "").Replace("\\", "");
                          int i = 0;
                          DateTime sTime = DateTime.Now;
                          DateTime eTime = DateTime.Now;
                          _worker.RunWorkerAsync(queuedFile);  // goes to BackgroundWorkerDoWork(object sender, DoWorkEventArgs e) //
  
                          while(_worker.IsBusy)
                          {
                              System.Threading.Thread.Sleep(5000);
                              i++;
                          }
                          eTime = DateTime.Now;
                          TimeSpan ts = new TimeSpan(eTime.Ticks - sTime.Ticks);
                          string msg = String.Format("Import for {0} started at {1} and ended at {2}.  It took {3} cycles and the elapsed time was {4}:{5}:{6}.", UserName, sTime, eTime, i, ts.Hours, ts.Minutes, ts.Seconds);
                          WriteToEventLog(msg, EventLogEntryType.Information);
                      }
                  }
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
              finally
              {
                  _isDequeueing = false;
                  WriteToEventLog("Exit DeQueue", EventLogEntryType.Information);
              }
          }
          private void WriteToEventLog(Exception ex, EventLogEntryType eventLogEntryType)
          {
              try
              {
                  string message = string.Empty;
                  string sTrace = ex.StackTrace;
                  while (ex != null)
                  {
                      message = message + Environment.NewLine + Environment.NewLine + ex.Message;
                      ex = ex.InnerException;
                  }
                  message = message + Environment.NewLine + Environment.NewLine + sTrace;
  
                  WriteToEventLog(message, eventLogEntryType);
              }
              catch (Exception ex2)
              {
                  WriteToEventLog(ex2.Message, EventLogEntryType.Error);
              }
          }
          private void WriteToEventLog(string message, EventLogEntryType eventLogEntryType)
          {
              try
              {
                  this.EventLog.WriteEntry(message, eventLogEntryType);
              }
              catch (Exception ex)
              {
                  throw ex;
              }
          }
          #endregion
      }
  }
  </code></pre>
  
  <hr>
  
  <p>2010-10-20 - NOTE - Added the Service code file.  Maybe there is an elementary mistake in here?</p>
  
  <pre><code>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.IO;
  using sysIO = System.IO;
  using RivWorks.FeedHandler;
  
  namespace RivWorks.FeedHandler.Service
  {
      public partial class FeedListener : ServiceBase
      {
          #region Declarations
          private List&lt;string&gt; _keys = new List&lt;string&gt;();
          private System.Threading.Timer _clock = null;
          private FileSystemWatcher _watcher;
          private BackgroundWorker _worker;
          static private bool _isBusy = false;
          #endregion
  
          #region Constructor
          public FeedListener()
          {
              InitializeComponent();
          }
          #endregion
  
          #region Start/Stop
          protected override void OnStart(string[] args)
          {
              try
              {
                  _keys.AddRange(new string[] { "csv", "xml", "zip", "rivx" });
  
                  _worker = new BackgroundWorker();
                  _worker.WorkerReportsProgress = true;
                  _worker.WorkerSupportsCancellation = true;
                  _worker.DoWork += new DoWorkEventHandler(BackgroundWorkerDoWork);
                  _worker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorkerProgressChanged);
                  _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerRunWorkerCompleted);
  
                  _watcher = new FileSystemWatcher(AppSettings.Default.FTPRootPath, "*.*");
                  _watcher.IncludeSubdirectories = true;
                  _watcher.NotifyFilter = sysIO.NotifyFilters.DirectoryName | sysIO.NotifyFilters.FileName | sysIO.NotifyFilters.LastAccess | sysIO.NotifyFilters.CreationTime | sysIO.NotifyFilters.LastWrite;
                  _watcher.Created += new sysIO.FileSystemEventHandler(fileCreatedOrChanged);
                  _watcher.Changed += new sysIO.FileSystemEventHandler(fileCreatedOrChanged);
                  _watcher.EnableRaisingEvents = true;
  
                  // check every 5 minutes...
                  _clock = new System.Threading.Timer(Tick, null, 0, 300000);
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
                  this.Stop();
              }
          }
          protected override void OnStop()  
          {
              try
              {
                  _watcher.Dispose();
                  _watcher = null;
                  _clock.Dispose();
                  _clock = null;
                  _worker.Dispose();
                  _worker = null;
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          #endregion
  
          #region Event Handlers
          void fileCreatedOrChanged(object sender, sysIO.FileSystemEventArgs e)
          {
              try
              {
                  DTO.BackgroundWorkerEventArgs eventArgs = new DTO.BackgroundWorkerEventArgs();
                  sysIO.WatcherChangeTypes myType = e.ChangeType;
  
                  bool isValid = false;
                  foreach (string key in _keys)
                  {
                      if (Path.GetExtension(e.FullPath).Replace(".", "").Equals(key, StringComparison.CurrentCultureIgnoreCase))
                          isValid = true;
                  }
  
                  if (isValid)
                  {
                      eventArgs.PathAndFile = e.FullPath;
                      eventArgs.Key = Path.GetExtension(e.FullPath).ToLower().Replace(".", "");
                      eventArgs.FileName = Path.GetFileName(e.FullPath);
                      eventArgs.Path = Path.GetDirectoryName(e.FullPath);
                      eventArgs.UserName = Path.GetDirectoryName(e.FullPath).Replace(AppSettings.Default.FTPRootPath, "").Replace("\\", "");
                      eventArgs.IsRunning = true;
  
                      System.Threading.Thread.Sleep(30000);
  
                      // Now, spin up a new thread and do the work on the file, based on file type...
                      _isBusy = true;
                      _worker.RunWorkerAsync(eventArgs);  // goes to BackgroundWorkerDoWork(object sender, DoWorkEventArgs e) //
                      int i = 0;
                      DateTime sTime = DateTime.Now;
                      DateTime eTime = DateTime.Now;
                      while (_isBusy)
                      {
                          System.Threading.Thread.Sleep(5000);
                          i++;
                      }
                      eTime = DateTime.Now;
                      TimeSpan ts = new TimeSpan(eTime.Ticks - sTime.Ticks);
                      string msg = String.Format("Import for {0} started at {1} and ended at {2}.  It took {3} cycles and the elapsed time was {4}:{5}:{6}.", eventArgs.UserName, sTime, eTime, i, ts.Hours, ts.Minutes, ts.Seconds);
                      WriteToEventLog(msg, EventLogEntryType.Information);
                  }
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          #endregion
  
          #region Do work on another Thread
          void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
          {
              try
              {
                  RivWorks.FeedHandler.Handler handler = new RivWorks.FeedHandler.Handler();
                  BackgroundWorker bw = sender as BackgroundWorker;
  
                  handler.Execute(bw, e);
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
              finally
              {
                  _isBusy = false;
              }
          }
          void BackgroundWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
          {
              try
              {
                  if (e.ProgressPercentage &gt;= 100)
                  {
                      _isBusy = false;
                  }
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
          {
              try
              {
                  if (e.Cancelled)
                  {
                      WriteToEventLog("Cancelled.", EventLogEntryType.Warning);
                      if (e.Error != null)
                      {
                          WriteToEventLog(e.Error, EventLogEntryType.Error);
                      }
                  }
                  else if (e.Error != null)
                  {
                      WriteToEventLog(e.Error, EventLogEntryType.Error);
                  }
                  else
                  {
                      WriteToEventLog("Successfully completed.", EventLogEntryType.Information);
                  }
                  _isBusy = false;
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          #endregion
  
          #region Private Methods
          private void Tick(object data)
          {
              try
              {
                  foreach (string key in _keys)
                  {
                      List&lt;string&gt; files = Directory.GetFiles(Path.Combine(AppSettings.Default.FTPRootPath), "*." + key, SearchOption.AllDirectories).ToList();
                      foreach (string fileName in files)
                      {
                          System.Threading.Thread.Sleep(5000);
                          if (File.Exists(fileName))
                          {
                              DateTime lat = File.GetLastWriteTime(fileName);
                              try
                              {
                                  File.SetLastWriteTime(fileName, DateTime.Now);
                              }
                              catch
                              {
                                  // just catch and ignore with a short pause...
                                  System.Threading.Thread.Sleep(5000);
                              }
                          }
                      }
                  }
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          private void WriteToEventLog(Exception ex, EventLogEntryType eventLogEntryType)
          {
              try
              {
                  string message = string.Empty;
                  string sTrace = ex.StackTrace;
                  while (ex != null)
                  {
                      message = message + Environment.NewLine + Environment.NewLine + ex.Message;
                      ex = ex.InnerException;
                  }
                  message = message + Environment.NewLine + Environment.NewLine + sTrace;
  
                  this.EventLog.WriteEntry(message, eventLogEntryType);
              }
              catch (Exception ex2)
              {
                  WriteToEventLog(ex2, EventLogEntryType.Error);
              }
          }
          private void WriteToEventLog(string message, EventLogEntryType eventLogEntryType)
          {
              try
              {
                  this.EventLog.WriteEntry(message, eventLogEntryType);
              }
              catch (Exception ex)
              {
                  WriteToEventLog(ex, EventLogEntryType.Error);
              }
          }
          #endregion
      }
  }
  </code></pre>