Esempio n. 1
0
        public IProcessController Compose(string cfg, LogLevel logLevel = LogLevel.Info, Dictionary <string, string> parameters = null, string placeHolderStyle = "@()")
        {
            var logger    = new TraceLogger(logLevel);
            var container = ConfigurationContainer.Create(cfg, logger, parameters, placeHolderStyle);

            Process = parameters == null?container.Resolve <Process>(new NamedParameter("cfg", cfg)) : container.Resolve <Process>(new NamedParameter("cfg", cfg), new NamedParameter("parameters", parameters));

            if (Process.Errors().Any())
            {
                foreach (var error in Process.Errors())
                {
                    Trace.WriteLine(error);
                }
                throw new Exception("Configuration Error(s)");
            }

            if (Process.Warnings().Any())
            {
                foreach (var warning in Process.Warnings())
                {
                    Trace.WriteLine(warning);
                }
            }

            return(DefaultContainer.Create(Process, logger, placeHolderStyle).Resolve <IProcessController>(new NamedParameter("cfg", cfg)));
        }
Esempio n. 2
0
        public IProcessController Compose(string cfg, LogLevel logLevel = LogLevel.Info, Dictionary <string, string> parameters = null)
        {
            var builder = new ContainerBuilder();

            builder.RegisterModule(new RootModule(@"Shorthand.xml"));
            var container = builder.Build();

            Process = parameters == null?container.Resolve <Process>(new NamedParameter("cfg", cfg)) : container.Resolve <Process>(new NamedParameter("cfg", cfg), new NamedParameter("parameters", parameters));

            if (Process.Errors().Any())
            {
                foreach (var error in Process.Errors())
                {
                    Trace.WriteLine(error);
                }
                throw new Exception("Configuration Error(s)");
            }

            if (Process.Warnings().Any())
            {
                foreach (var warning in Process.Warnings())
                {
                    Trace.WriteLine(warning);
                }
            }

            return(DefaultContainer.Create(Process, new TraceLogger(logLevel)).Resolve <IProcessController>(new NamedParameter("cfg", cfg)));
        }
        public ILifetimeScope CreateScope(string arrangement, ContentItem item, IDictionary <string, string> parameters, bool validateParameters = true)
        {
            var combinedParameters = parameters ?? new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            var builder = new ContainerBuilder();

            builder.RegisterModule(new ShorthandModule(_logger));

            builder.Register(ctx => {
                var dependancies = new List <IDependency>();

                if (item.ContentItem.Has("TransformalizeReportPart"))
                {
                    dependancies.Add(new ReportParameterModifier());
                }

                if (Serializer != null)
                {
                    dependancies.Add(Serializer);
                }

                dependancies.Add(new ParameterModifier(new PlaceHolderReplacer('@', '[', ']')));

                // these were registered by the ShorthandModule are are used to expand shorthand transforms and validators into "longhand".
                dependancies.Add(ctx.ResolveNamed <IDependency>(TransformModule.FieldsName));
                dependancies.Add(ctx.ResolveNamed <IDependency>(TransformModule.ParametersName));
                dependancies.Add(ctx.ResolveNamed <IDependency>(ValidateModule.FieldsName));
                dependancies.Add(ctx.ResolveNamed <IDependency>(ValidateModule.ParametersName));

                string modified = arrangement;
                if (_httpContext.HttpContext.Request.Method == "GET" && item.ContentItem.Has("TransformalizeFormPart"))
                {
                    modified = _loadFormModifier.Modify(arrangement, item.Id, combinedParameters);
                }

                if (validateParameters)
                {
                    modified = _transformalizeParameters.Modify(arrangement, item.Id, combinedParameters);
                }

                var process = new Process(modified, combinedParameters, dependancies.ToArray());

                if (process.Errors().Any())
                {
                    _logger.Error(() => "The configuration has errors.");
                    foreach (var error in process.Errors())
                    {
                        _logger.Error(() => error);
                    }
                }

                process.Id = item.Id;

                return(process);
            }).As <Process>().InstancePerDependency();
            return(builder.Build().BeginLifetimeScope());
        }
