public static async ValueTask <IShape> CreateAsync <T>(
            this IShapeFactory factory,
            string shapeType,
            INamedEnumerable <T> parameters)
        {
            if (parameters == null ! || parameters == Arguments.Empty)
            {
                return(await factory.CreateAsync(shapeType, NewShape));
            }

            var shape = (Shape)await factory.CreateAsync(shapeType, NewShape);

            var initializer = parameters.Positional.SingleOrDefault();

            // If only one non-Type, use it as the source object to copy.
            if (initializer != null)
            {
                // Use the Arguments class to optimize reflection code.
                var arguments = Arguments.From(initializer);

                foreach (var prop in arguments.Named)
                {
                    shape.Properties[prop.Key] = prop.Value;
                }
            }
            else
            {
                foreach (var(key, value) in parameters.Named)
                {
                    shape.Properties[key] = value !;
                }
            }

            return(shape);
        }
예제 #2
0
        public async Task <ActionResult> Index(PagerParameters pagerParameters)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
            {
                return(Unauthorized());
            }

            var openIdSettings = await _openIdService.GetOpenIdSettingsAsync();

            if (!_openIdService.IsValidOpenIdSettings(openIdSettings))
            {
                _notifier.Warning(H["OpenID Connect settings are not properly configured."]);
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();

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

            var results = await _applicationStore.GetAppsAsync(pager.GetStartIndex(), pager.PageSize);

            var pagerShape = await _shapeFactory.CreateAsync("Pager", new { TotalItemCount = await _applicationStore.GetCount() });

            var model = new OpenIdApplicationsIndexViewModel
            {
                Applications = results
                               .Select(x => new OpenIdApplicationEntry {
                    Application = x
                })
                               .ToList(),
                Pager = pagerShape
            };

            return(View(model));
        }
        public async Task OnResultExecutionAsync(ResultExecutingContext filterContext, ResultExecutionDelegate next)
        {
            // Should only run on a full view rendering result
            if (!(filterContext.Result is ViewResult))
            {
                await next();

                return;
            }

            // Don't create the menu if the status code is 3xx
            var statusCode = filterContext.HttpContext.Response.StatusCode;

            if (statusCode >= 300 && statusCode < 400)
            {
                await next();

                return;
            }

            // Populate main nav
            IShape menuShape = await _shapeFactory.CreateAsync("ProfileNavigation",
                                                               Arguments.From(new
            {
                MenuName  = "profile",
                RouteData = filterContext.RouteData,
            }));

            dynamic layout = await _layoutAccessor.GetLayoutAsync();

            layout.ProfileNavigation.Add(menuShape);

            await next();
        }
예제 #4
0
        public async Task <ActionResult> Index(PagerParameters pagerParameters)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
            {
                return(Unauthorized());
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();

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

            var model = new OpenIdApplicationsIndexViewModel
            {
                Pager = await _shapeFactory.CreateAsync("Pager", new
                {
                    TotalItemCount = await _applicationManager.CountAsync()
                })
            };

            foreach (var application in await _applicationManager.ListAsync(pager.PageSize, pager.GetStartIndex()))
            {
                model.Applications.Add(new OpenIdApplicationEntry
                {
                    DisplayName = await _applicationManager.GetDisplayNameAsync(application),
                    Id          = await _applicationManager.GetPhysicalIdAsync(application)
                });
            }

            return(View(model));
        }
