protected override IDictionary<string, object> GetValidationAttributes(
     ViewContext viewContext,
     ModelExplorer modelExplorer,
     string name)
 {
     return ValidationAttributes;
 }
Example #2
0
        public void CopyConstructor_CopiesExpectedProperties()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var originalContext = new ViewContext(
                new ActionContext(httpContext, new RouteData(), new ActionDescriptor()),
                view: Mock.Of<IView>(),
                viewData: new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider()),
                tempData: new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>()),
                writer: TextWriter.Null,
                htmlHelperOptions: new HtmlHelperOptions());
            var view = Mock.Of<IView>();
            var viewData = new ViewDataDictionary(originalContext.ViewData);
            var writer = new HtmlContentWrapperTextWriter(new HtmlContentBuilder(), Encoding.UTF8);

            // Act
            var context = new ViewContext(originalContext, view, viewData, writer);

            // Assert
            Assert.Same(originalContext.ActionDescriptor, context.ActionDescriptor);
            Assert.Equal(originalContext.ClientValidationEnabled, context.ClientValidationEnabled);
            Assert.Same(originalContext.ExecutingFilePath, context.ExecutingFilePath);
            Assert.Same(originalContext.FormContext, context.FormContext);
            Assert.Equal(originalContext.Html5DateRenderingMode, context.Html5DateRenderingMode);
            Assert.Same(originalContext.HttpContext, context.HttpContext);
            Assert.Same(originalContext.ModelState, context.ModelState);
            Assert.Same(originalContext.RouteData, context.RouteData);
            Assert.Same(originalContext.TempData, context.TempData);
            Assert.Same(originalContext.ValidationMessageElement, context.ValidationMessageElement);
            Assert.Same(originalContext.ValidationSummaryMessageElement, context.ValidationSummaryMessageElement);

            Assert.Same(view, context.View);
            Assert.Same(viewData, context.ViewData);
            Assert.Same(writer, context.Writer);
        }
Example #3
0
        public void SettingViewData_AlsoUpdatesViewBag()
        {
            // Arrange
            var originalViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());
            var context = new ViewContext(
                new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()),
                view: Mock.Of<IView>(),
                viewData: originalViewData,
                tempData: new TempDataDictionary(new HttpContextAccessor(), Mock.Of<ITempDataProvider>()),
                writer: TextWriter.Null,
                htmlHelperOptions: new HtmlHelperOptions());
            var replacementViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());

            // Act
            context.ViewBag.Hello = "goodbye";
            context.ViewData = replacementViewData;
            context.ViewBag.Another = "property";

            // Assert
            Assert.NotSame(originalViewData, context.ViewData);
            Assert.Same(replacementViewData, context.ViewData);
            Assert.Null(context.ViewBag.Hello);
            Assert.Equal("property", context.ViewBag.Another);
            Assert.Equal("property", context.ViewData["Another"]);
        }
        public async Task CartSummaryComponent_Returns_CartedItems()
        {
            // Arrange
            var viewContext = new ViewContext()
            {
                HttpContext = new DefaultHttpContext()
            };

            // Session initialization
            var cartId = "CartId_A";
            viewContext.HttpContext.Session = new TestSession();
            viewContext.HttpContext.Session.SetString("Session", cartId);

            // DbContext initialization
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            PopulateData(dbContext, cartId, albumTitle: "AlbumA", itemCount: 10);

            // CartSummaryComponent initialization
            var cartSummaryComponent = new CartSummaryComponent(dbContext)
            {
                ViewComponentContext = new ViewComponentContext() { ViewContext = viewContext }
            };

            // Act
            var result = await cartSummaryComponent.InvokeAsync();

            // Assert
            Assert.NotNull(result);
            var viewResult = Assert.IsType<ViewViewComponentResult>(result);
            Assert.Null(viewResult.ViewName);
            Assert.Null(viewResult.ViewData.Model);
            Assert.Equal(10, cartSummaryComponent.ViewBag.CartCount);
            Assert.Equal("AlbumA", cartSummaryComponent.ViewBag.CartSummary);
        }
        public void SettingViewData_AlsoUpdatesViewBag()
        {
            // Arrange (eventually passing null to these consturctors will throw)
            var context = new ViewContext(
                new ActionContext(null, null, null),
                view: null,
                viewData: null,
                tempData: null,
                writer: null,
                htmlHelperOptions: new HtmlHelperOptions());
            var originalViewData = context.ViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());
            var replacementViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());

            // Act
            context.ViewBag.Hello = "goodbye";
            context.ViewData = replacementViewData;
            context.ViewBag.Another = "property";

            // Assert
            Assert.NotSame(originalViewData, context.ViewData);
            Assert.Same(replacementViewData, context.ViewData);
            Assert.Null(context.ViewBag.Hello);
            Assert.Equal("property", context.ViewBag.Another);
            Assert.Equal("property", context.ViewData["Another"]);
        }
        /// <summary>
        /// Initialises a new instance of <see cref="WidgetContext"/>.
        /// </summary>
        /// <param name="widgetDescriptor">The widget descriptor.</param>
        /// <param name="values">The set of provided invocation values.</param>
        /// <param name="viewContext">The view context.</param>
        /// <param name="writer">The text writer.</param>
        public WidgetContext(WidgetDescriptor widgetDescriptor, RouteValueDictionary values, ViewContext viewContext, TextWriter writer)
        {
            if (widgetDescriptor == null)
            {
                throw new ArgumentNullException(nameof(widgetDescriptor));
            }

            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (viewContext == null)
            {
                throw new ArgumentNullException(nameof(viewContext));
            }

            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            WidgetDescriptor = widgetDescriptor;
            Values = values;

            ViewContext = new ViewContext(
                viewContext,
                viewContext.View,
                new ViewDataDictionary(viewContext.ViewData),
                writer);
        }
 public dynamic CreateHelper(ViewContext viewContext)
 {
     return new DisplayHelper(
         _displayManager,
         _shapeFactory,
         viewContext);
 }
