Windows service doesn't continue the execution

  • Thread starter Thread starter neonash
  • Start date Start date
N

neonash

Guest
Hi

I created a Windows Service which runs perfect when I run the code from a console app but I doesn't work when it runs in the windows service:

I can see that it line is not executed:

foreach (var item in pendientes)

My complete code:

using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Drawing;
using CajaWebTCC.ServicioComprobante02.Agente;
using CajaWebTCC.ServicioComprobante02.ServicioComprobante02;
using System.Net;
using CajaWebTCC.ServicioComprobante02.Impresion;

namespace CajaWebTCC.ServicioComprobante02
{
public partial class ServicioComprobanteViewer : ServiceBase
{
private readonly int _intervalo;
private System.Timers.Timer _timer;
private EstadoServicio _estadoServicio;
private readonly EventLog _log;
private readonly bool _logHabilitado;
private int m_currentPageIndex;
private IList<Stream> m_streams;
public ServicioComprobanteViewer()
{
InitializeComponent();

var logSource = ConfigurationManager.AppSettings["LogSource"];
var logName = ConfigurationManager.AppSettings["LogName"];
var inter = ConfigurationManager.AppSettings["Intervalo"];
_logHabilitado = Boolean.Parse(ConfigurationManager.AppSettings["LogHabilitado"]);


_intervalo = Int32.Parse(inter);

if (_logHabilitado)
_log = new EventLog { Source = logSource, Log = logName };
}

#region timer

void timer_Elapsed(object sender, ElapsedEventArgs e)
{

if (_estadoServicio != EstadoServicio.Esperando) return;
_estadoServicio = EstadoServicio.Procesando;

_log.WriteEntry("Se lanza proceso");
ProcesarImpresion();
_log.WriteEntry("fin proceso");
_estadoServicio = EstadoServicio.Esperando;
}

#endregion

#region Events Interface

protected override void OnStart(string[] args)
{
//Configuracion del Timer
if (_timer == null) _timer = new System.Timers.Timer();
_timer.AutoReset = true;
_timer.Interval = _intervalo * 1000;
_timer.Elapsed += timer_Elapsed;

_estadoServicio = EstadoServicio.Procesando;

_timer.Start();
//ProcesarImpresion();
_estadoServicio = EstadoServicio.Esperando;
//Registros del log
if (_logHabilitado)
_log.WriteEntry("Se inicia el servicio de impresión con QR.");
}


protected override void OnStop()
{
_timer.Stop();
_timer.Elapsed -= timer_Elapsed;
_timer = null;
if (_logHabilitado)
_log.WriteEntry("El servicio de impresión con QR se detuvo.");
}

#endregion
private Stream CreateStream(string name,
string fileNameExtension, Encoding encoding,
string mimeType, bool willSeek)
{
Stream stream = new MemoryStream();
m_streams.Add(stream);
return stream;
}

private void Export(LocalReport report)
{
const string deviceInfo =
@"<DeviceInfo>
<OutputFormat>EMF</OutputFormat>
<PageWidth>10in</PageWidth>
<PageHeight>12in</PageHeight>
<MarginTop>0.1in</MarginTop>
<MarginLeft>0.1in</MarginLeft>
<MarginRight>0.1in</MarginRight>
<MarginBottom>0.1in</MarginBottom>
</DeviceInfo>";
Warning[] warnings;
m_streams = new List<Stream>();
report.Render("Image", deviceInfo, CreateStream,
out warnings);
foreach (Stream stream in m_streams)
stream.Position = 0;
}

private void PrintPage(object sender, PrintPageEventArgs ev)
{
var pageImage = new
Metafile(m_streams[m_currentPageIndex]);

// Adjust rectangular area with printer margins.
var adjustedRect = new Rectangle(
ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
ev.PageBounds.Width,
ev.PageBounds.Height);

// Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect);


// Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect);


// Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex++;
ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
}
private void Print()
{
if (m_streams == null || m_streams.Count == 0)
throw new Exception("Error: No hay stream que imprimir.");
using (var printDoc = new PrintDocument())
{
printDoc.PrinterSettings.PrinterName = ConfigurationManager.AppSettings["NombreImpresora"];
printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
m_currentPageIndex = 0;


printDoc.Print();

}
}

public void ProcesarImpresion()
{
try
{
_log.WriteEntry("paso0");
var pendientes = AgenteServicioComprobante.ListarComprobantePendiente(new ComprobantePendienteEL
{
vch_CodigoEstacion = Dns.GetHostName()
});


if (pendientes != null && pendientes.Any())
{
_log.WriteEntry("paso01");

foreach (var item in pendientes)
{

var vchTextoComprobante = item.vch_TextoComprobante;
byte[] bitsCodigoQr = null;

if (!string.IsNullOrEmpty(item.vch_ImagenQR))
{
var codigoQr = item.vch_ImagenQR;

bitsCodigoQr = Convert.FromBase64String(codigoQr);
}

var ticket = new List<TicketQr>
{
new TicketQr
{
Comprobante = vchTextoComprobante,
CodigoQr = string.IsNullOrEmpty(item.vch_ImagenQR) ? null :
bitsCodigoQr
}
};

var report = new LocalReport
{
ReportPath = AppDomain.CurrentDomain.BaseDirectory + @"Impresion\ReporteQR.rdlc"
};

report.DataSources.Add(
new ReportDataSource("dsImpresionQr", ticket));

Export(report);
Print();


AgenteServicioComprobante.ActualizarComprobantePendiente(new ComprobantePendienteEL
{
int_CodigoComprobantePendiente = item.int_CodigoComprobantePendiente
});

System.Threading.Thread.Sleep(2000);

}
}


}
catch (Exception ex)
{
if (_logHabilitado)
{
_log.WriteEntry(ex.Message);
_log.WriteEntry(ex.StackTrace);
}
}
}
}

public enum EstadoServicio
{
Esperando = 0,
Procesando = 1
}
}




I seens that the app stop working. after:

if (pendientes != null && pendientes.Any())
{
_log.WriteEntry("paso01")

Continue reading...
 
Back
Top