public ScheduledReportViewModel(ScheduledReport report)
        {
            this.FrequencyScheduled = report.FrequencyScheduled;
            this.Recipients         = report.Recipients;
            this.DayOfWeek          = report.DayOfWeek;
            this.DayOfMonth         = report.DayOfMonth;
            DateTime time = DateTime.Today.Add(report.Time.Value);

            this.Time = time.ToString("hh:mm tt");
        }
        public static string GetScheduledReport(RestCommand command, int id)
        {
            ScheduledReport scheduledReport = ScheduledReports.GetScheduledReport(command.LoginUser, id);

            if (scheduledReport.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            return(scheduledReport.GetXml("ScheduledReport", true));
        }
Esempio n. 3
0
 public void Update()
 {
     if (report == null)
     {
         return;
     }
     if (report.reportType == ReportType.SavedPosition)
     {
         if (DefensivePositionsManager.Instance.AdvancedModeEnabled)
         {
             Messages.Message(string.Format("DefPos_msg_advancedSet".Translate(), report.controlIndex + 1, report.numPawnsSavedPosition), MessageTypeDefOf.TaskCompletion);
         }
         else
         {
             Messages.Message(string.Format("DefPos_msg_basicSet".Translate(), report.numPawnsSavedPosition), MessageTypeDefOf.TaskCompletion);
         }
     }
     else if (report.reportType == ReportType.SentToSavedPosition)
     {
         if (report.numPawnsHadNoTargetPosition > 0)
         {
             if (report.numPawnsHadTargetPosition == 0)
             {
                 // no pawns had a valid position
                 Messages.Message("DefPos_msg_noposition".Translate(), MessageTypeDefOf.RejectInput);
             }
             else if (report.numPawnsHadTargetPosition > 0)
             {
                 // some pawns had valid positions
                 Messages.Message(string.Format("DefPos_msg_noposition_partial".Translate(), report.noTargetPositionNames), MessageTypeDefOf.SilentInput);
             }
         }
     }
     else if (report.reportType == ReportType.ClearedPosition)
     {
         if (report.numPawnsHadTargetPosition == 0)
         {
             Messages.Message("DefPos_msg_clearFailed".Translate(), MessageTypeDefOf.RejectInput);
         }
         else
         {
             if (DefensivePositionsManager.Instance.AdvancedModeEnabled)
             {
                 Messages.Message("DefPos_msg_advancedCleared".Translate(report.controlIndex + 1, report.numPawnsHadTargetPosition), MessageTypeDefOf.TaskCompletion);
             }
             else
             {
                 Messages.Message("DefPos_msg_basicCleared".Translate(report.numPawnsHadTargetPosition), MessageTypeDefOf.TaskCompletion);
             }
         }
     }
     report = null;
 }
        private static string GenerateCleanOutputFileName(LoginUser loginUser, ScheduledReport scheduledReport, string reportName, string extension)
        {
            int    organizationId    = scheduledReport.OrganizationId;
            string fileName          = string.Empty;
            string outputImagePath   = TeamSupport.Data.Quarantine.ServiceQ.GetAttachmentPath17(loginUser, organizationId);
            string reportNameForFile = RemoveSpecialCharacters(reportName);

            if (string.IsNullOrEmpty(reportNameForFile))
            {
                reportNameForFile = string.Format("{0}_{1}", scheduledReport.Id, scheduledReport.ReportId);
            }

            fileName = string.Format("{0}\\{1}.{2}", outputImagePath, reportNameForFile, extension);

            return(fileName);
        }
Esempio n. 5
0
        public ScheduledReportProxy GetScheduledReport(int id)
        {
            ScheduledReportProxy proxy = new ScheduledReportProxy();

            try
            {
                ScheduledReport scheduledReport = ScheduledReports.GetScheduledReport(TSAuthentication.GetLoginUser(), id);
                proxy = scheduledReport.GetProxy();
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(TSAuthentication.GetLoginUser(), ex, "ReportService.GetScheduledReport");
            }

            return(proxy);
        }
Esempio n. 6
0
        public int[] DeleteScheduledReports(string reportIDs)
        {
            List <int> result = new List <int>();

            int[] ids = JsonConvert.DeserializeObject <int[]>(reportIDs);
            for (int i = 0; i < ids.Length; i++)
            {
                int             reportID        = ids[i];
                ScheduledReport scheduledReport = ScheduledReports.GetScheduledReport(TSAuthentication.GetLoginUser(), reportID);
                if (scheduledReport != null && scheduledReport.OrganizationId == TSAuthentication.OrganizationID && (TSAuthentication.UserID == scheduledReport.CreatorId || TSAuthentication.IsSystemAdmin))
                {
                    scheduledReport.Delete();
                    scheduledReport.Collection.Save();
                    result.Add(reportID);
                }
            }

            return(result.ToArray());
        }
Esempio n. 7
0
        public void ReportPawnInteraction(ReportType type, Pawn pawn, bool success, int usedControlIndex)
        {
            if (report == null)
            {
                report = new ScheduledReport {
                    reportType = type
                };
            }
            switch (type)
            {
            case ReportType.SavedPosition:
                report.numPawnsSavedPosition++;
                break;

            case ReportType.SentToSavedPosition:
                if (success)
                {
                    report.numPawnsHadTargetPosition++;
                }
                else
                {
                    report.numPawnsHadNoTargetPosition++;
                    var pawnName = pawn.Name.ToStringShort;
                    if (report.noTargetPositionNames == null)
                    {
                        report.noTargetPositionNames += pawnName;
                    }
                    else
                    {
                        report.noTargetPositionNames += ", " + pawnName;
                    }
                }
                break;

            case ReportType.ClearedPosition:
                if (success)
                {
                    report.numPawnsHadTargetPosition++;
                }
                break;
            }
            report.controlIndex = usedControlIndex;
        }
Esempio n. 8
0
        private void AddOrUpdateScheduleJob(ScheduledReport schedule, string editUrl)
        {
            if (schedule.FrequencyScheduled == FrequencyScheduled.Daily)
            {
                var period = string.Format("{0} {1} * * *", schedule.Time.Value.Minutes, schedule.Time.Value.Hours);
                this.AddOrUpdateJob(schedule, editUrl, period);
            }

            if (schedule.FrequencyScheduled == FrequencyScheduled.Weekly)
            {
                var period = string.Format("{0} {1} * * {2}", schedule.Time.Value.Minutes, schedule.Time.Value.Hours, (int)schedule.DayOfWeek);
                this.AddOrUpdateJob(schedule, editUrl, period);
            }

            if (schedule.FrequencyScheduled == FrequencyScheduled.Monthly)
            {
                var period = string.Format("{0} {1} {2} * *", schedule.Time.Value.Minutes, schedule.Time.Value.Hours, (int)schedule.DayOfMonth);
                this.AddOrUpdateJob(schedule, editUrl, period);
            }
        }
        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);
            }
        }
