public override void Render(TextWriter writer) { if (Context.Site != null) { string vrKey = Context.Site.Name + ViewPath; //This cache is cleared on publish by resource pipeline //cache is used to avoid expensive check for path on every request. var newViewPath = HttpRuntime.Cache.Get(vrKey); if (newViewPath == null) { newViewPath = ViewPath; string filePath = ViewPath.Replace(@"Views/", @"Themes/" + Context.Site.Name + @"/Views"); if (HostingEnvironment.VirtualPathProvider.FileExists(filePath)) { newViewPath = filePath; } HttpRuntime.Cache.Insert(vrKey, newViewPath); } ViewPath = newViewPath.ToString(); } base.Render(writer); }
public void OnProvidersExecuting(ActionDescriptorProviderContext context) { var newContext = new ActionDescriptorProviderContext(); _pageActionDescriptorProvider.OnProvidersExecuting(newContext); _pageActionDescriptorProvider.OnProvidersExecuted(newContext); var feature = new ViewsFeature(); _applicationPartManager.PopulateFeature(feature); var lookup = new Dictionary <string, CompiledViewDescriptor>(feature.ViewDescriptors.Count, StringComparer.Ordinal); foreach (var viewDescriptor in feature.ViewDescriptors) { // View ordering has precedence semantics, a view with a higher precedence was not // already added to the list. lookup.TryAdd(ViewPath.NormalizePath(viewDescriptor.RelativePath), viewDescriptor); } foreach (var item in newContext.Results) { var pageActionDescriptor = (PageActionDescriptor)item; if (!lookup.TryGetValue(pageActionDescriptor.RelativePath, out var compiledViewDescriptor)) { throw new InvalidOperationException($"A descriptor for '{pageActionDescriptor.RelativePath}' was not found."); } var compiledPageActionDescriptor = _compiledPageActionDescriptorFactory.CreateCompiledDescriptor( pageActionDescriptor, compiledViewDescriptor); context.Results.Add(compiledPageActionDescriptor); } }
public void Load(string viewFullPath, string viewFilesRootFullPath, string viewContent) { string viewPathRelativeToViewRoot = viewFullPath.Substring(viewFilesRootFullPath.Length) .Replace(@"\", "/"); ViewPath = Constants.ViewFilesRoot + viewPathRelativeToViewRoot; // --------------- if (!ViewPath.EndsWith(Constants.ViewFileExtension)) { throw new ViewExtensionsException( string.Format("{0} does not end with {1}", viewFullPath, Constants.ViewFileExtension)); } Url = UrlHelpers.TrimTrailingIndex(viewPathRelativeToViewRoot .Substring(0, viewPathRelativeToViewRoot.Length - Constants.ViewFileExtension.Length)); // --------------- Title = ViewBagPageItem(@"Title", viewContent) ?? ""; // If no key can be found on the page, use url instead. Key = ViewBagPageItem(@"Key", viewContent) ?? Url; Description = ViewBagPageItem(@"Description", viewContent) ?? ""; VersionNameRegex = ViewBagPageItem(@"VersionNameRegex", viewContent) ?? ""; string orderString = ViewBagPageItem(@"Order", viewContent) ?? "1000"; Order = int.Parse(orderString); }
public void SetUp() { path = new ViewPath { ViewName = "something" }; var render = new WebFormView(path.ViewName); var container = new Container(x => { x.For <IActionBehavior>().Use(new ObjectDefInstance(render.As <IContainerModel>().ToObjectDef(DiagnosticLevel.None))); x.For <IWebFormsControlBuilder>().Use <WebFormsControlBuilder>(); x.For <IWebFormRenderer>().Use <WebFormRenderer>(); x.For <HttpContextBase>().Use(() => new FakeHttpContext()); x.For <IOutputWriter>().Use <OutputWriter>(); x.For <IFubuRequest>().Use <InMemoryFubuRequest>(); x.For <IPageActivator>().Use <PageActivator>(); x.For <IPageActivationRules>().Use <PageActivationRuleCache>(); x.For <IServiceLocator>().Use <StructureMapServiceLocator>(); x.For <IHttpWriter>().Use(new NulloHttpWriter()); x.For <IFileSystem>().Use <FileSystem>(); }); behavior = container.GetInstance <IActionBehavior>(); }
public FileSystemRazorProjectItem(string key, string filePath) { if (Path.GetExtension(key) != ".cshtml") { throw new ArgumentException(nameof(key)); } Key = ViewPath.NormalizePath(key); //TODO Windows以外の環境への対応 File = new FileInfo(filePath); if (Path.IsPathRooted(filePath)) { BasePath = NormalizeAndEnsureValidPath(File.DirectoryName); filePath = NormalizeAndEnsureValidPath(File.Name); } else { var relativePath = NormalizeAndEnsureValidPath(filePath); var idx = File.FullName.LastIndexOf(filePath); BasePath = NormalizeAndEnsureValidPath(File.FullName.Substring(0, File.FullName.LastIndexOf(filePath)).TrimEnd(Path.DirectorySeparatorChar)); FilePath = relativePath; } }
/// <summary> /// Get the NodeLabel for this WatchViewModel and any children. /// Each level of children will be indented by 2 spaces. /// </summary> /// <param name="depth">The number of levels of indentation.</param> /// <param name="includeKey">If true the list or dictionary key will be included in the string.</param> /// <returns></returns> public string GetNodeLabelTree(int depth = 0, bool includeKey = false) { string indent = new string(' ', depth * 2); var str = new StringBuilder(); if (depth != 0) { str.AppendLine(); } str.Append(indent); if (Children.Count == 0) { if (includeKey) { str.Append($"{ViewPath.Trim()}: "); } str.Append(NodeLabel); } else if (NodeLabel == WatchViewModel.DICTIONARY) { IEnumerable <string> labels = Children.Select(x => x.GetNodeLabelTree(depth + 1, true)); str.Append("{"); str.AppendLine(string.Join(",", labels)); str.Append($"{indent}}}"); } else { IEnumerable <string> labels = Children.Select(x => x.GetNodeLabelTree(depth + 1, false)); str.Append("["); str.AppendLine(string.Join(",", labels)); str.Append($"{indent}]"); } return(str.ToString()); }
public void PopulateFeature(IEnumerable <ApplicationPart> parts, ViewsFeature feature) { //feature.ViewDescriptors.Add(new CompiledViewDescriptor() //{ // ExpirationTokens = Array.Empty<IChangeToken>(), // RelativePath = ViewPath.NormalizePath("/_ViewStart" + RazorViewEngine.ViewExtension), // ViewAttribute = new RazorViewAttribute("/_ViewStart" + RazorViewEngine.ViewExtension, typeof(ThemeViewStart)), // IsPrecompiled = true, //}); //feature.ViewDescriptors.Add(new CompiledViewDescriptor() //{ // ExpirationTokens = Array.Empty<IChangeToken>(), // RelativePath = ViewPath.NormalizePath("/Views/Shared/_Layout" + RazorViewEngine.ViewExtension), // ViewAttribute = new RazorViewAttribute("/Views/Shared/_Layout" + RazorViewEngine.ViewExtension, typeof(ThemeLayout)), // IsPrecompiled = true, //}); feature.ViewDescriptors.Add(new CompiledViewDescriptor() { ExpirationTokens = Array.Empty <IChangeToken>(), RelativePath = ViewPath.NormalizePath("/_ViewStart" + RazorViewEngine.ViewExtension), ViewAttribute = new RazorViewAttribute("/_ViewStart" + RazorViewEngine.ViewExtension, typeof(ThemeLayout2)), IsPrecompiled = true, }); }
public void SetUp() { path = new ViewPath { ViewName = "something" }; var render = new WebFormView(path.ViewName); var container = new Container(x => { x.For<IActionBehavior>().Use(new ObjectDefInstance(render.As<IContainerModel>().ToObjectDef(DiagnosticLevel.None))); x.For<IWebFormsControlBuilder>().Use<WebFormsControlBuilder>(); x.For<IWebFormRenderer>().Use<WebFormRenderer>(); x.For<HttpContextBase>().Use(() => new FakeHttpContext()); x.For<IOutputWriter>().Use<OutputWriter>(); x.For<IFubuRequest>().Use<InMemoryFubuRequest>(); x.For<IPageActivator>().Use<PageActivator>(); x.For<IPageActivationRules>().Use<PageActivationRuleCache>(); x.For<IServiceLocator>().Use<StructureMapServiceLocator>(); x.For<IHttpWriter>().Use(new NulloHttpWriter()); x.For<IFileSystem>().Use<FileSystem>(); }); behavior = container.GetInstance<IActionBehavior>(); }
/// <summary> /// Creates a new <see cref="CompiledViewDescriptor"/>. At least one of <paramref name="attribute"/> or /// <paramref name="item"/> must be non-<c>null</c>. /// </summary> /// <param name="item">The <see cref="RazorCompiledItem"/>.</param> /// <param name="attribute">The <see cref="RazorViewAttribute"/>.</param> public CompiledViewDescriptor(RazorCompiledItem item, RazorViewAttribute attribute) { if (item == null && attribute == null) { // We require at least one of these to be specified. throw new ArgumentException(Resources.FormatCompiledViewDescriptor_NoData(nameof(item), nameof(attribute))); } Item = item; // // For now we expect that MVC views and pages will still have either: // [RazorView(...)] or // [RazorPage(...)]. // // In theory we could look at the 'Item.Kind' to determine what kind of thing we're dealing // with, but for compat reasons we're basing it on ViewAttribute since that's what 2.0 had. ViewAttribute = attribute; // We don't have access to the file provider here so we can't check if the files // even exist or what their checksums are. For now leave this empty, it will be updated // later. ExpirationTokens = Array.Empty <IChangeToken>(); RelativePath = ViewPath.NormalizePath(item?.Identifier ?? attribute.Path); IsPrecompiled = true; }
public void NormalizePath_AppendsLeadingSlash(string input) { // Act var normalizedPath = ViewPath.NormalizePath(input); // Assert Assert.Equal("/Views/Home/Index.cshtml", normalizedPath); }
public RenderFubuWebFormView(ViewPath path, IWebFormsControlBuilder builder, IWebFormRenderer renderer, IPageActivator activator) : base(PartialBehavior.Executes) { _path = path; _builder = builder; _renderer = renderer; _activator = activator; }
protected override void beforeEach() { view = new ViewPath(); Services.Inject(view); engine = new StubViewEngine(); Services.Inject <IViewEngine <IFubuView> >(engine); ClassUnderTest.Invoke(); }
/// <summary> /// Creates a new <see cref="CompiledViewDescriptor"/>. /// </summary> /// <param name="item">The <see cref="RazorCompiledItem"/>.</param> public CompiledViewDescriptor(RazorCompiledItem item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } Item = item; RelativePath = ViewPath.NormalizePath(item.Identifier); }
public StringRazorProjectItem(string path, string cshtml) { if (Path.GetExtension(path) != ".cshtml") { throw new ArgumentException(nameof(path)); } FilePath = ViewPath.NormalizePath(path); Key = FilePath; Content = cshtml; }
/// <summary> /// Creates a new <see cref="CompiledViewDescriptor"/>. /// </summary> /// <param name="item">The <see cref="RazorCompiledItem"/>.</param> public CompiledViewDescriptor(RazorCompiledItem item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } Item = item; ExpirationTokens = Array.Empty <IChangeToken>(); RelativePath = ViewPath.NormalizePath(item.Identifier); }
public override int GetHashCode() { unchecked { var hashCode = (ViewPath != null ? ViewPath.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Url != null ? Url.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (LanguageCultureCode != null ? LanguageCultureCode.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Area != null ? Area.GetHashCode() : 0); return(hashCode); } }
public bool Equals(ViewPath other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(Equals(other.ViewName, ViewName)); }
public void RenderView(ViewPath viewPath, Action <T> configureView) { Control control = _builder.LoadControlFromVirtualPath(viewPath.ViewName, typeof(T)); var view = control as T; if (view != null) { configureView(view); } _renderer.RenderControl(control); }
public EmbeddedRazorProjectItem(string path, Assembly assembly, string resourceKey) { if (Path.GetExtension(path) != ".cshtml") { throw new ArgumentException(nameof(path)); } FilePath = ViewPath.NormalizePath(path); Key = FilePath; Assembly = assembly; ResourceKey = resourceKey; Exists = Assembly.GetManifestResourceNames().Any(f => f == ResourceKey); }
// Token: 0x06000184 RID: 388 RVA: 0x000074C0 File Offset: 0x000056C0 private string GetNormalizedPath(string relativePath) { if (relativePath.Length == 0) { return(relativePath); } string text; if (!this._normalizedPathCache.TryGetValue(relativePath, out text)) { text = ViewPath.NormalizePath(relativePath); this._normalizedPathCache[relativePath] = text; } return(text); }
private string GetNormalizedPath(string relativePath) { Debug.Assert(relativePath != null); if (relativePath.Length == 0) { return(relativePath); } if (!_normalizedPathCache.TryGetValue(relativePath, out var normalizedPath)) { normalizedPath = ViewPath.NormalizePath(relativePath); _normalizedPathCache[relativePath] = normalizedPath; } return(normalizedPath); }
public void ThrowIfInvalid() { Recipients.ThrowIfNullOrEmpty(nameof(Recipients)); Subject.ThrowIfNullOrEmpty(nameof(Subject)); ViewPath.ThrowIfNullOrEmpty(nameof(ViewPath)); foreach (string recipient in Recipients) { if (!StringHelpers.IsValidEmail(recipient)) { throw new InvalidOperationException($"Email '{recipient}' is invalid"); } } if (Cc.Any()) { foreach (string cc in Cc) { if (!StringHelpers.IsValidEmail(cc)) { throw new InvalidOperationException($"Email '{cc}' is invalid"); } } Cc = Cc.Where(x => !Recipients.Contains(x)).ToArray(); } if (HiddenCc.Any()) { foreach (string cc in HiddenCc) { if (!StringHelpers.IsValidEmail(cc)) { throw new InvalidOperationException($"Email '{cc}' is invalid"); } } HiddenCc = HiddenCc .Where(x => !Cc.Contains(x)) .Where(x => !Recipients.Contains(x)).ToArray(); } }
public void SetUp() { path = new ViewPath { ViewName = "something" }; var render = new WebFormView(path.ViewName); var container = new Container(x => { x.For <IActionBehavior>().Use(new ObjectDefInstance(render.ToObjectDef())); x.For <IWebFormsControlBuilder>().Use <WebFormsControlBuilder>(); x.For <IWebFormRenderer>().Use <WebFormRenderer>(); x.For <IOutputWriter>().Use <HttpResponseOutputWriter>(); x.For <IFubuRequest>().Use <InMemoryFubuRequest>(); x.For <IViewActivator>().Use <NulloViewActivator>(); }); behavior = container.GetInstance <IActionBehavior>(); }
public override async Task ExecuteAsync(HttpContext context) { var fullpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ViewPath.TrimStart('/', '\\')); if (File.Exists(fullpath)) { var razor = File.ReadAllText(fullpath, System.Text.Encoding.UTF8); string html = Razor.Parse(razor, this.Model); var response = context.Response; response.StatusCode = 200; response.ContentType = "text/html; charset=utf-8"; response.AddHeader("Content-Length", html.Length.ToString()); await response.WriteAsync(html); } else { await(new Http404NotFoundResult()).ExecuteAsync(context); } }
/// <inheritdoc /> public void PopulateFeature(IEnumerable <ApplicationPart> parts, ViewsFeature feature) { foreach (var assemblyPart in parts.OfType <AssemblyPart>()) { var viewAttributes = GetViewAttributes(assemblyPart); foreach (var attribute in viewAttributes) { var relativePath = ViewPath.NormalizePath(attribute.Path); var viewDescriptor = new CompiledViewDescriptor { ExpirationTokens = Array.Empty <IChangeToken>(), RelativePath = relativePath, ViewAttribute = attribute, IsPrecompiled = true, }; feature.ViewDescriptors.Add(viewDescriptor); } } }
public void SetUp() { path = new ViewPath { ViewName = "something" }; var render = new WebFormView(path.ViewName); var container = new Container(x => { x.For <IActionBehavior>().Use(new ObjectDefInstance(render.As <IContainerModel>().ToObjectDef())); x.For <IWebFormsControlBuilder>().Use <WebFormsControlBuilder>(); x.For <IWebFormRenderer>().Use <WebFormRenderer>(); x.For <IOutputWriter>().Use <HttpResponseOutputWriter>(); x.For <IFubuRequest>().Use <InMemoryFubuRequest>(); x.For <IPageActivator>().Use <PageActivator>(); x.For <IPageActivationRules>().Use <PageActivationRuleCache>(); x.For <IServiceLocator>().Use <StructureMapServiceLocator>(); }); behavior = container.GetInstance <IActionBehavior>(); }
public void SetUp() { path = new ViewPath { ViewName = "something" }; var render = new WebFormView(path.ViewName); var container = new Container(x => { x.For<IActionBehavior>().Use(new ObjectDefInstance(render.As<IContainerModel>().ToObjectDef())); x.For<IWebFormsControlBuilder>().Use<WebFormsControlBuilder>(); x.For<IWebFormRenderer>().Use<WebFormRenderer>(); x.For<IOutputWriter>().Use<HttpResponseOutputWriter>(); x.For<IFubuRequest>().Use<InMemoryFubuRequest>(); x.For<IPageActivator>().Use<PageActivator>(); x.For<IPageActivationRules>().Use<PageActivationRuleCache>(); x.For<IServiceLocator>().Use<StructureMapServiceLocator>(); }); behavior = container.GetInstance<IActionBehavior>(); }
public void PopulateFeature(IEnumerable <ApplicationPart> parts, ViewsFeature feature) { if (!parts.Where(p => p.Name == _hostingEnvironment.ApplicationName).Any()) { return; } feature.ViewDescriptors.Add(new CompiledViewDescriptor() { ExpirationTokens = Array.Empty <IChangeToken>(), RelativePath = ViewPath.NormalizePath("/_ViewStart" + RazorViewEngine.ViewExtension), ViewAttribute = new RazorViewAttribute("/_ViewStart" + RazorViewEngine.ViewExtension, typeof(ThemeViewStart)), IsPrecompiled = true, }); feature.ViewDescriptors.Add(new CompiledViewDescriptor() { ExpirationTokens = Array.Empty <IChangeToken>(), RelativePath = ViewPath.NormalizePath(ThemeLayoutFileName), ViewAttribute = new RazorViewAttribute(ThemeLayoutFileName, typeof(ThemeLayout)), IsPrecompiled = true, }); }
public bool Equals(ViewPath other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.ViewName, ViewName); }
/// <summary> /// /// </summary> /// <param name="project"></param> /// <param name="key"></param> /// <param name="model"></param> /// <param name="isMainPage"></param> /// <returns></returns> public async Task <string> CompileRenderAsync( DynamicRazorProject project, string key, object model, bool isMainPage = true, ActionDescriptor actionDescriptor = null) { if (project == null) { throw new ArgumentNullException(nameof(project)); } var templateEngine = new MvcRazorTemplateEngine(_engine, project); var httpContext = new CustomHttpContext(_httpContextAccessor?.HttpContext); httpContext.RequestServices = _serviceProvider; _razorEngineOptions.Value.ViewLocationFormats.Insert(0, "/{0}.cshtml"); var projectID = project.GetHashCode().ToString(); var viewCompilerProvider = new DynamicRazorViewCompilerProvider( _applicationPartManager, templateEngine, _razorViewEngineFileProviderAccessor, _cSharpCompiler, _projectCacheProvider.GetCache(projectID), _razorEngineOptions, _loggerFactory); var engine = new RazorViewEngine( new DefaultRazorPageFactoryProvider(viewCompilerProvider), _razorPageActivator, _htmlEncoder, _razorEngineOptions, project, _loggerFactory, _diagnosticSource); var viewResult = engine.GetView(null, ViewPath.NormalizePath(key), isMainPage); if (!viewResult.Success) { throw new InvalidOperationException("View Not Found"); } var actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor ?? new ActionDescriptor()); var viewContext = new ViewContext( actionContext, viewResult.View, new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()), _tempDataDictionaryFactory.GetTempData(httpContext), TextWriter.Null, _mvcViewOptions.Value.HtmlHelperOptions); viewContext.ViewData.Model = model; var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { viewContext.Writer = sw; await viewContext.View.RenderAsync(viewContext); } return(sb.ToString()); }
/// <inheritdoc /> public void PopulateFeature(IEnumerable <ApplicationPart> parts, ViewsFeature feature) { foreach (var assemblyPart in parts.OfType <AssemblyPart>()) { var viewAttributes = GetViewAttributes(assemblyPart) .Select(attribute => (Attribute: attribute, RelativePath: ViewPath.NormalizePath(attribute.Path))); var duplicates = viewAttributes.GroupBy(a => a.RelativePath, StringComparer.OrdinalIgnoreCase) .FirstOrDefault(g => g.Count() > 1); if (duplicates != null) { // Ensure parts do not specify views with differing cases. This is not supported // at runtime and we should flag at as such for precompiled views. var viewsDifferingInCase = string.Join(Environment.NewLine, duplicates.Select(d => d.RelativePath)); var message = string.Join( Environment.NewLine, Resources.RazorViewCompiler_ViewPathsDifferOnlyInCase, viewsDifferingInCase); throw new InvalidOperationException(message); } foreach (var(attribute, relativePath) in viewAttributes) { var viewDescriptor = new CompiledViewDescriptor { ExpirationTokens = Array.Empty <IChangeToken>(), RelativePath = relativePath, ViewAttribute = attribute, }; feature.ViewDescriptors.Add(viewDescriptor); } } }
public RenderFubuWebFormView(WebFormViewEngine <IFubuView> engine, IFubuRequest request, ViewPath view, IViewActivator activator) : base(engine, request, view, activator) { }
public void RenderView(ViewPath viewPath, Action <IFubuView> configureView) { _viewPath = viewPath; configureView(_view); }