public async Task <int> SendMail(int MessageId, string toEmail, string toCCEmail, string subject, string message, TraceWriter log)
        {
            IDapperHelper dapperHelper = new DapperHelper();

            try
            {
                System.Diagnostics.Trace.WriteLine(fromEmail);
                System.Diagnostics.Trace.WriteLine(toEmail);
                System.Diagnostics.Trace.WriteLine(toCCEmail);
                MailMessage msgMail = new MailMessage(fromEmail, toEmail);
                if (toCCEmail != string.Empty)
                {
                    MailAddress ccEmail = new MailAddress(toCCEmail);
                    msgMail.Bcc.Add(ccEmail);
                }
                //Copy to developer
                try
                {
                    foreach (var developerCCEmail in developerCCEmail)
                    {
                        MailAddress ccEmail = new MailAddress(developerCCEmail);
                        msgMail.Bcc.Add(developerCCEmail);
                    }
                }
                catch (Exception) { }

                msgMail.Body         = message;
                msgMail.BodyEncoding = System.Text.Encoding.UTF8;
                msgMail.IsBodyHtml   = true;
                msgMail.Subject      = subject;

                SmtpClient ObjSmtpClient = new SmtpClient(smtpServer, port);
                if (toEmail.Contains("gmail"))
                {
                    ObjSmtpClient.TargetName = "STARTTLS/smtp.gmail.com";
                }
                else if (toEmail.Contains("hotmail") || toEmail.Contains("outlook"))
                {
                    ObjSmtpClient.TargetName = "STARTTLS/smtp.office365.com";
                }
                ObjSmtpClient.Credentials = new System.Net.NetworkCredential(fromEmail, emailPassword);
                ObjSmtpClient.EnableSsl   = true;
                log.Info($"Correo configurado para enviar:");
                log.Info($"From:{msgMail.From}");
                log.Info($"To:{msgMail.To}");
                log.Info($"Bcc:{msgMail.Bcc}");
                log.Info($"Subject:{msgMail.Subject}");
                await dapperHelper.ExecuteSP_Single <string>(SpMessage.UPDATE_SENTSTATUS, new { @MessageId = MessageId, @Subject = subject, @Body = message });

                log.Info($"Correo añadido a la base de datos");
                await ObjSmtpClient.SendMailAsync(msgMail);

                log.Info($"Correo enviado");
                return(1);
            }
            catch (Exception ex)
            {
                log.Info($"Error en el envío Message: {ex.Message}");
                log.Info($"Error en el envío StackTrace: {ex.StackTrace}");
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                await dapperHelper.ExecuteSP_Single <string>(SpMessage.UPDATE_ERRORSTATUS, new { @MessageId = MessageId });

                ErrorNotification errorNotification = new ErrorNotification();
                errorNotification.errorNotification(ex, fromEmail, toEmail, subject, message);
                return(0);
            }
        }
        public async Task <int[]> Scheduler_RFX(TraceWriter log)
        {
            IDapperHelper dapperHelper = new DapperHelper();

            int[] schedule = { 0, 0, 0 };

            try
            {
                List <HeaderScheduler> headers = await dapperHelper.ExecuteSP_Multiple <HeaderScheduler>(SpHeader.GET_ALL_BYSTATUS);

                DateTime Now = Convert.ToDateTime(DateTime.UtcNow.AddHours(-5).ToShortDateString());
                foreach (HeaderScheduler item in headers)
                {
                    //la fecha de cierre es menor a la de apertura
                    if (item.CloseDate < item.OpenDate)
                    {
                        await dapperHelper.ExecuteSP_Single <string>(SpHeader.UPDATE_STATUS, new
                        {
                            @Status   = "ERROR",
                            @HeaderId = item.HeaderId
                        });

                        schedule[0] += 1;
                    }
                    else
                    {
                        //fecha de apertura es menor o igual a la fecha actual
                        if (item.OpenDate <= Now)
                        {
                            //Si la fecha de cierre es mayor o igual  a la fecha actual y igual a la fecha de apertura el estado es "PROGRAMADO"
                            if (item.CloseDate >= Now && item.Status == "PROGRAMADO")
                            {
                                await dapperHelper.ExecuteSP_Single <string>(SpHeader.RFX_OPEN, new
                                {
                                    @HeaderId = item.HeaderId
                                });

                                //Add pending RFx invitations to message table
                                await dapperHelper.ExecuteSP_Single <string>(SpMessage.SET_MESSAGE_BUYER_TO_SUPPLIER, new
                                {
                                    @HeaderId = item.HeaderId
                                });

                                schedule[1] += 1;
                            } //si la fecha de cierre es menor a la fecha actual
                            else if (item.CloseDate <= Now && item.Status == "PUBLICADO")
                            {
                                await dapperHelper.ExecuteSP_Single <string>(SpHeader.RFX_CLOSE, new
                                {
                                    @HeaderId = item.HeaderId
                                });

                                //Add pending RFx closed notifications to message table
                                await dapperHelper.ExecuteSP_Single <string>(SpMessage.SET_MESSAGE_BUYER_TO_SUPPLIER, new
                                {
                                    @HeaderId = item.HeaderId
                                });

                                schedule[2] += 1;
                            }
                        }
                    }
                }
                return(schedule);
            }
            catch (Exception ex)
            {
                ErrorNotification errorNotification = new ErrorNotification();
                errorNotification.errorNotification(ex, "", "", "", "");
                return(schedule);
            }
        }
        public async Task <int[]> message_notification(TraceWriter log)
        {
            IDapperHelper dapperHelper = new DapperHelper();

            int[] notification = { 0, 0, 0 };

            try
            {
                List <MessageEntity> listPendingNotification = await dapperHelper.ExecuteSP_Multiple <MessageEntity>(SpMessage.GET_ALL_BYPENDING);

                log.Info($"Lista de correos pendientes: {listPendingNotification.Count}");
                List <EmailTemplateEntity> listEmailTemplate = await dapperHelper.ExecuteSP_Multiple <EmailTemplateEntity>(SpMessage.GET_MESSAGE_EMAIL_TEMPLATE);

                log.Info($"Lista de correos template: {listEmailTemplate.Count}");

                foreach (MessageEntity item in listPendingNotification)
                {
                    try
                    {
                        if (listEmailTemplate.Exists(x => x.CompanyId == item.CompanyId && x.DocumentType == item.DocumentType && x.DocumentStatus == item.DocumentStatus))
                        {
                            item.Subject = listEmailTemplate.Find(x => x.CompanyId == item.CompanyId && x.DocumentType == item.DocumentType && x.DocumentStatus == item.DocumentStatus).Subject;
                            item.Body    = listEmailTemplate.Find(x => x.CompanyId == item.CompanyId && x.DocumentType == item.DocumentType && x.DocumentStatus == item.DocumentStatus).Body;
                        }
                        else
                        {
                            item.Subject = listEmailTemplate.Find(x => x.CompanyId == 0 && x.DocumentType == item.DocumentType && x.DocumentStatus == item.DocumentStatus).Subject;
                            item.Body    = listEmailTemplate.Find(x => x.CompanyId == 0 && x.DocumentType == item.DocumentType && x.DocumentStatus == item.DocumentStatus).Body;
                        }

                        MessageReplaceEntity data = await dapperHelper.ExecuteSP_Single <MessageReplaceEntity>(SpMessage.GET_DATA_TO_REPLACE, new { @messageId = item.MessageId });

                        item.Subject = item.Subject.Replace("[DocumentNumber]", data.DocumentNumber);
                        item.Subject = item.Subject.Replace("[DocumentNumberParent]", data.DocumentNumberParent);
                        item.Body    = item.Body.Replace("[Sender]", item.Sender);
                        item.Body    = item.Body.Replace("[Recipient]", item.Recipient);
                        item.Body    = item.Body.Replace("[DocumentNumber]", data.DocumentNumber);
                        item.Body    = item.Body.Replace("[DocumentNumberParent]", data.DocumentNumberParent);
                        item.Body    = item.Body.Replace("[OpenDate]", data.OpenDate.ToString("dd/MM/yyyy"));
                        item.Body    = item.Body.Replace("[CloseDate]", data.CloseDate.ToString("dd/MM/yyyy"));

                        notification[0] += 1;
                        notification[1] += await SendMail(item.MessageId, item.MessageTo, item.MessageToBCC, item.Subject, item.Body, log);
                    }
                    catch (Exception ex)
                    {
                        log.Info($"Error en identificar el template: {ex.Message}");
                        log.Info($"Error en identificar el template: {ex.StackTrace}");
                        System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                        Console.WriteLine(ex);
                        await dapperHelper.ExecuteSP_Single <string>(SpMessage.UPDATE_ERRORSTATUS, new { @MessageId = item.MessageId });

                        ErrorNotification errorNotification = new ErrorNotification();
                        errorNotification.errorNotification(ex, fromEmail, item.MessageTo, item.Subject, item.Body);
                        notification[2] += 1;
                    }
                }
                return(notification);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                ErrorNotification errorNotification = new ErrorNotification();
                errorNotification.errorNotification(ex, fromEmail, "", "", "");
                return(notification);
            }
        }