예제 #5
0
        protected async Task <bool> SendEmailAsync(string email, string subject, object model, string viewName)
        {
            var options = ControllerContext.HttpContext.RequestServices.GetRequiredService <IOptions <MvcViewOptions> >();

            ControllerContext.RouteData.Values["action"]     = viewName;
            ControllerContext.RouteData.Values["controller"] = "";
            var viewEngineResult = options.Value.ViewEngines.Select(x => x.FindView(ControllerContext, viewName, true)).FirstOrDefault(x => x != null);
            var displayContext   = new DisplayContext()
            {
                ServiceProvider = ControllerContext.HttpContext.RequestServices,
                Value           = await _shapeFactory.CreateAsync(viewName, model),
                ViewContext     = new ViewContext(ControllerContext, viewEngineResult.View, ViewData, TempData, new StringWriter(), new HtmlHelperOptions())
            };
            var htmlContent = await _displayManager.ExecuteAsync(displayContext);

            var message = new MailMessage()
            {
                Body = WebUtility.HtmlDecode(htmlContent.ToString()), IsBodyHtml = true, Subject = subject
            };

            message.To.Add(email);

            // send email
            var result = await _smtpService.SendAsync(message);

            return(result.Succeeded);
        }
예제 #6
0
        public async Task <IHtmlContent> TabContainer(IDisplayHelper displayAsync, GroupingsViewModel shape, IShapeFactory shapeFactory)
        {
            var localNavigation = await shapeFactory.CreateAsync("LocalNavigation", Arguments.From(new
            {
                shape.Identifier,
                Tabs = shape.Groupings
            }));

            var htmlContentBuilder = new HtmlContentBuilder();

            htmlContentBuilder.AppendHtml(await displayAsync.ShapeExecuteAsync(localNavigation));

            var tagBuilder = shape.GetTagBuilder("div");

            tagBuilder.AddCssClass("tab-content");

            htmlContentBuilder.AppendHtml(tagBuilder);

            var first = true;

            foreach (var tab in shape.Items.OfType <IShape>())
            {
                if (first)
                {
                    first = false;
                    tab.Classes.Add("show active");
                }

                tagBuilder.InnerHtml.AppendHtml(await displayAsync.ShapeExecuteAsync(tab));
            }

            return(htmlContentBuilder);
        }
예제 #7
0
        public static Task <IShape> CreateAsync <T>(this IShapeFactory factory, string shapeType, INamedEnumerable <T> parameters = null)
        {
            return(factory.CreateAsync(shapeType, NewShape, null, createdContext =>
            {
                var shape = (Shape)createdContext.Shape;

                // If only one non-Type, use it as the source object to copy
                if (parameters != null && parameters != Arguments.Empty)
                {
                    var initializer = parameters.Positional.SingleOrDefault();

                    if (initializer != null)
                    {
                        // Use the Arguments class to optimize reflection code
                        var arguments = Arguments.From(initializer);

                        foreach (var prop in arguments.Named)
                        {
                            shape.Properties[prop.Key] = prop.Value;
                        }
                    }
                    else
                    {
                        foreach (var kv in parameters.Named)
                        {
                            shape.Properties[kv.Key] = kv.Value;
                        }
                    }
                }
            }));
        }
예제 #8
0
        public async Task OnResultExecutionAsync(ResultExecutingContext filterContext, ResultExecutionDelegate next)
        {
            // Should only run on a full view rendering result
            if (!(filterContext.Result is ViewResult) && !(filterContext.Result is PageResult))
            {
                await next();

                return;
            }

            // Should only run on the Admin
            if (!AdminAttribute.IsApplied(filterContext.HttpContext))
            {
                await next();

                return;
            }

            // Should only run for authenticated users
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                await next();

                return;
            }

            // Don't create the menu if the status code is 3xx
            var statusCode = filterContext.HttpContext.Response.StatusCode;

            if (statusCode >= 300 && statusCode < 400)
            {
                await next();

                return;
            }

            // Populate main nav
            var menuShape = await _shapeFactory.CreateAsync("Navigation",
                                                            Arguments.From(new
            {
                MenuName  = "admin",
                RouteData = filterContext.RouteData,
            }));

            dynamic layout = await _layoutAccessor.GetLayoutAsync();

            if (layout.Navigation is ZoneOnDemand zoneOnDemand)
            {
                await zoneOnDemand.AddAsync(menuShape);
            }
            else if (layout.Navigation is Shape shape)
            {
                shape.Add(menuShape);
            }

            await next();
        }
