private string ActivateAndRenderTemplate(IRazorTemplateBase obj, DisplayContext displayContext, string templateVirtualPath, object model)
        {
            var buffer = new StringBuilder(1024);
            using (var writer = new StringWriter(buffer)) {
                using (var htmlWriter = new HtmlTextWriter(writer)) {

                    if (displayContext != null && displayContext.ViewContext.Controller != null) {
                        var shapeViewContext = new ViewContext(
                            displayContext.ViewContext.Controller.ControllerContext,
                            displayContext.ViewContext.View,
                            displayContext.ViewContext.ViewData,
                            displayContext.ViewContext.TempData,
                            htmlWriter
                            );

                        obj.WebPageContext = new WebPageContext(displayContext.ViewContext.HttpContext, obj as WebPageRenderingBase, model);
                        obj.ViewContext = shapeViewContext;

                        obj.ViewData = new ViewDataDictionary(displayContext.ViewDataContainer.ViewData) {Model = model};
                        obj.InitHelpers();
                    }
                    else {

                        obj.ViewData = new ViewDataDictionary(model);
                        obj.WebPageContext = new WebPageContext(_httpContextBase, obj as WebPageRenderingBase, model);
                    }

                    obj.VirtualPath = templateVirtualPath ?? "~/Themes/Orchard.Templates";
                    obj.Render(htmlWriter);
                }
            }

            return buffer.ToString();
        }
        public string Process(string template, string name, DisplayContext context = null, dynamic model = null)
        {
            try
            {
                var renderingContext = new TemplateRenderingContext
                {
                    TemplateType = TemplateType.TemplateContentItem,
                    TemplatePath = name
                };

                return _templateService.ExecuteTemplate(template, model, renderingContext);
            }
            catch (Exception ex)
            {
                if (ex.IsFatal()) throw;

                Logger.Error(ex, "An unexpected exception was caught during rendering the \"" + name + "\" Liquid template.");

                var reportActivityName = T("Liquid template errors: {0} shape", name).Text;

                var liquidReport = _reportsManager
                    .GetReports().FirstOrDefault(report => report.ActivityName == reportActivityName);

                var liquidReportId = liquidReport == null
                    ? _reportsManager
                        .CreateReport(
                            T("Errors caught in the Liquid template of the {0} shape.", name).Text,
                            reportActivityName)
                    : liquidReport.ReportId;

                _reportsManager.Add(liquidReportId, ReportEntryType.Error, ex.Message);

                return T("<strong style=\"color:red;font-weight:bold;\">An unexpected exception was caught during rendering \"{0}\" Liquid template. {1}</strong>", name, ex.Message).Text;
            }
        }
Example #3
0
        public object ShapeExecute(object shape) {
            if (shape == null) {
                return new HtmlString(string.Empty);
            }

            var context = new DisplayContext { Display = this, Value = shape, ViewContext = ViewContext, ViewDataContainer = ViewDataContainer };
            return _displayManager.Execute(context);
        }
        public override string Process(string template, string name, DisplayContext context = null, dynamic model = null) {
            if (String.IsNullOrEmpty(template))
                return string.Empty;

            var compiledTemplate = _compiler.CompileRazor(template, name, new Dictionary<string, object>());
            var result = ActivateAndRenderTemplate(compiledTemplate, context, null, model);
            return result;
        }
Example #5
0
 static IHtmlString Process(ShapeBinding shapeBinding, IShape shape, DisplayContext context)
 {
     if (shapeBinding == null || shapeBinding.Binding == null)
     {
         // todo: create result from all child shapes
         return(shape.Metadata.ChildContent ?? new HtmlString(""));
     }
     return(CoerceHtmlString(shapeBinding.Binding(context)));
 }
        private IHtmlString PerformInvoke(DisplayContext displayContext, MethodInfo methodInfo, object serviceInstance) {
            var output = new HtmlStringWriter();
            var arguments = methodInfo.GetParameters()
                .Select(parameter => BindParameter(displayContext, parameter, output));

            var returnValue = methodInfo.Invoke(serviceInstance, arguments.ToArray());
            if (methodInfo.ReturnType != typeof(void)) {
                output.Write(CoerceHtmlString(returnValue));
            }
            return output;
        }
        public IHtmlString ShapeExecute(object shape)
        {
            if (shape == null)
            {
                return(new HtmlString(string.Empty));
            }

            var context = new DisplayContext {
                Display = this, Value = shape, ViewContext = ViewContext, ViewDataContainer = ViewDataContainer
            };

            return(_displayManager.Execute(context));
        }
Example #8
0
        public async Task <IHtmlContent> ShapeExecuteAsync(object shape)
        {
            if (shape == null)
            {
                return(new HtmlString(string.Empty));
            }

            var context = new DisplayContext {
                Display = this, Value = shape, ViewContext = ViewContext
            };

            return(await _displayManager.ExecuteAsync(context));
        }
        //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);
        }
        private Task<IHtmlContent> PerformInvokeAsync(DisplayContext displayContext, MethodInfo methodInfo, object serviceInstance)
        {
            var parameters = _parameters.GetOrAdd(methodInfo, m => m.GetParameters());
            var arguments = parameters.Select(parameter => BindParameter(displayContext, parameter));

            // Resolve the service the method is declared on
            var returnValue = methodInfo.Invoke(serviceInstance, arguments.ToArray());

            // If the shape returns a value, write it to the stream
            if (methodInfo.ReturnType != typeof(void))
            {
                return Task.FromResult(CoerceHtmlContent(returnValue));
            }

            return Task.FromResult<IHtmlContent>(null);
        }
        private string ActivateAndRenderTemplate(IRazorTemplateBase obj, DisplayContext displayContext, string templateVirtualPath, object model) {
            var buffer = new StringBuilder(1024);
            using (var writer = new StringWriter(buffer)) {
                using (var htmlWriter = new HtmlTextWriter(writer)) {

                    if (displayContext != null && displayContext.ViewContext.Controller != null) {
                        var shapeViewContext = new ViewContext(
                            displayContext.ViewContext.Controller.ControllerContext,
                            displayContext.ViewContext.View,
                            displayContext.ViewContext.ViewData,
                            displayContext.ViewContext.TempData,
                            htmlWriter
                            );

                        obj.WebPageContext = new WebPageContext(displayContext.ViewContext.HttpContext, obj as WebPageRenderingBase, model);
                        obj.ViewContext = shapeViewContext;

                        obj.ViewData = new ViewDataDictionary(displayContext.ViewDataContainer.ViewData) { Model = model };
                        obj.InitHelpers();
                    }
                    else {

                        // Setup a fake view context in order to support razor syntax inside of HTML attributes,
                        // for instance: <a href="@WorkContext.CurrentSite.BaseUrl">Homepage</a>.
                        var viewData = new ViewDataDictionary(model);
                        var httpContext = _wca.GetContext().HttpContext;
                        obj.ViewContext = new ViewContext(
                            new ControllerContext(
                                httpContext.Request.RequestContext,
                                new StubController()),
                                new StubView(),
                                viewData,
                                new TempDataDictionary(),
                                htmlWriter);

                        obj.ViewData = viewData;
                        obj.WebPageContext = new WebPageContext(httpContext, obj as WebPageRenderingBase, model);
                        obj.WorkContext = _wca.GetContext();
                    }

                    obj.VirtualPath = templateVirtualPath ?? "~/Themes/Orchard.Templates";
                    obj.Render(htmlWriter);
                }
            }

            return buffer.ToString();
        }
