Attempting to fire two processes in a windows service

G

Guest

I have a service process that contains two services but only one of them ever
works properly. The background is I have two classes which are Individual()
and Mass() in the main service class and they both inherit ServiceBase. The
main Method is as follows:

static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;

ServicesToRun = new System.ServiceProcess.ServiceBase[]
{
new MassService(),
new IndividualService()
};

System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

When I install the service and start it only the Mass service perfoms any
action and nothing occurs in the Individual service. I have tried creating
installers for each service and the same result occurs. I know the Individual
service works because if I reverse the order in Main() then Mass does not
work. Here is the code and both Mass and Indivudal are the same:

public class MassService : ServiceBase
{
private const string RETRY_MAX_TIME_EXCEEDED = "The file \"{0}\" could not
be processed because a timeout occurred while waiting for the file to finish
uploading.";
private const string SUCCESS_EVENT_MSG = "The File \"{0}\" was successfully
procesed and has been deleted from the file system at \"{1}\"";
private const string FAILED_TO_ADD_TO_QUEUE = "The file \"{0}\" was not
added to the queue.";
private const string INBOUND_FILE_COMPLETE_MSG = "The file \"{0}\" from IMDS
CDB was suucesfuly created at \"{1}\".";
private const string CLEANUP_EXCEPTION_MSG = "An error occured while
performing cleanup. The exception was: \"{0}\"";
private const string MASS_FSO_WATCHER_EXCEPTION_MSG = "Error creating the
FileSystemWatcher object. The exception was: \"{0}\"";
private const string APP_CONFIG_EXCEPTION_MSG = "Error reading the
application configuration file. The exception was: \"{0}\"";
private const int RETRY_MAX_TIME = 3600000; // 1 hour
private const int RETRY_DELAY = 10000; // 10 seconds
private System.Diagnostics.EventLog _eventLog = null;
private System.IO.FileSystemWatcher _fileSystemWatcher = null;

private void InitializEventLog()
{
string _source = "MyApp Library Logging";
string _log = "MyApp";

if (!EventLog.SourceExists(_source))
{
EventLog.CreateEventSource(_source, _log);
}

_eventLog = new EventLog(); //Create Event Log
_eventLog.Log = _log; //Assign Event Log Name
_eventLog.Source = _source; //Assign Event Source Name
}

private void IntializeFileSystemWatcher()
{
string _massFileStore = string.Empty;
string _fileType = string.Empty;

try
{
_massFileStore = ConfigurationManager.AppSettings["MassXmlFileStore"];
_fileType = ConfigurationManager.AppSettings["FileType"];
}
catch (Exception ex)
{
_eventLog.WriteEntry(APP_CONFIG_EXCEPTION_MSG +
ex.Message.ToString());
}

try
{
_fileSystemWatcher = new FileSystemWatcher(_massFileStore, _fileType);
}
catch (Exception ex)
{
_eventLog.WriteEntry(MASS_FSO_WATCHER_EXCEPTION_MSG +
ex.Message.ToString());
}

_fileSystemWatcher.EnableRaisingEvents = true; // Begin watching.
_fileSystemWatcher.IncludeSubdirectories = true; // Monitor Sub Folders
_fileSystemWatcher.NotifyFilter = NotifyFilters.DirectoryName |
NotifyFilters.FileName; // Apply filters

// Add event handlers for new XML files and deletion of existing XML
files.
_fileSystemWatcher.Created += new
FileSystemEventHandler(OnXMLFileCreated);
_fileSystemWatcher.Deleted += new
FileSystemEventHandler(OnXMLFileDeleted);
}

protected override void OnStart(string[] args)
{
InitializEventLog(); //Initialize Event Log
IntializeFileSystemWatcher(); //Initialize File System Watcher
}

protected override void OnStop()
{
_fileSystemWatcher.Dispose();
_eventLog.Dispose();
}

private void OnXMLFileDeleted(object source, FileSystemEventArgs args)
{
string _filename = args.FullPath;
DateTime _deletedAt = DateTime.Now;
_eventLog.WriteEntry(String.Format(SUCCESS_EVENT_MSG, _filename,
_deletedAt));
}

private void OnXMLFileCreated(object source, FileSystemEventArgs args)
{
string _filename = args.FullPath;
DateTime _receivedAt = DateTime.Now;
_eventLog.WriteEntry(String.Format(INBOUND_FILE_COMPLETE_MSG, _filename,
_receivedAt));
}

private void FileCreated(object sender, FileSystemEventArgs args)
{
string filename = args.FullPath;
DateTime receivedAt = DateTime.Now;
bool timedOut = false;
bool processed = false;

while (!(timedOut || processed))
{
if (FileUploadCompleted(filename))
{
PassOffFileToOracle(filename);
processed = true;
}
else
{
TimeSpan timeElapsed = DateTime.Now - receivedAt;

if (timeElapsed.TotalMilliseconds > RETRY_MAX_TIME)
{
timedOut = true;
}
else
{
Thread.Sleep(RETRY_DELAY);
}
}
}

if (timedOut)
{
_eventLog.WriteEntry(String.Format(RETRY_MAX_TIME_EXCEEDED,
filename));
}
}

private bool FileUploadCompleted(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open,
FileAccess.Read,
FileShare.None))
{
return true;
}
}
catch (IOException)
{
return false;
}
}

private void PassOffFileToOracle(string fileName)
{
// Add the file to the queue
FileQueue _queue = new FileQueue();
_queue.AddFileToQueue(fileName);

if (!_queue.AddFileToQueue(fileName))
try

{
_queue.GetAndRemoveTopMostFileName();
// Oracle DAL Layer here
}
catch (Exception)
{
_eventLog.WriteEntry(String.Format(FAILED_TO_ADD_TO_QUEUE,
fileName));
}
}

private void CleanUpFile(string fileName)
{
string _massFileStore = string.Empty;

try
{
_massFileStore = ConfigurationManager.AppSettings["MassXmlFileStore"];
System.IO.File.Delete(_massFileStore + @"\" + fileName);
}
catch (Exception ex)
{
_eventLog.WriteEntry(CLEANUP_EXCEPTION_MSG + ex.Message.ToString());
}
}
}

I have created one installer and the services panel shows both and I can
start both but nothing is occuruing when it comes to the Individual service
but the Mass service works perfectly.

Any ideas why both services are not working?
 
W

Walter Wang [MSFT]

Hi,

Which version of .NET framework are you using?

I've just tested in .NET 2.0 and Visual Studio 2005 that hosting multiple
services in one process works: each service can start or stop
independently. I can send the test project to you if you're interested.

Also, please note: when passing multiple services to ServiceBase.Run(),
this means the services will run within in the same process.

You mentioned that you wanted to "fire two processes in a windows service",
I'm not quite sure about this, would you please telling me more? Thank you.

Sincerely,
Walter Wang ([email protected], remove 'online.')
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 
G

Guest

I am using .NET 2.0.

I created one projct and I added two services and two installers within this
project. While both services showed up and I could start them only one ever
performed any work. I have corrected this today but I only have one service
and one installer and it works fine but I am not positive this is the best
method as I would actually prefer two services.

I can post these code changes if you want to see first hand what I have
done, just let me know if you want to see these changes. I would be willing
to guess you note about multiple services is where my problem resides.

In the meantime I would very much like to see your test project.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top