public void CreationAndExecution()
        {
            var repository = Repository.Create();
            Report report = Report.Create(repository);
            report.DisplayName = "Sample Report";
            var source = report.Sources.FirstOrDefault(i => i.Name.StartsWith("Northwind"));
            source.MetaData.Tables.Clear();
            //Update the data source with a new table
            var table = source.AddTable(true);
            table.DynamicColumns = true;
            table.Name = "products";
            //Instead of the name, could be a direct SQL statement:
            //table.Sql = "select * from products";
            table.Refresh();

            //Set the source of the default model
            report.Models[0].SourceGUID = source.GUID;
            //Add elements to the reports model
            foreach (var column in table.Columns)
            {
                var element = ReportElement.Create();
                element.MetaColumnGUID = column.GUID;
                element.Name = column.Name;
                element.PivotPosition = PivotPosition.Row;
                element.Source = source;
                report.Models[0].Elements.Add(element);
            }

            //Add a restriction to the model
            var restriction = ReportRestriction.CreateReportRestriction();
            restriction.Source = report.Models[0].Source;
            restriction.Model = report.Models[0];
            restriction.MetaColumnGUID = table.Columns.FirstOrDefault(i => i.Name == "products.ProductName").GUID;
            restriction.SetDefaults();
            restriction.Operator = Operator.Contains;
            restriction.Value1 = "er";
            report.Models[0].Restrictions.Add(restriction);
            //Set the restriction text
            if (!string.IsNullOrEmpty(report.Models[0].Restriction)) report.Models[0].Restriction = string.Format("({0}) AND ", report.Models[0].Restriction);
            report.Models[0].Restriction += ReportRestriction.kStartRestrictionChar + restriction.GUID + ReportRestriction.kStopRestrictionChar;

            //Then execute it
            ReportExecution execution = new ReportExecution() { Report = report };
            execution.Execute();
            while (report.Status != ReportStatus.Executed) System.Threading.Thread.Sleep(100);
            string result = execution.GenerateHTMLResult();
            Process.Start(result);
        }
