public string ResolvePlaceholder(string placeholderText)
        {
            var placeholderParts = placeholderText.Split(new [] { "::" }, StringSplitOptions.RemoveEmptyEntries);

            if (placeholderParts[0] != "ItemLevelCacheResource" || placeholderParts.Length != 2)
            {
                return(null);
            }

            switch (placeholderParts[1])
            {
            case "Metas":
                return(GetMarkup(mShapeFactory.Create("Metas")));

            case "HeadLinks":
                return(GetMarkup(mShapeFactory.Create("HeadLinks")));

            case "StylesheetLinks":
                return(GetMarkup(mShapeFactory.Create("StylesheetLinks")));

            case "HeadScripts":
                return(GetMarkup(mShapeFactory.Create("HeadScripts")));

            case "FootScripts":
                return(GetMarkup(mShapeFactory.Create("FootScripts")));
            }

            return(null);
        }
Exemplo n.º 2
0
        public void SendChallengeEmail(IUser user, Func <string, string> createUrl)
        {
            string nonce = CreateNonce(user, DelayToValidate);
            string url   = createUrl(nonce);

            if (user != null)
            {
                var site = _siteService.GetSiteSettings();

                var template = _shapeFactory.Create("Template_User_Validated", Arguments.From(new {
                    RegisteredWebsite = site.As <RegistrationSettingsPart>().ValidateEmailRegisteredWebsite,
                    ContactEmail      = site.As <RegistrationSettingsPart>().ValidateEmailContactEMail,
                    ChallengeUrl      = url
                }));
                template.Metadata.Wrappers.Add("Template_User_Wrapper");

                var parameters = new Dictionary <string, object> {
                    { "Subject", T("Verification E-Mail").Text },
                    { "Body", _shapeDisplay.Display(template) },
                    { "Recipients", user.Email }
                };

                _messageService.Send("Email", parameters);
            }
        }
Exemplo n.º 3
0
        public dynamic DisplayElement(
            Element element,
            IContent content,
            string displayType     = null,
            IUpdateModel updater   = null,
            string renderEventName = null,
            string renderEventArgs = null)
        {
            var createShapeContext = new ElementCreatingDisplayShapeContext {
                Element     = element,
                DisplayType = displayType,
                Content     = content,
            };

            element.Descriptor.CreatingDisplay(createShapeContext);

            var typeName = element.GetType().Name;
            var category = element.Category.ToSafeName();
            var drivers  = element.Descriptor.GetDrivers();
            var elementShapeArguments = CreateArguments(element, content);
            var elementShape          = (dynamic)_shapeFactory.Create("Element", elementShapeArguments, () => new ZoneHolding(() => _shapeFactory.Create("ElementZone")));


            elementShape.Metadata.DisplayType = displayType;
            elementShape.Metadata.Alternates.Add(String.Format("Elements_{0}", typeName));
            elementShape.Metadata.Alternates.Add(String.Format("Elements_{0}_{1}", typeName, displayType));
            elementShape.Metadata.Alternates.Add(String.Format("Elements_{0}__{1}", typeName, category));
            elementShape.Metadata.Alternates.Add(String.Format("Elements_{0}_{1}__{2}", typeName, displayType, category));

            var displayContext = new ElementDisplayContext {
                Element         = element,
                ElementShape    = elementShape,
                DisplayType     = displayType,
                Content         = content,
                Updater         = updater,
                RenderEventName = renderEventName,
                RenderEventArgs = renderEventArgs
            };

            _elementEventHandlerHandler.Displaying(displayContext);
            InvokeDrivers(drivers, driver => driver.Displaying(displayContext));
            element.Descriptor.Display(displayContext);

            var container = element as Container;

            if (container != null)
            {
                if (container.Elements.Any())
                {
                    foreach (var child in container.Elements)
                    {
                        var childShape = DisplayElement(child, content, displayType: displayType, updater: updater);
                        childShape.Parent = elementShape;
                        elementShape.Add(childShape);
                    }
                }
            }

            return(elementShape);
        }
Exemplo n.º 4
0
        private dynamic CreateItemShape(string actualShapeType, string prefix = null)
        {
            var zoneHoldingBehavior = (prefix == null)?
                                      new ZoneHoldingBehavior(() => _shapeFactory.Create("ContentZone", Arguments.Empty()), null)
                : new ZoneHoldingBehavior(() => _shapeFactory.Create("ContentZone", Arguments.Empty(), new[] { new PrefixPrependingBehavior(prefix) }), null);

            return(_shapeFactory.Create(actualShapeType, Arguments.Empty(), new[] { zoneHoldingBehavior }));
        }