Example #12
0
        public Task <IHtmlContent> ShapeExecuteAsync(object shape)
        {
            if (shape == null)
            {
                return(Task.FromResult <IHtmlContent>(HtmlString.Empty));
            }

            var context = new DisplayContext
            {
                DisplayAsync    = this,
                Value           = shape,
                ViewContext     = ViewContext,
                ServiceProvider = _serviceProvider
            };

            return(_displayManager.ExecuteAsync(context));
        }
        private object BindParameter(DisplayContext displayContext, ParameterInfo parameter, TextWriter output) {
            if (parameter.Name == "Shape")
                return displayContext.Value;

            if (parameter.Name == "Display")
                return displayContext.Display;

            if (parameter.Name == "Output" && parameter.ParameterType == typeof(TextWriter))
                return output;

            if (parameter.Name == "Output" && parameter.ParameterType == typeof(Action<object>))
                return new Action<object>(output.Write);

            // meh--
            if (parameter.Name == "Html") {
                return new HtmlHelper(
                    displayContext.ViewContext,
                    displayContext.ViewDataContainer,
                    _routeCollection);
            }

            if (parameter.Name == "Url" && parameter.ParameterType.IsAssignableFrom(typeof(UrlHelper))) {
                return new UrlHelper(displayContext.ViewContext.RequestContext, _routeCollection);
            } 

            var getter = _getters.GetOrAdd(parameter.Name, n =>
                CallSite<Func<CallSite, object, dynamic>>.Create(
                Microsoft.CSharp.RuntimeBinder.Binder.GetMember(
                CSharpBinderFlags.None, n, null, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })));

            var result = getter.Target(getter, displayContext.Value);

            if (result == null)
                return null;

            var converter = _converters.GetOrAdd(parameter.ParameterType, CompileConverter);
            var argument = converter.Invoke(result);
            return argument;
        }
        public new IHtmlString Execute(DisplayContext context)
        {
            ContentPart part;
            var shape = ((dynamic)context.Value);

            try
            {
                part = (ContentPart)shape.ContentPart;
            }
            catch (Exception ex)
            {
                //this means that this is not a content part being displayed
                return base.Execute(context);
            }

            if (part == null)
            {
                return base.Execute(context);
            }

            return _outputCachedPartsService.BuildAndCacheOutput(() => base.Execute(context), part);
        }
        private async Task<IHtmlContent> RenderAsync(ShapeDescriptor shapeDescriptor, DisplayContext displayContext, HarvestShapeInfo harvestShapeInfo, HarvestShapeHit harvestShapeHit)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Rendering template file '{0}'", harvestShapeInfo.TemplateVirtualPath);
            }
            IHtmlContent result;

            if (displayContext.ViewContext.View != null)
            {
                var htmlHelper = MakeHtmlHelper(displayContext.ViewContext, displayContext.ViewContext.ViewData);
                result = htmlHelper.Partial(harvestShapeInfo.TemplateVirtualPath, displayContext.Value);
            }
            else
            {
                // If the View is null, it means that the shape is being executed from a non-view origin / where no ViewContext was established by the view engine, but manually.
                // Manually creating a ViewContext works when working with Shape methods, but not when the shape is implemented as a Razor view template.
                // Horrible, but it will have to do for now.
                result = await RenderRazorViewAsync(harvestShapeInfo.TemplateVirtualPath, displayContext);
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Done rendering template file '{0}'", harvestShapeInfo.TemplateVirtualPath);
            }
            return result;
        }