Esempio n. 4
0
 private static ContentResult Get503(string action, Process process, string format, long time)
 {
     process.Request = action;
     process.Status  = 503;
     process.Message = string.Join("\n", process.Errors());
     process.Time    = time;
     return(new ContentResult {
         Content = process.Serialize(), ContentType = "text/" + format
     });
 }
Esempio n. 5
0
        public ActionResult Index(int id) {

            var timer = new Stopwatch();
            timer.Start();

            var process = new Process { Name = "Export" };

            var part = _orchardServices.ContentManager.Get(id).As<PipelineConfigurationPart>();
            if (part == null) {
                process.Name = "Not Found";
            } else {

                var user = _orchardServices.WorkContext.CurrentUser == null ? "Anonymous" : _orchardServices.WorkContext.CurrentUser.UserName ?? "Anonymous";

                if (_orchardServices.Authorizer.Authorize(Permissions.ViewContent, part)) {

                    process = _processService.Resolve(part);

                    var parameters = Common.GetParameters(Request, _orchardServices, null);

                    process.Load(part.Configuration, parameters);
                    process.Buffer = false; // no buffering for export
                    process.ReadOnly = true;  // force exporting to omit system fields

                    // change process for export and batch purposes
                    var reportType = Request["output"] ?? "page";

                    ConvertToExport(user, process, part, reportType, parameters);
                    process.Load(process.Serialize(), parameters);

                    if (Request["sort"] != null) {
                        _sortService.AddSortToEntity(process.Entities.First(), Request["sort"]);
                    }

                    if (process.Errors().Any()) {
                        foreach (var error in process.Errors()) {
                            _orchardServices.Notifier.Add(NotifyType.Error, T(error));
                        }
                    } else {
                        if (process.Entities.Any(e => !e.Fields.Any(f => f.Input))) {
                            _orchardServices.WorkContext.Resolve<ISchemaHelper>().Help(process);
                        }

                        if (!process.Errors().Any()) {

                            var runner = _orchardServices.WorkContext.Resolve<IRunTimeExecute>();

                            try {

                                runner.Execute(process);
                                process.Request = "Export";
                                process.Time = timer.ElapsedMilliseconds;

                                if (process.Errors().Any()) {
                                    foreach (var error in process.Errors()) {
                                        _orchardServices.Notifier.Add(NotifyType.Error, T(error));
                                    }
                                    process.Status = 500;
                                    process.Message = "There are errors in the pipeline.  See log.";
                                } else {
                                    process.Status = 200;
                                    process.Message = "Ok";
                                }

                                var o = process.Output();
                                switch (o.Provider) {
                                    case "kml":
                                    case "geojson":
                                    case "file":
                                        Response.AddHeader("content-disposition", "attachment; filename=" + o.File);
                                        switch (o.Provider) {
                                            case "kml":
                                                Response.ContentType = "application/vnd.google-earth.kml+xml";
                                                break;
                                            case "geojson":
                                                Response.ContentType = "application/vnd.geo+json";
                                                break;
                                            default:
                                                Response.ContentType = "application/csv";
                                                break;
                                        }
                                        Response.Flush();
                                        Response.End();
                                        return new EmptyResult();
                                    case "excel":
                                        return new FilePathResult(o.File, Common.ExcelContentType) {
                                            FileDownloadName = _slugService.Slugify(part.Title()) + ".xlsx"
                                        };
                                    default:  // page and map are rendered to page
                                        break;
                                }
                            } catch (Exception ex) {
                                Logger.Error(ex, ex.Message);
                                _orchardServices.Notifier.Error(T(ex.Message));
                            }
                        }
                    }

                } else {
                    _orchardServices.Notifier.Warning(user == "Anonymous" ? T("Sorry. Anonymous users do not have permission to view this report. You may need to login.") : T("Sorry {0}. You do not have permission to view this report.", user));
                }
            }

            return View(new ReportViewModel(process, part));

        }
