Пример #1
0
        private void ConvertToExport(Process process, PipelineConfigurationPart part, IDictionary <string, string> parameters)
        {
            var fileName = _slugService.Slugify(part.Title()) + ".csv";
            var o        = process.Output();

            o.Provider         = "file";
            o.Delimiter        = ",";
            o.File             = fileName;
            parameters["page"] = "0";
            foreach (var entity in process.Entities)
            {
                entity.Page = 0;
                foreach (var field in entity.GetAllFields())
                {
                    field.T = "";
                    if (field.Output && field.Raw && field.Transforms.Any())
                    {
                        var lastTransform = field.Transforms.Last();
                        if (lastTransform.Method.In("tag", "razor"))
                        {
                            var firstParameter = lastTransform.Parameters.First();
                            field.Transforms.Remove(lastTransform);
                            field.T = "copy(" + firstParameter.Field + ")";
                        }
                    }
                }
            }
        }
Пример #2
0
        public async Task <ActionResult> StreamJson(string contentItemId)
        {
            var request = new TransformalizeRequest(contentItemId, HttpContext.User.Identity.Name)
            {
                Mode = "stream"
            };
            var stream = await _reportService.Validate(request);

            if (stream.Fails())
            {
                return(stream.ActionResult);
            }

            var o = stream.Process.GetOutputConnection();

            o.Stream   = true;
            o.Provider = "json";
            o.File     = _slugService.Slugify(stream.ContentItem.As <TitlePart>().Title) + ".json";

            Response.ContentType = "application/json";
            Response.Headers.Add("content-disposition", "attachment; filename=" + o.File);

            await _reportService.RunAsync(stream.Process);

            return(new EmptyResult());
        }
        public async Task <BoardColumn> Handle(CreateBoardColumnCommand request, CancellationToken cancellationToken)
        {
            var boardColumn = mappingService.Map <BoardColumnEntity>(request.BoardColumn);

            boardColumn.Slug = slugService.Slugify(boardColumn.Name);

            if (await dataContext.Set <BoardColumnEntity>().AnyAsync(x => x.Slug == boardColumn.Slug, cancellationToken))
            {
                throw new CreateBoardColumnCommandSlugExistsException();
            }

            var board = dataContext.Set <BoardEntity>().FirstOrDefault(x => x.Slug == request.BoardSlug);

            if (board == null)
            {
                throw new BoardNotFoundException();
            }

            dataContext.Set <BoardColumnEntity>().Add(boardColumn);
            board.Columns.Add(boardColumn);

            await dataContext.SaveChangesAsync();

            return(mappingService.Map <BoardColumn>(boardColumn));
        }
        public ActionResult Download(int id)
        {
            var part = _orchardServices.ContentManager.Get(id).As <PipelineConfigurationPart>();

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

            if (part == null)
            {
                process.Name = "Not Found";
                return(new FileStreamResult(Common.GenerateStreamFromString(process.Serialize()), "text/xml")
                {
                    FileDownloadName = id + ".xml"
                });
            }

            if (!_orchardServices.Authorizer.Authorize(Permissions.ViewContent, part))
            {
                process.Name = "Not Authorized";
                return(new FileStreamResult(Common.GenerateStreamFromString(process.Serialize()), "text/xml")
                {
                    FileDownloadName = id + ".xml"
                });
            }

            return(new FileStreamResult(Common.GenerateStreamFromString(part.Configuration), "text/" + part.EditorMode)
            {
                FileDownloadName = _slugService.Slugify(part.Title()) + "." + part.EditorMode
            });
        }
Пример #5
0
        public void SubmitPhoto(ObjectivePart objective, TeamPart team, HttpPostedFileBase photo)
        {
            Argument.ThrowIfNull(objective, "objective");
            Argument.ThrowIfNull(team, "team");
            Argument.ThrowIfNull(photo, "photo");

            var path = Path.Combine("Submits", _slugService.Slugify(team.Title), _slugService.Slugify(objective.Title));

            var guid      = Guid.NewGuid().ToString();
            var extension = photo.FileName.Split('.').LastOrDefault() ?? string.Empty;

            string publicUrl  = null;
            var    succesfull = true;

            try
            {
                using (Image img = Image.FromStream(photo.InputStream))
                {
                    double ratio  = img.Height > 1024 ? 1024.0 / img.Height : 1.0;
                    int    height = (int)(ratio * img.Height);
                    int    width  = (int)(ratio * img.Width);
                    using (Bitmap bitmap = new Bitmap(img, width, height))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            bitmap.Save(memoryStream, ImageFormat.Jpeg);
                            memoryStream.Position = 0;

                            publicUrl = _mediaService.UploadMediaFile(path, string.Format("{0}.{1}", guid, ".jpg"), memoryStream, false);
                        }
                    }
                }
            }
            catch (Exception)
            {
                succesfull = false;
            }
            if (succesfull)
            {
                var newSubmit = _actionSubmitService.NewActionSubmit <PhotoSubmitPart>(objective, team, "PhotoSubmit");
                newSubmit.PhotoUrl = publicUrl;
                _contentManager.Create(newSubmit);
            }
        }
        public void Evaluate(EvaluateContext context)
        {
            context.For <IContent>("Content")
            // {Content.Slug}
            .Token("Slug", (content => content == null ? String.Empty : _slugService.Slugify(content)))
            .Token("Path", (content => {
                var autoroutePart = content.As <AutoroutePart>();
                if (autoroutePart == null)
                {
                    return(String.Empty);
                }
                var isHomePage = _homeAliasService.IsHomePage(autoroutePart);
                return(isHomePage ? String.Empty : autoroutePart.DisplayAlias);
            }))
            // {Content.ParentPath}
            .Token("ParentPath", (content => {
                var common = content.As <CommonPart>();
                if (common == null || common.Container == null)
                {
                    return(String.Empty);
                }
                var containerAutoroutePart = common.Container.As <AutoroutePart>();
                if (containerAutoroutePart == null)
                {
                    return(String.Empty);
                }
                if (String.IsNullOrEmpty(containerAutoroutePart.DisplayAlias))
                {
                    return(String.Empty);
                }

                var isHomePage = _homeAliasService.IsHomePage(containerAutoroutePart);
                return(isHomePage ? "/" : containerAutoroutePart.DisplayAlias + "/");
            }));

            context.For <ContentTypeDefinition>("TypeDefinition")
            // {Content.ContentType.Slug}
            .Token("Slug", (ctd => _slugService.Slugify(ctd.DisplayName)));

            context.For <String>("Text")
            .Token("Slug", text => _slugService.Slugify(text));
        }
