Пример #1
0
        public ActionResult ActionGetEnumValues(string execution_guid, string enum_id, string filter)
        {
            WriteDebug("ActionGetEnumValues");
            string result = "";

            try
            {
                if (!CheckAuthentication())
                {
                    return(Content(_loginContent));
                }

                if (!string.IsNullOrEmpty(execution_guid) && Session[execution_guid] is ReportExecution)
                {
                    ReportExecution execution = Session[execution_guid] as ReportExecution;
                    result = execution.GetEnumValues(enum_id, filter);
                }
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }
            return(Json(result));
        }
Пример #2
0
        public ActionResult OutputResult(string execution_guid)
        {
            WriteDebug("OutputResult");
            try
            {
                if (!CheckAuthentication())
                {
                    return(Content(_loginContent));
                }

                if (!string.IsNullOrEmpty(execution_guid) && Session[execution_guid] is ReportExecution)
                {
                    ReportExecution execution = Session[execution_guid] as ReportExecution;
                    Report          report    = execution.Report;
                    return(getFileResult(report.ResultFilePath, report));
                }
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }

            return(Content(_noReportFoundMessage));
        }
Пример #3
0
        public ActionResult HtmlResult(string execution_guid)
        {
            WriteDebug("HtmlResult");
            try
            {
                if (!CheckAuthentication())
                {
                    return(Content(_loginContent));
                }

                if (!string.IsNullOrEmpty(execution_guid) && Session[execution_guid] is ReportExecution)
                {
                    ReportExecution execution  = Session[execution_guid] as ReportExecution;
                    string          resultPath = execution.GenerateHTMLResult();
                    return(getFileResult(resultPath, execution.Report));
                }
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }

            return(Content(_noReportFoundMessage));
        }
Пример #4
0
        public ActionResult ActionExecuteReport(string execution_guid)
        {
            WriteDebug("ActionExecuteReport");
            try
            {
                if (!CheckAuthentication())
                {
                    return(Content(_loginContent));
                }

                if (!string.IsNullOrEmpty(execution_guid) && Session[execution_guid] is ReportExecution)
                {
                    ReportExecution execution = Session[execution_guid] as ReportExecution;
                    Report          report    = execution.Report;
                    report.IsMobileDevice = Request.Browser.IsMobileDevice;

                    Helper.WriteLogEntryWeb(EventLogEntryType.Information, Request, WebUser, "Starting report '{0}'", report.FilePath);
                    initInputRestrictions(report);
                    while (execution.IsConvertingToExcel)
                    {
                        Thread.Sleep(100);
                    }
                    report.IsNavigating = false;
                    execution.Execute();
                    return(null);
                }
                else
                {
                    throw new Exception(string.Format("No report execution found in session '{0}'", execution_guid));
                }
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }
        }
        private void ExecuteThread(object param)
        {
            var schedule = param as SealSchedule;
            var report   = getScheduledReport(schedule);

            if (report != null)
            {
                var reportSchedule = getReportSchedule(report, schedule.GUID);
                ReportExecution.ExecuteReportSchedule(schedule.GUID, report, reportSchedule);

                if (File.GetLastWriteTime(schedule.FilePath) == schedule.LastModification)
                {
                    schedule.CalculateNextExecution();
                    SaveSchedule(schedule);
                    schedule.BeingExecuted = false;
                }
                else
                {
                    //Schedule modified from another editor...
                    schedule.BeingExecuted = false;
                    loadSchedules();
                }
            }
        }
Пример #6
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                try
                {
                    //Set repository path
                    IConfigurationRoot configuration = new ConfigurationBuilder()
                                                       .AddJsonFile("appsettings.json")
                                                       .Build();
                    var section = configuration.GetSection(Repository.SealConfigurationSectionKeyword);
                    if (section != null)
                    {
                        Repository.RepositoryConfigurationPath = configuration.GetSection(Repository.SealConfigurationSectionKeyword)[Repository.SealConfigurationRepositoryPathKeyword];
                    }

                    ReportExecution.ExecuteReportSchedule(args[0].ToString());
                }
                catch (Exception ex)
                {
                    Helper.WriteLogEntryScheduler(EventLogEntryType.Error, ex.Message);
                }
            }
        }
Пример #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);
            }
        }
