public async Task <IActionResult> Index()
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.AccessAdminDashboard))
            {
                return(Forbid());
            }

            var widgets = await _adminDashboardService.GetWidgetsAsync(x => x.Published);

            var wrappers = new List <DashboardWrapper>();

            foreach (var item in widgets)
            {
                wrappers.Add(new DashboardWrapper
                {
                    Dashboard = item,
                    Content   = await _contentItemDisplayManager.BuildDisplayAsync(item, _updateModelAccessor.ModelUpdater, "DetailAdmin")
                });
            }

            var model = new AdminDashboardViewModel
            {
                Dashboards = wrappers.ToArray()
            };

            return(View(model));
        }
示例#2
0
        public async Task <IActionResult> Display(string contentItemId)
        {
            if (contentItemId == null)
            {
                return(NotFound());
            }

            var contentItem = await _contentManager.GetAsync(contentItemId);

            if (contentItem == null)
            {
                return(NotFound());
            }

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContent, contentItem))
            {
                return(this.ChallengeOrForbid());
            }
            //set to a global variable"
            //  _httpContextAccessor.HttpContext.Items["Content.CurrentContentItemId"] =contentItem.ContentItemId;
            // _httpContextAccessor.HttpContext.Items["CurrentContentItem"] =contentItem;

            var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater);


            return(View(model));
        }
示例#3
0
        // See it under /Lombiq.TrainingDemo/PersonList/OlderThan30.
        public async Task <ActionResult> OlderThan30()
        {
            var thresholdDate = _clock.UtcNow.AddYears(-30);
            var people        = await _session
                                // This will query for content items where the related PersonPartIndex.BirthDateUtc is lower than the
                                // threshold date. Notice that there is no Where method. The Query method has an overload for that
                                // which can be useful if you don't want to filter in multiple indexes.
                                .Query <ContentItem, PersonPartIndex>(index => index.BirthDateUtc < thresholdDate)
                                .ListAsync();

            // Now let's build the display shape for a content item! Notice that this is not the IDisplayManager
            // service. The IContentItemDisplayManager is an abstraction over that and it's specifically for content
            // items. The reason we need that is that a ContentItem doesn't have a DisplayDriver but the ContentParts
            // and ContentFields attached to the ContentItem have. This service will handle generating all the drivers
            // created for these parts and fields.
            // NEXT STATION: Drivers/PersonPartDisplayDriver
            var shapes = await Task.WhenAll(people.Select(async person =>
                                                          await _contentItemDisplayManager.BuildDisplayAsync(person, this, "Summary")));

            // Now assuming that you've already created a few Person content items on the dashboard and some of
            // these persons are more than 30 years old then this query will contain items to display.
            // NEXT STATION: Views/PersonList/OlderThan30.cshtml

            return(View(shapes));
        }
示例#4
0
        public async Task <IActionResult> ListBinderTemplates()
        {
            string alias = "binder-templates";

            string contentItemId = alias != null
                ? await _contentAliasManager.GetContentItemIdAsync("alias:" + alias)
                : "NotFound";

            if (contentItemId == "NotFound")
            {
                return(NotFound());
            }

            var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);

            if (contentItem == null)
            {
                return(NotFound());
            }

            if (!await _authorizationService.AuthorizeAsync(User, OrchardCore.Contents.Permissions.ViewContent,
                                                            contentItem))
            {
                return(Unauthorized());
            }

            var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "DetailAdmin");

            return(View("DisplayByAlias", model));
        }
示例#5
0
        public async Task <IActionResult> Index()
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers))
            {
                return(Unauthorized());
            }

            var layers = await _layerService.GetLayersAsync();

            var widgets = await _layerService.GetLayerWidgetsAsync(c => c.Latest == true);

            var model = new LayersIndexViewModel {
                Layers = layers.Layers
            };

            model.Zones = (await _siteService.GetSiteSettingsAsync()).As <LayerSettings>()?.Zones ?? Array.Empty <string>();

            model.Widgets = new Dictionary <string, List <dynamic> >();

            foreach (var widget in widgets.OrderBy(x => x.Position))
            {
                var            zone = widget.Zone;
                List <dynamic> list;
                if (!model.Widgets.TryGetValue(zone, out list))
                {
                    model.Widgets.Add(zone, list = new List <dynamic>());
                }

                list.Add(await _contentItemDisplayManager.BuildDisplayAsync(widget.ContentItem, this, "SummaryAdmin"));
            }

            return(View(model));
        }
        public async Task <IActionResult> BuildDisplay(string contentItemId, string poiContentItemId)
        {
            if (string.IsNullOrWhiteSpace(contentItemId) || string.IsNullOrWhiteSpace(poiContentItemId))
            {
                return(NotFound());
            }

            var contentItem = await _contentManager.GetAsync(contentItemId);

            if (contentItem == null || !contentItem.Has <MapPoisPart>())
            {
                return(NotFound());
            }

            var part           = contentItem.As <MapPoisPart>();
            var poiContentItem = part.ContentItems.SingleOrDefault(x => x.ContentItemId == poiContentItemId);

            if (poiContentItem == null)
            {
                return(NotFound());
            }

            return(View("Display", new BuildDisplayViewModel
            {
                DisplayShape = await _contentItemDisplayManager.BuildDisplayAsync(poiContentItem, _updateModelAccessor.ModelUpdater)
            }));
        }
        public async Task <IActionResult> Index(string stripePaymentFormId, [FromQuery] Dictionary <string, string> metadata)
        {
            var stripePaymentForm = await _contentManager.GetAsync(stripePaymentFormId);

            //payment part
            var paymentPart = stripePaymentForm.As <PaymentPart>();
            var cost        = (long)(paymentPart.Cost * 100);
            var currency    = paymentPart.Currency.Text;

            //stripe payment form part
            var stripePaymentFormPart = stripePaymentForm.As <StripePaymentFormPart>();
            var StripeSecretKey       = stripePaymentFormPart.StripeSecretKey.Text;
            var stripePublishableKey  = stripePaymentFormPart.StripePublishableKey.Text;
            var paymentIntent         = await _stripePaymentService.CreatePaymentIntent(StripeSecretKey, cost, currency, metadata);

            //Should be using shapes but need a way to pass in custom metadata to an existing form
            var shape = await _contentDisplay.BuildDisplayAsync(stripePaymentForm, _updateModelAccessor.ModelUpdater);

            var stripePaymentFormViewModel = new StripePaymentFormViewModel()
            {
                PaymentIntentClientSecret = paymentIntent.ClientSecret,
                StripePublishableAPIKey   = stripePublishableKey,
                Shape = shape
            };

            return(View(stripePaymentFormViewModel));
        }
