Exemple #1
0
        public string GetTaskList_HtmlPage()
        {
            List <IRTask> tasks;

            lock (this)
                tasks = _tasks.ToList();

            var tasksView = tasks.Select(t => new
            {
                t.Id,
                SendAddresses = t.SendAddresses?.Addresses,
                t.ViewTemplate,
                Schedule = t.Schedule?.Name,
                t.ConnectionString,
                t.Query,
                t.TryCount,
                TimeOut = t.QueryTimeOut,
                t.Type
            })
                            .ToList();
            var jsonTasks = JsonConvert.SerializeObject(tasksView);
            var tr        = _tableView.ExecuteHtml("", jsonTasks);

            return(tr);
        }
Exemple #2
0
        public async Task <string> GetTasksList_HtmlPageAsync()
        {
            List <IReportTask> currentTasks;

            lock (this)
                currentTasks = tasks.ToList();

            var tasksData = currentTasks.Select(task => new
            {
                task.Id,
                task.Name,
                task.Schedule?.Schedule,
                Operations = string.Join("=>", task.Operations.Select(oper => oper.Properties.Name))
            });

            var pack = packageBuilder.GetPackage(tasksData);

            return(await Task.Factory.StartNew(() =>
                                               tableView.ExecuteHtml("Current tasks list", pack)));
        }