Esempio n. 6
0
        public ActionResult Index(int id)
        {
            var timer = new Stopwatch();

            timer.Start();

            var process = new Process {
                Name = "Report"
            };

            var part = _orchardServices.ContentManager.Get(id).As <PipelineConfigurationPart>();

            if (part == null)
            {
                process.Name = "Not Found";
            }
            else
            {
                var user = _orchardServices.WorkContext.CurrentUser == null ? "Anonymous" : _orchardServices.WorkContext.CurrentUser.UserName ?? "Anonymous";

                if (_orchardServices.Authorizer.Authorize(Permissions.ViewContent, part))
                {
                    process = _processService.Resolve(part);

                    var parameters = Common.GetParameters(Request, _orchardServices, _secureFileService);
                    if (part.NeedsInputFile && Convert.ToInt32(parameters[Common.InputFileIdName]) == 0)
                    {
                        _orchardServices.Notifier.Add(NotifyType.Error, T("This transformalize expects a file."));
                        process.Name = "File Not Found";
                    }

                    process.Load(part.Configuration, parameters);
                    process.Mode     = "report";
                    process.Buffer   = false; // no buffering for reports
                    process.ReadOnly = true;  // force reporting to omit system fields

                    // secure actions
                    var actions = process.Actions.Where(a => !a.Before && !a.After && !a.Description.StartsWith("Batch", StringComparison.OrdinalIgnoreCase));
                    foreach (var action in actions)
                    {
                        var p = _orchardServices.ContentManager.Get(action.Id);
                        if (!_orchardServices.Authorizer.Authorize(Permissions.ViewContent, p))
                        {
                            action.Description = "BatchUnauthorized";
                        }
                    }

                    Common.TranslatePageParametersToEntities(process, parameters, "page");

                    if (Request.HttpMethod.Equals("POST") && parameters.ContainsKey("action"))
                    {
                        var action = process.Actions.FirstOrDefault(a => a.Description == parameters["action"]);

                        if (action != null)
                        {
                            // check security
                            var actionPart = _orchardServices.ContentManager.Get(action.Id);
                            if (actionPart == null)
                            {
                                return(new HttpNotFoundResult(string.Format("The action id {0} does not refer to a content item id.", action.Id)));
                            }

                            if (_orchardServices.Authorizer.Authorize(Permissions.ViewContent, actionPart))
                            {
                                // security okay
                                parameters["entity"] = process.Entities.First().Alias;
                                var batchParameters = _batchCreateService.Create(process, parameters);

                                Common.AddOrchardVariables(batchParameters, _orchardServices, Request);

                                batchParameters["count"] = parameters.ContainsKey("count") ? parameters["count"] : "0";
                                var count = _batchWriteService.Write(Request, process, batchParameters);

                                if (count > 0)
                                {
                                    if (_batchRunService.Run(action, batchParameters))
                                    {
                                        if (action.Url == string.Empty)
                                        {
                                            if (batchParameters.ContainsKey("BatchId"))
                                            {
                                                _orchardServices.Notifier.Information(T(string.Format("Processed {0} records in batch {1}.", count, batchParameters["BatchId"])));
                                            }
                                            else
                                            {
                                                _orchardServices.Notifier.Information(T(string.Format("Processed {0} records.", count)));
                                            }
                                            var referrer = HttpContext.Request.UrlReferrer == null?Url.Action("Index", new { Id = id }) : HttpContext.Request.UrlReferrer.ToString();

                                            return(_batchRedirectService.Redirect(referrer, batchParameters));
                                        }
                                        return(_batchRedirectService.Redirect(action.Url, batchParameters));
                                    }

                                    var message = batchParameters.ContainsKey("BatchId") ? string.Format("Batch {0} failed.", batchParameters["BatchId"]) : "Batch failed.";
                                    Logger.Error(message);
                                    _orchardServices.Notifier.Error(T(message));
                                    foreach (var key in batchParameters.Keys)
                                    {
                                        Logger.Error("Batch Parameter {0} = {1}.", key, batchParameters[key]);
                                    }
                                    return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, message));
                                }
                            }
                            else
                            {
                                return(new HttpUnauthorizedResult("You do not have access to this bulk action."));
                            }
                        }
                    }


                    if (Request["sort"] != null)
                    {
                        _sortService.AddSortToEntity(process.Entities.First(), Request["sort"]);
                    }

                    if (process.Errors().Any())
                    {
                        foreach (var error in process.Errors())
                        {
                            _orchardServices.Notifier.Add(NotifyType.Error, T(error));
                        }
                    }
                    else
                    {
                        if (process.Entities.Any(e => !e.Fields.Any(f => f.Input)))
                        {
                            _orchardServices.WorkContext.Resolve <ISchemaHelper>().Help(process);
                        }

                        if (!process.Errors().Any())
                        {
                            var runner = _orchardServices.WorkContext.Resolve <IRunTimeExecute>();
                            try {
                                runner.Execute(process);
                                process.Request = "Run";
                                process.Time    = timer.ElapsedMilliseconds;

                                if (process.Errors().Any())
                                {
                                    foreach (var error in process.Errors())
                                    {
                                        _orchardServices.Notifier.Add(NotifyType.Error, T(error));
                                    }
                                    process.Status  = 500;
                                    process.Message = "There are errors in the pipeline.  See log.";
                                }
                                else
                                {
                                    process.Status  = 200;
                                    process.Message = "Ok";
                                }
                            } catch (Exception ex) {
                                Logger.Error(ex, ex.Message);
                                _orchardServices.Notifier.Error(T(ex.Message));
                            }
                        }
                    }
                }
                else
                {
                    _orchardServices.Notifier.Warning(user == "Anonymous" ? T("Sorry. Anonymous users do not have permission to view this report. You may need to login.") : T("Sorry {0}. You do not have permission to view this report.", user));
                }
            }

            return(View(new ReportViewModel(process, part)));
        }