Exemplo n.º 5
0
        private dynamic CreateItemShape(string actualShapeType)
        {
            var zoneHolding = new ZoneHolding(() => _shapeFactory.Create("ContentZone", Arguments.Empty()));

            zoneHolding.Metadata.Type = actualShapeType;
            return(zoneHolding);
        }
        protected override DriverResult Display(HighlightsGroupPart part, string displayType, dynamic shapeHelper)
        {
            ViewsInfos viewsInfos = _HighlightsService.ChooseView(part);
            var        group      = new HighlightsGroupViewModel {
                Id              = part.Id,
                DisplayPlugin   = part.DisplayPlugin,
                DisplayTemplate = part.DisplayTemplate,
                ItemsSourceType = part.ItemsSourceType,
            };

            IEnumerable <dynamic> items          = null;
            IList <dynamic>       fromQueryItems = new List <dynamic>();

            if (part.ItemsSourceType == Enums.ItemsSourceTypes.ByHand)
            {
                items = _HighlightsService.GetHighlightsItemsContentByGroupId(part.Id, part.DisplayTemplate, part.DisplayPlugin, viewsInfos.SuffixShapeName.Replace("_", ""));
            }
            else if (part.ItemsSourceType == Enums.ItemsSourceTypes.FromQuery)
            {
                var queryItems = _projectionManager.GetContentItems(part.Query_Id, 0, 10);
                fromQueryItems = _HighlightsService.MapContentToHighlightsItemsViewModel(queryItems, part.DisplayTemplate, part.DisplayPlugin, viewsInfos);
            }
            var dict = new Dictionary <string, object> {
                { "HighlightsGroup", group },
                { "HighlightsItems", part.ItemsSourceType == Enums.ItemsSourceTypes.FromQuery?fromQueryItems:items }
            };
            var args = Arguments.From(dict.Values, dict.Keys);

            return(ContentShape(viewsInfos.ResultShapeName,
                                () => _shapeFactory.Create(viewsInfos.ResultShapeName, args)));
            //return null;
        }
Exemplo n.º 7
0
        public void SendNotificationEmail(CommentPart commentPart)
        {
            try {
                var commentedOn = _orchardServices.ContentManager.Get(commentPart.CommentedOn);
                if (commentedOn == null)
                {
                    return;
                }

                var owner = commentedOn.As <CommonPart>().Owner;
                if (owner == null)
                {
                    return;
                }

                var template = _shapeFactory.Create("Template_Comment_Notification", Arguments.From(new {
                    CommentPart        = commentPart,
                    CommentApproveUrl  = CreateProtectedUrl("Approve", commentPart),
                    CommentModerateUrl = CreateProtectedUrl("Moderate", commentPart),
                    CommentDeleteUrl   = CreateProtectedUrl("Delete", commentPart)
                }));

                var parameters = new Dictionary <string, object> {
                    { "Subject", T("Comment notification").Text },
                    { "Body", _shapeDisplay.Display(template) },
                    { "Recipients", owner.Email }
                };

                _messageService.Send("Email", parameters);
            }
            catch (Exception e) {
                Logger.Error(e, "An unexpected error occured while sending a notification email");
            }
        }
Exemplo n.º 8
0
        public static IShape Create(this IShapeFactory factory, string shapeType, INamedEnumerable <object> parameters)
        {
            return(factory.Create(shapeType, () =>
            {
                var shape = new Shape();

                // If only one non-Type, use it as the source object to copy
                if (parameters != null)
                {
                    var initializer = parameters.Positional.SingleOrDefault();
                    if (initializer != null)
                    {
                        foreach (var prop in initializer.GetType().GetProperties())
                        {
                            shape.Properties[prop.Name] = prop.GetValue(initializer, null);
                        }
                    }
                    else
                    {
                        foreach (var kv in parameters.Named)
                        {
                            shape.Properties[kv.Key] = kv.Value;
                        }
                    }
                }

                return shape;
            }));
        }
Exemplo n.º 9
0
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            // Should only run on a full view rendering result
            if (!(filterContext.Result is ViewResult))
            {
                return;
            }

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

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

            // Enable shape caching
            menuShape.Metadata
            .Cache("menu-admin")
            .AddContext("user.roles")
            .AddDependency("features")
            .AddDependency("types")     // This should go in a Displaying Shape event in the Contents module
            ;

            _layoutAccessor.GetLayout().Navigation.Add(menuShape);
        }
