Esempio n. 1
1
 void setCurrentExecution()
 {
     string executionGUID = webBrowser.Document.All[ReportExecution.HtmlId_execution_guid].GetAttribute("value");
     if (_navigation.Navigations.ContainsKey(executionGUID))
     {
         _execution = _navigation.Navigations[executionGUID].Execution;
         _report = _execution.Report;
     }
 }
Esempio n. 2
0
        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);
        }
Esempio n. 3
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);
            }
        }
Esempio n. 4
0
        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);
        }
Esempio n. 5
0
 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);
 }
Esempio n. 6
0
        public void SetNavigation(ReportExecution execution)
        {
            Navigation navigation = null;
            if (!Navigations.ContainsKey(execution.Report.ExecutionGUID))
            {
                navigation = new Navigation() { Execution = execution };
                Navigations.Add(execution.Report.ExecutionGUID, navigation);
            }
            else
            {
                navigation = Navigations[execution.Report.ExecutionGUID];
            }
            //navigation.Origin = 
            navigation.Link = new NavigationLink() { Text = execution.Report.ExecutionName };
            navigation.Link.Href = !string.IsNullOrEmpty(execution.Report.WebUrl) ? execution.Report.WebTempUrl + Path.GetFileName(execution.Report.ResultFilePath) : execution.Report.ResultFilePath;

            //set root report here
            if (execution.RootReport == null) execution.RootReport = execution.Report;
        }
Esempio n. 7
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);
            }
        }
        public void ViewReport(Report report, Repository repository, bool render, string viewGUID, string outputGUID, string originalFilePath)
        {
            Show();
            Text = Path.GetFileNameWithoutExtension(originalFilePath) + " - " + Repository.SealRootProductName + " Report Viewer";
            BringToFront();

            Report previousReport = _report;

            _report = report;
            _report.ExecutionContext = ReportExecutionContext.DesignerReport;
            if (string.IsNullOrEmpty(_report.DisplayName)) _report.DisplayName = Path.GetFileNameWithoutExtension(originalFilePath);
            _report.CurrentViewGUID = _report.ViewGUID;

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

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

            if (previousReport != null && render)
            {
                //force execution
                var parameter = _report.ExecutionView.Parameters.FirstOrDefault(i => i.Name == "force_execution");
                if (parameter != null) parameter.BoolValue = true;

                //set previous data tables and restrictions
                foreach (var model in _report.Models)
                {
                    ReportModel previousModel = previousReport.Models.FirstOrDefault(i => i.GUID == model.GUID);
                    if (previousModel != null)
                    {
                        model.ResultTable = previousModel.ResultTable;
                        model.Restrictions = previousModel.Restrictions;
                        model.RestrictionText = previousModel.RestrictionText;
                        model.Sql = previousModel.Sql;
                    }
                }
                _report.RenderOnly = true;
            }

            _execution = new ReportExecution() { Report = _report };
            _report.InitForExecution();
            _execution.RenderHTMLDisplayForViewer();
            _url = "file:///" + _report.HTMLDisplayFilePath;
            webBrowser.Navigate(_url);
        }