Пример #8
0
        private bool processAction(string action)
        {
            bool cancelNavigation = false;

            try
            {
                switch (action)
                {
                case ReportExecution.ActionExecuteReport:
                    setCurrentExecution();
                    cancelNavigation = true;
                    _reportDone      = false;
                    if (webBrowser.Document != null)
                    {
                        initFromForm(HeaderForm);
                    }
                    _report.ExecutionTriggerView = null;
                    _report.IsNavigating         = false;
                    Execute();
                    break;

                case ReportExecution.ActionRefreshReport:
                    if (_report.IsExecuting)
                    {
                        cancelNavigation = true;
                        HtmlElement messages = webBrowser.Document.All[ReportExecution.HtmlId_execution_messages];
                        if (_report.ExecutionView.GetValue("messages_mode") != "disabled" && messages != null)
                        {
                            messages.SetAttribute("innerHTML", Helper.ToHtml(_report.ExecutionMessages));
                            if (_report.ExecutionView.GetBoolValue(Parameter.AutoScrollParameter))
                            {
                                messages.ScrollTop = messages.ScrollRectangle.Height;
                            }
                        }
                        setProgressBarInformation(ReportExecution.HtmlId_progress_bar, _report.ExecutionProgression, _report.ExecutionProgressionMessage);
                        setProgressBarInformation(ReportExecution.HtmlId_progress_bar_tasks, _report.ExecutionProgressionTasks, _report.ExecutionProgressionTasksMessage);
                        setProgressBarInformation(ReportExecution.HtmlId_progress_bar_models, _report.ExecutionProgressionModels, _report.ExecutionProgressionModelsMessage);
                    }
                    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.ActionViewCSVResult:
                    setCurrentExecution();
                    resultPath = _execution.GenerateCSVResult();
                    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");
                    var    parameters = HttpUtility.ParseQueryString(webBrowser.Document.All[ReportExecution.HtmlId_navigation_parameters].GetAttribute("value"));

                    if (nav.StartsWith(NavigationLink.FileDownloadPrefix))     //File download
                    {
                        var filePath = _navigation.NavigateScript(nav, _execution.Report, parameters);
                        if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
                        {
                            Process.Start(filePath);
                        }
                        else
                        {
                            throw new Exception(string.Format("Invalid file path got from the navigation script: '{0}'", filePath));
                        }
                        cancelNavigation = true;
                    }
                    else if (nav.StartsWith(NavigationLink.ReportScriptPrefix))     //Report Script
                    {
                        HtmlElement dataload = webBrowser.Document.All["navigation_result"];
                        dataload.InnerText = _navigation.NavigateScript(nav, _execution.Report, parameters);
                        cancelNavigation   = true;
                    }
                    else     //Drill or SubReport
                    {
                        _execution = _navigation.Navigate(nav, _execution, false);
                        _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 && _execution.RootReport != null)
                    {
                        navMenu.SetAttribute("innerHTML", _navigation.GetNavigationLinksHTML(_execution.RootReport));
                    }
                    break;

                case ReportExecution.ActionGetTableData:
                    cancelNavigation = true;
                    string      guid    = webBrowser.Document.All[ReportExecution.HtmlId_execution_guid].GetAttribute("value");
                    Report      report  = _navigation.Navigations.ContainsKey(guid) ? _navigation.Navigations[guid].Execution.Report : _report;
                    string      viewid  = webBrowser.Document.All[ReportExecution.HtmlId_viewid_tableload].GetAttribute("value");
                    string      pageid  = webBrowser.Document.All[ReportExecution.HtmlId_pageid_tableload].GetAttribute("value");
                    HtmlElement newLoad = webBrowser.Document.All[ReportExecution.HtmlId_parameter_tableload];
                    var         view    = report.ExecutionView.GetView(viewid);
                    if (view != null && view.ModelView != null)
                    {
                        var page = view.ModelView.Model.Pages.FirstOrDefault(i => i.PageId == pageid);
                        if (page != null)
                        {
                            newLoad.InnerText = page.DataTable.GetLoadTableData(view, newLoad.InnerText);
                        }
                    }
                    break;

                case ReportExecution.ActionUpdateEnumValues:
                {
                    cancelNavigation = true;
                    string enumId = webBrowser.Document.All[ReportExecution.HtmlId_id_load].GetAttribute("value");
                    string values = webBrowser.Document.All[ReportExecution.HtmlId_values_load].GetAttribute("value");
                    _execution.UpdateEnumValues(enumId, values);
                }
                break;

                case ReportExecution.ActionGetEnumValues:
                {
                    cancelNavigation = true;
                    string      enumId     = webBrowser.Document.All[ReportExecution.HtmlId_id_load].GetAttribute("value");
                    string      filter     = webBrowser.Document.All[ReportExecution.HtmlId_filter_enumload].GetAttribute("value");
                    HtmlElement enumValues = webBrowser.Document.All[ReportExecution.HtmlId_parameter_enumload];
                    enumValues.InnerText = _execution.GetEnumValues(enumId, filter);
                }
                break;

                case ReportExecution.ActionExecuteFromTrigger:
                {
                    setCurrentExecution();
                    cancelNavigation = true;
                    lock (_execution)
                    {
                        string formId = webBrowser.Document.All[ReportExecution.HtmlId_id_load].GetAttribute("value");
                        var    form   = webBrowser.Document.Forms[formId];
                        initFromForm(form);

                        _report.ExecutionTriggerView = _report.AllViews.FirstOrDefault(i => formId.EndsWith(i.IdSuffix));
                        _report.IsNavigating         = false;
                        _execution.Execute();
                        while (_report.IsExecuting && !_report.Cancel)
                        {
                            Thread.Sleep(100);
                        }

                        _url = "file:///" + _report.HTMLDisplayFilePath;
                        _navigation.SetNavigation(_execution);

                        webBrowser.Navigate(_url);
                    }
                }
                break;

                default:
                {
                    if (Interface.ProcessAction(action, webBrowser, _navigation))
                    {
                        cancelNavigation = true;
                    }
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                cancelNavigation = true;
                var message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "\r\n" + ex.InnerException.Message;
                }
                MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(cancelNavigation);
        }
Пример #9
0
        public static void CreationAndExecution()
        {
            var    repository = Repository.Create();
            Report report     = Report.Create(repository);

            report.DisplayName = "Meetings Report : Creation an Execution";
            var source = report.Sources.FirstOrDefault(i => i.Name.StartsWith("StatisticsDataSource"));

            source.MetaData.Tables.Clear();

            //Update the data source with the table dbo.Rooms
            var table = source.AddTable(true);

            table.Name = "t";
            table.Sql  = "select r.ID_ROOM as Id, r.ROOM_NAME as Name, m.MEETINGS_COUNT as NumberOfMeetings, " +
                         "m.OCCUPATION_RATE as OccupationRate, m.NUMBER_OF_ATTENDEES as NumberOfAttendees " +
                         "from dbo.Rooms r inner join dbo.Meetings m on r.ID_ROOM = m.ID_ROOM";
            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.Replace("t.", "");

                switch (element.Name)
                {
                case "Id": element.PivotPosition = PivotPosition.Hidden; break;

                case "Name":
                {
                    element.PivotPosition   = PivotPosition.Row;
                    element.SerieDefinition = SerieDefinition.Axis;
                }
                break;

                default:
                {
                    element.PivotPosition = PivotPosition.Data;
                    element.ChartJSSerie  = ChartJSSerieDefinition.Bar;
                }
                break;
                }

                element.Source = source;
                report.Models[0].Elements.Add(element);
            }


            var view      = report.Views.Find(x => x.ViewName == "View");
            var model     = view.Views.Find(x => x.ViewName == "Model");
            var container = model.Views.Find(x => x.ViewName == "Model Container");
            var chartJS   = container.Views.Find(x => x.ViewName == "Chart JS");

            chartJS.InitParameters(false);
            var paramTitle = chartJS.Parameters.Find(x => x.Name == "chartjs_title");

            paramTitle.TextValue = "Number of meetings by room";
            var paramBarH = chartJS.Parameters.Find(x => x.Name == "chartjs_bar_horizontal");

            paramBarH.BoolValue = true;


            //Then execute it
            ReportExecution execution = new ReportExecution()
            {
                Report = report
            };

            execution.Execute();
            while (report.IsExecuting)
            {
                System.Threading.Thread.Sleep(100);
            }
            string result = execution.GenerateHTMLResult();

            Process.Start(result);
        }
Пример #10
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 messages = webBrowser.Document.All[ReportExecution.HtmlId_execution_messages];
                        if (_report.ExecutionView.GetValue("messages_mode") != "disabled" && messages != null)
                        {
                            messages.SetAttribute("innerHTML", Helper.ToHtml(_report.ExecutionMessages));
                            messages.ScrollTop = messages.ScrollRectangle.Height;
                        }
                        setProgressBarInformation(ReportExecution.HtmlId_progress_bar, _report.ExecutionProgression, _report.ExecutionProgressionMessage);
                        setProgressBarInformation(ReportExecution.HtmlId_progress_bar_tasks, _report.ExecutionProgressionTasks, _report.ExecutionProgressionTasksMessage);
                        setProgressBarInformation(ReportExecution.HtmlId_progress_bar_models, _report.ExecutionProgressionModels, _report.ExecutionProgressionModelsMessage);
                    }
                    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.ActionViewCSVResult:
                    setCurrentExecution();
                    resultPath = _execution.GenerateCSVResult();
                    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;

                case ReportExecution.ActionGetTableData:
                    cancelNavigation = true;
                    string guid = webBrowser.Document.All[ReportExecution.HtmlId_execution_guid].GetAttribute("value");
                    if (_navigation.Navigations.ContainsKey(guid))
                    {
                        var         report   = _navigation.Navigations[guid].Execution.Report;
                        string      viewid   = webBrowser.Document.All[ReportExecution.HtmlId_viewid_tableload].GetAttribute("value");
                        string      pageid   = webBrowser.Document.All[ReportExecution.HtmlId_pageid_tableload].GetAttribute("value");
                        HtmlElement dataload = webBrowser.Document.All[ReportExecution.HtmlId_parameter_tableload];
                        var         view     = report.ExecutionView.GetView(viewid);
                        if (view != null && view.Model != null)
                        {
                            var page = view.Model.Pages.FirstOrDefault(i => i.PageId == pageid);
                            if (page != null)
                            {
                                dataload.InnerText = page.DataTable.GetLoadTableData(view, dataload.InnerText);
                            }
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                cancelNavigation = true;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(cancelNavigation);
        }
Пример #11
0
        public ActionResult SWIGetDashboardResult(string guid, string itemguid, bool force)
        {
            writeDebug("SWIGetDashboardResult");
            try
            {
                checkSWIAuthentication();

                if (!CheckAuthentication())
                {
                    return(Content(_loginContent));
                }

                Report          report     = null;
                ReportExecution execution  = null;
                Repository      repository = null;

                var dashboard = WebUser.UserDashboards.FirstOrDefault(i => i.GUID == guid);
                if (dashboard == null)
                {
                    return(Json(new object { }));
                }

                var item = dashboard.Items.FirstOrDefault(i => i.GUID == itemguid);
                if (item == null)
                {
                    throw new Exception("Error: The item does not exist");
                }

                var widget = DashboardWidgetsPool.Widgets.ContainsKey(item.WidgetGUID) ? DashboardWidgetsPool.Widgets[item.WidgetGUID] : null;
                if (widget == null)
                {
                    throw new Exception("Error: the widget does not exist");
                }

                /* No check on exec rights for widgets...
                 * SWIFolder folder = getParentFolder(widget.ReportPath);
                 * if (folder.right == 0) throw new Exception("Error: no right on this folder");
                 */
                var filePath = Repository.ReportsFolder + widget.ReportPath;
                if (!System.IO.File.Exists(filePath))
                {
                    throw new Exception("Error: the report does not exist");
                }

                string     content = "";
                ReportView view = null, modelView = null;

                var executions = DashboardExecutions;
                lock (executions)
                {
                    //remove executions older than 2 hours
                    executions.RemoveAll(i => i.Report.ExecutionEndDate != DateTime.MinValue && i.Report.ExecutionEndDate < DateTime.Now.AddHours(-2));
                    //check if report has been modified
                    var lastDateTime = System.IO.File.GetLastWriteTime(filePath);
                    executions.RemoveAll(i => i.Report.FilePath == filePath && i.Report.LastModification != lastDateTime);

                    //find existing execution
                    foreach (var exec in executions.Where(i => i.Report.FilePath == filePath))
                    {
                        exec.Report.GetWidgetViewToParse(exec.Report.ExecutionView.Views, widget.GUID, ref view, ref modelView);
                        if (view != null)
                        {
                            execution = exec;
                            break;
                        }
                    }

                    if (execution == null)
                    {
                        //create execution
                        repository = Repository.CreateFast();
                        report     = Report.LoadFromFile(filePath, repository);

                        report.ExecutionContext = ReportExecutionContext.WebReport;
                        report.SecurityContext  = WebUser;
                        //Set url
                        report.WebUrl = GetWebUrl(Request, Response);

                        execution = new ReportExecution()
                        {
                            Report = report
                        };
                        executions.Add(execution);
                    }
                    else
                    {
                        report = execution.Report;
                    }

                    if (view == null)
                    {
                        report.GetWidgetViewToParse(report.Views, widget.GUID, ref view, ref modelView);
                    }

                    if (view == null)
                    {
                        throw new Exception("Error: the widget does not exist");
                    }

                    //Set execution view from the new root...
                    report.CurrentViewGUID = report.GetRootView(view).GUID;
                }

                lock (execution)
                {
                    if (!report.IsExecuting && (report.ExecutionEndDate == DateTime.MinValue || report.ExecutionEndDate < DateTime.Now.AddSeconds(-1 * report.WidgetCache)))
                    {
                        //Disable basics
                        report.ExecutionView.InitParameters(false);
                        //Set HTML Format
                        report.ExecutionView.SetParameter(Parameter.ReportFormatParameter, ReportFormat.html.ToString());
                        execution.Execute();
                    }
                    while (report.IsExecuting)
                    {
                        Thread.Sleep(100);
                    }
                }

                if (report.HasErrors)
                {
                    throw new Exception(report.Translate("This report has execution errors. Please check details in the Repository Logs Files or in the Event Viewer..."));
                }

                //Reset pointers and parse
                lock (execution)
                {
                    try
                    {
                        report.Status           = ReportStatus.RenderingDisplay;
                        report.CurrentModelView = modelView;
                        if (modelView != null && modelView.Model != null && modelView.Model.Pages.Count > 0)
                        {
                            report.CurrentPage = modelView.Model.Pages[0];
                        }
                        content = view.Parse();
                    }
                    finally
                    {
                        report.Status = ReportStatus.Executed;
                    }
                }

                //Set context for navigation, remove previous, keep root
                var keys = NavigationContext.Navigations.Where(i => i.Value.Execution.RootReport.ExecutionGUID == report.ExecutionGUID && i.Value.Execution.RootReport != i.Value.Execution.Report).ToArray();
                foreach (var key in keys)
                {
                    NavigationContext.Navigations.Remove(key.Key);
                }
                NavigationContext.SetNavigation(execution);

                var execReportPath = widget.ExecReportPath;
                if (string.IsNullOrEmpty(execReportPath))
                {
                    execReportPath = widget.ReportPath;
                }

                var result = new
                {
                    dashboardguid = guid,
                    itemguid      = itemguid,
                    executionguid = execution.Report.ExecutionGUID,
                    path          = !string.IsNullOrEmpty(widget.ExecViewGUID) ? execReportPath : "",
                    viewGUID      = widget.ExecViewGUID,
                    lastexec      = Translate("Last execution at") + " " + report.ExecutionEndDate.ToString("G", Repository.CultureInfo),
                    description   = Repository.TranslateWidgetDescription(widget.ReportPath.Replace(Repository.ReportsFolder, Path.DirectorySeparatorChar.ToString()), widget.Description),
                    dynamic       = item.Dynamic,
                    content       = content,
                    refresh       = (item.Refresh == -1 ? report.ExecutionView.GetNumericValue("refresh_rate") : item.Refresh)
                };

                return(Json(result));
            }
            catch (Exception ex)
            {
                var result = new
                {
                    dashboardguid = guid,
                    itemguid      = itemguid,
                    content       = "<b>" + Translate("This Widget has an error. Please consider to remove it from your Dashboard...") + "</b><br><br>" + Helper.ToHtml(ex.Message)
                };

                return(Json(result));
            }
        }
Пример #12
0
        private void PreLoadThread()
        {
            try
            {
                WebHelper.WriteLogEntryWeb(EventLogEntryType.Information, "Starting Preload Templates");
                RepositoryServer.PreLoadTemplates();

                WebHelper.WriteLogEntryWeb(EventLogEntryType.Information, "Starting Preload Widgets");
                var widgets = DashboardWidgetsPool.Widgets;

                List <string> reportList = new List <string>();
                foreach (var widget in widgets.Values)
                {
                    var filePath = Repository.Instance.ReportsFolder + widget.ReportPath;
                    if (System.IO.File.Exists(filePath) && !reportList.Contains(filePath))
                    {
                        reportList.Add(filePath);
                    }
                }

                WebHelper.WriteLogEntryWeb(EventLogEntryType.Information, "Starting Preload of {0} Widget Reports", reportList.Count);
                var repository = Repository.Instance.CreateFast();
                foreach (var reportPath in reportList)
                {
                    try {
                        var report = Report.LoadFromFile(reportPath, repository);

                        report.ExecutionContext = ReportExecutionContext.TaskScheduler;
                        //Disable basics
                        report.ExecutionView.InitParameters(false);
                        report.ExecutionView.SetParameter(Parameter.DrillEnabledParameter, false);
                        report.ExecutionView.SetParameter(Parameter.SubReportsEnabledParameter, false);
                        report.ExecutionView.SetParameter(Parameter.ServerPaginationParameter, false);
                        //set HTML Format
                        report.ExecutionView.SetParameter(Parameter.ReportFormatParameter, ReportFormat.html.ToString());
                        //Force load of all models
                        report.ExecutionView.SetParameter(Parameter.ForceModelsLoad, true);

                        var execution = new ReportExecution()
                        {
                            Report = report
                        };
                        execution.Execute();
                        while (report.IsExecuting)
                        {
                            Thread.Sleep(100);
                        }
                    }
                    catch (Exception ex)
                    {
                        WebHelper.WriteLogEntryWeb(EventLogEntryType.Error, "Pre Load: Error executing '{0}\r\n{1}", reportPath, ex.Message);
                    }
                }

                WebHelper.WriteLogEntryWeb(EventLogEntryType.Information, "Ending Preload");
            }
            catch (Exception ex)
            {
                WebHelper.WriteLogEntryWeb(EventLogEntryType.Error, ex.Message);
            }
        }
Пример #13
0
        void initInputRestrictions(ReportExecution execution, Report report)
        {
            report.InputRestrictions.Clear();

            //Do not use input restrictions for navigation...
            if (report.IsNavigating)
            {
                return;
            }

            // If we receive the "use_default_restrictions" field we define the field
            execution.UseDefaultRestrictions = false; //flag not set
            if (report.PreInputRestrictions.ContainsKey("use_default_restrictions"))
            {
                execution.UseDefaultRestrictions = Convert.ToBoolean(report.PreInputRestrictions["use_default_restrictions"]);
            }

            if (report.PreInputRestrictions.Count > 0)
            {
                int i = 0;
                while (true)
                {
                    string prefix = string.Format("r{0}", i);
                    string key    = prefix + "_name";
                    if (report.PreInputRestrictions.ContainsKey(key))
                    {
                        var displayName = report.PreInputRestrictions[key].ToLower();
                        foreach (ReportRestriction restriction in report.ExecutionCommonRestrictions.Where(j => j.DisplayNameEl.ToLower() == displayName))
                        {
                            //Convert values to normal input using the html id...
                            key = prefix + "_operator";
                            if (report.PreInputRestrictions.ContainsKey(key))
                            {
                                //operator
                                report.InputRestrictions.Add(restriction.OperatorHtmlId, report.PreInputRestrictions[key]);
                                if (restriction.IsEnumRE)
                                {
                                    restriction.SetEnumHtmlIds();

                                    //options
                                    key = prefix + "_enum_values";
                                    if (report.PreInputRestrictions.ContainsKey(key))
                                    {
                                        var optionValues = report.PreInputRestrictions[key];
                                        //Convert values into index of the enum...
                                        var preOptionvalues = optionValues.Split(',');
                                        foreach (var enumDef in restriction.EnumRE.Values)
                                        {
                                            if (preOptionvalues.Contains(enumDef.Id))
                                            {
                                                report.InputRestrictions.Add(restriction.OptionHtmlId + enumDef.HtmlId, "true");
                                            }
                                        }
                                    }
                                }
                                else if (restriction.IsDateTime)
                                {
                                    //convert to user input format
                                    DateTime dt;
                                    key = prefix + "_value_1";
                                    if (report.PreInputRestrictions.ContainsKey(key))
                                    {
                                        if (DateTime.TryParseExact(report.PreInputRestrictions[key], "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                                        {
                                            report.InputRestrictions.Add(restriction.ValueHtmlId + "_1", ((IFormattable)dt).ToString(report.ExecutionView.CultureInfo.DateTimeFormat.ShortDatePattern, report.ExecutionView.CultureInfo));
                                        }
                                    }
                                    key = prefix + "_value_2";
                                    if (report.PreInputRestrictions.ContainsKey(key))
                                    {
                                        if (DateTime.TryParseExact(report.PreInputRestrictions[key], "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                                        {
                                            report.InputRestrictions.Add(restriction.ValueHtmlId + "_2", ((IFormattable)dt).ToString(report.ExecutionView.CultureInfo.DateTimeFormat.ShortDatePattern, report.ExecutionView.CultureInfo));
                                        }
                                    }
                                    key = prefix + "_value_3";
                                    if (report.PreInputRestrictions.ContainsKey(key))
                                    {
                                        if (DateTime.TryParseExact(report.PreInputRestrictions[key], "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                                        {
                                            report.InputRestrictions.Add(restriction.ValueHtmlId + "_3", ((IFormattable)dt).ToString(report.ExecutionView.CultureInfo.DateTimeFormat.ShortDatePattern, report.ExecutionView.CultureInfo));
                                        }
                                    }
                                    key = prefix + "_value_4";
                                    if (report.PreInputRestrictions.ContainsKey(key))
                                    {
                                        if (DateTime.TryParseExact(report.PreInputRestrictions[key], "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                                        {
                                            report.InputRestrictions.Add(restriction.ValueHtmlId + "_4", ((IFormattable)dt).ToString(report.ExecutionView.CultureInfo.DateTimeFormat.ShortDatePattern, report.ExecutionView.CultureInfo));
                                        }
                                    }
                                }
                                else
                                {
                                    //standard values
                                    key = prefix + "_value_1";
                                    if (report.PreInputRestrictions.ContainsKey(key))
                                    {
                                        report.InputRestrictions.Add(restriction.ValueHtmlId + "_1", report.PreInputRestrictions[key]);
                                    }
                                    key = prefix + "_value_2";
                                    if (report.PreInputRestrictions.ContainsKey(key))
                                    {
                                        report.InputRestrictions.Add(restriction.ValueHtmlId + "_2", report.PreInputRestrictions[key]);
                                    }
                                    key = prefix + "_value_3";
                                    if (report.PreInputRestrictions.ContainsKey(key))
                                    {
                                        report.InputRestrictions.Add(restriction.ValueHtmlId + "_3", report.PreInputRestrictions[key]);
                                    }
                                    key = prefix + "_value_4";
                                    if (report.PreInputRestrictions.ContainsKey(key))
                                    {
                                        report.InputRestrictions.Add(restriction.ValueHtmlId + "_4", report.PreInputRestrictions[key]);
                                    }
                                }
                            }
                        }
                        i++;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            else
            {
                //get restriction values from the form request (if any)
                foreach (string key in Request.Form.Keys)
                {
                    string value = Request.Form[key];
                    if (value != null)
                    {
                        if (key.EndsWith("_Option_Value"))
                        {
                            foreach (string optionValue in value.Split(','))
                            {
                                report.InputRestrictions.Add(optionValue, "true");
                            }
                        }
                        else
                        {
                            report.InputRestrictions.Add(key, value);
                        }
                    }
                }
            }
            report.PreInputRestrictions.Clear();
        }
Пример #14
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);
        }
Пример #15
0
        public ActionResult SWIGetDashboardResult(string guid, string itemguid, bool force)
        {
            WriteDebug("SWIGetDashboardResult");
            try
            {
                checkSWIAuthentication();

                if (!CheckAuthentication())
                {
                    return(Content(_loginContent));
                }

                Report          report     = null;
                ReportExecution execution  = null;
                Repository      repository = null;

                var dashboard = WebUser.UserDashboards.FirstOrDefault(i => i.GUID == guid);
                if (dashboard == null)
                {
                    throw new Exception("Error: The dashboard does not exist");
                }

                var item = dashboard.Items.FirstOrDefault(i => i.GUID == itemguid);
                if (item == null)
                {
                    throw new Exception("Error: The item does not exist");
                }

                var widget = WebUser.Widgets.FirstOrDefault(i => i.GUID == item.WidgetGUID);
                if (widget == null)
                {
                    throw new Exception("Error: the widget does not exist");
                }
                if (!WebUser.CanSelectWidget(widget))
                {
                    throw new Exception("Error: no right to view this widget");
                }

                /* No check on exec rights for widgets...
                 * SWIFolder folder = getParentFolder(widget.ReportPath);
                 * if (folder.right == 0) throw new Exception("Error: no right on this folder");
                 */
                var filePath = Repository.ReportsFolder + widget.ReportPath;
                if (!System.IO.File.Exists(filePath))
                {
                    throw new Exception("Error: the report does not exist");
                }

                var executions = DashboardExecutions;
                lock (executions)
                {
                    //remove executions older than 2 hours
                    executions.RemoveAll(i => i.Report.ExecutionEndDate < DateTime.Now.AddHours(-2));

                    execution = executions.FirstOrDefault(i => i.Report.FilePath == filePath);
                    if (execution != null && execution.Report.LastModification != System.IO.File.GetLastWriteTime(filePath))
                    {
                        executions.RemoveAll(i => i.Report.FilePath == filePath);
                        execution = null;
                    }
                }

                if (execution != null)
                {
                    report = execution.Report;
                }
                else
                {
                    repository = Repository.CreateFast();
                    report     = Report.LoadFromFile(filePath, repository);

                    report.ExecutionContext = ReportExecutionContext.WebReport;
                    //Disable basics
                    report.ExecutionView.InitParameters(false);
                    report.ExecutionView.SetParameter(Parameter.DrillEnabledParameter, false);
                    report.ExecutionView.SetParameter(Parameter.SubReportsEnabledParameter, false);
                    report.ExecutionView.SetParameter(Parameter.ServerPaginationParameter, false);
                    //Force load of all models
                    report.ExecutionView.SetParameter(Parameter.ForceModelsLoad, true);
                }

                string content         = "";
                var    view            = report.GetWidgetViewToParse(report.Views, widget.GUID);
                var    modelView       = report.CurrentModelView;
                var    rootAutoRefresh = 0;
                if (view != null)
                {
                    //Init parmeters if the root view is different from the one executed...
                    var rootView = report.GetRootView(view);
                    if (rootView != null && rootView != report.ExecutionView)
                    {
                        string templateErrors = "";
                        rootView.InitTemplates(rootView, ref templateErrors);
                        rootAutoRefresh = rootView.GetNumericValue("refresh_rate");
                    }
                    else
                    {
                        rootAutoRefresh = report.ExecutionView.GetNumericValue("refresh_rate");
                    }

                    if (execution != null)
                    {
                        if (!report.IsExecuting && (force || report.ExecutionEndDate < DateTime.Now.AddSeconds(-1 * report.WidgetCache)))
                        {
                            execution.Execute();
                            while (report.IsExecuting)
                            {
                                Thread.Sleep(100);
                            }
                        }
                    }
                    else
                    {
                        execution = new ReportExecution()
                        {
                            Report = report
                        };
                        lock (executions)
                        {
                            executions.Add(execution);
                        }
                        execution.Execute();
                        while (report.IsExecuting)
                        {
                            Thread.Sleep(100);
                        }
                    }

                    //Reset pointers and parse
                    lock (report)
                    {
                        report.CurrentModelView = modelView;
                        if (modelView.Model.Pages.Count > 0)
                        {
                            report.CurrentPage        = modelView.Model.Pages[0];
                            report.CurrentPage.PageId = null; //Reset page id
                        }
                        content = view.Parse();
                    }
                }
                else
                {
                    content = "<b>Invalid Widget definition</b>";
                }

                var result = new
                {
                    dashboardguid = guid,
                    itemguid      = itemguid,
                    path          = widget.Exec ? widget.ReportPath : "",
                    lastexec      = Translate("Last execution at") + " " + report.ExecutionEndDate.ToString("G", Repository.CultureInfo),
                    description   = widget.Description,
                    dynamic       = item.Dynamic,
                    content       = content,
                    refresh       = (item.Refresh == -1 ? rootAutoRefresh : item.Refresh)
                };

                return(Json(result));
            }
            catch (Exception ex)
            {
                return(HandleSWIException(ex));
            }
        }
Пример #16
0
        private ReportExecution initReportExecution(Report report, string viewGUID, string outputGUID, bool toResult)
        {
            Repository repository = report.Repository;

            report.ExecutionContext = toResult ? ReportExecutionContext.WebOutput : 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.Query.Keys)
            {
                report.PreInputRestrictions.Add(key, Request.Query[key]);
            }

            //execute to output
            if (!string.IsNullOrEmpty(outputGUID))
            {
                report.OutputToExecute = report.Outputs.FirstOrDefault(i => i.GUID == outputGUID);
                if (report.OutputToExecute == null)
                {
                    throw new Exception("Invalid report output to execute");
                }
                if (!report.OutputToExecute.PublicExec && !string.IsNullOrEmpty(report.OutputToExecute.UserName) && WebUser.Name != report.OutputToExecute.UserName)
                {
                    throw new Exception("This output is not public and can only be executed by:" + report.OutputToExecute.UserName);
                }
                report.ExecutionContext = ReportExecutionContext.WebOutput;
                report.CurrentViewGUID  = report.OutputToExecute.ViewGUID;
            }

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

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

            setSessionValue(report.ExecutionGUID, execution);
            int index = RequestUrl.ToLower().IndexOf("swexecutereport");

            if (index == -1)
            {
                throw new Exception("Invalid URL");
            }
            report.WebUrl = GetWebUrl(Request, Response);
            repository.WebApplicationPath = RequestPhysicalApplicationPath;

            //Purge temp files here
            FileHelper.PurgeTempApplicationDirectory();

            report.InitForExecution();
            initInputRestrictions(execution, report);
            //Apply input restrictions if any
            if (report.InputRestrictions.Count > 0)
            {
                execution.CheckInputRestrictions();
            }

            return(execution);
        }
Пример #17
0
        public ActionResult ActionNavigate(string execution_guid)
        {
            writeDebug("ActionNavigate");
            try
            {
                if (!CheckAuthentication())
                {
                    return(_loginContentResult);
                }
                if (string.IsNullOrEmpty(execution_guid))
                {
                    return(new EmptyResult());
                }

                ReportExecution execution = getExecution(execution_guid);
                if (execution != null)
                {
                    if (execution.RootReport == null)
                    {
                        execution.RootReport = execution.Report;
                    }

                    string nav = Request.Form[ReportExecution.HtmlId_navigation_id];
                    NameValueCollection parameters = null;
                    if (Request.Form.ContainsKey(ReportExecution.HtmlId_navigation_parameters))
                    {
                        parameters = HttpUtility.ParseQueryString(Request.Form[ReportExecution.HtmlId_navigation_parameters]);
                    }

                    if (nav.StartsWith(NavigationLink.FileDownloadPrefix)) //File download
                    {
                        var filePath = NavigationContext.NavigateScript(nav, execution.Report, parameters);
                        if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath))
                        {
                            return(getFileResult(filePath, null));
                        }
                        else
                        {
                            throw new Exception(string.Format("Invalid file path got from the navigation script: '{0}'", filePath));
                        }
                    }
                    else if (nav.StartsWith(NavigationLink.ReportScriptPrefix)) //Report Script
                    {
                        var data = NavigationContext.NavigateScript(nav, execution.Report, parameters);
                        return(Json(data));
                    }
                    else if (nav.StartsWith(NavigationLink.ReportExecutionPrefix)) //Report Script
                    {
                        Report report    = execution.Report;
                        string path      = report.Repository.ReportsFolder + nav.Substring(3);
                        var    newReport = Report.LoadFromFile(path, report.Repository);
                        newReport.WebUrl = report.WebUrl;
                        execution        = new ReportExecution()
                        {
                            Report = newReport
                        };
                        report = newReport;
                        setSessionValue(report.ExecutionGUID, execution);

                        WebHelper.WriteLogEntryWebDetail(EventLogEntryType.Information, string.Format("Execute report '{0}'", report.FilePath), getContextDetail(Request, WebUser));

                        report.ExecutionContext = ReportExecutionContext.WebReport;
                        report.SecurityContext  = WebUser;
                        report.CurrentViewGUID  = report.ViewGUID;

                        report.InitForExecution();
                        execution.RenderHTMLDisplayForViewer();
                        return(getFileResult(report.HTMLDisplayFilePath, report));
                    }
                    else
                    {
                        execution = NavigationContext.Navigate(nav, execution.RootReport);
                        Report report = execution.Report;
                        //Check rights if not in subreports folder
                        if (!report.FilePath.StartsWith(report.Repository.SubReportsFolder))
                        {
                            SWIFolder folder = getParentFolder(report.FilePath.Replace(report.Repository.ReportsFolder, ""));
                            if (folder.right == 0)
                            {
                                throw new Exception(string.Format("Error: no right to execute a report on the folder '{0}'", folder.path));
                            }
                        }

                        setSessionValue(report.ExecutionGUID, execution);

                        WebHelper.WriteLogEntryWebDetail(EventLogEntryType.Information, string.Format("Navigation report '{0}'", report.FilePath), getContextDetail(Request, WebUser));

                        report.ExecutionContext = ReportExecutionContext.WebReport;
                        report.SecurityContext  = WebUser;
                        report.CurrentViewGUID  = report.ViewGUID;

                        report.InitForExecution();
                        execution.RenderHTMLDisplayForViewer();
                        return(getFileResult(report.HTMLDisplayFilePath, report));
                    }
                }
                else
                {
                    throw new Exception(string.Format("No report execution found in session '{0}'", execution_guid));
                }
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }
        }
Пример #18
0
        private ReportExecution initReportExecution(Report report, string viewGUID, string outputGUID)
        {
            Repository repository = report.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);
            //Apply input restrictions if any
            if (report.InputRestrictions.Count > 0)
            {
                execution.CheckInputRestrictions();
            }

            return(execution);
        }
Пример #19
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.Report         = report;
            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.IsExecuting)
            {
                System.Threading.Thread.Sleep(100);
            }
            string result = execution.GenerateHTMLResult();
            var    p      = new Process();

            p.StartInfo = new ProcessStartInfo(result)
            {
                UseShellExecute = true
            };
            p.Start();
        }
