Пример #1
0
        private void QueueEmail(ScheduledReport scheduledReport)
        {
            scheduledReport.IsSuccessful = false;
            Log(string.Format("Scheduled Report Id: {0}, Report Id: {1}, Organization {2}", scheduledReport.Id.ToString(), scheduledReport.ReportId, scheduledReport.OrganizationId));
            Log(string.Format("Set to start on: {0}", scheduledReport.NextRun), LogType.Public);

            try
            {
                LoginUser scheduledReportCreator = new LoginUser(scheduledReport.CreatorId, scheduledReport.OrganizationId);
                Report    report = Reports.GetReport(scheduledReportCreator, scheduledReport.ReportId, scheduledReport.CreatorId);
                Log(string.Format("Generating {0} Report", report.ReportDefType.ToString()), LogType.Both);

                string reportAttachmentFile = string.Empty;

                if (report.ReportDefType == ReportType.Chart)
                {
                    reportAttachmentFile = GetReportChartFile(scheduledReportCreator, scheduledReport, report);
                }
                else
                {
                    reportAttachmentFile = GetReportDataToFile(scheduledReportCreator, report, scheduledReport, "", false, true, Logs);
                }

                if (!string.IsNullOrEmpty(reportAttachmentFile))
                {
                    if (report.ReportDefType != ReportType.Chart)
                    {
                        try
                        {
                            float fileSizeMB = 0;

                            if (File.Exists(reportAttachmentFile))
                            {
                                long fileSizeBytes = new FileInfo(reportAttachmentFile).Length;
                                fileSizeMB = (fileSizeBytes / 1024f) / 1024f;
                            }

                            //If the report is 2M or less, don't zip it.  If over 2M, zip it.
                            if (fileSizeMB > 2)
                            {
                                string zipFileName = reportAttachmentFile.Replace(".csv", ".zip");

                                if (File.Exists(zipFileName))
                                {
                                    try
                                    {
                                        File.Delete(zipFileName);
                                    }
                                    catch (IOException ioEx)
                                    {
                                        DateTime zipFileNamesuffix = scheduledReport.NextRun != null ? (DateTime)scheduledReport.NextRun : DateTime.UtcNow;
                                        zipFileName = zipFileName.Replace(".zip", string.Format("_{0}.zip", zipFileNamesuffix.ToString("yyyyMMddHHmm")));
                                        Log("Previous zip file could not be deleted. Naming the new one: ");
                                        Log(ioEx.Message + Environment.NewLine + ioEx.StackTrace);
                                    }
                                }

                                using (ZipArchive zip = ZipFile.Open(zipFileName, ZipArchiveMode.Create))
                                {
                                    zip.CreateEntryFromFile(reportAttachmentFile, Path.GetFileName(reportAttachmentFile));
                                }

                                if (File.Exists(zipFileName))
                                {
                                    Log("CSV File zipped", LogType.Both);

                                    try
                                    {
                                        File.Delete(reportAttachmentFile);
                                    }
                                    catch (IOException ioEx)
                                    {
                                        Log("CSV file could not be deleted.");
                                        Log(ioEx.Message + Environment.NewLine + ioEx.StackTrace);
                                    }

                                    reportAttachmentFile = zipFileName;
                                }
                                else
                                {
                                    Log("CSV zipped file was not found!");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("Error when zipping the CSV file.");
                            Log(ex.Message + Environment.NewLine + ex.StackTrace);
                        }
                    }

                    Log(string.Format("Report generated and file attachment created: {0}", Path.GetFileName(reportAttachmentFile)));

                    Organization  organization        = Organizations.GetOrganization(scheduledReportCreator, scheduledReportCreator.OrganizationID);
                    MailMessage   message             = EmailTemplates.GetScheduledReport(LoginUser, scheduledReport);
                    List <string> invalidEmailAddress = new List <string>();
                    scheduledReport.SetRecipientsAndAttachment(message, organization, ref invalidEmailAddress);

                    Log("Email message created", LogType.Public);
                    Log(string.Format("Email Recipients: {0}", string.Join(",", message.To.Select(p => p.Address).ToArray())), LogType.Both);

                    if (invalidEmailAddress.Any())
                    {
                        Log(string.Format("Invalid Email Recipients, they were excluded: {0}", string.Join(",", invalidEmailAddress.ToArray())), LogType.Both);
                    }

                    if (_isDebug == true)
                    {
                        string debugWhiteList = Settings.ReadString("Debug Email White List", "");
                        string debugDomains   = Settings.ReadString("Debug Email Domains", "");
                        string debugAddresses = Settings.ReadString("Debug Email Address", "");

                        if (!string.IsNullOrWhiteSpace(debugWhiteList))
                        {
                            Logs.WriteEvent("DEBUG Whitelist: " + debugWhiteList);
                            string[]           addresses     = debugWhiteList.Replace(';', ',').Split(',');
                            List <MailAddress> mailAddresses = new List <MailAddress>();

                            foreach (MailAddress mailAddress in message.To)
                            {
                                foreach (string address in addresses)
                                {
                                    if (mailAddress.Address.ToLower().IndexOf(address.ToLower()) > -1)
                                    {
                                        mailAddresses.Add(mailAddress);
                                    }
                                }
                            }

                            message.To.Clear();

                            foreach (MailAddress mailAddress in mailAddresses)
                            {
                                message.To.Add(mailAddress);
                            }
                        }
                        else if (!string.IsNullOrWhiteSpace(debugDomains))
                        {
                            Logs.WriteEvent("DEBUG Domains: " + debugDomains);
                            string[]           domains       = debugDomains.Replace(';', ',').Split(',');
                            List <MailAddress> mailAddresses = new List <MailAddress>();

                            foreach (MailAddress mailAddress in message.To)
                            {
                                foreach (string domain in domains)
                                {
                                    if (mailAddress.Address.ToLower().IndexOf(domain.ToLower()) > -1)
                                    {
                                        mailAddresses.Add(mailAddress);
                                    }
                                }
                            }

                            message.To.Clear();

                            foreach (MailAddress mailAddress in mailAddresses)
                            {
                                message.To.Add(mailAddress);
                            }
                        }
                        else if (!string.IsNullOrWhiteSpace(debugAddresses))
                        {
                            Logs.WriteEvent("DEBUG Addresses: " + debugAddresses);
                            message.To.Clear();
                            message.To.Add(debugAddresses.Replace(';', ','));
                        }
                        else
                        {
                            Logs.WriteEvent("NO DEBUG FILTERS SET");
                            return;
                        }

                        if (message.To.Count < 1)
                        {
                            Logs.WriteEvent("No Debug Address specified.");
                            return;
                        }

                        message.Subject = string.Format("[{0}] {1}", Settings.ReadString("Debug Email Subject", "TEST MODE"), message.Subject);
                    }

                    Log("Queueing email(s)", LogType.Public);
                    AddMessage(scheduledReport.OrganizationId, string.Format("Scheduled Report Sent [{0}]", scheduledReport.Id), message, null, new string[] { reportAttachmentFile });
                    scheduledReport.IsSuccessful = true;
                }
                else
                {
                    Log("Report could not be generated and emailed, please contact TeamSupport", LogType.Public);
                }

                if ((ScheduledReportFrequency)scheduledReport.RecurrencyId == ScheduledReportFrequency.Once)
                {
                    scheduledReport.NextRun = null;
                }
                else
                {
                    scheduledReport.SetNextRun(true);
                }

                scheduledReport.RunCount      = scheduledReport.RunCount != null ? (short)(scheduledReport.RunCount + 1) : (short)1;
                scheduledReport.LastRun       = DateTime.UtcNow;
                scheduledReport.LockProcessId = null;
                scheduledReport.Collection.Save();
                Log(string.Format("Set next run to: {0}", scheduledReport.NextRun == null ? "Never" : scheduledReport.NextRun.ToString()), LogType.Both);
            }
            catch (Exception ex)
            {
                Logs.WriteException(ex);
                ExceptionLogs.LogException(LoginUser, ex, _threadPosition.ToString() + " - Report Sender", scheduledReport.Row);
            }
        }