public RazorViewEngineFixture() { var environment = new DefaultNancyEnvironment(); environment.Tracing( enabled: true, displayErrorTraces: true); this.configuration = A.Fake <IRazorConfiguration>(); this.engine = new RazorViewEngine(this.configuration, environment, new AppDomainAssemblyCatalog()); var cache = A.Fake <IViewCache>(); A.CallTo(() => cache.GetOrAdd(A <ViewLocationResult> .Ignored, A <Func <ViewLocationResult, Func <INancyRazorView> > > .Ignored)) .ReturnsLazily(x => { var result = x.GetArgument <ViewLocationResult>(0); return(x.GetArgument <Func <ViewLocationResult, Func <INancyRazorView> > >(1).Invoke(result)); }); this.renderContext = A.Fake <IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); A.CallTo(() => this.renderContext.LocateView(A <string> .Ignored, A <object> .Ignored)) .ReturnsLazily(x => { var viewName = x.GetArgument <string>(0); return(FindView(viewName)); }); this.rootPathProvider = A.Fake <IRootPathProvider>(); A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, "TestViews")); this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader()); }
/// <summary> /// 创建主题视图引擎。 /// </summary> /// <param name="parameters">创建主题视图引擎所需的参数。</param> /// <returns>视图引擎。</returns> public IViewEngine CreateThemeViewEngine(CreateThemeViewEngineParams parameters) { // /Views/{area}/{controller}/{viewName} // /Views/{partialName} // /Views/"DisplayTemplates/"+{templateName} // /Views/"EditorTemplates/+{templateName} var partialViewLocationFormats = new[] { parameters.VirtualPath + "/Views/{0}.cshtml", }; var areaPartialViewLocationFormats = new[] { parameters.VirtualPath + "/Views/{2}/{1}/{0}.cshtml", }; var viewEngine = new RazorViewEngine { MasterLocationFormats = DisabledFormats, ViewLocationFormats = DisabledFormats, PartialViewLocationFormats = partialViewLocationFormats, AreaMasterLocationFormats = DisabledFormats, AreaViewLocationFormats = DisabledFormats, AreaPartialViewLocationFormats = areaPartialViewLocationFormats, ViewLocationCache = new ThemeViewLocationCache(parameters.VirtualPath), }; return(viewEngine); }
protected void Application_Start() { ViewEngines.Engines.Clear(); IViewEngine razorEngine = new RazorViewEngine() { FileExtensions = new string[] { "cshtml" } }; ViewEngines.Engines.Add(razorEngine); //ViewEngines.Engines.Add(new RazorViewEngine()); DevExpress.XtraReports.Web.WebDocumentViewer.Native.WebDocumentViewerBootstrapper.SessionState = System.Web.SessionState.SessionStateBehavior.Disabled; AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); ModelBinders.Binders.DefaultBinder = new DevExpress.Web.Mvc.DevExpressEditorsBinder(); BundleConfig.RegisterBundles(BundleTable.Bundles); DevExpress.Web.ASPxWebControl.CallbackError += Application_Error; }
public static string RenderPartial(string partialName, object model, string[] viewLocations) { using (var sw = new StringWriter()) { var httpContext = new HttpContextWrapper(HttpContext.Current); var routeData = new RouteData(); routeData.Values.Add("controller", "DummyController"); var controllerContext = new ControllerContext(new RequestContext(httpContext, routeData), new DummyController()); var viewEngine = new RazorViewEngine { PartialViewLocationFormats = viewLocations }; var viewResult = viewEngine.FindPartialView(controllerContext, partialName, false); if (viewResult.View == null) { // TODO: Log lack of view? return(null); } viewResult.View.Render(new ViewContext(controllerContext, viewResult.View, new ViewDataDictionary { Model = model }, new TempDataDictionary(), sw), sw); return(sw.ToString()); } }
public static void Start() { // Clears all previously registered view engines. ViewEngines.Engines.Clear(); // Registers our Razor C# specific view engine. // This can also be registered using dependency injection through the new IDependencyResolver interface. var viewEngine = new RazorViewEngine(); viewEngine.AreaPartialViewLocationFormats = new List <string>( viewEngine.AreaPartialViewLocationFormats.Concat(new string[] { "~/Areas/{2}/Views/{1}/_{0}.cshtml", "~/Areas/{2}/Views/{1}/_{0}.vbhtml", "~/Areas/{2}/Views/Shared/_{0}.cshtml", "~/Areas/{2}/Views/Shared/_{0}.vbhtml" })).ToArray(); viewEngine.PartialViewLocationFormats = new List <string>( viewEngine.PartialViewLocationFormats.Concat(new string[] { "~/Views/{1}/_{0}.cshtml", "~/Views/{1}/_{0}.vbhtml", "~/Views/Shared/_{0}.cshtml", "~/Views/Shared/_{0}.vbhtml" })).ToArray(); ViewEngines.Engines.Add(viewEngine); }
/// <summary> /// 创建模块视图引擎。 /// </summary> /// <param name="parameters">创建模块视图引擎所需的参数。</param> /// <returns>视图引擎。</returns> public IViewEngine CreateModulesViewEngine(CreateModulesViewEngineParams parameters) { var areaFormats = new[] { "~/Core/{2}/Views/{1}/{0}.cshtml", "~/Modules/{2}/Views/{1}/{0}.cshtml", "~/Themes/{2}/Views/{1}/{0}.cshtml", }; var universalFormats = parameters.VirtualPaths .SelectMany(x => new[] { x + "/Views/{0}.cshtml", }) .ToArray(); var viewEngine = new RazorViewEngine { MasterLocationFormats = DisabledFormats, ViewLocationFormats = universalFormats, PartialViewLocationFormats = universalFormats, AreaMasterLocationFormats = DisabledFormats, AreaViewLocationFormats = areaFormats, AreaPartialViewLocationFormats = areaFormats, }; return(viewEngine); }
private static RazorViewEngine CreateViewEngine() { var ret = new RazorViewEngine(); ret.AreaMasterLocationFormats = ret.AreaViewLocationFormats = ret.AreaPartialViewLocationFormats = new[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Branding/Views/Shared/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", }; ret.MasterLocationFormats = ret.ViewLocationFormats = ret.PartialViewLocationFormats = new[] { "~/Branding/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.cshtml", "~/Branding/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.cshtml", }; return(ret); }
protected string ViewToString <T>(string controllerName, string viewPath, T model, bool useCache = false) { try { using (var writer = new StringWriter()) { // Create a new route data var routeData = new RouteData(); routeData.Values.Add("controller", controllerName); // Create fake controller context var fakeControllerContext = new ControllerContext( new HttpContextWrapper( new HttpContext( new HttpRequest(null, "http://google.com", null), new HttpResponse(null))), routeData, new FakeController()); // Create the razor engine var razorViewEngine = new RazorViewEngine(); var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewPath, "", false); // Create view context var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(model), new TempDataDictionary(), writer); // Render view razorViewResult.View.Render(viewContext, writer); return(writer.ToString()); } } catch (Exception ex) { throw; } }
public void CreateController_DummyController_NewControllerViewEnginesHaveAdditinalSearchPaths() { //Arrange var controllerFactory = new FrontendControllerFactory(); controllerFactory.RegisterController(typeof(DummyController).Name, typeof(DummyController)); var viewEngine = new RazorViewEngine(); ViewEngines.Engines.Add(viewEngine); try { //Act var controller = (Controller)controllerFactory.CreateController(new DummyHttpContext().Request.RequestContext, "Dummy"); //Assert var controllerVe = controller.ViewEngineCollection.OfType <RazorViewEngine>().FirstOrDefault(); Assert.IsNotNull(controllerVe, "The newly created controller does not have the expected view engine."); var containerVp = "~/" + FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(DummyController).Assembly); Assert.IsTrue(controllerVe.ViewLocationFormats.Any(v => v.StartsWith(containerVp)), "The newly created controller does not have its container path in the view locations."); } finally { ViewEngines.Engines.Remove(viewEngine); } }
/// <summary> /// Renders the view to string. /// </summary> /// <param name="viewName">Name of the view.</param> /// <param name="viewData">The view data.</param> /// <param name="controller">The controller.</param> /// <param name="additionalData">The additional data.</param> /// <returns></returns> public static string RenderViewToString(string viewName, object viewData, ControllerBase controller, IDictionary <string, object> additionalData) { try { HttpContextBase contextBase = new HttpContextWrapper(HttpContext.Current); TempDataDictionary tempData = new TempDataDictionary(); foreach (var item in additionalData) { tempData[item.Key] = item.Value; } var routeData = new RouteData(); routeData.Values.Add("controller", controller.GetType().Name.Replace("Controller", "")); var controllerContext = new ControllerContext(contextBase, routeData, controller); var razorViewEngine = new RazorViewEngine(); var razorViewResult = razorViewEngine.FindView(controllerContext, viewName, "", false); var writer = new StringWriter(); var viewContext = new ViewContext(controllerContext, razorViewResult.View, new ViewDataDictionary(viewData), tempData, writer); razorViewResult.View.Render(viewContext, writer); return(writer.ToString()); } catch (Exception ex) { ex.ExceptionValueTracker(viewName, viewData, controller, additionalData); } return(string.Empty); }
protected void Application_Start() { ShareOptions.RootPath = Server.MapPath("~"); ViewEngines.Engines.Clear(); var customEngine = new RazorViewEngine(); customEngine.PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml", "~/Views/Partial/{0}.cshtml", "~/Views/Partial/{1}/{0}.cshtml" }; customEngine.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml", "~/Views/Controller/{1}/{0}.cshtml" }; customEngine.MasterLocationFormats = new string[] { "~/Views/Shared/{0}.cshtml", "~/Views/Layout/{0}.cshtml" }; ViewEngines.Engines.Add(customEngine); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); new DatabaseBootstrapper(new Models.TDContext()).Configure(); }
public IViewEngine CreateModulesViewEngine(CreateModulesViewEngineParams parameters) { var areaFormats = new[] { "~/Core/{2}/Views/{1}/{0}.cshtml", "~/Modules/{2}/Views/{1}/{0}.cshtml", "~/Themes/{2}/Views/{1}/{0}.cshtml", }; //Logger.Debug("AreaFormats (module): \r\n\t-{0}", string.Join("\r\n\t-", areaFormats)); var universalFormats = parameters.VirtualPaths .SelectMany(x => new[] { x + "/Views/{0}.cshtml", }) .ToArray(); //Logger.Debug("UniversalFormats (module): \r\n\t-{0}", string.Join("\r\n\t-", universalFormats)); var viewEngine = new RazorViewEngine { MasterLocationFormats = DisabledFormats, ViewLocationFormats = universalFormats, PartialViewLocationFormats = universalFormats, AreaMasterLocationFormats = DisabledFormats, AreaViewLocationFormats = areaFormats, AreaPartialViewLocationFormats = areaFormats, }; return(viewEngine); }
public IViewEngine CreateModulesViewEngine(CreateModulesViewEngineParams parameters) { //TBD: It would probably be better to determined the area deterministically from the module of the controller, not by trial and error. var areaFormats = parameters.ExtensionLocations.Select(location => location + "/{2}/Views/{1}/{0}.cshtml").ToArray(); //Logger.Debug("AreaFormats (module): \r\n\t-{0}", string.Join("\r\n\t-", areaFormats)); var universalFormats = parameters.VirtualPaths .SelectMany(x => new[] { x + "/Views/{0}.cshtml", }) .ToArray(); //Logger.Debug("UniversalFormats (module): \r\n\t-{0}", string.Join("\r\n\t-", universalFormats)); var viewEngine = new RazorViewEngine { MasterLocationFormats = DisabledFormats, ViewLocationFormats = universalFormats, PartialViewLocationFormats = universalFormats, AreaMasterLocationFormats = DisabledFormats, AreaViewLocationFormats = areaFormats, AreaPartialViewLocationFormats = areaFormats, }; return(viewEngine); }
public RazorViewEngineFixture() { this.configuration = A.Fake<IRazorConfiguration>(); this.engine = new RazorViewEngine(this.configuration); var cache = A.Fake<IViewCache>(); A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Func<NancyRazorViewBase>>>.Ignored)) .ReturnsLazily(x => { var result = x.GetArgument<ViewLocationResult>(0); return x.GetArgument<Func<ViewLocationResult, Func<NancyRazorViewBase>>>(1).Invoke(result); }); this.renderContext = A.Fake<IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); A.CallTo(() => this.renderContext.LocateView(A<string>.Ignored, A<object>.Ignored)) .ReturnsLazily(x => { var viewName = x.GetArgument<string>(0); return FindView(viewName); ; }); this.rootPathProvider = A.Fake<IRootPathProvider>(); A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, "TestViews")); this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader()); }
protected void Application_Start() { XmlConfigurator.Configure(); ViewEngines.Engines.Clear(); var razorViewEngine = new RazorViewEngine(); razorViewEngine.ViewLocationCache = new TwoLevelViewCache(razorViewEngine.ViewLocationCache); ViewEngines.Engines.Add(razorViewEngine); ModelBinders.Binders.DefaultBinder = new SharpModelBinder(); // ModelValidatorProviders.Providers.Add(new ClientDataTypeModelValidatorProvider()); this.InitializeServiceLocator(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); JobsService.Instance().Start(); if (KeepAliveMinutes > 0) { _keepAliveTimer = new Timer(60000 * KeepAliveMinutes); _keepAliveTimer.Elapsed += new ElapsedEventHandler(KeepAlive); _keepAliveTimer.Start(); } }
public void GetNormalizedRouteValue_UsesRouteValueDefaults_IfAttributeRouted() { // Arrange var key = "some-key"; var actionDescriptor = new ActionDescriptor { AttributeRouteInfo = new AttributeRouteInfo(), }; actionDescriptor.RouteValueDefaults[key] = "Route-Value"; var actionContext = new ActionContext { ActionDescriptor = actionDescriptor, RouteData = new RouteData() }; actionContext.RouteData.Values[key] = "route-value"; // Act var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key); // Assert Assert.Equal("Route-Value", result); }
public static string RenderViewToString(string controllerName, string viewName, object viewData) { var context = System.Web.HttpContext.Current; var contextBase = new HttpContextWrapper(context); var routeData = new RouteData(); routeData.Values.Add("controller", controllerName); var controllerContext = new ControllerContext(contextBase, routeData, new EmptyController()); var razorViewEngine = new RazorViewEngine(); var razorViewResult = razorViewEngine.FindView(controllerContext, viewName, "", false); var writer = new StringWriter(); var viewContext = new ViewContext(controllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer); razorViewResult.View.Render(viewContext, writer); return(writer.ToString()); }
public void GetNormalizedRouteValue_ReturnsNull_IfRouteConstraintKeyHandlingIsDeny() { // Arrange var key = "some-key"; var actionDescriptor = new ActionDescriptor { RouteConstraints = new[] { new RouteDataActionConstraint(key, routeValue: string.Empty) } }; var actionContext = new ActionContext { ActionDescriptor = actionDescriptor, RouteData = new RouteData() }; actionContext.RouteData.Values[key] = "route-value"; // Act var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key); // Assert Assert.Null(result); }
public void GetNormalizedRouteValue_ReturnsRouteDataValue_IfRouteConstraintKeyHandlingIsCatchAll() { // Arrange var key = "some-key"; var actionDescriptor = new ActionDescriptor { RouteConstraints = new[] { RouteDataActionConstraint.CreateCatchAll(key) } }; var actionContext = new ActionContext { ActionDescriptor = actionDescriptor, RouteData = new RouteData() }; actionContext.RouteData.Values[key] = "route-value"; // Act var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key); // Assert Assert.Equal("route-value", result); }
public void GetNormalizedRouteValue_ReturnsRouteValue_IfValueDoesNotMatchRouteConstraint() { // Arrange var key = "some-key"; var actionDescriptor = new ActionDescriptor { RouteConstraints = new[] { new RouteDataActionConstraint(key, "different-value") } }; var actionContext = new ActionContext { ActionDescriptor = actionDescriptor, RouteData = new RouteData() }; actionContext.RouteData.Values[key] = "route-value"; // Act var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key); // Assert Assert.Equal("route-value", result); }
public void GetNormalizedRouteValue_ReturnsValueFromRouteConstraints_IfKeyHandlingIsRequired() { // Arrange var key = "some-key"; var actionDescriptor = new ActionDescriptor { RouteConstraints = new[] { new RouteDataActionConstraint(key, "Route-Value") } }; var actionContext = new ActionContext { ActionDescriptor = actionDescriptor, RouteData = new RouteData() }; actionContext.RouteData.Values[key] = "route-value"; // Act var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key); // Assert Assert.Equal("Route-Value", result); }
public void GetNormalizedRouteValue_ConvertsRouteValueToString() { using (new CultureReplacer()) { // Arrange var key = "some-key"; var actionDescriptor = new ActionDescriptor { AttributeRouteInfo = new AttributeRouteInfo(), }; var actionContext = new ActionContext { ActionDescriptor = actionDescriptor, RouteData = new RouteData() }; actionContext.RouteData.Values[key] = 43; // Act var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key); // Assert Assert.Equal("43", result); } }
public void CreateController_DecoratedWithViewEnhanceViewEnginesAttribute_NewControllersViewEnginesHaveCustomTransformations() { //Arrange var controllerFactory = new FrontendControllerFactory(); controllerFactory.RegisterController(typeof(DummyEnhancedController).Name, typeof(DummyEnhancedController)); var viewEngine = new RazorViewEngine(); ViewEngines.Engines.Add(viewEngine); try { //Act var controller = (Controller)controllerFactory.CreateController(new DummyHttpContext().Request.RequestContext, "DummyEnhanced"); //Assert var controllerVe = controller.ViewEngineCollection.OfType <RazorViewEngine>().FirstOrDefault(); Assert.IsNotNull(controllerVe, "The newly created controller does not have the expected view engine."); Assert.IsTrue(controllerVe.ViewLocationFormats.Any(p => p.StartsWith("~/" + DummyEnhancedController.CustomControllerPath)), "The newly created controller does not have its custom path in the view locations."); } finally { ViewEngines.Engines.Remove(viewEngine); } }
/// <summary> /// Create the view engine. /// </summary> public static void Init() { // Create new precompiled view engine var engine = new PrecompiledMvcEngine(typeof(ManagerModule).Assembly) { UsePhysicalViewsIfNewer = true }; engine.PartialViewLocationFormats = engine.PartialViewLocationFormats.Union(ExtensionsFolder).ToArray(); var standard = new RazorViewEngine(); standard.PartialViewLocationFormats = standard.PartialViewLocationFormats.Union(ExtensionsFolder).ToArray(); ViewEngines.Engines.Insert(0, standard); ViewEngines.Engines.Insert(1, engine); VirtualPathFactoryManager.RegisterVirtualPathFactory(engine); // Register the manager area var manager = new ManagerRegistration(); var context = new AreaRegistrationContext(manager.AreaName, RouteTable.Routes); manager.RegisterArea(context); // Register custom model binders RegisterBinders(); // Register json deserialization for post data ValueProviderFactories.Factories.Add(new JsonValueProviderFactory()); // Register application part ApplicationPart.Register(new ApplicationPart(typeof(ManagerModule).Assembly, "~/")); }
private static void RegisterViewEngines() { // Register the standard view engine var standard = new RazorViewEngine(); standard.PartialViewLocationFormats = standard.PartialViewLocationFormats.Union(partialViewFolders).ToArray(); ViewEngines.Engines.Add(standard); // Get precompiled view assemblies var assemblies = new List <Assembly>(); if (Hooks.App.Init.RegisterPrecompiledViews != null) { Hooks.App.Init.RegisterPrecompiledViews(assemblies); } assemblies.Insert(0, typeof(Startup).Assembly); foreach (var assembly in assemblies) { var engine = new PrecompiledMvcEngine(assembly) { UsePhysicalViewsIfNewer = true }; engine.PartialViewLocationFormats = engine.PartialViewLocationFormats.Union(partialViewFolders).ToArray(); ViewEngines.Engines.Add(engine); VirtualPathFactoryManager.RegisterVirtualPathFactory(engine); } }
/// <inheritdoc /> /// <summary> /// Overridable method to execute when All resolvers have been initialized but resolution is not frozen so they can be modified in this method /// </summary> /// <param name="umbracoApplication"></param> /// <param name="applicationContext"></param> protected override void ApplicationStarting( UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { LogHelper.Info(GetType(), "ApplicationStarting"); IocConfiguration.Setup(); base.ApplicationStarting(umbracoApplication, applicationContext); //// add our 404 resolver ContentFinderResolver.Current.InsertTypeBefore <ContentFinderByNiceUrl, PageNotFoundContentFinder>(); // Remove ContentFinderByNiceUrl ContentFinderResolver.Current.RemoveType <ContentFinderByNiceUrl>(); RazorViewEngine razorEngine = ViewEngines.Engines.OfType <RazorViewEngine>().FirstOrDefault(); if (razorEngine != null) { razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats.Concat(new[] { "~/Views/Partials/Spectrum/Payments/{0}.cshtml", "~/Views/Partials/Spectrum/Appointments/{0}.cshtml" }).ToArray(); } }
internal static string RenderViewToString(string controllerName, string viewName, ViewDataDictionary viewData, bool partial = false) { var context = HttpContext.Current; var contextBase = new HttpContextWrapper(context); var routeData = new RouteData(); routeData.Values.Add("controller", controllerName); var controllerContext = new ControllerContext(contextBase, routeData, new EmptyController()); var razorViewEngine = new RazorViewEngine(); ViewEngineResult razorViewResult = null; if (partial) { razorViewResult = razorViewEngine.FindPartialView(controllerContext, viewName, false); } else { razorViewResult = razorViewEngine.FindView(controllerContext, viewName, "", false); } var writer = new StringWriter(); var viewContext = new ViewContext(controllerContext, razorViewResult.View, viewData, new TempDataDictionary(), writer); razorViewResult.View.Render(viewContext, writer); return(writer.ToString()); }
public RazorViewEngineFixture() { this.configuration = A.Fake <IRazorConfiguration>(); this.textResource = A.Fake <ITextResource>(); this.engine = new RazorViewEngine(this.configuration, this.textResource); var cache = A.Fake <IViewCache>(); A.CallTo(() => cache.GetOrAdd(A <ViewLocationResult> .Ignored, A <Func <ViewLocationResult, Func <NancyRazorViewBase> > > .Ignored)) .ReturnsLazily(x => { var result = x.GetArgument <ViewLocationResult>(0); return(x.GetArgument <Func <ViewLocationResult, Func <NancyRazorViewBase> > >(1).Invoke(result)); }); this.renderContext = A.Fake <IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); A.CallTo(() => this.renderContext.LocateView(A <string> .Ignored, A <object> .Ignored)) .ReturnsLazily(x => { var viewName = x.GetArgument <string>(0); return(FindView(viewName));; }); this.rootPathProvider = A.Fake <IRootPathProvider>(); A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, "TestViews")); this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader()); }
public RazorViewEngineFixture() { StaticConfiguration.DisableErrorTraces = false; this.configuration = A.Fake <IRazorConfiguration>(); this.engine = new RazorViewEngine(this.configuration); var cache = A.Fake <IViewCache>(); A.CallTo(() => cache.GetOrAdd(A <ViewLocationResult> .Ignored, A <Func <ViewLocationResult, Func <INancyRazorView> > > .Ignored)) .ReturnsLazily(x => { var result = x.GetArgument <ViewLocationResult>(0); return(x.GetArgument <Func <ViewLocationResult, Func <INancyRazorView> > >(1).Invoke(result)); }); this.renderContext = A.Fake <IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); A.CallTo(() => this.renderContext.LocateView(A <string> .Ignored, A <object> .Ignored)) .ReturnsLazily(x => { var viewName = x.GetArgument <string>(0); return(FindView(viewName)); }); this.rootPathProvider = A.Fake <IRootPathProvider>(); A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, "TestViews")); this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader()); AppDomainAssemblyTypeScanner.AddAssembliesToScan("Nancy.ViewEngines.Razor.Tests.Models.dll"); }
public static void RegisterEngines() { ViewEngines.Engines.Clear(); var viewEngine = new RazorViewEngine(); ViewEngines.Engines.Add(viewEngine); }
public RazorViewEngineFixture() { var environment = new DefaultNancyEnvironment(); environment.Tracing( enabled: true, displayErrorTraces: true); this.configuration = A.Fake<IRazorConfiguration>(); this.engine = new RazorViewEngine(this.configuration, environment); var cache = A.Fake<IViewCache>(); A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Func<INancyRazorView>>>.Ignored)) .ReturnsLazily(x => { var result = x.GetArgument<ViewLocationResult>(0); return x.GetArgument<Func<ViewLocationResult, Func<INancyRazorView>>>(1).Invoke(result); }); this.renderContext = A.Fake<IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); A.CallTo(() => this.renderContext.LocateView(A<string>.Ignored, A<object>.Ignored)) .ReturnsLazily(x => { var viewName = x.GetArgument<string>(0); return FindView(viewName); }); this.rootPathProvider = A.Fake<IRootPathProvider>(); A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, "TestViews")); this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader()); AppDomainAssemblyTypeScanner.AddAssembliesToScan("Nancy.ViewEngines.Razor.Tests.Models.dll"); }
public static string RenderViewAreaToString(string controllerName, string viewName, string areaName, object viewModel, RequestContext rctx) { try { using (var writer = new StringWriter()) { var routeData = new RouteData(); routeData.Values.Add("controller", controllerName); routeData.Values.Add("Area", areaName); routeData.DataTokens["area"] = areaName; var fakeControllerContext = new ControllerContext(rctx, new BaseController()); //new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), new HttpResponse(null))), routeData, new FakeController()); fakeControllerContext.RouteData = routeData; var razorViewEngine = new RazorViewEngine(); var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false); var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewModel), new TempDataDictionary(), writer); razorViewResult.View.Render(viewContext, writer); return writer.GetStringBuilder().ToString(); //use example //String renderedHTML = RenderViewToString("Email", "MyHTMLView", myModel ); //where file MyHTMLView.cstml is stored in Views/Email/MyHTMLView.cshtml. Email is a fake controller name. } } catch (Exception ex) { //do your exception handling here throw ex; } }
public void AreaMasterLocationFormats() { // Arrange string[] expected = new[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/{1}/{0}.vbhtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.vbhtml" }; // Act RazorViewEngine viewEngine = new RazorViewEngine(); // Assert CollectionAssert.AreEqual(expected, viewEngine.AreaMasterLocationFormats); }
public void AreaPartialViewLocationFormats() { // Arrange string[] expected = new[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", }; // Act RazorViewEngine viewEngine = new RazorViewEngine(); // Assert Assert.Equal(expected, viewEngine.AreaPartialViewLocationFormats); }
public void RenderViewSetsPath() { // arrange var templateLocator = A.Fake<IViewLocator>(); var viewCompiler = A.Fake<IViewCompiler>(); var viewLocationResult = new ViewLocationResult(@"c:\some\fake\path", null); A.CallTo(() => templateLocator.GetTemplateContents("test")).Returns(viewLocationResult); var engine = new RazorViewEngine(templateLocator, viewCompiler); // act var result = engine.RenderView("test", null); // assert result.Location.ShouldEqual(@"c:\some\fake\path"); }
public RazorViewCompilerFixture() { this.configuration = A.Fake<IRazorConfiguration>(); this.engine = new RazorViewEngine(this.configuration); var cache = A.Fake<IViewCache>(); A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Func<NancyRazorViewBase>>>.Ignored)) .ReturnsLazily(x => { var result = x.GetArgument<ViewLocationResult>(0); return x.GetArgument<Func<ViewLocationResult, Func<NancyRazorViewBase>>>(1).Invoke(result); }); this.renderContext = A.Fake<IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); }
public void RenderViewShouldReturnCompiledView() { // arrange var templateLocator = A.Fake<IViewLocator>(); var viewCompiler = A.Fake<IViewCompiler>(); var view = A.Fake<IView>(); var viewLocationResult = new ViewLocationResult(@"c:\some\fake\path", null); A.CallTo(() => templateLocator.GetTemplateContents("test")).Returns(viewLocationResult); A.CallTo(() => viewCompiler.GetCompiledView(null)).Returns(view); var engine = new RazorViewEngine(templateLocator, viewCompiler); var stream = new MemoryStream(); // act var result = engine.RenderView("test", stream); // assert result.View.ShouldBeSameAs(view); }
private RazorViewEngine CreateViewEngine( IRazorPageFactory pageFactory = null, IRazorViewFactory viewFactory = null, IEnumerable<IViewLocationExpander> expanders = null, IViewLocationCache cache = null) { pageFactory = pageFactory ?? Mock.Of<IRazorPageFactory>(); viewFactory = viewFactory ?? Mock.Of<IRazorViewFactory>(); cache = cache ?? GetViewLocationCache(); var viewEngine = new RazorViewEngine(pageFactory, viewFactory, GetOptionsAccessor(expanders), cache); return viewEngine; }
static View() { ViewEngine = new RazorViewEngine(); }
public RazorViewCompilerFixture() { this.engine = new RazorViewEngine(); }
public void FileExtensionsProperty() { // Arrange string[] expected = new[] { "cshtml", "vbhtml", }; // Act RazorViewEngine viewEngine = new RazorViewEngine(); // Assert CollectionAssert.AreEqual(expected, viewEngine.FileExtensions); }
public void FindView_ReturnsRazorView_IfLookupWasSuccessful() { // Arrange var pageFactory = new Mock<IRazorPageFactory>(); pageFactory.Setup(p => p.CreateInstance(It.IsAny<string>())) .Returns(Mock.Of<IRazorPage>()); var viewEngine = new RazorViewEngine(pageFactory.Object, Mock.Of<IRazorPageActivator>(), Mock.Of<IViewStartProvider>()); var context = GetActionContext(_controllerTestContext); // Act var result = viewEngine.FindView(context, "test-view"); // Assert Assert.True(result.Success); Assert.IsType<RazorView>(result.View); Assert.Equal("/Views/bar/test-view.cshtml", result.ViewName); }
private IViewEngine CreateSearchLocationViewEngineTester() { var pageFactory = new Mock<IRazorPageFactory>(); pageFactory.Setup(vpf => vpf.CreateInstance(It.IsAny<string>())) .Returns<RazorPage>(null); var viewEngine = new RazorViewEngine(pageFactory.Object, Mock.Of<IRazorPageActivator>(), Mock.Of<IViewStartProvider>()); return viewEngine; }