예제 #9
0
 /// <summary>
 /// Creates a dynamic proxy instance for the <see cref="TModel"/> type and initializes it.
 /// </summary>
 /// <typeparam name="TModel">The type to instantiate.</typeparam>
 /// <param name="shapeType">The shape type to create.</param>
 /// <param name="initializeAsync">The initialization method.</param>
 /// <returns></returns>
 public static Task <IShape> CreateAsync <TModel>(this IShapeFactory factory, string shapeType, Func <TModel, Task> initializeAsync)
 {
     return(factory.CreateAsync(shapeType, async() =>
     {
         var shape = CreateShape(typeof(TModel));
         await initializeAsync((TModel)shape);
         return shape;
     }));
 }
예제 #10
0
 /// <summary>
 /// Creates a dynamic proxy instance for the <see cref="TModel"/> type and initializes it.
 /// </summary>
 /// <typeparam name="TModel">The type to instantiate.</typeparam>
 /// <param name="shapeType">The shape type to create.</param>
 /// <param name="initialize">The initialization method.</param>
 /// <returns></returns>
 public static Task <IShape> CreateAsync <TModel>(this IShapeFactory factory, string shapeType, Action <TModel> initialize)
 {
     return(factory.CreateAsync(shapeType, () =>
     {
         var shape = CreateShape(typeof(TModel));
         initialize((TModel)shape);
         return Task.FromResult(shape);
     }));
 }
예제 #11
0
        public async Task <IShape> BuildFilterDisplayAsync(Filters filters)
        {
            var filterDisplay = await _shapeFactory.CreateAsync("AuditTrailFilter");

            var filterDisplayContext = new DisplayFilterContext(_shapeFactory, filters, filterDisplay as Shape);

            _auditTrailEventHandlers.Invoke((handler, context) => handler.DisplayFilterAsync(context), filterDisplayContext, Logger);

            // Give each provider a chance to provide a filter display.
            var providersContext = _auditTrailManager.DescribeProviders();

            foreach (var action in providersContext.FilterDisplays)
            {
                await action(filterDisplayContext);
            }

            return(filterDisplay);
        }
예제 #12
0
 public async Task <dynamic> BuildDisplayAsync(IShapeFactory shapeFactory, PresentationProfile profile, IEnumerable <dynamic> slides, ContentPart part)
 {
     return(await shapeFactory.CreateAsync <PresentationDisplayViewModel>("SlideshowPlayerEngines_StandardPlayer", vm =>
     {
         vm.Profile = profile;
         vm.Slides = slides;
         vm.Part = part;
     }));
 }
예제 #13
0
        public async Task <IShape> GetLayoutAsync()
        {
            if (_layout == null)
            {
                _layout = await _shapeFactory.CreateAsync("Layout", Arguments.Empty);
            }

            return(_layout);
        }
예제 #14
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (!(context.Result is ViewResult || context.Result is PageResult) ||
                !String.Equals("OrchardCore.Users", Convert.ToString(context.RouteData.Values["area"]), StringComparison.OrdinalIgnoreCase))
            {
                await next();

                return;
            }

            var settings = (await _siteService.GetSiteSettingsAsync()).As <ReCaptchaSettings>();

            if (!settings.IsValid())
            {
                await next();

                return;
            }

            var layout = await _layoutAccessor.GetLayoutAsync();

            if (_reCaptchaService.IsThisARobot())
            {
                var afterLoginZone = layout.Zones["AfterLogin"];
                await afterLoginZone.AddAsync(await _shapeFactory.CreateAsync("ReCaptcha"));
            }

            var afterForgotPasswordZone = layout.Zones["AfterForgotPassword"];
            await afterForgotPasswordZone.AddAsync(await _shapeFactory.CreateAsync("ReCaptcha"));

            var afterRegisterZone = layout.Zones["AfterRegister"];
            await afterRegisterZone.AddAsync(await _shapeFactory.CreateAsync("ReCaptcha"));

            var afterResetPasswordZone = layout.Zones["AfterResetPassword"];
            await afterResetPasswordZone.AddAsync(await _shapeFactory.CreateAsync("ReCaptcha"));

            await next();
        }