示例#8
0
        public async Task <IActionResult> Display(string contentItemId)
        {
            var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Published);

            if (contentItem == null)
            {
                return(NotFound());
            }

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContent, contentItem))
            {
                return(Unauthorized());
            }

            var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this);

            return(View(model));
        }
        public async Task <IActionResult> Display(string contentItemId)
        {
            var contentItem = await _contentManager.GetAsync(contentItemId);

            if (contentItem == null)
            {
                return(NotFound());
            }

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContent, contentItem))
            {
                return(User.Identity.IsAuthenticated ? (IActionResult)Forbid() : Challenge());
            }

            var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this);

            return(View(model));
        }
示例#10
0
        public async Task <IActionResult> Display(string contentItemId, string jsonPath)
        {
            var contentItem = await _contentManager.GetAsync(contentItemId, jsonPath);

            if (contentItem == null)
            {
                return(NotFound());
            }

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContent, contentItem))
            {
                return(this.ChallengeOrForbid());
            }

            var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater);

            return(View(model));
        }
示例#11
0
        public async Task <IActionResult> DisplayAsync([FromQuery] string contentItemId)
        {
            ContentItem contentItem = await _contentManager.GetAsync(contentItemId);


            IShape model = await _contentItemDisplayManager
                           .BuildDisplayAsync(contentItem,
                                              _updateModelAccessor.ModelUpdater);

            return(View(model));
        }
示例#12
0
        public async Task <IActionResult> Index(string id, string taxonomyid)
        {
            var taxonomyContentItem = await _contentManager.GetAsync(taxonomyid);

            var termContentItem = TaxonomyOrchardHelperExtensions.FindTerm(taxonomyContentItem.Content.TaxonomyPart.Terms as JArray, id);
            // This part is added automatically to all terms
            // termContentItem.Weld(new TermPart());
            var model = await _contentItemDisplayManager.BuildDisplayAsync(termContentItem, this, "Detail");

            //https://english.orchardproject.hu/blog/the-orchard-dynamic-page-pattern
            return(View(model));
        }
示例#13
0
        public async Task <IActionResult> Render()
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTemplates))
            {
                return(this.ChallengeOrForbid());
            }

            // Mark request as a `Preview` request so that drivers / handlers or underlying services can be aware of an active preview mode.
            HttpContext.Features.Set(new ContentPreviewFeature());

            var name    = Request.Form["Name"];
            var content = Request.Form["Content"];

            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(content))
            {
                HttpContext.Items["OrchardCore.PreviewTemplate"] = new TemplateViewModel {
                    Name = name, Content = content
                };
            }

            var handle = Request.Form["Handle"].ToString();

            string contentItemId;

            if (string.IsNullOrEmpty(handle) || handle == _homeUrl)
            {
                var homeRoute = (await _siteService.GetSiteSettingsAsync()).HomeRoute;
                contentItemId = homeRoute["contentItemId"]?.ToString();
            }
            else
            {
                var index = handle.IndexOf(_homeUrl, StringComparison.Ordinal);
                handle        = (index < 0) ? handle : handle.Substring(_homeUrl.Length);
                contentItemId = await _contentHandleManager.GetContentItemIdAsync("slug:" + handle);
            }

            if (string.IsNullOrEmpty(contentItemId))
            {
                return(NotFound());
            }

            var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Published);

            if (contentItem == null)
            {
                return(NotFound());
            }

            var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater, "Detail");

            return(View(model));
        }
示例#14
0
        public async Task <ActionResult> Display(string contentItemId)
        {
            var contentItem = await _contentManager.GetAsync(contentItemId);

            if (contentItem == null)
            {
                return(NotFound());
            }

            var shape = await _contentDisplay.BuildDisplayAsync(contentItem, this);

            return(View(shape));
        }
示例#15
0
        // /Contents/Item/Display/72
        public async Task <IActionResult> Display(int id, int?version)
        {
            if (version.HasValue)
            {
                return(await Preview(id, version));
            }

            var contentItem = await _contentManager.GetAsync(id, VersionOptions.Published);

            if (contentItem == null)
            {
                return(HttpNotFound());
            }

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContent, contentItem))
            {
                return(new HttpUnauthorizedResult());
            }

            var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this);

            return(View(model));
        }