Example #8
0
        public TemplateRenderer(
            IViewEngine viewEngine,
            ViewContext viewContext,
            ViewDataDictionary viewData,
            string templateName,
            bool readOnly)
        {
            if (viewEngine == null)
            {
                throw new ArgumentNullException(nameof(viewEngine));
            }

            if (viewContext == null)
            {
                throw new ArgumentNullException(nameof(viewContext));
            }

            if (viewData == null)
            {
                throw new ArgumentNullException(nameof(viewData));
            }

            _viewEngine = viewEngine;
            _viewContext = viewContext;
            _viewData = viewData;
            _templateName = templateName;
            _readOnly = readOnly;
        }
Example #9
0
        public void ViewLocalizer_UseIndexerWithArguments_ReturnsLocalizedString()
        {
            // Arrange
            var applicationEnvironment = new Mock<IApplicationEnvironment>();
            applicationEnvironment.Setup(a => a.ApplicationName).Returns("TestApplication");

            var localizedString = new LocalizedString("Hello", "Bonjour test");

            var htmlLocalizer = new Mock<IHtmlLocalizer>();
            htmlLocalizer.Setup(h => h["Hello", "test"]).Returns(localizedString);

            var htmlLocalizerFactory = new Mock<IHtmlLocalizerFactory>();
            htmlLocalizerFactory.Setup(
                h => h.Create("TestApplication.example", "TestApplication")).Returns(htmlLocalizer.Object);

            var viewLocalizer = new ViewLocalizer(htmlLocalizerFactory.Object, applicationEnvironment.Object);

            var view = new Mock<IView>();
            view.Setup(v => v.Path).Returns("example");
            var viewContext = new ViewContext();
            viewContext.View = view.Object;

            viewLocalizer.Contextualize(viewContext);

            // Act
            var actualLocalizedString = viewLocalizer["Hello", "test"];

            // Assert
            Assert.Equal(localizedString, actualLocalizedString);
        }
Example #10
0
        private async Task<RazorTextWriter> RenderPageAsync(IRazorPage page,
                                                            ViewContext context,
                                                            bool executeViewStart)
        {
            using (var bufferedWriter = new RazorTextWriter(context.Writer.Encoding))
            {
                // The writer for the body is passed through the ViewContext, allowing things like HtmlHelpers
                // and ViewComponents to reference it.
                var oldWriter = context.Writer;
                context.Writer = bufferedWriter;
                try
                {
                    if (executeViewStart)
                    {
                        // Execute view starts using the same context + writer as the page to render.
                        await RenderViewStartAsync(context);
                    }

                    await RenderPageCoreAsync(page, context);
                    return bufferedWriter;
                }
                finally
                {
                    context.Writer = oldWriter;
                }
            }
        }