예제 #15
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // Should only run on the front-end (or optionally also on the admin) for a full view.
            if ((context.Result is ViewResult || context.Result is PageResult) &&
                (_options.AllowOnAdmin || !AdminAttribute.IsApplied(context.HttpContext)))
            {
                dynamic layout = await _layoutAccessor.GetLayoutAsync();

                var footerZone = layout.Zones["Footer"];
                footerZone.Add(await _shapeFactory.CreateAsync("MiniProfiler"));
            }

            await next.Invoke();
        }
예제 #16
0
        public async Task <IShape> GetLayoutAsync()
        {
            if (_layout == null)
            {
                // Create a shape whose properties are dynamically created as Zone shapes
                _layout = await _shapeFactory.CreateAsync("Layout", () => new ValueTask <IShape>(new ZoneHolding(() => _shapeFactory.CreateAsync("Zone"))));
            }

            if (_layout == null)
            {
                // At this point a Layout shape should always exist
                throw new ApplicationException("Fatal error, a Layout couldn't be created.");
            }

            return(_layout);
        }
예제 #17
0
        public async Task OnResultExecutionAsync(ResultExecutingContext filterContext, ResultExecutionDelegate next)
        {
            if (_shouldDeleteCookie)
            {
                DeleteCookies(filterContext);

                await next();

                return;
            }

            if (!(filterContext.Result is ViewResult || filterContext.Result is PageResult))
            {
                await next();

                return;
            }

            if (_existingEntries.Length == 0)
            {
                await next();

                return;
            }

            var layout = await _layoutAccessor.GetLayoutAsync();

            var messagesZone = layout.Zones["Messages"];

            if (messagesZone is IShape zone)
            {
                foreach (var messageEntry in _existingEntries)
                {
                    // Also retrieve the actual zone in case it was only a temporary empty zone created on demand.
                    zone = await zone.AddAsync(await _shapeFactory.CreateAsync("Message", Arguments.From(messageEntry)));
                }
            }

            DeleteCookies(filterContext);

            await next();
        }
예제 #18
0
 /// <summary>
 /// Creates a new shape by copying the properties of the specific model.
 /// </summary>
 /// <param name="factory">The <see cref="IShapeFactory"/>.</param>
 /// <param name="shapeType">The type of shape to create.</param>
 /// <param name="model">The model to copy.</param>
 /// <returns></returns>
 public static ValueTask <IShape> CreateAsync <TModel>(this IShapeFactory factory, string shapeType, TModel model)
 {
     return(factory.CreateAsync(shapeType, Arguments.From(model)));
 }
예제 #19
0
 public static ValueTask <IShape> CreateAsync(this IShapeFactory factory, string shapeType)
 {
     return(factory.CreateAsync(shapeType, NewShape));
 }