Example #2
0
        public static void ExecuteReportSchedule(string scheduleGUID)
        {
            try
            {
                Task task;
                Report report;
                ReportSchedule schedule;
                InitReportSchedule(scheduleGUID, out task, out report, out schedule);
                Helper.WriteLogEntryScheduler(EventLogEntryType.Information, "Starting execution of schedule '{0} ({1})'.\r\nReport '{2}'\r\nUser '{3}\\{4}'", schedule.Name, scheduleGUID, report.FilePath, Environment.UserDomainName, Environment.UserName);
                int retries = schedule.ErrorNumberOfRetries + 1;
                while (--retries >= 0)
                {
                    if (report == null || schedule == null || task == null)
                    {
                        InitReportSchedule(scheduleGUID, out task, out report, out schedule);
                    }
                    ReportExecution reportExecution = new ReportExecution() { Report = report };
                    report.ExecutionContext = ReportExecutionContext.TaskScheduler;
                    if (!schedule.IsTasksSchedule)
                    {
                        report.OutputToExecute = schedule.Output;
                        if (report.OutputToExecute == null) throw new Exception("No output defined for the schedule");
                        report.CurrentViewGUID = report.OutputToExecute.ViewGUID;
                    }
                    else
                    {
                        report.CurrentViewGUID = report.ViewGUID;
                    }
                    reportExecution.Execute();
                    schedule.SynchronizeTask();

                    while (report.IsExecuting)
                    {
                        Thread.Sleep(100);
                    }
                    if (report.HasErrors)
                    {
                        string errorMessage = string.Format("Error: Schedule '{0}' has been executed with errors.\r\nReport '{1}'\r\n{2}\r\n", schedule.Name, report.FilePath, report.ExecutionErrors);
                        if (schedule.ErrorNumberOfRetries > 0)
                        {
                            if (schedule.ErrorNumberOfRetries != retries) errorMessage += string.Format("Retry number {0} of {1}.\r\n", schedule.ErrorNumberOfRetries - retries, schedule.ErrorNumberOfRetries, report.ExecutionMessages);
                            else errorMessage += string.Format("The schedule will have up to {0} retries every {1} minute(s).\r\n", schedule.ErrorNumberOfRetries, schedule.ErrorMinutesBetweenRetries);
                        }
                        errorMessage += "\r\n" + report.ExecutionMessages;
                        Helper.WriteLogEntryScheduler(EventLogEntryType.Error, errorMessage);
                        if (!string.IsNullOrEmpty(schedule.ErrorEmailTo) &&
                            (schedule.ErrorEmailSendMode == FailoverEmailMode.All ||
                            (schedule.ErrorEmailSendMode == FailoverEmailMode.First && retries == schedule.ErrorNumberOfRetries) ||
                            (schedule.ErrorEmailSendMode == FailoverEmailMode.Last && retries == 0))
                            )
                        {
                            //error email
                            string subject = Helper.IfNullOrEmpty(schedule.ErrorEmailSubject, string.Format("Report Execution Error '{0}'", report.ExecutionName));
                            sendEmail(report, schedule.ErrorEmailTo, schedule.ErrorEmailFrom, subject, errorMessage);
                        }

                        if (retries > 0)
                        {
                            //wait a while before retrying
                            string message = string.Format("Retrying execution of schedule '{0}' of report '{1}'.\r\nRetry number {2} of {3}.", schedule.Name, report.FilePath, schedule.ErrorNumberOfRetries - retries + 1, schedule.ErrorNumberOfRetries);
                            var newDate = DateTime.Now.AddMinutes(schedule.ErrorMinutesBetweenRetries);
                            report = null;
                            schedule = null;
                            task = null;
                            while (DateTime.Now < newDate) Thread.Sleep(1000); //Future: waiting for a notification to die...
                            Helper.WriteLogEntryScheduler(EventLogEntryType.Information, message);
                        }
                    }
                    else
                    {
                        Helper.WriteLogEntryScheduler(EventLogEntryType.Information, "Schedule '{0}' has been executed\r\nReport '{1}\r\n{2}", schedule.Name, report.FilePath, report.ExecutionMessages);
                        if (!string.IsNullOrEmpty(schedule.NotificationEmailTo) && !report.Cancel)
                        {
                            //information email
                            string subject = Helper.IfNullOrEmpty(schedule.NotificationEmailSubject, string.Format("Report Execution '{0}'", report.ExecutionName));
                            string body = Helper.IfNullOrEmpty(schedule.NotificationEmailBody, "The report has been executed successfully.");
                            sendEmail(report, schedule.NotificationEmailTo, schedule.NotificationEmailFrom, subject, body);
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Helper.WriteLogEntryScheduler(EventLogEntryType.Error, "Error got when executing schedule '{0}':\r\n{1}\r\n\r\n{2}", scheduleGUID, ex.Message, ex.StackTrace);
            }
        }
        public void ExecutionWithExternalDataTables()
        {
            //Get Data Table from another source
            string sql = @"
            SELECT DISTINCT
              DateSerial(DatePart('yyyy',[Orders.OrderDate]), 1, 1) AS C0,
              Products.CategoryID AS C1,
              Customers.Country AS C2,
              999999 AS C3
            FROM
            (Products INNER JOIN
            ([Order Details] INNER JOIN
            (Orders INNER JOIN Customers
             ON Customers.CustomerID = Orders.CustomerID)
             ON Orders.OrderID = [Order Details].OrderID)
             ON Products.ProductID = [Order Details].ProductID)
            ";

            var connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ProgramData\Seal Report Repository\Databases\Northwind.mdb;Persist Security Info=False");
            var command = connection.CreateCommand();
            command.CommandText = sql;
            var adapter = new OleDbDataAdapter(command);
            var newTable = new DataTable();
            adapter.Fill(newTable);

            //Data table must have the same column definition as the one defined in the report
            var repository = Repository.Create();
            var report = Report.LoadFromFile(@"C:\ProgramData\Seal Report Repository\Reports\Samples\03-Cross tab - Simple chart (Orders).srex", repository);

            //Set data table to the report model (here there is only 1 model)
            report.Models[0].ResultTable = newTable;
            //Set report in Render only mode so the Result table is not loaded during the execution
            report.RenderOnly = true;
            //Note that if model.ResultTable is null, the table will be loaded anyway

            var execution = new ReportExecution() { Report = report };
            execution.Execute();
            while (report.Status != ReportStatus.Executed) System.Threading.Thread.Sleep(100);
            string result = execution.GenerateHTMLResult();
            Process.Start(result);
        }
 public void SimpleExecution()
 {
     //Simple load and report execution and generation in a HTML Result file
     Repository repository = Repository.Create();
     Report report = Report.LoadFromFile(@"C:\ProgramData\Seal Report Repository\Reports\Search - Orders.srex", repository);
     ReportExecution execution = new ReportExecution() { Report = report };
     execution.Execute();
     while (report.Status != ReportStatus.Executed) System.Threading.Thread.Sleep(100);
     string result = execution.GenerateHTMLResult();
     Process.Start(result);
 }
Example #5
0
        void checkExecutions(ExecutionLogInterface log, string folder, Repository repository, ref int count, ref int errorCount, StringBuilder errorSummary)
        {
            log.Log("Checking folder '{0}'", folder);
            foreach (string reportPath in Directory.GetFiles(folder, "*." + Repository.SealReportFileExtension))
            {
                try
                {
                    if (log.IsJobCancelled()) return;
                    log.Log("Checking report '{0}'", reportPath);
                    count++;
                    Report report = Report.LoadFromFile(reportPath, repository);
                    report.CheckingExecution = true;
                    if (report.Tasks.Count > 0) log.Log("Warning: Report Task executions are skipped.");
                    foreach (ReportView view in report.Views)
                    {
                        if (log.IsJobCancelled()) return;
                        log.Log("Running report with view '{0}'", view.Name);
                        try
                        {
                            report.CurrentViewGUID = view.GUID;
                            ReportExecution reportExecution = new ReportExecution() { Report = report };
                            reportExecution.Execute();

                            int cnt = 120;
                            while (--cnt > 0 && report.IsExecuting && !log.IsJobCancelled())
                            {
                                Thread.Sleep(1000);
                            }

                            if (report.IsExecuting)
                            {
                                if (cnt == 0) log.Log("Warning: Report is running for more than 2 minutes. Cancelling the execution...");
                                report.CancelExecution();
                            }

                            if (!string.IsNullOrEmpty(report.ExecutionErrors)) throw new Exception(report.ExecutionErrors);
                            if (!string.IsNullOrEmpty(report.ExecutionView.Error)) throw new Exception(report.ExecutionView.Error);

                            report.RenderOnly = true;
                        }
                        catch (Exception ex)
                        {
                            errorCount++;
                            log.LogRaw("ERROR\r\n");
                            log.Log(ex.Message);
                            errorSummary.AppendFormat("\r\nReport '{0}' View '{1}': {2}\r\n", reportPath, view.Name, ex.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    errorCount++;
                    log.LogRaw("ERROR\r\n");
                    log.Log(ex.Message);
                    errorSummary.AppendFormat("\r\nReport '{0}': {1}\r\n", reportPath, ex.Message);
                }
            }
            log.LogRaw("\r\n");

            foreach (string subFolder in Directory.GetDirectories(folder))
            {
                if (log.IsJobCancelled()) return;
                checkExecutions(log, subFolder, repository, ref count, ref errorCount, errorSummary);
            }
        }
Example #6
0
        public ActionResult SWIExecuteReport(string path, string viewGUID, string outputGUID, string format)
        {
            try
            {
                if (WebUser == null || !WebUser.IsAuthenticated) throw new Exception("Error: user is not authenticated");
                if (string.IsNullOrEmpty(path)) throw new Exception("Error: path must be supplied");

                string filePath = Repository.ReportsFolder + path;
                if (System.IO.File.Exists(filePath))
                {
                    SecurityFolder securityFolder = WebUser.FindSecurityFolder(Path.GetDirectoryName(filePath));
                    if (securityFolder == null) throw new Exception("Error: this folder is not published");
                    if (!string.IsNullOrEmpty(outputGUID))
                    {
                        if (securityFolder.PublicationType != PublicationType.ExecuteOutput) throw new Exception("Error: outputs cannot be executed");
                    }

                    Repository repository = Repository.CreateFast();
                    Report report = Report.LoadFromFile(filePath, repository);
                    report.ExecutionContext = ReportExecutionContext.WebReport;
                    report.SecurityContext = WebUser;
                    report.CurrentViewGUID = report.ViewGUID;

                    //Init Pre Input restrictions
                    report.PreInputRestrictions.Clear();
                    foreach (string key in Request.Form.Keys) report.PreInputRestrictions.Add(key, Request.Form[key]);
                    foreach (string key in Request.QueryString.Keys) report.PreInputRestrictions.Add(key, Request.QueryString[key]);

                    //execute to output
                    if (!string.IsNullOrEmpty(outputGUID))
                    {
                        report.OutputToExecute = report.Outputs.FirstOrDefault(i => i.GUID == outputGUID);
                        report.ExecutionContext = ReportExecutionContext.WebOutput;
                        if (report.OutputToExecute != null) report.CurrentViewGUID = report.OutputToExecute.ViewGUID;
                    }

                    //execute with custom view
                    if (!string.IsNullOrEmpty(viewGUID)) report.CurrentViewGUID = viewGUID;

                    ReportExecution execution = new ReportExecution() { Report = report };

                    Session[report.ExecutionGUID] = execution;

                    int index = Request.Url.OriginalString.ToLower().IndexOf("swiexecutereport");
                    if (index == -1) throw new Exception("Invalid URL");
                    report.WebUrl = Request.Url.OriginalString.Substring(0, index);
                    repository.WebPublishFolder = Path.Combine(Request.PhysicalApplicationPath, "temp");
                    repository.WebApplicationPath = Path.Combine(Request.PhysicalApplicationPath, "bin");
                    if (!Directory.Exists(repository.WebPublishFolder)) Directory.CreateDirectory(repository.WebPublishFolder);
                    FileHelper.PurgeTempDirectory(repository.WebPublishFolder);

                    report.InitForExecution();

                    initInputRestrictions(report);

                    execution.Execute();
                    while (report.Status != ReportStatus.Executed) System.Threading.Thread.Sleep(100);

                    string result = "";
                    if (!string.IsNullOrEmpty(outputGUID))
                    {
                        //Copy the result output to temp
                        result = publishReportResult(report);
                    }
                    else {
                        string fileResult = "";
                        if (string.IsNullOrEmpty(format)) format = "html";
                        if (format.ToLower() == "print") fileResult = execution.GeneratePrintResult();
                        else if (format.ToLower() == "pdf") fileResult = execution.GeneratePDFResult();
                        else if (format.ToLower() == "excel") fileResult = execution.GenerateExcelResult();
                        else fileResult = execution.GenerateHTMLResult();
                        result = execution.Report.WebTempUrl + Path.GetFileName(fileResult);
                    }

                    return Json(new { url = result });
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = ex.Message });
            }
            return Content("Error: Report file not found.\r\n");
        }