Example #11
0
        public MvcForm([NotNull] ViewContext viewContext)
        {
            _viewContext = viewContext;

            // Push the new FormContext; GenerateEndForm() does the corresponding pop.
            _viewContext.FormContext = new FormContext();
        }
 private static TempDataResponseProvider Create(ViewContext context, string key)
 {
     if (context.TempData == null) return Empty();
     if (!context.TempData.ContainsKey(key)) return Empty();
     var bucket = context.TempData[key] as IEnumerable<IServerResponse>;
     if (bucket == null || !bucket.Any()) return Empty();
     return new TempDataResponseProvider(bucket);
 }
        private string GetValue(ViewContext viewContext, ModelExpression modelExpression)
        {
            string value = base.GetValue(viewContext, modelExpression);

              if (string.IsNullOrEmpty(value))
            return false.ToString().ToLower();

              return value.ToLower();
        }
        private TagBuilder GenerateInput(ViewContext viewContext, ModelExpression modelExpression)
        {
            TagBuilder tb = new TagBuilder("input");

              tb.Attributes.Add("name", this.GetIdentity(modelExpression));
              tb.Attributes.Add("type", "hidden");
              tb.Attributes.Add("value", this.GetValue(viewContext, modelExpression));
              return tb;
        }
Example #15
0
        /// <summary>
        /// Initializes a new instance of <see cref="MvcForm"/>.
        /// </summary>
        /// <param name="viewContext">The <see cref="ViewContext"/>.</param>
        public MvcForm(ViewContext viewContext)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException(nameof(viewContext));
            }

            _viewContext = viewContext;
        }
Example #16
0
 public DisplayHelper(
     IDisplayManager displayManager,
     IShapeFactory shapeFactory,
     ViewContext viewContext)
 {
     _displayManager = displayManager;
     _shapeFactory = shapeFactory;
     ViewContext = viewContext;
 }
Example #17
0
        public Task RenderAsync(ViewContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return Task.FromResult(0);
        }
        public void Contextualize(ViewContext viewContext)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException(nameof(viewContext));
            }

            _viewContext = viewContext;
        }
Example #19
0
        public string GetLayoutName(ViewContext viewContext)
        {
            ISiteSettings site = siteResolver.Resolve();
            if (site == null) return options.DefaultLayout;

            string layout = options.DefaultLayout.Replace(".cshtml", string.Empty); // "Default_Layout"

            // resolve tenant specific layout file name
            
            if (options.SelectionMode == LayoutSelectionMode.Convention) 
            {
                // with this mode layouts are not shown in a dropdown list in site settings
                // so the layout cannot be changed from the UI
                // use a convention like Site1Layout.cshtml Site2Layout.cshtml
                // based on siteid
                layout = string.Format(CultureInfo.InvariantCulture, 
                    options.ConventionFormat, 
                    site.SiteId.ToInvariantString());
            }
            else
            {
                // LayoutSelectionMode.Browsing -- this is the default
                // in this mode a dropdown list of available layouts is shown
                // and the layout can be chosen from the UI
                // the list is filtered per tenant using file naming conventions
                // where the SiteID is part of the filename format
                // ie you could name files like this:
                // Site1_dark_Layout.cshtml
                // Site1_light_Layout.cshtml
                // Site2_supercool_Layout.cshtml
                // Site2_autumn_Layout.cshtml
                // ...
                
                if (site.Layout.Length > 0)
                {
                    layout = site.Layout.Replace(".cshtml", string.Empty);
                }
                
            }
            
            // in all cases we need to determine of the layout file exists
            // and if not log something and fallback to a known layout file

            var layoutPageResult = viewEngine.FindPage(viewContext, layout);
            if (layoutPageResult.Page == null)
            {
                log.LogError("could not find the layout " + layout);

                return options.DefaultLayout.Replace(".cshtml", string.Empty);
            }
            
            log.LogDebug("using the layout " + layout);
            return layout;
            

                
        }
 public void Contextualize(ViewContext viewContext)
 {
     var baseName = viewContext.View.Path.Replace('/', '.').Replace('\\', '.');
     if (baseName.StartsWith("."))
     {
         baseName = baseName.Substring(1);
     }
     baseName = _appName + "." + baseName;
     _localizer = _localizerFactory.Create(baseName, _appName);
 }
        private TagBuilder GenerateIndicator(ViewContext viewContext, ModelExpression modelExpression)
        {
            TagBuilder tb = new TagBuilder("span");

              if (this.GetValue(viewContext, modelExpression) == true.ToString().ToLower())
            tb.Attributes.Add("class", "indicator checked");

              else tb.Attributes.Add("class", "indicator");

              return tb;
        }