示例#16
0
        public async Task <IActionResult> Render()
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTemplates))
            {
                return(Unauthorized());
            }

            var name    = Request.Form["Name"];
            var content = Request.Form["Content"];

            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(content))
            {
                HttpContext.Items["OrchardCore.PreviewTemplate"] = new TemplateViewModel {
                    Name = name, Content = content
                };
            }

            var alias = Request.Form["Alias"].ToString();

            string contentItemId = string.Empty;

            if (string.IsNullOrEmpty(alias) || alias == _homeUrl)
            {
                var homeRoute = (await _siteService.GetSiteSettingsAsync()).HomeRoute;
                contentItemId = homeRoute["contentItemId"]?.ToString();
            }
            else
            {
                var index = alias.IndexOf(_homeUrl);
                alias         = (index < 0) ? alias : alias.Substring(_homeUrl.Length);
                contentItemId = await _contentAliasManager.GetContentItemIdAsync("slug:" + alias);
            }

            if (string.IsNullOrEmpty(contentItemId))
            {
                return(NotFound());
            }

            var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Published);

            if (contentItem == null)
            {
                return(NotFound());
            }

            var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "Detail");

            return(View(model));
        }
        public async Task <IActionResult> Render()
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ContentPreview))
            {
                return(Unauthorized());
            }

            var contentItemType = Request.Form["ContentItemType"];
            var contentItem     = await _contentManager.NewAsync(contentItemType);

            // Assign the ids from the currently edited item so that validation thinks
            // it's working on the same item. For instance if drivers are checking name unicity
            // they need to think this is the same existing item (AutoroutePart).

            var contentItemId        = Request.Form["PreviewContentItemId"];
            var contentItemVersionId = Request.Form["PreviewContentItemVersionId"];

            int.TryParse(Request.Form["PreviewId"], out var contentId);

            contentItem.Id                   = contentId;
            contentItem.ContentItemId        = contentItemId;
            contentItem.ContentItemVersionId = contentItemVersionId;
            contentItem.CreatedUtc           = _clock.UtcNow;
            contentItem.ModifiedUtc          = _clock.UtcNow;
            contentItem.PublishedUtc         = _clock.UtcNow;

            // TODO: we should probably get this value from the main editor as it might impact validators
            var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, this, true);

            if (!ModelState.IsValid)
            {
                var errors = new List <string>();
                foreach (var modelState in ValidationHelpers.GetModelStateList(ViewData, false))
                {
                    for (var i = 0; i < modelState.Errors.Count; i++)
                    {
                        var modelError = modelState.Errors[i];
                        var errorText  = ValidationHelpers.GetModelErrorMessageOrDefault(modelError);
                        errors.Add(errorText);
                    }
                }

                return(StatusCode(500, new { errors = errors }));
            }

            model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "Detail");

            return(View(model));
        }
示例#18
0
        public async Task OnGetAsync(string contentItemId)
        {
            var query = _session.Query <ContentItem, ContentItemIndex>()
                        .With <ContentItemIndex>(x => x.ContentType == "Foo" && x.Published);
            var contentItems = await query.ListAsync();

            var updater = _updateModelAccessor.ModelUpdater;

            Items = new List <dynamic>();
            Title = "Foo List";

            foreach (var contentItem in contentItems)
            {
                Items.Add(await _contentDisplay.BuildDisplayAsync(contentItem, updater));
            }
        }
示例#19
0
        public async Task <ActionResult> Display(string contentItemId)
        {
            var contentItem = await _contentManager.GetAsync(contentItemId);

            if (contentItem == null)
            {
                return(NotFound());
            }

            if (!await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, CommonPermissions.ViewContent, contentItem))
            {
                return(Forbid());
            }

            var shape = await _contentDisplay.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater);

            return(View(shape));
        }
        public async Task <IViewComponentResult> InvokeAsync(string contentItemId = null, string displayType = null)
        {
            ContentItem contentItem = null;

            if (contentItemId != null)
            {
                contentItem = await _contentManager.GetAsync(contentItemId);
            }

            if (contentItem == null)
            {
                throw new ArgumentException("Content item not found");
            }

            var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _modelUpdaterAccessor.ModelUpdater, displayType);

            return(View(model));
        }
示例#21
0
        public async Task <IActionResult> Index()
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers))
            {
                return(Forbid());
            }

            var layers = await _layerService.GetLayersAsync();

            var widgets = await _layerService.GetLayerWidgetsMetadataAsync(c => c.Latest == true);

            var model = new LayersIndexViewModel {
                Layers = layers.Layers.ToList()
            };

            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var contentDefinitions = _contentDefinitionManager.ListTypeDefinitions();

            model.Zones   = siteSettings.As <LayerSettings>().Zones ?? Array.Empty <string>();
            model.Widgets = new Dictionary <string, List <dynamic> >();

            foreach (var widget in widgets.OrderBy(x => x.Position))
            {
                var            zone = widget.Zone;
                List <dynamic> list;
                if (!model.Widgets.TryGetValue(zone, out list))
                {
                    model.Widgets.Add(zone, list = new List <dynamic>());
                }

                if (contentDefinitions.Any(c => c.Name == widget.ContentItem.ContentType))
                {
                    list.Add(await _contentItemDisplayManager.BuildDisplayAsync(widget.ContentItem, _updateModelAccessor.ModelUpdater, "SummaryAdmin"));
                }
                else
                {
                    _logger.LogWarning("The Widget content item with id {ContentItemId} has no matching {ContentType} content type definition.", widget.ContentItem.ContentItemId, widget.ContentItem.ContentType);
                    await _notifier.WarningAsync(H["The Widget content item with id {0} has no matching {1} content type definition.", widget.ContentItem.ContentItemId, widget.ContentItem.ContentType]);
                }
            }

            return(View(model));
        }
示例#22
0
        public async Task <IActionResult> Index(PagerParameters pagerParameters) //ListContentsViewModel model,
        {
            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var pager = new Pager(pagerParameters, siteSettings.PageSize);

            var query = _session.Query <ContentItem, ContentItemIndex>();

            query = query.With <ContentItemIndex>(x => x.ContentType == contentType);
            query = query.With <ContentItemIndex>(x => x.Published);
            query = query.OrderByDescending(x => x.PublishedUtc);

            var maxPagedCount = siteSettings.MaxPagedCount;

            if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
            {
                pager.PageSize = maxPagedCount;
            }

            var routeData  = new RouteData();
            var pagerShape = (await New.Pager(pager)).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : await query.CountAsync()).RouteData(routeData);

            var pageOfContentItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync();

            IEnumerable <ContentItem> model = await query.ListAsync();

            // Prepare the content items Summary Admin shape
            var contentItemSummaries = new List <dynamic>();

            foreach (var contentItem in pageOfContentItems)
            {
                contentItemSummaries.Add(await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater, "Summary"));
            }

            var viewModel = new ListContentsViewModel
            {
                ContentItems = contentItemSummaries,
                Pager        = pagerShape
                               //Options = model.Options
            };

            return(View(viewModel));
        }
示例#23
0
        public async Task <IActionResult> Index(string id)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ContentPreview))
            {
                return(Unauthorized());
            }

            var contentItem = _contentManager.New(id);

            var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, this);

            if (!ModelState.IsValid)
            {
                return(StatusCode(500));
            }

            model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "Detail");

            return(View(model));
        }