Esempio n. 9
0
        private bool processAction(string action)
        {
            bool cancelNavigation = false;
            try
            {
                switch (action)
                {
                    case ReportExecution.ActionExecuteReport:
                        setCurrentExecution();
                        cancelNavigation = true;
                        _reportDone = false;
                        if (webBrowser.Document != null)
                        {
                            _report.InputRestrictions.Clear();
                            if (HeaderForm != null)
                            {
                                foreach (HtmlElement element in HeaderForm.All)
                                {
                                    if (element.Id != null)
                                    {
                                        _report.InputRestrictions.Add(element.Id, element.TagName.ToLower() == "option" ? element.GetAttribute("selected") : element.GetAttribute("value"));
                                        Debug.WriteLine("{0} {1} {2} {3}", element.Id, element.Name, element.GetAttribute("value"), element.GetAttribute("selected"));
                                    }
                                }
                            }
                        }
                        _report.IsNavigating = false;
                        Execute();
                        break;

                    case ReportExecution.ActionRefreshReport:
                        if (_report.IsExecuting)
                        {
                            cancelNavigation = true;
                            HtmlElement message = webBrowser.Document.All[ReportExecution.HtmlId_processing_message];
                            if (message != null) message.SetAttribute("innerHTML", _report.ExecutionHeader);
                            HtmlElement messages = webBrowser.Document.All[ReportExecution.HtmlId_execution_messages];
                            if (messages != null) messages.SetAttribute("innerHTML", Helper.ToHtml(_report.ExecutionMessages));
                        }
                        else if (!_reportDone)
                        {
                            _navigation.SetNavigation(_execution);
                            cancelNavigation = true;
                            _reportDone = true;
                            _report.IsNavigating = false;
                            _url = "file:///" + _report.HTMLDisplayFilePath;
                            webBrowser.Navigate(_url);
                        }
                        break;

                    case ReportExecution.ActionCancelReport:
                        _execution.Report.LogMessage(_report.Translate("Cancelling report..."));
                        cancelNavigation = true;
                        _report.Cancel = true;
                        break;

                    case ReportExecution.ActionUpdateViewParameter:
                        cancelNavigation = true;
                        _report.UpdateViewParameter(GetFormValue(ReportExecution.HtmlId_parameter_view_id), GetFormValue(ReportExecution.HtmlId_parameter_view_name), GetFormValue(ReportExecution.HtmlId_parameter_view_value));
                        break;

                    case ReportExecution.ActionViewHtmlResult:
                        setCurrentExecution();
                        string resultPath = _execution.GenerateHTMLResult();
                        if (File.Exists(resultPath)) Process.Start(resultPath);
                        cancelNavigation = true;
                        break;

                    case ReportExecution.ActionViewPrintResult:
                        setCurrentExecution();
                        resultPath = _execution.GeneratePrintResult();
                        if (File.Exists(resultPath)) Process.Start(resultPath);
                        cancelNavigation = true;
                        break;

                    case ReportExecution.ActionViewPDFResult:
                        setCurrentExecution();
                        resultPath = _execution.GeneratePDFResult();
                        if (File.Exists(resultPath)) Process.Start(resultPath);
                        cancelNavigation = true;
                        break;

                    case ReportExecution.ActionViewExcelResult:
                        setCurrentExecution();
                        resultPath = _execution.GenerateExcelResult();
                        if (File.Exists(resultPath)) Process.Start(resultPath);
                        cancelNavigation = true;
                        break;

                    case ReportExecution.ActionNavigate:
                        string nav = webBrowser.Document.All[ReportExecution.HtmlId_navigation_id].GetAttribute("value");
                        _execution = _navigation.Navigate(nav, _execution.RootReport);
                        _report = _execution.Report;

                        _canRender = false;
                        cancelNavigation = true;
                        _reportDone = false;
                        Execute();
                        break;

                    case ReportExecution.ActionGetNavigationLinks:
                        cancelNavigation = true;
                        HtmlElement navMenu = webBrowser.Document.All[ReportExecution.HtmlId_navigation_menu];
                        if (navMenu != null) navMenu.SetAttribute("innerHTML", _navigation.GetNavigationLinksHTML(_execution.RootReport));
                        break;
                }
            }
            catch (Exception ex)
            {
                cancelNavigation = true;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return cancelNavigation;
        }
Esempio n. 10
0
        public ActionResult InitExecuteReport(string path, string viewGUID, string outputGUID)
        {
            try
            {
                if (!CheckAuthentication()) return Content(_loginContent);

                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) || !string.IsNullOrEmpty(viewGUID))
                    {
                        if (securityFolder.PublicationType != PublicationType.ExecuteOutput) throw new Exception("Error: outputs cannot be executed");
                    }

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

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

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

                    ReportExecution execution = new ReportExecution() { Report = reportToExecute };
                    Session[reportToExecute.ExecutionGUID] = execution;
                    int index = Request.Url.OriginalString.ToLower().IndexOf("initexecutereport");
                    if (index == -1) throw new Exception("Invalid URL");
                    reportToExecute.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);

                    reportToExecute.InitForExecution();
                    execution.RenderHTMLDisplayForViewer();
                    return GetContentResult(reportToExecute.HTMLDisplayFilePath);
                }
            }
            catch (Exception ex)
            {
                return HandleException(ex);
            }
            return Content("Error: Report file not found.\r\n");
        }
        private bool processAction(string action)
        {
            bool cancelNavigation = false;
            try
            {
                switch (action)
                {
                    case ReportExecution.ActionExecuteReport:
                        cancelNavigation = true;
                        _reportDone = false;
                        if (webBrowser.Document != null)
                        {
                            _report.InputRestrictions.Clear();
                            if (HeaderForm != null)
                            {
                                foreach (HtmlElement element in HeaderForm.All)
                                {
                                    if (element.Id != null)
                                    {
                                        _report.InputRestrictions.Add(element.Id, element.TagName.ToLower() == "option" ? element.GetAttribute("selected") : element.GetAttribute("value"));
                                        Debug.WriteLine("{0} {1} {2} {3}", element.Id, element.Name, element.GetAttribute("value"), element.GetAttribute("selected"));
                                    }
                                }
                            }
                        }
                        _report.IsNavigating = false;
                        Execute();
                        break;

                    case ReportExecution.ActionRefreshReport:
                        if (_report.IsExecuting)
                        {
                            cancelNavigation = true;
                            HtmlElement message = webBrowser.Document.All[ReportExecution.HtmlId_processing_message];
                            if (message != null) message.SetAttribute("innerHTML", _report.ExecutionHeader);
                            HtmlElement messages = webBrowser.Document.All[ReportExecution.HtmlId_execution_messages];
                            if (messages != null) messages.SetAttribute("innerHTML", Helper.ToHtml(_report.ExecutionMessages));
                        }
                        else if (!_reportDone)
                        {
                            //Set last drill path if any
                            if (_report.NavigationLinks.Count > 0) _report.NavigationLinks.Last().Href = _report.ResultFilePath;

                            cancelNavigation = true;
                            _reportDone = true;
                            _report.IsNavigating = false;
                            _url = "file:///" + _report.HTMLDisplayFilePath;
                            webBrowser.Navigate(_url);
                        }
                        break;

                    case ReportExecution.ActionCancelReport:
                        _execution.Report.LogMessage(_report.Translate("Cancelling report..."));
                        cancelNavigation = true;
                        _report.Cancel = true;
                        break;

                    case ReportExecution.ActionUpdateViewParameter:
                        cancelNavigation = true;
                        _report.UpdateViewParameter(GetFormValue(ReportExecution.HtmlId_parameter_view_id), GetFormValue(ReportExecution.HtmlId_parameter_view_name), GetFormValue(ReportExecution.HtmlId_parameter_view_value));
                        break;

                    case ReportExecution.ActionViewHtmlResult:
                        string resultPath = _execution.GenerateHTMLResult();
                        if (File.Exists(resultPath)) Process.Start(resultPath);
                        cancelNavigation = true;
                        break;

                    case ReportExecution.ActionViewPrintResult:
                        resultPath = _execution.GeneratePrintResult();
                        if (File.Exists(resultPath)) Process.Start(resultPath);
                        cancelNavigation = true;
                        break;

                    case ReportExecution.ActionViewPDFResult:
                        resultPath = _execution.GeneratePDFResult();
                        if (File.Exists(resultPath)) Process.Start(resultPath);
                        cancelNavigation = true;
                        break;

                    case ReportExecution.ActionViewExcelResult:
                        resultPath = _execution.GenerateExcelResult();
                        if (File.Exists(resultPath)) Process.Start(resultPath);
                        cancelNavigation = true;
                        break;

                    case ReportExecution.ActionNavigate:
                        string nav = HeaderForm.GetAttribute(ReportExecution.HtmlId_navigation_attribute_name);
                        string sre = HttpUtility.ParseQueryString(nav).Get("sre");
                        bool navigationDone = false;
                        Report lastReport = _report;
                        ReportExecution lastExecution = _execution;
                        string destLabel = "", srcRestriction = "";

                        if (!string.IsNullOrEmpty(sre))
                        {
                            //Sub-Report
                            string path = sre.Replace(Repository.SealRepositoryKeyword, _report.Repository.RepositoryPath);
                            _report = Report.LoadFromFile(path, _report.Repository);
                            _report.NavigationLinks.AddRange(lastReport.NavigationLinks);

                            /*        if (!File.Exists(path))
                                    {
                                        cancelNavigation = true;
                                        break;
                                    }
                                    */
                            int index = 1;
                            while (true)
                            {
                                string res = HttpUtility.ParseQueryString(nav).Get("res" + index.ToString());
                                string val = HttpUtility.ParseQueryString(nav).Get("val" + index.ToString());
                                if (string.IsNullOrEmpty(res) || string.IsNullOrEmpty(val)) break;
                                foreach (var model in _report.Models)
                                {
                                    foreach (var restriction in model.Restrictions.Where(i => i.MetaColumnGUID == res && i.Prompt == PromptType.Prompt))
                                    {
                                        if (restriction.IsEnum)
                                        {
                                            restriction.EnumValues.Clear();
                                            restriction.EnumValues.Add(val);
                                        }
                                        else restriction.Value1 = val;
                                    }
                                }
                                index++;
                            }
                            _canRender = false;
                            _execution = new ReportExecution() { Report = _report };
                            _report.InitForExecution();
                            navigationDone = true;
                        }
                        else
                        {
                            //Drill
                            string src = HttpUtility.ParseQueryString(nav).Get("src");
                            string dst = HttpUtility.ParseQueryString(nav).Get("dst");
                            string val = HttpUtility.ParseQueryString(nav).Get("val");

                            foreach (var model in _report.Models)
                            {
                                ReportElement element = model.Elements.FirstOrDefault(i => i.MetaColumnGUID == src);
                                if (element != null)
                                {
                                    navigationDone = true;
                                    //If the dest element is already in the model, we can remove it
                                    if (model.Elements.Exists(i => i.MetaColumnGUID == dst && i.PivotPosition == element.PivotPosition)) model.Elements.Remove(element);
                                    else element.ChangeColumnGUID(dst);
                                    destLabel = element.DisplayNameElTranslated;
                                    if (val != null)
                                    {
                                        destLabel = "> " + destLabel;
                                        //Add restriction
                                        ReportRestriction restriction = ReportRestriction.CreateReportRestriction();
                                        restriction.Source = model.Source;
                                        restriction.Model = model;
                                        restriction.MetaColumnGUID = src;
                                        restriction.SetDefaults();
                                        restriction.Operator = Operator.Equal;
                                        if (restriction.IsEnum) restriction.EnumValues.Add(val);
                                        else restriction.Value1 = val;
                                        model.Restrictions.Add(restriction);
                                        if (!string.IsNullOrEmpty(model.Restriction)) model.Restriction = string.Format("({0}) AND ", model.Restriction);
                                        model.Restriction += ReportRestriction.kStartRestrictionChar + restriction.GUID + ReportRestriction.kStopRestrictionChar;

                                        srcRestriction = restriction.DisplayText;
                                    }
                                    else
                                    {
                                        destLabel = "< " + destLabel;
                                        var restrictions = model.Restrictions.Where(i => i.MetaColumnGUID == dst).ToList();
                                        foreach (var restr in restrictions)
                                        {
                                            model.Restrictions.Remove(restr);
                                            model.Restriction = model.Restriction.Replace(ReportRestriction.kStartRestrictionChar + restr.GUID + ReportRestriction.kStopRestrictionChar, "1=1");
                                        }
                                    }
                                }
                            }
                        }

                        if (navigationDone)
                        {
                            NavigationLink lastLink = null;
                            if (_report.NavigationLinks.Count == 0)
                            {
                                lastLink = new NavigationLink();
                                _report.NavigationLinks.Add(lastLink);
                            }
                            else lastLink = _report.NavigationLinks.Last();

                            //create HTML result for navigation -> NavigationLinks must have one link to activate the button
                            _report.IsNavigating = true;
                            _canRender = false;

                            if (lastReport != _report)
                            {
                                lastReport.IsNavigating = true;
                                if (lastReport.NavigationLinks.Count == 0) lastReport.NavigationLinks.Add(lastLink);
                            }

                            lastLink.Href = lastExecution.GenerateHTMLResult();
                            if (string.IsNullOrEmpty(lastLink.Text)) lastLink.Text = lastReport.ExecutionName;

                            string linkText = string.Format("{0} {1}", _report.ExecutionName, destLabel);
                            if (!string.IsNullOrEmpty(srcRestriction)) linkText += string.Format(" [{0}]", srcRestriction);
                            _report.NavigationLinks.Add(new NavigationLink() { Href = "#", Text = linkText });
                        }

                        cancelNavigation = true;
                        _reportDone = false;
                        Execute();

                        break;

                    case ReportExecution.ActionGetNavigationLinks:
                        cancelNavigation = true;
                        HtmlElement navMenu = webBrowser.Document.All[ReportExecution.HtmlId_navigation_menu];
                        if (navMenu != null)
                        {
                            string links = "";
                            foreach (var link in _report.NavigationLinks)
                            {
                                links += string.Format("<li><a href='{0}'>{1}</a></li>", link.Href, HttpUtility.HtmlEncode(link.Text));
                            }
                            navMenu.SetAttribute("innerHTML", links);
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                cancelNavigation = true;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return cancelNavigation;
        }
Esempio n. 12
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");
        }