Example #16
0
 static IHtmlString Process(ShapeBinding shapeBinding, IShape shape, DisplayContext context)
 {
     if (shapeBinding == null || shapeBinding.Binding == null) {
         // todo: create result from all child shapes
         return shape.Metadata.ChildContent ?? new HtmlString("");
     }
     return CoerceHtmlString(shapeBinding.Binding(context));
 }
        private bool TryGetDescriptorBinding(string shapeType, IEnumerable<string> shapeAlternates, ShapeTable shapeTable, DisplayContext displayContext, out ShapeBinding shapeBinding) {
            // shape alternates are optional, fully qualified binding names
            // the earliest added alternates have the lowest priority
            // the descriptor returned is based on the binding that is matched, so it may be an entirely
            // different descriptor if the alternate has a different base name
            foreach (var shapeAlternate in shapeAlternates.Reverse()) {

                foreach (var shapeBindingResolver in _shapeBindingResolvers) {
                    if (shapeBindingResolver.TryGetDescriptorBinding(shapeAlternate, out shapeBinding)) {
                        return true;
                    }
                }

                if (shapeTable.Bindings.TryGetValue(string.Concat(displayContext.BindingType, "|", shapeAlternate), out shapeBinding)) {
                    return true;
                }
            }

            // when no alternates match, the shapeType is used to find the longest matching binding
            // the shapetype name can break itself into shorter fallbacks at double-underscore marks
            // so the shapetype itself may contain a longer alternate forms that falls back to a shorter one
            var shapeTypeScan = shapeType;
            for (; ; ) {
                foreach (var shapeBindingResolver in _shapeBindingResolvers) {
                    if (shapeBindingResolver.TryGetDescriptorBinding(shapeTypeScan, out shapeBinding)) {
                        return true;
                    }
                }

                if (shapeTable.Bindings.TryGetValue(string.Concat(displayContext.BindingType, "|", shapeTypeScan), out shapeBinding)) {
                    return true;
                }

                var delimiterIndex = shapeTypeScan.LastIndexOf("__");
                if (delimiterIndex < 0) {
                    shapeBinding = null;
                    return false;
                }

                shapeTypeScan = shapeTypeScan.Substring(0, delimiterIndex);
            }
        }
Example #18
0
 static async Task <IHtmlContent> ProcessAsync(ShapeBinding shapeBinding, IShape shape, DisplayContext context)
 {
     if (shapeBinding == null || shapeBinding.BindingAsync == null)
     {
         // todo: create result from all child shapes
         return(shape.Metadata.ChildContent ?? HtmlString.Empty);
     }
     return(CoerceHtmlString(await shapeBinding.BindingAsync(context)));
 }
        private IHtmlString Render(ShapeDescriptor shapeDescriptor, DisplayContext displayContext, HarvestShapeInfo harvestShapeInfo, HarvestShapeHit harvestShapeHit) {
            Logger.Information("Rendering template file '{0}'", harvestShapeInfo.TemplateVirtualPath);

            var htmlHelper = new HtmlHelper(displayContext.ViewContext, displayContext.ViewDataContainer);
            var result = htmlHelper.Partial(harvestShapeInfo.TemplateVirtualPath, displayContext.Value);

            Logger.Information("Done rendering template file '{0}'", harvestShapeInfo.TemplateVirtualPath);
            return result;
        }
        private IHtmlString RenderRazorViewToString(string path, DisplayContext context) {
            using (var sw = new StringWriter()) {
                var controllerContext = CreateControllerContext();
                var viewResult = _viewEngine.Value.FindPartialView(controllerContext, path, false);

                context.ViewContext.ViewData = new ViewDataDictionary(context.Value);
                context.ViewContext.TempData = new TempDataDictionary();
                viewResult.View.Render(context.ViewContext, sw);
                viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
                return new HtmlString(sw.GetStringBuilder().ToString());
            }
        }
        private IHtmlString Render(ShapeDescriptor shapeDescriptor, DisplayContext displayContext, HarvestShapeInfo harvestShapeInfo, HarvestShapeHit harvestShapeHit) {
            Logger.Information("Rendering template file '{0}'", harvestShapeInfo.TemplateVirtualPath);
            IHtmlString result;

            if (displayContext.ViewContext.View != null) {
                var htmlHelper = new HtmlHelper(displayContext.ViewContext, displayContext.ViewDataContainer);
                result = htmlHelper.Partial(harvestShapeInfo.TemplateVirtualPath, displayContext.Value);
            }
            else {
                // If the View is null, it means that the shape is being executed from a non-view origin / where no ViewContext was established by the view engine, but manually.
                // Manually creating a ViewContext works when working with Shape methods, but not when the shape is implemented as a Razor view template.
                // Horrible, but it will have to do for now.
                result = RenderRazorViewToString(harvestShapeInfo.TemplateVirtualPath, displayContext);
            }

            Logger.Information("Done rendering template file '{0}'", harvestShapeInfo.TemplateVirtualPath);
            return result;
        }