示例#24
0
        public async Task <IActionResult> List(ListContentsViewModel model, PagerParameters pagerParameters)
        {
            var siteSettings = await _siteService.GetSiteSettingsAsync();

            Pager pager = new Pager(pagerParameters, siteSettings.PageSize);

            var query = _session.Query <ContentItem, ContentItemIndex>();

            switch (model.Options.ContentsStatus)
            {
            case ContentsStatus.Published:
                query = query.With <ContentItemIndex>(x => x.Published);
                break;

            case ContentsStatus.Draft:
                query = query.With <ContentItemIndex>(x => x.Latest && !x.Published);
                break;

            case ContentsStatus.AllVersions:
                query = query.With <ContentItemIndex>(x => x.Latest);
                break;

            default:
                query = query.With <ContentItemIndex>(x => x.Latest);
                break;
            }

            if (!string.IsNullOrEmpty(model.TypeName))
            {
                var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.TypeName);
                if (contentTypeDefinition == null)
                {
                    return(NotFound());
                }

                model.TypeDisplayName = contentTypeDefinition.ToString();

                // We display a specific type even if it's not listable so that admin pages
                // can reuse the Content list page for specific types.
                query = query.With <ContentItemIndex>(x => x.ContentType == model.TypeName);
            }
            else
            {
                var listableTypes = (await GetListableTypesAsync()).Select(t => t.Name).ToArray();
                if (listableTypes.Any())
                {
                    query = query.With <ContentItemIndex>(x => x.ContentType.IsIn(listableTypes));
                }
            }

            switch (model.Options.OrderBy)
            {
            case ContentsOrder.Modified:
                query = query.OrderByDescending(x => x.ModifiedUtc);
                break;

            case ContentsOrder.Published:
                query = query.OrderByDescending(cr => cr.PublishedUtc);
                break;

            case ContentsOrder.Created:
                query = query.OrderByDescending(cr => cr.CreatedUtc);
                break;

            default:
                query = query.OrderByDescending(cr => cr.ModifiedUtc);
                break;
            }

            //if (!String.IsNullOrWhiteSpace(model.Options.SelectedCulture))
            //{
            //    query = _cultureFilter.FilterCulture(query, model.Options.SelectedCulture);
            //}

            //if (model.Options.ContentsStatus == ContentsStatus.Owner)
            //{
            //    query = query.Where<CommonPartRecord>(cr => cr.OwnerId == Services.WorkContext.CurrentUser.Id);
            //}

            model.Options.SelectedFilter = model.TypeName;
            model.Options.FilterOptions  = (await GetListableTypesAsync())
                                           .Select(ctd => new KeyValuePair <string, string>(ctd.Name, ctd.DisplayName))
                                           .ToList().OrderBy(kvp => kvp.Value);

            //model.Options.Cultures = _cultureManager.ListCultures();

            // Invoke any service that could alter the query
            await _contentAdminFilters.InvokeAsync(x => x.FilterAsync(query, model, pagerParameters, this), Logger);

            var maxPagedCount = siteSettings.MaxPagedCount;

            if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
            {
                pager.PageSize = maxPagedCount;
            }

            var pagerShape         = (await New.Pager(pager)).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : await query.CountAsync());
            var pageOfContentItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync();

            var contentItemSummaries = new List <dynamic>();

            foreach (var contentItem in pageOfContentItems)
            {
                contentItemSummaries.Add(await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "SummaryAdmin"));
            }

            var viewModel = (await New.ViewModel())
                            .ContentItems(contentItemSummaries)
                            .Pager(pagerShape)
                            .Options(model.Options)
                            .TypeDisplayName(model.TypeDisplayName ?? "");

            return(View(viewModel));
        }