Exemple #3
0
        public void Execute(string address = null)
        {
            var dtoInstance = new DtoFullInstance()
            {
                StartTime = DateTime.Now,
                TaskId    = Id,
                State     = (int)InstanceState.InProcess
            };

            dtoInstance.Id =
                _repository.CreateEntity(_mapper.Map <DtoInstance>(dtoInstance));

            _repository.CreateEntity(_mapper.Map <DtoInstanceData>(dtoInstance));

            string[] deliveryAddrs = { };

            if (!string.IsNullOrEmpty(address))
            {
                deliveryAddrs = new[] { address }
            }
            ;
            else if (SendAddresses != null)
            {
                deliveryAddrs = SendAddresses.GetAddresses();
            }

            Stopwatch duration = new Stopwatch();

            duration.Start();
            int    i            = 1;
            bool   dataObtained = false;
            string jsonReport   = "";
            string htmlReport   = "";

            while (!dataObtained && i <= TryCount)
            {
                try
                {
                    jsonReport   = _dataEx.Execute(this);
                    htmlReport   = _viewEx.ExecuteHtml(ViewTemplate, jsonReport);
                    dataObtained = true;
                    i++;
                    break;
                }
                catch (Exception ex)
                {
                    jsonReport = ex.Message;
                    htmlReport = ex.Message;
                }

                i++;
            }

            if (dataObtained)
            {
                try
                {
                    if (deliveryAddrs?.Length > 0)
                    {
                        _postMaster.Send(ReportName, deliveryAddrs,
                                         HasHtmlBody ? htmlReport : null,
                                         HasJsonAttachment ? jsonReport : null);
                    }

                    if (ChatId != 0)
                    {
                        try
                        {
                            _bot.SendTextMessageAsync(ChatId, _viewEx.ExecuteTelegramView(jsonReport, ReportName),
                                                      ParseMode.Markdown).Wait();
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            throw;
                        }
                    }

                    _monik.ApplicationInfo($"Отчёт {Id} успешно выслан");
                }
                catch (Exception e)
                {
                    _monik.ApplicationError(e.Message);
                }
            }

            duration.Stop();

            dtoInstance.Data      = _archiver.CompressString(jsonReport);
            dtoInstance.ViewData  = _archiver.CompressString(htmlReport);
            dtoInstance.TryNumber = i - 1;
            dtoInstance.Duration  = Convert.ToInt32(duration.ElapsedMilliseconds);
            dtoInstance.State     = dataObtained ? (int)InstanceState.Success : (int)InstanceState.Failed;

            // string filename = $@"{AppDomain.CurrentDomain.BaseDirectory}\\Report{Id}-{DateTime.Now:HHmmss}";

            _repository.UpdateEntity(_mapper.Map <DtoInstance>(dtoInstance));
            _repository.UpdateEntity(_mapper.Map <DtoInstanceData>(dtoInstance));
        } //method
 public string GetDefaultPackageView(string taskName, OperationPackage package)
 {
     return(executor.ExecuteHtml(taskName, package));
 }
        public async Task ExecuteAsync(IReportTaskRunContext taskContext)
        {
            var package = taskContext.Packages[Properties.PackageName];

            if (!RunIfVoidPackage && package.DataSets.Count == 0)
            {
                if (!RunIfVoidPackage && package.DataSets.Count == 0)
                {
                    return;
                }
            }

            string fileName = (string.IsNullOrEmpty(ReportName)
                                  ? $@"{Properties.PackageName}"
                                  : taskContext.SetStringParameters(ReportName))
                              + (DateInName
                                  ? $" {DateTime.Now:dd.MM.yy}"
                                  : null);

            using var msg = ConfigureMessage(taskContext, fileName);

            var dataSets = parser.GetPackageValues(package);
            var firstSet = dataSets.First();

            viewExecutor = firstSet.GroupColumns != null && firstSet.GroupColumns.Any()
                ? autofac.ResolveNamed <IViewExecutor>("GroupedViewex")
                : string.IsNullOrEmpty(ViewTemplate)
                    ? autofac.ResolveNamed <IViewExecutor>("CommonTableViewEx")
                    : autofac.ResolveNamed <IViewExecutor>("commonviewex");

            if (HasHtmlBody)
            {
                msg.IsBodyHtml = true;
                msg.Body       = viewExecutor.ExecuteHtml(ViewTemplate, package);
            }

            MemoryStream streamJson = null;
            MemoryStream streamXlsx = null;

            try
            {
                if (HasJsonAttachment)
                {
                    var dataToSave = UseAllSetsJson
                        ? JsonConvert.SerializeObject(dataSets)
                        : JsonConvert.SerializeObject(dataSets.First());

                    streamJson =
                        new MemoryStream(System.Text.Encoding.UTF8
                                         .GetBytes(dataToSave));

                    AddDataSetsJson(msg, streamJson, fileName);
                }

                if (HasXlsxAttachment)
                {
                    streamXlsx = new MemoryStream();

                    AddDataSetsXlsx(package, msg, streamXlsx, fileName);
                }

                using var client = ConfigureClient();

                await using (taskContext.CancelSource.Token.Register(() => client.SendAsyncCancel()))
                {
                    var tryCount = 0;
                    while (tryCount < 3)
                    {
                        try
                        {
                            await client.SendMailAsync(msg);

                            break;
                        }
                        catch (Exception exc)
                        {
                            if (tryCount == 2)
                            {
                                throw new Exception("Message not sent", exc);
                            }
                            else
                            {
                                tryCount++;
                            }
                        }
                    }
                }
            }

            finally
            {
                streamJson?.Dispose();

                streamXlsx?.Dispose();
            }
        }
        } //ctor

        public void Execute(IReportTaskRunContext taskContext)
        {
            var package = taskContext.Packages[Properties.PackageName];

            if (!RunIfVoidPackage && package.DataSets.Count == 0)
            {
                return;
            }

            string filename = (string.IsNullOrEmpty(ReportName)
                                  ? $@"{Properties.PackageName}"
                                  : taskContext.SetStringParameters(ReportName))
                              + (DateInName
                                  ? null
                                  : $" {DateTime.Now:dd.MM.yy}");

            string filenameJson = $@"{filename}.json";
            string filenameXlsx = $@"{filename}.xlsx";

            using (var client = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"], 25))
                using (var msg = new MailMessage())
                {
                    client.DeliveryFormat = SmtpDeliveryFormat.International;
                    client.EnableSsl      = true;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;

                    msg.From = new MailAddress(ConfigurationManager.AppSettings["from"]);
                    msg.AddRecepientsFromGroup(addresses);

                    if (!string.IsNullOrEmpty(RecepientsDatasetName))
                    {
                        msg.AddRecepientsFromPackage(taskContext.Packages[RecepientsDatasetName]);
                    }

                    msg.Subject = filename;

                    var dataset = parser.GetPackageValues(package).First();

                    viewExecutor = dataset.GroupColumns != null && dataset.GroupColumns.Any()
                    ? autofac.ResolveNamed <IViewExecutor>("GroupedViewex")
                    : !string.IsNullOrEmpty(ViewTemplate)
                        ? autofac.ResolveNamed <IViewExecutor>("CommonTableViewEx")
                        : autofac.ResolveNamed <IViewExecutor>("commonviewex");

                    if (HasHtmlBody)
                    {
                        msg.IsBodyHtml = true;
                        msg.Body       = viewExecutor.ExecuteHtml(ViewTemplate, package);
                    }

                    MemoryStream streamJson = null;
                    MemoryStream streamXlsx = null;

                    try
                    {
                        if (HasJsonAttachment)
                        {
                            var sets       = parser.GetPackageValues(package);
                            var dataToSave = UseAllSetsJson
                            ? JsonConvert.SerializeObject(sets)
                            : JsonConvert.SerializeObject(sets.First());

                            streamJson =
                                new MemoryStream(System.Text.Encoding.UTF8
                                                 .GetBytes(dataToSave));
                            msg.Attachments.Add(new Attachment(streamJson, filenameJson,
                                                               @"application/json"));
                        }

                        if (HasXlsxAttachment)
                        {
                            streamXlsx = new MemoryStream();
                            var excel = viewExecutor.ExecuteXlsx(package, filename, UseAllSetsXlsx);
                            excel.SaveAs(streamXlsx);
                            excel.Dispose();
                            streamXlsx.Position = 0;
                            msg.Attachments.Add(new Attachment(streamXlsx, filenameXlsx,
                                                               @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                        }

                        var tryCount = 0;
                        while (tryCount < 3)
                        {
                            try
                            {
                                client.Send(msg);
                                break;
                            }
                            catch (Exception exc)
                            {
                                if (tryCount == 2)
                                {
                                    throw new Exception("Message not sent", exc);
                                }
                                else
                                {
                                    tryCount++;
                                }
                            }
                        }
                    }

                    finally
                    {
                        streamJson?.Dispose();

                        streamXlsx?.Dispose();
                    }
                }
        } //method