public ReportBundle Generate([NotNull] Reports report,
                                     long userId,
                                     IReadOnlyDictionary <string, object> parameters)
        {
            if (report == null)
            {
                throw new ArgumentNullException(nameof(report));
            }

            if (string.IsNullOrEmpty(report.Rule))
            {
                throw new ReportRuleIsEmptyException(report.Id);
            }

            var reportBundle = new ReportBundle
            {
                ParameterValues = parameters,
                Report          = report,
                TargetUserId    = userId
            };

            try
            {
                reportBundle.Rule = report.Rule.FromJson <ReportRule>();
            }
            catch (Exception ex)
            {
                throw new IncorrectReportRuleException(ex);
            }

            ProcessReport(reportBundle);

            return(reportBundle);
        }
        protected override void ExecuteStage([NotNull] ReportBundle reportBundle)
        {
            if (reportBundle == null)
            {
                throw new ArgumentNullException(nameof(reportBundle));
            }

            if (string.IsNullOrEmpty(reportBundle.Rule?.ReportTitle))
            {
                reportBundle.Title = reportBundle.Report.DisplayName;

                return;
            }

            var titleTemplate = _templateBuilder.Build(reportBundle.Rule.ReportTitle);

            foreach (var parameter in reportBundle.ParameterValues)
            {
                titleTemplate.Add(parameter.Key, parameter.Value);
            }

            foreach (var queryResult in reportBundle.QueryResults)
            {
                titleTemplate.Add(queryResult.Key, queryResult.Result.Items);
            }

            reportBundle.Title = titleTemplate.Render();
        }
Exemple #3
0
        public void Process([NotNull] ReportBundle reportBundle)
        {
            if (reportBundle == null)
            {
                throw new ArgumentNullException(nameof(reportBundle));
            }

            ExecuteStage(reportBundle);

            _successor?.Process(reportBundle);
        }
        private string GetReportFileName(ReportBundle reportBundle, ReportFileType reportFileType)
        {
            var currentDateUtc = _timeService.GetUtc();

            const string dateMask = "yyyy-MM-dd hh-mm-ss-ffff";

            var reportFileExtension = _reportFileExtensionProvider.Get(reportFileType);

            var validFileName = reportBundle.Title.ToValidPath();

            var fileName = $"{validFileName} {currentDateUtc.ToString(dateMask)}.{reportFileExtension}";

            return(fileName);
        }
        private void ProcessReport(ReportBundle reportBundle)
        {
            var validateParametersStage   = _reportGenerationStageDispatcher.Get <ValidateParametersStage>();
            var executeQueriesStage       = _reportGenerationStageDispatcher.Get <ExecuteQueriesStage>();
            var renderTitleStage          = _reportGenerationStageDispatcher.Get <RenderTitleStage>();
            var addDefaultParametersStage = _reportGenerationStageDispatcher.Get <AddDefaultParametersStage>();
            var vizualizationStage        = _reportGenerationStageDispatcher.Get <ReportVizualizationStage>();

            validateParametersStage.SetSuccessor(executeQueriesStage);
            executeQueriesStage.SetSuccessor(renderTitleStage);
            renderTitleStage.SetSuccessor(addDefaultParametersStage);
            addDefaultParametersStage.SetSuccessor(vizualizationStage);

            validateParametersStage.Process(reportBundle);
        }
        public ReportFile Translate([NotNull] ReportBundle reportBundle, ReportFileType reportFileType)
        {
            if (reportBundle == null)
            {
                throw new ArgumentNullException(nameof(reportBundle));
            }

            var translator = _reportTranslatorFabric.GetTranslator(reportFileType);

            var reportFileContent = translator.Translate(reportBundle.BodyHtml);

            var reportTitle = GetReportFileName(reportBundle, reportFileType);

            return(new ReportFile(reportBundle.Title, reportTitle, reportBundle.BodyHtml, reportFileContent, reportFileType));
        }
Exemple #7
0
        /// <summary>
        /// Executes a report.
        /// </summary>
        /// <param name="id">The id of the report.</param>
        /// <param name="format">The output format of the report.</param>
        /// <param name="bundle">The list of parameters of the report.</param>
        /// <returns>Returns the report in raw format.</returns>
        /// <exception cref="System.ArgumentException">If the id or format is not in a valid format.</exception>
        public Stream RunReport(string id, string format, ReportBundle bundle)
        {
            var reportId = Guid.Empty;
            var formatId = Guid.Empty;

            if (!Guid.TryParse(id, out reportId))
            {
                throw new ArgumentException($"The parameter { id } must be a valid { nameof(Guid) }");
            }

            if (!Guid.TryParse(format, out formatId))
            {
                throw new ArgumentException($"The parameter { format } must be a valid { nameof(Guid) }");
            }

            return(new MemoryStream(this.reportExecutor.RunReport(reportId, formatId, bundle.Parameters.Items)));
        }
        protected override void ExecuteStage(ReportBundle reportBundle)
        {
            var queryResults = new List <ReportQueryResult>();

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var reportQuery in reportBundle.Rule.QueryLinks)
            {
                var parameters = GetReportDefaultParameters(reportBundle);

                var queryResult = _reportQueryLinkDirector.Execute(reportBundle.TargetUserId, (dynamic)reportQuery, parameters);

                queryResults.Add(new ReportQueryResult
                {
                    Key    = reportQuery.Key,
                    Result = queryResult
                });
            }

            reportBundle.QueryResults = queryResults;
        }