示例#25
0
        public async Task <IActionResult> Render()
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ContentPreview))
            {
                return(Unauthorized());
            }

            var contentItemType = Request.Form["ContentItemType"];
            var contentItem     = await _contentManager.NewAsync(contentItemType);

            // Assign the ids from the currently edited item so that validation thinks
            // it's working on the same item. For instance if drivers are checking name unicity
            // they need to think this is the same existing item (AutoroutePart).

            var contentItemId        = Request.Form["PreviewContentItemId"];
            var contentItemVersionId = Request.Form["PreviewContentItemVersionId"];

            // Unique contentItem.Id that only Preview is using such that another
            // stored document can't have the same one in the IContentManagerSession index

            contentItem.Id                   = -1;
            contentItem.ContentItemId        = contentItemId;
            contentItem.ContentItemVersionId = contentItemVersionId;
            contentItem.CreatedUtc           = _clock.UtcNow;
            contentItem.ModifiedUtc          = _clock.UtcNow;
            contentItem.PublishedUtc         = _clock.UtcNow;
            contentItem.Published            = true;

            // TODO: we should probably get this value from the main editor as it might impact validators
            var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, this, true);

            if (!ModelState.IsValid)
            {
                var errors = new List <string>();
                foreach (var modelState in ValidationHelpers.GetModelStateList(ViewData, false))
                {
                    for (var i = 0; i < modelState.Errors.Count; i++)
                    {
                        var modelError = modelState.Errors[i];
                        var errorText  = ValidationHelpers.GetModelErrorMessageOrDefault(modelError);
                        errors.Add(errorText);
                    }
                }

                return(StatusCode(500, new { errors = errors }));
            }

            var previewAspect = await _contentManager.PopulateAspectAsync(contentItem, new PreviewAspect());

            if (!String.IsNullOrEmpty(previewAspect.PreviewUrl))
            {
                // The PreviewPart is configured, we need to set the fake content item
                _contentManagerSession.Store(contentItem);

                if (!previewAspect.PreviewUrl.StartsWith('/'))
                {
                    previewAspect.PreviewUrl = "/" + previewAspect.PreviewUrl;
                }

                Request.HttpContext.Items["PreviewPath"] = previewAspect.PreviewUrl;

                return(Ok());
            }

            model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "Detail");

            return(View(model));
        }
        public async Task <ActionResult> List(ListContentsViewModel model, PagerParameters pagerParameters, string contentTypeId = "")
        {
            if (model.PageCount == 0)
            {
                model.PageCount = 999;
            }

            List <ContentItem> contentItems;
            var siteSettings = await siteService.GetSiteSettingsAsync();

            var pager = new Pager(pagerParameters, model.PageCount);
            var query = await session.Query <ContentItem, ContentItemIndex>()
                        .Where(x => x.ContentType == "CommentPost" && x.Latest == true && x.Published == true)
                        .ListAsync();

            /* Get all comments for Document */
            contentItems = query.Where(x => BelongsToDocument(x, contentTypeId)).ToList();

            /* Group By */
            switch (model.Options.GroupBy)
            {
            case ContentsGrouping.Thread:
                /* Update Child Count */
                foreach (var contentItem in contentItems)
                {
                    string parentId = contentItem.ContentItemId;
                    contentItem.Content.CommentPost.ChildCount.Value = contentItems.Count(comment => IsChildOf(parentId, comment));
                }
                if (!model.OnlySubComments)
                {
                    contentItems = contentItems.Where(x => IsParentComment(x)).ToList();
                }
                break;

            case ContentsGrouping.Single:
                contentItems = contentItems.ToList();
                break;

            default:
                contentItems = contentItems.ToList();
                break;
            }


            /* Get Only Sub Comments */
            if (model.OnlySubComments && !string.IsNullOrEmpty(model.ParentId))
            {
                contentItems = contentItems.Where(x => IsChildOf(model.ParentId, x)).ToList();
            }

            /* Order By */
            switch (model.Options.OrderBy)
            {
            case ContentsOrder.Date:
                logger.LogInformation("Order By Date");
                contentItems = contentItems.OrderByDescending(x => x.PublishedUtc).ToList();
                break;

            case ContentsOrder.Rank:
                logger.LogInformation("Order By Rank");
                break;

            default:
                logger.LogInformation("No Order");
                contentItems = contentItems.OrderByDescending(x => x.PublishedUtc).ToList();
                break;
            }

            for (int i = 0; i < contentItems.Count; i++)
            {
                contentItems[i] = await contentManager.LoadAsync(contentItems[i]);
            }

            /* Prepare Pager */
            var maxPagedCount = siteSettings.MaxPagedCount;

            if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
            {
                pager.PageSize = maxPagedCount;
            }

            var pagerShape         = (await New.Pager(pager)).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : contentItems.Count());
            var pageOfContentItems = contentItems.Skip(pager.GetStartIndex()).Take(model.PageCount);

            var contentItemSummaries = new List <dynamic>();

            foreach (var contentItem in pageOfContentItems)
            {
                contentItemSummaries.Add(await contentItemDisplayManager.BuildDisplayAsync(contentItem, updateModelAccessor.ModelUpdater));
            }

            var viewModel = new ListContentsViewModel
            {
                ContentItems    = contentItemSummaries,
                Options         = model.Options,
                PageCount       = model.PageCount,
                Pager           = pagerShape,
                OnlySubComments = model.OnlySubComments
            };

            return(PartialView(viewModel));
        }