예제 #20
0
        public async Task <IHtmlContent> ColumnGrouping(IDisplayHelper DisplayAsync, GroupingViewModel Shape, IShapeFactory ShapeFactory)
        {
            var htmlContentBuilder = new HtmlContentBuilder();

            var groupings = Shape.Grouping.ToLookup(x =>
            {
                if (x is IShape s)
                {
                    var key = s.Metadata.Column;
                    if (String.IsNullOrEmpty(key))
                    {
                        return(ContentKey);
                    }

                    // Remove column modifier.
                    var modifierIndex = key.IndexOf('_');
                    if (modifierIndex != -1)
                    {
                        key = key.Substring(0, modifierIndex);
                    }

                    // Remove positional modifier.
                    modifierIndex = key.IndexOf(';');
                    if (modifierIndex != -1)
                    {
                        key = key.Substring(0, modifierIndex);
                    }

                    return(key);
                }

                return(ContentKey);
            });

            if (groupings.Count > 1)
            {
                var positionModifiers = GetColumnPositions(groupings);

                var orderedGroupings = groupings.OrderBy(grouping =>
                {
                    if (positionModifiers.TryGetValue(grouping.Key, out var position))
                    {
                        return(new PositionalGrouping {
                            Position = position
                        });
                    }
                    else
                    {
                        return(new PositionalGrouping());
                    }
                }, FlatPositionComparer.Instance);

                var columnModifiers = GetColumnModifiers(orderedGroupings);

                var container = (GroupViewModel)await ShapeFactory.CreateAsync <GroupViewModel>("ColumnContainer", m =>
                {
                    m.Identifier = Shape.Identifier;
                });

                foreach (var orderedGrouping in orderedGroupings)
                {
                    var groupingShape = (GroupingViewModel)await ShapeFactory.CreateAsync <GroupingViewModel>("Column", m =>
                    {
                        m.Identifier = Shape.Identifier;
                        m.Grouping   = orderedGrouping;
                    });

                    groupingShape.Classes.Add("ta-col-grouping");
                    groupingShape.Classes.Add("column-" + orderedGrouping.Key.HtmlClassify());

                    // To adjust this breakpoint apply a modifier of lg-3 to every column.
                    var columnClasses = "col-12 col-md";
                    if (columnModifiers.TryGetValue(orderedGrouping.Key, out var columnModifier))
                    {
                        // When the modifier also has a - assume it is providing a breakpointed class.
                        if (columnModifier.IndexOf('-') != -1)
                        {
                            columnClasses = "col-12 col-" + columnModifier;
                        }
                        else // Otherwise assume a default md breakpoint.
                        {
                            columnClasses = "col-12 col-md-" + columnModifier;
                        }
                    }

                    groupingShape.Classes.Add(columnClasses);

                    foreach (var item in orderedGrouping)
                    {
                        await groupingShape.AddAsync(item);
                    }
                    await container.AddAsync(groupingShape);
                }

                htmlContentBuilder.AppendHtml(await DisplayAsync.ShapeExecuteAsync(container));
            }
            else
            {
                // When nothing is grouped in a column, the grouping is rendered directly.
                foreach (var item in Shape.Grouping)
                {
                    htmlContentBuilder.AppendHtml(await DisplayAsync.ShapeExecuteAsync((IShape)item));
                }
            }

            return(htmlContentBuilder);
        }