Example #22
0
 public object ShapeExecute(object shape) {
     var context = new DisplayContext { Display = this, Value = shape, ViewContext = ViewContext, ViewDataContainer = ViewDataContainer };
     return _displayManager.Execute(context);
 }
        private object BindParameter(DisplayContext displayContext, ParameterInfo parameter, TextWriter output)
        {
            if (String.Equals(parameter.Name, "Shape", StringComparison.OrdinalIgnoreCase))
            {
                return displayContext.Value;
            }

            if (String.Equals(parameter.Name, "Display", StringComparison.OrdinalIgnoreCase))
            {
                return displayContext.Display;
            }

            if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) &&
                parameter.ParameterType == typeof(TextWriter))
            {
                return output;
            }

            if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) &&
                parameter.ParameterType == typeof(Action<object>))
            {
                return new Action<object>(output.Write);
            }

            if (String.Equals(parameter.Name, "Html", StringComparison.OrdinalIgnoreCase))
            {
                return MakeHtmlHelper(displayContext.ViewContext, displayContext.ViewContext.ViewData);
            }

            if (String.Equals(parameter.Name, "Url", StringComparison.OrdinalIgnoreCase) &&
                parameter.ParameterType.IsAssignableFrom(typeof(UrlHelper)))
            {
                return _componentContext.GetService<IUrlHelper>();
            }

            var getter = _getters.GetOrAdd(parameter.Name.ToLowerInvariant(), n =>
                CallSite<Func<CallSite, object, dynamic>>.Create(
                Binder.GetMember(
                CSharpBinderFlags.None, n, null, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })));

            var result = getter.Target(getter, displayContext.Value);

            if (result == null)
                return null;

            //var converter = _converters.GetOrAdd(parameter.ParameterType, CompileConverter);
            //var argument = converter.Invoke(result);
            //return argument;

            return Convert.ChangeType(result, parameter.ParameterType);
        }
        private async Task<IHtmlContent> RenderRazorViewAsync(string path, DisplayContext context)
        {
            var viewEngineResult = _viewEngine.Value.ViewEngines.First().FindView(context.ViewContext, path, isMainPage: false);
            if (viewEngineResult.Success)
            {
                var bufferScope = context.ViewContext.HttpContext.RequestServices.GetRequiredService<IViewBufferScope>();
                var viewBuffer = new ViewBuffer(bufferScope, viewEngineResult.ViewName, ViewBuffer.PartialViewPageSize);
                using (var writer = new ViewBufferTextWriter(viewBuffer, context.ViewContext.Writer.Encoding))
                {
                    // Forcing synchronous behavior so users don't have to await templates.
                    var view = viewEngineResult.View;
                    using (view as IDisposable)
                    {
                        var viewContext = new ViewContext(context.ViewContext, viewEngineResult.View, context.ViewContext.ViewData, writer);
                        await viewEngineResult.View.RenderAsync(viewContext);
                        return viewBuffer;
                    }
                }
            }

            return null;
        }
        private IHtmlContent PerformInvoke(DisplayContext displayContext, MethodInfo methodInfo, object serviceInstance)
        {
            using (var output = new StringCollectionTextWriter(System.Text.Encoding.UTF8))
            {
                var arguments = methodInfo
                    .GetParameters()
                    .Select(parameter => BindParameter(displayContext, parameter, output));

                // Resolve the service the method is declared on
                var returnValue = methodInfo.Invoke(serviceInstance, arguments.ToArray());

                // If the shape returns a value, write it to the stream
                if (methodInfo.ReturnType != typeof(void))
                {
                    output.Write(CoerceHtmlString(returnValue));
                }

                return output.Content;
            }
        }
        private async Task<IHtmlContent> RenderRazorViewAsync(string path, DisplayContext context)
        {
            var viewEngineResult = _viewEngine.Value.ViewEngines.First().FindPartialView(_actionContextAccessor.ActionContext, path);
            if (viewEngineResult.Success)
            {
                using (var writer = new StringCollectionTextWriter(context.ViewContext.Writer.Encoding))
                {
                    // Forcing synchronous behavior so users don't have to await templates.
                    var view = viewEngineResult.View;
                    using (view as IDisposable)
                    {
                        var viewContext = new ViewContext(context.ViewContext, viewEngineResult.View, context.ViewContext.ViewData, writer);
                        await viewEngineResult.View.RenderAsync(viewContext);
                        return writer.Content;
                    }
                }
            }

            return null;
        }
 static async Task<IHtmlContent> ProcessAsync(ShapeBinding shapeBinding, IShape shape, DisplayContext context)
 {
     if (shapeBinding == null || shapeBinding.BindingAsync == null)
     {
         // todo: create result from all child shapes
         return shape.Metadata.ChildContent ?? HtmlString.Empty;
     }
     return CoerceHtmlString(await shapeBinding.BindingAsync(context));
 }
        private object BindParameter(DisplayContext displayContext, ParameterInfo parameter)
        {
            if (String.Equals(parameter.Name, "Shape", StringComparison.OrdinalIgnoreCase))
            {
                return displayContext.Value;
            }

            if (String.Equals(parameter.Name, "Display", StringComparison.OrdinalIgnoreCase))
            {
                return displayContext.Display;
            }

            if (String.Equals(parameter.Name, "New", StringComparison.OrdinalIgnoreCase))
            {
                var httpContext = _httpContextAccessor.HttpContext;
                return httpContext.RequestServices.GetService<IShapeFactory>();
            }

            if (String.Equals(parameter.Name, "Html", StringComparison.OrdinalIgnoreCase))
            {
                return MakeHtmlHelper(displayContext.ViewContext, displayContext.ViewContext.ViewData);
            }

            if (String.Equals(parameter.Name, "Url", StringComparison.OrdinalIgnoreCase) &&
                parameter.ParameterType.IsAssignableFrom(typeof(UrlHelper)))
            {
                var httpContext = _httpContextAccessor.HttpContext;
                var urlHelperFactory = httpContext.RequestServices.GetService<IUrlHelperFactory>();
                return urlHelperFactory.GetUrlHelper(displayContext.ViewContext);
            }

            if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) &&
                parameter.ParameterType == typeof(TextWriter))
            {
                throw new InvalidOperationException("Output is no more a valid Shape method parameter. Return an IHtmlContent instead.");
            }

            if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) &&
                parameter.ParameterType == typeof(Action<object>))
            {
                throw new InvalidOperationException("Output is no more a valid Shape method parameter. Return an IHtmlContent instead.");
            }

            var getter = _getters.GetOrAdd(parameter.Name, n =>
                CallSite<Func<CallSite, object, dynamic>>.Create(
                Binder.GetMember(
                CSharpBinderFlags.None, n, null, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })));

            object result = getter.Target(getter, displayContext.Value);

            if (result == null)
                return null;

            if(parameter.ParameterType.IsAssignableFrom(result.GetType()))
            {
                return result;
            }

            return Convert.ChangeType(result, parameter.ParameterType);
        }
Example #29
0
        public async Task<IHtmlContent> ShapeExecuteAsync(object shape)
        {
            if (shape == null)
            {
                return new HtmlString(string.Empty);
            }

            var context = new DisplayContext { Display = this, Value = shape, ViewContext = ViewContext };
            return await _displayManager.ExecuteAsync(context);
        }
        private object BindParameter(DisplayContext displayContext, ParameterInfo parameter)
        {
            if (String.Equals(parameter.Name, "Shape", StringComparison.OrdinalIgnoreCase))
            {
                return displayContext.Value;
            }

            if (String.Equals(parameter.Name, "Display", StringComparison.OrdinalIgnoreCase))
            {
                return displayContext.Display;
            }
            
            if (String.Equals(parameter.Name, "Html", StringComparison.OrdinalIgnoreCase))
            {
                return MakeHtmlHelper(displayContext.ViewContext, displayContext.ViewContext.ViewData);
            }

            if (String.Equals(parameter.Name, "Url", StringComparison.OrdinalIgnoreCase) &&
                parameter.ParameterType.IsAssignableFrom(typeof(UrlHelper)))
            {
                return _componentContext.GetService<IUrlHelper>();
            }

            if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) &&
                parameter.ParameterType == typeof(TextWriter))
            {
                throw new InvalidOperationException("Output is no more a valid Shape method parameter");
            }

            if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) &&
                parameter.ParameterType == typeof(Action<object>))
            {
                throw new InvalidOperationException("Output is no more a valid Shape method parameter");
            }


            var getter = _getters.GetOrAdd(parameter.Name, n =>
                CallSite<Func<CallSite, object, dynamic>>.Create(
                Binder.GetMember(
                CSharpBinderFlags.None, n, null, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })));

            var result = getter.Target(getter, displayContext.Value);

            if (result == null)
                return null;

            return Convert.ChangeType(result, parameter.ParameterType);
        }