Пример #20
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.WebExecutionGUID = Guid.NewGuid().ToString();
                    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.WebExecutionGUID] = 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(Redirect(reportToExecute.WebTempUrl + Path.GetFileName(execution.Report.HTMLDisplayFilePath)));
                }
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }
            return(Content(string.Format("Error: Report file not found.\r\n{0}", path)));
        }
Пример #21
0
        public void SynchronizeSchedules(ExecutionLogInterface log, bool useCurrentUser)
        {
            int           count = 0, errorCount = 0, taskDeleted = 0;
            StringBuilder errorSummary = new StringBuilder("");

            Repository repository = Repository.Instance.CreateFast();

            try
            {
                log.Log("Starting Report Schedules Synchronization\r\n");

                if (!Helper.IsMachineAdministrator() && !useCurrentUser)
                {
                    log.Log("WARNING: For this tool, we recommend to execute the 'Server Manager' application with the option 'Run as administrator'\r\n");
                }

                SynchronizeSchedules(log, repository.ReportsFolder, repository, ref count, ref errorCount, errorSummary, useCurrentUser);
                log.Log("Checking personal folders\r\n");
                SynchronizeSchedules(log, repository.PersonalFolder, repository, ref count, ref errorCount, errorSummary, useCurrentUser);

                log.Log("Checking for Orphan schedules\r\n");

                if (repository.UseWebScheduler)
                {
                    SealReportScheduler.Instance.GetSchedules();
                }
                else
                {
                    TaskService taskService = new TaskService();
                    TaskFolder  taskFolder  = taskService.RootFolder.SubFolders.FirstOrDefault(i => i.Name == repository.Configuration.TaskFolderName);
                    if (taskFolder != null)
                    {
                        foreach (Task task in taskFolder.GetTasks())
                        {
                            log.Log("Checking task '{0}'", task.Name);
                            try
                            {
                                string reportPath   = ReportSchedule.GetTaskSourceDetail(task.Definition.RegistrationInfo.Source, 0);
                                string reportGUID   = ReportSchedule.GetTaskSourceDetail(task.Definition.RegistrationInfo.Source, 1);
                                string scheduleGUID = ReportSchedule.GetTaskSourceDetail(task.Definition.RegistrationInfo.Source, 3);
                                Report report       = ReportExecution.GetScheduledReport(taskFolder, reportPath, reportGUID, scheduleGUID, repository);
                                if (report != null)
                                {
                                    ReportSchedule schedule = ReportExecution.GetReportSchedule(taskFolder, report, scheduleGUID);
                                    if (schedule == null)
                                    {
                                        taskDeleted++;
                                        log.Log("WARNING: Unable to find schedule '{0}' in report '{1}'. Task has been deleted.", scheduleGUID, report.FilePath);
                                    }
                                }
                                else
                                {
                                    taskDeleted++;
                                    log.Log("WARNING: Unable to find report '{0}' for schedule '{1}'. Report tasks have been deleted.", reportGUID, scheduleGUID);
                                }
                            }
                            catch (Exception ex)
                            {
                                errorCount++;
                                log.LogRaw("ERROR\r\n");
                                log.Log(ex.Message);
                                errorSummary.AppendFormat("\r\nTask '{0}': {1}\r\n", task.Name, ex.Message);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Log("\r\n[UNEXPECTED ERROR RECEIVED]\r\n{0}\r\n", ex.Message);
            }
            log.Log("Report Schedules Synchronization terminated\r\n");

            log.Log("SUMMARY: {0} Report(s) checked, {1} Task(s) deleted, {2} Error(s) detected.\r\n{3}", count, taskDeleted, errorCount, errorSummary);
            if (errorCount == 0)
            {
                log.Log("Youpi, pas d'erreur !");
            }
        }
Пример #22
0
        public ActionResult ActionNavigate(string execution_guid)
        {
            WriteDebug("ActionNavigate");
            try
            {
                if (!CheckAuthentication())
                {
                    return(Content(_loginContent));
                }

                ReportExecution execution = null;
                if (!string.IsNullOrEmpty(execution_guid) && Session[execution_guid] is ReportExecution)
                {
                    execution = Session[execution_guid] as ReportExecution;
                }
                else
                {
                    //Navigation from dashboard, set the root report in the session
                    execution = DashboardExecutions.FirstOrDefault(i => i.Report.ExecutionGUID == execution_guid);
                    Session[execution_guid] = execution;
                }

                if (execution != null)
                {
                    if (execution.RootReport == null)
                    {
                        execution.RootReport = execution.Report;
                    }

                    string nav = Request.Form[ReportExecution.HtmlId_navigation_id];
                    if (nav.StartsWith(NavigationLink.FileDownloadPrefix))
                    {
                        var filePath = NavigationContext.NavigateScript(nav, execution.Report);
                        if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath))
                        {
                            Process.Start(filePath);
                        }
                        return(getFileResult(filePath, execution.Report));
                    }
                    else
                    {
                        execution = NavigationContext.Navigate(nav, execution.RootReport);
                        Report report = execution.Report;
                        Session[report.ExecutionGUID] = execution;

                        Helper.WriteLogEntryWeb(EventLogEntryType.Information, Request, WebUser, "Navigation report '{0}'", report.FilePath);

                        report.ExecutionContext = ReportExecutionContext.WebReport;
                        report.SecurityContext  = WebUser;
                        report.CurrentViewGUID  = report.ViewGUID;

                        report.InitForExecution();
                        execution.RenderHTMLDisplayForViewer();
                        return(getFileResult(report.HTMLDisplayFilePath, report));
                    }
                }
                else
                {
                    throw new Exception(string.Format("No report execution found in session '{0}'", execution_guid));
                }
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }
        }
Пример #23
0
        public ReportExecution Navigate(string navigation, ReportExecution execution, bool newWindow)
        {
            var    rootReport    = execution.RootReport;
            var    parameters    = HttpUtility.ParseQueryString(navigation);
            string reportPath    = parameters.Get("rpa"); //For subreports
            string executionGuid = parameters.Get("exe"); //For drill

            Report     newReport = null;
            string     destLabel = "", srcRestriction = "";
            Navigation previousNav = null;

            if (!newWindow)
            {
                //Check if the same navigation with the same execution GUID occured
                previousNav = Navigations.Values.FirstOrDefault(i => i.Execution.NavigationParameter == navigation && i.Execution.RootReport.ExecutionGUID == rootReport.ExecutionGUID);
                if (previousNav != null)
                {
                    newReport = previousNav.Execution.Report;
                }

                if (Navigations.Count(i => i.Value.Execution.RootReport.ExecutionGUID == rootReport.ExecutionGUID) == 1)
                {
                    //For the first navigation, we update the JS file in the result to show up the button
                    string html = File.ReadAllText(rootReport.ResultFilePath);
                    html = html.Replace("var _hasNavigation = false;/*SRKW do not modify*/", "var _hasNavigation = true;");
                    rootReport.ResultFilePath = Helpers.FileHelper.GetUniqueFileName(rootReport.ResultFilePath);
                    File.WriteAllText(rootReport.ResultFilePath, html, System.Text.Encoding.UTF8);
                    rootReport.IsNavigating  = true;
                    rootReport.HasNavigation = true;
                    Navigations.First(i => i.Value.Execution.RootReport.ExecutionGUID == rootReport.ExecutionGUID).Value.Link.Href = rootReport.ExecutionGUID; // !string.IsNullOrEmpty(rootReport.WebUrl) ? ReportExecution.ActionViewHtmlResultFile + "?execution_guid=" + rootReport.ExecutionGUID : rootReport.ResultFilePath;
                }
            }

            if (!string.IsNullOrEmpty(reportPath))
            {
                //Sub-Report
                if (newReport == null)
                {
                    string path = FileHelper.ConvertOSFilePath(reportPath.Replace(Repository.SealRepositoryKeyword, rootReport.Repository.RepositoryPath));
                    if (!File.Exists(path))
                    {
                        path = rootReport.Repository.ReportsFolder + path;
                    }
                    newReport = Report.LoadFromFile(path, rootReport.Repository);
                    newReport.CurrentViewGUID = newReport.ViewGUID;

                    int index = 1;
                    while (true)
                    {
                        string res = parameters.Get("res" + index.ToString());
                        string val = parameters.Get("val" + index.ToString());
                        if (string.IsNullOrEmpty(res) || string.IsNullOrEmpty(val))
                        {
                            break;
                        }
                        foreach (var model in newReport.Models)
                        {
                            foreach (var restriction in model.Restrictions.Where(i => i.MetaColumnGUID == res))
                            {
                                restriction.SetNavigationValue(val);
                                srcRestriction = restriction.GeNavigationDisplayValue();
                            }
                        }
                        index++;
                    }
                    //Get display value
                    string dis = parameters.Get("dis");
                    if (!string.IsNullOrEmpty(dis))
                    {
                        srcRestriction = HttpUtility.HtmlDecode(dis);
                    }
                }
            }
            else if (!string.IsNullOrEmpty(executionGuid))
            {
                //Drill
                if (newReport == null)
                {
                    newReport = Navigations[executionGuid].Execution.Report.Clone();
                    newReport.ExecutionGUID = Guid.NewGuid().ToString();

                    //Set view
                    newReport.CurrentViewGUID = execution.Report.CurrentViewGUID;
                    //Set Navigation view if specified
                    string viewGUID = parameters.Get("view");
                    if (!string.IsNullOrEmpty(viewGUID) && newReport.Views.Exists(i => i.GUID == viewGUID))
                    {
                        newReport.CurrentViewGUID = viewGUID;
                    }

                    string src = parameters.Get("src");
                    string dst = parameters.Get("dst");
                    string val = parameters.Get("val");
                    newReport.DrillParents.Add(src);

                    foreach (var model in newReport.Models)
                    {
                        drillModel(model, src, dst, val, ref destLabel, ref srcRestriction, newReport, rootReport);

                        if (model.IsLINQ)
                        {
                            //Handle restriction also for the sub-models
                            foreach (var subModel in model.LINQSubModels)
                            {
                                drillModel(subModel, src, dst, val, ref destLabel, ref srcRestriction, newReport, rootReport);
                            }
                        }
                    }
                }
            }

            if (newReport == null)
            {
                throw new Exception("Invalid Navigation");
            }

            newReport.WebUrl        = rootReport.WebUrl;
            newReport.IsNavigating  = true;
            newReport.HasNavigation = true;

            if (previousNav == null)
            {
                if (!string.IsNullOrEmpty(srcRestriction))
                {
                    newReport.DisplayName = string.Format("{0} > {1}", newReport.ExecutionName, srcRestriction);
                }
                else
                {
                    newReport.DisplayName = newReport.ExecutionName;
                    if (!string.IsNullOrEmpty(destLabel))
                    {
                        newReport.DisplayName += string.Format(" < {0}", destLabel);
                    }
                }
            }
            return(new ReportExecution()
            {
                NavigationParameter = navigation, Report = newReport, RootReport = rootReport
            });
        }
Пример #24
0
        public ActionResult ActionNavigate(string execution_guid)
        {
            writeDebug("ActionNavigate");
            try
            {
                if (!CheckAuthentication())
                {
                    return(_loginContentResult);
                }

                ReportExecution execution = getExecution(execution_guid);
                if (execution != null)
                {
                    if (execution.RootReport == null)
                    {
                        execution.RootReport = execution.Report;
                    }

                    string nav = Request.Form[ReportExecution.HtmlId_navigation_id];
                    NameValueCollection parameters = null;
                    if (Request.Form[ReportExecution.HtmlId_navigation_parameters] != null)
                    {
                        parameters = HttpUtility.ParseQueryString(Request.Form[ReportExecution.HtmlId_navigation_parameters]);
                    }

                    if (nav.StartsWith(NavigationLink.FileDownloadPrefix)) //File download
                    {
                        var filePath = NavigationContext.NavigateScript(nav, execution.Report, parameters);
                        if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath))
                        {
                            return(getFileResult(filePath, null));
                        }
                        else
                        {
                            throw new Exception(string.Format("Invalid file path got from the navigation script: '{0}'", filePath));
                        }
                    }
                    else if (nav.StartsWith(NavigationLink.ReportScriptPrefix)) //Report Script
                    {
                        var data = NavigationContext.NavigateScript(nav, execution.Report, parameters);
                        return(Json(data));
                    }
                    else
                    {
                        execution = NavigationContext.Navigate(nav, execution.RootReport);
                        Report report = execution.Report;
                        setSessionValue(report.ExecutionGUID, execution);

                        WebHelper.WriteLogEntryWeb(EventLogEntryType.Information, string.Format("Navigation report '{0}'", report.FilePath), getContextDetail(Request, WebUser));

                        report.ExecutionContext = ReportExecutionContext.WebReport;
                        report.SecurityContext  = WebUser;
                        report.CurrentViewGUID  = report.ViewGUID;

                        report.InitForExecution();
                        execution.RenderHTMLDisplayForViewer();
                        return(getFileResult(report.HTMLDisplayFilePath, report));
                    }
                }
                else
                {
                    throw new Exception(string.Format("No report execution found in session '{0}'", execution_guid));
                }
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }
        }