Esempio n. 10
0
        public override void Run()
        {
            ScheduledReports.UnlockThread(LoginUser, (int)_threadPosition);

            while (!IsStopped)
            {
                Logs.WriteHeader("Starting Run");

                try
                {
                    int      waitBeforeLoggingWithoutScheduledReportsDue = 30;
                    DateTime noScheduledReportsDue = DateTime.UtcNow;

                    while (true)
                    {
                        try
                        {
                            if (ServiceStopped)
                            {
                                Logs.WriteHeader("ServiceThread.ServiceStopped");
                                break;
                            }

                            if (IsStopped)
                            {
                                Logs.WriteHeader("IsStopped");
                                break;
                            }

                            ScheduledReport scheduledReport = GetNextScheduledReport(LoginUser.ConnectionString, (int)_threadPosition, Logs);

                            if (scheduledReport != null)
                            {
                                string publicLogPath = TeamSupport.Data.Quarantine.ServiceQ.GetAttachmentPath16(LoginUser, scheduledReport.OrganizationId, scheduledReport.FilePathID);
                                _publicLog = new ReportSenderPublicLog(publicLogPath, scheduledReport.Id, scheduledReport.OrganizationId);
                                Log(string.Format("Date and times used for this log entries are in TimeZone {0}", _publicLog.OrganizationTimeZoneInfo.DisplayName), LogType.Public);
                                QueueEmail(scheduledReport);
                                noScheduledReportsDue = DateTime.UtcNow;
                            }
                            else
                            {
                                if (DateTime.UtcNow.Subtract(noScheduledReportsDue).Minutes >= waitBeforeLoggingWithoutScheduledReportsDue)
                                {
                                    Log(string.Format("No scheduled reports due found in the last {0} minutes", waitBeforeLoggingWithoutScheduledReportsDue));
                                    noScheduledReportsDue = DateTime.UtcNow;
                                }

                                Thread.Sleep(10000);
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("Error sending report email - Ending Thread");
                            Logs.WriteException(ex);
                            ExceptionLogs.LogException(LoginUser, ex, "ReportSender", "Error sending report email");
                        }
                        finally
                        {
                            UpdateHealth();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logs.WriteException(ex);
                }
                finally
                {
                    Logs.WriteHeader("Exiting.");
                }
            }
        }
Esempio n. 11
0
        private string GetReportChartFile(LoginUser scheduledReportCreator, ScheduledReport scheduledReport, Report report)
        {
            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            string chartOptionsFilesDirectory = "ChartOptionsFiles";
            string chartOptionsFilesPath      = Path.Combine(path, chartOptionsFilesDirectory);

            if (!Directory.Exists(chartOptionsFilesPath))
            {
                Directory.CreateDirectory(chartOptionsFilesPath);
            }

            DataTable  dataTable       = GetReportTableAll(scheduledReportCreator, report, "", false, true, false);
            ReportItem reportItem      = new ReportItem(report, true);
            string     reportData      = TeamSupport.Data.BusinessObjects.Reporting.SummaryReportSql.GetHubChartData(scheduledReportCreator, report);
            string     optionsFileData = GetChartOptionsAndData(report.ReportDef, reportData);

            string optionsFile = string.Format("{0}_{1}.js", scheduledReport.Id, scheduledReport.ReportId);

            optionsFile = Path.Combine(chartOptionsFilesPath, optionsFile);
            Log("Writting chart options to: " + optionsFile);
            File.WriteAllText(optionsFile, optionsFileData);
            string outputImage = GenerateCleanOutputFileName(_loginUser, scheduledReport, report.Name, "png");

            Log("outputImage: " + outputImage);

            //Create Batch File
            string batchFile        = string.Format("thread_{0}.bat", _threadPosition);
            string batchFileCommand = Path.GetPathRoot(System.Reflection.Assembly.GetEntryAssembly().Location) + Environment.NewLine;

            if (!string.IsNullOrEmpty(batchFileCommand))
            {
                batchFileCommand = batchFileCommand.Replace(@"\", "");
            }

            batchFileCommand += "chdir " + Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + Environment.NewLine;
            batchFileCommand += string.Format(PHANTOMJSCOMMAND, optionsFile, outputImage);
            string batchFileFullPath = Path.Combine(path, batchFile);

            Log("batchFile: " + batchFileFullPath);

            File.WriteAllText(batchFileFullPath, batchFileCommand);
            Log("Command written: " + batchFileCommand);

            if (File.Exists(outputImage))
            {
                File.Delete(outputImage);
                Log("Old chart image deleted.");
            }

            bool commandIsSuccessful = ExecuteCommand(batchFileFullPath);

            if (!commandIsSuccessful)
            {
                outputImage = string.Empty;
            }
            else if (!File.Exists(outputImage))
            {
                Log("outputImage not created/found");
                outputImage = string.Empty;
            }

            return(outputImage);
        }
Esempio n. 12
0
 private void AddOrUpdateJob(ScheduledReport schedule, string editUrl, string period)
 {
     RecurringJob.AddOrUpdate(schedule.ScheduleID.ToString(), () => _scheduledEmailManager.BuildScheduledEmail(schedule.Query.Name, editUrl, schedule.Recipients, schedule.Query.QueryID), period);
 }
Esempio n. 13
0
        public async Task <ActionResult> Schedule([FromBody] ScheduledReportViewModel model)
        {
            var query = this.db.Queries
                        .Include(q => q.DatabaseConnection)
                        .FirstOrDefault(q => q.QueryID == model.QueryID);

            if (query != null && CanUserAccessDatabase(query.DatabaseConnection))
            {
                if (model.FrequencyScheduled == FrequencyScheduled.None)
                {
                    // Remove schedule
                    var schedule = await this.db.ScheduledReports.FirstOrDefaultAsync(m => m.ScheduleID == model.QueryID);

                    if (schedule != null)
                    {
                        this.db.ScheduledReports.Remove(schedule);
                        await this.db.SaveChangesAsync();
                    }

                    // Remove schedule job
                    this.RemoveScheduleJob(model.QueryID.ToString());

                    return(StatusCode((int)HttpStatusCode.OK));
                }

                if (model.FrequencyScheduled == FrequencyScheduled.Monthly &&
                    (!model.DayOfMonth.HasValue || model.DayOfMonth < 1 || model.DayOfMonth > 32))
                {
                    return(BadRequest("Select the correct Day of the Month"));
                }

                DateTime dateValue;
                if (!DateTime.TryParseExact(model.Time, "h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
                {
                    return(BadRequest("Select the correct Time"));
                }

                Regex regex = new Regex(@"^(?!.*<[^>]+>).*");
                if (!regex.IsMatch(model.Recipients))
                {
                    return(BadRequest("No html tags allowed"));
                }

                var recipients = this.RecipientsValidation(model.Recipients);
                if (string.IsNullOrEmpty(recipients))
                {
                    return(BadRequest("Wrong 'Recipients' format. Only e-mails are separated by comma"));
                }

                ScheduledReport scheduleReport = await this.db.ScheduledReports.FirstOrDefaultAsync(m => m.ScheduleID == model.QueryID);

                if (scheduleReport == null)
                {
                    scheduleReport = new ScheduledReport
                    {
                        FrequencyScheduled = model.FrequencyScheduled,
                        Time       = dateValue.TimeOfDay,
                        DayOfWeek  = model.DayOfWeek,
                        DayOfMonth = model.DayOfMonth,
                        Recipients = recipients,
                        Query      = query
                    };

                    this.db.ScheduledReports.Add(scheduleReport);
                }
                else
                {
                    scheduleReport.FrequencyScheduled = model.FrequencyScheduled;
                    scheduleReport.Time       = dateValue.TimeOfDay;
                    scheduleReport.DayOfWeek  = model.DayOfWeek;
                    scheduleReport.DayOfMonth = model.DayOfMonth;
                    scheduleReport.Recipients = recipients;

                    this.db.Entry(scheduleReport).State = EntityState.Modified;
                }

                await this.db.SaveChangesAsync();

                this.AddOrUpdateScheduleTask(scheduleReport);

                return(StatusCode((int)HttpStatusCode.OK));
            }

            return(NotFound());
        }
Esempio n. 14
0
        public int SaveScheduledReport(int scheduledReportId,
                                       int reportId,
                                       string emailSubject,
                                       string emailBody,
                                       string emailAddresses,
                                       Object startOn,
                                       ScheduledReportFrequency frequency,
                                       int every,
                                       int weekday,
                                       int dayOfMonth,
                                       bool isActive)
        {
            try
            {
                LoginUser        loginUser        = TSAuthentication.GetLoginUser();
                ScheduledReports scheduledReports = new ScheduledReports(loginUser);

                if (scheduledReportId == 0)
                {
                    ScheduledReport scheduledReport = scheduledReports.AddNewScheduledReport();
                    scheduledReport.ReportId        = reportId;
                    scheduledReport.EmailSubject    = emailSubject;
                    scheduledReport.EmailBody       = emailBody;
                    scheduledReport.EmailRecipients = emailAddresses;
                    scheduledReport.OrganizationId  = TSAuthentication.OrganizationID;
                    scheduledReport.IsActive        = true;
                    scheduledReport.StartDate       = (DateTime)startOn;
                    scheduledReport.RecurrencyId    = (byte)frequency;
                    scheduledReport.Every           = (byte)every;
                    scheduledReport.Weekday         = (byte)weekday;
                    scheduledReport.Monthday        = (byte)dayOfMonth;
                    scheduledReport.IsActive        = isActive;
                    scheduledReport.FilePathID      = 3;

                    //This needs to be set before SetNextRun because that one needs it to get the timezone to use.
                    scheduledReport.CreatorId = loginUser.UserID;

                    if (isActive)
                    {
                        scheduledReport.SetNextRun();
                    }
                    else
                    {
                        scheduledReport.NextRun = null;
                    }

                    scheduledReport.Collection.Save();

                    scheduledReportId = scheduledReport.Id;
                }
                else
                {
                    scheduledReports.LoadById(scheduledReportId);

                    if (scheduledReports != null && scheduledReports.Any())
                    {
                        scheduledReports[0].EmailSubject    = emailSubject;
                        scheduledReports[0].EmailBody       = emailBody;
                        scheduledReports[0].EmailRecipients = emailAddresses;
                        scheduledReports[0].IsActive        = true;
                        try
                        { scheduledReports[0].StartDate = (DateTime)startOn; }
                        catch (Exception ex) { }
                        scheduledReports[0].RecurrencyId = (byte)frequency;
                        scheduledReports[0].Every        = (byte)every;
                        scheduledReports[0].Weekday      = (byte)weekday;
                        scheduledReports[0].Monthday     = (byte)dayOfMonth;
                        scheduledReports[0].IsActive     = isActive;

                        if (isActive)
                        {
                            scheduledReports[0].SetNextRun();
                        }
                        else
                        {
                            scheduledReports[0].NextRun = null;
                        }

                        scheduledReports[0].ModifierId = loginUser.UserID;
                        scheduledReports.Save();
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(TSAuthentication.GetLoginUser(), ex, "ReportService.SaveScheduledReport");
            }

            return(scheduledReportId);
        }
Esempio n. 15
0
        private static string GetReportDataToFile(LoginUser scheduledReportCreator, Report report, ScheduledReport scheduledReport, string sortField, bool isDesc, bool useUserFilter, Logs logs = null)
        {
            if (logs != null)
            {
                logs.WriteEvent("GetReportTableAll");
            }

            DataTable dataTable = GetReportTableAll(scheduledReportCreator, report, sortField, isDesc, useUserFilter, false);

            dataTable = DataUtils.DecodeDataTable(dataTable);
            dataTable = DataUtils.StripHtmlDataTable(dataTable);

            if (logs != null)
            {
                logs.WriteEventFormat("dataTable created with {0} rows and {1} columns", dataTable.Rows.Count, dataTable.Columns.Count);
            }

            try
            {
                dynamic settings = null;
                object  o        = report.Row["Settings"];

                if (o != null && o != DBNull.Value && !string.IsNullOrEmpty(o.ToString()))
                {
                    settings = JObject.Parse(o.ToString());
                }

                if (settings != null)
                {
                    if (settings["Columns"] != null)
                    {
                        List <string> reportColumnNames = new List <string>();
                        for (int i = 0; i < settings["Columns"].Count; i++)
                        {
                            reportColumnNames.Add(settings["Columns"][i]["id"].ToString());
                        }

                        int index = 0;
                        foreach (string columnName in reportColumnNames)
                        {
                            DataColumn column = dataTable.Columns[columnName];
                            if (column != null)
                            {
                                column.SetOrdinal(index);
                                index++;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logs.WriteEventFormat("Exception when setting the column order by user settings. {0}", ex.Message);
            }

            StringBuilder stringBuilder = new StringBuilder();

            IEnumerable <string> columnNames = dataTable.Columns.Cast <DataColumn>().Select(column => column.ColumnName);

            stringBuilder.AppendLine(string.Join(",", columnNames));

            foreach (DataRow row in dataTable.Rows)
            {
                IEnumerable <string> fields = row.ItemArray.Select(field => string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
                stringBuilder.AppendLine(string.Join(",", fields));
            }

            string fileName = GenerateCleanOutputFileName(scheduledReportCreator, scheduledReport, report.Name, "csv");

            File.WriteAllText(fileName, stringBuilder.ToString());

            if (logs != null)
            {
                logs.WriteEvent("File.WriteAllText completed");
            }

            return(fileName);
        }
Esempio n. 16
0
        private void AddOrUpdateScheduleTask(ScheduledReport scheduledReport)
        {
            string editUrl = Url.Action("Details", "Queries", new { id = scheduledReport.Query.QueryID }, Request.Scheme);

            AddOrUpdateScheduleJob(scheduledReport, editUrl);
        }
Esempio n. 17
0
 public static void GetLogPath1(ScheduledReport scheduledReport, out string logPath, out string fileName)
 {
     logPath  = AttachmentPath.GetPath(scheduledReport.Collection.LoginUser, scheduledReport.OrganizationId, AttachmentPath.Folder.ScheduledReportsLogs, scheduledReport.FilePathID);
     fileName = scheduledReport.Id.ToString() + ".txt";
     logPath  = Path.Combine(logPath, fileName);
 }