예제 #21
0
        public async Task <IHtmlContent> ContentZone(IDisplayHelper DisplayAsync, dynamic Shape, IShapeFactory ShapeFactory)
        {
            var htmlContentBuilder = new HtmlContentBuilder();

            // This maybe a collection of IShape, IHtmlContent, or plain object.
            var shapes = ((IEnumerable <object>)Shape);

            // Evaluate shapes for grouping metadata, when it is not an IShape it cannot be grouped.
            var isGrouped = shapes.Any(x => x is IShape s &&
                                       (!String.IsNullOrEmpty(s.Metadata.Tab) ||
                                        !String.IsNullOrEmpty(s.Metadata.Card) ||
                                        !String.IsNullOrEmpty(s.Metadata.Column)));

            // When there is no grouping metadata on any shapes just render the Zone.
            if (!isGrouped)
            {
                foreach (var item in shapes)
                {
                    htmlContentBuilder.AppendHtml(await DisplayAsync.ShapeExecuteAsync((IShape)item));
                }

                return(htmlContentBuilder);
            }

            string identifier = Shape.Identifier ?? String.Empty;

            var groupings = shapes.ToLookup(x =>
            {
                if (x is IShape s)
                {
                    var key = s.Metadata.Tab;
                    if (String.IsNullOrEmpty(key))
                    {
                        return(ContentKey);
                    }

                    // Remove any positioning modifier.
                    var modifierIndex = key.IndexOf(';');
                    if (modifierIndex != -1)
                    {
                        key = key.Substring(0, modifierIndex);
                    }

                    return(key);
                }

                return(ContentKey);
            });

            // Process Tabs first, then Cards, then Columns.
            if (groupings.Count > 1)
            {
                var orderedGroupings = groupings.OrderBy(grouping =>
                {
                    var firstGroupWithModifier = grouping.FirstOrDefault(group =>
                    {
                        if (group is IShape s && !String.IsNullOrEmpty(s.Metadata.Tab) && s.Metadata.Tab.IndexOf(';') != -1)
                        {
                            return(true);
                        }

                        return(false);
                    });

                    if (firstGroupWithModifier is IShape shape)
                    {
                        var key           = shape.Metadata.Tab;
                        var modifierIndex = key.IndexOf(';');

                        return(new PositionalGrouping(key.Substring(modifierIndex)));
                    }

                    return(new PositionalGrouping(null));
                }, FlatPositionComparer.Instance).ToArray();

                var container = (GroupingsViewModel)await ShapeFactory.CreateAsync <GroupingsViewModel>("TabContainer", m =>
                {
                    m.Identifier = identifier;
                    m.Groupings  = orderedGroupings;
                });

                container.Classes.Add("accordion");

                foreach (var orderedGrouping in orderedGroupings)
                {
                    var groupingShape = (GroupingViewModel)await ShapeFactory.CreateAsync <GroupingViewModel>("Tab", m =>
                    {
                        m.Identifier = identifier;
                        m.Grouping   = orderedGrouping;
                    });

                    foreach (var item in orderedGrouping)
                    {
                        await groupingShape.AddAsync(item);
                    }

                    await container.AddAsync(groupingShape);
                }

                htmlContentBuilder.AppendHtml(await DisplayAsync.ShapeExecuteAsync(container));
            }
            else if (groupings.Count == 1)
            {
                // Evaluate for cards.
                var cardGrouping = (GroupingViewModel)await ShapeFactory.CreateAsync <GroupingViewModel>("CardGrouping", m =>
                {
                    m.Identifier = identifier;
                    m.Grouping   = groupings.ElementAt(0);
                });

                htmlContentBuilder.AppendHtml(await DisplayAsync.ShapeExecuteAsync(cardGrouping));
            }

            return(htmlContentBuilder);
        }
예제 #22
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));
        }
예제 #23
0
        public async Task <IHtmlContent> CardGrouping(IDisplayHelper DisplayAsync, GroupingViewModel Shape, IShapeFactory ShapeFactory)
        {
            var htmlContentBuilder = new HtmlContentBuilder();

            var groupings = Shape.Grouping.ToLookup(x =>
            {
                if (x is IShape s)
                {
                    var key = s.Metadata.Card;
                    if (String.IsNullOrEmpty(key))
                    {
                        return(ContentKey);
                    }

                    // Remove positional modifier.
                    var modifierIndex = key.IndexOf(';');
                    if (modifierIndex != -1)
                    {
                        key = key.Substring(0, modifierIndex);
                    }

                    return(key);
                }

                return(ContentKey);
            });

            if (groupings.Count > 1)
            {
                var orderedGroupings = groupings.OrderBy(grouping =>
                {
                    var firstGroupWithModifier = grouping.FirstOrDefault(group =>
                    {
                        if (group is IShape s && !String.IsNullOrEmpty(s.Metadata.Card) && s.Metadata.Card.IndexOf(';') != -1)
                        {
                            return(true);
                        }

                        return(false);
                    });

                    if (firstGroupWithModifier is IShape shape)
                    {
                        var key           = shape.Metadata.Card;
                        var modifierIndex = key.IndexOf(';');
                        return(new PositionalGrouping(key.Substring(modifierIndex)));
                    }

                    return(new PositionalGrouping());
                }, FlatPositionComparer.Instance);

                var container = (GroupViewModel)await ShapeFactory.CreateAsync <GroupViewModel>("CardContainer", m =>
                {
                    m.Identifier = Shape.Identifier;
                });

                container.Classes.Add("accordion");

                foreach (var orderedGrouping in orderedGroupings)
                {
                    var groupingShape = (GroupingViewModel)await ShapeFactory.CreateAsync <GroupingViewModel>("Card", m =>
                    {
                        m.Identifier = Shape.Identifier;
                        m.Grouping   = orderedGrouping;
                    });

                    foreach (var item in orderedGrouping)
                    {
                        await groupingShape.AddAsync(item);
                    }

                    await container.AddAsync(groupingShape);
                }

                htmlContentBuilder.AppendHtml(await DisplayAsync.ShapeExecuteAsync(container));
            }
            else
            {
                // Evaluate for columns.
                var groupingShape = (GroupingViewModel)await ShapeFactory.CreateAsync <GroupingViewModel>("ColumnGrouping", m =>
                {
                    m.Identifier = Shape.Identifier;
                    m.Grouping   = Shape.Grouping;
                });

                htmlContentBuilder.AppendHtml(await DisplayAsync.ShapeExecuteAsync(groupingShape));
            }

            return(htmlContentBuilder);
        }