Exemple #9
0
        /// <summary>
        /// Executes a report.
        /// </summary>
        /// <param name="id">The id of the report.</param>
        /// <param name="format">The output format of the report.</param>
        /// <param name="bundle">The list of parameters of the report.</param>
        /// <returns>Returns the report in raw format.</returns>
        /// <exception cref="System.ArgumentException">If the id or format is not in a valid format.</exception>
        public Stream RunReport(string id, string format, ReportBundle bundle)
        {
            var reportId = Guid.Empty;
            var formatId = Guid.Empty;

            if (!Guid.TryParse(id, out reportId))
            {
                throw new ArgumentException($"The parameter { id } must be a valid { nameof(Guid) }");
            }

            if (!Guid.TryParse(format, out formatId))
            {
                throw new ArgumentException($"The parameter { format } must be a valid { nameof(Guid) }");
            }

            if (formatId == ReportFormatKeys.Html)
            {
                RestOperationContext.Current.OutgoingResponse.ContentType = "text/html";
            }
            return(new MemoryStream(this.reportExecutor.RunReport(reportId, formatId, bundle.Parameters.Items)));
        }
        protected override void ExecuteStage(ReportBundle reportBundle)
        {
            if (reportBundle.Rule.Parameters == null)
            {
                reportBundle.Rule.Parameters = new ReportParameter[0];
            }

            if (!reportBundle.Rule.Parameters.Any())
            {
                return;
            }

            // ReSharper disable once LoopCanBePartlyConvertedToQuery
            foreach (var requiredParameter in reportBundle.Rule.Parameters)
            {
                if (!reportBundle.ParameterValues.Any(_ => _.Key.Equals(requiredParameter.Key)))
                {
                    throw new RequiredParameterDoesNotSpecifiedException(requiredParameter.Key);
                }
            }
        }
        public void ShouldGenerateReport()
        {
            const int reportId = 234234;

            var report = new Reports
            {
                Id = reportId
            };

            _reportStorage
            .Setup(_ => _.Get(reportId))
            .Returns(report);

            const int userId = 2342342;

            var parameters = new Dictionary <string, object>
            {
                { "Halo", "No" }
            };

            var reportBundle = new ReportBundle();

            _reportGenerationPipelineManager
            .Setup(_ => _.Generate(report, userId, parameters))
            .Returns(reportBundle);

            const ReportFileType reportFileType = ReportFileType.Html;

            var reportFile = new ReportFile("Title", "Repo", "<div></div>", Guid.NewGuid().ToByteArray(), reportFileType);

            _reportTranslationManager
            .Setup(_ => _.Translate(reportBundle, reportFileType))
            .Returns(reportFile);

            var result = _target.Build(reportId, userId, parameters, reportFileType);

            _repositoryLogger.Verify(_ => _.SaveReportFile(reportBundle, reportFile, userId), Times.Once);

            result.ShouldBeEquivalentTo(reportFile);
        }
        protected override void ExecuteStage([NotNull] ReportBundle reportBundle)
        {
            if (reportBundle == null)
            {
                throw new ArgumentNullException(nameof(reportBundle));
            }

            var parameterValues = reportBundle.ParameterValues?.ToDictionary(_ => _.Key, _ => _.Value)
                                  ?? new Dictionary <string, object>();

            parameterValues.Add(DefaultReportParameters.CurrentDate, _timeService.GetUtc().ToString(CultureInfo.CurrentCulture));

            parameterValues.Add(DefaultReportParameters.ReportName, reportBundle.Report.DisplayName);

            parameterValues.Add(DefaultReportParameters.ReportTitle, reportBundle.Title);

            parameterValues.Add(DefaultReportParameters.SystemVersion, _systemVersionProvider.GetSystemVersion());

            parameterValues.Add(DefaultReportParameters.UiHost, _userInterfaceProvider.GetLatest().Host);

            reportBundle.ParameterValues = parameterValues;
        }
        protected override void ExecuteStage(ReportBundle reportBundle)
        {
            if (reportBundle.Rule.Template.Root == null)
            {
                throw new EmptyReportRuleTemplateException(reportBundle);
            }

            using (var stringWriter = new StringWriter())
            {
                using (var htmlTextWriter = new HtmlTextWriter(stringWriter))
                {
                    _reportBlockVizualizationManager.Vizualize(
                        htmlTextWriter,
                        (dynamic)reportBundle.Rule.Template.Root,
                        reportBundle.ParameterValues,
                        reportBundle.QueryResults,
                        reportBundle.TargetUserId);
                }

                reportBundle.BodyHtml = stringWriter.ToString();
            }
        }