Example #22
0
 protected BasePageHelper(ViewContext viewContext)
 {
     //_rootViewContext = viewContext;
     //while (_rootViewContext.IsChildAction)
     //{
     //    _rootViewContext = _rootViewContext.ParentActionViewContext;
     //}
     //_rootTempData = _rootViewContext.TempData;
     _rootViewContext = viewContext;
     _rootTempData = _rootViewContext.TempData;
 }
Example #23
0
        public async Task<IHtmlContent> DisplayAsync(object shape)
        {
            var viewContext = new ViewContext
            {
                HttpContext = _httpContextAccessor.HttpContext,
            };

            var display = _displayHelperFactory.CreateHelper(viewContext);

            return (await ((DisplayHelper)display).ShapeExecuteAsync(shape));
        }
Example #24
0
        public string Display(object shape)
        {
            var viewContext = new ViewContext
            {
                HttpContext = _httpContextAccessor.HttpContext,
            };

            var display = _displayHelperFactory.CreateHelper(viewContext);

            return ((DisplayHelper)display).ShapeExecute(shape).ToString();
        }
 public static void AfterView(
     this DiagnosticSource diagnosticSource,
     IView view,
     ViewContext viewContext)
 {
     if (diagnosticSource.IsEnabled("Microsoft.AspNet.Mvc.AfterView"))
     {
         diagnosticSource.Write(
             "Microsoft.AspNet.Mvc.AfterView",
             new { view = view, viewContext = viewContext, });
     }
 }
Example #26
0
        protected string GetValue(ViewContext viewContext, ModelExpression modelExpression, Localization localization = null)
        {
            ModelStateEntry modelState;

              if (viewContext.ModelState.TryGetValue(this.GetIdentity(modelExpression, localization), out modelState) && !string.IsNullOrEmpty(modelState.AttemptedValue))
            return modelState.AttemptedValue;

              if (localization != null)
            return localization.Value;

              return modelExpression.Model == null ? null : modelExpression.Model.ToString();
        }
 public override TagBuilder GenerateAntiForgery(ViewContext viewContext)
 {
     return new TagBuilder("input", new CommonTestEncoder())
     {
         Attributes =
         {
             { "name", "__RequestVerificationToken" },
             { "type", "hidden" },
             { "value", "olJlUDjrouRNWLen4tQJhauj1Z1rrvnb3QD65cmQU1Ykqi6S4" }, // 50 chars of a token.
         },
     };
 }
Example #28
0
 public TemplateRenderer(
     [NotNull] IViewEngine viewEngine,
     [NotNull] ViewContext viewContext,
     [NotNull] ViewDataDictionary viewData,
     string templateName,
     bool readOnly)
 {
     _viewEngine = viewEngine;
     _viewContext = viewContext;
     _viewData = viewData;
     _templateName = templateName;
     _readOnly = readOnly;
 }
Example #29
0
        public override HtmlString GenerateAntiforgery(ViewContext viewContext)
        {
            var tagBuilder = new TagBuilder("input", new CommonTestEncoder())
            {
                Attributes =
                {
                    { "name", "__RequestVerificationToken" },
                    { "type", "hidden" },
                    { "value", "olJlUDjrouRNWLen4tQJhauj1Z1rrvnb3QD65cmQU1Ykqi6S4" }, // 50 chars of a token.
                },
            };

            return tagBuilder.ToHtmlString(TagRenderMode.SelfClosing);
        }
Example #30
0
        /// <inheritdoc />
        public virtual async Task RenderAsync(ViewContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            _pageExecutionFeature = context.HttpContext.Features.Get<IPageExecutionListenerFeature>();

            // Partials don't execute _ViewStart pages, but may execute Layout pages if the Layout property
            // is explicitly specified in the page.
            var bodyWriter = await RenderPageAsync(RazorPage, context, executeViewStart: !IsPartial);
            await RenderLayoutAsync(context, bodyWriter);
        }