Example #31
0
        public async Task <IHtmlContent> ExecuteAsync(DisplayContext context)
        {
            var shape = context.Value as IShape;

            // non-shape arguments are returned as a no-op
            if (shape == null)
            {
                return(CoerceHtmlString(context.Value));
            }

            var shapeMetadata = shape.Metadata;

            // can't really cope with a shape that has no type information
            if (shapeMetadata == null || string.IsNullOrEmpty(shapeMetadata.Type))
            {
                return(CoerceHtmlString(context.Value));
            }

            var theme = await _themeManager.GetThemeAsync();

            var shapeTable = _shapeTableManager.GetShapeTable(theme?.Id);

            var displayingContext = new ShapeDisplayingContext
            {
                Shape          = shape,
                ShapeMetadata  = shapeMetadata,
                DisplayContext = context
            };

            // Evaluate global Shape Display Events
            _shapeDisplayEvents.Invoke(sde => sde.Displaying(displayingContext), _logger);

            // Find base shape association using only the fundamental shape type.
            // Alternates that may already be registered do not affect the "displaying" event calls.
            ShapeBinding shapeBinding;

            if (TryGetDescriptorBinding(shapeMetadata.Type, Enumerable.Empty <string>(), shapeTable, out shapeBinding))
            {
                shapeBinding.ShapeDescriptor.Displaying.Invoke(action => action(displayingContext), _logger);

                // copy all binding sources (all templates for this shape) in order to use them as Localization scopes
                shapeMetadata.BindingSources = shapeBinding.ShapeDescriptor.BindingSources.Where(x => x != null).ToList();
                if (!shapeMetadata.BindingSources.Any())
                {
                    shapeMetadata.BindingSources.Add(shapeBinding.ShapeDescriptor.BindingSource);
                }
            }

            // invoking ShapeMetadata displaying events
            shapeMetadata.Displaying.Invoke(action => action(displayingContext), _logger);

            // use pre-fectched content if available (e.g. coming from specific cache implementation)
            if (displayingContext.ChildContent != null)
            {
                shape.Metadata.ChildContent = displayingContext.ChildContent;
            }
            else
            {
                // now find the actual binding to render, taking alternates into account
                ShapeBinding actualBinding;
                if (TryGetDescriptorBinding(shapeMetadata.Type, shapeMetadata.Alternates, shapeTable, out actualBinding))
                {
                    shapeBinding.ShapeDescriptor.Processing.Invoke(action => action(displayingContext), _logger);

                    // invoking ShapeMetadata processing events
                    await shapeMetadata.Processing.InvokeAsync(processing => processing(shape), _logger);

                    shape.Metadata.ChildContent = await ProcessAsync(actualBinding, shape, context);
                }
                else
                {
                    throw new OrchardException(T("Shape type {0} not found", shapeMetadata.Type));
                }
            }

            foreach (var frameType in shape.Metadata.Wrappers)
            {
                ShapeBinding frameBinding;
                if (TryGetDescriptorBinding(frameType, Enumerable.Empty <string>(), shapeTable, out frameBinding))
                {
                    shape.Metadata.ChildContent = await ProcessAsync(frameBinding, shape, context);
                }
            }

            var displayedContext = new ShapeDisplayedContext
            {
                Shape          = shape,
                ShapeMetadata  = shape.Metadata,
                ChildContent   = shape.Metadata.ChildContent,
                DisplayContext = context
            };

            _shapeDisplayEvents.Invoke(sde =>
            {
                var prior = displayedContext.ChildContent = displayedContext.ShapeMetadata.ChildContent;
                sde.Displayed(displayedContext);
                // update the child content if the context variable has been reassigned
                if (prior != displayedContext.ChildContent)
                {
                    displayedContext.ShapeMetadata.ChildContent = displayedContext.ChildContent;
                }
            }, _logger);

            if (shapeBinding != null)
            {
                shapeBinding.ShapeDescriptor.Displayed.Invoke(action =>
                {
                    var prior = displayedContext.ChildContent = displayedContext.ShapeMetadata.ChildContent;
                    action(displayedContext);
                    // update the child content if the context variable has been reassigned
                    if (prior != displayedContext.ChildContent)
                    {
                        displayedContext.ShapeMetadata.ChildContent = displayedContext.ChildContent;
                    }
                }, _logger);
            }

            // invoking ShapeMetadata displayed events
            shapeMetadata.Displayed.Invoke(action => action(displayedContext), _logger);

            return(shape.Metadata.ChildContent);
        }
