I am developing a Windows Service in C#, it installed perfectly, everything seems fine, but when I run the service, it automatically stops. I displays a message that reads:
"The BuzonVigiaCRM Service on Local Computer started and then stopped. Some services stop automatically if they are not used by any service or program."
Loading

Wim SturkenboomPosted Sep 21, 2014, 3:09 AM
{
System.Diagnostics.EventLog.CreateEventSource("BuzonVigiaCRM", "VGCRM_LOG");
}
If System.Diagnostics.EventLog.CreateEventSource("BuzonVigiaCRM", "VGCRM_LOG"); is executed, you might run into problems as the service might not have the required permission. So create that eventsource before you even install the service.
The setup of your ServiceProcessnstaller's account can cause issues. LocalSystem, LocalService, ... I have only used LocalSystem till now, but you might need something else; I can not advise which one.
Further your onStart() code is not embedded in a try/catch and might throw an exception. Catch it and write to the eventlog.
Emailing might take long (connecting etc); if so, the service manager will throw the error message that you get.
A better approach would be to set the initial value of the timer to e.g. one second and execute your emailing when the the timer fires the first time; after that you can use the normal timeout. You can keep a flag like fFirstrun to indicate that this is the first time the timer fires and should do the initial email.
I have not looked at the rest of your code. I suggest that you build it up 'from scratch'. Maybe first remove (comment out) the emailing in the onstart() event, recompile, re-install the service and check if it wants to start. If so, the problem is probably taht the emailing in the onStart takes too long and I gave you a suggestion higher up in this post.
That way you can slowly but surely narrow down the problems.
Enrique RomeroPosted Sep 19, 2014, 2:58 PM
I'll leave the code ... I do not find any error. I'm starting with C#, I regularly use .NET...
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.Timers;
using BuzonVigiaCRM.Resources;
using System.IO;
namespace BuzonVigiaCRM
{
public partial class BuzonVigiaCRM : ServiceBase
{
private System.Timers.Timer timer;
public List
public List
public List
public List
public List
public List
public List
public string user = "buzonfiscal";
public string pass = "buzon";
public BuzonVigiaCRM()
{
InitializeComponent();
string logName;
if (!System.Diagnostics.EventLog.SourceExists("BuzonVigiaCRM"))
{
System.Diagnostics.EventLog.CreateEventSource("BuzonVigiaCRM", "VGCRM_LOG");
}
logName = System.Diagnostics.EventLog.LogNameFromSourceName("BuzonVigiaCRM", ".");
System.Diagnostics.EventLog.DeleteEventSource("BuzonVigiaCRM");
eventLog1.Source = "BuzonVigiaCRM";
eventLog1.Log = "VGCRM_LOG";
int wait = 60000;
//int wait = 300000;
timer = new Timer(wait);
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("Vigia Buzon Fiscal iniciado");
EmailManager inicio = new EmailManager(eventLog1, user, pass);
EmailManager.connectToMail();
if (EmailManager.pop3Client.Connected)
{
inicio.sendEmail(user + "@gruporoga.com", "[email protected], [email protected]", "Vigía Buzón Fiscal Iniciado", "Se ha iniciado el Vigía del Buzón Fiscal");
EmailManager.disconnectFromEmail();
}
timer.Elapsed += timerElapsed;
timer.Start();
}
[Conditional("DEBUG")]
static void DebugMode()
{
if (!Debugger.IsAttached)
Debugger.Launch();
Debugger.Break();
}
void timerElapsed(object sender, ElapsedEventArgs e)
{
try
{
//Detenemos el contador
timer.Stop();
try
{
//Tratamos de buscar correos para el Buzón Fiscal
eventLog1.WriteEntry("Buscando correos en el Buzón Fiscal");
//Get the emails and process it
EmailManager managerEmail = new EmailManager(eventLog1, user, pass);
EmailManager.connectToMail();
if (EmailManager.pop3Client.Connected)
{
emailList = managerEmail.readEmails();
eventLog1.WriteEntry("Correos en el buzón: " + emailList.Count);
if (emailList.Count > 0)
{
//Process the email list, to download the atached files
for (int i = 0; i < emailList.Count; i++)
{
xmlFiles = new List
pdfFiles = new List
otherFiles = new List
filesToSend = new List
Email mail = emailList.ElementAt(i);
int attachmentCount = emailList.ElementAt(i).attachments.Count;
//Si el correo contiene archivos adjuntos, se busca el tipo de archivos adjuntos, para poder procesar los archivos XML
if (attachmentCount > 0)
{
xmlToSend = new List
eventLog1.WriteEntry("Attachment found " + attachmentCount);
for (int j = 0; j < attachmentCount; j++)
{
Attachment fileAttached = emailList.ElementAt(i).attachments.ElementAt(j);
eventLog1.WriteEntry("Attachment " + j + ".- File Name: " + fileAttached.fileName);
if (fileAttached.fileName.Contains(".XML"))
{
fileAttached.fileName.Replace(".XML", ".xml");
}
if (fileAttached.fileName.Contains(".PDF"))
{
fileAttached.fileName.Replace(".PDF", ".pdf");
}
//Si el archivo adjunto es XML, lo agregamos a la lista xmlFiles, para procesarlos
if (fileAttached.fileName.Contains(".xml") || fileAttached.fileName.Contains(".XML"))
{
eventLog1.WriteEntry("XML attachment file found");
xmlFiles.Add(fileAttached);
}
else
{
//Si el archivo adjunto es PDF, lo agregamos a la lista de pdfFiles, para buscar el archivo PDF correspondiente al XML
if (fileAttached.fileName.Contains(".pdf") || fileAttached.fileName.Contains(".PDF"))
{
eventLog1.WriteEntry("PDF attachment file found");
pdfFiles.Add(fileAttached);
}
else
{
//Si el tipo de archivo adjunto, no corresponde a un archivo XML o PDF, se responde al remitente con una lista de los archivos no procesados
otherFiles.Add(fileAttached.fileName);
}
}
}
//Comprobamos que se recibió por lo menos un archivo XML, para validar y procesar las facturas.
if (xmlFiles.Count > 0)
{
ProcesadorXML.eventLog1 = eventLog1;
/*
* Procesar todos los archivos XML encontrados,
* se busca respuesta con el SAT de la validez de la factura,
* también que el RFC corresponda al de la empresa y que se haya guardado el XML en la base de datos
*/
for (int y = 0; y < xmlFiles.Count; y++)
{
xmlFiles.ElementAt(y).respuesta = ProcesadorXML.processXML(xmlFiles.ElementAt(y).content, xmlFiles.ElementAt(y).fileName);
xmlFiles.ElementAt(y).idFactura = ProcesadorXML.idFactura;
xmlFiles.ElementAt(y).rfcReceptorValido = ProcesadorXML.rfcReceptorValido;
xmlFiles.ElementAt(y).rfcEmisor = ProcesadorXML.rfcEmisor;
}
//Enviar correo con los archivos procesados, respondiendo al correo que envió la factura al Buzón Fiscal.
EmailManager archivosProcesados = new EmailManager(eventLog1, user, pass);
string asunto = "Facturas en proceso de pago";
string message = "\r\n\r\n\r\n\r\n\r\n
\r\n
\r\n
for (int u = 0; u < xmlFiles.Count; u++)
{
if (xmlFiles.ElementAt(u).respuesta.Contains("0 - Sin Errores.") && xmlFiles.ElementAt(u).idFactura > 0)
{
//Comprobar que el RFC del receptor sea el nuestro: CEN060623PKA
if (xmlFiles.ElementAt(u).rfcReceptorValido)
{
eventLog1.WriteEntry("Adding a xml file to send");
xmlToSend.Add(xmlFiles.ElementAt(u));
Stream sx = new MemoryStream(xmlFiles.ElementAt(u).content);
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(sx, xmlFiles.ElementAt(u).fileName);
filesToSend.Add(att);
eventLog1.WriteEntry("Count of files to send:\t" + filesToSend.Count);
//Formar mensaje para el proveedor con las facturas que se validaron y aceptaron
message += "
//Guardar archivos XML físicamente en el servidor dónde esté corriendo el Vigía.
if (FileManager.saveFile(xmlFiles.ElementAt(u).content, xmlFiles.ElementAt(u).fileName))
{
eventLog1.WriteEntry("Archivo guardado correctamente");
}
else
{
eventLog1.WriteEntry("No se ha podido guardar el archivo");
}
//Buscar el archivo PDF correspondiente
int pos = FileManager.getPosPDFFile(xmlFiles.ElementAt(u).fileName, pdfFiles);
//Si existe el archivo PDF guardarlo en el servidor dónde esté corriendo el Vigía.
if (pos != -1)
{
eventLog1.WriteEntry("Adding a pdf file to send");
Stream sp = new MemoryStream(pdfFiles.ElementAt(pos).content);
System.Net.Mail.Attachment att2 = new System.Net.Mail.Attachment(sp, pdfFiles.ElementAt(pos).fileName);
filesToSend.Add(att2);
eventLog1.WriteEntry("Count of files to send:\t" + filesToSend.Count);
eventLog1.WriteEntry("PDF encontrado, tratando de guardar");
if (FileManager.saveFile(pdfFiles.ElementAt(pos).content, pdfFiles.ElementAt(pos).fileName))
{
eventLog1.WriteEntry("PDF guardado correctamente.");
}
else
{
eventLog1.WriteEntry("Error al tratar de guardar el PDF");
}
}
else
{
//Crear un PDF Genérico para la factura y agregarlo a la lista filesToSend
eventLog1.WriteEntry("Tratando de crear archivo PDF");
PDFCreator.eventLog1 = eventLog1;
filesToSend.Add(PDFCreator.createPDF(xmlFiles.ElementAt(u).fileName, xmlFiles.ElementAt(u).content));
eventLog1.WriteEntry("Archivo PDF creado correctamente");
}
}
else
{
eventLog1.WriteEntry("El RFC del receptor no corresponde con el de la empresa");
EmailManager rfcInvalido = new EmailManager(eventLog1, user, pass);
rfcInvalido.sendEmail(EmailManager.user + "@gruporoga.com", mail.from, "RFC desconocido", "El RFC de la factura " + xmlFiles.ElementAt(u).fileName + ", no corresponde con nuestro RFC, favor de verificar los datos registrados de nuestra empresa.\r\nCEN060623PKA\r\nComercial Empresarial Del Norte\r\n");
//Enviar correo con notificación de RFC no correspondiente con el de la empresa.
}
}
}
message += "\r\n
message += "\r\n
\r\n
\r\n
for (int u = 0; u < xmlFiles.Count; u++)
{
if (!xmlFiles.ElementAt(u).respuesta.Contains("0 - Sin Errores."))
{
if (xmlFiles.ElementAt(u).idFactura == -100)
{
message += "
}
else
{
message += "
}
}
if (xmlFiles.ElementAt(u).respuesta.Contains("0 - Sin Errores.") && xmlFiles.ElementAt(u).idFactura == -100)
{
message += "
}
}
message += "\r\n
if (archivosProcesados.sendEmail(EmailManager.user + "@gruporoga.com", mail.from, asunto, message))
{
eventLog1.WriteEntry("Notificación del procesamiento de XML enviada al proveedor");
}
else
{
eventLog1.WriteEntry("No se ha podido enviar la notificación del procesamiento de XML al proveedor");
}
if (xmlToSend.Count > 0)
{
Proveedor prov = SQLManager.getDatosProveedor(xmlFiles.ElementAt(0).rfcEmisor);
string toEmail;
if (prov.getClase().Equals("Servicios") || prov.getClase().Equals("SERVICIOS"))
{
//Enviar correo a la persona encargada de servicios
toEmail = SQLManager.getCorreosVigia("Servicios");
message = "\n\rMensaje recibido de:\t" + mail.from;
message += "Se han recibido y validado las siguientes facturas:";
}
else
{
if (prov.getClase().Equals("Insumos") || prov.getClase().Equals("INSUMOS"))
{
//Enviar correo a la persona encargada de insumos
toEmail = SQLManager.getCorreosVigia("Insumos");
message = "\n\rMensaje recibido de:\t" + mail.from;
message += "Se han recibido y validado las siguientes facturas:";
}
else
{
toEmail = SQLManager.getCorreosVigia("Registro");
/*
* Enviar correo a las personas encargadas de insumos y servicios,
* pedir actualizar datos al proveedor,
* notificar a la persona responsable de dar de alta a los proveedores,
* para que se verifiquen los datos del proveedor.
*/
message = "\n\rMensaje recibido de:\t" + mail.from;
message += "\n\rEl Buzón Fiscal ha recibido una(s) factura(s) de un proveedor que no se ha registrado en el sistema, favor de dar de alta sus datos, o pedirle al proveedor que se registre en nuestro sistema CRM.";
}
}
/*
for(int j = 0; j < xmlToSend.Count; j++)
{
eventLog1.WriteEntry("Adding a file to filesToSend:\t" + xmlToSend.ElementAt(j).fileName);
message += "\n\r" + xmlToSend.ElementAt(j).fileName + "\t" + xmlToSend.ElementAt(j).respuesta;
Stream sx = new MemoryStream(xmlToSend.ElementAt(j).content);
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(sx, xmlToSend.ElementAt(j).fileName);
filesToSend.Add(att);
}
* */
/*
for(int p = 0; p < pdfToSend.Count; p++)
{
message += "\n\r" + pdfToSend.ElementAt(p).fileName + "\t" + pdfToSend.ElementAt(p).respuesta;
Stream sp = new MemoryStream(pdfToSend.ElementAt(p).content);
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(sp, pdfToSend.ElementAt(p).fileName);
filesToSend.Add(att);
}
* */
//Enviar correo con las facturas procesadas
EmailManager facturaProcesar = new EmailManager(eventLog1, user, pass);
facturaProcesar.sendEmailAttachments(user + "@gruporoga.com", toEmail, "Procesar pagos", message, filesToSend);
}
List
//Borrar el correo actual, sólo se están borrando los correos que tengan archivos xml
EmailManager.deleteEmail(i);
}
}
else
{
eventLog1.WriteEntry("File not processed, sending auto-responce");
EmailManager responce = new EmailManager(eventLog1, user, pass);
if (responce.sendInstructions(mail.from))
{
eventLog1.WriteEntry("Mail succesfully sended");
EmailManager.deleteEmail(i);
}
else
{
eventLog1.WriteEntry("Mail not sended");
}
/*
//if (responce.sendEmail( EmailManager.user + "@gruporoga.com", sendTo, "Auto-Replay", "Los archivos adjuntos no han podido procesarse, favor de intentar nuevamente."))
if (responce.sendEmail(EmailManager.user + "@gruporoga.com", mail.from, "Auto-Replay", "No hemos recibido ningún archivo con su factura, favor de intentar nuevamente."))
{
eventLog1.WriteEntry("Mail succesfully sended");
EmailManager.deleteEmail(i);
}
else
{
eventLog1.WriteEntry("Mail not sended");
}*/
}
if (otherFiles.Count > 0 && xmlFiles.Count < 1)
{
/*
else
{
eventLog1.WriteEntry("No se encontraron archivos XML");
EmailManager responce = new EmailManager(eventLog1, "buzonfiscal", "buzon");
if (responce.sendEmail(EmailManager.user + "@gruporoga.com", mail.from, "No se pudo procesar su petición", "Le informamos que los archivos que hemos recibido, no concuerdan con el tipo de documento esperado, le solicitamos de la manera más atenta, nos envíe su factura en archivo xml, con su correspondiente archivo pdf."))
{
eventLog1.WriteEntry("Mail succesfully sended");
EmailManager.deleteEmail(i);
}
else
{
eventLog1.WriteEntry("Mail not sended");
}
}
*/
eventLog1.WriteEntry("File not processed, sending auto-responce");
EmailManager responce = new EmailManager(eventLog1, user, pass);
string listaFiles = "";
for (int k = 0; k < otherFiles.Count; k++)
{
listaFiles += otherFiles.ElementAt(k) + "\n";
}
if (responce.sendEmail(EmailManager.user + "@gruporoga.com", mail.from, "Auto-Replay", "Los archivos adjuntos no han podido procesarse, ya que no son archivos válidos, requerimos por lo menos un archivo XML con su factura. Favor de intentar nuevamente. " + listaFiles))
{
eventLog1.WriteEntry("Mail succesfully sended");
EmailManager.deleteEmail(i);
}
else
{
eventLog1.WriteEntry("Mail not sended");
}
}
}
}
else
{
eventLog1.WriteEntry("Mail not connected");
}
}
}
finally
{
//Close connections
EmailManager.disconnectFromEmail();
eventLog1.WriteEntry("Busqueda finalizada");
}
//DebugMode();
timer.Start();
}
catch (Exception ex)
{
eventLog1.WriteEntry("Error " + ex.Message);
EmailManager.connectToMail();
EmailManager failureMail = new EmailManager(eventLog1, user, pass);
failureMail.sendEmail(EmailManager.user + "@gruporoga.com", "[email protected],[email protected]", "Error en el Vigia de Buzón Fiscal", "El Buzón Fiscal detectó el siguiente error:\t" + ex.Message);
//this.Stop();
}
}
protected override void OnStop()
{
eventLog1.WriteEntry("Vigia Buzon Fiscal detenido");
EmailManager fin = new EmailManager(eventLog1, user, pass);
EmailManager.connectToMail();
if (EmailManager.pop3Client.Connected)
{
fin.sendEmail(user + "@gruporoga.com", "[email protected], [email protected]", "Vigía Buzón Fiscal Detenido", "Se ha detenido el Vigía del Buzón Fiscal");
EmailManager.disconnectFromEmail();
}
timer.Stop();
}
protected override void OnPause()
{
base.OnPause();
eventLog1.WriteEntry("Vigia Buzon Fiscal pausado");
EmailManager pausa = new EmailManager(eventLog1, user, pass);
EmailManager.connectToMail();
if (EmailManager.pop3Client.Connected)
{
pausa.sendEmail(user + "@gruporoga.com", "[email protected], [email protected]", "Vigía Buzón Fiscal Pausado", "Se ha pausado el Vigía del Buzón Fiscal");
EmailManager.disconnectFromEmail();
}
timer.Stop();
}
protected override void OnContinue()
{
eventLog1.WriteEntry("Vigia Buzon Fiscal reiniciado");
EmailManager reanudado = new EmailManager(eventLog1, user, pass);
EmailManager.connectToMail();
if (EmailManager.pop3Client.Connected)
{
reanudado.sendEmail(user + "@gruporoga.com", "[email protected], [email protected]", "Vigía Buzón Fiscal Reanudado", "Se ha reanudado el Vigía del Buzón Fiscal");
EmailManager.disconnectFromEmail();
}
timer.Elapsed += timerElapsed;
timer.Start();
}
}
}
Wim SturkenboomPosted Sep 19, 2014, 2:47 PM
You might have permission issues; e.g. if your service attempts to access network shares, it needs admin rights (you can configure a user somewhere in the properties of the service in the service manager); I'm not sure if the result is the error that you get. Or if the service tries to create a logfile or directory in a directory that it does not have permission on (e.g. C:\).
My approach is to log anything in the event log till the service is started completely. I also log in the eventlog when the service is stopped normally.
The start of a service has a time limit; if the onStart() is not finished within a certain time (I think one minute), the service will be considered as non-responding and stopped.
Did you develop a console application or windows application in parallel that was used to test / debug the main functionality of the service using exactly the same methods?
I use a conditional compilation flag to decide between console application and service. The console application will start a thread while the service will start service (onStart). The thread and the service will do exactly the same so it's easy to debug in the console application.
Vithal WadjePosted Sep 19, 2014, 2:45 PM