예제 #24
0
 protected ValueTask <IShape> CreateContentShapeAsync(string actualShapeType)
 {
     return(_shapeFactory.CreateAsync(actualShapeType, () =>
                                      new ValueTask <IShape>(new ZoneHolding(() => _shapeFactory.CreateAsync("ContentZone")))));
 }
예제 #25
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));
        }
예제 #26
0
        public async Task <ActionResult> Index([ModelBinder(BinderType = typeof(AuditTrailFilterEngineModelBinder), Name = "q")] QueryFilterResult <AuditTrailEvent> queryFilterResult, PagerParameters pagerParameters, string correlationId = "")
        {
            if (!await _authorizationService.AuthorizeAsync(User, AuditTrailPermissions.ViewAuditTrail))
            {
                return(Forbid());
            }

            var options = new AuditTrailIndexOptions
            {
                FilterResult = queryFilterResult
            };

            // This is used by Contents feature for routing so needs to be passed into the options.
            if (!String.IsNullOrEmpty(correlationId))
            {
                options.CorrelationId          = correlationId;
                options.CorrelationIdFromRoute = true;
            }

            if (options.CorrelationIdFromRoute)
            {
                // When the correlation id is provided via the route or options a placeholder node is used to apply a filter.
                options.FilterResult.TryAddOrReplace(new CorrelationIdFilterNode(options.CorrelationId));
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();

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

            // With the options populated we filter the query, allowing the filters to alter the options.
            var result = await _auditTrailAdminListQueryService.QueryAsync(pager.Page, pager.PageSize, options);

            // 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 pagerShape = await _shapeFactory.CreateAsync("Pager", Arguments.From(new
            {
                pager.Page,
                pager.PageSize,
                TotalItemCount = result.TotalCount
            }));

            var items = new List <IShape>();

            foreach (var auditTrailEvent in result.Events)
            {
                items.Add(
                    await _displayManager.BuildDisplayAsync(auditTrailEvent, updater: _updateModelAccessor.ModelUpdater, displayType: "SummaryAdmin")
                    );
            }

            var startIndex = (pager.Page - 1) * (pager.PageSize) + 1;

            options.StartIndex     = startIndex;
            options.EndIndex       = startIndex + items.Count - 1;
            options.EventsCount    = items.Count;
            options.TotalItemCount = result.TotalCount;

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

            var shapeViewModel = await _shapeFactory.CreateAsync <AuditTrailListViewModel>("AuditTrailAdminList", viewModel =>
            {
                viewModel.Events  = items;
                viewModel.Pager   = pagerShape;
                viewModel.Options = options;
                viewModel.Header  = header;
            });

            return(View(shapeViewModel));
        }
예제 #27
0
 public static ValueTask <IShape> CreateAsync(this IShapeFactory factory, string shapeType, Func <ValueTask <IShape> > shapeFactory)
 {
     return(factory.CreateAsync(shapeType, shapeFactory, null, null));
 }
