protected override void InitializeParameters() { WebPageBase razorPage = null; try { using (BuildManagerHelper.DisableUrlMetadataCachingScope()) { razorPage = WebPage.CreateInstanceFromVirtualPath(VirtualPath); } var razorFunction = razorPage as RazorFunction; if (razorFunction == null) { throw new InvalidOperationException($"Failed to initialize function from cache. Path: '{VirtualPath}'"); } Parameters = FunctionBasedFunctionProviderHelper.GetParameters(razorFunction, typeof(RazorFunction), VirtualPath); PreventFunctionOutputCaching = razorFunction.PreventFunctionOutputCaching; } finally { (razorPage as IDisposable)?.Dispose(); } }
protected override IFunction InstantiateFunction(string virtualPath, string @namespace, string name) { WebPageBase razorPage; using (BuildManagerHelper.DisableUrlMetadataCachingScope()) { razorPage = WebPage.CreateInstanceFromVirtualPath(virtualPath); } if (!(razorPage is RazorFunction razorFunction)) { Log.LogWarning(nameof(RazorFunctionProvider), $"Razor page '{virtualPath}' does not inherit from the base class for razor functions '{typeof(RazorFunction).FullName}' and will be ignored"); return(null); } try { var functionParameters = FunctionBasedFunctionProviderHelper.GetParameters( razorFunction, typeof(RazorFunction), virtualPath); return(new RazorBasedFunction(@namespace, name, razorFunction.FunctionDescription, functionParameters, razorFunction.FunctionReturnType, virtualPath, this)); } finally { razorFunction.Dispose(); } }
public void CreateInstanceFromVirtualPathTest() { var vpath = "~/hello/test.cshtml"; var page = CreateMockPageWithPostContext().Object; var result = WebPage.CreateInstanceFromVirtualPath(vpath, (path, type) => { return(page); }); Assert.AreEqual(page, result); Assert.AreEqual(vpath, result.VirtualPath); }
/// <summary> /// 渲染一个Razor视图模板 /// </summary> /// <param name="context">HttpContextBase实例引用</param> /// <param name="pageVirtualPath">Razor视图的路径</param> /// <param name="model">要渲染到视图上的数据对象</param> /// <returns>渲染后的HTML代码</returns> protected virtual string RenderPage(HttpContextBase context, string pageVirtualPath, object model) { // 扩展点:如果需要实现页面替换逻辑,例如个性化页面覆盖标准产品页面,可以重写这个方法 WebPageBase page = WebPage.CreateInstanceFromVirtualPath(pageVirtualPath); StringWriter output = new StringWriter(); WebPageContext pageContext = new WebPageContext(context, null, model); page.ExecutePageHierarchy(pageContext, output); return(output.ToString()); }
public void CreatePageFromVirtualPathAssignsVirtualPathFactory() { // Arrange var path = "~/index.cshtml"; var page = Utils.CreatePage(null, path); var factory = new HashVirtualPathFactory(page); // Act var result = WebPage.CreateInstanceFromVirtualPath(path, factory); // Assert Assert.Equal(page, result); Assert.Equal(page.VirtualPathFactory, factory); Assert.Equal(page.VirtualPath, path); }
protected override void InitializeParameters() { WebPageBase razorPage; using (BuildManagerHelper.DisableUrlMetadataCachingScope()) { razorPage = WebPage.CreateInstanceFromVirtualPath(VirtualPath); } if (!(razorPage is RazorFunction)) { throw new InvalidOperationException("Failed to initialize function from cache. Path: '{0}'".FormatWith(VirtualPath)); } Parameters = FunctionBasedFunctionProviderHelper.GetParameters(razorPage as RazorFunction, typeof(RazorFunction), VirtualPath); }
private bool CompileAndValidate(string file, string fileContent) { string tempMarkupFile = GetTempFilePath(file); try { File.WriteAllText(tempMarkupFile, fileContent); string tempFileVirtualPath = "~" + PathUtil.GetWebsitePath(tempMarkupFile); WebPageBase webPageBase; try { webPageBase = WebPage.CreateInstanceFromVirtualPath(tempFileVirtualPath); } catch (Exception ex) { Log.LogWarning(LogTitle, "Failed to compile CSHTML file"); Log.LogWarning(LogTitle, ex); Exception compilationException = (ex is TargetInvocationException) ? ex.InnerException : ex; // Replacing file path and temp file name from error message as it is irrelevant to the user string markupFileName = Path.GetFileName(file); string errorMessage = compilationException.Message; if (errorMessage.StartsWith(tempMarkupFile, StringComparison.OrdinalIgnoreCase)) { errorMessage = markupFileName + errorMessage.Substring(tempMarkupFile.Length); } ShowWarning(GetText("EditRazorFunctionWorkflow.Validation.CompilationFailed") .FormatWith(errorMessage)); return(false); } return(Validate(webPageBase)); } finally { // Deleting temporary file File.Delete(tempMarkupFile); } }
public void ExtensionNotSupportedTest() { // Tests that calling RenderPage on an unsupported extension returns a new simpler error message // instead of the full error about build providers in system.web.dll. var vpath = "~/hello/world.txt"; var ext = ".txt"; var compilationUtilThrowingBuildManager = new CompilationUtil(); var otherExceptionBuildManager = new Mock <IVirtualPathFactory>(); var msg = "The file \"~/hello/world.txt\" could not be rendered, because it does not exist or is not a valid page."; otherExceptionBuildManager.Setup(c => c.CreateInstance(It.IsAny <string>())).Throws(new HttpException(msg)); Assert.Throws <HttpException>(() => WebPage.CreateInstanceFromVirtualPath(vpath, new VirtualPathFactoryManager(compilationUtilThrowingBuildManager)), String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, ext, vpath)); // Test that other error messages are thrown unmodified. Assert.Throws <HttpException>(() => WebPage.CreateInstanceFromVirtualPath(vpath, otherExceptionBuildManager.Object), msg); }
private bool ValidateMarkup(string virtualPath, string content, out EntityToken newEntityToken) { newEntityToken = null; string filePath = PathUtil.Resolve(virtualPath); string fileName = Path.GetFileName(filePath); string tempFileName = RazorPageTemplateProvider.TempFilePrefix + fileName; string tempFileVirtualPath = virtualPath.Substring(0, virtualPath.Length - fileName.Length) + tempFileName; string tempFile = Path.Combine(Path.GetDirectoryName(filePath), tempFileName); try { C1File.WriteAllText(tempFile, content); WebPageBase webPageBase; try { webPageBase = WebPage.CreateInstanceFromVirtualPath(tempFileVirtualPath); } catch (Exception ex) { Log.LogWarning(LogTitle, "Compilation failed while validating changes to '{0}'", virtualPath); Log.LogWarning(LogTitle, ex); string message = ex.Message; if (message.StartsWith(tempFile, StringComparison.OrdinalIgnoreCase)) { message = fileName + message.Substring(tempFile.Length); } ShowWarning(GetText("EditTemplate.Validation.CompilationFailed") .FormatWith(message)); return(false); } if (!(webPageBase is RazorPageTemplate)) { if (IsPageTemplate) { var templateDescriptor = GetPageTemplateDescriptor(); if (templateDescriptor.IsValid) { ShowWarning(GetText("EditTemplate.Validation.IncorrectBaseClass") .FormatWith(typeof(RazorPageTemplate).FullName)); return(false); } newEntityToken = new SharedCodeFileEntityToken(virtualPath); return(true); } return(true); } Guid templateId; var pageTemplate = webPageBase as RazorPageTemplate; pageTemplate.Configure(); try { templateId = pageTemplate.TemplateId; } catch (Exception ex) { ShowPropertyError("TemplateId", ex); return(false); } try { string templateTitle = pageTemplate.TemplateTitle; } catch (Exception ex) { ShowPropertyError("TemplateTitle", ex); return(false); } if (!IsPageTemplate) { newEntityToken = new PageTemplateEntityToken(templateId); return(true); } var pageTemplateDescriptor = GetPageTemplateDescriptor(); if (pageTemplateDescriptor.IsValid) { // Forbidding to change template id from this workflow in order to avoid mistakes if (templateId != pageTemplateDescriptor.Id) { ShowWarning(GetText("EditTemplate.Validation.TemplateIdChanged").FormatWith(pageTemplateDescriptor.Id)); return(false); } } else { newEntityToken = new PageTemplateEntityToken(templateId); } } finally { C1File.Delete(tempFile); } return(true); }