none
Windows service doesn't continue the execution RRS feed

  • Question

  • 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")

    Tuesday, December 18, 2018 4:39 AM

Answers

All replies

  • In order to investigate the problem, add some more ‘_log.WriteEntry’ inside the foreach loop. Also check if it continues working if you temporarily comment the call of ‘Print()’.


    Tuesday, December 18, 2018 5:51 AM
  • Hi neonash,

    Welcome to the MSDN forum.

    According to the description, it seems your issue is about the Windows Service development and our forum is to discuss the VS IDE, I will move this thread to seek for a better support forum, thank you for your understanding.

    Best regards,

    Sara


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com

    Wednesday, December 19, 2018 3:18 AM
  • I'd try asking for help over here.

    https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/home?forum=windowsgeneraldevelopmentissues

     

     




    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows Server] Datacenter Management

    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees, and confers no rights.

    Wednesday, December 19, 2018 4:06 AM
    Moderator
  • Hi

    I identified the problem.

    The following code is not executed:

                            var report = new LocalReport
                            {
                                ReportPath = AppDomain.CurrentDomain.BaseDirectory + @"Impresion\ReporteQR.rdlc"
                            };
    
                            report.DataSources.Add(
                            new ReportDataSource("dsImpresionQr", ticket));
    
                            Export(report);
                            Print();
    But I works fine when I call the method from a console app.

    Wednesday, December 19, 2018 4:40 AM
  • This is "where is" forum for direction on where best to ask questions. I'd try asking for help over here. 

    https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/home?forum=windowsgeneraldevelopmentissues

     

     



    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows Server] Datacenter Management

    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees, and confers no rights.

    Wednesday, December 19, 2018 5:04 AM
    Moderator