예제 #28
0
        public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHelperOutput output)
        {
            // Extract all attributes from the tag helper to
            var properties = output.Attributes
                             .Where(x => !InternalProperties.Contains(x.Name))
                             .ToDictionary(x => LowerKebabToPascalCase(x.Name), x => (object)x.Value.ToString())
            ;

            if (string.IsNullOrWhiteSpace(Type))
            {
                Type = output.TagName;
            }

            if (string.IsNullOrWhiteSpace(Cache) && output.Attributes.ContainsName("cache-id"))
            {
                Cache = Convert.ToString(output.Attributes["cache-id"].Value);
            }

            if (string.IsNullOrWhiteSpace(Context) && output.Attributes.ContainsName("cache-context"))
            {
                Context = Convert.ToString(output.Attributes["cache-context"].Value);
            }

            if (string.IsNullOrWhiteSpace(Tag) && output.Attributes.ContainsName("cache-tag"))
            {
                Tag = Convert.ToString(output.Attributes["cache-tag"].Value);
            }

            if (!FixedDuration.HasValue && output.Attributes.ContainsName("cache-fixed-duration"))
            {
                TimeSpan timespan;
                if (TimeSpan.TryParse(Convert.ToString(output.Attributes["cache-fixed-duration"].Value), out timespan))
                {
                    FixedDuration = timespan;
                }
            }

            if (!SlidingDuration.HasValue && output.Attributes.ContainsName("cache-sliding-duration"))
            {
                TimeSpan timespan;
                if (TimeSpan.TryParse(Convert.ToString(output.Attributes["cache-sliding-duration"].Value), out timespan))
                {
                    SlidingDuration = timespan;
                }
            }

            var shape = await _shapeFactory.CreateAsync(Type, Arguments.From(properties));

            if (output.Attributes.ContainsName("id"))
            {
                shape.Id = Convert.ToString(output.Attributes["id"].Value);
            }

            if (output.Attributes.ContainsName("alternate"))
            {
                shape.Metadata.Alternates.Add(Convert.ToString(output.Attributes["alternate"].Value));
            }

            if (output.Attributes.ContainsName("wrapper"))
            {
                shape.Metadata.Wrappers.Add(Convert.ToString(output.Attributes["wrapper"].Value));
            }

            tagHelperContext.Items.Add(typeof(IShape), shape);

            if (!string.IsNullOrWhiteSpace(Cache))
            {
                var metadata = shape.Metadata;

                metadata.Cache(Cache);

                if (FixedDuration.HasValue)
                {
                    metadata.Cache().WithExpiryAfter(FixedDuration.Value);
                }

                if (SlidingDuration.HasValue)
                {
                    metadata.Cache().WithExpirySliding(SlidingDuration.Value);
                }

                if (!string.IsNullOrWhiteSpace(Context))
                {
                    var contexts = Context.Split(Separators, StringSplitOptions.RemoveEmptyEntries);
                    metadata.Cache().AddContext(contexts);
                }

                if (!string.IsNullOrWhiteSpace(Tag))
                {
                    var tags = Tag.Split(Separators, StringSplitOptions.RemoveEmptyEntries);
                    metadata.Cache().AddTag(tags);
                }
            }

            await output.GetChildContentAsync();

            output.Content.SetHtmlContent(await _displayHelper.ShapeExecuteAsync(shape));

            // We don't want any encapsulating tag around the shape
            output.TagName = null;
        }
예제 #29
0
        private async Task <IHtmlContent> ShapeTypeExecuteAsync(string name, INamedEnumerable <object> parameters)
        {
            var shape = await _shapeFactory.CreateAsync(name, parameters);

            return(await ShapeExecuteAsync(shape));
        }
예제 #30
0
 protected Task <IShape> CreateContentShapeAsync(string actualShapeType)
 {
     return(_shapeFactory.CreateAsync(actualShapeType, () => Task.FromResult <IShape>(new ZoneHolding(() => _shapeFactory.CreateAsync("ContentZone", Arguments.Empty)))));
 }