Exemplo n.º 10
0
        private object TokenValue(EvaluateContext context, string shapeName, string data)
        {
            var parameters = Arguments.From(context.Data.Values, context.Data.Keys);
            var shape      = _shapeFactory.Create(shapeName, parameters);

            return(_shapeDisplay.Display(shape));
        }
Exemplo n.º 11
0
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            // Should only run on a full view rendering result
            if (!(filterContext.Result is ViewResult))
            {
                return;
            }

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

            if (filterContext.HttpContext.Response.StatusCode != 200)
            {
                return;
            }

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

            _layoutAccessor.GetLayout().Navigation.Add(menuShape);
        }
Exemplo n.º 12
0
        public void AddShape()
        {
            var shape = _ShapeFactory.Create(SelectedShapeType);

            _ShapeRepo.AddShape(shape);
            Close(this);
        }
Exemplo n.º 13
0
        public bool SendChallengeMail(ApplicationRecord app, IUser user, Func <string, string> createUrl)
        {
            string nonce = CreateNonce(user, DelayToValidate, app.AppKey);
            string url   = createUrl(nonce);

            var site = _siteService.GetSiteSettings();

            var template = _shapeFactory.Create("Template_User_Validation", Arguments.From(new
            {
                RegisteredWebsite = app.Name, //site.As<RegistrationSettingsPart>().ValidateEmailRegisteredWebsite,
                ContactEmail      = site.As <RegistrationSettingsPart>().ValidateEmailContactEMail,
                ChallengeUrl      = url,
                ChallengeText     = app.Name + " Registration"
            }));

            template.Metadata.Wrappers.Add("Template_User_Wrapper");

            var parameters = new Dictionary <string, object> {
                { "Application", app.AppKey },
                { "Subject", T("Verification E-Mail").Text },
                { "Body", _shapeDisplay.Display(template) },
                { "Recipients", user.Email }
            };

            _messageService.Send("Email", parameters);
            return(true);
        }
Exemplo n.º 14
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 = _shapeFactory.Create("Pager", new { TotalItemCount = await _applicationStore.GetCount() });

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

            return(View(model));
        }
Exemplo n.º 15
0
 public Func <WorkContext, T> Get <T>(string name)
 {
     if (name == "Layout")
     {
         var layout = _shapeFactory.Create("Layout", Arguments.Empty());
         return(ctx => (T)layout);
     }
     return(null);
 }
Exemplo n.º 16
0
        public dynamic GetLayout()
        {
            if (_layout == null)
            {
                _layout = _shapeFactory.Create("Layout", Arguments.Empty());
            }

            return(_layout);
        }
Exemplo n.º 17
0
 public static IShape Create(this IShapeFactory factory, Type baseType, string shapeType, Action <object> initialize)
 {
     return(factory.Create(shapeType, () =>
     {
         var shape = CreateShape(baseType);
         initialize?.Invoke(shape);
         return shape;
     }));
 }
Exemplo n.º 18
0
 public static IShape Create <TShape>(this IShapeFactory factory, string shapeType, Action <TShape> initialize)
 {
     return(factory.Create(shapeType, () =>
     {
         var shape = (TShape)CreateShape(typeof(TShape));
         initialize?.Invoke(shape);
         return shape;
     }));
 }
Exemplo n.º 19
0
        protected override DriverResult Display(DashboardShapePart part, string displayType, dynamic shapeHelper)
        {
            return(ContentShape("Parts_DashboardShapePart",
                                () => {
                var shape = shapeFactory.Create(part.Shape);
                var html = shapeDisplay.Display(shape);

                return shapeHelper.Parts_DashboardShapePart(Html: html);
            }));
        }
        protected override void OnDisplaying(Shape element, ElementDisplayContext context)
        {
            if (String.IsNullOrWhiteSpace(element.ShapeType))
            {
                return;
            }

            var shape = _shapeFactory.Create(element.ShapeType);

            context.ElementShape.Shape = shape;
        }
        protected override DriverResult Display(HighlightsItemPart part, String displayType, dynamic shapeHelper)
        {
            ViewsInfos viewInfos = _HighlightsService.ChooseView(part);
            var        dict      = new Dictionary <string, object> {
                { "HighlightsItem", _HighlightsService.MapContentToHighlightsItemViewModel(part) },
                { "DisplayTemplate", displayType }
            };
            var args = Arguments.From(dict.Values, dict.Keys);

            return(ContentShape(
                       viewInfos.ResultShapeName,
                       () => _shapeFactory.Create(viewInfos.ResultShapeName, args)));
        }