Esempio n. 7
0
        public ActionResult Report(int id)
        {
            var timer = new Stopwatch();

            timer.Start();

            var process = new Process {
                Name = "Report"
            };

            var part = _orchardServices.ContentManager.Get(id).As <PipelineConfigurationPart>();

            if (part == null)
            {
                process.Name = "Not Found";
            }
            else
            {
                var user = _orchardServices.WorkContext.CurrentUser == null ? "Anonymous" : _orchardServices.WorkContext.CurrentUser.UserName ?? "Anonymous";

                if (_orchardServices.Authorizer.Authorize(Permissions.ViewContent, part))
                {
                    process = _processService.Resolve(part);

                    var parameters = Common.GetParameters(Request, _secureFileService, _orchardServices);
                    if (part.NeedsInputFile && Convert.ToInt32(parameters[Common.InputFileIdName]) == 0)
                    {
                        _orchardServices.Notifier.Add(NotifyType.Error, T("This transformalize expects a file."));
                        process.Name = "File Not Found";
                    }

                    process.Load(part.Configuration, parameters);
                    process.Buffer   = false; // no buffering for reports
                    process.ReadOnly = true;  // force reporting to omit system fields

                    // secure actions
                    var actions = process.Actions.Where(a => !a.Before && !a.After && !a.Description.StartsWith("Batch", StringComparison.OrdinalIgnoreCase));
                    foreach (var action in actions)
                    {
                        var p = _orchardServices.ContentManager.Get(action.Id);
                        if (!_orchardServices.Authorizer.Authorize(Permissions.ViewContent, p))
                        {
                            action.Description = "BatchUnauthorized";
                        }
                    }

                    var output = process.Output();

                    if (_reportOutputs.Contains(output.Provider))
                    {
                        Common.TranslatePageParametersToEntities(process, parameters, "page");

                        // change process for export and batch purposes
                        var reportType = Request["output"] ?? "page";
                        if (!_renderedOutputs.Contains(reportType))
                        {
                            if (reportType == "batch" && Request.HttpMethod.Equals("POST") && parameters.ContainsKey("action"))
                            {
                                var action = process.Actions.FirstOrDefault(a => a.Description == parameters["action"]);

                                if (action != null)
                                {
                                    // check security
                                    var actionPart = _orchardServices.ContentManager.Get(action.Id);
                                    if (actionPart != null && _orchardServices.Authorizer.Authorize(Permissions.ViewContent, actionPart))
                                    {
                                        // security okay
                                        parameters["entity"] = process.Entities.First().Alias;
                                        var batchParameters = _batchCreateService.Create(process, parameters);

                                        Common.AddOrchardVariables(batchParameters, _orchardServices, Request);

                                        batchParameters["count"] = parameters.ContainsKey("count") ? parameters["count"] : "0";
                                        var count = _batchWriteService.Write(Request, process, batchParameters);

                                        if (count > 0)
                                        {
                                            if (_batchRunService.Run(action, batchParameters))
                                            {
                                                if (action.Url == string.Empty)
                                                {
                                                    if (batchParameters.ContainsKey("BatchId"))
                                                    {
                                                        _orchardServices.Notifier.Information(T(string.Format("Processed {0} records in batch {1}.", count, batchParameters["BatchId"])));
                                                    }
                                                    else
                                                    {
                                                        _orchardServices.Notifier.Information(T(string.Format("Processed {0} records.", count)));
                                                    }
                                                    var referrer = HttpContext.Request.UrlReferrer == null?Url.Action("Report", new { Id = id }) : HttpContext.Request.UrlReferrer.ToString();

                                                    return(_batchRedirectService.Redirect(referrer, batchParameters));
                                                }
                                                return(_batchRedirectService.Redirect(action.Url, batchParameters));
                                            }

                                            var message = batchParameters.ContainsKey("BatchId") ? string.Format("Batch {0} failed.", batchParameters["BatchId"]) : "Batch failed.";
                                            Logger.Error(message);
                                            _orchardServices.Notifier.Error(T(message));
                                            foreach (var key in batchParameters.Keys)
                                            {
                                                Logger.Error("Batch Parameter {0} = {1}.", key, batchParameters[key]);
                                            }
                                            return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, message));
                                        }
                                    }
                                    else
                                    {
                                        return(new HttpUnauthorizedResult("You do not have access to this bulk action."));
                                    }
                                }
                            }
                            else     // export
                            {
                                ConvertToExport(user, process, part, reportType, parameters);
                                process.Load(process.Serialize(), parameters);
                            }
                        }

                        if (Request["sort"] != null)
                        {
                            _sortService.AddSortToEntity(process.Entities.First(), Request["sort"]);
                        }

                        if (process.Errors().Any())
                        {
                            foreach (var error in process.Errors())
                            {
                                _orchardServices.Notifier.Add(NotifyType.Error, T(error));
                            }
                        }
                        else
                        {
                            if (process.Entities.Any(e => !e.Fields.Any(f => f.Input)))
                            {
                                _orchardServices.WorkContext.Resolve <ISchemaHelper>().Help(process);
                            }

                            if (!process.Errors().Any())
                            {
                                var runner = _orchardServices.WorkContext.Resolve <IRunTimeExecute>();
                                try {
                                    runner.Execute(process);
                                    process.Request = "Run";
                                    process.Time    = timer.ElapsedMilliseconds;

                                    if (process.Errors().Any())
                                    {
                                        foreach (var error in process.Errors())
                                        {
                                            _orchardServices.Notifier.Add(NotifyType.Error, T(error));
                                        }
                                        process.Status  = 500;
                                        process.Message = "There are errors in the pipeline.  See log.";
                                    }
                                    else
                                    {
                                        process.Status  = 200;
                                        process.Message = "Ok";
                                    }

                                    var o = process.Output();
                                    switch (o.Provider)
                                    {
                                    case "kml":
                                    case "geojson":
                                    case "file":
                                        Response.AddHeader("content-disposition", "attachment; filename=" + o.File);
                                        switch (o.Provider)
                                        {
                                        case "kml":
                                            Response.ContentType = "application/vnd.google-earth.kml+xml";
                                            break;

                                        case "geojson":
                                            Response.ContentType = "application/vnd.geo+json";
                                            break;

                                        default:
                                            Response.ContentType = "application/csv";
                                            break;
                                        }
                                        Response.Flush();
                                        Response.End();
                                        return(new EmptyResult());

                                    case "excel":
                                        return(new FilePathResult(o.File, Common.ExcelContentType)
                                        {
                                            FileDownloadName = _slugService.Slugify(part.Title()) + ".xlsx"
                                        });

                                    default:      // page and map are rendered to page
                                        break;
                                    }
                                } catch (Exception ex) {
                                    Logger.Error(ex, ex.Message);
                                    _orchardServices.Notifier.Error(T(ex.Message));
                                }
                            }
                        }
                    }
                }
                else
                {
                    _orchardServices.Notifier.Warning(user == "Anonymous" ? T("Sorry. Anonymous users do not have permission to view this report. You may need to login.") : T("Sorry {0}. You do not have permission to view this report.", user));
                }
            }

            return(View(new ReportViewModel(process, part)));
        }
        public ActionResult Index(int id)
        {
            var timer = new Stopwatch();

            timer.Start();

            var process = new Process {
                Name = "Report"
            };

            var part = _orchardServices.ContentManager.Get(id).As <PipelineConfigurationPart>();

            if (part == null)
            {
                process.Name = "Not Found";
            }
            else
            {
                var user = _orchardServices.WorkContext.CurrentUser == null ? "Anonymous" : _orchardServices.WorkContext.CurrentUser.UserName ?? "Anonymous";

                if (_orchardServices.Authorizer.Authorize(Permissions.ViewContent, part))
                {
                    process = _processService.Resolve(part);

                    var parameters = Common.GetParameters(Request, _orchardServices, _secureFileService);
                    if (part.NeedsInputFile && Convert.ToInt32(parameters[Common.InputFileIdName]) == 0)
                    {
                        _orchardServices.Notifier.Add(NotifyType.Error, T("This transformalize expects a file."));
                        process.Name = "File Not Found";
                    }

                    GetStickyParameters(part.Id, parameters);

                    process.Load(part.Configuration, parameters);
                    process.Mode     = "report";
                    process.ReadOnly = true; // force reporting to omit system fields

                    SetStickyParameters(part.Id, process.Parameters);

                    // secure actions
                    var actions = process.Actions.Where(a => !a.Before && !a.After && !a.Description.StartsWith("Batch", StringComparison.OrdinalIgnoreCase));
                    foreach (var action in actions)
                    {
                        var p = _orchardServices.ContentManager.Get(action.Id);
                        if (!_orchardServices.Authorizer.Authorize(Permissions.ViewContent, p))
                        {
                            action.Description = "BatchUnauthorized";
                        }
                    }

                    var sizes = new List <int>();
                    sizes.AddRange(part.Sizes(part.PageSizes));
                    var stickySize = GetStickyParameter(part.Id, "size", () => sizes.Min());

                    Common.SetPageSize(process, parameters, sizes.Min(), stickySize, sizes.Max());

                    if (Request["sort"] != null)
                    {
                        _sortService.AddSortToEntity(process.Entities.First(), Request["sort"]);
                    }

                    if (process.Errors().Any())
                    {
                        foreach (var error in process.Errors())
                        {
                            _orchardServices.Notifier.Add(NotifyType.Error, T(error));
                        }
                    }
                    else
                    {
                        if (process.Entities.Any(e => !e.Fields.Any(f => f.Input)))
                        {
                            _orchardServices.WorkContext.Resolve <ISchemaHelper>().Help(process);
                        }

                        if (part.ReportRowClassField != string.Empty || part.ReportRowStyleField != string.Empty)
                        {
                            var fieldAliases = new HashSet <string>(process.GetAllFields().Select(f => f.Alias));
                            if (part.ReportRowClassField != string.Empty && !fieldAliases.Contains(part.ReportRowClassField))
                            {
                                _orchardServices.Notifier.Error(T("Can not find report row class field {0}", part.ReportRowClassField));
                                return(View(new ReportViewModel(process, part)));
                            }
                            if (part.ReportRowStyleField != string.Empty && !fieldAliases.Contains(part.ReportRowStyleField))
                            {
                                _orchardServices.Notifier.Error(T("Can not find report row style field {0}", part.ReportRowStyleField));
                                return(View(new ReportViewModel(process, part)));
                            }
                        }

                        if (!process.Errors().Any())
                        {
                            if (IsMissingRequiredParameters(process.Parameters, _orchardServices.Notifier))
                            {
                                return(View(new ReportViewModel(process, part)));
                            }

                            var runner = _orchardServices.WorkContext.Resolve <IRunTimeExecute>();
                            try {
                                runner.Execute(process);
                                process.Request = "Run";
                                process.Time    = timer.ElapsedMilliseconds;

                                if (process.Errors().Any())
                                {
                                    foreach (var error in process.Errors())
                                    {
                                        _orchardServices.Notifier.Add(NotifyType.Error, T(error));
                                    }
                                    process.Status  = 500;
                                    process.Message = "There are errors in the pipeline.  See log.";
                                }
                                else
                                {
                                    process.Status  = 200;
                                    process.Message = "Ok";
                                }
                            } catch (Exception ex) {
                                Logger.Error(ex, ex.Message);
                                _orchardServices.Notifier.Error(T(ex.Message));
                            }
                        }
                    }
                }
                else
                {
                    _orchardServices.Notifier.Warning(user == "Anonymous" ? T("Sorry. Anonymous users do not have permission to view this report. You may need to login.") : T("Sorry {0}. You do not have permission to view this report.", user));
                }
            }

            return(View(new ReportViewModel(process, part)));
        }
        public ActionResult Index(int id)
        {
            var timer = new Stopwatch();

            timer.Start();

            var settings = _orchardServices.WorkContext.CurrentSite.As <PipelineSettingsPart>();

            var process = new Process {
                Name = "Calendar"
            };

            var part = _orchardServices.ContentManager.Get(id).As <PipelineConfigurationPart>();

            if (part == null)
            {
                process.Name = "Not Found";
                return(new HttpNotFoundResult());
            }

            if (!_orchardServices.Authorizer.Authorize(Permissions.ViewContent, part))
            {
                return(new HttpUnauthorizedResult());
            }

            process = _processService.Resolve(part);

            var parameters = Common.GetParameters(Request, _orchardServices, _secureFileService);

            GetStickyParameters(part.Id, parameters);

            process.Load(part.Configuration, parameters);

            if (process.Errors().Any())
            {
                foreach (var error in process.Errors())
                {
                    _orchardServices.Notifier.Add(NotifyType.Error, T(error));
                }
                return(new HttpStatusCodeResult(500, "There are errors in the configuration."));
            }

            process.Mode     = "calendar";
            process.ReadOnly = true; // force calendar to omit system fields
            process.Pipeline = "parallel.linq";

            SetStickyParameters(part.Id, process.Parameters);

            // secure actions
            var actions = process.Actions.Where(a => !a.Before && !a.After && !a.Description.StartsWith("Batch", StringComparison.OrdinalIgnoreCase));

            foreach (var action in actions)
            {
                var p = _orchardServices.ContentManager.Get(action.Id);
                if (!_orchardServices.Authorizer.Authorize(Permissions.ViewContent, p))
                {
                    action.Description = "BatchUnauthorized";
                }
            }

            var sizes = new List <int>();

            sizes.AddRange(part.Sizes(part.PageSizes));
            if (part.CalendarPaging)
            {
                sizes.AddRange(part.Sizes(part.MapSizes)); // MapSizes is now "Extended" sizes
            }

            var stickySize = GetStickyParameter(part.Id, "size", () => sizes.Min());

            Common.SetPageSize(process, parameters, sizes.Min(), stickySize, sizes.Max());

            if (IsMissingRequiredParameters(process.Parameters, _orchardServices.Notifier))
            {
                return(View(new ReportViewModel(process, part)));
            }

            try {
                var runner = _orchardServices.WorkContext.Resolve <IRunTimeExecute>();
                runner.Execute(process);
                process.Request = "Execute";
                process.Time    = timer.ElapsedMilliseconds;

                if (process.Log.Any(l => l.LogLevel == LogLevel.Error))
                {
                    foreach (var error in process.Log.Where(l => l.LogLevel == LogLevel.Error))
                    {
                        _orchardServices.Notifier.Add(NotifyType.Error, T(error.Message));
                    }
                    process.Status = 500;
                    return(new HttpStatusCodeResult(500));
                }
            } catch (Exception ex) {
                Logger.Error(ex, ex.Message);
                _orchardServices.Notifier.Error(T(ex.Message));
            }

            return(View(new ReportViewModel(process, part)));
        }