Example #32
0
        public async Task <IHtmlContent> ExecuteAsync(DisplayContext context)
        {
            var shape = context.Value as IShape;

            // non-shape arguments are returned as a no-op
            if (shape == null)
            {
                return(CoerceHtmlString(context.Value));
            }

            var shapeMetadata = shape.Metadata;

            // can't really cope with a shape that has no type information
            if (shapeMetadata == null || string.IsNullOrEmpty(shapeMetadata.Type))
            {
                return(CoerceHtmlString(context.Value));
            }

            var theme = await _themeManager.GetThemeAsync();

            var shapeTable = _shapeTableManager.GetShapeTable(theme?.Id);

            var displayContext = new ShapeDisplayContext
            {
                Shape           = shape,
                ShapeMetadata   = shapeMetadata,
                DisplayContext  = context,
                ServiceProvider = _serviceProvider
            };

            // Use the same prefix as the shape
            var originalHtmlFieldPrefix = context.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix;

            context.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = shapeMetadata.Prefix ?? "";

            // Evaluate global Shape Display Events
            _shapeDisplayEvents.Invoke(sde => sde.Displaying(displayContext), _logger);

            // Find base shape association using only the fundamental shape type.
            // Alternates that may already be registered do not affect the "displaying" event calls.
            ShapeBinding shapeBinding;

            if (TryGetDescriptorBinding(shapeMetadata.Type, Enumerable.Empty <string>(), shapeTable, out shapeBinding))
            {
                shapeBinding.ShapeDescriptor.Displaying.Invoke(action => action(displayContext), _logger);

                // copy all binding sources (all templates for this shape) in order to use them as Localization scopes
                shapeMetadata.BindingSources = shapeBinding.ShapeDescriptor.BindingSources.Where(x => x != null).ToList();
                if (!shapeMetadata.BindingSources.Any())
                {
                    shapeMetadata.BindingSources.Add(shapeBinding.ShapeDescriptor.BindingSource);
                }
            }

            // invoking ShapeMetadata displaying events
            shapeMetadata.Displaying.Invoke(action => action(displayContext), _logger);

            // use pre-fectched content if available (e.g. coming from specific cache implementation)
            if (displayContext.ChildContent != null)
            {
                shape.Metadata.ChildContent = displayContext.ChildContent;
            }

            if (shape.Metadata.ChildContent == null)
            {
                // now find the actual binding to render, taking alternates into account
                ShapeBinding actualBinding;
                if (TryGetDescriptorBinding(shapeMetadata.Type, shapeMetadata.Alternates, shapeTable, out actualBinding))
                {
                    // There might be no shape binding for the main shape, and only for its alternates.
                    if (shapeBinding != null)
                    {
                        await shapeBinding.ShapeDescriptor.ProcessingAsync.InvokeAsync(action => action(displayContext), _logger);
                    }

                    // invoking ShapeMetadata processing events, this includes the Drivers results
                    await shapeMetadata.ProcessingAsync.InvokeAsync(processing => processing(displayContext.Shape), _logger);

                    shape.Metadata.ChildContent = await ProcessAsync(actualBinding, shape, context);
                }
                else
                {
                    throw new Exception($"Shape type '{shapeMetadata.Type}' not found");
                }
            }

            // Process wrappers
            if (shape.Metadata.Wrappers.Count > 0)
            {
                foreach (var frameType in shape.Metadata.Wrappers)
                {
                    ShapeBinding frameBinding;
                    if (TryGetDescriptorBinding(frameType, Enumerable.Empty <string>(), shapeTable, out frameBinding))
                    {
                        shape.Metadata.ChildContent = await ProcessAsync(frameBinding, shape, context);
                    }
                }

                // Clear wrappers to prevent the child content from rendering them again
                shape.Metadata.Wrappers.Clear();
            }

            _shapeDisplayEvents.Invoke(sde =>
            {
                var prior = displayContext.ChildContent = displayContext.ShapeMetadata.ChildContent;
                sde.Displayed(displayContext);
                // update the child content if the context variable has been reassigned
                if (prior != displayContext.ChildContent)
                {
                    displayContext.ShapeMetadata.ChildContent = displayContext.ChildContent;
                }
            }, _logger);

            if (shapeBinding != null)
            {
                shapeBinding.ShapeDescriptor.Displayed.Invoke(action =>
                {
                    var prior = displayContext.ChildContent = displayContext.ShapeMetadata.ChildContent;
                    action(displayContext);
                    // update the child content if the context variable has been reassigned
                    if (prior != displayContext.ChildContent)
                    {
                        displayContext.ShapeMetadata.ChildContent = displayContext.ChildContent;
                    }
                }, _logger);
            }

            // invoking ShapeMetadata displayed events
            shapeMetadata.Displayed.Invoke(action => action(displayContext), _logger);

            //restore original HtmlFieldPrefix
            context.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = originalHtmlFieldPrefix;

            return(shape.Metadata.ChildContent);
        }
 public string Process(string template, string name, DisplayContext context = null, dynamic model = null)
 {
     return _templateService.ExecuteTemplate(template, model);
 }
        public async Task<IHtmlContent> ExecuteAsync(DisplayContext context)
        {
            var shape = context.Value as IShape;

            // non-shape arguments are returned as a no-op
            if (shape == null)
                return CoerceHtmlString(context.Value);

            var shapeMetadata = shape.Metadata;
            // can't really cope with a shape that has no type information
            if (shapeMetadata == null || string.IsNullOrEmpty(shapeMetadata.Type))
                return CoerceHtmlString(context.Value);

            var theme = await _themeManager.GetThemeAsync();
            var shapeTable = _shapeTableManager.GetShapeTable(theme?.Id);

            var displayingContext = new ShapeDisplayingContext
            {
                Shape = shape,
                ShapeMetadata = shapeMetadata,
                DisplayContext = context
            };

            // Evaluate global Shape Display Events
            _shapeDisplayEvents.Invoke(sde => sde.Displaying(displayingContext), _logger);

            // Find base shape association using only the fundamental shape type.
            // Alternates that may already be registered do not affect the "displaying" event calls.
            ShapeBinding shapeBinding;
            if (TryGetDescriptorBinding(shapeMetadata.Type, Enumerable.Empty<string>(), shapeTable, out shapeBinding))
            {
                shapeBinding.ShapeDescriptor.Displaying.Invoke(action => action(displayingContext), _logger);

                // copy all binding sources (all templates for this shape) in order to use them as Localization scopes
                shapeMetadata.BindingSources = shapeBinding.ShapeDescriptor.BindingSources.Where(x => x != null).ToList();
                if (!shapeMetadata.BindingSources.Any())
                {
                    shapeMetadata.BindingSources.Add(shapeBinding.ShapeDescriptor.BindingSource);
                }
            }

            // invoking ShapeMetadata displaying events
            shapeMetadata.Displaying.Invoke(action => action(displayingContext), _logger);

            // use pre-fectched content if available (e.g. coming from specific cache implementation)
            if (displayingContext.ChildContent != null)
            {
                shape.Metadata.ChildContent = displayingContext.ChildContent;
            }
            else
            {
                // now find the actual binding to render, taking alternates into account
                ShapeBinding actualBinding;
                if (TryGetDescriptorBinding(shapeMetadata.Type, shapeMetadata.Alternates, shapeTable, out actualBinding))
                {
                    shapeBinding.ShapeDescriptor.Processing.Invoke(action => action(displayingContext), _logger);

                    // invoking ShapeMetadata processing events
                    await shapeMetadata.Processing.InvokeAsync(processing => processing(shape), _logger);

                    shape.Metadata.ChildContent = await ProcessAsync(actualBinding, shape, context);
                }
                else
                {
                    throw new OrchardException(T("Shape type {0} not found", shapeMetadata.Type));
                }
            }

            foreach (var frameType in shape.Metadata.Wrappers)
            {
                ShapeBinding frameBinding;
                if (TryGetDescriptorBinding(frameType, Enumerable.Empty<string>(), shapeTable, out frameBinding))
                {
                    shape.Metadata.ChildContent = await ProcessAsync(frameBinding, shape, context);
                }
            }

            var displayedContext = new ShapeDisplayedContext
            {
                Shape = shape,
                ShapeMetadata = shape.Metadata,
                ChildContent = shape.Metadata.ChildContent,
                DisplayContext = context
            };

            _shapeDisplayEvents.Invoke(sde =>
            {
                var prior = displayedContext.ChildContent = displayedContext.ShapeMetadata.ChildContent;
                sde.Displayed(displayedContext);
                // update the child content if the context variable has been reassigned
                if (prior != displayedContext.ChildContent)
                    displayedContext.ShapeMetadata.ChildContent = displayedContext.ChildContent;
            }, _logger);

            if (shapeBinding != null)
            {
                shapeBinding.ShapeDescriptor.Displayed.Invoke(action =>
                {
                    var prior = displayedContext.ChildContent = displayedContext.ShapeMetadata.ChildContent;
                    action(displayedContext);
                    // update the child content if the context variable has been reassigned
                    if (prior != displayedContext.ChildContent)
                        displayedContext.ShapeMetadata.ChildContent = displayedContext.ChildContent;
                }, _logger);
            }

            // invoking ShapeMetadata displayed events
            shapeMetadata.Displayed.Invoke(action => action(displayedContext), _logger);

            return shape.Metadata.ChildContent;
        }