Пример #25
0
        public void ViewReport(Report report, Repository repository, bool render, string viewGUID, string outputGUID, string originalFilePath, string taskGUID = null)
        {
            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 one task
            _report.TaskToExecute = null;
            if (!string.IsNullOrEmpty(taskGUID))
            {
                _report.TaskToExecute = _report.Tasks.FirstOrDefault(i => i.GUID == taskGUID);
            }
            //execute to output
            _report.OutputToExecute = null;
            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 == Parameter.ForceExecutionParameter);
                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();
            if (_report.HasErrors)
            {
                _report.Cancel = true;
            }
            _execution.RenderHTMLDisplayForViewer();
            _url = "file:///" + _report.HTMLDisplayFilePath;
            webBrowser.Navigate(_url);
        }
Пример #26
0
        public ActionResult SWIGetDashboardResult(string guid, string itemguid, bool force)
        {
            WriteDebug("SWIGetDashboardResult");
            try
            {
                checkSWIAuthentication();

                if (!CheckAuthentication())
                {
                    return(Content(_loginContent));
                }

                Report          report     = null;
                ReportExecution execution  = null;
                Repository      repository = null;

                var dashboard = WebUser.UserDashboards.FirstOrDefault(i => i.GUID == guid);
                if (dashboard == null)
                {
                    return(Json(new object { }));
                }

                var item = dashboard.Items.FirstOrDefault(i => i.GUID == itemguid);
                if (item == null)
                {
                    throw new Exception("Error: The item does not exist");
                }

                var widget = DashboardWidgetsPool.Widgets.ContainsKey(item.WidgetGUID) ? DashboardWidgetsPool.Widgets[item.WidgetGUID] : null;
                if (widget == null)
                {
                    throw new Exception("Error: the widget does not exist");
                }

                /* No check on exec rights for widgets...
                 * SWIFolder folder = getParentFolder(widget.ReportPath);
                 * if (folder.right == 0) throw new Exception("Error: no right on this folder");
                 */
                var filePath = Repository.ReportsFolder + widget.ReportPath;
                if (!System.IO.File.Exists(filePath))
                {
                    throw new Exception("Error: the report does not exist");
                }

                var executions = DashboardExecutions;
                lock (executions)
                {
                    //remove executions older than 2 hours
                    executions.RemoveAll(i => i.Report.ExecutionEndDate < DateTime.Now.AddHours(-2));

                    execution = executions.FirstOrDefault(i => i.Report.FilePath == filePath);
                    if (execution != null && execution.Report.LastModification != System.IO.File.GetLastWriteTime(filePath))
                    {
                        executions.RemoveAll(i => i.Report.FilePath == filePath);
                        execution = null;
                    }
                }

                if (execution != null)
                {
                    report = execution.Report;
                }
                else
                {
                    repository = Repository.CreateFast();
                    report     = Report.LoadFromFile(filePath, repository);

                    report.ExecutionContext = ReportExecutionContext.WebReport;
                    report.SecurityContext  = WebUser;
                    //Disable basics
                    report.ExecutionView.InitParameters(false);
                    report.ExecutionView.SetParameter(Parameter.DrillEnabledParameter, false);
                    report.ExecutionView.SetParameter(Parameter.SubReportsEnabledParameter, false);
                    report.ExecutionView.SetParameter(Parameter.ServerPaginationParameter, false);
                    //set HTML Format
                    report.ExecutionView.SetParameter(Parameter.ReportFormatParameter, ReportFormat.html.ToString());
                    //Force load of all models
                    report.ExecutionView.SetParameter(Parameter.ForceModelsLoad, true);
                    //set url
                    report.WebUrl = GetWebUrl(Request, Response);
                }

                string     content = "";
                ReportView view = null, modelView = null;
                report.GetWidgetViewToParse(report.Views, widget.GUID, ref view, ref modelView);
                var rootAutoRefresh = 0;

                if (view == null)
                {
                    throw new Exception("Error: the widget does not exist");
                }

                //Init parameters if the root view is different from the one executed...
                var rootView = report.GetRootView(view);
                if (rootView != null && rootView != report.ExecutionView)
                {
                    string templateErrors = "";
                    rootView.InitTemplates(rootView, ref templateErrors);
                    rootAutoRefresh = rootView.GetNumericValue("refresh_rate");
                }
                else
                {
                    rootAutoRefresh = report.ExecutionView.GetNumericValue("refresh_rate");
                }

                if (execution != null)
                {
                    if (!report.IsExecuting && (force || report.ExecutionEndDate < DateTime.Now.AddSeconds(-1 * report.WidgetCache)))
                    {
                        execution.Execute();
                        while (report.IsExecuting)
                        {
                            Thread.Sleep(100);
                        }
                    }
                }
                else
                {
                    execution = new ReportExecution()
                    {
                        Report = report
                    };
                    lock (executions)
                    {
                        executions.Add(execution);
                    }
                    execution.Execute();
                    while (report.IsExecuting)
                    {
                        Thread.Sleep(100);
                    }
                }
                if (report.HasErrors)
                {
                    Helper.WriteWebException(new Exception(report.FilePath + ":\r\n" + report.ExecutionErrors), Request, WebUser);
                    throw new Exception("Error: the widget has errors");
                }
                //Reset pointers and parse
                lock (report)
                {
                    report.CurrentModelView = modelView;
                    if (modelView != null && modelView.Model != null && modelView.Model.Pages.Count > 0)
                    {
                        report.CurrentPage        = modelView.Model.Pages[0];
                        report.CurrentPage.PageId = null; //Reset page id
                    }
                    content = view.Parse();
                }

                var result = new
                {
                    dashboardguid = guid,
                    itemguid      = itemguid,
                    path          = widget.Exec ? widget.ReportPath : "",
                    lastexec      = Translate("Last execution at") + " " + report.ExecutionEndDate.ToString("G", Repository.CultureInfo),
                    description   = Repository.TranslateWidgetDescription(widget.ReportPath.Replace(Repository.ReportsFolder, "\\"), widget.Description),
                    dynamic       = item.Dynamic,
                    content       = content,
                    refresh       = (item.Refresh == -1 ? rootAutoRefresh : item.Refresh)
                };

                return(Json(result));
            }
            catch (Exception ex)
            {
                var result = new
                {
                    dashboardguid = guid,
                    itemguid      = itemguid,
                    content       = "<b>" + Translate("This Widget has an error. Please consider to remove it from your Dashboard...") + "</b><br><br>" + Helper.ToHtml(ex.Message)
                };

                return(Json(result));
            }
        }