Пример #7
0
        public async Task <Board> HandleAsync(CreateBoardCommand command)
        {
            var board = mappingService.Map <BoardEntity>(command.Board);

            board.Slug = slugService.Slugify(board.Name);

            if (dataContext.Set <BoardEntity>().Any(x => x.Slug == board.Slug))
            {
                throw new CreateBoardCommandSlugExistsException();
            }

            dataContext.Set <BoardEntity>().Add(board);
            await dataContext.SaveChangesAsync();

            return(mappingService.Map <Board>(board));
        }
Пример #8
0
        public async Task <Board> Handle(CreateBoardCommand request, CancellationToken cancellationToken)
        {
            var board = mappingService.Map <BoardEntity>(request.Board);

            board.Slug = slugService.Slugify(board.Name);

            if (await dataContext.Set <BoardEntity>().AnyAsync(x => x.Slug == board.Slug, cancellationToken))
            {
                throw new CreateBoardCommandSlugExistsException();
            }

            dataContext.Set <BoardEntity>().Add(board);
            await dataContext.SaveChangesAsync();

            return(mappingService.Map <Board>(board));
        }
        public override Task GetContentItemAspectAsync(ContentItemAspectContext context)
        {
            return(context.ForAsync <RouteHandlerAspect>(aspect =>
            {
                // Only use default aspect if no other handler has set the aspect.
                if (String.IsNullOrEmpty(aspect.Path))
                {
                    // By default contained route is content item id + display text, if present.
                    var path = context.ContentItem.ContentItemId;
                    if (!String.IsNullOrEmpty(context.ContentItem.DisplayText))
                    {
                        path = path + "-" + context.ContentItem.DisplayText;
                    }

                    aspect.Path = _slugService.Slugify(path);
                }

                return Task.CompletedTask;
            }));
        }
        private async Task <ContentItem> CreateAsync(IContentManager contentManager, Posting posting)
        {
            var contentItem = await contentManager.NewAsync(Constants.Lever.ContentType);

            contentItem.DisplayText = posting.Text;
            contentItem.SetLeverPostingPart(posting);

            var autoroutePart = contentItem.As <AutoroutePart>();

            autoroutePart.Path = $"{_slugService.Slugify(posting.Text)}/{posting.Id}";
            contentItem.Apply(nameof(AutoroutePart), autoroutePart);

            ContentExtensions.Apply(contentItem, contentItem);

            await contentManager.CreateAsync(contentItem);

            await contentManager.PublishAsync(contentItem);

            return(contentItem);
        }
Пример #11
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));

        }
Пример #12
0
 public string GetSitemapSlug(string name)
 {
     return(_slugService.Slugify(name) + SitemapPathExtension);
 }
Пример #13
0
        public Task <FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext ctx)
        {
            var text = input.ToStringValue();

            return(Task.FromResult <FluidValue>(new StringValue(_slugService.Slugify(text))));
        }
Пример #14
0
 public string NormalizeFolderName(string folderName)
 {
     return(_slugService.Slugify(folderName));
 }
Пример #15
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 part = _orchardServices.ContentManager.Get(id).As <PipelineConfigurationPart>();

            if (part == null)
            {
                return(new HttpNotFoundResult());
            }

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

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

            var process = _processService.Resolve(part);

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

            process.Load(part.Configuration, parameters);
            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);
            process.Load(process.Serialize(), parameters);

            Common.SetPageSize(process, parameters, 0, 0, 0);

            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
            {
                var runner = _orchardServices.WorkContext.Resolve <IRunTimeExecute>();

                var o = process.Output();
                switch (o.Provider)
                {
                case "kml":
                case "json":
                case "geojson":
                case "file":
                    Response.Clear();
                    Response.BufferOutput = false;

                    switch (o.Provider)
                    {
                    case "kml":
                        Response.ContentType = "application/vnd.google-earth.kml+xml";
                        break;

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

                    case "json":
                        Response.ContentType = "application/json";
                        break;

                    default:
                        Response.ContentType = "application/csv";
                        break;
                    }

                    Response.AddHeader("content-disposition", "attachment; filename=" + o.File);
                    runner.Execute(process);
                    return(new EmptyResult());

                case "excel":
                    runner.Execute(process);

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

                default: // page and map are rendered to page
                    break;
                }
            }

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