Example #35
0
        public IHtmlString Execute(DisplayContext context)
        {
            var shape = _convertAsShapeCallsite.Target(_convertAsShapeCallsite, context.Value);

            // non-shape arguments are returned as a no-op
            if (shape == null)
            {
                return(CoerceHtmlString(context.Value));
            }

            var shapeMetadata = shape.Metadata;

            // can't really cope with a shape that has no type information
            if (shapeMetadata == null || string.IsNullOrEmpty(shapeMetadata.Type))
            {
                return(CoerceHtmlString(context.Value));
            }

            var workContext = _workContextAccessor.GetContext();
            // CurrentTheme is now available in the background, so here we no longer use IsBackgroundContext().
            // We only do a null check, so we can render in the background a view that only exists in the theme.
            var shapeTable = _httpContextAccessor.Current() != null
                ? _shapeTableLocator.Value.Lookup(workContext.CurrentTheme.Id)
                : _shapeTableLocator.Value.Lookup(null);

            var displayingContext = new ShapeDisplayingContext {
                Shape         = shape,
                ShapeMetadata = shapeMetadata
            };

            _shapeDisplayEvents.Invoke(sde => sde.Displaying(displayingContext), Logger);

            // find base shape association using only the fundamental shape type.
            // alternates that may already be registered do not affect the "displaying" event calls
            ShapeBinding shapeBinding;

            if (TryGetDescriptorBinding(shapeMetadata.Type, Enumerable.Empty <string>(), shapeTable, shapeMetadata.BindingType, out shapeBinding))
            {
                shapeBinding.ShapeDescriptor.Displaying.Invoke(action => action(displayingContext), Logger);

                // copy all binding sources (all templates for this shape) in order to use them as Localization scopes
                shapeMetadata.BindingSources = shapeBinding.ShapeDescriptor.BindingSources.Where(x => x != null).ToList();
                if (!shapeMetadata.BindingSources.Any())
                {
                    shapeMetadata.BindingSources.Add(shapeBinding.ShapeDescriptor.BindingSource);
                }
            }

            // invoking ShapeMetadata displaying events
            shapeMetadata.Displaying.Invoke(action => action(displayingContext), Logger);

            // use pre-fectched content if available (e.g. coming from specific cache implmentation)
            if (displayingContext.ChildContent != null)
            {
                shape.Metadata.ChildContent = displayingContext.ChildContent;
            }
            else
            {
                // now find the actual binding to render, taking alternates into account
                ShapeBinding actualBinding;
                if (TryGetDescriptorBinding(shapeMetadata.Type, shapeMetadata.Alternates, shapeTable, shapeMetadata.BindingType, out actualBinding))
                {
                    shape.Metadata.ChildContent = Process(actualBinding, shape, context);
                }
                else
                {
                    throw new OrchardException(T("Shape type {0} not found", shapeMetadata.Type));
                }
            }

            foreach (var frameType in shape.Metadata.Wrappers)
            {
                ShapeBinding frameBinding;
                if (TryGetDescriptorBinding(frameType, Enumerable.Empty <string>(), shapeTable, shapeMetadata.BindingType, out frameBinding))
                {
                    shape.Metadata.ChildContent = Process(frameBinding, shape, context);
                }
            }

            var displayedContext = new ShapeDisplayedContext {
                Shape         = shape,
                ShapeMetadata = shape.Metadata,
                ChildContent  = shape.Metadata.ChildContent,
            };

            _shapeDisplayEvents.Invoke(sde => {
                var prior = displayedContext.ChildContent = displayedContext.ShapeMetadata.ChildContent;
                sde.Displayed(displayedContext);
                // update the child content if the context variable has been reassigned
                if (prior != displayedContext.ChildContent)
                {
                    displayedContext.ShapeMetadata.ChildContent = displayedContext.ChildContent;
                }
            }, Logger);

            if (shapeBinding != null)
            {
                shapeBinding.ShapeDescriptor.Displayed.Invoke(action => {
                    var prior = displayedContext.ChildContent = displayedContext.ShapeMetadata.ChildContent;
                    action(displayedContext);
                    // update the child content if the context variable has been reassigned
                    if (prior != displayedContext.ChildContent)
                    {
                        displayedContext.ShapeMetadata.ChildContent = displayedContext.ChildContent;
                    }
                }, Logger);
            }

            // invoking ShapeMetadata displayed events
            shapeMetadata.Displayed.Invoke(action => action(displayedContext), Logger);

            return(shape.Metadata.ChildContent);
        }
        public void BindingProvidedByStrategyInvokesMethod() {
            var initializers = GetAlterationBuilders(_container.Resolve<IShapeTableProvider>());

            var shapeDescriptor = initializers.Where(i => i.ShapeType == "Simple")
                .Aggregate(new ShapeDescriptor { ShapeType = "Simple" }, (d, i) => { i.Alter(d); return d; });

            var displayContext = new DisplayContext();
            var result = shapeDescriptor.Binding(displayContext);
            var result2 = shapeDescriptor.Binding.Invoke(displayContext);
            Assert.That(result.ToString(), Is.StringContaining("Simple"));
            Assert.That(result2.ToString(), Is.StringContaining("Simple"));
        }