示例#27
0
        public async Task <IActionResult> List(
            [ModelBinder(BinderType = typeof(ContentItemFilterEngineModelBinder), Name = "q")] QueryFilterResult <ContentItem> queryFilterResult,
            ContentOptionsViewModel options,
            PagerParameters pagerParameters,
            string contentTypeId = "")
        {
            var context = _httpContextAccessor.HttpContext;
            var contentTypeDefinitions = _contentDefinitionManager.ListTypeDefinitions()
                                         .Where(ctd => ctd.GetSettings <ContentTypeSettings>().Creatable)
                                         .OrderBy(ctd => ctd.DisplayName);

            if (!await _authorizationService.AuthorizeContentTypeDefinitionsAsync(User, CommonPermissions.EditContent, contentTypeDefinitions, _contentManager))
            {
                return(Forbid());
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var pager = new Pager(pagerParameters, siteSettings.PageSize);

            // This is used by the AdminMenus so needs to be passed into the options.
            if (!String.IsNullOrEmpty(contentTypeId))
            {
                options.SelectedContentType = contentTypeId;
            }

            // The filter is bound seperately and mapped to the options.
            // The options must still be bound so that options that are not filters are still bound
            options.FilterResult = queryFilterResult;

            // Populate the creatable types.
            if (!String.IsNullOrEmpty(options.SelectedContentType))
            {
                // When the selected content type is provided via the route or options a placeholder node is used to apply a filter.
                options.FilterResult.TryAddOrReplace(new ContentTypeFilterNode(options.SelectedContentType));

                var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(options.SelectedContentType);
                if (contentTypeDefinition == null)
                {
                    return(NotFound());
                }

                var creatableList = new List <SelectListItem>();

                // Allows non creatable types to be created by another admin page.
                if (contentTypeDefinition.GetSettings <ContentTypeSettings>().Creatable || options.CanCreateSelectedContentType)
                {
                    var contentItem = await _contentManager.NewAsync(contentTypeDefinition.Name);

                    contentItem.Owner = context.User.FindFirstValue(ClaimTypes.NameIdentifier);

                    if (await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.EditContent, contentItem))
                    {
                        creatableList.Add(new SelectListItem(new LocalizedString(contentTypeDefinition.DisplayName, contentTypeDefinition.DisplayName).Value, contentTypeDefinition.Name));
                    }
                }

                options.CreatableTypes = creatableList;
            }

            if (options.CreatableTypes == null)
            {
                var creatableList = new List <SelectListItem>();
                if (contentTypeDefinitions.Any())
                {
                    foreach (var contentTypeDefinition in contentTypeDefinitions)
                    {
                        var contentItem = await _contentManager.NewAsync(contentTypeDefinition.Name);

                        contentItem.Owner = context.User.FindFirstValue(ClaimTypes.NameIdentifier);

                        if (await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.EditContent, contentItem))
                        {
                            creatableList.Add(new SelectListItem(new LocalizedString(contentTypeDefinition.DisplayName, contentTypeDefinition.DisplayName).Value, contentTypeDefinition.Name));
                        }
                    }
                }

                options.CreatableTypes = creatableList;
            }

            // We populate the remaining SelectLists.
            options.ContentStatuses = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = S["Latest"], Value = nameof(ContentsStatus.Latest), Selected = (options.ContentsStatus == ContentsStatus.Latest)
                },
                new SelectListItem()
                {
                    Text = S["Published"], Value = nameof(ContentsStatus.Published), Selected = (options.ContentsStatus == ContentsStatus.Published)
                },
                new SelectListItem()
                {
                    Text = S["Unpublished"], Value = nameof(ContentsStatus.Draft), Selected = (options.ContentsStatus == ContentsStatus.Draft)
                },
                new SelectListItem()
                {
                    Text = S["All versions"], Value = nameof(ContentsStatus.AllVersions), Selected = (options.ContentsStatus == ContentsStatus.AllVersions)
                }
            };

            if (await _authorizationService.AuthorizeAsync(context.User, Permissions.ListContent))
            {
                options.ContentStatuses.Insert(1, new SelectListItem()
                {
                    Text = S["Owned by me"], Value = nameof(ContentsStatus.Owner)
                });
            }

            options.ContentSorts = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = S["Recently created"], Value = nameof(ContentsOrder.Created), Selected = (options.OrderBy == ContentsOrder.Created)
                },
                new SelectListItem()
                {
                    Text = S["Recently modified"], Value = nameof(ContentsOrder.Modified), Selected = (options.OrderBy == ContentsOrder.Modified)
                },
                new SelectListItem()
                {
                    Text = S["Recently published"], Value = nameof(ContentsOrder.Published), Selected = (options.OrderBy == ContentsOrder.Published)
                },
                new SelectListItem()
                {
                    Text = S["Title"], Value = nameof(ContentsOrder.Title), Selected = (options.OrderBy == ContentsOrder.Title)
                },
            };

            options.ContentsBulkAction = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = S["Publish Now"], Value = nameof(ContentsBulkAction.PublishNow)
                },
                new SelectListItem()
                {
                    Text = S["Unpublish"], Value = nameof(ContentsBulkAction.Unpublish)
                },
                new SelectListItem()
                {
                    Text = S["Delete"], Value = nameof(ContentsBulkAction.Remove)
                }
            };

            if ((String.IsNullOrEmpty(options.SelectedContentType) || String.IsNullOrEmpty(contentTypeId)) && options.ContentTypeOptions == null)
            {
                var listableTypes      = new List <ContentTypeDefinition>();
                var userNameIdentifier = context.User.FindFirstValue(ClaimTypes.NameIdentifier);

                foreach (var ctd in _contentDefinitionManager.ListTypeDefinitions())
                {
                    if (ctd.GetSettings <ContentTypeSettings>().Listable)
                    {
                        var contentItem = await _contentManager.NewAsync(ctd.Name);

                        contentItem.Owner = userNameIdentifier;
                        var authorized = await _authorizationService.AuthorizeAsync(User, CommonPermissions.EditContent, contentItem);

                        if (authorized)
                        {
                            listableTypes.Add(ctd);
                        }
                    }
                }

                var contentTypeOptions = listableTypes
                                         .Select(ctd => new KeyValuePair <string, string>(ctd.Name, ctd.DisplayName))
                                         .ToList().OrderBy(kvp => kvp.Value);

                options.ContentTypeOptions = new List <SelectListItem>
                {
                    new SelectListItem()
                    {
                        Text = S["All content types"], Value = ""
                    }
                };

                foreach (var option in contentTypeOptions)
                {
                    options.ContentTypeOptions.Add(new SelectListItem()
                    {
                        Text = option.Value, Value = option.Key, Selected = (option.Value == options.SelectedContentType)
                    });
                }
            }

            // If ContentTypeOptions is not initialized by query string or by the code above, initialize it
            if (options.ContentTypeOptions == null)
            {
                options.ContentTypeOptions = new List <SelectListItem>();
            }

            // With the options populated we filter the query, allowing the filters to alter the options.
            var query = await _contentsAdminListQueryService.QueryAsync(options, _updateModelAccessor.ModelUpdater);

            // The search text is provided back to the UI.
            options.SearchText         = options.FilterResult.ToString();
            options.OriginalSearchText = options.SearchText;

            // Populate route values to maintain previous route data when generating page links.
            options.RouteValues.TryAdd("q", options.FilterResult.ToString());

            var routeData     = new RouteData(options.RouteValues);
            var maxPagedCount = siteSettings.MaxPagedCount;

            if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
            {
                pager.PageSize = maxPagedCount;
            }

            var pagerShape = (await New.Pager(pager)).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : await query.CountAsync()).RouteData(routeData);

            // Load items so that loading handlers are invoked.
            var pageOfContentItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync(_contentManager);

            // We prepare the content items SummaryAdmin shape
            var contentItemSummaries = new List <dynamic>();

            foreach (var contentItem in pageOfContentItems)
            {
                contentItemSummaries.Add(await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater, "SummaryAdmin"));
            }

            // Populate options pager summary values.
            var startIndex = (pagerShape.Page - 1) * (pagerShape.PageSize) + 1;

            options.StartIndex        = startIndex;
            options.EndIndex          = startIndex + contentItemSummaries.Count - 1;
            options.ContentItemsCount = contentItemSummaries.Count;
            options.TotalItemCount    = pagerShape.TotalItemCount;

            var header = await _contentOptionsDisplayManager.BuildEditorAsync(options, _updateModelAccessor.ModelUpdater, false);

            var shapeViewModel = await _shapeFactory.CreateAsync <ListContentsViewModel>("ContentsAdminList", viewModel =>
            {
                viewModel.ContentItems = contentItemSummaries;
                viewModel.Pager        = pagerShape;
                viewModel.Options      = options;
                viewModel.Header       = header;
            });

            return(View(shapeViewModel));
        }