Exemplo n.º 22
0
        private IShape ParseShape(string line, DrawingContext context)
        {
            var match = ShapeRegex.Match(line);

            if (!match.Success)
            {
                throw new FormatException($"Invalid shape declaration: '{line}'.");
            }
            var shapeName  = match.Groups["name"].Value;
            var parameters = match.Groups["coords"].Value
                             .Split(',')
                             .Select(item => item.Trim());

            return(shapeFactory_.Create(shapeName, parameters, context));
        }
Exemplo n.º 23
0
        public void Process(IDictionary <string, object> parameters)
        {
            if (!_smtpSettings.IsValid())
            {
                return;
            }

            var emailMessage = new EmailMessage {
                Body       = parameters["Body"] as string,
                Subject    = parameters["Subject"] as string,
                Recipients = parameters["Recipients"] as string
            };

            if (emailMessage.Recipients.Length == 0)
            {
                Logger.Error("Email message doesn't have any recipient");
                return;
            }

            // Applying default Body alteration for SmtpChannel
            var template = _shapeFactory.Create("Template_Smtp_Wrapper", Arguments.From(new {
                Content = new MvcHtmlString(emailMessage.Body)
            }));

            var mailMessage = new MailMessage {
                Subject    = emailMessage.Subject,
                Body       = _shapeDisplay.Display(template),
                IsBodyHtml = true
            };

            var section = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

            mailMessage.From = !String.IsNullOrWhiteSpace(_smtpSettings.Address)
                ? new MailAddress(_smtpSettings.Address)
                : new MailAddress(section.From);

            try {
                foreach (var recipient in emailMessage.Recipients.Split(new [] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    mailMessage.To.Add(new MailAddress(recipient));
                }

                _smtpClientField.Value.Send(mailMessage);
            }
            catch (Exception e) {
                Logger.Error(e, "Could not send email");
            }
        }
        public ThemeSelectorResult GetTheme(RequestContext context)
        {
            if (AdminFilter.IsApplied(context))
            {
                return(null);
            }
            if (_result != null)
            {
                return(_result);
            }
            // If the user reverted to the default, short-circuit this
            var workContext = _workContextAccessor.GetContext();
            var session     = workContext.HttpContext.Session;

            if (session != null &&
                (bool)(session[workContext.CurrentSite.SiteName + "Vandelay.ThemePicker.UseDefault"] ?? false))
            {
                return(null);
            }
            var settings = _cacheManager.Get(
                "Vandelay.ThemePicker",
                ctx => {
                ctx.Monitor(_signals.When("Vandelay.ThemePicker.SettingsChanged"));
                return(_settingsService.Get());
            });
            var selectedThemeRule =
                (from settingsRecord in settings
                 let rule = _rules.Where(r =>
                                         r.GetType().Name.Equals(settingsRecord.RuleType, StringComparison.OrdinalIgnoreCase)).FirstOrDefault()
                            where rule != null && rule.Matches(settingsRecord.Name, settingsRecord.Criterion)
                            select settingsRecord).FirstOrDefault();

            if (selectedThemeRule == default(ThemePickerSettingsRecord))
            {
                return(null);
            }
            if (!String.IsNullOrWhiteSpace(selectedThemeRule.Zone))
            {
                dynamic linkShape = _shapeFactory.Create("Vandelay_ThemePicker_LinkToDefault");
                var     zone      = workContext.Layout.Zones[selectedThemeRule.Zone];
                zone.Add(linkShape, selectedThemeRule.Position);
            }
            _result = new ThemeSelectorResult {
                Priority  = selectedThemeRule.Priority,
                ThemeName = selectedThemeRule.Theme
            };
            return(_result);
        }
Exemplo n.º 25
0
        //https://core.trac.wordpress.org/browser/tags/3.8.1/src/wp-includes/shortcodes.php
        public string ProcessContent(string text, string flavor)
        {
            //dynamic foo = factory.Create("Foo", ArgsUtility.Named(new { one = 1, two = "dos" }));

            var args = new RouteValueDictionary(new Dictionary <string, object> {
            });

            var shape = _shapeFactory.Create("ShortCodeName", Arguments.FromT(args.Values, args.Keys));


            var context = new DisplayContext {
                Value       = shape,
                ViewContext = new ViewContext()
            };

            var shortCodeText = _displayManager.Execute(context);
        }
Exemplo n.º 26
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var display = (DisplayHelper)_displayHelperFactory.CreateHelper(ViewContext);

            // Extract all attributes from the tag helper to
            var properties = output.Attributes
                             .Where(x => x.Name != "type")
                             .ToDictionary(x => x.Name, x => (object)x.Value.ToString())
            ;

            var shape = _shapeFactory.Create(Type ?? output.TagName, Arguments.From(properties));

            output.Content.SetContent(await display.ShapeExecuteAsync(shape));

            // We don't want any encapsulating tag around the shape
            output.TagName = null;
        }
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            // First we make some checks before inserting our top bar.
            if (filterContext.Result as ViewResult == null)
            {
                return;
            }
            if (Orchard.UI.Admin.AdminFilter.IsApplied(filterContext.RequestContext))
            {
                return;
            }
            if (filterContext.Result is PartialViewResult)
            {
                return;
            }

            //IUser owner = _content.As<ICommonPart>().Owner;

            //if (!_authorizer.Authorize(Orchard.Core.Contents.Permissions.EditContent)) return;


            var r = _wca.GetContext(filterContext).CurrentUser.As <UserRolesPart>();

            if (r == null)
            {
                return;
            }
            if (r.Roles.Any(p => p == "vendedor"))
            {
                if (!IsOwner(((filterContext.RequestContext.HttpContext).Request).RawUrl, (_wca.GetContext(filterContext).CurrentUser).UserName))
                {
                    return;
                }
            }
            else
            {
                if (!_authorizer.Authorize(Orchard.Core.Contents.Permissions.EditContent))
                {
                    return;
                }
            }

            // Here we insert our topbar into the body.
            _wca.GetContext(filterContext).Layout.Zones["Body"].Add(_shapeFactory.Create("InlineEditing_TopBar"), ":before");
        }
        public dynamic BuildFilterDisplay(Filters filters)
        {
            var filterDisplay        = (dynamic)_shapeFactory.Create("AuditTrailFilter");
            var filterDisplayContext = new DisplayFilterContext(_shapeFactory, filters, filterDisplay);

            // Invoke event handlers.
            _auditTrailEventHandlers.DisplayFilter(filterDisplayContext);

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

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

            return(filterDisplay);
        }
        public dynamic CreateHighlightsItemShape(dynamic item, string displayTemplate, string overrideShapeName = "")
        {
            var dict = new Dictionary <string, object> {
                { "HighlightsItem", item },
                { "DisplayTemplate", displayTemplate }
            };
            var args      = Arguments.From(dict.Values, dict.Keys);
            var shapeName = ChooseView(item).ResultShapeName;

            if (!String.IsNullOrWhiteSpace(overrideShapeName))
            {
                shapeName = overrideShapeName;
            }
            var shape = _shapeFactory.Create(shapeName, args);

            shape.Metadata.DisplayType = displayTemplate.ToString();
            return(shape);
        }
Exemplo n.º 30
0
        private dynamic BuildEventShape(string shapeType, AuditTrailEventRecord record, string displayType)
        {
            var eventData  = _serializer.Deserialize(record.EventData);
            var descriptor = _auditTrailManager.DescribeEvent(record);
            var auditTrailEventActionsShape = _shapeFactory.Create(shapeType, Arguments.From(new Dictionary <string, object> {
                { "Record", record },
                { "EventData", eventData },
                { "Descriptor", descriptor }
            }));
            var metaData = auditTrailEventActionsShape.Metadata;

            metaData.DisplayType = displayType;
            metaData.Alternates.Add(String.Format("{0}_{1}", shapeType, displayType));
            metaData.Alternates.Add(String.Format("{0}__{1}", shapeType, record.Category));
            metaData.Alternates.Add(String.Format("{0}_{1}__{2}", shapeType, displayType, record.Category));
            metaData.Alternates.Add(String.Format("{0}__{1}__{2}", shapeType, record.Category, record.EventName));
            metaData.Alternates.Add(String.Format("{0}_{1}__{2}__{3}", shapeType, displayType, record.Category, record.EventName));
            return(auditTrailEventActionsShape);
        }