private static ViewEngineResult WrapResult(ViewEngineResult innerResult) { var profiledResult = innerResult.View != null ? new ViewEngineResult(new ProfilingView(innerResult.View), innerResult.ViewEngine) : new ViewEngineResult(innerResult.SearchedLocations); return profiledResult; }
/// <summary> /// Renders A ViewEngineResult (Either A Partial View Or A View) To A String /// </summary> /// <param name="ControllerToRenderWith">Controller to render the view with</param> /// <param name="RazorViewToRender">Partial view or view to render</param> /// <param name="Model">Model that gets passed into the view</param> /// <param name="ViewBagData">View Bag that is accessible when the view is rendered</param> /// <returns>Rendered partial view as string</returns> internal static string RenderRazorViewToString(Controller ControllerToRenderWith, ViewEngineResult RazorViewToRender, object Model, ViewDataDictionary ViewBagData) { //set the model ControllerToRenderWith.ViewData.Model = Model; //make sure the view bag data is not null{ if (ViewBagData.AnyWithNullCheck()) { //we need to make sure we include both the controller and the view data we pass in...so add the view data to the controllers view data foreach (KeyValuePair<string, object> thisViewBagItem in ViewBagData) { //add the view data to the controller's view data ControllerToRenderWith.ViewData.Add(thisViewBagItem); } } //create the string write to output the html using (var ViewStringWriter = new StringWriter()) { //create the view context with all the view data..and render that control to the view context var ViewContextToUse = new ViewContext(ControllerToRenderWith.ControllerContext, RazorViewToRender.View, ControllerToRenderWith.ViewData, ControllerToRenderWith.TempData, ViewStringWriter); //Now go render the partial view to the string writer RazorViewToRender.View.Render(ViewContextToUse, ViewStringWriter); //return the string which contains the html for this partial view with the model and view data embedded return ViewStringWriter.GetStringBuilder().ToString(); } }
public static string GetHtmlFromView(this ControllerContext context, ViewEngineResult viewResult, string viewName, object model) { context.Controller.ViewData.Model = model; using (StringWriter sw = new StringWriter()) { // view not found, throw an exception with searched locations if (viewResult.View == null) { var locations = new StringBuilder(); locations.AppendLine(); foreach (string location in viewResult.SearchedLocations) { locations.AppendLine(location); } throw new InvalidOperationException( string.Format( "The view '{0}' or its master was not found, searched locations: {1}", viewName, locations)); } ViewContext viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw); viewResult.View.Render(viewContext, sw); string html = sw.GetStringBuilder().ToString(); string baseUrl = string.Format("{0}://{1}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Authority); html = Regex.Replace(html, "<head>", string.Format("<head><base href=\"{0}\" />", baseUrl), RegexOptions.IgnoreCase); return html; } }
public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache) { var found = wrapped.FindPartialView(controllerContext, partialViewName, useCache); if (found != null && found.View != null) found = new ViewEngineResult(new WrappedView(found.View, partialViewName, isPartial: true), this); return found; }
private ViewEngineResult Find(ControllerContext ctx, string name, Func<ViewEngineResult> finder, bool isPartial) { var profiler = MiniProfiler.Current; IDisposable block = null; const string Key = "find-view-or-partial"; if (profiler != null) { block = HttpContext.Current.Items[Key] as IDisposable; if (block == null) { HttpContext.Current.Items[Key] = block = profiler.Step("Find: " + name); } } var found = finder(); if (found != null && found.View != null) { found = new ViewEngineResult(new WrappedView(found.View, name, isPartial), this); if (block != null) { block.Dispose(); HttpContext.Current.Items[Key] = null; } } if (found == null && block != null && this == ViewEngines.Engines.Last()) { block.Dispose(); HttpContext.Current.Items[Key] = null; } return found; }
private ViewEngineResult Process(ViewEngineResult viewEngineResult, bool isPartial, string viewName, string masterName, bool useCache) { var contextStore = HttpContext.Current.Items;//Can this be removed? var vmStore = contextStore[GlimpseConstants.ViewEngine] as IList<GlimpseViewEngineCallMetadata>; if (vmStore == null) contextStore[GlimpseConstants.ViewEngine] = vmStore = new List<GlimpseViewEngineCallMetadata>(); GlimpseView glimpseView = null; if (viewEngineResult.View != null) { //wrap up IView so we can get access to ViewContext glimpseView = new GlimpseView(viewEngineResult.View); glimpseView.ViewName = viewName; viewEngineResult = new ViewEngineResult(glimpseView, viewEngineResult.ViewEngine); } var metadata = new GlimpseViewEngineCallMetadata { ViewEngineResult = viewEngineResult, IsPartial = isPartial, ViewName = viewName, MasterName = masterName, UseCache = useCache, GlimpseView = glimpseView, ViewEngineName = ViewEngine.GetType().Name }; vmStore.Add(metadata); return viewEngineResult; }
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { var searchedEngine = RouteServiceValue + "_ViewEngine"; var notFound = new ViewEngineResult(new[] { searchedEngine }); if (controllerContext.RouteData.DataTokens.ContainsKey(Consts.RouteServiceKey)) return (string)controllerContext.RouteData.DataTokens[Consts.RouteServiceKey] == RouteServiceValue ? base.FindView(controllerContext, viewName, masterName, useCache) : notFound; return notFound; }
public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { var found = wrapped.FindView(controllerContext, viewName, masterName, useCache); if (found != null && found.View != null) { found = new ViewEngineResult(new WrappedView(found.View, viewName, isPartial: false), this); } return found; }
public void SearchedLocationsProperty() { // Arrange string[] searchedLocations = new string[0]; ViewEngineResult result = new ViewEngineResult(searchedLocations); // Act & Assert Assert.AreSame(searchedLocations, result.SearchedLocations); Assert.IsNull(result.View); }
public void ViewEngineProperty() { // Arrange IView view = new Mock<IView>().Object; IViewEngine viewEngine = new Mock<IViewEngine>().Object; ViewEngineResult result = new ViewEngineResult(view, viewEngine); // Act & Assert Assert.AreSame(viewEngine, result.ViewEngine); Assert.IsNull(result.SearchedLocations); }
protected string ConvertViewToHtml(ControllerContext controllerContextParam, ViewEngineResult viewEngineResultParam) { string content; using (var writer = new StringWriter()) { var context = new ViewContext(ControllerContext, viewEngineResultParam.View, controllerContextParam.Controller.ViewData, controllerContextParam.Controller.TempData, writer); viewEngineResultParam.View.Render(context, writer); writer.Flush(); content = writer.ToString(); } return content; }
private static string RenderView(object model, ControllerContext Context, ViewEngineResult viewEngineResult, string result) { // get the view and attach the model to view data var view = viewEngineResult.View; Context.Controller.ViewData.Model = model; using (var sw = new StringWriter()) { var ctx = new ViewContext(Context, view, Context.Controller.ViewData, Context.Controller.TempData, sw); view.Render(ctx, sw); result = sw.ToString(); } return result; }
public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache) { var cache = HttpRuntime.Cache; var key = CacheKey("FindPartialView", controllerContext, partialViewName, string.Empty); if (cache.Get(key) != null) return (ViewEngineResult)cache.Get(key); ViewLocationFormats[0] = ViewLocationFormats[0].Replace("$$", PortalAlias); PartialViewLocationFormats[0] = PartialViewLocationFormats[0].Replace("$$", PortalAlias); ViewLocationFormats[1] = ViewLocationFormats[1].Replace("$$", PortalAlias); PartialViewLocationFormats[1] = PartialViewLocationFormats[1].Replace("$$", PortalAlias); /*custom partialview exists ?*/ var formattedView = FormatViewName(controllerContext, partialViewName); string str2 = formattedView.path; ViewEngineResult result; if (formattedView.custom) { result = new ViewEngineResult(new RazorView(controllerContext, str2, null, false, null), this); AddToCache(key, result); return result; } result = base.FindPartialView(controllerContext, str2, useCache); if ((result != null) && (result.View != null)) { AddToCache(key, result); return result; } /**/ /*or custom shared partialview exists ?*/ formattedView = FormatSharedViewName(controllerContext, partialViewName); string str3 = formattedView.path; if (formattedView.custom) { result = new ViewEngineResult(new RazorView(controllerContext, str3, null, false, null), this); AddToCache(key, result); return result; } result = base.FindPartialView(controllerContext, str3, useCache); if ((result != null) && (result.View != null)) { AddToCache(key, result); return result; } /*else return original partialview*/ result = base.FindPartialView(controllerContext, partialViewName, useCache); AddToCache(key, result); return result; }
private string GetViewToString(ControllerContext context, ViewEngineResult result, object model) { string viewResult = string.Empty; var viewData = ViewData; viewData.Model = model; TempDataDictionary tempData = new TempDataDictionary(); StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { using (HtmlTextWriter output = new HtmlTextWriter(sw)) { ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output); result.View.Render(viewContext, output); } viewResult = sb.ToString(); } return viewResult; }
private void SetupViewEngineStub(string viewString = null) { viewString = viewString ?? string.Empty; Mock<IView> partialViewStub = new Mock<IView>(); partialViewStub. Setup(pvs => pvs.Render(It.IsAny<ViewContext>(), It.IsAny<TextWriter>())). Callback((ViewContext vc, TextWriter tw) => tw.Write(viewString)); Mock<IViewEngine> viewEngineStub = new Mock<IViewEngine>(); var viewEngineResult = new ViewEngineResult(partialViewStub.Object, viewEngineStub.Object); viewEngineStub.Setup(ve => ve.FindView(It.IsAny<ControllerContext>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(viewEngineResult); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(viewEngineStub.Object); }
private static string ViewToContent(Controller controller, ViewEngineResult view) { string content; using (var writer = new StringWriter()) { var context = new ViewContext(controller.ControllerContext, view.View, controller.ViewData, controller.TempData, writer); view.View.Render(context, writer); writer.Flush(); content = writer.ToString(); } return content; }
public ViewEngineResult FindView( ControllerContext controllerContext, string viewName, string masterName, bool useCache) { var skipLayoutViewEngine = false; if (string.IsNullOrEmpty(masterName) == false) skipLayoutViewEngine = true; if (!ThemeFilter.IsApplied(controllerContext.RequestContext)) skipLayoutViewEngine = true; if (_viewEngines == null || _viewEngines.Count == 0) skipLayoutViewEngine = true; if (skipLayoutViewEngine) return new ViewEngineResult(Enumerable.Empty<string>()); var bodyView = _viewEngines.FindPartialView(controllerContext, viewName); ViewEngineResult layoutView = null; if (!string.IsNullOrEmpty(controllerContext.RouteData.Values["area"] as string)) layoutView = _viewEngines.FindPartialView(controllerContext, string.Format("Layout.{0}", controllerContext.RouteData.Values["area"])); if (layoutView == null || layoutView.View == null) layoutView = _viewEngines.FindPartialView(controllerContext, "Layout"); var documentView = _viewEngines.FindPartialView(controllerContext, "Document"); if (bodyView.View == null || layoutView.View == null || documentView.View == null) { var missingTemplatesResult = new ViewEngineResult( (bodyView.SearchedLocations ?? Enumerable.Empty<string>()) .Concat((layoutView.SearchedLocations ?? Enumerable.Empty<string>())) .Concat((documentView.SearchedLocations ?? Enumerable.Empty<string>())) ); return missingTemplatesResult; } var view = new LayoutView(this, new[] { bodyView, layoutView, documentView, }); return new ViewEngineResult(view, this); }
private ViewEngineResult CreateNestedView( ViewEngineResult result, ControllerContext controllerContext) { if (result.View == null) return result; var parentContainer = controllerContext.HttpContext.GetContainer(); var nestedContainer = parentContainer.GetNestedContainer(); var webFormView = (WebFormView)result.View; var wrappedView = new WrappedView(webFormView, nestedContainer); var newResult = new ViewEngineResult(wrappedView, this); return newResult; }
private static void AppendRazorViewPath(ControllerContext controllerContext, ViewEngineResult result) { if (result.View == null) return; var viewContext = controllerContext as ViewContext; if (viewContext == null) return; var re = RegistrationExtensions.GetRegistrationExpression(viewContext.HttpContext); if (re == null) return; var viewPath = Utility.GetProperty(result.View, "ViewPath") as string; if (viewPath == null) return; re.Context.TouchedPaths.Add(viewPath); }
private static void AppendRazorViewPath(ControllerContext controllerContext, ViewEngineResult result) { if (result.View == null) return; var viewContext = controllerContext as ViewContext; if (viewContext == null) return; var re = RegistrationExtensions.GetRegistrationExpression(viewContext.ViewData); if (re == null) return; var razorView = result.View as RazorView; if (razorView == null) return; re.TouchedPaths.Add(razorView.ViewPath); }
/// <summary> /// Ensures that the correct web.config for razor exists in the /Views folder. /// </summary> private void EnsureFolderAndWebConfig(ViewEngineResult result) { if (result.View == null) return; var razorResult = result.View as RazorView; if (razorResult == null) return; var folder = Path.GetDirectoryName(IOHelper.MapPath(razorResult.ViewPath)); //now we need to get the /View/ folder var viewFolder = folder.Substring(0, folder.LastIndexOf("\\Views\\")) + "\\Views"; //ensure the web.config file is in the ~/Views folder Directory.CreateDirectory(viewFolder); if (!File.Exists(Path.Combine(viewFolder, "web.config"))) { using (var writer = File.CreateText(Path.Combine(viewFolder, "web.config"))) { writer.Write(Strings.web_config); } } }
/// <summary> /// Mocks the contents of a view that will be rendered during the test. /// </summary> /// <param name="mock"></param> /// <param name="viewName">Name of the view that is going to be rendered.</param> /// <param name="viewContentGetter">Expression that takes a ViewContext and returns the content of the view.</param> public static Mock<IViewEngine> SetViewContent(this Mock<IViewEngine> mock, string viewName, Func<ViewContext, string> viewContentGetter) { var resultView = new Mock<IView>(); resultView .Setup(x => x.Render(It.IsAny<ViewContext>(), It.IsAny<TextWriter>())) .Callback<ViewContext, TextWriter>((vc, tw) => tw.Write(viewContentGetter(vc))); var viewEngineResult = new ViewEngineResult(resultView.Object, mock.Object); mock .Setup(x => x.FindPartialView(It.IsAny<ControllerContext>(), viewName, It.IsAny<bool>())) .Returns(viewEngineResult); mock .Setup(x => x.FindView(It.IsAny<ControllerContext>(), viewName, It.IsAny<string>(), It.IsAny<bool>())) .Returns(viewEngineResult); return mock; }
public static string RenderPartialViewToString(nameFile.ControllerContext controllerContext, string viewName, object model) { nameFile.ViewDataDictionary ViewData = new nameFile.ViewDataDictionary(model); nameFile.TempDataDictionary TempData = new nameFile.TempDataDictionary(); if (string.IsNullOrEmpty(viewName)) { viewName = controllerContext.RouteData.GetRequiredString("action"); } ViewData.Model = model; using (StringWriter sw = new StringWriter()) { nameFile.ViewEngineResult viewResult = nameFile.ViewEngines.Engines.FindPartialView(controllerContext, viewName); nameFile.ViewContext viewContext = new nameFile.ViewContext(controllerContext, viewResult.View, ViewData, TempData, sw); viewResult.View.Render(viewContext, sw); return(sw.GetStringBuilder().ToString()); } }
// this is mostly copied over from Umbraco's internals private static void EnsureFolderAndWebConfig(ViewEngineResult result) { var razorResult = result.View as RazorView; if (razorResult == null) return; var folder = Path.GetDirectoryName(IOHelper.MapPath(razorResult.ViewPath)); if (folder == null) throw new Exception("Panic: null folder."); //now we need to get the /View/ folder var pos = folder.LastIndexOf("\\Views\\", StringComparison.OrdinalIgnoreCase); var viewFolder = folder.Substring(0, pos) + "\\Views"; //ensure the web.config file is in the ~/Views folder Directory.CreateDirectory(viewFolder); if (File.Exists(Path.Combine(viewFolder, "web.config"))) return; using (var writer = File.CreateText(Path.Combine(viewFolder, "web.config"))) { writer.Write(UmbracoInternals.WebConfigTemplate); } }
public void Should_Forward_FindPartialView_To_Current_ModuleApplication_ViewEngineCollection() { // Arrange var mockEngines = new Mock<ViewEngineCollection>(); ViewEngineResult result = new ViewEngineResult(new[] {"foo", "bar", "baz"}); ControllerContext context = Mockery.CreateMockControllerContext(); string viewName = "Foo"; mockEngines.Setup(e => e.FindPartialView(context, viewName)) .Returns(result); SetupMockModuleApplication(context, mockEngines.Object); ModuleDelegatingViewEngine viewEngine = new ModuleDelegatingViewEngine(); // Act ViewEngineResult engineResult = viewEngine.FindPartialView(context, viewName, true); // Assert mockEngines.Verify(e => e.FindPartialView(context, viewName)); Assert.AreEqual("foo", engineResult.SearchedLocations.ElementAt(0)); Assert.AreEqual("bar", engineResult.SearchedLocations.ElementAt(1)); Assert.AreEqual("baz", engineResult.SearchedLocations.ElementAt(2)); }
private ContentRegistration RenderViewForRegistration(VirtualFile file, Type modelType, ControllerContext cctx, ViewEngineResult result) { var re = new ContentRegistration(map.CreateDefinition(modelType, N2.Web.Url.RemoveAnyExtension(file.Name))); re.IsDefined = false; re.Context.TouchedPaths.Add(file.VirtualPath); using (StringWriter sw = new StringWriter()) { var vdd = new ViewDataDictionary(); cctx.Controller.ViewData = vdd; N2.Web.Mvc.Html.RegistrationExtensions.SetRegistrationExpression(cctx.HttpContext, re); try { logger.DebugFormat("Rendering view {0} for registrations", file.VirtualPath); result.View.Render(new ViewContext(cctx, result.View, vdd, new TempDataDictionary(), sw), sw); logger.DebugFormat("Rendered view {0}, editables = {1}, defined = {2}", file.VirtualPath, re.Definition.Editables.Count, re.IsDefined); } catch (Exception ex) { logger.Error(file.VirtualPath, ex); if (re.IsDefined) throw; return null; } finally { N2.Web.Mvc.Html.RegistrationExtensions.SetRegistrationExpression(cctx.HttpContext, null); } if (re.IsDefined) { return re; } return null; } }
private ViewContext InitializeView(ControllerContext context, out ViewEngineResult result) { if (context == null) { throw new ArgumentNullException("context"); } if (String.IsNullOrEmpty(ViewName)) { ViewName = context.RouteData.GetRequiredString("action"); } if (View == null) { result = FindView(context); View = result.View; } else { result = null; } TextWriter writer = context.HttpContext.Response.Output; ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, writer); return viewContext; }
private void ReleaseView(ControllerContext context, ViewEngineResult result) { if (result != null) { result.ViewEngine.ReleaseView(context, View); } }
private ViewTemplateDescription RenderViewForRegistration(VirtualFile file, Type modelType, ControllerContext cctx, ViewEngineResult result) { var re = new ContentRegistration(); re.ContentType = modelType; re.Template = N2.Web.Url.RemoveAnyExtension(file.Name); re.IsDefined = false; using (StringWriter sw = new StringWriter()) { var vdd = new ViewDataDictionary(); cctx.Controller.ViewData = vdd; vdd["RegistrationExpression"] = re; try { result.View.Render(new ViewContext(cctx, result.View, vdd, new TempDataDictionary(), sw), sw); } catch (Exception ex) { Trace.WriteLine(ex); if (re.IsDefined) throw; return null; } if (re.IsDefined) { return new ViewTemplateDescription { Registration = re, Definition = GetOrCreateDefinition(re), TouchedPaths = new[] { file.VirtualPath }.Union(re.TouchedPaths) }; } return null; } }
public PdfView(ViewEngineResult result) { _result = result; }
public void SetUp() { _logger = new Mock<ILog>(); _pageContext = new Mock<IPageContext>(); _pageContext.SetupAllProperties(); _pageContext.SetupGet(x => x.PageDefinition).Returns(new PageDefinition()); _filter = new InjectViewInPlaceholderFilter(_logger.Object) { PageContext = _pageContext.Object }; _httpRequest = new Mock<HttpRequestBase>(); _httpRequest.SetupGet(r => r["X-Requested-With"]).Returns(default(string)); _httpContext = new Mock<HttpContextBase>(); _httpContext.SetupAllProperties(); _itemsDictionary = new Dictionary<string, object>(); _httpContext.SetupGet(x => x.Items).Returns(_itemsDictionary); _httpContext.SetupGet(x => x.Request).Returns(_httpRequest.Object); _controller = new Mock<Controller>(); _controller.SetupAllProperties(); _controller.Object.ControllerContext = new ControllerContext(_httpContext.Object, new RouteData(), _controller.Object); _viewEngine = new Mock<IViewEngine>(); _view = new Mock<IView>(); _viewResult = new ViewResult { ViewEngineCollection = new ViewEngineCollection { _viewEngine.Object } }; _viewEngineResult = new ViewEngineResult(_view.Object, _viewEngine.Object); }