示例#28
0
        public async Task <IActionResult> List(ListContentsViewModel model, PagerParameters pagerParameters, string contentTypeId = "")
        {
            var context = _httpContextAccessor.HttpContext;
            var contentTypeDefinitions = _contentDefinitionManager.ListTypeDefinitions()
                                         .Where(ctd => ctd.GetSettings <ContentTypeSettings>().Creatable&& ctd.GetSettings <ContentTypeSettings>().Enabled)
                                         .OrderBy(ctd => ctd.DisplayName);

            if (!await _authorizationService.AuthorizeContentTypeDefinitionsAsync(User, CommonPermissions.EditContent, contentTypeDefinitions, _contentManager))
            {
                return(Forbid());
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var pager = new Pager(pagerParameters, siteSettings.PageSize);

            // This is used by the AdminMenus so needs to be passed into the options.
            if (!String.IsNullOrEmpty(contentTypeId))
            {
                model.Options.SelectedContentType = contentTypeId;
            }

            // Populate the creatable types.
            if (!String.IsNullOrEmpty(model.Options.SelectedContentType))
            {
                var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.Options.SelectedContentType);
                if (contentTypeDefinition == null)
                {
                    return(NotFound());
                }

                var creatableList = new List <SelectListItem>();

                // Allows non creatable types to be created by another admin page.
                if (contentTypeDefinition.GetSettings <ContentTypeSettings>().Creatable || model.Options.CanCreateSelectedContentType)
                {
                    creatableList.Add(new SelectListItem(new LocalizedString(contentTypeDefinition.DisplayName, contentTypeDefinition.DisplayName).Value, contentTypeDefinition.Name));
                }

                model.Options.CreatableTypes = creatableList;
            }

            if (model.Options.CreatableTypes == null)
            {
                var creatableList = new List <SelectListItem>();
                if (contentTypeDefinitions.Any())
                {
                    foreach (var contentTypeDefinition in contentTypeDefinitions)
                    {
                        var contentItem = await _contentManager.NewAsync(contentTypeDefinition.Name);

                        contentItem.Owner = context.User.FindFirstValue(ClaimTypes.NameIdentifier);

                        if (await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.EditContent, contentItem))
                        {
                            creatableList.Add(new SelectListItem(new LocalizedString(contentTypeDefinition.DisplayName, contentTypeDefinition.DisplayName).Value, contentTypeDefinition.Name));
                        }
                    }
                }

                model.Options.CreatableTypes = creatableList;
            }

            // We populate the remaining SelectLists.
            model.Options.ContentStatuses = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = S["Latest"], Value = nameof(ContentsStatus.Latest)
                },
                new SelectListItem()
                {
                    Text = S["Published"], Value = nameof(ContentsStatus.Published)
                },
                new SelectListItem()
                {
                    Text = S["Unpublished"], Value = nameof(ContentsStatus.Draft)
                },
                new SelectListItem()
                {
                    Text = S["All versions"], Value = nameof(ContentsStatus.AllVersions)
                }
            };

            if (await _authorizationService.AuthorizeAsync(context.User, Permissions.ListContent))
            {
                model.Options.ContentStatuses.Insert(1, new SelectListItem()
                {
                    Text = S["Owned by me"], Value = nameof(ContentsStatus.Owner)
                });
            }

            model.Options.ContentSorts = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = S["Recently created"], Value = nameof(ContentsOrder.Created)
                },
                new SelectListItem()
                {
                    Text = S["Recently modified"], Value = nameof(ContentsOrder.Modified)
                },
                new SelectListItem()
                {
                    Text = S["Recently published"], Value = nameof(ContentsOrder.Published)
                },
                new SelectListItem()
                {
                    Text = S["Title"], Value = nameof(ContentsOrder.Title)
                }
            };

            model.Options.ContentsBulkAction = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = S["Publish Now"], Value = nameof(ContentsBulkAction.PublishNow)
                },
                new SelectListItem()
                {
                    Text = S["Unpublish"], Value = nameof(ContentsBulkAction.Unpublish)
                },
                new SelectListItem()
                {
                    Text = S["Delete"], Value = nameof(ContentsBulkAction.Remove)
                }
            };

            if ((String.IsNullOrEmpty(model.Options.SelectedContentType) || String.IsNullOrEmpty(contentTypeId)) && model.Options.ContentTypeOptions == null)
            {
                var listableTypes = new List <ContentTypeDefinition>();
                foreach (var ctd in _contentDefinitionManager.ListTypeDefinitions())
                {
                    if (ctd.GetSettings <ContentTypeSettings>().Listable)
                    {
                        var contentItem = await _contentManager.NewAsync(ctd.Name);

                        contentItem.Owner = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
                        var authorized = await _authorizationService.AuthorizeAsync(User, CommonPermissions.EditContent, contentItem);

                        if (authorized)
                        {
                            listableTypes.Add(ctd);
                        }
                    }
                }

                var contentTypeOptions = listableTypes
                                         .Select(ctd => new KeyValuePair <string, string>(ctd.Name, ctd.DisplayName))
                                         .ToList().OrderBy(kvp => kvp.Value);

                model.Options.ContentTypeOptions = new List <SelectListItem>
                {
                    new SelectListItem()
                    {
                        Text = S["All content types"], Value = ""
                    }
                };

                foreach (var option in contentTypeOptions)
                {
                    model.Options.ContentTypeOptions.Add(new SelectListItem()
                    {
                        Text = option.Value, Value = option.Key, Selected = (option.Value == model.Options.SelectedContentType)
                    });
                }
            }

            // If ContentTypeOptions is not initialized by query string or by the code above, initialize it
            if (model.Options.ContentTypeOptions == null)
            {
                model.Options.ContentTypeOptions = new List <SelectListItem>();
            }

            // With the model populated we filter the query, allowing the filters to alter the model.
            var query = await _contentsAdminListQueryService.QueryAsync(model.Options, _updateModelAccessor.ModelUpdater);

            var maxPagedCount = siteSettings.MaxPagedCount;

            if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
            {
                pager.PageSize = maxPagedCount;
            }

            // We prepare the pager
            var routeData = new RouteData();

            routeData.Values.Add("DisplayText", model.Options.DisplayText);

            var pagerShape         = (await New.Pager(pager)).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : await query.CountAsync()).RouteData(routeData);
            var pageOfContentItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync();

            // We prepare the content items SummaryAdmin shape
            var contentItemSummaries = new List <dynamic>();

            foreach (var contentItem in pageOfContentItems)
            {
                contentItemSummaries.Add(await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater, "SummaryAdmin"));
            }

            // Populate options pager summary values.
            var startIndex = (pagerShape.Page - 1) * (pagerShape.PageSize) + 1;

            model.Options.StartIndex        = startIndex;
            model.Options.EndIndex          = startIndex + contentItemSummaries.Count - 1;
            model.Options.ContentItemsCount = contentItemSummaries.Count;
            model.Options.TotalItemCount    = pagerShape.TotalItemCount;

            var header = await _contentOptionsDisplayManager.BuildEditorAsync(model.Options, _updateModelAccessor.ModelUpdater, false);

            var shapeViewModel = await _shapeFactory.CreateAsync <ListContentsViewModel>("ContentsAdminList", viewModel =>
            {
                viewModel.ContentItems = contentItemSummaries;
                viewModel.Pager        = pagerShape;
                viewModel.Options      = model.Options;
                viewModel.Header       = header;
            });

            return(View(shapeViewModel));
        }