Example #37
0
        public IHtmlString Execute(DisplayContext context)
        {
            var shape = _convertAsShapeCallsite.Target(_convertAsShapeCallsite, context.Value);

            // non-shape arguments are returned as a no-op
            if (shape == null)
                return CoerceHtmlString(context.Value);

            var shapeMetadata = shape.Metadata;
            // can't really cope with a shape that has no type information
            if (shapeMetadata == null || string.IsNullOrEmpty(shapeMetadata.Type))
                return CoerceHtmlString(context.Value);

            var workContext = _workContextAccessor.GetContext();
            // CurrentTheme is now available in the background, so here we no longer use IsBackgroundContext().
            // We only do a null check, so we can render in the background a view that only exists in the theme.
            var shapeTable = _httpContextAccessor.Current() != null
                ? _shapeTableLocator.Value.Lookup(workContext.CurrentTheme.Id)
                : _shapeTableLocator.Value.Lookup(null);

            var displayingContext = new ShapeDisplayingContext {
                Shape = shape,
                ShapeMetadata = shapeMetadata
            };
            _shapeDisplayEvents.Invoke(sde => sde.Displaying(displayingContext), Logger);

            // find base shape association using only the fundamental shape type.
            // alternates that may already be registered do not affect the "displaying" event calls
            ShapeBinding shapeBinding;
            if (TryGetDescriptorBinding(shapeMetadata.Type, Enumerable.Empty<string>(), shapeTable, out shapeBinding)) {
                shapeBinding.ShapeDescriptor.Displaying.Invoke(action => action(displayingContext), Logger);

                // copy all binding sources (all templates for this shape) in order to use them as Localization scopes
                shapeMetadata.BindingSources = shapeBinding.ShapeDescriptor.BindingSources.Where(x => x != null).ToList();
                if (!shapeMetadata.BindingSources.Any()) {
                    shapeMetadata.BindingSources.Add(shapeBinding.ShapeDescriptor.BindingSource);
                }
            }

            // invoking ShapeMetadata displaying events
            shapeMetadata.Displaying.Invoke(action => action(displayingContext), Logger);

            // use pre-fectched content if available (e.g. coming from specific cache implmentation)
            if ( displayingContext.ChildContent != null ) {
                shape.Metadata.ChildContent = displayingContext.ChildContent;
            }
            else {
                // now find the actual binding to render, taking alternates into account
                ShapeBinding actualBinding;
                if ( TryGetDescriptorBinding(shapeMetadata.Type, shapeMetadata.Alternates, shapeTable, out actualBinding) ) {
                    shape.Metadata.ChildContent = Process(actualBinding, shape, context);
                }
                else {
                    throw new OrchardException(T("Shape type {0} not found", shapeMetadata.Type));
                }
            }

            foreach (var frameType in shape.Metadata.Wrappers) {
                ShapeBinding frameBinding;
                if (TryGetDescriptorBinding(frameType, Enumerable.Empty<string>(), shapeTable, out frameBinding)) {
                    shape.Metadata.ChildContent = Process(frameBinding, shape, context);
                }
            }

            var displayedContext = new ShapeDisplayedContext {
                Shape = shape,
                ShapeMetadata = shape.Metadata,
                ChildContent = shape.Metadata.ChildContent,
            };

            _shapeDisplayEvents.Invoke(sde => {
                var prior = displayedContext.ChildContent = displayedContext.ShapeMetadata.ChildContent;
                sde.Displayed(displayedContext);
                // update the child content if the context variable has been reassigned
                if (prior != displayedContext.ChildContent)
                    displayedContext.ShapeMetadata.ChildContent = displayedContext.ChildContent;
            }, Logger);

            if (shapeBinding != null) {
                shapeBinding.ShapeDescriptor.Displayed.Invoke(action => {
                    var prior = displayedContext.ChildContent = displayedContext.ShapeMetadata.ChildContent;
                    action(displayedContext);
                    // update the child content if the context variable has been reassigned
                    if (prior != displayedContext.ChildContent)
                        displayedContext.ShapeMetadata.ChildContent = displayedContext.ChildContent;
                }, Logger);
            }

            // invoking ShapeMetadata displayed events
            shapeMetadata.Displayed.Invoke(action => action(displayedContext), Logger);

            return shape.Metadata.ChildContent;
        }
 public abstract string Process(string template, string name, DisplayContext context = null, dynamic model = null);