Exemple #14
0
    /// <summary>
    /// Used by RoutingProtocol when received bundle either arrived at its destination or  when this node is a custodian.
    /// </summary>
    public void Handle(Bundle bundle)
    {
        if (bundle is DataBundle)
        {
            //check if this bundle was not already handled:
            if (handledBundles.Contains(bundle))
            {
                return;
            }
            TimerEntry timerEntry = Timer.Schedule(bundle.LifeTimeEnd, onBundleLifeTimeEnd, bundle);
            handledBundles.Add(bundle, timerEntry);

            DataBundle dataBundle = (DataBundle)bundle;
            if (dataBundle.Destination == node)
            {
                confirm(dataBundle);
                dataDestination.Receive(dataBundle.DataChunk);
                //Debug.Assert(dataBundle.CreationTime == dataBundle.DataChunk.CreationTime);
                bundleDelay.Add(Timer.CurrentTime - bundle.CreationTime);
                dataBundleDelay.Add(Timer.CurrentTime - dataBundle.CreationTime);
            }
            else
            {
                //custodian
                Debug.Assert(node.IsCustodian);
                if (dataBundle.Custodian != node)//do to send confirmation to ourselvelves.
                {
                    confirm(dataBundle);
                }
                if (buffer.Store(dataBundle.DataChunk, dataBundle.Destination))
                {
                    ++custodianResponsibilityTakeOverCount;
                    Bundle copy = new DataBundle(dataBundle, node);
                    routingProtocol.Route(copy);
                }
            }
        }
        else
        {
            //it has to be report bundle
            ReportBundle report = bundle as ReportBundle;
            buffer.Confirm(report.ReportedDataChunk);
            bundleDelay.Add(Timer.CurrentTime - bundle.CreationTime);
            confirmationDelay.Add(Timer.CurrentTime - report.CreationTime);
        }



        /*
         * if (bundle.Destination == node)
         * {
         *  bundleDelay.Add(Timer.CurrentTime - bundle.CreationTime);
         *  if (bundle is DataBundle)
         *  {
         *      DataBundle dataBundle = bundle as DataBundle;
         *      confirm(dataBundle);
         *      dataDestination.Receive(dataBundle.DataChunk);
         *      dataBundleDelay.Add(Timer.CurrentTime - dataBundle.CreationTime);
         *  }
         *  else
         *  {
         *      ReportBundle report = bundle as ReportBundle;
         *      buffer.Confirm(report.ReportedDataChunk);
         *      confirmationDelay.Add(Timer.CurrentTime - report.CreationTime);
         *  }
         * }
         * else
         * {
         *  Debug.Assert(node.IsCustodian);
         *  DataBundle dataBundle = (DataBundle)bundle;
         *  confirm(dataBundle);
         *  buffer.Store(dataBundle.DataChunk, dataBundle.Destination);
         *  Bundle copy = new DataBundle(dataBundle, node);
         *  routingProtocol.Route(copy);
         * }
         */
    }
Exemple #15
0
    void confirm(DataBundle dataBundle)
    {
        ReportBundle report = new ReportBundle(node, dataBundle.Custodian, dataBundle.DataChunk);

        routingProtocol.Route(report);
    }
Exemple #16
0
 protected abstract void ExecuteStage(ReportBundle reportBundle);
        private static IEnumerable <KeyValuePair <string, string> > GetReportDefaultParameters(ReportBundle reportBundle)
        {
            var parameters = reportBundle
                             .ParameterValues
                             ?.Select(_ => new KeyValuePair <string, string>(_.Key, _.Value.ToString()));

            return(parameters);
        }
 public EmptyReportRuleTemplateException(ReportBundle reportBundle) :
     base($"Empty report template. Report Id='{reportBundle.Report.Id}'")
 {
 }
Exemple #19
0
        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        // ~RisiServiceClient() {
        //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        //   Dispose(false);
        // }

        #endregion IDisposable Support

        /// <summary>
        /// Executes a report.
        /// </summary>
        /// <param name="id">The id of the report.</param>
        /// <param name="format">The output format of the report.</param>
        /// <param name="bundle">The list of parameters of the report.</param>
        /// <returns>Returns the report in raw format.</returns>
        public Stream RunReport(Guid id, string format, ReportBundle bundle)
        {
            return(new MemoryStream(this.Client.Post <ReportBundle, byte[]>($"report/{id}/format/{format}", bundle)));
        }