示例#29
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // Should only run on the front-end for a full view
            if ((context.Result is ViewResult || context.Result is PageResult) &&
                !AdminAttribute.IsApplied(context.HttpContext))
            {
                // Even if the Admin attribute is not applied we might be using the admin theme, for instance in Login views.
                // In this case don't render Layers.
                var selectedTheme = (await _themeManager.GetThemeAsync())?.Id;
                var adminTheme    = await _adminThemeService.GetAdminThemeNameAsync();

                if (selectedTheme == adminTheme)
                {
                    await next.Invoke();

                    return;
                }

                var widgets = await _memoryCache.GetOrCreateAsync("OrchardCore.Layers.LayerFilter:AllWidgets", entry =>
                {
                    entry.AddExpirationToken(_signal.GetToken(LayerMetadataHandler.LayerChangeToken));
                    return(_layerService.GetLayerWidgetsAsync(x => x.Published));
                });

                var layers = (await _layerService.GetLayersAsync()).Layers.ToDictionary(x => x.Name);

                dynamic layout = await _layoutAccessor.GetLayoutAsync();

                var updater = _modelUpdaterAccessor.ModelUpdater;

                var engine = _scriptingManager.GetScriptingEngine("js");
                var scope  = engine.CreateScope(_scriptingManager.GlobalMethodProviders.SelectMany(x => x.GetMethods()), _serviceProvider, null, null);

                var layersCache = new Dictionary <string, bool>();

                foreach (var widget in widgets)
                {
                    var layer = layers[widget.Layer];

                    if (layer == null)
                    {
                        continue;
                    }

                    bool display;
                    if (!layersCache.TryGetValue(layer.Name, out display))
                    {
                        if (String.IsNullOrEmpty(layer.Rule))
                        {
                            display = false;
                        }
                        else
                        {
                            display = Convert.ToBoolean(engine.Evaluate(scope, layer.Rule));
                        }

                        layersCache[layer.Rule] = display;
                    }

                    if (!display)
                    {
                        continue;
                    }

                    var widgetContent = await _contentItemDisplayManager.BuildDisplayAsync(widget.ContentItem, updater);

                    widgetContent.Classes.Add("widget");
                    widgetContent.Classes.Add("widget-" + widget.ContentItem.ContentType.HtmlClassify());

                    var wrapper = new WidgetWrapper
                    {
                        Widget  = widget.ContentItem,
                        Content = widgetContent
                    };

                    wrapper.Metadata.Alternates.Add("Widget_Wrapper__" + widget.ContentItem.ContentType);
                    wrapper.Metadata.Alternates.Add("Widget_Wrapper__Zone__" + widget.Zone);

                    var contentZone = layout.Zones[widget.Zone];
                    contentZone.Add(wrapper);
                }
            }

            await next.Invoke();
        }
示例#30
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // Should only run on the front-end for a full view
            if (context.Result is ViewResult && !AdminAttribute.IsApplied(context.HttpContext))
            {
                var widgets = await _layerService.GetLayerWidgetsAsync(x => x.Published);

                var layers = (await _layerService.GetLayersAsync()).Layers.ToDictionary(x => x.Name);

                var layout  = _layoutAccessor.GetLayout();
                var updater = _modelUpdaterAccessor.ModelUpdater;

                var engine = _scriptingManager.GetScriptingEngine("js");
                var scope  = engine.CreateScope(_scriptingManager.GlobalMethodProviders.SelectMany(x => x.GetMethods()), _serviceProvider);

                var layersCache = new Dictionary <string, bool>();

                foreach (var widget in widgets)
                {
                    var layer = layers[widget.Layer];

                    if (layer == null)
                    {
                        continue;
                    }

                    bool display;
                    if (!layersCache.TryGetValue(layer.Name, out display))
                    {
                        if (String.IsNullOrEmpty(layer.Rule))
                        {
                            display = false;
                        }
                        else
                        {
                            display = Convert.ToBoolean(engine.Evaluate(scope, layer.Rule));
                        }

                        layersCache[layer.Rule] = display;
                    }

                    if (!display)
                    {
                        continue;
                    }

                    IShape widgetContent = await _contentItemDisplayManager.BuildDisplayAsync(widget.ContentItem, updater);

                    widgetContent.Classes.Add("widget");
                    widgetContent.Classes.Add("widget-" + widget.ContentItem.ContentType.HtmlClassify());

                    var wrapper = _shapeFactory.Create("Widget_Wrapper", new { Widget = widget.ContentItem, Content = widgetContent });
                    wrapper.Metadata.Alternates.Add("Widget_Wrapper__" + widget.ContentItem.ContentType);

                    var contentZone = layout.Zones[widget.Zone];
                    contentZone.Add(wrapper);
                }
            }

            await next.Invoke();
        }